Android: Synchronize with myTeamSpeak; keep each installation's default identity

Settings → myTeamSpeak gets Synchronize, with conflicts settled in
SyncConflictsScreen. The default identity is no longer a synced field:
an identity new to the account carries it only when the account has
none, and one brought here takes it only when we have none, so
installations stop flipping each other's default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-15 16:37:04 +00:00
co-authored by Claude Opus 5.5
parent 116986c6fc
commit 1f61ad0b29
8 changed files with 294 additions and 31 deletions
@@ -27,7 +27,8 @@ class AppParts(context: Context) {
val whisperLists: WhisperListManager = WhisperListManager()
val audio: AudioSetup = AudioSetup(context, settings)
val myTeamSpeak: MyTeamSpeakAccount = MyTeamSpeakAccount(context, pictures,
TeamSpeakImporter(identityStore, bookmarkStore, settings, contactStore), bookmarks, identities) { sessions.myTeamSpeakChanged() }
TeamSpeakImporter(identityStore, bookmarkStore, settings, contactStore), bookmarks, identities,
identityStore, bookmarkStore, settings) { sessions.myTeamSpeakChanged() }
private val serverParts = ServerParts(context, settings, identityStore, audio, contactStore, myTeamSpeak)
val sessions: SessionController = SessionController(context, settings, identities, bookmarks, serverParts,
@@ -7,6 +7,10 @@ import eu.lixko.ts3j.client.myts.ChatAttachment
import eu.lixko.ts3j.client.myts.ChatAttachments
import eu.lixko.ts3j.client.myts.MyTeamSpeak
import eu.lixko.ts3j.client.myts.MyTeamSpeakLogin
import eu.lixko.ts3j.client.myts.MyTeamSpeakSync
import eu.lixko.ts3j.client.config.Bookmarks
import eu.lixko.ts3j.client.config.IdentityStore
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.teamspeak.SyncItem
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
import kotlinx.coroutines.Dispatchers
@@ -29,6 +33,9 @@ class MyTeamSpeakAccount internal constructor(
private val importer: TeamSpeakImporter,
private val bookmarks: BookmarkManager,
private val identities: IdentityManager,
identityStore: IdentityStore,
bookmarkStore: Bookmarks,
settings: Settings,
/** Signed in or out, for the servers to pass on. */
private val onSignInChanged: () -> Unit,
) {
@@ -37,6 +44,8 @@ class MyTeamSpeakAccount internal constructor(
private val _signedIn = MutableStateFlow(login.isSignedIn)
val signedIn: StateFlow<Boolean> = _signedIn
private val sync = MyTeamSpeakSync(login, identityStore, bookmarkStore, settings)
/** Files shared in chat. */
internal val attachments = ChatAttachments(login).also {
pictures.addSource(ChatAttachment.SCHEME, it::fetchPicture)
@@ -76,6 +85,30 @@ class MyTeamSpeakAccount internal constructor(
identities.refresh()
}
/**
* Reads what changed in the account and works out what goes which way. Call on the main
* thread, which owns the bookmarks and identities; the network part runs on [Dispatchers.IO].
*/
suspend fun planSync(): MyTeamSpeakSync.Plan =
try {
sync.plan(withContext(Dispatchers.IO) { sync.fetch() })
} finally {
_signedIn.value = login.isSignedIn
}
/** Sends this side's changes, then brings the account's here; [plan]'s conflicts settled. Main thread. */
suspend fun finishSync(plan: MyTeamSpeakSync.Plan): MyTeamSpeakSync.Result {
try {
withContext(Dispatchers.IO) { sync.upload(plan) }
} finally {
_signedIn.value = login.isSignedIn
}
return sync.apply(plan).also {
bookmarks.refresh()
identities.refresh()
}
}
/** Fetches a file shared in chat whole. */
suspend fun downloadAttachment(ref: ChatAttachment.Ref): ByteArray =
withContext(Dispatchers.IO) { attachments.download(ref, ChatAttachments.MAX_UPLOAD_BYTES) }
@@ -46,6 +46,7 @@ import eu.lixko.ts3j.client.android.MyTeamSpeakAccount
import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.myts.AccountInfo
import eu.lixko.ts3j.client.myts.MyTeamSpeak
import eu.lixko.ts3j.client.myts.MyTeamSpeakSync
import eu.lixko.ts3j.client.myts.MyTsException
import eu.lixko.ts3j.client.teamspeak.SyncItem
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
@@ -58,8 +59,8 @@ import kotlinx.coroutines.launch
private data class ItemRow(val item: SyncItem, val imported: Boolean, val selected: Boolean)
/**
* The myTeamSpeak account: sign in and out, and pick what the account synchronises to
* import. Signing in lasts until signing out; the password itself is not kept.
* The myTeamSpeak account: sign in and out, pick what the account synchronises to import,
* or synchronise both ways. Signing in lasts until signing out; the password itself is not kept.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -75,7 +76,7 @@ fun MyTeamSpeakScreen(account: MyTeamSpeakAccount, onBack: () -> Unit) {
var info by remember { mutableStateOf<AccountInfo?>(null) }
var all by remember { mutableStateOf(emptyList<SyncItem>()) }
var rows by remember { mutableStateOf(emptyList<ItemRow>()) }
BackHandler(onBack = onBack)
var conflicted by remember { mutableStateOf<MyTeamSpeakSync.Plan?>(null) }
fun show(fetched: MyTeamSpeak.Account) {
info = fetched.info()
@@ -107,10 +108,26 @@ fun MyTeamSpeakScreen(account: MyTeamSpeakAccount, onBack: () -> Unit) {
}
}
suspend fun finishSync(plan: MyTeamSpeakSync.Plan) {
val r = account.finishSync(plan)
rows = rows.map { it.copy(imported = account.isImported(it.item)) }
message = if (r.sent() == 0 && r.received() == 0) "In sync."
else "Synchronized: ${r.sent()} sent, ${r.received()} received."
}
LaunchedEffect(Unit) {
if (signedIn) work { show(account.fetch()) }
}
conflicted?.let { plan ->
SyncConflictsScreen(plan.conflicts()) { accepted ->
conflicted = null
if (accepted) work { finishSync(plan) } else message = "Synchronization cancelled."
}
return
}
BackHandler(onBack = onBack)
Scaffold(
topBar = {
TopAppBar(
@@ -214,8 +231,9 @@ fun MyTeamSpeakScreen(account: MyTeamSpeakAccount, onBack: () -> Unit) {
)
}
}
if (rows.isNotEmpty()) {
item {
Row(Modifier.padding(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (rows.isNotEmpty()) {
Button(
onClick = {
work {
@@ -227,9 +245,18 @@ fun MyTeamSpeakScreen(account: MyTeamSpeakAccount, onBack: () -> Unit) {
}
},
enabled = !busy && rows.any { it.selected },
modifier = Modifier.padding(horizontal = 16.dp),
) { Text("Import selected") }
}
OutlinedButton(
onClick = {
work {
val plan = account.planSync()
if (plan.conflicts().isEmpty()) finishSync(plan) else conflicted = plan
}
},
enabled = !busy,
) { Text("Synchronize") }
}
}
}
message?.let { text ->
@@ -0,0 +1,151 @@
package eu.lixko.ts3j.client.android.ui
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.selection.selectable
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.myts.MyTeamSpeakSync.Conflict
/**
* Which copy to keep of each item changed both here and in myTeamSpeak since the last
* synchronisation: the item's fields side by side, the ones that differ in bold.
* [onDone] gets whether the user went on; the choices are recorded on the conflicts.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SyncConflictsScreen(conflicts: List<Conflict>, onDone: (Boolean) -> Unit) {
// Mirrors the choices recorded on the conflicts, for recomposition.
val choices = remember(conflicts) {
mutableStateMapOf<Int, Conflict.Choice>().apply {
conflicts.forEachIndexed { i, c -> c.choice()?.let { put(i, it) } }
}
}
fun choose(index: Int, choice: Conflict.Choice) {
conflicts[index].choose(choice)
choices[index] = choice
}
BackHandler { onDone(false) }
Scaffold(
topBar = {
TopAppBar(
title = { Text("Synchronization conflicts") },
navigationIcon = { IconButton(onClick = { onDone(false) }) { Icon(Icons.Filled.Close, "Cancel") } },
)
},
bottomBar = {
Surface(tonalElevation = 3.dp) {
Row(
Modifier.fillMaxWidth().navigationBarsPadding().padding(horizontal = 8.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
TextButton(onClick = { conflicts.indices.forEach { choose(it, Conflict.Choice.HERE) } }) {
Text("Keep all of this device's")
}
TextButton(onClick = { conflicts.indices.forEach { choose(it, Conflict.Choice.CLOUD) } }) {
Text("Keep all of myTeamSpeak's")
}
}
Button(onClick = { onDone(true) }, enabled = choices.size == conflicts.size) { Text("Synchronize") }
}
}
},
) { padding ->
LazyColumn(
Modifier.padding(padding),
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
item { Text("Changed here and in myTeamSpeak since the last synchronization:") }
itemsIndexed(conflicts) { index, conflict ->
ConflictCard(conflict, choices[index]) { choose(index, it) }
}
}
}
}
@Composable
private fun ConflictCard(conflict: Conflict, choice: Conflict.Choice?, onChoose: (Conflict.Choice) -> Unit) {
Card(Modifier.fillMaxWidth()) {
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text((if (conflict.isIdentity) "Identity: " else "Bookmark: ") + conflict.title(),
style = MaterialTheme.typography.titleMedium)
Row {
Spacer(0.3f)
Header(if (conflict.deletedHere()) "This device (deleted)" else "This device")
Header(if (conflict.deletedInCloud()) "myTeamSpeak (deleted)" else "myTeamSpeak")
}
for (d in conflict.differences()) {
Row {
Text(d.label(), Modifier.weight(0.3f), style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant)
Value(if (conflict.deletedHere()) "—" else d.here(), d.differs())
Value(if (conflict.deletedInCloud()) "—" else d.cloud(), d.differs())
}
}
Option(if (conflict.deletedHere()) "Delete" else "Keep this device's", choice == Conflict.Choice.HERE) {
onChoose(Conflict.Choice.HERE)
}
Option(if (conflict.deletedInCloud()) "Delete" else "Keep myTeamSpeak's", choice == Conflict.Choice.CLOUD) {
onChoose(Conflict.Choice.CLOUD)
}
}
}
}
@Composable
private fun androidx.compose.foundation.layout.RowScope.Spacer(weight: Float) {
androidx.compose.foundation.layout.Spacer(Modifier.weight(weight))
}
@Composable
private fun androidx.compose.foundation.layout.RowScope.Header(text: String) {
Text(text, Modifier.weight(0.35f).padding(end = 4.dp), style = MaterialTheme.typography.labelMedium)
}
@Composable
private fun androidx.compose.foundation.layout.RowScope.Value(text: String, differs: Boolean) {
Text(text, Modifier.weight(0.35f).padding(end = 4.dp), style = MaterialTheme.typography.bodySmall,
fontWeight = if (differs) FontWeight.Bold else FontWeight.Normal)
}
@Composable
private fun Option(text: String, selected: Boolean, onClick: () -> Unit) {
Row(
Modifier.fillMaxWidth().selectable(selected, onClick = onClick, role = Role.RadioButton),
verticalAlignment = Alignment.CenterVertically,
) {
RadioButton(selected, onClick = null)
Text(text, Modifier.padding(start = 8.dp))
}
}
@@ -326,6 +326,7 @@ public final class MyTeamSpeakSync {
}
item.varint(9, System.currentTimeMillis() / 1000);
kind.write(localId, content, labels);
if (onto == null) kind.writeNew(localId, content);
item.message(kind.contentField(), content);
return new Step(kind, Action.PUSH, uuid, localId, null,
new MyTeamSpeak.CloudItem(kind.itemClass(), uuid, version, item.toByteArray()));
@@ -15,6 +15,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -73,6 +74,10 @@ abstract sealed class SyncKind {
/** Writes the labelled fields of the local item into the content message. */
abstract void write(String localId, ProtobufMessage content, Set<String> labels) throws IOException;
/** Writes what only an item new to the account carries, after {@link #write}. */
void writeNew(String localId, ProtobufMessage content) {
}
/** Creates the cloud item here; returns its local id. */
abstract String add(SyncItem cloud) throws IOException;
@@ -86,7 +91,6 @@ abstract sealed class SyncKind {
static final String NICKNAME = "Nickname";
static final String PHONETIC = "Phonetic nickname";
static final String KEY = "Unique ID";
static final String DEFAULT = "Default identity";
IdentityKind(IdentityStore identities, Bookmarks bookmarks, Settings settings, Links links) {
super(identities, bookmarks, settings, links);
@@ -104,15 +108,14 @@ abstract sealed class SyncKind {
@Override
List<String> localIds() {
return identities.all().stream().map(IdentityEntry::getId).toList();
return identities.all().stream().map(IdentityEntry::getId).collect(Collectors.toList());
}
@Override
SyncFields localFields(String localId) {
IdentityEntry e = identities.byId(localId);
if (e == null) return null;
return fields(e.getName(), e.getNickname(), e.getPhoneticNickname(), e.getIdentity(),
localId.equals(settings.defaultIdentityId.get()));
return fields(e.getName(), e.getNickname(), e.getPhoneticNickname(), e.getIdentity());
}
@Override
@@ -120,18 +123,20 @@ abstract sealed class SyncKind {
if (!(item instanceof SyncItem.Identity i)) return null;
try {
return fields(i.name(), i.nickname(), i.phoneticNickname(),
IdentityStore.parseIdentityString(i.identity()), i.isDefault());
IdentityStore.parseIdentityString(i.identity()));
} catch (IOException malformed) {
return null;
}
}
private static SyncFields fields(String name, String nickname, String phonetic, LocalIdentity key,
boolean isDefault) {
/**
* Which identity is the default is each installation's own: it is not compared, and travels
* only with an identity new to the other side, which takes it when it has no default yet.
*/
private static SyncFields fields(String name, String nickname, String phonetic, LocalIdentity key) {
String uid = key.getUid().toBase64();
return new SyncFields().put(NAME, name).put(NICKNAME, nickname).put(PHONETIC, phonetic)
.put(KEY, uid + "#" + key.getKeyOffset(), uid + " (level " + key.getSecurityLevel() + ")")
.flag(DEFAULT, isDefault);
.put(KEY, uid + "#" + key.getKeyOffset(), uid + " (level " + key.getSecurityLevel() + ")");
}
@Override
@@ -152,7 +157,13 @@ abstract sealed class SyncKind {
if (labels.contains(NAME)) content.string(2, e.getName());
if (labels.contains(NICKNAME)) content.string(3, e.getNickname());
if (labels.contains(PHONETIC)) content.string(4, e.getPhoneticNickname());
if (labels.contains(DEFAULT)) content.varint(5, localId.equals(settings.defaultIdentityId.get()) ? 1 : 0);
}
/** The account's default only when it has none: another installation's default stays. */
@Override
void writeNew(String localId, ProtobufMessage content) {
boolean cloudHasDefault = links.cloudIdentities.values().stream().anyMatch(SyncItem.Identity::isDefault);
content.varint(5, !cloudHasDefault && localId.equals(settings.defaultIdentityId.get()) ? 1 : 0);
}
@Override
@@ -163,7 +174,9 @@ abstract sealed class SyncKind {
if (existing != null) return update(existing.getId(), cloud);
String name = i.name().isBlank() ? (i.nickname().isBlank() ? "TeamSpeak identity" : i.nickname()) : i.name();
IdentityEntry e = identities.add(name, key, i.nickname(), i.phoneticNickname());
if (i.isDefault()) settings.defaultIdentityId.set(e.getId());
if (i.isDefault() && identities.byId(settings.defaultIdentityId.get()) == null) {
settings.defaultIdentityId.set(e.getId());
}
return e.getId();
}
@@ -184,7 +197,7 @@ abstract sealed class SyncKind {
i.nickname(), i.phoneticNickname());
identities.remove(e, settings, null);
for (Bookmark b : using) b.identityId = replacement.getId();
if (wasDefault || i.isDefault()) settings.defaultIdentityId.set(replacement.getId());
if (wasDefault) settings.defaultIdentityId.set(replacement.getId());
return replacement.getId();
}
if (key.getKeyOffset() != e.getIdentity().getKeyOffset()) identities.setKeyOffset(e, key);
@@ -192,7 +205,6 @@ abstract sealed class SyncKind {
if (!i.nickname().equals(e.getNickname()) || !i.phoneticNickname().equals(e.getPhoneticNickname())) {
identities.setNicknames(e, i.nickname(), i.phoneticNickname());
}
if (i.isDefault()) settings.defaultIdentityId.set(localId);
return localId;
}
@@ -232,7 +244,7 @@ abstract sealed class SyncKind {
@Override
List<String> localIds() {
return bookmarks.all().stream().map(b -> b.id).toList();
return bookmarks.all().stream().map(b -> b.id).collect(Collectors.toList());
}
@Override
@@ -283,6 +283,40 @@ class MyTeamSpeakSyncTest {
assertEquals(0, cloud.items.get(1).size());
}
@Test
void eachInstallationKeepsItsOwnDefaultIdentity(@TempDir File dir) throws Exception {
Client a = new Client(new File(dir, "a"));
Client b = new Client(new File(dir, "b"));
for (Client c : List.of(a, b)) {
c.in(() -> {
IdentityEntry mine = c.identities.generate("Mine", 1);
c.settings.defaultIdentityId.set(mine.getId());
});
}
String aDefault = a.settings.defaultIdentityId.get();
String bDefault = b.settings.defaultIdentityId.get();
a.sync();
b.sync();
a.sync();
assertEquals(aDefault, a.settings.defaultIdentityId.get());
assertEquals(bDefault, b.settings.defaultIdentityId.get());
long defaults = 0;
for (String uuid : cloud.items.get(1).keySet()) {
if (eu.lixko.ts3j.client.teamspeak.SyncItemDecoder.decode(cloud.plain(1, uuid))
instanceof eu.lixko.ts3j.client.teamspeak.SyncItem.Identity i && i.isDefault()) defaults++;
}
assertEquals(1, defaults, "the account keeps one default");
assertEquals(new MyTeamSpeakSync.Result(0, 0), a.sync());
assertEquals(new MyTeamSpeakSync.Result(0, 0), b.sync());
// A fresh installation takes the account's.
Client c = new Client(new File(dir, "c"));
c.sync();
assertEquals(a.identities.byId(aDefault).getUniqueId(),
c.identities.byId(c.settings.defaultIdentityId.get()).getUniqueId());
}
@Test
void anItemChangedOnBothSidesIsTheUsersToSettle(@TempDir File dir) throws Exception {
Client a = new Client(new File(dir, "a"));
@@ -41,14 +41,18 @@ the captured login and item), `MyTeamSpeakLoginTest` (persistence, failed sign-i
## Two-way sync
`MyTeamSpeakSync` (with `SyncKind`, `SyncFields`, `SyncState`): bookmarks and identities, run by hand
(Swing: Options → myTeamSpeak → Synchronize; conflicts in `SyncConflictsDialog`). A run is
(Swing: Options → myTeamSpeak → Synchronize, conflicts in `SyncConflictsDialog`; Android: Settings →
myTeamSpeak → Synchronize, conflicts in `ui/SyncConflictsScreen.kt`). A run is
`fetch` (network) → `plan` (stores' thread) → user settles `Plan.conflicts()` → `upload` (network) → `apply`
(stores' thread). Nothing changes on either side before `upload`, and here only after it succeeded.
The comparison is three-way per item, against `SyncState` (profile file `myteamspeak-sync.properties`: the
global cursor, each class's cursor, and per item its server revision, plaintext `Item_Data` and local id).
Changed on one side → carried over (deletions too); on both → a `Conflict` with a field-by-field diff;
first run → items paired by identity UID or bookmark name+address, the rest carried over. Edits are
first run → items paired by identity UID or bookmark name+address, the rest carried over. The default
identity is each installation's own: `is_default` is not compared, an identity new to the account is
uploaded as its default only when it has none, and one brought here becomes ours only when we have none
(otherwise installations flip each other's default on every run). Edits are
written over the item's current `Item_Data` field by field (`ProtobufMessage`), so fields this client does not
model survive.