diff --git a/CHANGELOG.md b/CHANGELOG.md index d2c4a80..88ac674 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -69,13 +69,23 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows ### Changed -- The view models, the app's state and the decisions of the settings pages and - of the Stream Studio moved out of `voelin-ui` into a new crate, - `voelin-ui-vm`, which depends on no UI toolkit (a second front end can use - it); `voelin-ui` converts its plain rows into Slint's and keeps the window, - the Bridge writes and the engine's tasks. The chat formatting reader and the - Twemoji archive moved with them. Nothing changes on screen. See - docs/ui.md, "Two crates". +- The key store now keeps the device key when signing out of an account, + unbound, whether it was in use before the account or was made for it; "Forget + this device's identity" is the only way a key is deleted. The identity store + also reports a damaged TeamSpeak identity by the kind of damage and never + repeats its key in an error. Nothing changes on screen yet: accounts and + sign-in are later steps. +- The view models, the app's state, the state change of every engine event and + the decisions of the settings pages, the Stream Studio, the streams, the chat, + the servers, the audio settings page, the friends and the development + switches moved out of `voelin-ui` into a new crate, `voelin-ui-vm`, which + depends on no UI toolkit (a second front end can use it); `voelin-ui` + converts its plain rows into Slint's and keeps the window, the Bridge writes + and the engine's tasks. The chat formatting reader and the + Twemoji archive moved with them. Two things change on screen: the chat of + a server that is gone takes the colour of its title instead of opaque + black, and a cached avatar file cut after a valid header shows the + initials instead of a broken picture. See docs/ui.md, "Two crates". - The identity store keeps identities of more than one kind (TeamSpeak, a Voelin key, the signed-in account) with the account each belongs to, as a `voelin-identity` key store, in two database migrations. Existing diff --git a/Cargo.lock b/Cargo.lock index 28d5774..31c9466 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9578,7 +9578,7 @@ dependencies = [ [[package]] name = "voelin-identity" version = "0.2.0" -source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c8e0e5a17c1ff5dfaefa087f49b395d2918af650#c8e0e5a17c1ff5dfaefa087f49b395d2918af650" +source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562#c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" dependencies = [ "aws-lc-rs", "base64 0.23.1", @@ -9637,7 +9637,7 @@ dependencies = [ [[package]] name = "voelin-model" version = "0.1.0" -source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c8e0e5a17c1ff5dfaefa087f49b395d2918af650#c8e0e5a17c1ff5dfaefa087f49b395d2918af650" +source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562#c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" dependencies = [ "prost", "serde", @@ -9676,7 +9676,7 @@ dependencies = [ [[package]] name = "voelin-proto" version = "0.2.0" -source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c8e0e5a17c1ff5dfaefa087f49b395d2918af650#c8e0e5a17c1ff5dfaefa087f49b395d2918af650" +source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562#c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" dependencies = [ "bytes", "prost", @@ -9768,6 +9768,7 @@ dependencies = [ "image", "miniz_oxide 0.8.9", "png", + "roxmltree", "serde", "serde_json", "unicode-segmentation", diff --git a/Cargo.toml b/Cargo.toml index 10350af..61c3b6f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -58,13 +58,14 @@ publish = false # docs/development.md names, so that a per-developer .cargo/config.toml [patch] # can point it at a sibling checkout (docs/building.md, "Working with a sibling # VoelinProtocol checkout"). Pinned by commit until the protocol tags a release: -# the three crates below are at one revision (main c8e0e5a: the account-bound -# KeyStore of Phase 2 task 28, the account types of the session seam). -voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" } +# the three crates below are at one revision (main c5bb6b9: the account-bound +# KeyStore whose sign-out keeps every device key and the release of a device key, +# Phase 2 task 34; the account types of the session seam). +voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" } # The backend-neutral session seam (`voelin_proto::link`) and the v1 messages. -voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" } +voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" } # The UI-facing domain model and the client's replica of v1 entities. -voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" } +voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" } [workspace.lints.rust] # deny, not forbid: generated code (Slint) needs a local allow. diff --git a/crates/voelin-core/src/link/fake_tests.rs b/crates/voelin-core/src/link/fake_tests.rs index f428d5c..a04b9ee 100644 --- a/crates/voelin-core/src/link/fake_tests.rs +++ b/crates/voelin-core/src/link/fake_tests.rs @@ -313,7 +313,7 @@ async fn the_conformance_suite_passes_on_a_session_of_the_registry() { } let report = conformance::run(&through_the_registry).await; assert_eq!(report.cases.len(), conformance::CASES.len()); - assert_eq!(report.cases.len(), 17, "the suite of c8e0e5a has 17 cases"); + assert_eq!(report.cases.len(), 17, "the suite of c5bb6b9 has 17 cases"); assert!( report.cases.iter().all(|(_, verdict)| *verdict == Verdict::Passed), "{:?}", diff --git a/crates/voelin-core/src/ts/ts_session/live_tests.rs b/crates/voelin-core/src/ts/ts_session/live_tests.rs index 87966e7..ba51e9a 100644 --- a/crates/voelin-core/src/ts/ts_session/live_tests.rs +++ b/crates/voelin-core/src/ts/ts_session/live_tests.rs @@ -333,7 +333,7 @@ enum Expect { } use Expect::{NotRun, Passes, Skipped}; -/// Every case of the suite of the protocol repository at `c8e0e5a`, in its +/// Every case of the suite of the protocol repository at `c5bb6b9`, in its /// order, with what a TeamSpeak session does with it. A case the suite gains /// fails `the_suite_is_known` until it is listed here. /// diff --git a/crates/voelin-store/src/keystore.rs b/crates/voelin-store/src/keystore.rs index 185433b..34a797b 100644 --- a/crates/voelin-store/src/keystore.rs +++ b/crates/voelin-store/src/keystore.rs @@ -35,44 +35,119 @@ //! the trait's [`KeyStore::sign_out`] starts with it and then reads the account //! record and the device key with [`KeyStore::get`]: one damaged row, the //! record's own included, would otherwise keep a sign-out from ever finishing, -//! and with it the deletion of the key the user asked to forget. Unbound is the -//! reading that never deletes on a guess: a sign-out neither deletes such a row -//! as a synced copy nor writes it, it stays as it is until a `put` of it writes -//! four good binding columns. A `data` column that is not text (a BLOB, or text -//! of bytes that are no UTF-8) is read as text with the odd bytes replaced, so -//! that a record that cannot be read is deleted by the sign-out, as the trait -//! says, instead of its read failing. A [`KeyStore::put`] of the text that +//! and with it the deletion of the synced copies and of the record, and the +//! forgetting of the key the user asked to forget. Unbound is the reading that +//! never deletes on a guess: a sign-out neither deletes such a row as a synced +//! copy nor writes it, it stays as it is until a `put` of it writes four good +//! binding columns. A `data` column that is not text (a BLOB, or text of bytes +//! that are no UTF-8) is read as text with the odd bytes replaced, so that a +//! record that cannot be read is deleted by the sign-out, as the trait says, +//! instead of its read failing. A [`KeyStore::put`] of the text that //! [`KeyStore::get`] returned for such a row is taken for the data that is //! there: it changes the binding and keeps the stored bytes, where any other //! text replaces them (a TeamSpeak blob still has to be an identity). A row //! whose `kind` or `uid` is not text cannot be addressed, and the list leaves it //! out with a warning. //! +//! # Signing out keeps every key +//! +//! [`KeyStore::sign_out`] is the trait's own, run on this table, and since +//! Phase 2 task 34 of the protocol repository (open question 10 of its accounts +//! design, answered by the owner on 2026-10-24) it keeps every key of the +//! device. The device key stays, unbound and byte for byte, whether it was in +//! use before the account existed or the client made it for the account: +//! `AccountRecord::bound_existing_key` only records which, for the client's +//! wording, and no rule reads it. At every host without accounts that the user +//! reached with it, either key is the user's identity, and deleting it would +//! lose their servers, roles and memberships there. The identities that only +//! this device holds (a TeamSpeak identity of custody `DEVICE`, one the user +//! kept local) are unbound and kept as well. +//! +//! What a sign-out deletes is not a key of the device: the synced copies of +//! integration secrets, which the account service holds and every device can +//! fetch again (a copy of a TeamSpeak identity is a private key, and is deleted +//! like one, see below), and the account record, which holds no secret. A +//! sign-out does not release the device key at the account service either: the +//! key stays registered with the account there. The release is its own +//! operation, see below. +//! +//! # Releasing a device key +//! +//! The release of the device key from its account (part 2 of open question 10) +//! is the account service's operation followed by a local unbind, and the unbind +//! is a sign-out: `AccountClient::release` of `voelin-account-client` calls +//! `POST /v1/devices//release` after a password check, and then runs +//! [`KeyStore::sign_out`] with [`DeviceKeyChoice::Auto`], which keeps the key, +//! unbound. So the store needs nothing of its own for it: no call that unbinds +//! one key (a [`KeyStore::put`] of the blob without its binding does that, and +//! keeps the data, as the sign-out does), and no record that the key was +//! released. The accounts design asks the client to remember nothing of the +//! kind: the service holds the registration of the key (after a release it is +//! registered with no account, after a sign-out with the account that was +//! signed out of), and the client learns which at the next sign-in or sign-up, +//! from the service's answer (`CONFLICT`, field `device`), not from a note kept +//! here. The deletion of the account (`AccountClient::delete_account`) is the +//! same: the service writes a DEVICE and a RELEASED entry for every device key +//! of the account, and the local half is this sign-out, which keeps this +//! device's key. +//! +//! # Forgetting the device's identity +//! +//! "Forget this device's identity" is the user's explicit choice and the only +//! deletion of a key of the device; the UI offers to export the key first and +//! asks before it deletes. +//! +//! - Signed in, it is a sign-out with [`DeviceKeyChoice::Forget`] and the uid of +//! the device key. The caller names the key, because the key goes before the +//! record is read: a record that cannot be read does not keep it. +//! - Signed out, or with a key that no account ever bound, it is +//! [`KeyStore::remove`] of `(KIND_VOELIN, uid)`; a TeamSpeak identity is +//! [`Store::delete_identity`]. Neither looks at an account record, so a UI +//! that forgets the device key of the account it is signed in to does it +//! through the sign-out, not through `remove`. +//! +//! The store has no call that exports, because it would only wrap what the +//! caller can read before it deletes: a Voelin key is +//! `KeyStore::voelin_key(uid)` followed by `IdentityKey::to_pkcs8` (the DER that +//! `voelin_identity::FileSigner` reads back; the buffer is zeroized when it is +//! dropped), and a TeamSpeak identity is `Store::identity(id)` followed by +//! `voelin_core::ts::identity::export` or `write_export`. The same two calls, +//! with [`KeyStore::list`] for the `voelin` rows, serve the dialog that deletes +//! the account: it offers an export of the device keys before the service is +//! asked. +//! +//! # Deleted keys leave no trace +//! //! The rows are private keys, so a removed row is not left behind in the file: //! every connection sets `secure_delete`, which makes SQLite overwrite what it //! deletes, and [`KeyStore::remove`] truncates the write-ahead log after it, as //! [`Store::delete_identity`] does, so that the frame of the log that held the -//! page with the key is gone too. [`KeyStore::sign_out`], which deletes with -//! `remove`, truncates the log once, after its last step, not after each -//! removal. The checkpoint waits for another connection for a moment at most -//! (`Store::truncate_wal`): one that keeps reading an old snapshot blocks it, -//! and then the removal still succeeds and a warning says that the deleted -//! bytes may stay in the log file, until a later checkpoint truncates the log, -//! later writes overwrite those frames, or the last connection to the database -//! closes and the log is deleted. +//! page with the key is gone too. A forgotten key needs exactly that. So does +//! the one deletion a sign-out still makes of a key: a synced copy of a +//! TeamSpeak identity, and with `Forget` the device key itself. The sign-out +//! deletes with `remove` on a `SignOutPass` and truncates the log once, after +//! its last step, not after each removal; one that deletes nothing (the record +//! was gone, no copies) truncates nothing. The checkpoint waits for another +//! connection for a moment at most (`Store::truncate_wal`): one that keeps +//! reading an old snapshot blocks it, and then the removal still succeeds and a +//! warning says that the deleted bytes may stay in the log file, until a later +//! checkpoint truncates the log, later writes overwrite those frames, or the +//! last connection to the database closes and the log is deleted. //! -//! The device key is never a synced copy. The account record names the Voelin key -//! that is the installation's device key, and [`KeyStore::sign_out`] deletes -//! every identity bound with `synced = true` in its first step, before it reads -//! the record, so a key stored that way would be deleted whatever the record -//! says (a key that predates the account is to be kept). The store therefore -//! refuses, with an error that says why, a [`KeyStore::put`] of a `voelin` blob -//! with `synced = true` while an account record names its uid as the device, or -//! while a record cannot be read, because then it cannot tell; and a put of an +//! # The device key is never a synced copy +//! +//! A sign-out keeps the device key, but its first step deletes every identity +//! bound with `synced = true`, before it reads the account record that names +//! the device key. A device key stored that way would be deleted by that step, +//! whether it predates the account or not, which is what the rule that a +//! sign-out keeps every device key forbids. The store therefore refuses, with an +//! error that says why, a [`KeyStore::put`] of a `voelin` blob with +//! `synced = true` while an account record names its uid as the device, or while +//! a record cannot be read, because then it cannot tell; and a put of an //! account record that names a key which is stored as a synced copy. A binding -//! with `synced = false` is accepted: a sign-out unbinds such a key and then -//! follows the record. The check and the write are done under the store's lock; -//! a second process writing the same file at the same moment is not covered. +//! with `synced = false` is accepted: a sign-out unbinds such a key and keeps +//! it. The check and the write are done under the store's lock; a second +//! process writing the same file at the same moment is not covered. //! //! A TeamSpeak blob that is refused says why in words that carry none of its //! input: its `data` is the identity's private key, and an error reaches log @@ -136,8 +211,10 @@ const PUT: &str = "INSERT INTO identities /// access to the TeamSpeak methods of the same connection. /// /// [`KeyStore::sign_out`] and the rest of the trait's provided methods work as -/// `voelin-identity` defines them, on top of the five methods here; the -/// sign-out only truncates the write-ahead log once, at its end. +/// `voelin-identity` defines them, on top of the five methods here: a sign-out +/// keeps every key of the device (only [`DeviceKeyChoice::Forget`] deletes the +/// device key), and only truncates the write-ahead log once, at its end, when +/// it deleted something. pub struct SqliteKeyStore { store: Mutex, } @@ -270,10 +347,13 @@ impl KeyStore for SqliteKeyStore { /// The trait's sign-out, with the log truncated once after its last step /// instead of after each of its removals: it removes up to a handful of - /// rows, and a checkpoint that another connection blocks costs a moment + /// rows (the synced copies, the account record and, with + /// [`DeviceKeyChoice::Forget`], the device key; every other key stays), and + /// a checkpoint that another connection blocks costs a moment /// (`Store::truncate_wal`) each time. The steps are the trait's own; they /// run on a `SignOutPass`, which deletes like [`Self::remove`] and leaves - /// the checkpoint to this method. + /// the checkpoint to this method. A sign-out that deleted nothing does not + /// checkpoint. fn sign_out(&self, account: &Uid, device_key: DeviceKeyChoice) -> KsResult { let pass = SignOutPass { store: self, deleted: AtomicBool::new(false) }; let outcome = KeyStore::sign_out(&pass, account, device_key); @@ -299,7 +379,10 @@ fn delete_row(store: &Store, kind: &str, uid: &str) -> KsResult { /// A [`SqliteKeyStore`] for the length of one [`KeyStore::sign_out`]: the same /// rows, but `remove` only notes that it deleted something, so that the sign-out -/// truncates the log once at its end. +/// truncates the log once at its end. What a sign-out removes is the synced +/// copies of integration secrets, the account record and, when the user chose +/// to forget it, the device key; unbinding goes through `put`, which deletes +/// nothing. struct SignOutPass<'a> { store: &'a SqliteKeyStore, /// Whether a row was deleted. @@ -470,26 +553,28 @@ enum Refused { /// `uid` is unique across kinds in this table. #[error("the uid {uid:?} is already stored as an identity of kind {kind:?}")] UidHeld { uid: String, kind: String }, - /// The Voelin key is the device key of an account record. A sign-out - /// deletes a synced copy without reading the record, so the key the record - /// says to keep would be deleted. + /// The Voelin key is the device key of an account record. A sign-out keeps + /// the device key, but it deletes a synced copy without reading the record, + /// so a device key stored as one would be deleted all the same. #[error( "the Voelin key {uid:?} is the device key of the account record {record:?} and cannot be \ - stored as a synced copy (synced = true): a sign-out would delete it whatever the record says" + stored as a synced copy (synced = true): a sign-out deletes every synced copy before it \ + reads the record, so it would delete the device key that it keeps" )] SyncedDeviceKey { uid: String, record: String }, /// An account record cannot be read, so the store cannot tell whether the /// Voelin key is its device key. #[error( "the Voelin key {uid:?} cannot be stored as a synced copy (synced = true): the account \ - record {record:?} cannot be read, so it may name this key as the device key" + record {record:?} cannot be read, so it may name this key as the device key, which a \ + sign-out keeps but would delete as a synced copy" )] UnreadableRecord { uid: String, record: String }, /// The device key of the record is stored as a synced copy already. #[error( "the account record {record:?} names the Voelin key {device:?} as the device key, which is \ - stored as a synced copy (synced = true): a sign-out would delete it whatever the record \ - says" + stored as a synced copy (synced = true): a sign-out deletes every synced copy before it \ + reads the record, so it would delete the device key that it keeps" )] RecordNamesSyncedKey { record: String, device: String }, } diff --git a/crates/voelin-store/src/lib.rs b/crates/voelin-store/src/lib.rs index 696290a..8a126f7 100644 --- a/crates/voelin-store/src/lib.rs +++ b/crates/voelin-store/src/lib.rs @@ -33,12 +33,48 @@ pub use store::{ Bookmark, CachedServerIcon, IdentityEntry, IdentityOrigin, QueryConfig, QueryTransport, Store, }; +/// How the JSON of a stored TeamSpeak identity is wrong: the category of the +/// reader's complaint and nothing of the text, which holds a private key. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum IdentityDamage { + /// The text is not JSON. + Malformed, + /// The text ends before the JSON does. + CutShort, + /// The JSON is not that of an identity: a field is missing or of another + /// type, or the key does not import. + NotAnIdentity, + /// The text could not be read. + Unreadable, +} + +impl std::fmt::Display for IdentityDamage { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Malformed => "malformed", + Self::CutShort => "cut short", + Self::NotAnIdentity => "not an identity", + Self::Unreadable => "unreadable", + }) + } +} + #[derive(Debug, thiserror::Error)] pub enum Error { #[error("database: {0}")] Db(#[from] rusqlite::Error), #[error("serialization: {0}")] Json(#[from] serde_json::Error), + /// The JSON of a stored TeamSpeak identity cannot be read, which only damage + /// outside the client can cause. It says how the text is wrong and where, and + /// never what it holds: the text is a private key, and the message of the + /// JSON reader quotes the value it refuses (`tsproto` reports a key that does + /// not import as an invalid value, the key string and all), so that message is + /// not kept, not here and not in a log line. + #[error( + "the stored TeamSpeak identity cannot be read: {damage} at line {line}, column {column}" + )] + Identity { damage: IdentityDamage, line: usize, column: usize }, #[error("{0} {1} not found")] NotFound(&'static str, i64), #[error("secret store: {0}")] diff --git a/crates/voelin-store/src/store.rs b/crates/voelin-store/src/store.rs index a1a0623..a79b3c6 100644 --- a/crates/voelin-store/src/store.rs +++ b/crates/voelin-store/src/store.rs @@ -8,7 +8,7 @@ use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use tsclientlib::Identity; -use crate::{Error, Result}; +use crate::{Error, IdentityDamage, Result}; /// A schema migration: SQL, or code for what SQL alone cannot do. enum Migration { @@ -244,6 +244,28 @@ impl Bookmark { /// waits. const CHECKPOINT_WAIT: Duration = Duration::from_millis(150); +/// The TeamSpeak identity in the JSON of a stored row. +/// +/// A text that does not read (it could only have been damaged outside the +/// client: [`Store::add_identity`] writes what `serde_json` makes of an +/// identity) is refused with [`Error::Identity`], which says how it is wrong and +/// where and never what it holds, as `voelin-core`'s `ts::identity::from_json` +/// does for the text it is handed. The reader's own message is dropped: it +/// quotes a value it refuses, and `tsproto` reports a key that does not import +/// as an invalid value, the key string and all, which would reach a status line +/// or a log. +fn identity_from_json(json: &str) -> Result { + serde_json::from_str(json).map_err(|error| { + let damage = match error.classify() { + serde_json::error::Category::Syntax => IdentityDamage::Malformed, + serde_json::error::Category::Eof => IdentityDamage::CutShort, + serde_json::error::Category::Data => IdentityDamage::NotAnIdentity, + serde_json::error::Category::Io => IdentityDamage::Unreadable, + }; + Error::Identity { damage, line: error.line(), column: error.column() } + }) +} + pub struct Store { pub(crate) db: Connection, } @@ -348,7 +370,7 @@ impl Store { })?; rows.map(|row| { let (id, name, uid, data, origin, is_default) = row?; - let identity: Identity = serde_json::from_str(&data)?; + let identity = identity_from_json(&data)?; let origin = IdentityOrigin::parse(&origin); Ok(IdentityEntry { id, name, uid, level: identity.level(), origin, is_default }) }) @@ -395,7 +417,7 @@ impl Store { ) .optional()?; let data = data.ok_or(Error::NotFound("identity", id))?; - Ok(serde_json::from_str(&data)?) + identity_from_json(&data) } /// Store an identity again, e.g. after its security level was improved. @@ -630,23 +652,43 @@ mod tests { reader.query_row("SELECT count(*) FROM identities", [], |r| r.get::<_, i64>(0)).unwrap(); store.add_identity("second", &Identity::create(), IdentityOrigin::User).unwrap(); - // A value that is not the default, so that restoring a constant would show. + // A value that is not the default, so that restoring a constant would + // show, and one so long that a checkpoint that waited as long as the + // connection allows would not come back by itself. + const HOUR_MS: i64 = 3_600_000; let timeout = |store: &Store| -> i64 { store.db.pragma_query_value(None, "busy_timeout", |r| r.get(0)).unwrap() }; - store.db.busy_timeout(Duration::from_millis(2345)).unwrap(); - let started = std::time::Instant::now(); - store.truncate_wal(); - let elapsed = started.elapsed(); - assert!(elapsed < Duration::from_secs(1), "the checkpoint waited {elapsed:?}"); + store.db.busy_timeout(Duration::from_secs(3600)).unwrap(); + + // "Briefly" is not a time: a checkpoint ends in two fsyncs, which take + // seconds under disk pressure (it took 6 s here beside `dd conv=fsync` + // loops), and only a checkpoint that comes back while the reader still + // holds its snapshot has not waited for it. So the reader lets go from + // another thread after 30 s, which ends a checkpoint that does not give + // up with a failure here and not with an hour's wait. + let (back, hear) = std::sync::mpsc::channel::<()>(); + let watchdog = std::thread::spawn(move || { + let in_time = hear.recv_timeout(Duration::from_secs(30)).is_ok(); + if !in_time { + reader.execute_batch("COMMIT").unwrap(); + } + (reader, in_time) + }); + // One attempt, which the reader blocks (`1`). + let blocked = store.checkpoint_truncate(); + back.send(()).ok(); + let (reader, in_time) = watchdog.join().unwrap(); + assert!(in_time, "the checkpoint waited for the reader instead of giving up"); + assert_eq!(blocked.unwrap(), 1, "the reader should block the reset"); assert!(std::fs::metadata(&wal).unwrap().len() > 0, "the reader should block the reset"); - assert_eq!(timeout(&store), 2345); + assert_eq!(timeout(&store), HOUR_MS); // Without the reader the same call resets the log. reader.execute_batch("COMMIT").unwrap(); store.truncate_wal(); assert_eq!(std::fs::metadata(&wal).unwrap().len(), 0); - assert_eq!(timeout(&store), 2345); + assert_eq!(timeout(&store), HOUR_MS); drop(reader); drop(store); std::fs::remove_dir_all(dir).unwrap(); diff --git a/crates/voelin-store/tests/identity_text.rs b/crates/voelin-store/tests/identity_text.rs new file mode 100644 index 0000000..6297829 --- /dev/null +++ b/crates/voelin-store/tests/identity_text.rs @@ -0,0 +1,330 @@ +//! A damaged identity row: what the store returns and logs about it says how +//! the row is wrong and never what it holds. +//! +//! The `data` of a TeamSpeak row is the JSON of a private key. Only something +//! outside the client can damage it, but when that happens the error of the +//! JSON reader quotes the value it refuses (`tsproto` reports a key that does +//! not import as an invalid value, the key string and all), and an error +//! reaches a status line, an event or a log. `Store::identity` and +//! `Store::identities` used to return that error as it was. +//! +//! Every case here damages a row of a database file through a second +//! connection, calls everything of the store that reads or writes the row, and +//! looks through the errors (their text, their `Debug` text and their sources) +//! and the logs at TRACE for any 8 characters in a row of what the row held. + +use rusqlite::types::Value; +use rusqlite::{Connection, params}; +use tsclientlib::Identity; +use voelin_identity::{ + AccountBinding, AccountId, DeviceKeyChoice, IdentityBlob, IntegrationId, KIND_TEAMSPEAK, + KeyStore, Uid, account_uid, +}; +use voelin_store::{Error, IdentityDamage, IdentityOrigin, SqliteKeyStore, Store}; + +mod support; + +/// A directory of its own that is removed again. +struct Scratch(std::path::PathBuf); + +impl Scratch { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir() + .join(format!("voelin-identity-text-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + + fn db(&self) -> std::path::PathBuf { + self.0.join("client.db") + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// Letters and digits that no message of this crate, of `serde_json` or of +/// SQLite is made of in a run of eight. +const SECRET: &str = "Zq7Xm2Vb9Lk4Pw8Rt3Yn6Hd1Fs5Jc0Ga"; +const OTHER_SECRET: &str = "Qx3Wv8Nb5Mj1Kh6Gf2Dt9Rs4Pl7Yc0Za"; + +/// The JSON of a fresh identity whose key lost its last two characters (a key +/// that does not import), and that cut key. +fn json_with_a_cut_key() -> (String, String) { + let mut json = serde_json::to_value(Identity::create()).unwrap(); + let key = json["key"].as_str().unwrap().to_owned(); + let cut = key[..key.len() - 2].to_owned(); + json["key"] = cut.clone().into(); + (json.to_string(), cut) +} + +/// The JSON of a fresh identity whose counter is a string (`SECRET`), and that +/// string: the reader quotes it in its message. +fn json_with_a_counter_of_the_wrong_type() -> String { + let mut json = serde_json::to_value(Identity::create()).unwrap(); + json["counter"] = SECRET.into(); + json.to_string() +} + +/// The JSON of a fresh identity cut in the middle of its key, and the key. +fn json_cut_inside_its_key() -> (String, String) { + let json = serde_json::to_value(Identity::create()).unwrap(); + let key = json["key"].as_str().unwrap().to_owned(); + let text = json.to_string(); + let cut = text.find(&key).unwrap() + key.len() / 2; + (text[..cut].to_owned(), key) +} + +/// How a row's `data` is damaged: what is stored, as which storage class, and +/// the text of it that must never be repeated. +struct Damage { + label: &'static str, + value: Value, + /// `CAST(? AS TEXT)`: the bytes are stored as TEXT, not as a BLOB. + as_text: bool, + secret: String, + /// What the store says of it, when it reads it as JSON. + damage: Option, +} + +fn damages() -> Vec { + let (cut, cut_key) = json_with_a_cut_key(); + let (cut_short, whole_key) = json_cut_inside_its_key(); + let mut not_utf8 = format!(r#"{{"key":"{SECRET}","counter":1}}"#).into_bytes(); + not_utf8.push(0xff); + vec![ + Damage { + label: "a key that does not import", + value: Value::Text(cut), + as_text: false, + secret: cut_key, + damage: Some(IdentityDamage::NotAnIdentity), + }, + Damage { + label: "a field of the wrong type", + value: Value::Text(json_with_a_counter_of_the_wrong_type()), + as_text: false, + secret: SECRET.to_owned(), + damage: Some(IdentityDamage::NotAnIdentity), + }, + Damage { + label: "syntax", + value: Value::Text(format!("not json: {SECRET}")), + as_text: false, + secret: SECRET.to_owned(), + damage: Some(IdentityDamage::Malformed), + }, + Damage { + label: "cut short", + value: Value::Text(cut_short), + as_text: false, + secret: whole_key, + damage: Some(IdentityDamage::CutShort), + }, + Damage { + label: "bytes that are no UTF-8, stored as a BLOB", + value: Value::Blob(not_utf8.clone()), + as_text: false, + secret: SECRET.to_owned(), + damage: None, + }, + Damage { + label: "bytes that are no UTF-8, stored as TEXT", + value: Value::Blob(not_utf8), + as_text: true, + secret: SECRET.to_owned(), + damage: None, + }, + ] +} + +/// Fail if `text` holds any 8 characters in a row of `secret`. +fn assert_holds_no_piece_of(text: &str, secret: &str, what: &str) { + assert!(secret.len() >= 8 && secret.is_ascii()); + for piece in secret.as_bytes().windows(8) { + let piece = std::str::from_utf8(piece).unwrap(); + assert!(!text.contains(piece), "{what}: {text:?} holds {piece:?} of the row's data"); + } +} + +/// The texts an error shows to a caller: how it reads, its `Debug` text and +/// those of everything it was caused by. +fn texts_of(error: &(dyn std::error::Error + 'static)) -> Vec { + let mut texts = vec![error.to_string(), format!("{error:?}")]; + let mut source = error.source(); + while let Some(cause) = source { + texts.push(cause.to_string()); + texts.push(format!("{cause:?}")); + source = cause.source(); + } + texts +} + +fn binding() -> AccountBinding { + let account = account_uid(&Uid::from_bytes([1; 32]), &AccountId::from_bytes([2; 16])); + AccountBinding { + account, + integration: Some(IntegrationId::from_bytes([7; 16])), + rev: 3, + synced: false, + } +} + +/// A database file with one TeamSpeak identity, its `data` replaced by `damage` +/// through a second connection. Returns the id and uid of the row. +fn damaged_database(scratch: &Scratch, damage: &Damage) -> (i64, String) { + let store = Store::open(&scratch.db()).unwrap(); + let identity = Identity::create(); + let id = store.add_identity("damaged", &identity, IdentityOrigin::User).unwrap(); + let uid = identity.key().to_pub().get_uid(); + drop(store); + + let db = Connection::open(scratch.db()).unwrap(); + let sql = if damage.as_text { + "UPDATE identities SET data = CAST(?1 AS TEXT) WHERE id = ?2" + } else { + "UPDATE identities SET data = ?1 WHERE id = ?2" + }; + assert_eq!(db.execute(sql, params![damage.value, id]).unwrap(), 1); + (id, uid) +} + +#[test] +fn the_json_readers_own_message_quotes_what_it_refuses() { + // Without this the cases below could not fail: serde's message for a key + // that does not import and for a field of the wrong type repeats the value. + let (json, cut_key) = json_with_a_cut_key(); + let raw = serde_json::from_str::(&json).unwrap_err().to_string(); + assert!(raw.contains(&cut_key), "the reader's own message quotes the key: {raw}"); + let typed = json_with_a_counter_of_the_wrong_type(); + let raw = serde_json::from_str::(&typed).unwrap_err().to_string(); + assert!(raw.contains(SECRET), "the reader's own message quotes the value: {raw}"); +} + +#[test] +fn a_damaged_identity_row_is_reported_by_its_kind_of_damage_and_never_by_its_text() { + for damage in damages() { + let scratch = Scratch::new("store"); + let (id, _) = damaged_database(&scratch, &damage); + let label = damage.label; + let store = Store::open(&scratch.db()).unwrap(); + + let ((one, all, default), lines) = support::at_trace(|| { + ( + store.identity(id).unwrap_err(), + store.identities().unwrap_err(), + store.default_identity().unwrap_err(), + ) + }); + for (call, error) in [("identity", &one), ("identities", &all), ("default", &default)] { + for text in texts_of(error) { + assert_holds_no_piece_of(&text, &damage.secret, &format!("{label}: {call}")); + } + if let Some(expected) = damage.damage { + // The kind of damage and where, in the store's own words. + match error { + Error::Identity { damage, line, column } => { + assert_eq!(*damage, expected, "{label}: {call}"); + assert_eq!((*line, *column > 0), (1, true), "{label}: {call}: {error}"); + let shown = error.to_string(); + assert!( + shown.starts_with(&format!( + "the stored TeamSpeak identity cannot be read: {expected} at line 1, column " + )), + "{label}: {call}: {shown}" + ); + } + other => panic!("{label}: {call}: {other:?}"), + } + } + } + for line in &lines { + assert_holds_no_piece_of(line, &damage.secret, &format!("{label}: a log line")); + } + } +} + +#[test] +fn a_damaged_identity_row_does_not_leak_through_the_key_store_either() { + for damage in damages() { + let scratch = Scratch::new("keystore"); + let (_id, uid) = damaged_database(&scratch, &damage); + let label = damage.label; + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + + // Everything that reads or writes the row, in the order a sign-out would, + // with the errors and the logs of all of it kept. + let (results, lines) = support::at_trace(|| { + let mut errors: Vec> = Vec::new(); + let mut note = |result: Result<(), voelin_identity::KeyStoreError>| { + if let Err(error) = result { + errors.push(Box::new(error)); + } + }; + let listed = store.list().unwrap(); + let entry = listed.iter().find(|info| info.uid == uid).expect("the row is listed"); + assert_eq!(entry.level, 0, "{label}: damage reads as level 0"); + + // What `get` hands out is the data itself; a `put` of it rebinds the row. + let blob = store.get(KIND_TEAMSPEAK, &uid).unwrap().expect("the row is read"); + note(store.put(&blob.clone().with_binding(binding()))); + // Other data over the row is checked and refused, and the refusal does + // not repeat it. + let other = format!(r#"{{"key":"{SECRET}","counter":"{OTHER_SECRET}"}}"#); + note(store.put(&IdentityBlob::from_row(KIND_TEAMSPEAK, uid.clone(), 0, other))); + note(store.put(&IdentityBlob::teamspeak(uid.clone(), 8, SECRET))); + // The sign-out that unbinds it, and the delete that removes it. + store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + store.remove(KIND_TEAMSPEAK, &uid).unwrap(); + errors + }); + assert_eq!(results.len(), 2, "{label}: the two refusals: {results:?}"); + for error in &results { + for text in texts_of(error.as_ref()) { + assert_holds_no_piece_of(&text, &damage.secret, &format!("{label}: a refusal")); + assert_holds_no_piece_of( + &text, + SECRET, + &format!("{label}: a refusal of other data"), + ); + assert_holds_no_piece_of(&text, OTHER_SECRET, &format!("{label}: other data")); + } + } + for line in &lines { + assert_holds_no_piece_of(line, &damage.secret, &format!("{label}: a log line")); + assert_holds_no_piece_of(line, SECRET, &format!("{label}: a log line, other data")); + } + } +} + +#[test] +fn the_capture_sees_what_the_store_logs() { + // A control for the cases above: a row whose binding columns are damaged is + // listed with a warning that names it, and the capture takes it in at TRACE. + let scratch = Scratch::new("control"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + let blob = IdentityBlob::new("future", "future:one", 0, format!(r#"{{"secret":"{SECRET}"}}"#)); + store.put(&blob).unwrap(); + let db = Connection::open(scratch.db()).unwrap(); + assert_eq!( + db.execute("UPDATE identities SET synced = 2 WHERE kind = 'future'", []).unwrap(), + 1 + ); + + let (listed, lines) = support::at_trace(|| store.list().unwrap()); + assert_eq!(listed.len(), 1); + let warning = lines + .iter() + .find(|line| line.contains("the binding columns of an identity cannot be read")) + .unwrap_or_else(|| panic!("no warning in {lines:?}")); + assert!(warning.starts_with("WARN "), "{warning}"); + assert!(warning.contains("future:one"), "{warning}"); + // And it does not carry the row's data either. + for line in &lines { + assert_holds_no_piece_of(line, SECRET, "a log line"); + } +} diff --git a/crates/voelin-store/tests/keystore.rs b/crates/voelin-store/tests/keystore.rs index 5da0b3e..cb1b595 100644 --- a/crates/voelin-store/tests/keystore.rs +++ b/crates/voelin-store/tests/keystore.rs @@ -31,6 +31,8 @@ use voelin_identity::{ }; use voelin_store::{IdentityOrigin, SqliteKeyStore, Store}; +mod support; + /// What `serde_json::to_string(&tsproto::Identity)` writes for the test /// identity of tsproto's own `identity_tests`. const TEAMSPEAK_JSON: &str = r#"{"key":"YTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=","counter":2792354,"max_counter":2792354}"#; @@ -803,8 +805,9 @@ fn the_record_fixture_is_what_the_protocol_writes() { } #[test] -fn signing_out_deletes_the_copies_and_keeps_the_device_secrets() { - // The device key was made for the account: signing out deletes it. +fn signing_out_deletes_the_copies_and_keeps_the_keys_and_the_device_secrets() { + // The device key was made for the account: signing out keeps it all the + // same, unbound (open question 10 of the accounts design). let Install { store, synced, device_only, local } = signed_in_install(false); let mine = binding().account; let theirs = account_uid(&issuer(), &AccountId::from_bytes([9; 16])); @@ -815,19 +818,20 @@ fn signing_out_deletes_the_copies_and_keeps_the_device_secrets() { store.put_voelin_key(&other_key).unwrap(); let done = store.sign_out(&mine, DeviceKeyChoice::Auto).unwrap(); - let mut expected_removed = vec![ - (KIND_ACCOUNT.to_owned(), record().blob_uid()), - pair(&synced), - (KIND_VOELIN.to_owned(), key().uid().to_base32()), - ]; + let mut expected_removed = vec![(KIND_ACCOUNT.to_owned(), record().blob_uid()), pair(&synced)]; expected_removed.sort(); assert_eq!(sorted(done.removed.clone()), expected_removed, "{done:?}"); - assert_eq!(done.unbound, vec![info_of(&device_only.clone().with_binding(None))]); + assert_eq!( + sorted(done.unbound.clone()), + sorted(vec![device_key_info(), info_of(&device_only.clone().with_binding(None))]), + "{done:?}" + ); - // What is left: the device secret unbound and byte for byte as it was, the - // local and the other account's identities as they were, the other key. + // What is left: the device key, the device secret unbound and byte for + // byte as it was, the local and the other account's identities as they + // were, the other key. assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none()); - assert!(store.voelin_key(&key().uid()).unwrap().is_none()); + assert_eq!(store.voelin_key(&key().uid()).unwrap().unwrap().uid(), key().uid()); assert_eq!(store.account_record().unwrap(), None); let kept = store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap(); assert_eq!(kept, device_only.clone().with_binding(None)); @@ -835,11 +839,11 @@ fn signing_out_deletes_the_copies_and_keeps_the_device_secrets() { assert_eq!(store.get(KIND_TEAMSPEAK, &local.uid).unwrap().unwrap(), local); assert_eq!(store.get(KIND_TEAMSPEAK, &theirs_blob.uid).unwrap().unwrap(), theirs_blob); assert!(store.voelin_key(&other_key.uid()).unwrap().is_some()); - assert_eq!(store.list().unwrap().len(), 4); + assert_eq!(store.list().unwrap().len(), 5); // Signing out again finds nothing to do. assert_eq!(store.sign_out(&mine, DeviceKeyChoice::Auto).unwrap(), SignOut::default()); - assert_eq!(store.list().unwrap().len(), 4); + assert_eq!(store.list().unwrap().len(), 5); // Another account's sign-out acts on that account's identities only. assert_eq!( store.sign_out(&theirs, DeviceKeyChoice::Auto).unwrap().removed, @@ -892,17 +896,38 @@ fn signing_out_keeps_a_device_key_that_predates_the_account() { } #[test] -fn signing_out_deletes_a_device_key_the_client_made_for_the_account() { +fn signing_out_keeps_a_device_key_the_client_made_for_the_account_too() { + // Open question 10 of the accounts design (answered 2026-10-24): a key that + // the client made for the account is the user's identity at every host + // without accounts that the user reached with it as well, so `Auto` keeps + // it like a key that predates the account. Only `Forget` deletes it. let Install { store, device_only, local, .. } = signed_in_install(false); + let key_before = store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap(); + let signature = key().sign(b"the same key, signed before and after"); + let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); - assert!(done.removed.contains(&device_key_info()), "{done:?}"); - assert!(!done.unbound.contains(&device_key_info()), "{done:?}"); - assert!(store.voelin_key(&key().uid()).unwrap().is_none()); + assert!(!done.removed.contains(&device_key_info()), "{done:?}"); + assert!(done.unbound.contains(&device_key_info()), "{done:?}"); + let kept = store.voelin_key(&key().uid()).unwrap().expect("the key stays"); + assert_eq!(kept.sign(b"the same key, signed before and after"), signature); + let key_after = store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap(); + assert_eq!(key_after, key_before, "the stored blob is untouched"); + assert_eq!(key_after.binding, None); let mut left = sorted(store.list().unwrap()); left.sort(); - let mut expected = vec![pair(&device_only), pair(&local)]; + let mut expected = vec![pair(&device_only), pair(&local), pair(&key_after)]; expected.sort(); - assert_eq!(left, expected, "the device secret and the local one"); + assert_eq!(left, expected, "the key, the device secret and the local one"); + + // The flag changes nothing: a key that predates the account gets the same + // treatment. (The other identities of the two installs are fresh ones, so + // the reports differ in them.) + let existing = signed_in_install(true); + let again = existing.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + assert!(again.unbound.contains(&device_key_info()), "{again:?}"); + assert!(!again.removed.contains(&device_key_info()), "{again:?}"); + assert_eq!(again.removed.len(), done.removed.len()); + assert_eq!(again.unbound.len(), done.unbound.len()); } #[test] @@ -1282,16 +1307,10 @@ impl OnFile { /// What a sign-out of `choice` must have done, whatever else was damaged: /// the record and the synced copy are gone, the device-only secret is /// unbound and the local identity is as it was; the device key is deleted - /// when the user forgot it or the client made it for the account, and - /// reported as kept and unbound otherwise. - fn assert_signed_out( - &self, - done: &SignOut, - bound_existing_key: bool, - choice: DeviceKeyChoice, - label: &str, - ) { - let key_goes = matches!(choice, DeviceKeyChoice::Forget(_)) || !bound_existing_key; + /// when the user forgot it, and reported as kept and unbound otherwise, + /// whether it predates the account or not. + fn assert_signed_out(&self, done: &SignOut, choice: DeviceKeyChoice, label: &str) { + let key_goes = matches!(choice, DeviceKeyChoice::Forget(_)); let mut removed = vec![(KIND_ACCOUNT.to_owned(), record().blob_uid()), pair(&self.synced)]; let mut unbound = vec![pair(&self.device_only)]; let device_key = (KIND_VOELIN.to_owned(), key().uid().to_base32()); @@ -1335,7 +1354,7 @@ const RECORD_ROW_DAMAGE: [&str; 5] = [ fn a_damaged_account_record_row_does_not_keep_a_sign_out_from_finishing() { // The record carries no binding, so damage in those columns says nothing // about the record: it is read, and the sign-out does what it always does. - // `Forget` deletes the key it names; `Auto` follows the record. + // `Forget` deletes the key it names; `Auto` keeps it. for bound_existing_key in [true, false] { for damage in RECORD_ROW_DAMAGE { for choice in [DeviceKeyChoice::Auto, DeviceKeyChoice::Forget(key().uid())] { @@ -1346,7 +1365,7 @@ fn a_damaged_account_record_row_does_not_keep_a_sign_out_from_finishing() { .store .sign_out(&binding().account, choice) .unwrap_or_else(|error| panic!("{label}: {error}")); - install.assert_signed_out(&done, bound_existing_key, choice, &label); + install.assert_signed_out(&done, choice, &label); } } } @@ -1354,8 +1373,9 @@ fn a_damaged_account_record_row_does_not_keep_a_sign_out_from_finishing() { #[test] fn a_damaged_device_key_row_does_not_keep_a_sign_out_from_finishing() { - // With `Auto` and a key that predates the account, the trait reads the key - // to report it as kept. Damage in its binding columns must not fail that. + // With `Auto` the trait reads the key to report it as kept, whether it + // predates the account or not. Damage in its binding columns must not fail + // that. for bound_existing_key in [true, false] { for damage in [ "UPDATE identities SET synced = 2 WHERE kind = 'voelin'", @@ -1369,12 +1389,10 @@ fn a_damaged_device_key_row_does_not_keep_a_sign_out_from_finishing() { .store .sign_out(&binding().account, DeviceKeyChoice::Auto) .unwrap_or_else(|error| panic!("{label}: {error}")); - install.assert_signed_out(&done, bound_existing_key, DeviceKeyChoice::Auto, &label); - if bound_existing_key { - // The key was kept, as it was stored. - let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap(); - assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]); - } + install.assert_signed_out(&done, DeviceKeyChoice::Auto, &label); + // The key was kept, as it was stored. + let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap(); + assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]); } } } @@ -1423,7 +1441,7 @@ fn an_account_row_whose_data_is_not_text_is_deleted_like_an_unreadable_record() assert!(store.get(KIND_TEAMSPEAK, &install.synced.uid).unwrap().is_none(), "{label}"); let secret = store.get(KIND_TEAMSPEAK, &install.device_only.uid).unwrap().unwrap(); assert_eq!(secret.binding, None, "{label}"); - // `Auto` cannot find the key the record named, and keeps it. + // `Auto` keeps the key, as it always does; `Forget` deleted it first. let forgot = matches!(choice, DeviceKeyChoice::Forget(_)); assert_eq!(store.voelin_key(&key().uid()).unwrap().is_none(), forgot, "{label}"); assert_eq!(store.sign_out(&binding().account, choice).unwrap(), SignOut::default()); @@ -1623,14 +1641,13 @@ fn key_text(json: &str, field: &str) -> String { } #[test] -fn a_key_deleted_by_a_sign_out_is_in_neither_the_database_file_nor_its_log() { - // The device key the client made for the account goes with `Auto`, and a - // key that predates the account goes when the user forgets it. Either way - // its PKCS#8 text, and a synced TeamSpeak copy's key, must not stay in the - // free pages of `client.db` or in a frame of `client.db-wal`. - for (bound_existing_key, choice) in - [(false, DeviceKeyChoice::Auto), (true, DeviceKeyChoice::Forget(key().uid()))] - { +fn a_key_forgotten_by_a_sign_out_is_in_neither_the_database_file_nor_its_log() { + // The device key goes when the user forgets it, whether it predates the + // account or the client made it for the account. Its PKCS#8 text, and a + // synced TeamSpeak copy's key, must not stay in the free pages of + // `client.db` or in a frame of `client.db-wal`. + for bound_existing_key in [true, false] { + let choice = DeviceKeyChoice::Forget(key().uid()); let scratch = Scratch::new("scrub-signout"); let store = SqliteKeyStore::open(&scratch.db()).unwrap(); let device = IdentityBlob::voelin(&key()).unwrap(); @@ -1697,13 +1714,23 @@ fn removing_through_the_key_store_leaves_no_key_behind_either() { } #[test] -fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer() { +fn a_reader_that_blocks_the_checkpoint_costs_one_checkpoint_and_starves_no_writer() { // A connection that keeps a read snapshot (a long query of the UI, a backup) // keeps the checkpoint that truncates the log from finishing. The sign-out - // still deletes and warns that the bytes may stay in the log, and it waits - // for the checkpoint a moment, not for the busy timeout of five seconds once - // per removed row. While the checkpoint waits it holds the writer lock of the - // log, so a second connection that writes meanwhile must get through. + // still deletes and warns that the bytes may stay in the log, and it makes + // one checkpoint for all its removals, not one per removed row. While the + // checkpoint waits it holds the writer lock of the log, so a second + // connection that writes meanwhile must get through. + // + // No clock decides anything here. A checkpoint ends in two fsyncs, and under + // disk pressure (a build or a copy writing beside the tests) they take + // seconds: the review saw sign-outs of 1.2 to 1.9 s at 10 to 30 % I/O + // pressure, and `dd conv=fsync` loops beside 32 busy loops made them 5 s. A + // bound on the sign-out or a short busy timeout on the writer failed this + // test with "database is locked" for a checkpoint that was only slow. That a + // checkpoint gives up on a reader after a moment and does not wait out the + // connection's busy timeout is pinned where that timeout can be set to an + // hour: `store::tests::a_blocked_checkpoint_waits_briefly_and_leaves_the_busy_timeout_as_it_was`. let scratch = Scratch::new("blocked-checkpoint"); let store = SqliteKeyStore::open(&scratch.db()).unwrap(); store.put_voelin_key(&key()).unwrap(); @@ -1718,37 +1745,71 @@ fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer( let rows: i64 = reader.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap(); assert_eq!(rows, 4); + /// Stops the writer when dropped, so that a failed assertion of the test does + /// not leave the scope waiting for it. + struct StopsTheWriter<'a>(&'a AtomicBool); + impl Drop for StopsTheWriter<'_> { + fn drop(&mut self) { + self.0.store(true, Ordering::Relaxed); + } + } let stop = AtomicBool::new(false); - let (done, elapsed, writes, errors) = std::thread::scope(|scope| { + let written = AtomicUsize::new(0); + let (done, elapsed, errors, lines) = std::thread::scope(|scope| { + let _stops = StopsTheWriter(&stop); let writer = scope.spawn(|| { - // Its own connection, which gives up on a lock after one second. + // Its own connection, set up as the app's are (`Store::open`: the log + // and `synchronous = NORMAL`, so that a commit does not wait for the + // disk), with a busy timeout that a slow checkpoint does not reach. let db = Connection::open(scratch.db()).unwrap(); - db.busy_timeout(Duration::from_secs(1)).unwrap(); + db.pragma_update(None, "synchronous", "NORMAL").unwrap(); + db.busy_timeout(Duration::from_secs(60)).unwrap(); let sql = "INSERT OR REPLACE INTO settings (key, value) VALUES ('probe', ?1)"; - let (mut writes, mut errors) = (0, Vec::new()); + let mut errors = Vec::new(); while !stop.load(Ordering::Relaxed) { - match db.execute(sql, [writes.to_string()]) { - Ok(_) => writes += 1, + let began = Instant::now(); + match db.execute(sql, [written.load(Ordering::Relaxed).to_string()]) { + Ok(_) => { + written.fetch_add(1, Ordering::Relaxed); + } Err(error) => errors.push(error.to_string()), } - std::thread::sleep(Duration::from_millis(5)); + // It pauses ten times as long as the write took, and 5 ms at least. + // Under disk pressure a commit takes 100 ms and more, and a writer + // that paused 5 ms after each would hold the writer lock nearly all + // the time and keep the sign-out, whose busy timeout is the default + // five seconds, from getting it (`DatabaseBusy`). + let wake = Instant::now() + (began.elapsed() * 10).max(Duration::from_millis(5)); + while Instant::now() < wake && !stop.load(Ordering::Relaxed) { + std::thread::sleep(Duration::from_millis(1)); + } } - (writes, errors) + errors }); + // The sign-out starts when the writer is up and has written, not when + // the thread was spawned: a thread of a busy machine can start late. + let deadline = Instant::now() + Duration::from_secs(60); + while written.load(Ordering::Relaxed) == 0 { + assert!(Instant::now() < deadline, "the writer never ran"); + std::thread::sleep(Duration::from_millis(1)); + } let started = Instant::now(); - let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto); + let (done, lines) = support::at_trace(|| { + store.sign_out(&binding().account, DeviceKeyChoice::Forget(key().uid())) + }); let elapsed = started.elapsed(); stop.store(true, Ordering::Relaxed); - let (writes, errors) = writer.join().unwrap(); - (done.unwrap(), elapsed, writes, errors) + let errors = writer.join().unwrap(); + (done.unwrap(), elapsed, errors, lines) }); - // Four removals: the two copies, the device key the client made, the record. + // Four removals: the two copies, the device key the user forgot, the record. assert_eq!(done.removed.len(), 4, "{done:?}"); assert!(store.list().unwrap().is_empty()); - assert!(writes > 0, "the writer never ran"); assert!(errors.is_empty(), "a concurrent writer failed: {errors:?}"); - assert!(elapsed < Duration::from_secs(1), "the sign-out took {elapsed:?}"); + // One checkpoint for the four removals: each one that is blocked says so. + let blocked = support::blocked_checkpoints(&lines); + assert_eq!(blocked, 1, "{lines:?} (the sign-out took {elapsed:?})"); // Nothing is lost by the wait: once the reader is gone, the next removal // truncates the log. @@ -1758,6 +1819,245 @@ fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer( assert!(RawFiles::read(&scratch).wal.is_empty(), "the log is truncated again"); } +// ------------------------- the keys a sign-out keeps, and the one the user forgets +// +// Open question 10 of the accounts design (Phase 2 task 34): a sign-out keeps +// every device key, and "Forget this device's identity" is the only deletion. + +/// Every column of the row of this `(kind, uid)` as SQLite holds it, by name. +fn named_row(db: &Connection, kind: &str, uid: &str) -> Vec<(String, rusqlite::types::Value)> { + db.query_row( + "SELECT * FROM identities WHERE kind = ?1 AND uid = ?2", + params![kind, uid], + |row| { + let names: Vec = + row.as_ref().column_names().iter().map(|n| n.to_string()).collect(); + names + .into_iter() + .enumerate() + .map(|(index, name)| Ok((name, row.get(index)?))) + .collect::>>() + }, + ) + .unwrap() +} + +#[test] +fn the_device_key_survives_a_sign_out_byte_for_byte_in_the_file() { + // Whether it predates the account or the client made it for the account, no + // column of its row changes: the key never carried a binding, and a sign-out + // writes nothing to it. + for bound_existing_key in [true, false] { + let install = signed_in_install_on_file(bound_existing_key); + let uid = key().uid().to_base32(); + let db = Connection::open(install.scratch.db()).unwrap(); + let before = named_row(&db, KIND_VOELIN, &uid); + assert!(before.len() >= 8, "{before:?}"); + + let done = install.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + assert!(done.unbound.contains(&device_key_info()), "{bound_existing_key}: {done:?}"); + assert!(!done.removed.contains(&device_key_info()), "{bound_existing_key}: {done:?}"); + assert_eq!(named_row(&db, KIND_VOELIN, &uid), before, "{bound_existing_key}"); + let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap(); + assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]); + } +} + +#[test] +fn a_device_key_that_carries_a_binding_is_unbound_and_keeps_the_rest_of_its_row() { + // The store accepts a binding with `synced = false` on the device key (a + // binding with `synced = true` is refused, see the last section). A sign-out + // unbinds it and keeps it: the four binding columns are the only ones that + // change. + const BINDING_COLUMNS: [&str; 4] = ["account", "integration", "integration_rev", "synced"]; + for bound_existing_key in [true, false] { + let install = signed_in_install_on_file(bound_existing_key); + let uid = key().uid().to_base32(); + let device_only = AccountBinding { synced: false, ..binding() }; + install + .store + .put(&IdentityBlob::voelin(&key()).unwrap().with_binding(device_only)) + .unwrap(); + let db = Connection::open(install.scratch.db()).unwrap(); + let before = named_row(&db, KIND_VOELIN, &uid); + let bound = |row: &[(String, rusqlite::types::Value)]| { + row.iter().any(|(name, value)| { + name == "account" && !matches!(value, rusqlite::types::Value::Null) + }) + }; + assert!(bound(&before), "the setup binds the key"); + + let done = install.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + assert!(done.unbound.contains(&device_key_info()), "{bound_existing_key}: {done:?}"); + assert!(!done.removed.contains(&device_key_info()), "{bound_existing_key}: {done:?}"); + + let after = named_row(&db, KIND_VOELIN, &uid); + assert!(!bound(&after), "{bound_existing_key}: unbound"); + assert_eq!(before.len(), after.len()); + for ((name, was), (_, is)) in before.iter().zip(&after) { + if !BINDING_COLUMNS.contains(&name.as_str()) { + assert_eq!(is, was, "{bound_existing_key}: column {name} is not a binding column"); + } + } + let stored = install.store.get(KIND_VOELIN, &uid).unwrap().unwrap(); + assert_eq!(stored, IdentityBlob::voelin(&key()).unwrap()); + assert!(install.store.bound_to(&binding().account).unwrap().is_empty()); + } +} + +#[test] +fn a_sign_out_scrubs_the_copies_it_deletes_and_leaves_the_kept_keys_in_the_file() { + // What a sign-out still deletes is a synced copy (a private key, which + // the service holds again) and the record: those are gone from the file and + // its log. The device key and the device-only secret are kept, so their text + // is still there. + let scratch = Scratch::new("scrub-keeps"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + let device = IdentityBlob::voelin(&key()).unwrap(); + let synced = fresh_teamspeak(binding()); + let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() }); + let device_text = key_text(&device.json, "pkcs8"); + let (synced_text, device_only_text) = + (key_text(&synced.json, "key"), key_text(&device_only.json, "key")); + for blob in [&device, &synced, &device_only] { + store.put(blob).unwrap(); + } + store.put_account_record(&AccountRecord { bound_existing_key: false, ..record() }).unwrap(); + let neighbour = Store::open(&scratch.db()).unwrap(); + let before = RawFiles::read(&scratch); + assert!(before.holds(&device_text) && before.holds(&synced_text)); + + store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + let after = RawFiles::read(&scratch); + assert_eq!(after.where_is(&synced_text), (false, false), "the synced copy"); + assert!(after.holds(&device_text), "the device key is kept"); + assert!(after.holds(&device_only_text), "the device-only secret is kept"); + assert!(after.wal.is_empty(), "the log is truncated"); + drop(neighbour); +} + +#[test] +fn a_sign_out_that_deletes_nothing_does_not_checkpoint() { + // With no record and no synced copy a sign-out only unbinds. The checkpoint + // belongs to deletions: with a reader that blocks it, a deletion says so, and + // the sign-out does not. + let scratch = Scratch::new("no-deletion"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() }); + store.put(&device_only).unwrap(); + let reader = Connection::open(scratch.db()).unwrap(); + reader.execute_batch("BEGIN").unwrap(); + let rows: i64 = reader.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap(); + assert_eq!(rows, 1); + + let (done, lines) = + support::at_trace(|| store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap()); + assert!(done.removed.is_empty(), "{done:?}"); + assert_eq!(done.unbound, vec![info_of(&device_only.clone().with_binding(None))]); + assert_eq!(support::blocked_checkpoints(&lines), 0, "{lines:?}"); + + // The same reader does block the checkpoint of a deletion, so the count above + // would have shown one. + store.put_voelin_key(&key()).unwrap(); + let (removed, lines) = + support::at_trace(|| store.remove(KIND_VOELIN, &key().uid().to_base32()).unwrap()); + assert!(removed); + assert_eq!(support::blocked_checkpoints(&lines), 1, "{lines:?}"); + reader.execute_batch("COMMIT").unwrap(); +} + +#[test] +fn a_key_kept_by_a_sign_out_is_exported_and_then_forgotten_without_a_trace() { + // The flow of "Forget this device's identity" after a sign-out: the key is + // still there, unbound; the UI exports it, then deletes it. The export is + // what `voelin_key` and `to_pkcs8` give, and it restores the key. + let scratch = Scratch::new("export-forget"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + store.put_voelin_key(&key()).unwrap(); + store.put_account_record(&AccountRecord { bound_existing_key: false, ..record() }).unwrap(); + store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + let uid = key().uid(); + let stored = store.get(KIND_VOELIN, &uid.to_base32()).unwrap().unwrap(); + let text = key_text(&stored.json, "pkcs8"); + + let exported = store.voelin_key(&uid).unwrap().expect("the key is there").to_pkcs8().unwrap(); + assert!(RawFiles::read(&scratch).holds(&text)); + assert!(store.remove(KIND_VOELIN, &uid.to_base32()).unwrap()); + assert!(store.voelin_key(&uid).unwrap().is_none()); + let after = RawFiles::read(&scratch); + assert_eq!(after.where_is(&text), (false, false), "nothing of the key is left"); + assert!(after.wal.is_empty(), "the log is truncated"); + + // The export brings the same key back. + let restored = IdentityKey::from_pkcs8(&exported).unwrap(); + assert_eq!(restored.uid(), uid); + assert_eq!(restored.sign(b"the exported key"), key().sign(b"the exported key")); + store.put_voelin_key(&restored).unwrap(); + assert_eq!(store.get(KIND_VOELIN, &uid.to_base32()).unwrap().unwrap(), stored); +} + +// ------------------------------------------ releasing the device key from its account +// +// `AccountClient::release` asks the service to release the key and then runs the +// local sign-out with `Auto` (protocol 13.6, "Releasing this device's key"), so +// the store's part is the sign-out of the tests above, and the key has to be +// usable for another account afterwards. + +#[test] +fn the_local_half_of_a_release_keeps_the_key_and_it_serves_another_account() { + let Install { store, .. } = signed_in_install(false); + let uid = key().uid().to_base32(); + let before = store.get(KIND_VOELIN, &uid).unwrap().unwrap(); + let signature = key().sign(b"the same key, before and after the release"); + + // The service released the key; the device finishes with a local sign-out. + let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + assert!(done.unbound.contains(&device_key_info()), "{done:?}"); + assert!(!done.removed.contains(&device_key_info()), "{done:?}"); + assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before, "byte for byte"); + assert_eq!(store.account_record().unwrap(), None); + + // The key is registered with no account and signs up for another one: its + // record names the same key, and a copy of the new account's material is + // bound to it. + let other_id = AccountId::from_bytes([42; 16]); + let other = AccountRecord { account_id: other_id, login: "bob".into(), ..record() }; + store.put_account_record(&other).unwrap(); + assert_eq!(store.account_record().unwrap(), Some(other.clone())); + let other_binding = AccountBinding { account: account_uid(&issuer(), &other_id), ..binding() }; + let other_copy = fresh_teamspeak(other_binding); + store.put(&other_copy).unwrap(); + + // Signing out of the new account keeps the key again, and the copy goes. + let done = store.sign_out(&other_binding.account, DeviceKeyChoice::Auto).unwrap(); + assert!(done.unbound.contains(&device_key_info()), "{done:?}"); + assert!(done.removed.contains(&info_of(&other_copy)), "{done:?}"); + let kept = store.voelin_key(&key().uid()).unwrap().expect("the key stays"); + assert_eq!(kept.sign(b"the same key, before and after the release"), signature); + assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before, "byte for byte"); +} + +#[test] +fn a_release_whose_local_half_was_cut_short_is_finished_by_a_sign_out() { + // The service released the device and the call was dropped before the local + // sign-out took the slot: the record and the copies are still here, and the + // key is still the record's device key. A sign-out with `Auto` finishes it + // and keeps the key; running it again finds nothing to do. + let Install { store, synced, device_only, .. } = signed_in_install(true); + let uid = key().uid().to_base32(); + let before = store.get(KIND_VOELIN, &uid).unwrap().unwrap(); + + let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + assert!(done.removed.contains(&info_of(&synced)), "{done:?}"); + assert!(done.unbound.contains(&info_of(&device_only.clone().with_binding(None))), "{done:?}"); + assert_eq!(store.account_record().unwrap(), None); + assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before); + assert_eq!( + store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(), + SignOut::default() + ); +} + // -------------------------------------- the device key is never a synced copy // // `KeyStore::sign_out` deletes everything bound with `synced = true` in its @@ -1798,15 +2098,15 @@ fn a_synced_binding_on_the_device_key_is_refused_with_a_precise_error() { assert_eq!(store.list().unwrap().iter().filter(|i| i.binding.is_some()).count(), 0); // A binding that is not synced is a device-only secret: accepted, and a - // sign-out unbinds it and keeps it (or deletes it, as the record says). + // sign-out unbinds it and keeps it. let device_only = AccountBinding { synced: false, ..binding() }; store.put(&IdentityBlob::voelin(&key()).unwrap().with_binding(device_only)).unwrap(); store.put(&before).unwrap(); - // So the sign-out still does what the record says with the key. + // So the sign-out keeps the key, whether it predates the account or not. let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); - assert_eq!(done.unbound.contains(&device_key_info()), bound_existing_key, "{done:?}"); - assert_eq!(store.voelin_key(&key().uid()).unwrap().is_some(), bound_existing_key); + assert!(done.unbound.contains(&device_key_info()), "{done:?}"); + assert!(store.voelin_key(&key().uid()).unwrap().is_some()); } } diff --git a/crates/voelin-store/tests/support/mod.rs b/crates/voelin-store/tests/support/mod.rs new file mode 100644 index 0000000..4284422 --- /dev/null +++ b/crates/voelin-store/tests/support/mod.rs @@ -0,0 +1,87 @@ +//! Helpers the integration tests of this crate share. + +// Each integration test crate of this directory uses some of these helpers. +#![allow(dead_code)] + +use std::fmt::{self, Write as _}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; + +use tracing::field::{Field, Visit}; +use tracing::level_filters::LevelFilter; +use tracing::span::{Attributes, Id, Record}; +use tracing::{Event, Metadata, Subscriber}; + +/// A subscriber that keeps every event and span it sees as one line of text +/// each: level, target and every field with its `Debug` text, as a log line +/// would show them. +struct Capture { + lines: Arc>>, + spans: AtomicU64, +} + +impl Capture { + fn push(&self, line: String) { + self.lines.lock().unwrap_or_else(PoisonError::into_inner).push(line); + } +} + +/// The fields of an event or a span as ` name=value` text. +struct Fields<'a>(&'a mut String); + +impl Visit for Fields<'_> { + fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) { + let _ = write!(self.0, " {}={value:?}", field.name()); + } +} + +impl Subscriber for Capture { + fn enabled(&self, _: &Metadata<'_>) -> bool { + true + } + + fn max_level_hint(&self) -> Option { + Some(LevelFilter::TRACE) + } + + fn new_span(&self, attributes: &Attributes<'_>) -> Id { + let mut line = format!("span {}", attributes.metadata().name()); + attributes.record(&mut Fields(&mut line)); + self.push(line); + Id::from_u64(self.spans.fetch_add(1, Ordering::Relaxed) + 1) + } + + fn record(&self, _: &Id, values: &Record<'_>) { + let mut line = String::from("span record"); + values.record(&mut Fields(&mut line)); + self.push(line); + } + + fn record_follows_from(&self, _: &Id, _: &Id) {} + + fn event(&self, event: &Event<'_>) { + let metadata = event.metadata(); + let mut line = format!("{} {}:", metadata.level(), metadata.target()); + event.record(&mut Fields(&mut line)); + self.push(line); + } + + fn enter(&self, _: &Id) {} + + fn exit(&self, _: &Id) {} +} + +/// Run `f` on this thread with a subscriber that takes in everything logged at +/// TRACE and above, and return what `f` returned with the lines logged. +pub fn at_trace(f: impl FnOnce() -> R) -> (R, Vec) { + let lines = Arc::new(Mutex::new(Vec::new())); + let subscriber = Capture { lines: Arc::clone(&lines), spans: AtomicU64::new(0) }; + let out = tracing::subscriber::with_default(subscriber, f); + let lines = std::mem::take(&mut *lines.lock().unwrap_or_else(PoisonError::into_inner)); + (out, lines) +} + +/// How many of the lines say that a checkpoint was blocked. +pub fn blocked_checkpoints(lines: &[String]) -> usize { + lines.iter().filter(|line| line.contains("another connection blocked the checkpoint")).count() +} diff --git a/crates/voelin-ui-vm/Cargo.toml b/crates/voelin-ui-vm/Cargo.toml index f06af6c..b34df35 100644 --- a/crates/voelin-ui-vm/Cargo.toml +++ b/crates/voelin-ui-vm/Cargo.toml @@ -16,24 +16,26 @@ path = "src/lib.rs" # must show neither. The front ends convert these types (docs/ui.md). [dependencies] chrono = { version = "0.4.45", default-features = false, features = ["clock"] } -# Picture sizes (the header of a file); PNG and JPEG are listed as the -# front end's toolkit used to bring them. +# Whether a picture file decodes, and its size; PNG and JPEG are listed as +# the front end's toolkit used to bring them. image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp", "ico"] } serde = { version = "1", features = ["derive"] } # JSON values of the settings and the gateway's configuration keys. serde_json = "1" +# Whether an SVG document is XML with an svg root (the vector renderers read +# it with this parser too). +roxmltree = { version = "0.21", default-features = false, features = ["std"] } # The Twemoji archive's blocks (raw deflate). miniz_oxide = "0.8" # Grapheme clusters for emoji in chat text. unicode-segmentation = "1.13" +# The sample pictures of the demo data (VOELIN_DEMO_UI) and the tests. +png = "0.18" voelin-audio = { path = "../voelin-audio", default-features = false } voelin-core = { path = "../voelin-core", default-features = false, features = ["media"] } voelin-gateway-proto = { path = "../voelin-gateway-proto" } voelin-model = { workspace = true } voelin-store = { path = "../voelin-store" } -[dev-dependencies] -png = "0.18" - [lints] workspace = true diff --git a/crates/voelin-ui-vm/src/bbcode.rs b/crates/voelin-ui-vm/src/bbcode.rs index 1b8f238..24a67d3 100644 --- a/crates/voelin-ui-vm/src/bbcode.rs +++ b/crates/voelin-ui-vm/src/bbcode.rs @@ -36,9 +36,13 @@ pub const MAX_RUNS: usize = 1500; /// How a span of text looks. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Style { + /// Bold (`[b]`). pub bold: bool, + /// Italic (`[i]`). pub italic: bool, + /// Underlined (`[u]`). pub underline: bool, + /// Struck through (`[s]`). pub strike: bool, /// Code: on a background. pub code: bool, @@ -51,12 +55,16 @@ pub struct Style { /// A piece of a block. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Span { + /// Text with one style. Text { + /// The characters. text: String, + /// How they look. style: Style, }, /// A picture at an address (`[img]…[/img]`). Image { + /// Where the picture is. url: String, }, } @@ -68,7 +76,10 @@ pub enum BlockKind { Text, /// A line of a quote; the first names who said it (`[quote=Name]`), when /// the quote does. - Quote { author: String }, + Quote { + /// Who said it, empty when the quote does not say. + author: String, + }, /// Code: all its lines in one span. Code, /// An item of a list. @@ -80,13 +91,16 @@ pub enum BlockKind { /// A line, a quote's line, code, a list item or a rule. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Block { + /// What the block is. pub kind: BlockKind, + /// Its pieces, left to right. pub spans: Vec, } /// A message's text: its blocks, top to bottom. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Doc { + /// The lines, quotes, code and rules in order. pub blocks: Vec, } diff --git a/crates/voelin-ui-vm/src/bridge.rs b/crates/voelin-ui-vm/src/bridge.rs index 6dcdf21..f027f46 100644 --- a/crates/voelin-ui-vm/src/bridge.rs +++ b/crates/voelin-ui-vm/src/bridge.rs @@ -5,6 +5,10 @@ //! (`bind/convert.rs`), the GPUI client will render them as they are. //! `MytsBadge` and `MytsForm` (account screens without a data source in this //! build) stay in Slint. +//! +//! Every field is documented here: the comments of `bridge.slint` were +//! carried over, and the fields that had none were described from the code +//! that fills them. use std::sync::Arc; @@ -14,13 +18,17 @@ use crate::image::ImageRef; /// A row or form of the bridge (the plain counterpart of the Slint struct `ServerItem`). #[derive(Clone, Debug, Default, PartialEq)] pub struct ServerItem { + /// The bookmark's id, which is the session's too. pub id: i32, + /// The server's name. pub name: Arc, + /// The address the bookmark connects to. pub address: Arc, /// "offline", "connecting", "observing" or "connected" pub status: Arc, /// Avatar of a server without an icon. pub initials: Arc, + /// The colour of its avatar. pub tint: Rgb, /// The server's icon, empty without one. pub icon: ImageRef, @@ -39,50 +47,70 @@ pub struct ServerItem { /// A row or form of the bridge (the plain counterpart of the Slint struct `TreeItem`). #[derive(Clone, Debug, Default, PartialEq)] pub struct TreeItem { + /// A channel; else a client. pub is_channel: bool, /// A TeamSpeak spacer channel, its name without the `[cspacer1]` part: /// 0 none, 1 left, 2 centred, 3 right, 4 a line (the name repeats its /// pattern across the row). pub spacer: i32, + /// How far the row is indented: its level in the tree. pub depth: i32, + /// The channel's or the client's id on the server. pub id: i32, + /// A channel's name (a spacer's text, without its `[cspacer1]` part) or a client's nickname. pub name: Arc, + /// Our own channel (channels). pub own: bool, + /// The client is speaking. pub talking: bool, + /// The client's microphone is muted. pub muted: bool, + /// The client's speakers are muted. pub sound_off: bool, + /// The client is away. pub away: bool, + /// The client streams. pub streaming: bool, + /// The channel needs a password. pub locked: bool, + /// The channel's contents are hidden. pub collapsed: bool, /// Local playback of this client: muted, or its volume in percent /// (100 = unchanged). pub local_muted: bool, + /// Its local volume in percent; 100 is unchanged. pub local_volume: i32, /// Our own client. pub myself: bool, /// Avatar of a client. pub initials: Arc, + /// The colour of the client's avatar. pub tint: Rgb, /// The client's avatar picture, empty without one. pub avatar: ImageRef, /// Channels: clients inside, and the limit (-1: none). pub members: i32, + /// The channel's limit of clients; -1: none. pub max_members: i32, /// Leading channel icon or trailing client icons, empty where absent: a channel's /// icon; a client's server group icons, its channel group's and its own, /// in that order (the first three). pub icon: ImageRef, + /// The second icon, as `icon`. pub icon_2: ImageRef, + /// The third icon, as `icon`. pub icon_3: ImageRef, /// A client's badges (myTeamSpeak), the first three in its order, empty /// where absent; shown after the name. pub badge: ImageRef, + /// The second badge, as `badge`. pub badge_2: ImageRef, + /// The third badge, as `badge`. pub badge_3: ImageRef, /// A channel's banner picture (TeamSpeak 6), drawn behind the row; /// Wire sizing metadata; compact decorative backgrounds always cover. pub banner: ImageRef, + /// How the server sizes the banner: 0 as it is, 1 stretched, 2 scaled keeping the aspect ratio. pub banner_mode: i32, } @@ -90,16 +118,27 @@ pub struct TreeItem { /// channel view (our channel). #[derive(Clone, Debug, Default, PartialEq)] pub struct MemberItem { + /// The client's id on the server. pub id: i32, + /// Its nickname. pub name: Arc, + /// The initials of its avatar. pub initials: Arc, + /// The colour of its avatar. pub tint: Rgb, + /// Its avatar picture, empty without one. pub avatar: ImageRef, + /// It is speaking. pub talking: bool, + /// Its microphone is muted. pub muted: bool, + /// Its speakers are muted. pub sound_off: bool, + /// It is away. pub away: bool, + /// It streams. pub streaming: bool, + /// Our own client. pub myself: bool, /// "Speaking", "Streaming", "Away", ... pub status: Arc, @@ -108,24 +147,31 @@ pub struct MemberItem { /// The section the row is in (a server group, "In Voice", /// "Streaming"), and the group's icon. pub group: Arc, + /// The section's icon, empty where it has none. pub group_icon: ImageRef, /// The first row of its section draws the heading, with the number of /// rows in the section. pub first_in_group: bool, + /// The number of rows in its section. pub group_count: i32, /// Badges: a crown for the server's admin groups. pub admin: bool, /// A moderator group's name, shown as a role next to the name. pub role: Arc, + /// It is a priority speaker. pub priority: bool, + /// It is a channel commander. pub commander: bool, + /// It is recording the conversation. pub recording: bool, /// Its channel needs more talk power than it has (and it is no /// talker): it cannot speak. pub cannot_talk: bool, /// myTeamSpeak badges, as in `TreeItem`. pub badge: ImageRef, + /// The second badge. pub badge_2: ImageRef, + /// The third badge. pub badge_3: ImageRef, } @@ -133,8 +179,11 @@ pub struct MemberItem { /// the app does not know; its picture is empty until it is downloaded. #[derive(Clone, Debug, Default, PartialEq)] pub struct BadgeItem { + /// The badge's name. pub name: Arc, + /// What the badge says of its holder. pub description: Arc, + /// The badge's picture, empty until it is downloaded. pub icon: ImageRef, } @@ -142,24 +191,37 @@ pub struct BadgeItem { /// can be done with them. #[derive(Clone, Debug, Default, PartialEq)] pub struct MemberCard { + /// The card is shown. pub open: bool, + /// The client's id on the server. pub id: i32, + /// Its nickname. pub name: Arc, + /// The initials of its avatar. pub initials: Arc, + /// The colour of its avatar. pub tint: Rgb, + /// Its avatar picture, empty without one. pub avatar: ImageRef, + /// What it does: "Speaking", "Streaming", "Away", ... (as `MemberItem::status`). pub status: Arc, + /// The description the client set. pub description: Arc, /// Server groups, one per line. pub groups: Vec>, /// The badges the client shows (at most three, in its order). pub badges: Vec, + /// The country the server reports for it, empty if none. pub country: Arc, + /// Its talk power. pub talk_power: i32, + /// It is one of our friends. pub friend: bool, + /// It is a blocked contact. pub blocked: bool, /// Local playback, in percent. pub volume: f32, + /// Its voice is muted for us (local playback). pub muted: bool, /// The client has a unique id, so contacts and private chats work. pub known: bool, @@ -176,15 +238,19 @@ pub struct ChatTab { pub name: Arc, /// 0 = server chat, 1 = channel chat, 2 = private chat pub kind: i32, + /// A channel chat's channel id; 0 for the others. pub id: i32, + /// How many of its messages are unread. pub unread: i32, /// The channel's topic (channel chats). pub topic: Arc, /// The last message ("Mira: the banner I promised") and its time. pub last: Arc, + /// The time of the last message. pub time: Arc, /// The channel's banner picture behind the chat's header (as TreeItem). pub banner: ImageRef, + /// As `TreeItem::banner_mode`. pub banner_mode: i32, } @@ -193,27 +259,36 @@ pub struct ChatTab { /// characters). #[derive(Clone, Debug, Default, PartialEq)] pub struct TextRun { + /// The characters of the run. pub text: Arc, + /// The Twemoji key if the run is an emoji, else empty. pub emoji: Arc, + /// In bold. pub bold: bool, + /// In italics. pub italic: bool, + /// Underlined. pub underline: bool, + /// Struck through. pub strike: bool, /// Code: on a background. pub code: bool, /// The author's colour, made readable on each theme; transparent: the /// text's own. pub ink_dark: Option, + /// The author's colour made readable on the light theme (`ink_dark`: the dark one). pub ink_light: Option, /// Where it links to ("": nowhere), and whether its text shows something /// else (a page's name, another address): asked about before it opens. pub link: Arc, + /// Its text shows something else than the address it links to. pub masked: bool, } /// A block of a chat line (`vm::bbcode`): its runs, and what it is. #[derive(Clone, Debug, Default, PartialEq)] pub struct TextBlock { + /// The pieces of the block, in order. pub runs: Vec, /// 0 = a line, 1 = a quote's line, 2 = a line of code, 3 = a list item, /// 4 = a rule (no runs) @@ -227,7 +302,9 @@ pub struct TextBlock { pub struct ReactionItem { /// The Twemoji key of the first emoji in `text` ("1f389"), for the image. pub key: Arc, + /// The emoji, as text. pub text: Arc, + /// How many reacted with it. pub count: i32, /// We reacted with it. pub me: bool, @@ -236,6 +313,7 @@ pub struct ReactionItem { /// A file linked in a message (`ChatMessage::file_refs`). #[derive(Clone, Debug, Default, PartialEq)] pub struct FileItem { + /// The file's name. pub name: Arc, /// "2.4 MB", or what the transfer is doing. pub detail: Arc, @@ -257,26 +335,35 @@ pub struct ChatLine { /// A handle for this message in its chat, stable while the chat is open /// (the engine's ids do not fit a Slint int). pub key: i32, + /// The author's name. pub author: Arc, /// The text without formatting, a line per block (shown as it is when /// the message has neither formatting nor emoji, and read out). pub text: Arc, + /// When it was sent, as shown ("11:42"). pub time: Arc, /// The text in blocks of styled runs; only filled when it has /// formatting or emoji (`rich`). pub blocks: Vec, + /// The blocks are shown, not `text`. pub rich: bool, /// Only one to three emoji: shown large. pub jumbo: bool, /// Same author as the line before, shortly after: no header. pub continued: bool, + /// The initials of the author's avatar. pub initials: Arc, + /// The colour of the author's avatar. pub tint: Rgb, + /// The author's avatar picture, empty without one. pub avatar: ImageRef, /// From a blocked contact. pub blocked: bool, + /// The message is pinned. pub pinned: bool, + /// The reactions to it. pub reactions: Vec, + /// The files it links to. pub files: Vec, /// The gateway knows this message: it can be pinned, reacted to and /// made into a topic. @@ -295,6 +382,7 @@ pub struct ChatLine { /// A pinned message in the pins drawer. #[derive(Clone, Debug, Default, PartialEq)] pub struct PinItem { + /// The pinned message. pub line: ChatLine, /// "pinned by Nova · 12:04" pub by: Arc, @@ -303,14 +391,19 @@ pub struct PinItem { /// A gateway topic (thread). #[derive(Clone, Debug, Default, PartialEq)] pub struct TopicItem { + /// The topic's id on the gateway. pub id: i32, + /// Its title. pub title: Arc, + /// Who started it. pub creator: Arc, /// "12 messages · by Nova" pub detail: Arc, /// "Last active 3 min ago", and whether that was within the hour. pub activity: Arc, + /// It was active within the hour. pub recent: bool, + /// It is archived. pub archived: bool, } @@ -318,17 +411,24 @@ pub struct TopicItem { /// Connect goes. #[derive(Clone, Debug, Default, PartialEq)] pub struct BookmarkForm { + /// The bookmark's id; -1: a new one. pub id: i32, + /// The name, empty to use the address. pub name: Arc, + /// The server's address. pub address: Arc, + /// The nickname to connect with. pub nickname: Arc, + /// The server's password. pub server_password: Arc, /// The server has voice: no Connect. pub connected: bool, /// From a link, not stored with the server: the channel to join (a - /// path, or /), its password and a privilege key. + /// path, or `/`), its password and a privilege key. pub channel: Arc, + /// The password of the channel to join. pub channel_password: Arc, + /// A privilege key to use on joining. pub token: Arc, } @@ -337,8 +437,11 @@ pub struct BookmarkForm { /// being looked up (it started before we joined, or in another channel). #[derive(Clone, Debug, Default, PartialEq)] pub struct StreamItem { + /// The stream's id; empty while it is looked up. pub id: Arc, + /// The stream's title. pub name: Arc, + /// The streamer's name. pub streamer: Arc, /// The streamer's channel when it is not ours; empty in ours. pub channel: Arc, @@ -347,13 +450,17 @@ pub struct StreamItem { /// The streamer's avatar, as the members show it: their picture, or /// their initials on their colour (also the card's picture's colour). pub initials: Arc, + /// The colour of the streamer's avatar. pub tint: Rgb, + /// The streamer's picture, empty without one. pub avatar: ImageRef, /// How many watch it (the gateway's directory; 0 unknown). pub viewers: i32, + /// The stream has sound. pub audio: bool, /// "Screen", "Window", "Camera"; and the announced bitrate ("8 Mbit/s"). pub kind: Arc, + /// The announced bitrate, "8 Mbit/s". pub bitrate: Arc, /// Shown in the viewer. pub watching: bool, @@ -366,9 +473,13 @@ pub struct StreamItem { /// A viewer of our stream. state: "requested", "connecting" or "connected". #[derive(Clone, Debug, Default, PartialEq)] pub struct ViewerItem { + /// The viewer's client id. pub client: i32, + /// The viewer's name. pub name: Arc, + /// "requested", "connecting" or "connected". pub state: Arc, + /// The message of its request to watch. pub message: Arc, /// Their avatar picture, empty without one. pub avatar: ImageRef, @@ -377,14 +488,18 @@ pub struct ViewerItem { /// A capture source for the share dialog. #[derive(Clone, Debug, Default, PartialEq)] pub struct SourceItem { + /// The source's name. pub name: Arc, + /// The line under the name. pub detail: Arc, } /// A row or form of the bridge (the plain counterpart of the Slint struct `ShareForm`). #[derive(Clone, Debug, Default, PartialEq)] pub struct ShareForm { + /// Index into the sources offered (`SourceItem`). pub source: i32, + /// The stream's title. pub name: Arc, /// Index into the frame rate choices (15, 30, 60, 120, 144, 240, 320). pub fps_index: i32, @@ -396,7 +511,9 @@ pub struct ShareForm { /// Video bitrate in kbit/s as typed; a choice fills it in. Empty with /// Auto: from the size and frame rate shared, up to 60 Mbit/s. pub bitrate: Arc, + /// The stream carries sound too. pub audio: bool, + /// Viewers are let in without being asked. pub auto_accept: bool, } @@ -405,15 +522,19 @@ pub struct ShareForm { pub struct AudioForm { /// 0 = system default, then the devices. pub input_index: i32, + /// As `input_index`, for the output device. pub output_index: i32, /// 0 = push-to-talk, 1 = voice activation, 2 = continuous. pub transmit: i32, /// dBFS. pub vad_threshold: f32, + /// Echo cancellation is on. pub echo_cancellation: bool, + /// Noise suppression is on. pub noise_suppression: bool, /// 0 = low ... 3 = very high. pub noise_level: i32, + /// Automatic gain control is on. pub auto_gain: bool, /// dB. pub input_gain: f32, @@ -426,9 +547,13 @@ pub struct AudioForm { /// Local playback settings of one client. volume in percent. #[derive(Clone, Debug, Default, PartialEq)] pub struct ClientAudio { + /// The client's id on the server. pub id: i32, + /// Its nickname. pub name: Arc, + /// Its playback volume in percent. pub volume: f32, + /// Its playback is muted. pub muted: bool, /// The client streams: the dialog offers to watch it. pub streaming: bool, @@ -439,24 +564,34 @@ pub struct ClientAudio { pub struct AppearanceForm { /// "dark", "light" or "system" pub theme: Arc, + /// The factor the text size is scaled by; 1 is normal. pub font_scale: f32, /// Pixels. pub narrow_breakpoint: f32, + /// Memory for decoded pictures in MB; 0 keeps none. pub image_cache_mb: f32, } /// A contact (friend, blocked or neutral) and where they are now. #[derive(Clone, Debug, Default, PartialEq)] pub struct ContactItem { + /// The contact's unique id. pub uid: Arc, + /// The contact's name. pub name: Arc, + /// The initials of its avatar. pub initials: Arc, + /// The colour of its avatar. pub tint: Rgb, + /// Its avatar picture, empty without one. pub avatar: ImageRef, /// "friend", "blocked" or "neutral" pub relation: Arc, + /// A session sees them. pub online: bool, + /// They are away. pub away: bool, + /// They stream. pub streaming: bool, /// What they do: "In Chill Zone", "Streaming", "Away: brb", "Offline". pub status: Arc, @@ -465,9 +600,11 @@ pub struct ContactItem { pub place: Arc, /// "12m ago": online since (this run), else when last seen. pub when: Arc, + /// Our note about them. pub note: Arc, /// Local playback in percent. pub volume: f32, + /// Their voice is muted for us. pub muted: bool, /// "Contact since 14 Jan 2022". pub since: Arc, @@ -475,6 +612,7 @@ pub struct ContactItem { pub spots: Vec>, /// A voice connection sees them: they can be messaged, poked, joined. pub reachable: bool, + /// They are the contact the friends page shows in full. pub selected: bool, } @@ -483,13 +621,21 @@ pub struct ContactItem { pub struct LiveItem { /// The session (bookmark id) and the stream (directory or stream id). pub session: i32, + /// The stream's id in the directory or on the voice connection. pub id: Arc, + /// The stream's title. pub title: Arc, + /// The streamer's name. pub streamer: Arc, + /// The initials of the streamer's avatar. pub initials: Arc, + /// The colour of the streamer's avatar. pub tint: Rgb, + /// The streamer's picture, empty without one. pub avatar: ImageRef, + /// The server's name. pub server: Arc, + /// The channel's name. pub channel: Arc, /// 0: unknown. pub viewers: i32, @@ -508,6 +654,7 @@ pub struct ConversationItem { pub key: i32, /// 0 server chat, 1 channel chat, 2 private chat, 3 offline message. pub kind: i32, + /// The chat's title: the channel's or the person's name, or the server's. pub title: Arc, /// The server's name. pub server: Arc, @@ -517,27 +664,40 @@ pub struct ConversationItem { pub time: Arc, /// "10m ago". pub ago: Arc, + /// How many of its messages are unread. pub unread: i32, + /// The initials of its avatar. pub initials: Arc, + /// The colour of its avatar. pub tint: Rgb, + /// Its picture, empty without one. pub avatar: ImageRef, + /// The other person is online (private chats). pub online: bool, + /// It is the conversation that is open. pub selected: bool, } /// A notification of the bell. #[derive(Clone, Debug, Default, PartialEq)] pub struct NoticeItem { + /// What the rows call the notice. pub key: i32, /// "mention", "poke", "message", "event", "friend" pub kind: Arc, + /// The headline. pub title: Arc, + /// The line under it. pub body: Arc, /// "3 min ago" pub time: Arc, + /// It was not opened or marked read. pub unread: bool, + /// The initials of the avatar it shows. pub initials: Arc, + /// The colour of that avatar. pub tint: Rgb, + /// The avatar picture it shows, empty without one. pub avatar: ImageRef, } @@ -546,10 +706,15 @@ pub struct NoticeItem { pub struct SearchItem { /// "server", "channel", "person", "contact", "setting" pub kind: Arc, + /// What the result is called. pub title: Arc, + /// The line under it. pub subtitle: Arc, + /// The initials of its avatar. pub initials: Arc, + /// The colour of its avatar. pub tint: Rgb, + /// Its picture, empty without one. pub avatar: ImageRef, /// The first result of a group names it ("Servers", "People", ...). pub header: Arc, @@ -560,12 +725,17 @@ pub struct SearchItem { pub struct HappeningItem { /// "event", "stream", "news" pub kind: Arc, + /// The event's or stream's title, or the news' headline. pub title: Arc, + /// The line under it, with the server's name. pub subtitle: Arc, /// "Sat 26 Apr · 19:00" pub when: Arc, + /// The session (bookmark id) it is on. pub session: i32, + /// The event's id on the gateway; 0: news. pub id: i32, + /// Its stream is live. pub live: bool, } @@ -574,28 +744,39 @@ pub struct HappeningItem { pub struct ResumeItem { /// There is one: its server is still a bookmark at the same address. pub shown: bool, + /// The server's bookmark id. pub server_id: i32, + /// The server's name. pub server: Arc, + /// The initials of its avatar. pub initials: Arc, + /// The colour of its avatar. pub tint: Rgb, + /// The server's icon, empty without one. pub icon: ImageRef, /// The channel's name as the tree shows it. pub channel: Arc, /// Voice is connected there: the button shows the server; else it /// connects into the channel. pub open: bool, + /// The server is connecting now. pub connecting: bool, } /// A scheduled event of a server's gateway. #[derive(Clone, Debug, Default, PartialEq)] pub struct EventItem { + /// The event's id on the gateway. pub id: i32, + /// The event's title. pub title: Arc, + /// Its description. pub description: Arc, /// The date block: "SAT", "26", "APR". pub weekday: Arc, + /// The day of the month, in the date block. pub day: Arc, + /// The month, abbreviated, in the date block. pub month: Arc, /// "Sat 26 Apr, 19:00 – 21:00" pub when: Arc, @@ -603,12 +784,17 @@ pub struct EventItem { pub place: Arc, /// A scheduled stream: "Exploring the Lands Between · Elden Ring". pub stream: Arc, + /// Its stream is live. pub live: bool, + /// How many go. pub going: i32, + /// How many may go. pub maybe: i32, + /// How many do not go. pub not_going: i32, /// "going", "maybe", "not_going" or "". pub rsvp: Arc, + /// Who made it. pub creator: Arc, /// We may edit and delete it (ours, or we moderate). pub editable: bool, @@ -616,6 +802,7 @@ pub struct EventItem { pub soon: Arc, /// "Nova (going)", ...; filled once the event was opened. pub attendees: Vec>, + /// Its details are open. pub expanded: bool, } @@ -624,7 +811,9 @@ pub struct EventItem { pub struct EventForm { /// -1: a new event. pub id: i32, + /// The event's title. pub title: Arc, + /// Its description. pub description: Arc, /// "2026-10-04 19:00", local time. pub start: Arc, @@ -632,8 +821,11 @@ pub struct EventForm { pub end: Arc, /// Index into `event-channels` (0: server-wide). pub channel: i32, + /// It is a scheduled stream. pub stream: bool, + /// The scheduled stream's title. pub stream_title: Arc, + /// The game or category it shows. pub game: Arc, } @@ -642,26 +834,40 @@ pub struct EventForm { pub struct OfflineForm { /// The peer's unique id and name. pub uid: Arc, + /// The recipient's name. pub to: Arc, + /// The message's subject. pub subject: Arc, + /// The message's text. pub text: Arc, } /// The open direct message: who, and what can be done. #[derive(Clone, Debug, Default, PartialEq)] pub struct DmPeer { + /// A conversation is open. pub open: bool, + /// The peer's unique id. pub uid: Arc, + /// The peer's name. pub name: Arc, + /// The initials of their avatar. pub initials: Arc, + /// The colour of their avatar. pub tint: Rgb, + /// Their avatar picture, empty without one. pub avatar: ImageRef, + /// They are online on one of our servers. pub online: bool, /// "Online · Nightfall Guild · Chill Zone", "Offline · last seen 2 h ago". pub status: Arc, + /// The description they set. pub description: Arc, + /// Their server groups. pub groups: Vec>, + /// Our note about them. pub note: Arc, + /// "Contact since 14 Jan 2022"; empty for no contact. pub since: Arc, /// Where they are now, or where they were last seen. pub servers: Vec>, @@ -669,11 +875,17 @@ pub struct DmPeer { /// first (at most six; `media-more` counts the others), and the other /// files: name, "2.4 MB · Today at 11:36", picture. pub media: Vec, + /// How many pictures there are besides the ones in `media`. pub media_more: i32, + /// The other files linked in the conversation. pub files: Vec, + /// They are a friend. pub friend: bool, + /// They are blocked. pub blocked: bool, + /// Their local volume in percent. pub volume: f32, + /// Their voice is muted for us. pub muted: bool, /// Messages can be sent now (a voice connection that sees them). pub can_send: bool, @@ -687,19 +899,26 @@ pub struct DmPeer { pub stored: bool, /// An offline message is shown instead of the conversation. pub mail: bool, + /// The open offline message's subject. pub mail_subject: Arc, + /// Its text, empty until the server has sent it. pub mail_text: Arc, + /// When it was sent. pub mail_time: Arc, } /// An identity (Profiles page); never its key. #[derive(Clone, Debug, Default, PartialEq)] pub struct IdentityItem { + /// The identity's id in the store. pub id: i32, + /// The identity's name. pub name: Arc, /// Unique ids on TeamSpeak 3 and TeamSpeak 6 servers. pub uid: Arc, + /// Its unique id on TeamSpeak 6 servers. pub uid6: Arc, + /// The security level of its key. pub level: i32, /// The store's default: servers see us as this one unless a bookmark /// names another. @@ -708,6 +927,7 @@ pub struct IdentityItem { pub origin: Arc, /// Raising its level: the level aimed at and the best one reached (0: no). pub improving: i32, + /// The best level reached so far while it is raised. pub reached: i32, /// The bookmarks that use it. pub used_by: Arc, @@ -716,19 +936,26 @@ pub struct IdentityItem { /// An identity found in another client's files (import). #[derive(Clone, Debug, Default, PartialEq)] pub struct FoundIdentity { + /// The identity's name. pub name: Arc, + /// Its unique id. pub uid: Arc, + /// The security level of its key. pub level: i32, + /// The other client's file it was found in. pub source: Arc, /// Already in our identities. pub known: bool, + /// It is chosen for the import. pub picked: bool, } /// A bookmark and the identity it connects with (Profiles page). #[derive(Clone, Debug, Default, PartialEq)] pub struct BookmarkIdentity { + /// The bookmark's id. pub id: i32, + /// The bookmark's name. pub name: Arc, /// Index into `identity-names` (0: the default identity). pub identity: i32, @@ -747,7 +974,9 @@ pub struct VideoForm { pub fps: Arc, /// auto, vp8, vp9, h264, av1. pub codec: i32, + /// Hardware video encoders are used where there are some. pub hardware: bool, + /// The camera picture is mirrored. pub mirror: bool, /// everyone, friends, channel, nobody. pub permissions: i32, @@ -768,7 +997,9 @@ pub struct LayerItem { pub fps: Arc, /// kbit/s. pub bitrate: Arc, + /// kbit/s a viewer needs for the layer. pub min_bitrate: Arc, + /// kbit/s the layer may use at most, not below `bitrate`; empty: no limit. pub max_bitrate: Arc, } @@ -777,34 +1008,47 @@ pub struct LayerItem { pub struct AudioSourceItem { /// "desktop", "app", "window", "microphone", "synthetic" pub kind: Arc, + /// The source's name. pub name: Arc, + /// The line under the name. pub detail: Arc, /// Percent. pub gain: f32, + /// It is muted in the mix. pub muted: bool, } /// Stream defaults (Streaming page). #[derive(Clone, Debug, Default, PartialEq)] pub struct StreamingForm { + /// Frames per second as typed (`stream.fps`). pub fps: Arc, + /// kbit/s as typed (`stream.bitrate_kbps`); "Auto" or empty: from the size and frame rate. pub bitrate: Arc, /// auto, vp8, vp9, h264, av1. pub codec: i32, /// auto, portal, wlroots, x11. pub capture: i32, + /// Seconds the replay buffer keeps, as typed; 0: off. pub replay_seconds: Arc, + /// MiB of the replay buffer kept in memory, as typed. pub replay_memory: Arc, + /// The folder of recordings and clips; empty: the default. pub recording_dir: Arc, } /// Notification kinds: 0 off, 1 in the app, 2 also on the desktop. #[derive(Clone, Debug, Default, PartialEq)] pub struct NotifyForm { + /// How a mention notifies: 0 off, 1 in the app, 2 also on the desktop. pub mentions: i32, + /// How a poke notifies, as `mentions`. pub pokes: i32, + /// How a private message notifies, as `mentions`. pub messages: i32, + /// How an event that starts soon notifies, as `mentions`. pub events: i32, + /// How a friend coming online notifies, as `mentions`. pub friends: i32, } @@ -815,52 +1059,74 @@ pub struct PrivacyForm { pub block_mode: i32, /// everyone, friends, nobody. pub messages: i32, + /// Who may poke us, as `messages`. pub pokes: i32, } /// A server's gateway (Integrations page). #[derive(Clone, Debug, Default, PartialEq)] pub struct GatewayItem { + /// The session (bookmark id) whose gateway it is. pub session: i32, + /// The server's name. pub server: Arc, + /// The gateway's address. pub url: Arc, /// "connected", "connecting", "off" pub status: Arc, + /// The features it offers. pub features: Vec>, + /// We may administer it. pub admin: bool, } /// A gateway configuration key (gateway administration). #[derive(Clone, Debug, Default, PartialEq)] pub struct ConfigItem { + /// The dotted key, "history.retention_days". pub key: Arc, /// JSON. pub value: Arc, + /// Where the value comes from: "set at runtime", "command line", "environment", "file" or + /// "default". pub source: Arc, + /// What the key is for. pub description: Arc, + /// The type of the value: `bool`, `int`, `string`, `int_list`, `string_list` or `rule`. pub kind: Arc, + /// It is read at start only and cannot be set at runtime. pub bootstrap: bool, } /// A gateway permission rule. #[derive(Clone, Debug, Default, PartialEq)] pub struct PermItem { + /// What the rule allows. pub action: Arc, /// "Everyone", "Server groups 6, 7", "Default: server admins". pub rule: Arc, + /// Where the rule comes from, as `ConfigItem::source`. pub source: Arc, + /// Everyone is allowed. pub everyone: bool, + /// The server groups allowed, as a list. pub server_groups: Arc, + /// The channel groups allowed, as a list. pub channel_groups: Arc, } /// A video encoder backend (Integrations page). #[derive(Clone, Debug, Default, PartialEq)] pub struct EncoderItem { + /// The encoder backend's name. pub name: Arc, + /// The API it uses. pub api: Arc, + /// The codec it encodes. pub codec: Arc, + /// It encodes in hardware. pub hardware: bool, + /// It works on this machine. pub ok: bool, /// Why it does not work, or "used first". pub status: Arc, @@ -869,7 +1135,9 @@ pub struct EncoderItem { /// Any registered setting (Advanced page). #[derive(Clone, Debug, Default, PartialEq)] pub struct SettingItem { + /// The setting's key. pub key: Arc, + /// What the setting is for. pub doc: Arc, /// JSON. pub value: Arc, @@ -880,55 +1148,80 @@ pub struct SettingItem { /// A recording or clip of the Stream Studio (Library). #[derive(Clone, Debug, Default, PartialEq)] pub struct RecordingItem { + /// The file's name. pub name: Arc, /// "12.3 MB · 3 Oct 18:04". pub detail: Arc, + /// A clip saved from the replay buffer; else a recording. pub clip: bool, + /// Where the file is. pub path: Arc, } /// Encoders, chat history, cache and logs (Advanced page); numbers as typed. #[derive(Clone, Debug, Default, PartialEq)] pub struct AdvancedForm { + /// `stream.encoder_backend`: auto, software or an encoder's name. pub encoder: Arc, + /// `stream.hardware_acceleration`: hardware encoders where available. pub hardware: bool, /// `stream.decoder_backend`, `stream.hardware_decoding`. pub decoder: Arc, + /// `stream.hardware_decoding`: hardware decoders where available. pub hardware_decoding: bool, + /// `chat.store_history`: keep the chat history on this device. pub store_history: bool, + /// `chat.history_page`: messages per page; 0: all at once. pub history_page: Arc, + /// `chat.dedupe_tolerance_ms`: how far apart two copies of a message may be and count as one. pub dedupe_ms: Arc, + /// `chat.retention_days`: delete stored messages older than this; 0: keep all. pub retention_days: Arc, + /// `cache.max_mb`: the picture cache's size in MiB; 0: no limit. pub cache_mb: Arc, + /// `cache.fetch_images`: download pictures of servers and chats. pub fetch_images: bool, + /// `files.progress_interval_ms`: how often a transfer reports; 0: continuously. pub progress_ms: Arc, /// `ui.image_preview_kb`. pub preview_kb: Arc, + /// A text on where the logs go and how to get more of them. pub logs: Arc, + /// The folder crash reports are kept in; empty if there is none. pub crash_dir: Arc, } /// A row or form of the bridge (the plain counterpart of the Slint struct `AccountForm`). #[derive(Clone, Debug, Default, PartialEq)] pub struct AccountForm { + /// The nickname the current server's bookmark connects with. pub nickname: Arc, + /// The name of the identity the server sees us as. pub identity: Arc, + /// Its unique id on TeamSpeak 3 servers. pub uid: Arc, + /// Its unique id on TeamSpeak 6 servers. pub uid6: Arc, + /// The security level of its key. pub level: i32, + /// The name of the current server. pub server: Arc, } /// One emoji of the picker. `text` is what picking it inserts. #[derive(Clone, Debug, Default, PartialEq)] pub struct EmojiCell { + /// The Twemoji key, "1f600". pub key: Arc, + /// The emoji's name. pub name: Arc, + /// What picking it inserts. pub text: Arc, } /// A row or form of the bridge (the plain counterpart of the Slint struct `EmojiRow`). #[derive(Clone, Debug, Default, PartialEq)] pub struct EmojiRow { + /// The emoji of the row. pub cells: Vec, } diff --git a/crates/voelin-ui-vm/src/chat/logic.rs b/crates/voelin-ui-vm/src/chat/logic.rs new file mode 100644 index 0000000..f2f3d19 --- /dev/null +++ b/crates/voelin-ui-vm/src/chat/logic.rs @@ -0,0 +1,1537 @@ +//! What happens to a session's chats when the engine tells something: tabs +//! open, messages arrive and are read, the gateway adds pins and topics, +//! files move. The functions change the [`AppState`] and say in the +//! [`Cx`]'s update what to draw and send; nothing here touches a toolkit. +//! +//! The engine keeps the history: `Event::ChatHistory` is an upsert of +//! messages by their local id (see `voelin_core::history`), so a tab holds +//! the messages it was given, ordered by `(ts_ms, id)`. Sessions the engine +//! keeps no history for (it does not know the server yet) fall back to +//! `Event::Chat`. +//! +//! Messages are read while their tab is on screen in the focused window +//! ([`track_reading`]). A tab remembers the newest message read +//! (`Tab::read`, kept in the store's `chat_reads`), counts what came after +//! it, and when it comes on screen shows a "New" divider above the first of +//! those until it is left. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use voelin_core::gateway::Pin; +use voelin_core::{ + Command, DownloadTo, GatewayRequest, GatewayUpdate, HistoryMessage, HistorySource, + TransferState, +}; +use voelin_gateway_proto::{ErrorCode, TopicInfo, feature}; +use voelin_model::{ChatMessage, ChatTarget}; +use voelin_store::ChatRead; + +use super::{LineCache, LineCtx, Previous, SERVER_LINES, server_texts, tab_title}; +use crate::bridge::{ChatLine, ChatTab, FileItem, PinItem, TopicItem}; +use crate::host::Cx; +use crate::previews::{fetch_previews, image_of, preview_progress}; +use crate::social::{Poke, is_own, own_message, peer_name, poke_lines}; +use crate::state::{AppState, Download, Lines, Msg, PinRow, SessionView, Tab, store_target}; + +/// The index of `target`'s tab in session `id`, opened if new (the engine +/// then sends its history). +pub fn chat_tab( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + target: ChatTarget, +) -> usize { + let peer = match &target { + ChatTarget::Private(uid) => peer_name(state, uid, None), + _ => String::new(), + }; + let view = state.sessions.entry(id).or_default(); + if let Some(i) = view.tabs.iter().position(|t| t.target == target) { + return i; + } + let title = tab_title(&view.presence, &target, &peer); + let tab = view.new_tab(target.clone(), title); + view.tabs.push(tab); + let index = view.tabs.len() - 1; + cx.send_real(Command::OpenChat { session: id as u64, target }); + index +} + +/// Open the chat `target` of the current session, and with `focus` show it. +pub fn open_chat( + state: &mut AppState, + cx: &mut Cx<'_>, + target: ChatTarget, + focus: bool, +) { + let Some(id) = state.current else { return }; + let index = chat_tab(state, cx, id, target); + if focus { + state.sessions.entry(id).or_default().focus_tab(index); + prefetch_counts(state, cx); + track_reading(state, cx); + } + cx.update.refresh.chat = true; + cx.update.refresh.servers = true; +} + +/// The index of `target`'s tab, opening one if it is new. +fn tab_for( + view: &mut SessionView, + target: &ChatTarget, + title: impl FnOnce() -> String, +) -> usize { + match view.tabs.iter().position(|t| t.target == *target) { + Some(i) => i, + None => { + let tab = view.new_tab(target.clone(), title()); + view.tabs.push(tab); + view.tabs.len() - 1 + } + } +} + +/// A live message of a session without stored history: appended as it +/// comes, without an id. +pub fn add_message( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + message: ChatMessage, +) { + let current = state.current == Some(id); + let reading = reads_now(state, cx, id); + let new = !is_own(state, id, &message); + let view = state.sessions.entry(id).or_default(); + let title = tab_title(&view.presence, &message.target, &message.author_name); + let index = tab_for(view, &message.target, || title); + let seen = reading && view.current_tab == index; + let tab = &mut view.tabs[index]; + let line = super::line(&message, tab.last.as_ref()); + tab.last = Some(Previous::of(&message)); + tab.lines.push(line); + let counted = new && !seen; + if counted { + tab.unread += 1; + } + if current { + cx.update.refresh.chat = true; + } + if counted { + cx.update.refresh.servers = true; + } + cx.chat_changed(id, &message.target); +} + +/// Messages the engine stored: added or updated by their local id. +pub fn history_batch( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + target: &ChatTarget, + messages: Vec, + source: HistorySource, + complete: bool, +) { + let current = state.current == Some(id); + let reading = reads_now(state, cx, id); + // A private chat is named after the peer, whoever wrote first. + let peer = match target { + ChatTarget::Private(uid) => Some(format!( + "@{}", + peer_name( + state, + uid, + messages.iter().find(|m| m.message.author_uid.as_deref() == Some(uid.as_str())) + ) + )), + _ => None, + }; + let own_uids = &state.own_uids; + let view = state.sessions.entry(id).or_default(); + let author = messages.first().map_or("", |m| m.message.author_name.as_str()); + let title = peer.unwrap_or_else(|| tab_title(&view.presence, target, author)); + let index = tab_for(view, target, || title); + let seen = reading && view.current_tab == index; + let own_client = view.state.own_client; + let tab = &mut view.tabs[index]; + if source == HistorySource::Gateway { + tab.synced = true; + } + if source != HistorySource::Live { + tab.loading = false; + tab.complete = tab.complete || complete; + } + // Without a marker, what the tab holds was read. + if tab.read.is_none() { + tab.read = tab.newest(); + } + for message in messages { + match tab.messages.iter().position(|m| m.message.id == message.id) { + Some(i) => tab.messages[i].message = message, + None => { + let key = tab.take_key(); + tab.messages.push(Msg { key, message }); + } + } + } + tab.messages.sort_by_key(|m| (m.message.message.ts_ms, m.message.id)); + // ...and so is a first stored page; a first live message is new. + if tab.read.is_none() { + tab.read = match source { + HistorySource::Live => tab + .messages + .first() + .map(|m| (m.message.message.ts_ms, m.message.id.saturating_sub(1))), + _ => tab.newest(), + }; + } + let unread = tab.unread; + let own = |m: &ChatMessage| own_message(own_uids, own_client, m); + if seen && source == HistorySource::Live { + tab.catch_up(); + } else { + tab.count_unread(own); + // What came while away (a stored or gateway page) gets the divider + // also when its chat is on screen already. + if seen { + tab.enter(own); + } + } + let counted = tab.unread != unread; + if current { + fetch_previews(state, cx, id); + cx.update.refresh.chat = true; + } + if counted { + cx.update.refresh.servers = true; + } + cx.chat_changed(id, target); +} + +// What is read. + +/// New messages of session `id` in its current tab are read as they come: +/// they are on screen in the focused window. +fn reads_now(state: &AppState, cx: &Cx<'_>, id: i64) -> bool { + state.focused && state.current == Some(id) && cx.host.chat_shown() +} + +/// Where the tab of `target` is in session `id`. +fn tab_index(state: &AppState, id: i64, target: &ChatTarget) -> Option { + state.sessions.get(&id)?.tabs.iter().position(|t| t.target == *target) +} + +/// After anything that can change which chat is on screen (a tab, a server, +/// the page, the window's focus): the chat left is stored and loses its +/// divider; the one on screen, in the focused window, is read (its divider +/// above what was new). `true` if a tab changed. +pub fn track_reading(state: &mut AppState, cx: &mut Cx<'_>) -> bool { + let open = state.current.filter(|_| cx.host.chat_shown()).and_then(|id| { + let view = state.sessions.get(&id)?; + Some((id, view.tabs.get(view.current_tab)?.target.clone())) + }); + let mut changed = false; + if open != state.reading { + if let Some((id, target)) = state.reading.take() + && let Some(index) = tab_index(state, id, &target) + { + let tab = &mut state.sessions.entry(id).or_default().tabs[index]; + changed |= tab.divider.take().is_some(); + save_read(state, cx, id, index); + } + state.reading = open.clone(); + } + if let (true, Some((id, target))) = (state.focused, open) + && let Some(index) = tab_index(state, id, &target) + { + let own_uids = &state.own_uids; + let view = state.sessions.entry(id).or_default(); + let own_client = view.state.own_client; + let tab = &mut view.tabs[index]; + let before = (tab.unread, tab.divider); + tab.enter(|m| own_message(own_uids, own_client, m)); + changed |= (tab.unread, tab.divider) != before; + } + changed +} + +/// Store where tab `index` of session `id` was read, if that moved (not for +/// the sample data of `VOELIN_DEMO_UI`). +pub fn save_read(state: &mut AppState, cx: &mut Cx<'_>, id: i64, index: usize) { + if cx.host.demo_ui() { + return; + } + let Some(view) = state.sessions.get_mut(&id) else { return }; + let Some(server_uid) = view.state.server_uid.as_deref() else { return }; + let Some(tab) = view.tabs.get_mut(index) else { return }; + let Some((ts_ms, message)) = tab.read.filter(|r| tab.stored_read != Some(*r)) else { + return; + }; + let read = ChatRead { ts_ms, id: message, updated_ms: chrono::Utc::now().timestamp_millis() }; + let target = store_target(&tab.target); + match cx.host.set_chat_read(server_uid, &target, &read) { + Ok(()) => { + tab.stored_read = tab.read; + // A tab closed and opened again starts from here. + view.reads.insert(target.key(), (ts_ms, message)); + } + Err(e) => cx.warn(format!("could not keep where a chat was read: {e}")), + } +} + +/// Store where every chat of session `id` was read (it ended, or the app +/// exits). +pub fn save_reads(state: &mut AppState, cx: &mut Cx<'_>, id: i64) { + let count = state.sessions.get(&id).map_or(0, |v| v.tabs.len()); + for index in 0..count { + save_read(state, cx, id, index); + } +} + +/// Where the chats of session `id` were read, from the store, once its +/// server is known (or another one: the gateway's id wins): its tabs start +/// from there, now and when they open. +pub fn load_reads(state: &mut AppState, cx: &mut Cx<'_>, id: i64) { + let Some(view) = state.sessions.get_mut(&id) else { return }; + if cx.host.demo_ui() + || view.state.server_uid.is_none() + || view.reads_of == view.state.server_uid + { + return; + } + view.reads_of = view.state.server_uid.clone(); + let server_uid = view.reads_of.as_deref().unwrap_or_default(); + view.reads = match cx.host.chat_reads(server_uid) { + Ok(reads) => reads.into_iter().map(|(t, r)| (t.key(), (r.ts_ms, r.id))).collect(), + Err(e) => { + cx.warn(format!("could not read where the chats were read: {e}")); + HashMap::new() + } + }; + for tab in &mut view.tabs { + tab.read_from(&view.reads); + } +} + +// Gateway features of a chat. + +/// Ask the gateway for the current chat's pins and topics until it sent +/// them, so the header counts them before their drawers are opened. +pub fn prefetch_counts(state: &AppState, cx: &mut Cx<'_>) { + let Some(id) = state.current else { return }; + let Some(view) = state.sessions.get(&id) else { return }; + let Some(tab) = view.tabs.get(view.current_tab) else { return }; + if !tab.pins_loaded && view.gateway_has(feature::PINS) { + cx.gateway_to(id, GatewayRequest::Pins { target: tab.target.clone() }); + } + if !tab.topics_loaded && view.gateway_has(feature::TOPICS) { + let target = tab.target.clone(); + cx.gateway_to(id, GatewayRequest::Topics { target, include_archived: false }); + } +} + +/// What a gateway update says about the chats of session `id`: its +/// features, pins, topics and the viewers of its streams. +pub fn gateway_update( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + update: GatewayUpdate, +) { + let current = state.current == Some(id); + let view = state.sessions.entry(id).or_default(); + match update { + GatewayUpdate::Connected { capabilities, .. } + | GatewayUpdate::Capabilities { capabilities } => { + view.gateway_caps = capabilities; + if current { + prefetch_counts(state, cx); + } + } + GatewayUpdate::Disconnected { .. } => { + view.gateway_caps.clear(); + for tab in &mut view.tabs { + tab.pins_loaded = false; + tab.topics_loaded = false; + } + } + // Answers to our requests: a chat closed while they were on their way + // (prefetch_counts asks on every change of chat) stays closed. + GatewayUpdate::Pins { target, pins } => { + let Some(tab) = view.tabs.iter_mut().find(|t| t.target == target) else { return }; + tab.pins_loaded = true; + tab.pins = pins.into_iter().map(|p| pin_row(tab.take_key(), p)).collect(); + tab.pins.sort_by_key(|p| -p.ts_ms); + } + GatewayUpdate::Pinned { target, pin } => { + let index = tab_for(view, &target, || "Server".into()); + let tab = &mut view.tabs[index]; + let row = pin_row(tab.take_key(), pin); + tab.pins.retain(|p| p.message.id != row.message.id); + tab.pins.insert(0, row); + } + GatewayUpdate::Unpinned { target, message_id, .. } => { + let index = tab_for(view, &target, || "Server".into()); + view.tabs[index].pins.retain(|p| p.message.remote_id != Some(message_id)); + } + GatewayUpdate::Topics { target, topics } => { + let Some(tab) = view.tabs.iter_mut().find(|t| t.target == target) else { return }; + tab.topics = topics; + tab.topics_loaded = true; + } + GatewayUpdate::Topic { topic } => { + let index = tab_for(view, &topic.target.clone(), || "Server".into()); + upsert_topic(&mut view.tabs[index].topics, topic); + } + GatewayUpdate::TopicHistory { target, topic, messages, .. } => { + let index = tab_for(view, &target, || "Server".into()); + let tab = &mut view.tabs[index]; + if tab.topic != Some(topic) { + return; + } + for message in messages { + match tab.topic_messages.iter().position(|m| m.message.id == message.id) { + Some(i) => tab.topic_messages[i].message = message, + None => { + let key = tab.take_key(); + tab.topic_messages.push(Msg { key, message }); + } + } + } + tab.topic_messages.sort_by_key(|m| (m.message.message.ts_ms, m.message.id)); + } + GatewayUpdate::Failed { request, code, message } => { + cx.warn(format!("gateway request {request} failed ({code:?}): {message}")); + if let Some(text) = failure_text(&request, code, &message) { + cx.status(text); + } + return; + } + // The stream directory: how many watch each stream. + GatewayUpdate::Streams { streams } => { + view.stream_viewers = streams.iter().filter_map(viewers_of).collect(); + return stream_viewers_changed(cx, current); + } + GatewayUpdate::StreamStarted { stream } + | GatewayUpdate::StreamUpdated { stream } + | GatewayUpdate::StreamRegistered { stream } => { + if let Some((id, viewers)) = viewers_of(&stream) { + view.stream_viewers.insert(id, viewers); + } + return stream_viewers_changed(cx, current); + } + GatewayUpdate::StreamEnded { id, .. } => { + view.stream_viewers.remove(&id); + return stream_viewers_changed(cx, current); + } + // Posts, pins and reactions also arrive as stored messages. + _ => return, + } + if current { + cx.update.refresh.chat = true; + } +} + +fn stream_viewers_changed(cx: &mut Cx<'_>, current: bool) { + if current { + cx.update.refresh.streams = true; + cx.update.refresh.viewer = true; + } +} + +// Files in chat. + +/// A transfer of a file that was not a picture preview: an upload from the +/// composer posts the file's link once it is up; a download of a message's +/// file shows how far it is. +pub fn transfer_progress( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + transfer: u64, + progress: TransferState, +) { + // An upload from the composer: post the file's link once it is up. + if let Some((_, channel, name)) = state.uploads.get(&transfer).cloned() { + match &progress { + TransferState::Done { size, .. } => { + state.uploads.remove(&transfer); + let file = voelin_model::FileRef { + channel, + path: "/".into(), + name: name.clone(), + size: Some(*size), + ..Default::default() + }; + cx.send(Command::SendChat { + session: id as u64, + target: ChatTarget::Channel(channel), + text: file.to_bbcode(), + }); + cx.status(format!("{name} shared")); + } + TransferState::Failed(e) => { + state.uploads.remove(&transfer); + cx.status(format!("Could not upload {name}: {e}")); + } + TransferState::Cancelled => { + state.uploads.remove(&transfer); + } + _ => {} + } + return; + } + if preview_progress(state, cx, id, transfer, &progress) { + return; + } + let done = matches!(progress, TransferState::Done { .. }); + let current = state.current == Some(id); + let view = state.sessions.entry(id).or_default(); + let Some(entry) = view.downloads.get_mut(&transfer) else { return }; + entry.state = progress; + let name = entry.name.clone(); + if done { + cx.status(format!("{name} downloaded")); + } + if current { + cx.update.refresh.chat = true; + } +} + +// What the user does. + +/// A request to the current session's gateway. +fn gateway(state: &AppState, cx: &mut Cx<'_>, request: GatewayRequest) { + if let Some(id) = state.current { + cx.gateway_to(id, request); + } +} + +/// The message with this handle in the current chat. +fn message_of(state: &AppState, key: i32) -> Option<&HistoryMessage> { + let view = state.sessions.get(&state.current?)?; + view.tabs.get(view.current_tab)?.message(key) +} + +/// Show tab `index` of the current session. +pub fn select_tab(state: &mut AppState, cx: &mut Cx<'_>, index: usize) { + if let Some(id) = state.current { + let view = state.sessions.entry(id).or_default(); + if index < view.tabs.len() { + view.set_current_tab(index); + view.tabs[index].topic = None; + } + fetch_previews(state, cx, id); + } + prefetch_counts(state, cx); + track_reading(state, cx); + cx.update.refresh.chat = true; + cx.update.refresh.servers = true; +} + +/// Close tab `index` of the current session (never the server's chat). +pub fn close_tab(state: &mut AppState, cx: &mut Cx<'_>, index: usize) { + let Some(id) = state.current else { return }; + let view = state.sessions.entry(id).or_default(); + if index == 0 || index >= view.tabs.len() { + return; + } + save_read(state, cx, id, index); + let tab = state.sessions.entry(id).or_default().remove_tab(index); + cx.send(Command::CloseChat { session: id as u64, target: tab.target }); + prefetch_counts(state, cx); + track_reading(state, cx); + cx.update.refresh.chat = true; + cx.update.refresh.servers = true; +} + +/// Say `text` in the current chat. +pub fn send_message(state: &AppState, cx: &mut Cx<'_>, text: String) { + let Some(id) = state.current else { return }; + let Some(view) = state.sessions.get(&id) else { return }; + let target = view.tabs[view.current_tab].target.clone(); + cx.send(Command::SendChat { session: id as u64, target, text }); +} + +/// What the sample data answers an older page with (no engine does). +pub struct SampleOlder { + /// The session. + pub session: i64, + /// The chat. + pub target: ChatTarget, + /// The oldest message shown now. + pub oldest: Option, +} + +/// The page of messages before the oldest one shown is asked for; the +/// sample data's is answered by the front end. +pub fn load_older(state: &mut AppState, cx: &mut Cx<'_>) -> Option { + let id = state.current?; + let view = state.sessions.get_mut(&id)?; + let tab = &mut view.tabs[view.current_tab]; + if tab.loading || tab.complete { + return None; + } + tab.loading = true; + let target = tab.target.clone(); + let oldest = tab.messages.first().map(|m| &m.message); + cx.update.refresh.chat = true; + if cx.host.demo_ui() { + return Some(SampleOlder { session: id, target, oldest: oldest.cloned() }); + } + let before = oldest.map(|m| m.id); + cx.send(Command::LoadOlderHistory { session: id as u64, target, before }); + None +} + +/// The current chat is read (the bar over its messages): the divider goes. +pub fn mark_read(state: &mut AppState, cx: &mut Cx<'_>) { + let Some(id) = state.current else { return }; + let Some(view) = state.sessions.get_mut(&id) else { return }; + let index = view.current_tab; + let tab = &mut view.tabs[index]; + tab.divider = None; + tab.catch_up(); + save_read(state, cx, id, index); + cx.update.refresh.chat = true; + cx.update.refresh.servers = true; +} + +/// The chat on screen may have changed (the page, the window's focus). +pub fn chat_shown_changed(state: &mut AppState, cx: &mut Cx<'_>) { + if track_reading(state, cx) { + cx.update.refresh.chat = true; + cx.update.refresh.servers = true; + } +} + +/// The window gained or lost the focus. +pub fn window_focused(state: &mut AppState, cx: &mut Cx<'_>, focused: bool) { + state.focused = focused; + chat_shown_changed(state, cx); +} + +/// Add or remove our reaction to a message. +pub fn react(state: &AppState, cx: &mut Cx<'_>, key: i32, emoji: String) { + let Some(message) = message_of(state, key) else { return }; + let Some(message_id) = message.remote_id else { return }; + let had = message.reactions.iter().any(|r| r.emoji == emoji && r.me); + let request = if had { + GatewayRequest::Unreact { message_id, emoji } + } else { + GatewayRequest::React { message_id, emoji } + }; + gateway(state, cx, request); +} + +/// Pin or unpin a message. +pub fn pin(state: &AppState, cx: &mut Cx<'_>, key: i32, on: bool) { + let Some(message) = message_of(state, key) else { return }; + let Some(message_id) = message.remote_id else { return }; + let request = + if on { GatewayRequest::Pin { message_id } } else { GatewayRequest::Unpin { message_id } }; + gateway(state, cx, request); +} + +/// Open the pins of the current chat (loading them once). +pub fn open_pins(state: &AppState, cx: &mut Cx<'_>) { + let Some(view) = current_view(state) else { return }; + let tab = &view.tabs[view.current_tab]; + if !tab.pins_loaded { + let target = tab.target.clone(); + gateway(state, cx, GatewayRequest::Pins { target }); + } + cx.update.refresh.chat = true; +} + +/// Highlight a pinned message in the chat; the row of the line to scroll to, +/// if the message is loaded. +pub fn jump_to_pin(state: &mut AppState, cx: &mut Cx<'_>, key: i32) -> Option { + let id = state.current?; + let view = state.sessions.entry(id).or_default(); + let tab = &mut view.tabs[view.current_tab]; + tab.marked = tab.pins.iter().find(|p| p.key == key).map(|p| p.message.id); + // The message is in the chat, not in an open topic. + if tab.topic.take().is_some() { + tab.topic_messages.clear(); + } + // Older than what is loaded: only highlighted once it is. The server + // chat's first lines are the server's. + let row = tab.marked.and_then(|id| tab.messages.iter().position(|m| m.message.id == id)); + let first = match tab.target { + ChatTarget::Server => server_texts(&view.presence.server).len(), + _ => 0, + }; + cx.update.refresh.chat = true; + row.map(|row| row + first) +} + +/// The topics drawer's search. +pub fn search_topics(state: &mut AppState, cx: &mut Cx<'_>, text: String) { + if state.topic_filter != text { + state.topic_filter = text; + cx.update.refresh.chat = true; + } +} + +/// Open the topics of the current chat (loading them once). +pub fn open_topics(state: &AppState, cx: &mut Cx<'_>) { + let Some(view) = current_view(state) else { return }; + let tab = &view.tabs[view.current_tab]; + if !tab.topics_loaded { + let target = tab.target.clone(); + gateway(state, cx, GatewayRequest::Topics { target, include_archived: false }); + } + cx.update.refresh.chat = true; +} + +/// Show a topic's messages (`-1` goes back to the chat). +pub fn open_topic(state: &mut AppState, cx: &mut Cx<'_>, topic: i32) { + let Some(id) = state.current else { return }; + let view = state.sessions.entry(id).or_default(); + let tab = &mut view.tabs[view.current_tab]; + tab.topic_messages.clear(); + tab.topic = (topic >= 0).then_some(i64::from(topic)); + let target = tab.target.clone(); + if let Some(topic) = tab.topic { + gateway( + state, + cx, + GatewayRequest::TopicHistory { target, topic, before: None, limit: None }, + ); + } + cx.update.refresh.chat = true; +} + +/// Say `text` in the open topic. +pub fn send_topic_message(state: &AppState, cx: &mut Cx<'_>, text: String) { + let Some(view) = current_view(state) else { return }; + let tab = &view.tabs[view.current_tab]; + let (Some(topic), target) = (tab.topic, tab.target.clone()) else { return }; + gateway(state, cx, GatewayRequest::Post { target, text, topic: Some(topic) }); +} + +/// Start a topic from a message (`key` < 0: a standalone topic). +pub fn create_topic(state: &AppState, cx: &mut Cx<'_>, key: i32, title: String) { + let Some(view) = current_view(state) else { return }; + let target = view.tabs[view.current_tab].target.clone(); + let message_id = message_of(state, key).and_then(|m| m.remote_id); + gateway(state, cx, GatewayRequest::CreateTopic { target, title, message_id }); +} + +/// The current session's view. +fn current_view(state: &AppState) -> Option<&SessionView> { + state.sessions.get(&state.current?) +} + +/// Download a file a message links, into `dir`. +pub fn download_file( + state: &mut AppState, + cx: &mut Cx<'_>, + key: i32, + index: i32, + dir: &Path, +) { + let Some(id) = state.current else { return }; + let index = index.max(0) as usize; + let Some(file) = + message_of(state, key).and_then(|m| m.message.file_refs().into_iter().nth(index)) + else { + return; + }; + let path = dir.join(&file.name); + let view = state.sessions.entry(id).or_default(); + let transfer = view.next_transfer; + view.next_transfer += 1; + view.downloads.insert( + transfer, + Download { key, index, name: file.name.clone(), state: TransferState::Requested }, + ); + cx.send(Command::DownloadChatFile { + session: id as u64, + transfer, + file, + password: None, + to: DownloadTo::Path { path, resume: false }, + }); + cx.update.refresh.chat = true; +} + +/// Where a file attached to the current chat goes: its session and +/// channel; the reason when the chat is not a channel's. +pub fn attach_target(state: &AppState) -> Result, &'static str> { + let Some(id) = state.current else { return Ok(None) }; + let Some(view) = state.sessions.get(&id) else { return Ok(None) }; + match view.tabs[view.current_tab].target { + ChatTarget::Channel(channel) => Ok(Some((id, channel))), + _ => Err("Files can be attached to a channel's chat."), + } +} + +/// Upload a file into a channel and link it in the chat once it is up. +pub fn upload( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + channel: u64, + from: PathBuf, +) { + let Some(name) = from.file_name().map(|n| n.to_string_lossy().to_string()) else { return }; + let view = state.sessions.entry(id).or_default(); + let transfer = view.next_transfer; + view.next_transfer += 1; + state.uploads.insert(transfer, (id, channel, name.clone())); + cx.send(Command::UploadFile { + session: id as u64, + transfer, + channel, + password: None, + path: format!("/{name}"), + from, + overwrite: true, + resume: false, + }); + cx.status(format!("Uploading {name}…")); +} + +// What is shown. + +/// What the lines of a chat need besides the state. +pub struct LinesFacts<'a> { + /// Pictures on the web show: they are fetched and previews are on. + pub pictures_shown: bool, + /// The pokes we got (they show among a private chat's messages). + pub pokes: &'a [Poke], +} + +/// The lines of a tab's messages (`main`) or of its open topic, grouped and +/// with everything the row shows (also the stream chat of the Stream Studio). +/// The server chat starts with what the server says to everyone who +/// connects (`server_lines`). +pub fn lines_of( + state: &AppState, + view: &SessionView, + tab: &Tab, + main: bool, + facts: &LinesFacts<'_>, +) -> Vec { + let messages = if main { &tab.messages } else { &tab.topic_messages }; + let gateway = view.gateway_has(feature::PINS) + || view.gateway_has(feature::REACTIONS) + || view.gateway_has(feature::TOPICS); + // Pictures on the web show only while pictures are fetched and shown. + let pictures = facts.pictures_shown.then_some(&view.pictures); + let cache = main.then_some(&tab.cache); + let mut previous: Option = None; + let mut lines: Vec<(i64, ChatLine)> = Vec::with_capacity(messages.len()); + for m in messages { + let avatar = m.message.message.author_uid.as_ref().and_then(|uid| view.avatars.get(uid)); + let topic = m + .message + .topic_id + .filter(|_| tab.topic.is_none()) + .and_then(|t| tab.topics.iter().find(|i| i.id == t)) + .map(|t| t.title.clone()) + .unwrap_or_default(); + let previews = m + .message + .message + .file_refs() + .iter() + .enumerate() + .filter_map(|(i, f)| image_of(view, f).map(|image| (i, image))) + .collect(); + let ctx = LineCtx { + key: m.key, + avatar: crate::avatar::image(avatar), + gateway, + marked: tab.marked == Some(m.message.id), + topic, + downloads: downloads_of(view, m.key), + previews, + pictures, + cache, + unread_start: main && tab.divider == Some(m.message.id), + }; + lines.push(( + m.message.message.ts_ms, + super::history_line(&m.message, previous.as_ref(), &ctx), + )); + previous = Some(Previous::of(&m.message.message)); + } + if let Some(cache) = cache { + let ids = messages.iter().map(|m| m.message.id).chain(SERVER_LINES); + cache.keep(ids, messages.len()); + } + // Pokes of a private chat's peer show among its messages. + if let (ChatTarget::Private(uid), Some(session)) = (&tab.target, state.current) { + lines.extend(poke_lines(state, facts.pokes, session, uid)); + lines.sort_by_key(|(ts, _)| *ts); + } + let server = if main && tab.target == ChatTarget::Server { + server_lines(view, pictures, cache) + } else { + Vec::new() + }; + server.into_iter().chain(lines.into_iter().map(|(_, line)| line)).collect() +} + +/// What the server says to everyone who connects ([`server_texts`]) as the +/// first lines of the server chat: by the server, without reactions or +/// pins. +fn server_lines( + view: &SessionView, + pictures: Option<&HashMap>, + cache: Option<&LineCache>, +) -> Vec { + let name = match view.presence.server_name.as_str() { + "" => "Server", + name => name, + }; + server_texts(&view.presence.server) + .into_iter() + .enumerate() + .map(|(i, (text, id))| { + let ctx = LineCtx { key: -1 - i as i32, pictures, cache, ..Default::default() }; + super::server_line(name, text, id, i > 0, &ctx) + }) + .collect() +} + +/// The file cards of a message that has downloads running. +fn downloads_of(view: &SessionView, key: i32) -> Vec<(usize, FileItem)> { + view.downloads + .values() + .filter(|d| d.key == key) + .map(|d| { + let (detail, status, progress) = match &d.state { + TransferState::Requested => ("Starting…".to_owned(), "running", 0.0), + TransferState::Started { size, offset } => ( + format!("{} of {}", super::size_text(*offset), super::size_text(*size)), + "running", + if *size > 0 { *offset as f32 / *size as f32 } else { 0.0 }, + ), + TransferState::Progress { done, size } => ( + format!("{} of {}", super::size_text(*done), super::size_text(*size)), + "running", + if *size > 0 { *done as f32 / *size as f32 } else { 0.0 }, + ), + TransferState::Done { size, .. } => { + (format!("Downloaded · {}", super::size_text(*size)), "done", 1.0) + } + TransferState::Failed(e) => (e.clone(), "failed", 0.0), + TransferState::Cancelled => ("Cancelled".to_owned(), "failed", 0.0), + }; + ( + d.index, + FileItem { + name: d.name.clone().into(), + detail: detail.into(), + index: d.index as i32, + state: status.into(), + progress, + ..Default::default() + }, + ) + }) + .collect() +} + +/// "3 min ago", "yesterday", "12 Mar". +fn ago(ts_ms: i64) -> String { + let Some(then) = chrono::DateTime::from_timestamp_millis(ts_ms) else { return String::new() }; + let minutes = (chrono::Utc::now() - then).num_minutes(); + match minutes { + i64::MIN..=0 => "just now".into(), + 1 => "1 min ago".into(), + 2..=59 => format!("{minutes} min ago"), + 60..=119 => "1 hour ago".into(), + 120..=1439 => format!("{} hours ago", minutes / 60), + 1440..=2879 => "yesterday".into(), + _ => then.with_timezone(&chrono::Local).format("%e %b").to_string().trim().into(), + } +} + +/// What the chat view shows of the current session. +pub struct ChatView { + /// The chat strip's tabs (without private chats). + pub tabs: Vec, + /// Which of the session's tabs each of `tabs` is. + pub strip: Vec, + /// The strip's current tab (-1: the current tab is not in it). + pub current: i32, + /// The session's current tab. + pub current_chat: i32, + /// The lines of the current tab, built from its messages; none for a + /// session without stored history, whose tabs hold the lines they were + /// pushed. + pub lines: Option>, + /// The row of the "New" divider, -1 without one. + pub unread_index: i32, + /// How many came from there on. + pub unread_count: i32, + /// And since when. + pub unread_since: String, + /// Older messages can be asked for. + pub more_history: bool, + /// An older page was asked for. + pub loading_history: bool, + /// The chat is only what this device saw, though the gateway has history. + pub local_history: bool, + /// The gateway takes pins. + pub has_pins: bool, + /// The gateway takes reactions. + pub has_reactions: bool, + /// The gateway has topics. + pub has_topics: bool, + /// The pins were asked for and are not there yet. + pub pins_loading: bool, + /// The topics were asked for and are not there yet. + pub topics_loading: bool, + /// The header's pins count, -1 while unknown. + pub pins_count: i32, + /// The header's topics count, -1 while unknown. + pub topics_count: i32, + /// The pins drawer's rows. + pub pins: Vec, + /// The topics drawer's rows. + pub topics: Vec, + /// The open topic, -1 without one. + pub current_topic: i32, + /// Its title. + pub topic_title: String, + /// Its messages. + pub topic_lines: Vec, +} + +/// The tabs, the lines and the drawers of the current session's chat; +/// none when no server is shown. +pub fn chat_view(state: &AppState, facts: &LinesFacts<'_>) -> Option { + let view = current_view(state)?; + // Private chats are on the messages page, not in the strip. + let (strip, current) = super::strip(view.tabs.iter().map(|t| &t.target), view.current_tab); + let tabs: Vec = strip + .iter() + .map(|&i| &view.tabs[i]) + .map(|t| { + let (last, time) = + t.messages.last().map(|m| super::preview(&m.message.message)).unwrap_or_default(); + let channel = match t.target { + ChatTarget::Channel(cid) => view.presence.channels.get(&cid), + _ => None, + }; + ChatTab { + last: last.into(), + time: time.into(), + title: t.title.clone().into(), + name: super::tab_name(&t.title, &t.target).into(), + kind: match t.target { + ChatTarget::Server => 0, + ChatTarget::Channel(_) => 1, + ChatTarget::Private(_) => 2, + }, + id: match t.target { + ChatTarget::Channel(cid) => cid as i32, + _ => 0, + }, + unread: t.unread, + topic: channel.and_then(|c| c.topic.clone()).unwrap_or_default().into(), + banner: crate::tree::banner( + &view.pictures, + channel.and_then(|c| c.banner_gfx_url.as_deref()), + ), + banner_mode: channel.map_or(0, |c| crate::tree::banner_mode(c.banner_mode)), + } + }) + .collect(); + let tab = &view.tabs[view.current_tab]; + // Sessions without stored history push their lines themselves. + let lines = view.has_history().then(|| lines_of(state, view, tab, true, facts)); + let divider = lines.as_ref().and_then(|l| l.iter().position(|l| l.unread_start)); + // The "New" divider: how many came from there on, and when. + let new = tab + .divider + .and_then(|d| tab.messages.iter().position(|m| m.message.id == d)) + .map_or(&[][..], |i| &tab.messages[i..]); + let session = state.current.unwrap_or_default(); + let count = new.iter().filter(|m| !is_own(state, session, &m.message.message)).count(); + let pins: Vec = tab + .pins + .iter() + .map(|p| { + let avatar = p.message.message.author_uid.as_ref().and_then(|u| view.avatars.get(u)); + let ctx = LineCtx { + key: p.key, + avatar: crate::avatar::image(avatar), + gateway: true, + ..Default::default() + }; + PinItem { + line: super::history_line(&p.message, None, &ctx), + by: format!("Pinned by {} · {}", p.by, super::time_of(p.ts_ms)).into(), + } + }) + .collect(); + let filter = state.topic_filter.trim().to_lowercase(); + let now = chrono::Utc::now().timestamp_millis(); + let topics: Vec = tab + .topics + .iter() + .filter(|t| filter.is_empty() || t.title.to_lowercase().contains(&filter)) + .map(|t| TopicItem { + id: t.id as i32, + title: t.title.clone().into(), + creator: t.creator.name.clone().into(), + detail: format!( + "{} {} · by {}", + t.message_count, + if t.message_count == 1 { "message" } else { "messages" }, + t.creator.name + ) + .into(), + activity: format!("Last active {}", ago(t.last_activity_ms)).into(), + recent: now - t.last_activity_ms < 3_600_000, + archived: t.archived, + }) + .collect(); + Some(ChatView { + tabs, + strip, + current, + current_chat: view.current_tab as i32, + lines, + unread_index: divider.map_or(-1, |i| i as i32), + unread_count: count as i32, + unread_since: new + .first() + .map(|m| super::since_time(m.message.message.ts_ms)) + .unwrap_or_default(), + more_history: view.has_history() && !tab.complete, + loading_history: tab.loading, + local_history: view.has_history() && !tab.synced && view.gateway_has(feature::HISTORY), + has_pins: view.gateway_has(feature::PINS), + has_reactions: view.gateway_has(feature::REACTIONS), + has_topics: view.gateway_has(feature::TOPICS), + pins_loading: !tab.pins_loaded && view.gateway_has(feature::PINS), + topics_loading: !tab.topics_loaded && view.gateway_has(feature::TOPICS), + pins_count: super::known_count(tab.pins_loaded, tab.pins.len()), + topics_count: super::known_count(tab.topics_loaded, tab.topics.len()), + pins, + topics, + current_topic: tab.topic.map_or(-1, |t| t as i32), + topic_title: tab + .topic + .and_then(|t| tab.topics.iter().find(|i| i.id == t)) + .map(|t| t.title.clone()) + .unwrap_or_default(), + topic_lines: lines_of(state, view, tab, false, facts), + }) +} + +/// What a failed gateway request tells the user. What the app asked for by +/// itself (history, lists, subscriptions) fails quietly; what the user did +/// says so in plain words, never the gateway's; the gateway's own +/// administration page shows its message as it is. +pub fn failure_text(request: &str, code: Option, message: &str) -> Option { + if request.starts_with("config_") || request.starts_with("perm_") { + return Some(format!("{request}: {message}")); + } + // The requests a user makes by hand (a list, not an or-pattern: the + // pattern's layout differs between rustfmt releases). + const DONE_BY_USER: [&str; 11] = [ + "post", + "pin", + "unpin", + "react", + "unreact", + "create_topic", + "update_topic", + "create_event", + "update_event", + "delete_event", + "rsvp", + ]; + if !DONE_BY_USER.contains(&request) { + return None; + } + let text = match code { + Some(ErrorCode::Forbidden) => "Not allowed on this server.", + Some(ErrorCode::RateLimited) => "Too many requests; try again in a moment.", + Some(ErrorCode::QuotaExceeded) => "This server's limit is reached.", + Some(ErrorCode::NotFound) => "That is no longer there.", + Some(ErrorCode::FeatureDisabled) => "This server does not offer that.", + _ => "That did not work; try again later.", + }; + Some(text.to_owned()) +} + +/// A directory entry's stream id and viewer count, when it has both. +fn viewers_of(entry: &voelin_gateway_proto::StreamEntry) -> Option<(String, u32)> { + Some((entry.stream_id.clone()?, entry.viewers?)) +} + +fn pin_row(key: i32, pin: Pin) -> PinRow { + PinRow { key, message: pin.message, by: pin.by.name, ts_ms: pin.ts_ms } +} + +fn upsert_topic(topics: &mut Vec, topic: TopicInfo) { + match topics.iter().position(|t| t.id == topic.id) { + Some(i) => topics[i] = topic, + None => topics.insert(0, topic), + } +} + +#[cfg(test)] +mod tests { + use voelin_core::Event; + + use super::*; + use crate::events::apply; + use crate::host::testing::{Fake, State, presence, said, session, state}; + use voelin_core::VoiceState; + + #[test] + fn relative_times() { + let now = chrono::Utc::now().timestamp_millis(); + assert_eq!(ago(now), "just now"); + assert_eq!(ago(now - 3 * 60_000), "3 min ago"); + assert_eq!(ago(now - 3 * 3_600_000), "3 hours ago"); + assert_eq!(ago(now - 36 * 3_600_000), "yesterday"); + } + + #[test] + fn failures_say_what_the_user_did_never_the_gateway() { + let lost = "websocket: IO error: Connection refused (os error 111)"; + // The app's own requests fail quietly. + for request in ["history", "sync", "pins", "events", "subscribe_streams"] { + assert_eq!(failure_text(request, None, lost), None, "{request}"); + } + // The user's own, in plain words. + assert_eq!( + failure_text("pin", Some(ErrorCode::Forbidden), "no b_pin").as_deref(), + Some("Not allowed on this server.") + ); + let text = failure_text("post", None, lost).unwrap(); + assert!(!text.contains("websocket") && !text.to_lowercase().contains("gateway"), "{text}"); + // The gateway's administration page shows its message. + assert_eq!( + failure_text("config_set", Some(ErrorCode::BadRequest), "bad value").as_deref(), + Some("config_set: bad value") + ); + } + + /// Server 1 connected into Games with its chat (messages 6 and 7 of + /// Alice, a gateway with pins, reactions and topics), the Games tab + /// shown. + fn games() -> (State, Fake) { + let mut st = state(); + let host = Fake::default(); + for event in [ + Event::Presence { session: 1, presence: presence() }, + Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }, + Event::ChatHistory { + session: 1, + target: ChatTarget::Channel(2), + messages: vec![said(6, 190, false, "hi"), said(7, 200, false, "there")], + source: HistorySource::Local, + complete: false, + }, + ] { + apply(&mut st, &host, event); + } + st.sessions.get_mut(&1).unwrap().gateway_caps = + [feature::PINS, feature::REACTIONS, feature::TOPICS].map(String::from).into(); + (st, host) + } + + fn commands<'a>(cx: &'a Cx<'_>) -> Vec<&'a Command> { + cx.update.commands.iter().collect() + } + + /// Tabs open, are selected and closed (never the server's), and a message + /// goes to the chat on screen. + #[test] + fn tabs_open_are_selected_and_closed() { + let (mut st, host) = games(); + let mut cx = Cx::new(&host); + open_chat(&mut st, &mut cx, ChatTarget::Channel(1), true); + let view = &st.sessions[&1]; + assert_eq!(view.tabs.len(), 3); + assert_eq!(view.tabs[view.current_tab].target, ChatTarget::Channel(1)); + assert!( + matches!(commands(&cx).as_slice(), [Command::OpenChat { session: 1, target }, ..] if target == &ChatTarget::Channel(1)) + ); + // The gateway's pins and topics of the chat are asked for once. + assert!(commands(&cx).iter().any(|c| matches!( + c, + Command::Gateway { + request: GatewayRequest::Pins { target: ChatTarget::Channel(1) }, + .. + } + ))); + let mut cx = Cx::new(&host); + send_message(&st, &mut cx, "hello".into()); + assert!(matches!( + commands(&cx).as_slice(), + [Command::SendChat { session: 1, target: ChatTarget::Channel(1), text }] if text == "hello" + )); + // Back to Games; a topic that was open is closed with the move. + st.sessions.get_mut(&1).unwrap().tabs[1].topic = Some(3); + let mut cx = Cx::new(&host); + select_tab(&mut st, &mut cx, 1); + assert_eq!(st.sessions[&1].current_tab, 1); + assert_eq!(st.sessions[&1].tabs[1].topic, None); + assert!(cx.update.refresh.chat && cx.update.refresh.servers); + // The server's chat stays; the Lobby's goes, and the chat on screen with it. + let mut cx = Cx::new(&host); + close_tab(&mut st, &mut cx, 0); + assert_eq!(st.sessions[&1].tabs.len(), 3); + st.sessions.get_mut(&1).unwrap().set_current_tab(2); + close_tab(&mut st, &mut cx, 2); + assert_eq!(st.sessions[&1].tabs.len(), 2); + assert!(matches!( + commands(&cx).first(), + Some(Command::CloseChat { session: 1, target: ChatTarget::Channel(1) }) + )); + assert_eq!( + st.sessions[&1].tabs[st.sessions[&1].current_tab].target, + ChatTarget::Channel(2) + ); + } + + /// What the chat view shows: the strip, the lines, the divider and the + /// drawers' counts. + #[test] + fn the_chat_view_has_the_strip_the_divider_and_the_counts() { + let (mut st, host) = games(); + let facts = LinesFacts { pictures_shown: false, pokes: &[] }; + let chat = chat_view(&st, &facts).unwrap(); + assert_eq!(chat.strip, [0, 1]); + assert_eq!(chat.tabs.iter().map(|t| &*t.title).collect::>(), ["Server", "Games"]); + assert_eq!((chat.current, chat.current_chat), (1, 1)); + assert_eq!(chat.tabs[1].last.as_ref(), "Alice: there"); + // The stored page has the engine's history: its lines are rebuilt from + // the messages (and the server chat starts with the server's own). + assert_eq!(chat.lines.as_ref().map(Vec::len), Some(2)); + assert!(chat.has_pins && chat.has_reactions && chat.has_topics); + assert_eq!((chat.pins_count, chat.topics_count), (-1, -1)); + assert!(chat.pins_loading && chat.topics_loading); + assert_eq!((chat.unread_index, chat.unread_count), (-1, 0)); + assert!(chat.more_history && !chat.loading_history); + + // A message while away is new; on screen it gets the divider. + apply( + &mut st, + &host, + Event::ChatHistory { + session: 1, + target: ChatTarget::Channel(2), + messages: vec![said(8, 300, false, "new")], + source: HistorySource::Live, + complete: false, + }, + ); + host.shown.set(true); + let mut cx = Cx::new(&host); + assert!(track_reading(&mut st, &mut cx)); + let chat = chat_view(&st, &facts).unwrap(); + assert_eq!((chat.unread_index, chat.unread_count), (2, 1)); + assert!(!chat.unread_since.is_empty()); + assert!(chat.lines.as_ref().unwrap()[2].unread_start); + // Marked read: the divider goes and the position is kept. + let mut cx = Cx::new(&host); + mark_read(&mut st, &mut cx); + let chat = chat_view(&st, &facts).unwrap(); + assert_eq!((chat.unread_index, chat.unread_count), (-1, 0)); + assert_eq!(host.written.borrow().last().map(|w| (w.2.ts_ms, w.2.id)), Some((300, 8))); + + // Nothing on screen without a server. + st.current = None; + assert!(chat_view(&st, &facts).is_none()); + } + + /// Pins and topics: asked for when opened, the topic's messages, the + /// highlight of a pinned message, reactions. + #[test] + fn pins_topics_and_reactions() { + let (mut st, host) = games(); + let mut cx = Cx::new(&host); + open_pins(&st, &mut cx); + open_topics(&st, &mut cx); + assert!(matches!( + commands(&cx).as_slice(), + [ + Command::Gateway { request: GatewayRequest::Pins { .. }, .. }, + Command::Gateway { + request: GatewayRequest::Topics { include_archived: false, .. }, + .. + }, + ] + )); + assert!(cx.update.refresh.chat); + // A pin to jump to. + let pinned = Pin { + message: said(6, 190, false, "hi"), + by: voelin_gateway_proto::UserRef { uid: "alice=".into(), name: "Alice".into() }, + ts_ms: 10, + }; + let mut cx = Cx::new(&host); + gateway_update( + &mut st, + &mut cx, + 1, + GatewayUpdate::Pins { target: ChatTarget::Channel(2), pins: vec![pinned] }, + ); + let key = st.sessions[&1].tabs[1].pins[0].key; + let mut cx = Cx::new(&host); + assert_eq!(jump_to_pin(&mut st, &mut cx, key), Some(0)); + assert_eq!(st.sessions[&1].tabs[1].marked, Some(6)); + // A pin of a message that is not loaded is highlighted once it is. + assert_eq!(jump_to_pin(&mut st, &mut cx, 999), None); + assert_eq!(st.sessions[&1].tabs[1].marked, None); + // A topic: its history is asked for, going back closes it. + let mut cx = Cx::new(&host); + open_topic(&mut st, &mut cx, 5); + assert_eq!(st.sessions[&1].tabs[1].topic, Some(5)); + assert!(matches!( + commands(&cx).as_slice(), + [Command::Gateway { request: GatewayRequest::TopicHistory { topic: 5, .. }, .. }] + )); + let mut cx = Cx::new(&host); + send_topic_message(&st, &mut cx, "in the topic".into()); + assert!(matches!( + commands(&cx).as_slice(), + [Command::Gateway { request: GatewayRequest::Post { topic: Some(5), .. }, .. }] + )); + open_topic(&mut st, &mut cx, -1); + assert_eq!(st.sessions[&1].tabs[1].topic, None); + // The search of the drawer redraws only when the text changes. + let mut cx = Cx::new(&host); + search_topics(&mut st, &mut cx, "ban".into()); + search_topics(&mut st, &mut cx, "ban".into()); + assert_eq!(st.topic_filter, "ban"); + // Reactions and pins go by the gateway's id of the message. + let mut cx = Cx::new(&host); + let key = st.sessions[&1].tabs[1].messages[0].key; + react(&st, &mut cx, key, "👍".into()); + pin(&st, &mut cx, key, true); + create_topic(&st, &mut cx, key, "Plans".into()); + assert!(matches!( + commands(&cx).as_slice(), + [ + Command::Gateway { request: GatewayRequest::React { message_id: 1006, .. }, .. }, + Command::Gateway { request: GatewayRequest::Pin { message_id: 1006 }, .. }, + Command::Gateway { + request: GatewayRequest::CreateTopic { message_id: Some(1006), .. }, + .. + }, + ] + )); + // The sample sessions have no gateway to ask. + let demo = Fake { demo: true, ..Default::default() }; + let mut cx = Cx::new(&demo); + react(&st, &mut cx, key, "👍".into()); + assert!(cx.update.commands.is_empty()); + } + + /// Older pages are asked for once; files are downloaded into a folder and + /// uploaded from the composer. + #[test] + fn older_pages_and_files() { + let (mut st, host) = games(); + let mut cx = Cx::new(&host); + assert!(load_older(&mut st, &mut cx).is_none()); + assert!(matches!( + commands(&cx).as_slice(), + [Command::LoadOlderHistory { session: 1, before: Some(6), .. }] + )); + assert!(st.sessions[&1].tabs[1].loading); + // Asked: not again before the answer. + let mut cx = Cx::new(&host); + assert!(load_older(&mut st, &mut cx).is_none() && cx.update.commands.is_empty()); + // The sample data answers itself. + st.sessions.get_mut(&1).unwrap().tabs[1].loading = false; + let demo = Fake { demo: true, ..Default::default() }; + let mut cx = Cx::new(&demo); + let sample = load_older(&mut st, &mut cx).unwrap(); + assert_eq!((sample.session, sample.oldest.map(|m| m.id)), (1, Some(6))); + assert!(cx.update.commands.is_empty()); + + // A file the message links: downloaded into the folder, shown as it runs. + let link = "[URL=ts3file://ts.example?port=9987&channel=2&path=%2F&channelpassword=&filename=a.png&isDir=0&size=2048&fileSize=2048]a.png[/URL]"; + apply( + &mut st, + &host, + Event::ChatHistory { + session: 1, + target: ChatTarget::Channel(2), + messages: vec![said(9, 400, false, link)], + source: HistorySource::Live, + complete: false, + }, + ); + let key = st.sessions[&1].tabs[1].messages.last().unwrap().key; + let mut cx = Cx::new(&host); + download_file(&mut st, &mut cx, key, 0, Path::new("/home/me/Downloads")); + assert!(matches!( + commands(&cx).as_slice(), + [Command::DownloadChatFile { session: 1, transfer: 1, to: DownloadTo::Path { path, .. }, .. }] + if path == Path::new("/home/me/Downloads/a.png") + )); + let facts = LinesFacts { pictures_shown: false, pokes: &[] }; + let chat = chat_view(&st, &facts).unwrap(); + let line = chat.lines.unwrap().pop().unwrap(); + assert_eq!(line.files.len(), 1); + assert_eq!((&*line.files[0].state, &*line.files[0].detail), ("running", "Starting…")); + // Attaching: a channel's chat takes files, the server's does not. + assert_eq!(attach_target(&st), Ok(Some((1, 2)))); + st.sessions.get_mut(&1).unwrap().set_current_tab(0); + assert!(attach_target(&st).is_err()); + let mut cx = Cx::new(&host); + upload(&mut st, &mut cx, 1, 2, PathBuf::from("/tmp/notes.txt")); + assert!(matches!( + commands(&cx).as_slice(), + [Command::UploadFile { session: 1, channel: 2, path, .. }] if path == "/notes.txt" + )); + assert_eq!(cx.update.status.as_deref(), Some("Uploading notes.txt…")); + assert_eq!(st.uploads.len(), 1); + } + + /// A private chat shows the pokes of its peer among its messages. + #[test] + fn a_private_chat_has_the_pokes_of_its_peer() { + let (mut st, host) = games(); + let direct = said(20, 1000, false, "psst"); + let mut direct_message = direct.clone(); + direct_message.message.target = ChatTarget::Private("alice=".into()); + apply( + &mut st, + &host, + Event::ChatHistory { + session: 1, + target: ChatTarget::Private("alice=".into()), + messages: vec![direct_message], + source: HistorySource::Local, + complete: true, + }, + ); + let pokes = [Poke { + session: 1, + uid: Some("alice=".into()), + name: "Alice".into(), + message: "hey".into(), + ts_ms: 500, + }]; + let view = &st.sessions[&1]; + let tab = view.tabs.iter().find(|t| t.is_private()).unwrap(); + let facts = LinesFacts { pictures_shown: false, pokes: &pokes }; + let lines = lines_of(&st, view, tab, true, &facts); + assert_eq!(lines.len(), 2); + assert_eq!(lines[0].key, -1_000_000, "the poke came first"); + let none = + lines_of(&st, view, tab, true, &LinesFacts { pictures_shown: false, pokes: &[] }); + assert_eq!(none.len(), 1); + } +} diff --git a/crates/voelin-ui-vm/src/chat.rs b/crates/voelin-ui-vm/src/chat/mod.rs similarity index 96% rename from crates/voelin-ui-vm/src/chat.rs rename to crates/voelin-ui-vm/src/chat/mod.rs index e7c0b3c..dbc8667 100644 --- a/crates/voelin-ui-vm/src/chat.rs +++ b/crates/voelin-ui-vm/src/chat/mod.rs @@ -1,6 +1,9 @@ //! Chat lines: one [`ChatLine`] per message, with its text in blocks of //! styled runs (`vm::bbcode`), its reactions and the files and pictures it -//! links. +//! links; [`logic`] has what happens to a session's chats when the engine +//! tells something. + +pub mod logic; use std::borrow::Cow; use std::cell::RefCell; @@ -9,7 +12,7 @@ use std::path::PathBuf; use unicode_segmentation::UnicodeSegmentation; use voelin_core::HistoryMessage; -use voelin_model::{ChatMessage, ChatTarget, FileRef, Presence}; +use voelin_model::{ChatMessage, ChatTarget, FileRef, HostMessageMode, Presence, ServerDetails}; use crate::avatar; use crate::bbcode::{self, BlockKind, Doc, Span, Style}; @@ -17,6 +20,32 @@ use crate::bridge::{ChatLine, FileItem, ReactionItem, TextBlock, TextRun}; use crate::color::Rgb; use crate::emoji; use crate::image::ImageRef; +use crate::state::{SessionView, Tab}; + +/// Where the server's welcome and host message keep what their lines were +/// built from (`LineCache`), apart from the messages' ids. +pub const SERVER_LINES: [i64; 2] = [i64::MIN, i64::MIN + 1]; + +/// What the server says to everyone who connects, with where its line keeps +/// its parts: its welcome message, and its host message when that goes to +/// the chat log. +pub fn server_texts(details: &ServerDetails) -> Vec<(&str, i64)> { + let host = details.host_message_mode == HostMessageMode::Log; + [Some(&details.welcome_message), host.then_some(&details.host_message)] + .into_iter() + .zip(SERVER_LINES) + .filter_map(|(text, id)| Some((text.filter(|t| !t.trim().is_empty())?.as_str(), id))) + .collect() +} + +/// The text of the server's line `key` (-1, -2, ...) of a server chat, if +/// `tab` is one. +pub fn server_text<'a, L>(view: &'a SessionView, tab: &Tab, key: i32) -> Option<&'a str> { + if tab.target != ChatTarget::Server || key >= 0 { + return None; + } + server_texts(&view.presence.server).get((-1 - key) as usize).map(|(text, _)| *text) +} /// Lines of the same author within this time are grouped (no header). const GROUP_MS: i64 = 5 * 60 * 1000; @@ -24,7 +53,9 @@ const GROUP_MS: i64 = 5 * 60 * 1000; /// The author and time of the line before, for grouping. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Previous { + /// Who wrote it. pub author: String, + /// When, in milliseconds since the epoch. pub ts_ms: i64, } diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui-vm/src/dev/logic.rs similarity index 61% rename from crates/voelin-ui/src/dev.rs rename to crates/voelin-ui-vm/src/dev/logic.rs index 597d088..7d0a7e3 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui-vm/src/dev/logic.rs @@ -1,77 +1,19 @@ -//! Development switches (environment variables), for trying screens and -//! taking screenshots without a server: -//! -//! - `VOELIN_DATA_DIR=`: the database (app.rs). -//! - `VOELIN_AUTOCONNECT=voice|observe`: connect the first bookmark on start. -//! - `VOELIN_SCREENSHOT=`: save the window after -//! `VOELIN_SCREENSHOT_DELAY` seconds (default 4) and exit. -//! - `VOELIN_WINDOW_SIZE=x`: the window's size (e.g. `390x844` for the -//! phone layout). -//! - `VOELIN_DEMO_UI=1`: sample servers, channels, chat (two pages of older -//! messages answer scrolling up) and streams, no server needed (nothing is -//! stored). -//! - `VOELIN_DEMO_STREAM=1`: a local test stream in the viewer. -//! - `VOELIN_OPEN=[,...]`: open screens on start: `home`, -//! `server` (`server:chat`: its server chat), `settings[:
]` -//! (voice, keybinds, streaming, privacy, appearance, or 0-4), `about`, -//! `share`, `bookmark` (add a server, also `join`; -//! `bookmark:edit` the current one, Advanced open), -//! `emoji` (the picker), `client` (the volume dialog of the first other -//! client once connected), `panel` / `no-panel` (the members panel), -//! `voice` (the voice channel view; on the phone its own screen; -//! `voice:compact` with the smaller stage, not stored), -//! `more` (after `voice` on the phone: the voice screen's More menu, -//! opened once the screen is laid out), -//! `members` (the phone's members page), `notification` (a tapped voice -//! notification), `shared:` (text shared to the app on Android), -//! `pins`, `topics` (the drawers), -//! `topic:` (a topic's messages), `member` (the member card of the -//! first other client), `poke` (the poke dialog: for the contact shown -//! after `friends`, else for the first other client, its card open), -//! `channel-password` (the password dialog of the first locked channel, -//! the sample's Officers; `channel-password:wrong` as after a refused -//! one), `actions` (the last message's actions, as if hovered), -//! `first-run` (home's banner as before the first server, over the -//! sample data), -//! `unread` (the current chat read up to five messages before its end: -//! the "New" divider, scrolled up to; `unread:end` ten messages before, -//! at the list's end, under the bar that counts the new messages), -//! `link-confirm[:]` (the question before a masked link opens, by -//! default the sample's raid board), `link:` (a TeamSpeak link -//! opened: the server dialog filled in from it, or in voice on its -//! server a move into its channel), `watch` (the first stream; with -//! sample data the local test pattern in its place), `theatre` (after -//! `watch`: in theatre mode), `popout` (`watch` in a window of its own), -//! `tab:` (phone layout); `friends[:]`, -//! `messages[:]` (a private chat), `inbox` (offline messages), -//! `library`, `events`, `event-form`, `search[:]`, -//! `notifications` (the bell), `offline` (an offline message), `picture` -//! (a chat picture opened large), `camera` (the settings' camera -//! preview); settings sections also `account`, -//! `profiles` (also `identities`), `devices`, `notifications`, -//! `integrations`, `advanced` (5-10); -//! `studio[:]`: the Stream Studio (with `VOELIN_DEMO_UI` a demo -//! studio from synthetic sources), `studio:window` in a window of its own, -//! `studio:live` going live (also with a screen opened after it: -//! `studio:live,server,voice` shows our stream's card with the studio's -//! picture), `studio:record`, or a dialog: `studio:source`, -//! `studio:audio`, `studio:camera`, `studio:scene`, `studio:settings`. -//! A screenshot also saves the studio's window, or the stream's -//! (`-window.png`), and draws it over the main window. -//! - `VOELIN_AUTOWATCH=1`: watch the first stream that shows up. -//! - `VOELIN_AUTOSHARE=test-pattern`: share the test pattern (accepting -//! everyone) once connected to a TeamSpeak 6 server. +//! Sample data of `VOELIN_DEMO_UI`: servers, channels, people, chats, +//! contacts, notices and pictures, as plain values and as the events a +//! server would send. A front end feeds the events to +//! [`crate::events::handle`], so the screens are filled by the same code +//! that fills them from a real server; nothing here touches the engine, +//! the store or a toolkit. The pictures are PNG bytes the front end saves +//! where it wants. +use std::path::PathBuf; use std::sync::Arc; -use std::time::Duration; -use anyhow::Result; -use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer}; use voelin_core::gateway::Pin; use voelin_core::stream::{StreamInfo, StreamKind}; use voelin_core::{ - BackendInfo, Contact, Event, GatewayUpdate, HistoryMessage, HistorySource, JoinFailure, - ObserveState, OfflineMessageInfo, Relation, SessionState, Source, VoiceState, + BackendInfo, Contact, Event, GatewayUpdate, HistoryMessage, HistorySource, ObserveState, + OfflineMessageInfo, Relation, SessionState, Source, VoiceState, }; use voelin_gateway_proto::{ Action, Attendee, ConfigEntry, ConfigSource, EventInfo, EventKind, EventSpec, PermRule, @@ -79,426 +21,19 @@ use voelin_gateway_proto::{ feature, }; use voelin_model::{ - BannerMode, Capabilities, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, GroupInfo, Presence, + BannerMode, Capabilities, ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, + GroupInfo, Presence, }; use voelin_store::{Bookmark, MessageSource}; -use crate::app::{App, Bridge, MainWindow, MobileTab, Nav, Page, SettingsSection, with_app}; +use crate::bridge::RecordingItem; use crate::settings::LastVoice; -use crate::vm::bridge::RecordingItem; +use crate::social::logic::Social; +use crate::social::{NoticeKind, NoticeRequest, NoticeTarget}; +use crate::state::{AppState, Lines}; -/// The switches read at start. -#[derive(Clone, Debug, Default)] -pub(crate) struct Switches { - pub demo_stream: bool, - pub demo_ui: bool, - pub autoshare: bool, - pub open_client: bool, - open: Vec, - autoconnect: Option, - screenshot: Option, - screenshot_delay: u64, - window_size: Option<(f32, f32)>, -} - -fn flag(name: &str) -> bool { - std::env::var(name).is_ok_and(|v| v == "1") -} - -/// `390x844` → (390, 844). -fn parse_size(text: &str) -> Option<(f32, f32)> { - let (w, h) = text.split_once(['x', 'X'])?; - Some((w.trim().parse().ok()?, h.trim().parse().ok()?)) -} - -impl Switches { - pub fn from_env() -> Self { - let open: Vec = std::env::var("VOELIN_OPEN") - .unwrap_or_default() - .split(',') - .map(|s| s.trim().to_owned()) - .filter(|s| !s.is_empty()) - .collect(); - Self { - demo_stream: flag("VOELIN_DEMO_STREAM"), - demo_ui: flag("VOELIN_DEMO_UI"), - autoshare: std::env::var("VOELIN_AUTOSHARE").is_ok_and(|v| v == "test-pattern"), - open_client: open.iter().any(|o| o == "client"), - open, - autoconnect: std::env::var("VOELIN_AUTOCONNECT").ok(), - screenshot: std::env::var_os("VOELIN_SCREENSHOT").map(Into::into), - screenshot_delay: std::env::var("VOELIN_SCREENSHOT_DELAY") - .ok() - .and_then(|d| d.parse().ok()) - .unwrap_or(4), - window_size: std::env::var("VOELIN_WINDOW_SIZE").ok().as_deref().and_then(parse_size), - } - } -} - -fn section(name: &str) -> SettingsSection { - match name { - "1" | "keybinds" | "ptt" => SettingsSection::Keybinds, - "2" | "streaming" => SettingsSection::Streaming, - "3" | "privacy" => SettingsSection::Privacy, - "4" | "appearance" => SettingsSection::Appearance, - "5" | "account" => SettingsSection::Account, - "6" | "profiles" | "identities" => SettingsSection::Profiles, - "7" | "devices" => SettingsSection::Devices, - "8" | "notifications" => SettingsSection::Notifications, - "9" | "integrations" => SettingsSection::Integrations, - "10" | "advanced" => SettingsSection::Advanced, - _ => SettingsSection::Voice, - } -} - -fn mobile_tab(name: &str) -> MobileTab { - match name { - "home" => MobileTab::Home, - "servers" => MobileTab::Servers, - "activity" => MobileTab::Activity, - "you" => MobileTab::You, - _ => MobileTab::Chat, - } -} - -/// Timers that must live while the window runs. -pub(crate) struct Running { - _screenshot: Option, - _resize: Option, - _scroll: Option, - _more: Option, -} - -/// Apply the switches once the app is set up. -pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running { - if let Some((w, h)) = switches.window_size { - ui.window().set_size(slint::LogicalSize::new(w, h)); - } - if switches.demo_ui { - with_app(demo_ui); - } - match switches.autoconnect.as_deref() { - Some("voice") => { - with_app(|app| app.connect_voice()); - } - Some("observe") => { - with_app(|app| { - if let Some(id) = app.state.current { - app.observe(id); - } - }); - } - _ => {} - } - let nav = ui.global::