diff --git a/crates/voelin-core/src/identity.rs b/crates/voelin-core/src/identity.rs index eea4bbf..4496c00 100644 --- a/crates/voelin-core/src/identity.rs +++ b/crates/voelin-core/src/identity.rs @@ -76,6 +76,8 @@ pub struct Found { pub identity: Identity, /// The file it came from. pub source: PathBuf, + /// The identity the other client uses by default (payload field 5). + pub selected: bool, } impl Found { @@ -171,6 +173,26 @@ pub fn import(store: &Store, found: &[Found]) -> Result, IdentityE .collect() } +/// Store the identities in the official clients' files at `paths` (usually +/// [`discover`]) that the store does not have yet, as the app does when it +/// starts. Files that cannot be read or hold no identity are skipped; none is +/// written. The identities the clients use by default go in first, so on a +/// store without identities the official client's default becomes ours (the +/// first identity) and servers see the same unique id. Returns what was +/// added. +pub fn import_new(store: &Store, paths: &[PathBuf]) -> Result, IdentityError> { + let mut found: Vec = paths.iter().filter_map(|path| read(path).ok()).flatten().collect(); + // Stable: TeamSpeak 6's default before TeamSpeak 3's, as `locations` lists them. + found.sort_by_key(|f| !f.selected); + let outcomes = import(store, &found)?; + Ok(found + .into_iter() + .zip(outcomes) + .filter(|(_, outcome)| matches!(outcome, Imported::Added(_))) + .map(|(f, _)| f) + .collect()) +} + /// The TeamSpeak 3 `.ini` export of an identity, which the official client /// and every other tool reads. pub fn export(nickname: &str, identity: &Identity) -> String { @@ -326,7 +348,7 @@ fn record_identity(record: &[(String, String)], source: &Path) -> Option let identity = Identity::new_from_ts_str(find("identity")?).ok()?; let nickname = find("nickname").or_else(|| find("id")).unwrap_or_default(); let nickname = if nickname.is_empty() { DEFAULT_NICKNAME } else { nickname }.to_owned(); - Some(Found { nickname, identity, source: source.to_owned() }) + Some(Found { nickname, identity, source: source.to_owned(), selected: false }) } /// The identity payload of a `ProtobufItems` item, or `None` if the item is @@ -347,22 +369,27 @@ fn identity_payload(item: &[u8]) -> Option<&[u8]> { payload.filter(|_| kind == Some(IDENTITY_TYPE)) } -/// The export string is field 1 of the identity payload, the nickname field 2. +/// The export string is field 1 of the identity payload, the nickname field 2, +/// and field 5 is 1 on the identity the client uses by default. fn payload_identity(payload: &[u8], source: &Path) -> Option { let mut export = None; let mut nickname = None; + let mut selected = false; let mut wire = Wire { rest: payload }; - while let Some((number, Field::Bytes(bytes))) = wire.next_field() { - match number { - 1 => export = str::from_utf8(bytes).ok(), - 2 => nickname = Some(String::from_utf8_lossy(bytes).into_owned()), + while let Some((number, field)) = wire.next_field() { + match (number, field) { + (1, Field::Bytes(bytes)) => export = str::from_utf8(bytes).ok(), + (2, Field::Bytes(bytes)) => { + nickname = Some(String::from_utf8_lossy(bytes).into_owned()) + } + (5, Field::Var(value)) => selected = value == 1, _ => {} } } let identity = Identity::new_from_ts_str(export?).ok()?; let nickname = nickname.filter(|n| !n.is_empty()).unwrap_or_else(|| DEFAULT_NICKNAME.to_owned()); - Some(Found { nickname, identity, source: source.to_owned() }) + Some(Found { nickname, identity, source: source.to_owned(), selected }) } /// A protobuf field's value. Fixed-width fields carry nothing we read; they @@ -472,13 +499,14 @@ mod tests { } } - /// An item of the shape both clients write, holding `identity`. - fn protobuf_item(identity: &Identity, nickname: &str) -> Vec { + /// An item of the shape both clients write, holding `identity`; `selected` + /// is the client's default. + fn protobuf_item(identity: &Identity, nickname: &str, selected: bool) -> Vec { let export = format!("{}V{}", identity.counter(), identity.key().to_ts_obfuscated()); let mut payload = bytes_field(1, export.as_bytes()); payload.extend(bytes_field(2, nickname.as_bytes())); payload.extend(bytes_field(3, b"a1b2c3d4")); - payload.extend(varint_field(5, 1)); + payload.extend(varint_field(5, u64::from(selected))); let mut item = bytes_field(2, b"4a7b4f46-0000-4000-8000-000000000001"); item.extend(varint_field(TYPE_FIELD, IDENTITY_TYPE)); item.extend(varint_field(9, 1_700_000_000)); @@ -576,7 +604,7 @@ mod tests { mismatched.extend(bytes_field(PAYLOAD_FIELD_BASE, b"not an identity")); for (key, value) in [ ("1", other), - ("2", protobuf_item(&identity, "Имя")), + ("2", protobuf_item(&identity, "Имя", true)), ("3", mismatched), ("Checksum", vec![0; 20]), ] { @@ -588,6 +616,52 @@ mod tests { // A non-ASCII nickname survives. assert_eq!(found[0].nickname, "Имя"); assert_eq!(found[0].uid(), identity.key().to_pub().get_uid()); + assert!(found[0].selected); + fs::remove_dir_all(dir).unwrap(); + } + + /// A `settings.db` as the official clients write it, with these + /// identities. + fn client_database(path: &Path, items: &[(&Identity, &str, bool)]) { + let db = Connection::open(path).unwrap(); + db.execute_batch( + "CREATE TABLE ProtobufItems (timestamp integer unsigned NOT NULL, + key varchar NOT NULL UNIQUE, value varchar)", + ) + .unwrap(); + for (key, (identity, nickname, selected)) in items.iter().enumerate() { + let item = protobuf_item(identity, nickname, *selected); + db.execute("INSERT INTO ProtobufItems VALUES (0, ?1, ?2)", (key.to_string(), item)) + .unwrap(); + } + } + + #[test] + fn launch_import_makes_the_clients_default_ours_and_adds_only_new_ones() { + let dir = temp_dir("launch"); + let ts6 = dir.join("ts6.db"); + let ts3 = dir.join("ts3.db"); + let (spare, main, old) = (synthetic(), synthetic(), synthetic()); + // The default identity is not the first item. + client_database(&ts6, &[(&spare, "Spare", false), (&main, "Main", true)]); + let missing = dir.join("missing.db"); + let store = Store::open_in_memory().unwrap(); + + let added = import_new(&store, &[ts6.clone(), missing.clone()]).unwrap(); + let nicknames: Vec<_> = added.iter().map(|f| f.nickname.as_str()).collect(); + assert_eq!(nicknames, ["Main", "Spare"]); + // The first identity is the app's default: the client's default. + assert_eq!(store.identities().unwrap()[0].uid, main.key().to_pub().get_uid()); + + // The next start finds only what is new. + client_database(&ts3, &[(&old, "Old", true), (&main, "Main", true)]); + let added = import_new(&store, &[ts6, ts3, missing]).unwrap(); + let nicknames: Vec<_> = added.iter().map(|f| f.nickname.as_str()).collect(); + assert_eq!(nicknames, ["Old"]); + let stored = store.identities().unwrap(); + assert_eq!(stored.len(), 3); + // A store that has identities keeps its default. + assert_eq!(stored[0].uid, main.key().to_pub().get_uid()); fs::remove_dir_all(dir).unwrap(); } @@ -599,6 +673,7 @@ mod tests { nickname: nickname.to_owned(), identity: identity.clone(), source: PathBuf::from("test.ini"), + selected: false, }; // The same unique id twice in one batch, then again in a second run. let outcome = import(&store, &[found("first"), found("again")]).unwrap(); diff --git a/crates/voelin-core/src/settings.rs b/crates/voelin-core/src/settings.rs index eb2b7ba..f8c19a2 100644 --- a/crates/voelin-core/src/settings.rs +++ b/crates/voelin-core/src/settings.rs @@ -1115,6 +1115,15 @@ pub static CACHE_FETCH_IMAGES: Key = Key::new( || true, ); +/// Import identities from the official TeamSpeak clients when the app +/// starts ([`crate::identity::import_new`]; their files are only read). +pub static IDENTITY_IMPORT: Key = Key::new( + "identity.import_from_teamspeak", + Kind::Bool, + "Import new identities from the official TeamSpeak clients on start (read only).", + || true, +); + /// How often a file transfer reports its progress (ms); 0: after every /// piece received or sent. pub static FILES_PROGRESS_MS: Key = Key::new( @@ -1290,6 +1299,7 @@ pub fn builtin_keys() -> Vec<&'static dyn Setting> { &STREAM_AUDIO_SOURCES, &CACHE_MAX_MB, &CACHE_FETCH_IMAGES, + &IDENTITY_IMPORT, &FILES_PROGRESS_MS, &PRIVACY_BLOCK_MODE, #[cfg(feature = "media")] diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 113f858..51f2f2b 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -17,7 +17,7 @@ use anyhow::{Context, Result}; use slint::{ComponentHandle, ModelRc, VecModel}; use tokio::runtime::Runtime; use tracing::warn; -use voelin_core::settings::{AUDIO, CRASH_REPORTS, Settings}; +use voelin_core::settings::{AUDIO, CRASH_REPORTS, IDENTITY_IMPORT, Settings}; use voelin_core::stream::StreamInfo; use voelin_core::{ AudioSettings, Command, Engine, Event, History, HistoryMessage, SessionState, VoiceState, @@ -521,6 +521,21 @@ pub fn run(options: RunOptions) -> Result<()> { Ok(history) => engine.send(Command::AttachHistory(history)), Err(e) => warn!(%e, "chat history is not stored this time"), } + let prefs = open_settings(&dir, &options.setting_overrides); + let switches = crate::dev::Switches::from_env(); + // New identities of the official TeamSpeak clients, on every start (not + // with the sample data of VOELIN_DEMO_UI); with none of our own yet, the + // client's default identity becomes ours. + let had_identity = !store.identities()?.is_empty(); + let imported = if prefs.get(&IDENTITY_IMPORT) && !switches.demo_ui { + voelin_core::identity::import_new(&store, &voelin_core::identity::discover()) + .unwrap_or_else(|e| { + warn!(%e, "could not import TeamSpeak identities"); + Vec::new() + }) + } else { + Vec::new() + }; let identity = match store.identities()?.first() { Some(entry) => store.identity(entry.id)?, None => { @@ -530,7 +545,6 @@ pub fn run(options: RunOptions) -> Result<()> { identity } }; - let prefs = open_settings(&dir, &options.setting_overrides); engine.send(Command::AttachSettings(prefs.clone())); let mut settings: UiSettings = (*prefs.get_arc(&UI)).clone(); settings.crash_reports = prefs.get(&CRASH_REPORTS); @@ -560,7 +574,6 @@ pub fn run(options: RunOptions) -> Result<()> { ptt.set(Some(settings.ptt_key.clone())); } let video = Video::new(&dir, settings.openh264); - let switches = crate::dev::Switches::from_env(); let app = App { ui: ui.as_weak(), store, @@ -611,6 +624,9 @@ pub fn run(options: RunOptions) -> Result<()> { if app.demo { app.start_demo(); } + if let Some(text) = crate::servers::imported_status(&imported, had_identity) { + app.set_status(text); + } }); // Engine events -> UI thread, until the event loop is gone. diff --git a/crates/voelin-ui/src/servers.rs b/crates/voelin-ui/src/servers.rs index d405f30..ad456b9 100644 --- a/crates/voelin-ui/src/servers.rs +++ b/crates/voelin-ui/src/servers.rs @@ -3,12 +3,31 @@ use slint::{ComponentHandle, SharedString}; use tracing::warn; +use voelin_core::identity::Found; use voelin_core::{Command, ObserveState, Source, VoiceOptions, VoiceState}; use voelin_store::{Bookmark, QueryConfig, QueryTransport}; use crate::app::{App, BookmarkForm, Bridge}; use crate::vm; +/// What to tell the user about the identities imported from the official +/// clients at start ([`voelin_core::identity::import_new`]), if any. +/// `had_identity`: we had one before, so it stays the default. +pub(crate) fn imported_status(imported: &[Found], had_identity: bool) -> Option { + let first = imported.first()?; + let n = imported.len(); + let names = imported.iter().map(|f| f.nickname.as_str()).collect::>().join(", "); + Some(match (had_identity, n) { + (true, 1) => format!("Imported the identity \u{201c}{names}\u{201d} from TeamSpeak"), + (true, _) => format!("Imported {n} identities from TeamSpeak: {names}"), + (false, 1) => format!("Using your TeamSpeak identity \u{201c}{names}\u{201d}"), + (false, _) => format!( + "Using your TeamSpeak identity \u{201c}{}\u{201d} ({n} imported: {names})", + first.nickname + ), + }) +} + impl App { pub(crate) fn connect_voice(&mut self) { let Some(b) = self.current.and_then(|id| self.bookmark(id)).cloned() else { return }; diff --git a/docs/identity.md b/docs/identity.md index 65ee49f..fa33050 100644 --- a/docs/identity.md +++ b/docs/identity.md @@ -92,7 +92,7 @@ field carries the body. **Type 1, payload field 17, is an identity:** | 4 | bytes | empty in every row seen | | 5 | varint | 1 on exactly one identity: the selected one | -Voelin reads field 1 and field 2 and ignores the rest. The other item types +Voelin reads fields 1, 2 and 5 and ignores the rest. The other item types (0, 2, 3, 4, 5 — connection profiles, bookmarks, server lists and such) are **not** decoded; they are skipped by their type, not by guessing at their contents. @@ -168,6 +168,18 @@ voelinctl identity export [--store ] `--store` defaults to the desktop app's client database, `/voelin/client.db`, so the CLI and the app share identities. +**On every start** the app does the same as `import --auto` +(`voelin_core::identity::import_new`): identities found in the default +locations that the client database does not have yet are added, the files +are only read. The identity the official client uses by default (field 5 of +its payload, below) goes in first, so when Voelin has no identity of its own +yet, that one becomes Voelin's default (the first identity) and servers see +the same unique id; otherwise Voelin's default stays. What was imported is +shown once, in the status line (the toast on desktop), by nickname. The +runtime setting `identity.import_from_teamspeak` (default on) turns it off, +e.g. `--set identity.import_from_teamspeak=false`. The sample data of +`VOELIN_DEMO_UI` never imports. + - **Import** prints what it found as nickname, unique id and security level — all three are public, everything else in an identity is the private key — and stores each one through `voelin-store` under its nickname. An identity