myTeamSpeak: import TeamSpeak 6 contacts; bookmark myTeamSpeak switch

TeamSpeak 6 syncs chat contacts as item class 8 (Item_Data field 25). They
are imported as friends keyed by myTeamSpeak ID, taken from the item or from
the partner's chat ID (@<base32 id>:<homeserver>), the same bytes servers
report as base64 client_myteamspeak_id. The contact list matches them to
clients through the ID each client carries.

Bookmarks gain TeamSpeak's "Enable myTeamSpeak features" switch
(send_mytsid_on_server), stored and imported but not yet sent; what is
still missing is noted in docs/myteamspeak/myteamspeak_server_signin.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-10 17:56:29 +00:00
co-authored by Claude Opus 5.5
parent f78e4fcd66
commit ca86c510b7
31 changed files with 594 additions and 128 deletions
@@ -438,7 +438,7 @@ class SessionController(private val context: Context) {
/** The account the app stays signed in to; its reads block, so they run on [Dispatchers.IO]. */ /** The account the app stays signed in to; its reads block, so they run on [Dispatchers.IO]. */
val myTeamSpeak: MyTeamSpeakLogin = MyTeamSpeakLogin.load() val myTeamSpeak: MyTeamSpeakLogin = MyTeamSpeakLogin.load()
private val importer = TeamSpeakImporter(identityStore, bookmarkStore, settings) private val importer = TeamSpeakImporter(identityStore, bookmarkStore, settings, contactStore)
private val _myTeamSpeakSignedIn = MutableStateFlow(myTeamSpeak.isSignedIn) private val _myTeamSpeakSignedIn = MutableStateFlow(myTeamSpeak.isSignedIn)
val myTeamSpeakSignedIn: StateFlow<Boolean> = _myTeamSpeakSignedIn val myTeamSpeakSignedIn: StateFlow<Boolean> = _myTeamSpeakSignedIn
@@ -504,7 +504,7 @@ class SessionController(private val context: Context) {
fun isImported(item: SyncItem): Boolean = importer.isPresent(item) fun isImported(item: SyncItem): Boolean = importer.isPresent(item)
/** Imports [chosen] out of the account's [all] items, with the identities the chosen bookmarks use. */ /** Imports [chosen] out of the account's [all] items, with the identities the chosen bookmarks use; contacts announce themselves. */
suspend fun importMyTeamSpeak(all: List<SyncItem>, chosen: List<SyncItem>): TeamSpeakImporter.Result = suspend fun importMyTeamSpeak(all: List<SyncItem>, chosen: List<SyncItem>): TeamSpeakImporter.Result =
withContext(Dispatchers.IO) { importer.importSelected(all, chosen) } withContext(Dispatchers.IO) { importer.importSelected(all, chosen) }
.also { .also {
@@ -42,7 +42,8 @@ val BookmarkEditSaver = listSaver<BookmarkEdit?, Any>(
save = { edit -> save = { edit ->
val b = edit?.bookmark ?: return@listSaver emptyList() val b = edit?.bookmark ?: return@listSaver emptyList()
listOf(edit.index, b.label.orEmpty(), b.address.orEmpty(), b.port, b.nickname.orEmpty(), b.password, listOf(edit.index, b.label.orEmpty(), b.address.orEmpty(), b.port, b.nickname.orEmpty(), b.password,
b.identityId, b.channel, b.channelPassword, b.connectOnStartup, b.iconId, b.id) b.identityId, b.channel, b.channelPassword, b.connectOnStartup, b.iconId, b.id,
b.myTeamSpeakFeatures)
}, },
restore = { saved -> restore = { saved ->
if (saved.isEmpty()) null if (saved.isEmpty()) null
@@ -54,6 +55,7 @@ val BookmarkEditSaver = listSaver<BookmarkEdit?, Any>(
connectOnStartup = saved[9] as Boolean connectOnStartup = saved[9] as Boolean
iconId = saved[10] as Long iconId = saved[10] as Long
id = saved[11] as String id = saved[11] as String
myTeamSpeakFeatures = saved[12] as Boolean
}) })
}, },
) )
@@ -73,6 +75,7 @@ fun BookmarkScreen(vm: SessionController, edit: BookmarkEdit, onDone: () -> Unit
var channel by rememberSaveable { mutableStateOf(b.channel.orEmpty()) } var channel by rememberSaveable { mutableStateOf(b.channel.orEmpty()) }
var channelPassword by rememberSaveable { mutableStateOf(b.channelPassword.orEmpty()) } var channelPassword by rememberSaveable { mutableStateOf(b.channelPassword.orEmpty()) }
var connectOnStartup by rememberSaveable { mutableStateOf(b.connectOnStartup) } var connectOnStartup by rememberSaveable { mutableStateOf(b.connectOnStartup) }
var myTeamSpeakFeatures by rememberSaveable { mutableStateOf(b.myTeamSpeakFeatures) }
val save = { val save = {
val (host, port) = SessionController.parseAddress(address) val (host, port) = SessionController.parseAddress(address)
@@ -86,6 +89,7 @@ fun BookmarkScreen(vm: SessionController, edit: BookmarkEdit, onDone: () -> Unit
it.channel = channel.trim() it.channel = channel.trim()
it.channelPassword = channelPassword it.channelPassword = channelPassword
it.connectOnStartup = connectOnStartup it.connectOnStartup = connectOnStartup
it.myTeamSpeakFeatures = myTeamSpeakFeatures
}) })
onDone() onDone()
} }
@@ -120,6 +124,11 @@ fun BookmarkScreen(vm: SessionController, edit: BookmarkEdit, onDone: () -> Unit
Text("Connect on startup", Modifier.weight(1f)) Text("Connect on startup", Modifier.weight(1f))
Switch(connectOnStartup, { connectOnStartup = it }) Switch(connectOnStartup, { connectOnStartup = it })
} }
Row(Modifier.fillMaxWidth().clickable { myTeamSpeakFeatures = !myTeamSpeakFeatures },
verticalAlignment = Alignment.CenterVertically) {
Text("Enable myTeamSpeak features", Modifier.weight(1f))
Switch(myTeamSpeakFeatures, { myTeamSpeakFeatures = it })
}
} }
} }
} }
@@ -117,11 +117,11 @@ fun ContactsScreen(vm: SessionController, editing: String?, onEdit: (String?) ->
val group = contacts.filter { it.type == type }.sortedBy { label(it).lowercase() } val group = contacts.filter { it.type == type }.sortedBy { label(it).lowercase() }
if (group.isEmpty()) continue if (group.isEmpty()) continue
item(key = type) { Section(title) } item(key = type) { Section(title) }
items(group, key = { it.uniqueId }) { contact -> items(group, key = { it.key() }) { contact ->
ListItem( ListItem(
headlineContent = { Text(label(contact), color = typeColor(contact.type)) }, headlineContent = { Text(label(contact), color = typeColor(contact.type)) },
supportingContent = { Text(lastSeen(contact)) }, supportingContent = { Text(lastSeen(contact)) },
modifier = Modifier.clickable { onEdit(contact.uniqueId) }, modifier = Modifier.clickable { onEdit(contact.key()) },
) )
} }
} }
@@ -133,14 +133,16 @@ fun ContactsScreen(vm: SessionController, editing: String?, onEdit: (String?) ->
@Composable @Composable
private fun ContactScreen(vm: SessionController, uniqueId: String, onBack: () -> Unit) { private fun ContactScreen(vm: SessionController, uniqueId: String, onBack: () -> Unit) {
val contacts by vm.contacts.collectAsStateWithLifecycle() val contacts by vm.contacts.collectAsStateWithLifecycle()
val contact = contacts.firstOrNull { it.uniqueId == uniqueId } // A client's unique id may stand for a contact filed under its myTeamSpeak ID.
val key = remember(uniqueId) { vm.contact(uniqueId)?.key() ?: uniqueId }
val contact = contacts.firstOrNull { it.key() == key }
if (contact == null) { if (contact == null) {
LaunchedEffect(Unit) { onBack() } LaunchedEffect(Unit) { onBack() }
return return
} }
// Starts from the stored entry, which may have been seen again since this page opened. // Starts from the stored entry, which may have been seen again since this page opened.
fun edit(change: Contact.() -> Unit) { fun edit(change: Contact.() -> Unit) {
vm.contact(uniqueId)?.let { vm.saveContact(it.apply(change)) } vm.contact(key)?.let { vm.saveContact(it.apply(change)) }
} }
var customName by rememberSaveable(uniqueId) { mutableStateOf(contact.nickname) } var customName by rememberSaveable(uniqueId) { mutableStateOf(contact.nickname) }
var phoneticName by rememberSaveable(uniqueId) { mutableStateOf(contact.phoneticNickname) } var phoneticName by rememberSaveable(uniqueId) { mutableStateOf(contact.phoneticNickname) }
@@ -191,10 +193,11 @@ private fun ContactScreen(vm: SessionController, uniqueId: String, onBack: () ->
Section("Details") Section("Details")
val context = LocalContext.current val context = LocalContext.current
LinkRow("Unique ID", contact.uniqueId) { val idLabel = if (contact.uniqueId.isEmpty()) "myTeamSpeak ID" else "Unique ID"
LinkRow(idLabel, contact.shownId()) {
// The system confirms the copy itself. // The system confirms the copy itself.
context.getSystemService(ClipboardManager::class.java) context.getSystemService(ClipboardManager::class.java)
.setPrimaryClip(ClipData.newPlainText("Unique ID", contact.uniqueId)) .setPrimaryClip(ClipData.newPlainText(idLabel, contact.shownId()))
} }
ListItem(headlineContent = { Text(lastSeen(contact)) }) ListItem(headlineContent = { Text(lastSeen(contact)) })
} }
@@ -208,7 +211,7 @@ private fun ContactScreen(vm: SessionController, uniqueId: String, onBack: () ->
confirmButton = { confirmButton = {
TextButton(onClick = { TextButton(onClick = {
removing = false removing = false
vm.removeContact(uniqueId) vm.removeContact(key)
onBack() onBack()
}) { Text("Remove") } }) { Text("Remove") }
}, },
@@ -251,7 +254,7 @@ private fun ContactDefaultsScreen(vm: SessionController, onBack: () -> Unit) {
} }
} }
private fun label(contact: Contact) = contact.nickname.ifBlank { contact.uniqueId } private fun label(contact: Contact) = contact.label()
private fun lastSeen(contact: Contact): String { private fun lastSeen(contact: Contact): String {
val seen = contact.lastSeen ?: return "Never seen" val seen = contact.lastSeen ?: return "Never seen"
@@ -48,6 +48,7 @@ import eu.lixko.ts3j.client.myts.AccountInfo
import eu.lixko.ts3j.client.myts.MyTeamSpeak import eu.lixko.ts3j.client.myts.MyTeamSpeak
import eu.lixko.ts3j.client.myts.MyTsException import eu.lixko.ts3j.client.myts.MyTsException
import eu.lixko.ts3j.client.teamspeak.SyncItem import eu.lixko.ts3j.client.teamspeak.SyncItem
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import java.io.IOException import java.io.IOException
import java.time.ZoneId import java.time.ZoneId
@@ -79,11 +80,11 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
fun show(account: MyTeamSpeak.Account) { fun show(account: MyTeamSpeak.Account) {
info = account.info() info = account.info()
all = account.items() all = account.items()
rows = all.filter { it !is SyncItem.Folder }.map { rows = all.filter { it !is SyncItem.Folder && (it !is SyncItem.Contact || TeamSpeakImporter.isImportable(it)) }.map {
val imported = vm.isImported(it) val imported = vm.isImported(it)
ItemRow(it, imported, !imported) ItemRow(it, imported, !imported)
} }
message = if (rows.isEmpty()) "The account holds no bookmarks or identities." else null message = if (rows.isEmpty()) "The account holds no bookmarks, identities or contacts." else null
error = false error = false
} }
@@ -134,7 +135,7 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
if (!signedIn) { if (!signedIn) {
item { item {
Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("Sign in to bring over the bookmarks and identities your account synchronises. " + Text("Sign in to bring over the bookmarks, identities and contacts your account synchronises. " +
"The app stays signed in; your password itself is not kept.") "The app stays signed in; your password itself is not kept.")
OutlinedTextField(email, { email = it }, Modifier.fillMaxWidth(), label = { Text("Email") }, OutlinedTextField(email, { email = it }, Modifier.fillMaxWidth(), label = { Text("Email") },
singleLine = true, enabled = !busy, singleLine = true, enabled = !busy,
@@ -189,6 +190,7 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
for ((title, section) in listOf( for ((title, section) in listOf(
"Identities" to rows.filter { it.item is SyncItem.Identity }, "Identities" to rows.filter { it.item is SyncItem.Identity },
"Bookmarks" to rows.filter { it.item is SyncItem.Bookmark }, "Bookmarks" to rows.filter { it.item is SyncItem.Bookmark },
"Contacts" to rows.filter { it.item is SyncItem.Contact },
)) { )) {
if (section.isEmpty()) continue if (section.isEmpty()) continue
item { item {
@@ -219,8 +221,9 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
work { work {
val r = vm.importMyTeamSpeak(all, rows.filter { it.selected }.map { it.item }) val r = vm.importMyTeamSpeak(all, rows.filter { it.selected }.map { it.item })
rows = rows.map { it.copy(imported = vm.isImported(it.item), selected = false) } rows = rows.map { it.copy(imported = vm.isImported(it.item), selected = false) }
message = "Imported ${count(r.identitiesAdded(), "identity", "identities")} and " + message = "Imported ${count(r.identitiesAdded(), "identity", "identities")}, " +
"${count(r.bookmarksAdded(), "bookmark", "bookmarks")}." "${count(r.bookmarksAdded(), "bookmark", "bookmarks")} and " +
"${count(r.contactsAdded(), "contact", "contacts")}."
} }
}, },
enabled = !busy && rows.any { it.selected }, enabled = !busy && rows.any { it.selected },
@@ -253,12 +256,14 @@ private fun Detail(label: String, value: String) {
private fun name(item: SyncItem) = when (item) { private fun name(item: SyncItem) = when (item) {
is SyncItem.Bookmark -> item.name().ifBlank { item.address() } is SyncItem.Bookmark -> item.name().ifBlank { item.address() }
is SyncItem.Identity -> item.name() is SyncItem.Identity -> item.name()
is SyncItem.Contact -> item.customName().ifBlank { item.myTeamSpeakId() }
else -> "" else -> ""
} }
private fun details(item: SyncItem) = when (item) { private fun details(item: SyncItem) = when (item) {
is SyncItem.Bookmark -> Bookmark.hostPort(item.address(), item.port()) is SyncItem.Bookmark -> Bookmark.hostPort(item.address(), item.port())
is SyncItem.Identity -> item.nickname() is SyncItem.Identity -> item.nickname()
is SyncItem.Contact -> item.myTeamSpeakId()
else -> "" else -> ""
} }
@@ -60,7 +60,7 @@ fun SettingsScreen(vm: SessionController, onContacts: () -> Unit, onBack: () ->
"IDENTITY_MANAGER") { page = SettingsPage.IDENTITIES } "IDENTITY_MANAGER") { page = SettingsPage.IDENTITIES }
LinkRow("myTeamSpeak", LinkRow("myTeamSpeak",
if (vm.myTeamSpeak.isSignedIn) "Signed in as ${vm.myTeamSpeak.username()}" if (vm.myTeamSpeak.isSignedIn) "Signed in as ${vm.myTeamSpeak.username()}"
else "Sign in to bring over your synchronised bookmarks and identities", else "Sign in to bring over your synchronised bookmarks, identities and contacts",
"MYTS_ACCOUNT") { page = SettingsPage.MY_TEAMSPEAK } "MYTS_ACCOUNT") { page = SettingsPage.MY_TEAMSPEAK }
} }
} }
@@ -24,6 +24,8 @@ public final class Bookmark {
public String channelPassword = ""; public String channelPassword = "";
/** Connect to this server automatically when the client starts. */ /** Connect to this server automatically when the client starts. */
public boolean connectOnStartup = false; public boolean connectOnStartup = false;
/** TeamSpeak's "Enable myTeamSpeak features" ({@code Bookmark_Data.send_mytsid_on_server}). */
public boolean myTeamSpeakFeatures = true;
/** The server's icon as last seen there, 0 for none or not yet known. */ /** The server's icon as last seen there, 0 for none or not yet known. */
public long iconId = 0; public long iconId = 0;
@@ -46,6 +48,7 @@ public final class Bookmark {
b.channel = channel; b.channel = channel;
b.channelPassword = channelPassword; b.channelPassword = channelPassword;
b.connectOnStartup = connectOnStartup; b.connectOnStartup = connectOnStartup;
b.myTeamSpeakFeatures = myTeamSpeakFeatures;
b.iconId = iconId; b.iconId = iconId;
return b; return b;
} }
@@ -88,6 +88,7 @@ public final class Bookmarks {
bm.channel = p.getProperty(prefix + "channel", ""); bm.channel = p.getProperty(prefix + "channel", "");
bm.channelPassword = p.getProperty(prefix + "channelPassword", ""); bm.channelPassword = p.getProperty(prefix + "channelPassword", "");
bm.connectOnStartup = Boolean.parseBoolean(p.getProperty(prefix + "connectOnStartup", "false")); bm.connectOnStartup = Boolean.parseBoolean(p.getProperty(prefix + "connectOnStartup", "false"));
bm.myTeamSpeakFeatures = Boolean.parseBoolean(p.getProperty(prefix + "myTeamSpeakFeatures", "true"));
bm.iconId = parseLong(p.getProperty(prefix + "iconId")); bm.iconId = parseLong(p.getProperty(prefix + "iconId"));
if (bm.address != null && !bm.address.isBlank()) b.entries.add(bm); if (bm.address != null && !bm.address.isBlank()) b.entries.add(bm);
} }
@@ -110,6 +111,7 @@ public final class Bookmarks {
p.setProperty(prefix + "channel", nullToEmpty(bm.channel)); p.setProperty(prefix + "channel", nullToEmpty(bm.channel));
p.setProperty(prefix + "channelPassword", nullToEmpty(bm.channelPassword)); p.setProperty(prefix + "channelPassword", nullToEmpty(bm.channelPassword));
p.setProperty(prefix + "connectOnStartup", Boolean.toString(bm.connectOnStartup)); p.setProperty(prefix + "connectOnStartup", Boolean.toString(bm.connectOnStartup));
p.setProperty(prefix + "myTeamSpeakFeatures", Boolean.toString(bm.myTeamSpeakFeatures));
p.setProperty(prefix + "iconId", Long.toString(bm.iconId)); p.setProperty(prefix + "iconId", Long.toString(bm.iconId));
} }
try { try {
@@ -8,19 +8,27 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
/** /**
* One entry of the contact list, keyed by the client's unique id. * One entry of the contact list, keyed by the client's unique id — or, for a contact
* brought over from TeamSpeak 6, by a myTeamSpeak ID, which is the person rather
* than one of their identities.
* *
* <p>The fields are exactly the ones the TeamSpeak 3 client keeps for a contact, * <p>The fields are exactly the ones the TeamSpeak 3 client keeps for a contact,
* and {@link #toRecord()} / {@link #parseRecord} use its own {@code Key=Value} * and {@link #toRecord()} / {@link #parseRecord} use its own {@code Key=Value}
* serialisation (the {@code value} column of its {@code Contacts} table), so * serialisation (the {@code value} column of its {@code Contacts} table), so
* records can be exchanged with it as they are. * records can be exchanged with it as they are. The myTeamSpeak ID is an extra
* {@code MyTsId} line, written only when set.
*/ */
public final class Contact { public final class Contact {
/** TeamSpeak writes {@code LastSeen} as an ISO local date-time without zone. */ /** TeamSpeak writes {@code LastSeen} as an ISO local date-time without zone. */
private static final DateTimeFormatter LAST_SEEN = DateTimeFormatter.ISO_LOCAL_DATE_TIME; private static final DateTimeFormatter LAST_SEEN = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
/** Base64 never holds a colon, so these keys cannot pass for a unique id. */
private static final String MYTS_KEY_PREFIX = "myts:";
/** Empty for a contact known only by its {@link #myTeamSpeakId}. */
public final String uniqueId; public final String uniqueId;
/** The {@code client_myteamspeak_id} the contact's clients carry, or empty. */
public final String myTeamSpeakId;
/** Custom name; TeamSpeak seeds it with the nickname the client had when added. */ /** Custom name; TeamSpeak seeds it with the nickname the client had when added. */
public String nickname = ""; public String nickname = "";
public String phoneticNickname = ""; public String phoneticNickname = "";
@@ -42,7 +50,27 @@ public final class Contact {
public String lastSeenServerAddress = ""; public String lastSeenServerAddress = "";
public Contact(String uniqueId) { public Contact(String uniqueId) {
this(uniqueId, "");
}
public Contact(String uniqueId, String myTeamSpeakId) {
this.uniqueId = uniqueId == null ? "" : uniqueId; this.uniqueId = uniqueId == null ? "" : uniqueId;
this.myTeamSpeakId = myTeamSpeakId == null ? "" : myTeamSpeakId;
}
/** What the contact list files the entry under: the unique id, else the myTeamSpeak ID. */
public String key() {
return uniqueId.isEmpty() ? MYTS_KEY_PREFIX + myTeamSpeakId : uniqueId;
}
/** The id shown for the contact: its unique id, else its myTeamSpeak ID. */
public String shownId() {
return uniqueId.isEmpty() ? myTeamSpeakId : uniqueId;
}
/** What the contact list calls the contact: its custom name, else its id. */
public String label() {
return nickname.isBlank() ? shownId() : nickname;
} }
/** The name the contact is shown under, given the nickname it currently carries. */ /** The name the contact is shown under, given the nickname it currently carries. */
@@ -56,12 +84,12 @@ public final class Contact {
} }
public Contact copy() { public Contact copy() {
Contact c = new Contact(uniqueId); Contact c = new Contact(uniqueId, myTeamSpeakId);
c.copyFrom(this); c.copyFrom(this);
return c; return c;
} }
/** Takes over every field but the unique id. */ /** Takes over every field but the ids. */
public void copyFrom(Contact other) { public void copyFrom(Contact other) {
nickname = other.nickname; nickname = other.nickname;
phoneticNickname = other.phoneticNickname; phoneticNickname = other.phoneticNickname;
@@ -115,10 +143,11 @@ public final class Contact {
line(sb, "LastSeen", lastSeen == null ? "" : LAST_SEEN.format(lastSeen)); line(sb, "LastSeen", lastSeen == null ? "" : LAST_SEEN.format(lastSeen));
line(sb, "LastSeenServerName", lastSeenServerName); line(sb, "LastSeenServerName", lastSeenServerName);
line(sb, "LastSeenServerAddress", lastSeenServerAddress); line(sb, "LastSeenServerAddress", lastSeenServerAddress);
if (!myTeamSpeakId.isEmpty()) line(sb, "MyTsId", myTeamSpeakId);
return sb.toString(); return sb.toString();
} }
/** Parses a TeamSpeak contact record, or returns {@code null} when it carries no unique id. */ /** Parses a TeamSpeak contact record, or returns {@code null} when it carries no id at all. */
public static Contact parseRecord(String record) { public static Contact parseRecord(String record) {
if (record == null) return null; if (record == null) return null;
Map<String, String> fields = new LinkedHashMap<>(); Map<String, String> fields = new LinkedHashMap<>();
@@ -127,9 +156,10 @@ public final class Contact {
if (eq > 0) fields.put(line.substring(0, eq).trim(), line.substring(eq + 1)); if (eq > 0) fields.put(line.substring(0, eq).trim(), line.substring(eq + 1));
} }
String uid = fields.getOrDefault("IDS", "").trim(); String uid = fields.getOrDefault("IDS", "").trim();
if (uid.isEmpty()) return null; String myTsId = fields.getOrDefault("MyTsId", "").trim();
if (uid.isEmpty() && myTsId.isEmpty()) return null;
Contact c = new Contact(uid); Contact c = new Contact(uid, myTsId);
c.nickname = fields.getOrDefault("Nickname", ""); c.nickname = fields.getOrDefault("Nickname", "");
c.type = ContactType.fromCode(parseInt(fields.get("Friend"), ContactType.NEUTRAL.code())); c.type = ContactType.fromCode(parseInt(fields.get("Friend"), ContactType.NEUTRAL.code()));
c.automute = parseFlag(fields.get("Automute")); c.automute = parseFlag(fields.get("Automute"));
@@ -15,6 +15,7 @@ import java.util.Collection;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
@@ -31,6 +32,10 @@ import java.util.concurrent.atomic.AtomicBoolean;
* between the two verbatim. On first run the list is seeded from an installed * between the two verbatim. On first run the list is seeded from an installed
* TeamSpeak client's database, when one is found. * TeamSpeak client's database, when one is found.
* *
* <p>A contact known by its myTeamSpeak ID alone stands for every client carrying
* that ID, once the connection {@linkplain #link links} the client to it; lookups by
* unique id then find it like any other.
*
* <p>Safe to use from any thread: lookups are lock-free on a snapshot, and * <p>Safe to use from any thread: lookups are lock-free on a snapshot, and
* mutations are serialised and announced to listeners on the calling thread. * mutations are serialised and announced to listeners on the calling thread.
*/ */
@@ -49,7 +54,9 @@ public final class ContactStore {
} }
private final File file; private final File file;
private final Map<String, Contact> byUid = new LinkedHashMap<>(); private final Map<String, Contact> byKey = new LinkedHashMap<>();
/** Unique id → myTeamSpeak ID of the clients seen so far, which only lives as long as the client. */
private final Map<String, String> myTsIds = new ConcurrentHashMap<>();
/** Immutable snapshot for readers, replaced under the lock after every change. */ /** Immutable snapshot for readers, replaced under the lock after every change. */
private volatile List<Contact> snapshot = List.of(); private volatile List<Contact> snapshot = List.of();
private final List<Listener> listeners = new CopyOnWriteArrayList<>(); private final List<Listener> listeners = new CopyOnWriteArrayList<>();
@@ -96,9 +103,9 @@ public final class ContactStore {
if (c != null) parsed.add(c); if (c != null) parsed.add(c);
} }
synchronized (this) { synchronized (this) {
byUid.clear(); byKey.clear();
for (Contact c : parsed) byUid.put(c.uniqueId, c); for (Contact c : parsed) byKey.put(c.key(), c);
snapshot = List.copyOf(byUid.values()); snapshot = List.copyOf(byKey.values());
} }
} }
@@ -132,14 +139,33 @@ public final class ContactStore {
return snapshot; return snapshot;
} }
/**
* The contact a client is filed under: by its unique id, else by the myTeamSpeak ID it was
* {@linkplain #link linked} with. A {@link Contact#key()} finds its contact too.
*/
public Contact find(String uniqueId) { public Contact find(String uniqueId) {
if (uniqueId == null || uniqueId.isEmpty()) return null; if (uniqueId == null || uniqueId.isEmpty()) return null;
for (Contact c : snapshot) { for (Contact c : snapshot) {
if (c.uniqueId.equals(uniqueId)) return c; if (c.uniqueId.equals(uniqueId) || c.key().equals(uniqueId)) return c;
}
return findByMyTeamSpeakId(myTsIds.get(uniqueId));
}
public Contact findByMyTeamSpeakId(String myTeamSpeakId) {
if (myTeamSpeakId == null || myTeamSpeakId.isEmpty()) return null;
for (Contact c : snapshot) {
if (c.myTeamSpeakId.equals(myTeamSpeakId)) return c;
} }
return null; return null;
} }
/** Notes which myTeamSpeak ID a client carries (empty for none), so {@link #find} can match it. */
public void link(String uniqueId, String myTeamSpeakId) {
if (uniqueId == null || uniqueId.isEmpty()) return;
if (myTeamSpeakId == null || myTeamSpeakId.isEmpty()) myTsIds.remove(uniqueId);
else myTsIds.put(uniqueId, myTeamSpeakId);
}
/** The type a client is filed under, {@code null} when it is not a contact. */ /** The type a client is filed under, {@code null} when it is not a contact. */
public ContactType typeOf(String uniqueId) { public ContactType typeOf(String uniqueId) {
Contact c = find(uniqueId); Contact c = find(uniqueId);
@@ -163,35 +189,38 @@ public final class ContactStore {
public Contact add(String uniqueId, String nickname, ContactType type, ContactDefaults defaults) { public Contact add(String uniqueId, String nickname, ContactType type, ContactDefaults defaults) {
Contact contact; Contact contact;
synchronized (this) { synchronized (this) {
contact = byUid.get(uniqueId); contact = find(uniqueId);
if (contact == null) { if (contact == null) {
contact = new Contact(uniqueId); contact = new Contact(uniqueId);
contact.nickname = nickname == null ? "" : nickname; contact.nickname = nickname == null ? "" : nickname;
contact.applyDefaults(defaults.of(type)); contact.applyDefaults(defaults.of(type));
byUid.put(uniqueId, contact); byKey.put(contact.key(), contact);
} }
contact.type = type; contact.type = type;
snapshot = List.copyOf(byUid.values()); snapshot = List.copyOf(byKey.values());
} }
changed(); changed();
return contact; return contact;
} }
/** Stores an edited contact, replacing any entry with the same unique id. */ /** Stores an edited contact, replacing any entry with the same {@link Contact#key()}. */
public void put(Contact contact) { public void put(Contact contact) {
synchronized (this) { synchronized (this) {
Contact existing = byUid.get(contact.uniqueId); Contact existing = byKey.get(contact.key());
if (existing != null && existing != contact) existing.copyFrom(contact); if (existing != null && existing != contact) existing.copyFrom(contact);
else byUid.put(contact.uniqueId, contact); else byKey.put(contact.key(), contact);
snapshot = List.copyOf(byUid.values()); snapshot = List.copyOf(byKey.values());
} }
changed(); changed();
} }
/** Removes the contact {@link #find} gives for the id. */
public void remove(String uniqueId) { public void remove(String uniqueId) {
synchronized (this) { synchronized (this) {
if (byUid.remove(uniqueId) == null) return; Contact contact = find(uniqueId);
snapshot = List.copyOf(byUid.values()); if (contact == null) return;
byKey.remove(contact.key());
snapshot = List.copyOf(byKey.values());
} }
changed(); changed();
} }
@@ -199,9 +228,9 @@ public final class ContactStore {
/** Takes over a whole list, e.g. one read from the TeamSpeak client. */ /** Takes over a whole list, e.g. one read from the TeamSpeak client. */
public void replaceAll(Collection<Contact> contacts) { public void replaceAll(Collection<Contact> contacts) {
synchronized (this) { synchronized (this) {
byUid.clear(); byKey.clear();
for (Contact c : contacts) byUid.put(c.uniqueId, c); for (Contact c : contacts) byKey.put(c.key(), c);
snapshot = List.copyOf(byUid.values()); snapshot = List.copyOf(byKey.values());
} }
changed(); changed();
} }
@@ -216,9 +245,9 @@ public final class ContactStore {
int added = 0; int added = 0;
synchronized (this) { synchronized (this) {
for (Contact c : contacts) { for (Contact c : contacts) {
if (byUid.put(c.uniqueId, c) == null) added++; if (byKey.put(c.key(), c) == null) added++;
} }
snapshot = List.copyOf(byUid.values()); snapshot = List.copyOf(byKey.values());
} }
changed(); changed();
return added; return added;
@@ -12,27 +12,8 @@ import java.time.Instant;
*/ */
public record AccountInfo(String username, String userId, String uuid, Instant created) { public record AccountInfo(String username, String userId, String uuid, Instant created) {
private static final String BASE32 = "abcdefghijklmnopqrstuvwxyz234567";
static AccountInfo of(String username, String uuid, byte[] userId, long createdSeconds) { static AccountInfo of(String username, String uuid, byte[] userId, long createdSeconds) {
return new AccountInfo(username, userId == null ? "" : base32(userId), uuid, return new AccountInfo(username, userId == null ? "" : MyTsId.base32(userId), uuid,
createdSeconds > 0 ? Instant.ofEpochSecond(createdSeconds) : null); createdSeconds > 0 ? Instant.ofEpochSecond(createdSeconds) : null);
} }
/** RFC 4648 base32, lowercase and unpadded. */
static String base32(byte[] data) {
StringBuilder out = new StringBuilder((data.length * 8 + 4) / 5);
int buffer = 0, bits = 0;
for (byte b : data) {
buffer = (buffer << 8) | (b & 0xff);
bits += 8;
while (bits >= 5) {
out.append(BASE32.charAt((buffer >> (bits - 5)) & 31));
bits -= 5;
}
buffer &= (1 << bits) - 1;
}
if (bits > 0) out.append(BASE32.charAt((buffer << (5 - bits)) & 31));
return out.toString();
}
} }
@@ -13,7 +13,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
* Reads the bookmarks and identities a myTeamSpeak account synchronises, the way * Reads the bookmarks, identities and contacts a myTeamSpeak account synchronises, the way
* the official client pulls them on a fresh install: sign in, ask for every item * the official client pulls them on a fresh install: sign in, ask for every item
* of the wanted classes against an empty local state, decrypt them, and sign out. * of the wanted classes against an empty local state, decrypt them, and sign out.
* Nothing is ever written to the account. Staying signed in is {@link MyTeamSpeakLogin}'s. * Nothing is ever written to the account. Staying signed in is {@link MyTeamSpeakLogin}'s.
@@ -41,11 +41,16 @@ public final class MyTeamSpeak {
public long bookmarks() { public long bookmarks() {
return items.stream().filter(SyncItem.Bookmark.class::isInstance).count(); return items.stream().filter(SyncItem.Bookmark.class::isInstance).count();
} }
public long contacts() {
return items.stream().filter(SyncItem.Contact.class::isInstance).count();
}
} }
private static final String NO_VERSION = "00000000-0000-0000-0000-000000000000"; private static final String NO_VERSION = "00000000-0000-0000-0000-000000000000";
private static final int SYNC_VERSION_1_1 = 1; private static final int SYNC_VERSION_1_1 = 1;
private static final int[] ITEM_CLASSES = {0 /* BOOKMARK */, 1 /* IDENTITY */, 6 /* ITEM_FOLDER */}; private static final int CONTACTS = 8;
private static final int[] ITEM_CLASSES = {0 /* BOOKMARK */, 1 /* IDENTITY */, 6 /* ITEM_FOLDER */, CONTACTS};
private static final int LOGIN_OK = 200; private static final int LOGIN_OK = 200;
private static final int LOGIN_OFFLINE = 201; private static final int LOGIN_OFFLINE = 201;
@@ -159,7 +164,7 @@ public final class MyTeamSpeak {
ProtobufReader reply = new ProtobufReader( ProtobufReader reply = new ProtobufReader(
transport.call("synchronization", "requestServerItems", request.toByteArray())); transport.call("synchronization", "requestServerItems", request.toByteArray()));
List<byte[]> frames = new ArrayList<>(); List<Frame> frames = new ArrayList<>();
int status = 0; int status = 0;
while (reply.next()) { while (reply.next()) {
switch (reply.fieldNumber()) { switch (reply.fieldNumber()) {
@@ -173,13 +178,8 @@ public final class MyTeamSpeak {
} }
List<SyncItem> items = new ArrayList<>(); List<SyncItem> items = new ArrayList<>();
for (byte[] frame : frames) { for (Frame frame : frames) {
SyncItem item; SyncItem item = decode(frame, itemKey);
try {
item = SyncItemDecoder.decode(MyTsCrypto.decryptItem(frame, itemKey));
} catch (GeneralSecurityException e) {
throw new MyTsException("Could not decrypt the account's items", e);
}
if (item != null) items.add(item); if (item != null) items.add(item);
} }
return SyncOrder.sorted(items); return SyncOrder.sorted(items);
@@ -191,7 +191,7 @@ public final class MyTeamSpeak {
* and not all of them are encrypted (add-on flags come in the clear), so only the * and not all of them are encrypted (add-on flags come in the clear), so only the
* wanted classes are kept. * wanted classes are kept.
*/ */
private static void collectFrames(ProtobufReader itemClass, List<byte[]> frames) throws IOException { private static void collectFrames(ProtobufReader itemClass, List<Frame> frames) throws IOException {
int classId = 0; int classId = 0;
List<byte[]> blobs = new ArrayList<>(); List<byte[]> blobs = new ArrayList<>();
while (itemClass.next()) { while (itemClass.next()) {
@@ -205,7 +205,30 @@ public final class MyTeamSpeak {
} }
} }
for (int wanted : ITEM_CLASSES) { for (int wanted : ITEM_CLASSES) {
if (wanted == classId) frames.addAll(blobs); if (wanted != classId) continue;
for (byte[] blob : blobs) frames.add(new Frame(classId, blob));
}
}
private record Frame(int itemClass, byte[] blob) {
}
/**
* Contacts are TeamSpeak 6's and were never seen in an account, so one that does not
* decrypt is taken for plaintext, like add-on flags, or else left out — not allowed to
* fail the bookmarks and identities.
*/
private static SyncItem decode(Frame frame, byte[] itemKey) throws IOException, MyTsException {
try {
return SyncItemDecoder.decode(MyTsCrypto.decryptItem(frame.blob(), itemKey));
} catch (GeneralSecurityException e) {
if (frame.itemClass() != CONTACTS) throw new MyTsException("Could not decrypt the account's items", e);
}
try {
SyncItem item = SyncItemDecoder.decode(frame.blob());
return item instanceof SyncItem.Contact ? item : null;
} catch (IOException | RuntimeException notPlaintext) {
return null;
} }
} }
@@ -0,0 +1,60 @@
package eu.lixko.ts3j.client.myts;
import java.util.Base64;
/**
* The two spellings of a myTeamSpeak ID. Servers carry it as {@code client_myteamspeak_id},
* standard base64; TeamSpeak chat puts the same bytes, lowercase base32, in the localpart of
* the account's Matrix user ID ({@code @<base32>:<homeserver>}).
*/
public final class MyTsId {
private static final String BASE32 = "abcdefghijklmnopqrstuvwxyz234567";
private MyTsId() {
}
/** The myTeamSpeak ID behind a TeamSpeak chat user ID, or empty when it is not one. */
public static String fromChatId(String chatId) {
if (chatId == null || !chatId.startsWith("@")) return "";
int colon = chatId.indexOf(':');
if (colon < 2) return "";
byte[] id = base32Decode(chatId.substring(1, colon));
return id == null ? "" : Base64.getEncoder().encodeToString(id);
}
/** RFC 4648 base32, lowercase and unpadded. */
static String base32(byte[] data) {
StringBuilder out = new StringBuilder((data.length * 8 + 4) / 5);
int buffer = 0, bits = 0;
for (byte b : data) {
buffer = (buffer << 8) | (b & 0xff);
bits += 8;
while (bits >= 5) {
out.append(BASE32.charAt((buffer >> (bits - 5)) & 31));
bits -= 5;
}
buffer &= (1 << bits) - 1;
}
if (bits > 0) out.append(BASE32.charAt((buffer << (5 - bits)) & 31));
return out.toString();
}
/** The inverse of {@link #base32}, either case; {@code null} for anything else. */
static byte[] base32Decode(String text) {
byte[] out = new byte[text.length() * 5 / 8];
int buffer = 0, bits = 0, n = 0;
for (int i = 0; i < text.length(); i++) {
int value = BASE32.indexOf(Character.toLowerCase(text.charAt(i)));
if (value < 0) return null;
buffer = (buffer << 5) | value;
bits += 5;
if (bits >= 8) {
out[n++] = (byte) (buffer >> (bits - 8));
bits -= 8;
buffer &= (1 << bits) - 1;
}
}
return out;
}
}
@@ -11,6 +11,8 @@ public final class ClientEntry {
/** How text-to-speech should say the nickname ({@code client_nickname_phonetic}). */ /** How text-to-speech should say the nickname ({@code client_nickname_phonetic}). */
public volatile String phoneticNickname = ""; public volatile String phoneticNickname = "";
public volatile String uniqueId = ""; public volatile String uniqueId = "";
/** {@code client_myteamspeak_id}: the client's myTeamSpeak account, empty when it shares none. */
public volatile String myTeamSpeakId = "";
public volatile int databaseId; public volatile int databaseId;
public volatile int type; // 0 = normal voice client, 1 = server-query public volatile int type; // 0 = normal voice client, 1 = server-query
public volatile int talkPower; public volatile int talkPower;
@@ -47,6 +47,7 @@ final class ConnectionEventHandler implements TS3Listener {
c.away = e.isClientAway(); c.away = e.isClientAway();
c.awayMessage = TeamspeakConnection.orEmpty(e.get("client_away_message")); c.awayMessage = TeamspeakConnection.orEmpty(e.get("client_away_message"));
c.uniqueId = TeamspeakConnection.orEmpty(e.getUniqueClientIdentifier()); c.uniqueId = TeamspeakConnection.orEmpty(e.getUniqueClientIdentifier());
c.myTeamSpeakId = TeamspeakConnection.orEmpty(e.get("client_myteamspeak_id"));
c.avatarFlag = TeamspeakConnection.orEmpty(e.get("client_flag_avatar")); c.avatarFlag = TeamspeakConnection.orEmpty(e.get("client_flag_avatar"));
c.country = TeamspeakConnection.orEmpty(e.get("client_country")); c.country = TeamspeakConnection.orEmpty(e.get("client_country"));
c.databaseId = e.getClientDatabaseId(); c.databaseId = e.getClientDatabaseId();
@@ -351,6 +352,10 @@ final class ConnectionEventHandler implements TS3Listener {
c.channelCommander = e.getBoolean("client_is_channel_commander"); c.channelCommander = e.getBoolean("client_is_channel_commander");
if (reported(e, "client_flag_avatar")) c.avatarFlag = TeamspeakConnection.orEmpty(e.get("client_flag_avatar")); if (reported(e, "client_flag_avatar")) c.avatarFlag = TeamspeakConnection.orEmpty(e.get("client_flag_avatar"));
if (reported(e, "client_country")) c.country = TeamspeakConnection.orEmpty(e.get("client_country")); if (reported(e, "client_country")) c.country = TeamspeakConnection.orEmpty(e.get("client_country"));
if (reported(e, "client_myteamspeak_id")) {
c.myTeamSpeakId = TeamspeakConnection.orEmpty(e.get("client_myteamspeak_id"));
if (!c.self && !c.isQuery()) conn.applyContact(c);
}
if (has(e, "client_unread_messages")) { if (has(e, "client_unread_messages")) {
int before = c.unreadMessages; int before = c.unreadMessages;
c.unreadMessages = safeInt(e, "client_unread_messages"); c.unreadMessages = safeInt(e, "client_unread_messages");
@@ -1312,9 +1312,11 @@ public final class TeamspeakConnection implements TS3Listener {
/** /**
* Applies a client's contact entry to its playback — the automatic mute and the * Applies a client's contact entry to its playback — the automatic mute and the
* volume modifier — and records the sighting. Called when the client appears. * volume modifier — and records the sighting. Called when the client appears, which
* is also when its myTeamSpeak ID can first match a contact.
*/ */
void applyContact(ClientEntry client) { void applyContact(ClientEntry client) {
contacts.link(client.uniqueId, client.myTeamSpeakId);
Contact contact = applyContactPlayback(client); Contact contact = applyContactPlayback(client);
if (contact != null) contacts.markSeen(client.uniqueId, model.getServerName(), serverHost + ":" + serverPort); if (contact != null) contacts.markSeen(client.uniqueId, model.getServerName(), serverHost + ":" + serverPort);
} }
@@ -1,10 +1,13 @@
package eu.lixko.ts3j.client.teamspeak; package eu.lixko.ts3j.client.teamspeak;
import eu.lixko.ts3j.client.myts.MyTsId;
/** /**
* One entry of the TeamSpeak 3 client's synchronised item store — the data that * One entry of the TeamSpeak 3 client's synchronised item store — the data that
* a myTeamSpeak account syncs between installations. Since client 3.1 the * a myTeamSpeak account syncs between installations. Since client 3.1 the
* bookmarks and identities of every installation live there, signed in or not. * bookmarks and identities of every installation live there, signed in or not.
* Whisper lists, hotkey profiles and the other item classes are not modelled. * TeamSpeak 6 adds contacts. Whisper lists, hotkey profiles and the other item
* classes are not modelled.
*/ */
public sealed interface SyncItem { public sealed interface SyncItem {
@@ -33,10 +36,28 @@ public sealed interface SyncItem {
* in some myTeamSpeak items); empty for the default * in some myTeamSpeak items); empty for the default
* @param defaultChannel channel path to join, "/"-separated; empty for the server default * @param defaultChannel channel path to join, "/"-separated; empty for the server default
* @param defaultChannelId the same channel by id, {@code 0} when unknown * @param defaultChannelId the same channel by id, {@code 0} when unknown
* @param myTeamSpeakFeatures "Enable myTeamSpeak features" ({@code send_mytsid_on_server})
*/ */
record Bookmark(String uuid, String parentUuid, String previousUuid, String name, String address, int port, record Bookmark(String uuid, String parentUuid, String previousUuid, String name, String address, int port,
String nickname, String phoneticNickname, String identityUuid, String nickname, String phoneticNickname, String identityUuid,
String serverPassword, String defaultChannel, String defaultChannelPassword, String serverPassword, String defaultChannel, String defaultChannelPassword,
long defaultChannelId, boolean autoconnect) implements SyncItem { long defaultChannelId, boolean autoconnect, boolean myTeamSpeakFeatures) implements SyncItem {
}
/**
* What TeamSpeak 6 keeps about a chat: a custom name and how it is filed. One exists only
* once something about the chat was customised, so it is not a whole contact list.
*
* @param myTsId the partner's myTeamSpeak ID as servers carry it; TeamSpeak 6 leaves it empty
* @param chatMemberId the partner's TeamSpeak chat (Matrix) user ID, for a direct chat
*/
record Contact(String uuid, String parentUuid, String previousUuid, String customName, String category,
boolean favourite, boolean directChat, String myTsId, String chatMemberId) implements SyncItem {
/** The partner's myTeamSpeak ID, read out of the chat ID when the item names none; empty for a group chat. */
public String myTeamSpeakId() {
if (!myTsId.isBlank()) return myTsId;
return directChat ? MyTsId.fromChatId(chatMemberId) : "";
}
} }
} }
@@ -38,7 +38,7 @@ public final class SyncItemDecoder {
case 4 -> deleted = r.readVarint() == ITEM_DELETED; case 4 -> deleted = r.readVarint() == ITEM_DELETED;
case 7 -> parent = r.readString(); case 7 -> parent = r.readString();
case 8 -> previous = r.readString(); case 8 -> previous = r.readString();
case 16, 17, 22 -> { case 16, 17, 22, 25 -> {
contentField = r.fieldNumber(); contentField = r.fieldNumber();
content = r.readMessage(); content = r.readMessage();
} }
@@ -50,6 +50,7 @@ public final class SyncItemDecoder {
return switch (contentField) { return switch (contentField) {
case 16 -> bookmark(uuid, parent, previous, content); case 16 -> bookmark(uuid, parent, previous, content);
case 17 -> identity(uuid, parent, previous, content); case 17 -> identity(uuid, parent, previous, content);
case 25 -> contact(uuid, parent, previous, content);
default -> folder(uuid, parent, previous, content); default -> folder(uuid, parent, previous, content);
}; };
} }
@@ -59,7 +60,7 @@ public final class SyncItemDecoder {
String serverPassword = "", channel = "", channelPassword = ""; String serverPassword = "", channel = "", channelPassword = "";
int port = 9987; int port = 9987;
long channelId = 0; long channelId = 0;
boolean autoconnect = false; boolean autoconnect = false, myTeamSpeakFeatures = false;
while (r.next()) { while (r.next()) {
switch (r.fieldNumber()) { switch (r.fieldNumber()) {
case 1 -> name = r.readString(); case 1 -> name = r.readString();
@@ -73,11 +74,12 @@ public final class SyncItemDecoder {
case 9 -> channelPassword = r.readString(); case 9 -> channelPassword = r.readString();
case 10 -> channelId = r.readVarint(); case 10 -> channelId = r.readVarint();
case 14 -> autoconnect = r.readBool(); case 14 -> autoconnect = r.readBool();
case 22 -> myTeamSpeakFeatures = r.readBool();
default -> r.skip(); default -> r.skip();
} }
} }
return new SyncItem.Bookmark(uuid, parent, previous, name, address, port, nickname, phonetic, identity, return new SyncItem.Bookmark(uuid, parent, previous, name, address, port, nickname, phonetic, identity,
serverPassword, channel, channelPassword, channelId, autoconnect); serverPassword, channel, channelPassword, channelId, autoconnect, myTeamSpeakFeatures);
} }
private static SyncItem.Identity identity(String uuid, String parent, String previous, ProtobufReader r) throws IOException { private static SyncItem.Identity identity(String uuid, String parent, String previous, ProtobufReader r) throws IOException {
@@ -96,6 +98,23 @@ public final class SyncItemDecoder {
return new SyncItem.Identity(uuid, parent, previous, identity, name, nickname, phonetic, isDefault); return new SyncItem.Identity(uuid, parent, previous, identity, name, nickname, phonetic, isDefault);
} }
private static SyncItem.Contact contact(String uuid, String parent, String previous, ProtobufReader r) throws IOException {
String name = "", category = "", myTsId = "", memberId = "";
boolean favourite = false, direct = false;
while (r.next()) {
switch (r.fieldNumber()) {
case 2 -> name = r.readString();
case 3 -> category = r.readString();
case 5 -> favourite = r.readBool();
case 6 -> direct = r.readBool();
case 7 -> myTsId = r.readString();
case 8 -> memberId = r.readString();
default -> r.skip();
}
}
return new SyncItem.Contact(uuid, parent, previous, name, category, favourite, direct, myTsId, memberId);
}
private static SyncItem.Folder folder(String uuid, String parent, String previous, ProtobufReader r) throws IOException { private static SyncItem.Folder folder(String uuid, String parent, String previous, ProtobufReader r) throws IOException {
String name = ""; String name = "";
while (r.next()) { while (r.next()) {
@@ -5,6 +5,9 @@ import eu.lixko.ts3j.client.config.Bookmarks;
import eu.lixko.ts3j.client.config.IdentityEntry; import eu.lixko.ts3j.client.config.IdentityEntry;
import eu.lixko.ts3j.client.config.IdentityStore; import eu.lixko.ts3j.client.config.IdentityStore;
import eu.lixko.ts3j.client.config.Settings; import eu.lixko.ts3j.client.config.Settings;
import eu.lixko.ts3j.client.contacts.Contact;
import eu.lixko.ts3j.client.contacts.ContactStore;
import eu.lixko.ts3j.client.contacts.ContactType;
import com.github.manevolent.ts3j.identity.LocalIdentity; import com.github.manevolent.ts3j.identity.LocalIdentity;
import java.io.File; import java.io.File;
@@ -21,15 +24,18 @@ import java.util.Set;
/** /**
* Carries the TeamSpeak 3 client's synchronised bookmarks and identities — * Carries the TeamSpeak 3 client's synchronised bookmarks and identities —
* from its local store or a myTeamSpeak account — over into this client's stores. Importing is additive and idempotent: an identity * from its local store or a myTeamSpeak account — over into this client's stores,
* already present (same unique ID) or a bookmark already present (same label, * and TeamSpeak 6's contacts along with them when given a contact list. Importing
* address and port) is left alone, and bookmarks are wired to the identities * is additive and idempotent: an identity already present (same unique ID), a
* they referenced in TeamSpeak. * bookmark already present (same label, address and port) or a contact already
* present (same myTeamSpeak ID) is left alone, and bookmarks are wired to the
* identities they referenced in TeamSpeak.
*/ */
public final class TeamSpeakImporter { public final class TeamSpeakImporter {
/** What an import did; {@code known} counts the items that were already there. */ /** What an import did; {@code known} counts the items that were already there. */
public record Result(int identitiesAdded, int identitiesKnown, int bookmarksAdded, int bookmarksKnown) { public record Result(int identitiesAdded, int identitiesKnown, int bookmarksAdded, int bookmarksKnown,
int contactsAdded, int contactsKnown) {
public int identities() { public int identities() {
return identitiesAdded + identitiesKnown; return identitiesAdded + identitiesKnown;
} }
@@ -42,11 +48,26 @@ public final class TeamSpeakImporter {
private final IdentityStore identities; private final IdentityStore identities;
private final Bookmarks bookmarks; private final Bookmarks bookmarks;
private final Settings settings; private final Settings settings;
/** Where contacts go; {@code null} leaves them out. */
private final ContactStore contacts;
public TeamSpeakImporter(IdentityStore identities, Bookmarks bookmarks, Settings settings) { public TeamSpeakImporter(IdentityStore identities, Bookmarks bookmarks, Settings settings) {
this(identities, bookmarks, settings, null);
}
public TeamSpeakImporter(IdentityStore identities, Bookmarks bookmarks, Settings settings, ContactStore contacts) {
this.identities = identities; this.identities = identities;
this.bookmarks = bookmarks; this.bookmarks = bookmarks;
this.settings = settings; this.settings = settings;
this.contacts = contacts;
}
/**
* Whether a contact can be brought over: only a direct chat says whose it is, and only a
* myTeamSpeak ID can be matched against clients on a server.
*/
public static boolean isImportable(SyncItem.Contact contact) {
return !contact.myTeamSpeakId().isEmpty();
} }
/** Imports the identities only. */ /** Imports the identities only. */
@@ -64,7 +85,7 @@ public final class TeamSpeakImporter {
return importAll(TeamSpeakSettingsDb.readSyncItems(db)); return importAll(TeamSpeakSettingsDb.readSyncItems(db));
} }
/** Imports every identity and bookmark among items read elsewhere, such as from a myTeamSpeak account. */ /** Imports every identity, bookmark and contact among items read elsewhere, such as from a myTeamSpeak account. */
public Result importAll(List<SyncItem> items) throws IOException { public Result importAll(List<SyncItem> items) throws IOException {
return importItems(items, true, false); return importItems(items, true, false);
} }
@@ -84,9 +105,15 @@ public final class TeamSpeakImporter {
return importItems(new ArrayList<>(selection), true, false); return importItems(new ArrayList<>(selection), true, false);
} }
/** Whether the item is here already: an identity with the same key, or a bookmark with the same label and address. */ /**
* Whether the item is here already: an identity with the same key, a bookmark with the same
* label and address, or a contact with the same myTeamSpeak ID.
*/
public boolean isPresent(SyncItem item) { public boolean isPresent(SyncItem item) {
if (item instanceof SyncItem.Bookmark bookmark) return find(bookmark) != null; if (item instanceof SyncItem.Bookmark bookmark) return find(bookmark) != null;
if (item instanceof SyncItem.Contact contact) {
return contacts != null && contacts.findByMyTeamSpeakId(contact.myTeamSpeakId()) != null;
}
if (!(item instanceof SyncItem.Identity identity)) return false; if (!(item instanceof SyncItem.Identity identity)) return false;
try { try {
return identities.byUniqueId(IdentityStore.parseIdentityString(identity.identity()).getUid().toBase64()) != null; return identities.byUniqueId(IdentityStore.parseIdentityString(identity.identity()).getUid().toBase64()) != null;
@@ -157,7 +184,7 @@ public final class TeamSpeakImporter {
} }
} }
if (settingsChanged) settings.save(); if (settingsChanged) settings.save();
if (!withBookmarks) return new Result(identitiesAdded, identitiesKnown, 0, 0); if (!withBookmarks) return new Result(identitiesAdded, identitiesKnown, 0, 0, 0, 0);
for (SyncItem.Bookmark bookmark : syncBookmarks) { for (SyncItem.Bookmark bookmark : syncBookmarks) {
if (find(bookmark) != null) { if (find(bookmark) != null) {
@@ -172,7 +199,32 @@ public final class TeamSpeakImporter {
bookmarksAdded++; bookmarksAdded++;
} }
if (bookmarksAdded > 0) bookmarks.save(); if (bookmarksAdded > 0) bookmarks.save();
return new Result(identitiesAdded, identitiesKnown, bookmarksAdded, bookmarksKnown);
int contactsAdded = 0, contactsKnown = 0;
if (contacts != null) {
Map<String, Contact> added = new LinkedHashMap<>();
for (SyncItem item : items) {
if (!(item instanceof SyncItem.Contact sync) || !isImportable(sync)) continue;
if (isPresent(sync) || added.containsKey(sync.myTeamSpeakId())) {
contactsKnown++;
} else {
added.put(sync.myTeamSpeakId(), toContact(sync));
contactsAdded++;
}
}
if (!added.isEmpty()) contacts.merge(added.values());
}
return new Result(identitiesAdded, identitiesKnown, bookmarksAdded, bookmarksKnown,
contactsAdded, contactsKnown);
}
/** Someone chatted with in TeamSpeak 6 is a friend, as a contact there is. */
private Contact toContact(SyncItem.Contact sync) {
Contact contact = new Contact("", sync.myTeamSpeakId());
contact.nickname = sync.customName();
contact.type = ContactType.FRIEND;
contact.applyDefaults(settings.contactDefaults.of(ContactType.FRIEND));
return contact;
} }
private Bookmark toBookmark(SyncItem.Bookmark sync, IdentityEntry identity) { private Bookmark toBookmark(SyncItem.Bookmark sync, IdentityEntry identity) {
@@ -183,6 +235,7 @@ public final class TeamSpeakImporter {
if (b.channel.isBlank() && sync.defaultChannelId() != 0) b.channel = "/" + sync.defaultChannelId(); if (b.channel.isBlank() && sync.defaultChannelId() != 0) b.channel = "/" + sync.defaultChannelId();
b.channelPassword = sync.defaultChannelPassword(); b.channelPassword = sync.defaultChannelPassword();
b.connectOnStartup = sync.autoconnect(); b.connectOnStartup = sync.autoconnect();
b.myTeamSpeakFeatures = sync.myTeamSpeakFeatures();
return b; return b;
} }
@@ -118,4 +118,41 @@ class ContactStoreTest {
store.remove("a="); store.remove("a=");
assertEquals(1, store.all().size()); assertEquals(1, store.all().size());
} }
@Test
void aMyTeamSpeakContactStandsForTheClientsLinkedToIt() throws Exception {
File file = new File(dir, "myts.txt");
ContactStore store = new ContactStore(file);
Contact friend = new Contact("", "AQID");
friend.nickname = "Friend";
friend.type = ContactType.FRIEND;
store.merge(List.of(friend));
assertNull(store.find("one="));
store.link("one=", "AQID");
store.link("two=", "AQID");
assertEquals(friend, store.find("one="));
assertEquals(friend, store.find("two="));
assertEquals(friend, store.find(friend.key()));
assertEquals("Friend (Nick)", store.displayName("two=", "Nick"));
// Adding a linked client re-types the shared contact rather than filing a second one.
store.add("one=", "One", ContactType.BLOCKED, new ContactDefaults());
assertEquals(1, store.all().size());
assertEquals(ContactType.BLOCKED, friend.type);
// A contact of the client's own comes first.
store.merge(List.of(new Contact("two=")));
assertEquals("two=", store.find("two=").uniqueId);
store.remove("two=");
store.link("two=", "");
assertNull(store.find("two="));
ContactStore reloaded = new ContactStore(file);
reloaded.readFile();
assertEquals("AQID", reloaded.all().get(0).myTeamSpeakId);
assertEquals("", reloaded.all().get(0).uniqueId);
store.remove("one=");
assertTrue(store.all().isEmpty());
}
} }
@@ -80,4 +80,24 @@ class ContactTest {
c.volumeModifier = -6; c.volumeModifier = -6;
assertEquals(0.501, c.volumeGain(), 0.001); assertEquals(0.501, c.volumeGain(), 0.001);
} }
@Test
void aMyTeamSpeakIdTravelsAsAnExtraLine() {
Contact plain = Contact.parseRecord(new Contact("abc=").toRecord());
assertFalse(plain.toRecord().contains("MyTsId"));
Contact c = new Contact("", "AQID");
c.nickname = "Friend";
String record = c.toRecord();
assertTrue(record.startsWith("IDS=\n"), record);
assertTrue(record.endsWith("MyTsId=AQID\n"), record);
Contact back = Contact.parseRecord(record);
assertEquals("", back.uniqueId);
assertEquals("AQID", back.myTeamSpeakId);
assertEquals("Friend", back.nickname);
assertEquals("myts:AQID", back.key());
assertEquals("AQID", back.shownId());
assertEquals("AQID", back.copy().myTeamSpeakId);
assertNull(Contact.parseRecord("Nickname=Nobody\n"));
}
} }
@@ -2,28 +2,11 @@ package eu.lixko.ts3j.client.myts;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertNull;
class AccountInfoTest { class AccountInfoTest {
private static String base32(String text) {
return AccountInfo.base32(text.getBytes(StandardCharsets.US_ASCII));
}
@Test
void encodesRfc4648VectorsLowercaseAndUnpadded() {
assertEquals("", base32(""));
assertEquals("my", base32("f"));
assertEquals("mzxq", base32("fo"));
assertEquals("mzxw6", base32("foo"));
assertEquals("mzxw6yq", base32("foob"));
assertEquals("mzxw6ytb", base32("fooba"));
assertEquals("mzxw6ytboi", base32("foobar"));
}
@Test @Test
void toleratesAReplyWithoutIdentityData() { void toleratesAReplyWithoutIdentityData() {
AccountInfo info = AccountInfo.of("tester", "u", null, 0); AccountInfo info = AccountInfo.of("tester", "u", null, 0);
@@ -0,0 +1,48 @@
package eu.lixko.ts3j.client.myts;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
class MyTsIdTest {
private static String base32(String text) {
return MyTsId.base32(text.getBytes(StandardCharsets.US_ASCII));
}
@Test
void encodesRfc4648VectorsLowercaseAndUnpadded() {
assertEquals("", base32(""));
assertEquals("my", base32("f"));
assertEquals("mzxq", base32("fo"));
assertEquals("mzxw6", base32("foo"));
assertEquals("mzxw6yq", base32("foob"));
assertEquals("mzxw6ytb", base32("fooba"));
assertEquals("mzxw6ytboi", base32("foobar"));
}
@Test
void decodesWhatItEncodes() {
for (String text : new String[] {"", "f", "fo", "foo", "foob", "fooba", "foobar"}) {
assertArrayEquals(text.getBytes(StandardCharsets.US_ASCII), MyTsId.base32Decode(base32(text)));
}
assertArrayEquals("foobar".getBytes(StandardCharsets.US_ASCII), MyTsId.base32Decode("MZXW6YTBOI"));
assertNull(MyTsId.base32Decode("mzxw6ytb0i"));
}
@Test
void readsTheIdOutOfAChatUserId() {
byte[] id = {1, 2, 3, (byte) 0xfe, (byte) 0xff, 0x40, 0x7f};
String expected = Base64.getEncoder().encodeToString(id);
assertEquals(expected, MyTsId.fromChatId("@" + MyTsId.base32(id) + ":chat.teamspeak.com"));
assertEquals("", MyTsId.fromChatId("@someone"));
assertEquals("", MyTsId.fromChatId("someone:chat.teamspeak.com"));
assertEquals("", MyTsId.fromChatId("@not-base32:chat.teamspeak.com"));
assertEquals("", MyTsId.fromChatId(null));
}
}
@@ -1,6 +1,7 @@
package eu.lixko.ts3j.client.teamspeak; package eu.lixko.ts3j.client.teamspeak;
import eu.lixko.ts3j.client.config.IdentityStore; import eu.lixko.ts3j.client.config.IdentityStore;
import eu.lixko.ts3j.client.proto.ProtobufWriter;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.File; import java.io.File;
@@ -8,6 +9,7 @@ import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -79,4 +81,29 @@ class SyncItemsTest {
assertEquals(42, byId.defaultChannelId()); assertEquals(42, byId.defaultChannelId());
assertEquals("", byId.identityUuid()); assertEquals("", byId.identityUuid());
} }
/** TeamSpeak 6's contact item, Item_Data field 25, as its client writes one: no myTeamSpeak ID, only the chat partner. */
static byte[] contactItem(String uuid, String customName, boolean direct, String memberId) {
ProtobufWriter contact = new ProtobufWriter().string(1, "!room:chat.teamspeak.com").string(2, customName)
.string(3, "Work").varint(5, 1).varint(6, direct ? 1 : 0).string(8, memberId);
return new ProtobufWriter().string(2, uuid).varint(4, 3).varint(6, 8)
.string(7, "ffffffff-ffff-ffff-ffff-ffffffffffff").message(25, contact).toByteArray();
}
@Test
void decodesATeamSpeak6Contact() throws Exception {
// "aebagbaf" is base32 for bytes 01 02 03 04 05.
SyncItem item = SyncItemDecoder.decode(contactItem("c1", "Buddy", true, "@aebagbaf:chat.teamspeak.com"));
SyncItem.Contact contact = assertInstanceOf(SyncItem.Contact.class, item);
assertEquals("c1", contact.uuid());
assertEquals("", contact.parentUuid());
assertEquals("Buddy", contact.customName());
assertEquals("Work", contact.category());
assertTrue(contact.favourite());
assertEquals("AQIDBAU=", contact.myTeamSpeakId());
SyncItem.Contact group = (SyncItem.Contact) SyncItemDecoder.decode(
contactItem("c2", "Group", false, "@aebagbaf:chat.teamspeak.com"));
assertEquals("", group.myTeamSpeakId());
}
} }
@@ -40,7 +40,7 @@ class SyncOrderTest {
private static SyncItem.Bookmark bookmark(String uuid, String parent, String previous) { private static SyncItem.Bookmark bookmark(String uuid, String parent, String previous) {
return new SyncItem.Bookmark(uuid, parent, previous, uuid, uuid + ".example", 9987, "", "", "", "", "", "", return new SyncItem.Bookmark(uuid, parent, previous, uuid, uuid + ".example", 9987, "", "", "", "", "", "",
0, false); 0, false, true);
} }
private static SyncItem.Folder folder(String uuid, String parent, String previous) { private static SyncItem.Folder folder(String uuid, String parent, String previous) {
@@ -6,6 +6,9 @@ import eu.lixko.ts3j.client.config.Bookmarks;
import eu.lixko.ts3j.client.config.IdentityEntry; import eu.lixko.ts3j.client.config.IdentityEntry;
import eu.lixko.ts3j.client.config.IdentityStore; import eu.lixko.ts3j.client.config.IdentityStore;
import eu.lixko.ts3j.client.config.Settings; import eu.lixko.ts3j.client.config.Settings;
import eu.lixko.ts3j.client.contacts.Contact;
import eu.lixko.ts3j.client.contacts.ContactStore;
import eu.lixko.ts3j.client.contacts.ContactType;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@@ -85,13 +88,14 @@ class TeamSpeakImporterTest {
SyncItem.Identity identity = TeamSpeakSettingsDb.readSyncItems(SyncItemsTest.fixture()).stream() SyncItem.Identity identity = TeamSpeakSettingsDb.readSyncItems(SyncItemsTest.fixture()).stream()
.filter(SyncItem.Identity.class::isInstance).map(SyncItem.Identity.class::cast).findFirst().orElseThrow(); .filter(SyncItem.Identity.class::isInstance).map(SyncItem.Identity.class::cast).findFirst().orElseThrow();
SyncItem.Bookmark bookmark = new SyncItem.Bookmark("b", "", "", "Server", "example.com", 9987, "", "", SyncItem.Bookmark bookmark = new SyncItem.Bookmark("b", "", "", "Server", "example.com", 9987, "", "",
identity.name(), "", "", "", 0, false); identity.name(), "", "", "", 0, false, true);
new TeamSpeakImporter(identities, bookmarks, settings).importAll(List.of(bookmark, identity)); new TeamSpeakImporter(identities, bookmarks, settings).importAll(List.of(bookmark, identity));
assertEquals(identities.all().get(0).getId(), bookmarks.all().get(0).identityId); assertEquals(identities.all().get(0).getId(), bookmarks.all().get(0).identityId);
assertEquals("", bookmarks.all().get(0).nickname); assertEquals("", bookmarks.all().get(0).nickname);
assertEquals(identity.nickname(), identities.all().get(0).getNickname()); assertEquals(identity.nickname(), identities.all().get(0).getNickname());
assertEquals(identity.phoneticNickname(), identities.all().get(0).getPhoneticNickname()); assertEquals(identity.phoneticNickname(), identities.all().get(0).getPhoneticNickname());
assertTrue(bookmarks.all().get(0).myTeamSpeakFeatures);
} }
@Test @Test
@@ -127,4 +131,33 @@ class TeamSpeakImporterTest {
assertEquals(before + first.identitiesAdded(), identities.all().size()); assertEquals(before + first.identitiesAdded(), identities.all().size());
assertNotNull(identities.byId(settings.defaultIdentityId)); assertNotNull(identities.byId(settings.defaultIdentityId));
} }
@Test
void importsTeamSpeak6ContactsAsFriendsByMyTeamSpeakId() throws Exception {
Settings settings = new Settings();
settings.contactDefaults.of(ContactType.FRIEND).ignorePokes = true;
ContactStore contacts = ContactStore.load();
TeamSpeakImporter importer = new TeamSpeakImporter(IdentityStore.load(settings), new Bookmarks(), settings,
contacts);
List<SyncItem> items = List.of(
SyncItemDecoder.decode(SyncItemsTest.contactItem("c1", "Buddy", true, "@aebagbaf:chat.teamspeak.com")),
SyncItemDecoder.decode(SyncItemsTest.contactItem("c2", "Group", false, "")));
assertFalse(importer.isPresent(items.get(0)));
assertFalse(TeamSpeakImporter.isImportable((SyncItem.Contact) items.get(1)));
TeamSpeakImporter.Result first = importer.importAll(items);
assertEquals(1, first.contactsAdded());
Contact buddy = contacts.findByMyTeamSpeakId("AQIDBAU=");
assertNotNull(buddy);
assertEquals("", buddy.uniqueId);
assertEquals("Buddy", buddy.nickname);
assertEquals(ContactType.FRIEND, buddy.type);
assertTrue(buddy.ignorePokes);
assertTrue(importer.isPresent(items.get(0)));
TeamSpeakImporter.Result second = importer.importSelected(items, List.of(items.get(0)));
assertEquals(0, second.contactsAdded());
assertEquals(1, second.contactsKnown());
assertEquals(1, contacts.all().size());
}
} }
+11
View File
@@ -47,6 +47,17 @@ body is protobuf, not JSON).
[CRYPTO_RE_SALT.md](CRYPTO_RE_SALT.md#5-synchronization-and-upload-state-machine) for the recovered [CRYPTO_RE_SALT.md](CRYPTO_RE_SALT.md#5-synchronization-and-upload-state-machine) for the recovered
state machine and confidence boundaries. state machine and confidence boundaries.
### TeamSpeak 6 item classes
The TS6 binary's `Sync_Serializing.proto` is newer than the TS3 one in `myteamspeak.recovered.proto`:
`Item_Class` 7 is `GROUP_CHATS` (TS3: `ROOM_CATEGORY`) and **8 is `CONTACTS`**; `Item_Data` gains oneof
`group_chats(24)` and `contact(25)`. `Contact{chat_room_id(1), custom_name(2), custom_category(3),
notification_preference(4), is_favourite(5), is_direct_chat(6), mytsid(7), chat_member_id(8)}`.
TS6 writes one per chat once a custom name, category or notification setting is set — it is room
settings, not the contact list (that is the Matrix rooms) — and never fills `mytsid`; a direct chat's
`chat_member_id` is the partner's Matrix ID `@<base32 myTS ID bytes>:<homeserver>`. The same bytes as
standard base64 are the `client_myteamspeak_id` servers report (33 bytes, leading `0x01`), which is how
TS6 ties a server client to a chat contact.
## Crypto status ## Crypto status
myTeamSpeak sync is **end-to-end encrypted**, using TeamSpeak's own `teamcrypto` library myTeamSpeak sync is **end-to-end encrypted**, using TeamSpeak's own `teamcrypto` library
@@ -0,0 +1,46 @@
# Announcing the myTeamSpeak ID to a server
What the client has to send so that a server shows our `client_myteamspeak_id`, the way the
official client does when a bookmark has "Enable myTeamSpeak features" on. Observed with TS3 3.6.2
signed in to the throwaway account against the test server, 2026-10-10.
## The switch
Connect dialog and bookmarks: **"Enable myTeamSpeak features"**, on by default. It is
`Bookmark_Data.send_mytsid_on_server (22)` in the sync schema. When it is on and the client is
signed in, `clientinit` carries the extra parameters below. `client_myteamspeak_id` itself is
sent empty; the server fills it in from them and announces it to everyone
(`notifycliententerview client_myteamspeak_id=<base64>`).
The official client also has a post-connect `updatemytsid` command, which takes the same data,
for signing in or out while connected. It was not hit during a normal connect.
## Extra `clientinit` parameters
| Parameter | Value | Source |
|-----------------|-----------------------------------------------------------------|----------------------------|
| `myTeamspeakId` | base64 of the 33-byte myTeamSpeak ID (`01 20 …`) | known: login `myts_id_data.my_teamspeak_id (4)` |
| `acTime` | account creation time as a u64, byte-swapped, in decimal | known: login `myts_id_data.account_creation_time (3)` |
| `userPubKey` | base64, 32 bytes (Ed25519 public key) | known: login `myts_id_data.user_public_key (1)` |
| `pubSign` | base64, 64 bytes | known: first 64 bytes of login `myts_id_data.public_signature (5)` |
| `pubSignCert` | base64, 112 bytes (certificate naming "TeamSpeak Systems GmbH") | known: remaining 112 bytes of `public_signature (5)` |
| `authSign` | base64, 64 bytes | **unknown, still to find** |
`acTime` example: creation time `1790376353` = `0x6AB6F9A1`; as big-endian u64
`a1f9b66a00000000` = `11671560475690139648`.
## Still to find: `authSign`
- It is made fresh for each connection. It is not part of the login reply, and replaying an old
one is not expected to work.
- Without valid data the server refuses the ID: `clientupdate client_myteamspeak_id=<anything>`
gives "invalid parameter".
- To find: what `authSign` covers and how the client produces it, using only what our existing
sign-in (`MyTeamSpeakLogin`) already holds.
## Verification once it is known
1. Connect our client with the switch on, signed in to the throwaway account.
2. From a second client (the ts3j probe bot), check that `notifycliententerview` carries
`client_myteamspeak_id=ASCwXERY29umCjNyMewplck8cVzzMx/Xsh8vab8V7grN`, the throwaway's ID.
3. Check that with the switch off the field stays empty.
@@ -59,6 +59,7 @@ public final class BookmarksDialog extends JDialog {
private final JTextField channel = new JTextField(); private final JTextField channel = new JTextField();
private final JPasswordField channelPassword = new JPasswordField(); private final JPasswordField channelPassword = new JPasswordField();
private final JCheckBox connectOnStartup = new JCheckBox("Connect on startup"); private final JCheckBox connectOnStartup = new JCheckBox("Connect on startup");
private final JCheckBox myTeamSpeakFeatures = new JCheckBox("Enable myTeamSpeak features");
private final IdentityChooser identity; private final IdentityChooser identity;
private final JPanel details; private final JPanel details;
@@ -144,6 +145,7 @@ public final class BookmarksDialog extends JDialog {
addRow(panel, row++, "Channel password:", channelPassword); addRow(panel, row++, "Channel password:", channelPassword);
addRow(panel, row++, "Identity:", identity); addRow(panel, row++, "Identity:", identity);
addRow(panel, row++, "", connectOnStartup); addRow(panel, row++, "", connectOnStartup);
addRow(panel, row++, "", myTeamSpeakFeatures);
GridBagConstraints filler = new GridBagConstraints(); GridBagConstraints filler = new GridBagConstraints();
filler.gridx = 0; filler.gridx = 0;
@@ -210,6 +212,7 @@ public final class BookmarksDialog extends JDialog {
channel.setText(b == null ? "" : nullToEmpty(b.channel)); channel.setText(b == null ? "" : nullToEmpty(b.channel));
channelPassword.setText(b == null ? "" : nullToEmpty(b.channelPassword)); channelPassword.setText(b == null ? "" : nullToEmpty(b.channelPassword));
connectOnStartup.setSelected(b != null && b.connectOnStartup); connectOnStartup.setSelected(b != null && b.connectOnStartup);
myTeamSpeakFeatures.setSelected(b == null || b.myTeamSpeakFeatures);
identity.setSelectedIdentityId(b == null ? "" : nullToEmpty(b.identityId)); identity.setSelectedIdentityId(b == null ? "" : nullToEmpty(b.identityId));
} }
@@ -229,6 +232,7 @@ public final class BookmarksDialog extends JDialog {
editing.channelPassword = new String(channelPassword.getPassword()); editing.channelPassword = new String(channelPassword.getPassword());
editing.identityId = identity.getSelectedIdentityId(); editing.identityId = identity.getSelectedIdentityId();
editing.connectOnStartup = connectOnStartup.isSelected(); editing.connectOnStartup = connectOnStartup.isSelected();
editing.myTeamSpeakFeatures = myTeamSpeakFeatures.isSelected();
list.repaint(); list.repaint();
} }
@@ -208,13 +208,13 @@ final class ContactsDialog extends JDialog {
tree.setTransferHandler(new DropHandler()); tree.setTransferHandler(new DropHandler());
} }
/** Re-lists the contacts, keeping the selection on the same unique id. */ /** Re-lists the contacts, keeping the selection on the same contact. */
private void reload() { private void reload() {
String selectedUid = selectedContact() == null ? null : selectedContact().uniqueId; String selectedUid = selectedContact() == null ? null : selectedContact().key();
for (DefaultMutableTreeNode group : List.of(friends, blocked, neutral)) group.removeAllChildren(); for (DefaultMutableTreeNode group : List.of(friends, blocked, neutral)) group.removeAllChildren();
List<Contact> sorted = new ArrayList<>(contacts.all()); List<Contact> sorted = new ArrayList<>(contacts.all());
sorted.sort(Comparator.comparing((Contact c) -> c.nickname, String.CASE_INSENSITIVE_ORDER) sorted.sort(Comparator.comparing(Contact::label, String.CASE_INSENSITIVE_ORDER)
.thenComparing(c -> c.uniqueId)); .thenComparing(Contact::key));
for (Contact c : sorted) groupOf(c.type).add(new DefaultMutableTreeNode(c)); for (Contact c : sorted) groupOf(c.type).add(new DefaultMutableTreeNode(c));
treeModel.reload(); treeModel.reload();
for (int i = 0; i < tree.getRowCount(); i++) tree.expandRow(i); for (int i = 0; i < tree.getRowCount(); i++) tree.expandRow(i);
@@ -233,12 +233,14 @@ final class ContactsDialog extends JDialog {
} }
} }
/** Selects the contact with a unique id, if it is on the list. */ /** Selects the contact a client's unique id (or a contact key) is filed under, if it is on the list. */
void select(String uniqueId) { void select(String uniqueId) {
Contact wanted = contacts.find(uniqueId);
if (wanted == null) return;
java.util.Enumeration<?> nodes = root.depthFirstEnumeration(); java.util.Enumeration<?> nodes = root.depthFirstEnumeration();
while (nodes.hasMoreElements()) { while (nodes.hasMoreElements()) {
DefaultMutableTreeNode n = (DefaultMutableTreeNode) nodes.nextElement(); DefaultMutableTreeNode n = (DefaultMutableTreeNode) nodes.nextElement();
if (n.getUserObject() instanceof Contact && ((Contact) n.getUserObject()).uniqueId.equals(uniqueId)) { if (n.getUserObject() instanceof Contact && ((Contact) n.getUserObject()).key().equals(wanted.key())) {
TreePath path = new TreePath(n.getPath()); TreePath path = new TreePath(n.getPath());
tree.setSelectionPath(path); tree.setSelectionPath(path);
tree.scrollPathToVisible(path); tree.scrollPathToVisible(path);
@@ -276,9 +278,10 @@ final class ContactsDialog extends JDialog {
applyDefaults.addActionListener(a -> edit(c -> c.applyDefaults(settings.contactDefaults.of(c.type)))); applyDefaults.addActionListener(a -> edit(c -> c.applyDefaults(settings.contactDefaults.of(c.type))));
menu.add(applyDefaults); menu.add(applyDefaults);
menu.addSeparator(); menu.addSeparator();
JMenuItem copyUid = new JMenuItem("Copy Unique ID to Clipboard", Icons.of("COPY")); JMenuItem copyUid = new JMenuItem(contact.uniqueId.isEmpty()
? "Copy myTeamSpeak ID to Clipboard" : "Copy Unique ID to Clipboard", Icons.of("COPY"));
copyUid.addActionListener(a -> Toolkit.getDefaultToolkit().getSystemClipboard() copyUid.addActionListener(a -> Toolkit.getDefaultToolkit().getSystemClipboard()
.setContents(new StringSelection(contact.uniqueId), null)); .setContents(new StringSelection(contact.shownId()), null));
menu.add(copyUid); menu.add(copyUid);
menu.show(tree, e.getX(), e.getY()); menu.show(tree, e.getX(), e.getY());
} }
@@ -287,9 +290,9 @@ final class ContactsDialog extends JDialog {
Contact contact = selectedContact(); Contact contact = selectedContact();
if (contact == null) return; if (contact == null) return;
int answer = JOptionPane.showConfirmDialog(this, int answer = JOptionPane.showConfirmDialog(this,
"Do you really want to delete contact " + contact.nickname + "?", "Remove Contact", "Do you really want to delete contact " + contact.label() + "?", "Remove Contact",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (answer == JOptionPane.YES_OPTION) contacts.remove(contact.uniqueId); if (answer == JOptionPane.YES_OPTION) contacts.remove(contact.key());
} }
private void importFromTeamSpeak() { private void importFromTeamSpeak() {
@@ -545,7 +548,7 @@ final class ContactsDialog extends JDialog {
Object obj = ((DefaultMutableTreeNode) value).getUserObject(); Object obj = ((DefaultMutableTreeNode) value).getUserObject();
if (obj instanceof Contact) { if (obj instanceof Contact) {
Contact c = (Contact) obj; Contact c = (Contact) obj;
setText("<html>" + esc(c.nickname) + " <span style='color:" + hex(sel ? getForeground() : Theme.chatSystem()) setText("<html>" + esc(c.label()) + " <span style='color:" + hex(sel ? getForeground() : Theme.chatSystem())
+ "'>&nbsp;" + (c.lastSeen == null ? "Never" : SEEN_DAY.format(c.lastSeen)) + "</span></html>"); + "'>&nbsp;" + (c.lastSeen == null ? "Never" : SEEN_DAY.format(c.lastSeen)) + "</span></html>");
setFont(Theme.uiFont()); setFont(Theme.uiFont());
setBorder(margin); setBorder(margin);
@@ -1023,7 +1023,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
sessions.microphoneOwner() == null ? null : sessions.microphoneOwner().connection().getMicrophone(), sessions.microphoneOwner() == null ? null : sessions.microphoneOwner().connection().getMicrophone(),
selected == null ? null : selected.connection().getPlayback(), selected == null ? null : selected.connection().getPlayback(),
sounds, hotkeys, sounds, hotkeys,
new MyTeamSpeakPanel(myTeamSpeak, new TeamSpeakImporter(identities, bookmarks, settings), new MyTeamSpeakPanel(myTeamSpeak, new TeamSpeakImporter(identities, bookmarks, settings, contacts),
menuBar::rebuildBookmarks, this::myTeamSpeakChanged), menuBar::rebuildBookmarks, this::myTeamSpeakChanged),
() -> { () -> {
applyOutputSettingsToAllTabs(); applyOutputSettingsToAllTabs();
@@ -61,6 +61,7 @@ final class MyTeamSpeakPanel extends JPanel {
private final JPanel details = new JPanel(new GridBagLayout()); private final JPanel details = new JPanel(new GridBagLayout());
private final ItemTable identities = new ItemTable("Nickname"); private final ItemTable identities = new ItemTable("Nickname");
private final ItemTable bookmarks = new ItemTable("Address"); private final ItemTable bookmarks = new ItemTable("Address");
private final ItemTable contacts = new ItemTable("myTeamSpeak ID");
private final FormPanel sections = new FormPanel(false); private final FormPanel sections = new FormPanel(false);
private final JButton refresh = new JButton("Refresh"); private final JButton refresh = new JButton("Refresh");
private final JButton importButton = new JButton("Import selected"); private final JButton importButton = new JButton("Import selected");
@@ -91,8 +92,8 @@ final class MyTeamSpeakPanel extends JPanel {
GridBagConstraints c = FormPanel.gbc(); GridBagConstraints c = FormPanel.gbc();
c.gridwidth = 2; c.gridwidth = 2;
c.gridy = 0; c.gridy = 0;
form.add(new JLabel("<html>Sign in to your myTeamSpeak account to bring over the bookmarks and " form.add(new JLabel("<html>Sign in to your myTeamSpeak account to bring over the bookmarks, "
+ "identities it synchronises. The client stays signed in; your password itself is not kept.</html>"), c); + "identities and contacts it synchronises. The client stays signed in; your password itself is not kept.</html>"), c);
c.gridwidth = 1; c.gridwidth = 1;
FormPanel.addRow(form, c, 1, new JLabel("Email:"), email); FormPanel.addRow(form, c, 1, new JLabel("Email:"), email);
FormPanel.addRow(form, c, 2, new JLabel("Password:"), password); FormPanel.addRow(form, c, 2, new JLabel("Password:"), password);
@@ -245,11 +246,12 @@ final class MyTeamSpeakPanel extends JPanel {
List<Row> rows = new ArrayList<>(); List<Row> rows = new ArrayList<>();
for (SyncItem item : accountItems) { for (SyncItem item : accountItems) {
if (item instanceof SyncItem.Folder) continue; if (item instanceof SyncItem.Folder) continue;
if (item instanceof SyncItem.Contact contact && !TeamSpeakImporter.isImportable(contact)) continue;
boolean present = importer.isPresent(item); boolean present = importer.isPresent(item);
rows.add(new Row(item, present, !present)); rows.add(new Row(item, present, !present));
} }
setRows(rows); setRows(rows);
status(dataStatus, rows.isEmpty() ? "The account holds no bookmarks or identities." : " ", false); status(dataStatus, rows.isEmpty() ? "The account holds no bookmarks, identities or contacts." : " ", false);
updateImportButton(); updateImportButton();
} }
@@ -258,8 +260,9 @@ final class MyTeamSpeakPanel extends JPanel {
if (chosen.isEmpty()) return; if (chosen.isEmpty()) return;
try { try {
TeamSpeakImporter.Result r = importer.importSelected(accountItems, chosen); TeamSpeakImporter.Result r = importer.importSelected(accountItems, chosen);
status(dataStatus, "Imported " + count(r.identitiesAdded(), "identity", "identities") + " and " status(dataStatus, "Imported " + count(r.identitiesAdded(), "identity", "identities") + ", "
+ count(r.bookmarksAdded(), "bookmark", "bookmarks") + ".", false); + count(r.bookmarksAdded(), "bookmark", "bookmarks") + " and "
+ count(r.contactsAdded(), "contact", "contacts") + ".", false);
if (onImported != null) onImported.run(); if (onImported != null) onImported.run();
} catch (IOException e) { } catch (IOException e) {
status(dataStatus, "Could not import: " + e.getMessage(), true); status(dataStatus, "Could not import: " + e.getMessage(), true);
@@ -304,18 +307,20 @@ final class MyTeamSpeakPanel extends JPanel {
} }
private Stream<Row> allRows() { private Stream<Row> allRows() {
return Stream.concat(identities.rows.stream(), bookmarks.rows.stream()); return Stream.of(identities, bookmarks, contacts).flatMap(table -> table.rows.stream());
} }
/** Splits the rows into the Identities and Bookmarks sections, leaving out an empty one. */ /** Splits the rows into the Identities, Bookmarks and Contacts sections, leaving out an empty one. */
private void setRows(List<Row> rows) { private void setRows(List<Row> rows) {
identities.set(rows.stream().filter(r -> r.item() instanceof SyncItem.Identity).toList()); identities.set(rows.stream().filter(r -> r.item() instanceof SyncItem.Identity).toList());
bookmarks.set(rows.stream().filter(r -> r.item() instanceof SyncItem.Bookmark).toList()); bookmarks.set(rows.stream().filter(r -> r.item() instanceof SyncItem.Bookmark).toList());
contacts.set(rows.stream().filter(r -> r.item() instanceof SyncItem.Contact).toList());
sections.removeAll(); sections.removeAll();
GridBagConstraints c = FormPanel.gbc(); GridBagConstraints c = FormPanel.gbc();
int row = 0; int row = 0;
if (!identities.rows.isEmpty()) row = addSection(c, row, "Identities", identities); if (!identities.rows.isEmpty()) row = addSection(c, row, "Identities", identities);
if (!bookmarks.rows.isEmpty()) row = addSection(c, row, "Bookmarks", bookmarks); if (!bookmarks.rows.isEmpty()) row = addSection(c, row, "Bookmarks", bookmarks);
if (!contacts.rows.isEmpty()) row = addSection(c, row, "Contacts", contacts);
FormPanel.addFiller(sections, c, row); FormPanel.addFiller(sections, c, row);
sections.revalidate(); sections.revalidate();
sections.repaint(); sections.repaint();
@@ -414,11 +419,13 @@ final class MyTeamSpeakPanel extends JPanel {
case 1 -> switch (r.item()) { case 1 -> switch (r.item()) {
case SyncItem.Bookmark b -> b.name(); case SyncItem.Bookmark b -> b.name();
case SyncItem.Identity i -> i.name(); case SyncItem.Identity i -> i.name();
case SyncItem.Contact contact -> contact.customName();
default -> ""; default -> "";
}; };
case 2 -> switch (r.item()) { case 2 -> switch (r.item()) {
case SyncItem.Bookmark b -> Bookmark.hostPort(b.address(), b.port()); case SyncItem.Bookmark b -> Bookmark.hostPort(b.address(), b.port());
case SyncItem.Identity i -> i.nickname(); case SyncItem.Identity i -> i.nickname();
case SyncItem.Contact contact -> contact.myTeamSpeakId();
default -> ""; default -> "";
}; };
default -> r.present() ? "Yes" : ""; default -> r.present() ? "Yes" : "";