Import the official client's identities on every start

Switching clients should not mean a new unique id. On every start the app
now does what `voelinctl identity import --auto` does: identities in the
official TeamSpeak 3/6 clients' databases that Voelin does not have yet
are added, the files opened read-only and immutable as before. The
identity the official client uses by default (field 5 of its payload, now
read into `Found::selected`) goes in first, so when Voelin has no identity
of its own yet, that one becomes Voelin's default and servers see the same
unique id; an existing 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; the sample data
of VOELIN_DEMO_UI never imports. The settings are now opened before the
identity is chosen. Tested with synthetic databases only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
selikhovandClaude Opus 5.5 committed 2026-10-03 23:18:19 +03:00
1 parent 5ebc6ceda5
commit 3daccb7fd6
5 files changed
+147 -15

No files matched your search

+86 -11
View File
@@ -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<Vec<Imported>, 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<Vec<Found>, IdentityError> {
let mut found: Vec<Found> = 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<Found>
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<Found> {
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<u8> {
/// 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<u8> {
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();
+10
View File
@@ -1115,6 +1115,15 @@ pub static CACHE_FETCH_IMAGES: Key<bool> = 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<bool> = 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<u32> = 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")]
+19 -3
View File
@@ -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.
+19
View File
@@ -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<String> {
let first = imported.first()?;
let n = imported.len();
let names = imported.iter().map(|f| f.nickname.as_str()).collect::<Vec<_>>().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 };