From a334173fcc3ddaeb769a8610c0eaa843397740b4 Mon Sep 17 00:00:00 2001 From: ericek111 Date: Fri, 9 Oct 2026 22:19:52 +0000 Subject: [PATCH] Android: whisper to channels, clients and whisper lists The channel and client sheets whisper to them or add them to a whisper list. The top bar's whisper menu picks a list, replies to the last whisper, stops whispering and edits the lists; a banner over the voice bar says who the microphone whispers to. Core keeps the whisper on the session, finding its channels by path and its clients by unique id again as the server changes, and the saved lists in whisperlists.properties. ts3j now sends whisper packets. Co-Authored-By: Claude Opus 5.5 --- .../com/ts3client/android/ServerController.kt | 29 ++ .../ts3client/android/SessionController.kt | 37 +++ .../com/ts3client/android/ui/ServerScreen.kt | 34 ++- .../java/com/ts3client/android/ui/Sheets.kt | 10 +- .../java/com/ts3client/android/ui/Whisper.kt | 254 ++++++++++++++++++ .../com/ts3client/config/WhisperList.java | 40 +++ .../com/ts3client/config/WhisperLists.java | 93 +++++++ .../ts3client/net/TeamspeakConnection.java | 30 ++- .../main/java/com/ts3client/net/Whisper.java | 76 ++++++ .../com/ts3client/session/ServerSession.java | 47 ++++ ts3j | 2 +- 11 files changed, 646 insertions(+), 6 deletions(-) create mode 100644 android/app/src/main/java/com/ts3client/android/ui/Whisper.kt create mode 100644 ts3-client/core/src/main/java/com/ts3client/config/WhisperList.java create mode 100644 ts3-client/core/src/main/java/com/ts3client/config/WhisperLists.java create mode 100644 ts3-client/core/src/main/java/com/ts3client/net/Whisper.java diff --git a/android/app/src/main/java/com/ts3client/android/ServerController.kt b/android/app/src/main/java/com/ts3client/android/ServerController.kt index feba856..7a84cc9 100644 --- a/android/app/src/main/java/com/ts3client/android/ServerController.kt +++ b/android/app/src/main/java/com/ts3client/android/ServerController.kt @@ -3,11 +3,14 @@ package com.ts3client.android import android.net.Uri import com.ts3client.config.Bookmark import com.ts3client.contacts.ContactType +import com.ts3client.config.WhisperList import com.ts3client.net.ChannelNode +import com.ts3client.net.ClientEntry import com.ts3client.net.ChannelSettings import com.ts3client.net.ConnectionStats import com.ts3client.net.Details import com.ts3client.net.GroupChoice +import com.ts3client.net.Whisper import com.ts3client.net.ban.BanEntry import com.ts3client.net.ban.BanRule import com.ts3client.net.filetransfer.RemoteFile @@ -185,6 +188,30 @@ class ServerController internal constructor( conn.model.getClient(clientId)?.let { conn.setClientVolumeModifier(it, decibels) } } + // ---- whisper ---- + + fun setWhisper(whisper: Whisper?) = session.setWhisper(whisper) + + fun whisperToChannel(channelId: Int) = conn.model.getChannel(channelId)?.let { setWhisper(Whisper.toChannel(it)) } + + fun whisperToClient(clientId: Int) = conn.model.getClient(clientId)?.let { setWhisper(Whisper.toClient(it)) } + + /** The client who whispered to us last, while on the server. */ + fun lastWhisperer(): ClientEntry? = session.lastWhisperer() + + /** A channel as a whisper list holds it: by path, so the list works on any server with that channel. */ + fun channelRef(channelId: Int): String? = conn.model.getChannel(channelId)?.let { conn.model.channelPath(it.id) } + + fun clientRef(clientId: Int): WhisperList.Client? = + conn.model.getClient(clientId)?.let { WhisperList.Client(it.uniqueId, it.nickname) } + + /** The clients on the server, for adding to a whisper list; ourselves left out. */ + fun clientRefs(): List = if (!session.isConnected) emptyList() + else conn.model.allClients().filter { it.id != conn.selfClientId && !it.uniqueId.isNullOrEmpty() } + .sortedBy { it.nickname.lowercase() }.map { WhisperList.Client(it.uniqueId, it.nickname) } + + fun channelPaths(): List = session.channelPaths() + // ---- channel administration ---- val canCreateChannels: Boolean get() = session.canCreateChannels() @@ -439,6 +466,8 @@ class ServerController internal constructor( inputMode = app.settings.inputMode, hostButton = if (session.isConnected) conn.model.hostButton() else null, self = session.selfState(), + whisper = session.whisper()?.label, + whisperNobody = session.isWhisperingToNobody, ) } diff --git a/android/app/src/main/java/com/ts3client/android/SessionController.kt b/android/app/src/main/java/com/ts3client/android/SessionController.kt index 200a6ce..7ff0689 100644 --- a/android/app/src/main/java/com/ts3client/android/SessionController.kt +++ b/android/app/src/main/java/com/ts3client/android/SessionController.kt @@ -16,6 +16,8 @@ import com.ts3client.config.Bookmark import com.ts3client.config.Bookmarks import com.ts3client.config.IdentityStore import com.ts3client.config.Settings +import com.ts3client.config.WhisperList +import com.ts3client.config.WhisperLists import com.ts3client.contacts.Contact import com.ts3client.contacts.ContactStore import com.ts3client.myts.ChatAttachment @@ -64,6 +66,10 @@ data class SessionState( val hostButton: HostButton? = null, /** What the tree shows for the local client, and the connection notification too. */ val self: SelfState = SelfState.DISCONNECTED, + /** Who the microphone whispers to instead of the channel; null when it talks in the channel. */ + val whisper: String? = null, + /** Whether none of the whisper's channels and clients are on the server, so nobody hears it. */ + val whisperNobody: Boolean = false, ) /** A file to share in chat, open for reading. */ @@ -361,6 +367,37 @@ class SessionController(private val context: Context) { shortcuts.pin(bookmark) } + // ---- whisper lists ---- + + private val whisperListStore = WhisperLists.load() + private val _whisperLists = MutableStateFlow(whisperListCopies()) + val whisperLists: StateFlow> = _whisperLists + + private fun whisperListCopies() = whisperListStore.all().map { it.copy() } + + /** Puts [list] in place of the one at [index], or adds it when [index] is -1. */ + fun saveWhisperList(index: Int, list: WhisperList) { + val all = whisperListStore.all() + if (index in all.indices) all[index] = list.copy() else all.add(list.copy()) + whisperListStore.save() + _whisperLists.value = whisperListCopies() + } + + /** Adds a channel or a client to the list at [index], or to a new list named [newName] when [index] is -1. */ + fun addToWhisperList(index: Int, newName: String, add: (WhisperList) -> Unit) { + val list = whisperListStore.all().getOrNull(index)?.copy() ?: WhisperList(newName) + add(list) + saveWhisperList(index, list) + } + + fun removeWhisperList(index: Int) { + val all = whisperListStore.all() + if (index !in all.indices) return + all.removeAt(index) + whisperListStore.save() + _whisperLists.value = whisperListCopies() + } + // ---- contacts ---- private fun contactCopies(): List = contactStore.all().map { it.copy() } diff --git a/android/app/src/main/java/com/ts3client/android/ui/ServerScreen.kt b/android/app/src/main/java/com/ts3client/android/ui/ServerScreen.kt index 3edb28e..24befc1 100644 --- a/android/app/src/main/java/com/ts3client/android/ui/ServerScreen.kt +++ b/android/app/src/main/java/com/ts3client/android/ui/ServerScreen.kt @@ -79,6 +79,7 @@ import com.ts3client.android.SessionState import com.ts3client.android.TreeFind import com.ts3client.android.findIn import com.ts3client.config.Settings +import com.ts3client.config.WhisperList import com.ts3client.myts.ChatAttachment import com.ts3client.session.ServerLink import com.ts3client.text.TsLink @@ -156,6 +157,9 @@ fun ServerScreen( /** A locked channel whose files are wanted, while its password is asked for. */ var filesLocked by remember { mutableStateOf(null) } var deletingChannel by remember { mutableStateOf(null) } + var whisperLists by rememberSaveable { mutableStateOf(false) } + /** What is being added to a whisper list, while the list is picked: its name and how to add it. */ + var toWhisperList by remember { mutableStateOf Unit>?>(null) } var connectionInfo by rememberSaveable { mutableStateOf(null) } /** The client to move, while a channel for them is being picked. */ var moving by remember { mutableStateOf(null) } @@ -246,6 +250,10 @@ fun ServerScreen( FilesScreen(server, it.channelId, it.name, it.password, onBack = { files = null }) return } + if (whisperLists) { + WhisperListsScreen(vm, server, onBack = { whisperLists = false }) + return + } connectionInfo?.let { id -> ConnectionInfoScreen(server, id, tree.client(id), onBack = { connectionInfo = null }) return @@ -276,6 +284,7 @@ fun ServerScreen( expandedHeight = 48.dp, actions = { state.hostButton?.let { HostButtonAction(it) { url -> runCatching { uriHandler.openUri(url) } } } + if (state.connected) WhisperMenu(vm, server, state) { whisperLists = true } IconButton(onClick = find::show) { PackIcon("FIND", "Find") } IconButton(onClick = onSettings) { PackIcon("SETTINGS", "Settings") } }, @@ -283,9 +292,12 @@ fun ServerScreen( } }, bottomBar = { - val ptt = rememberPttTarget(vm) - VoiceBar(state, ptt.owner != null, ptt.talking, vm, server, onEnableMicrophone, showChat, chats.anyUnread) { - showChat = !showChat + Column { + val ptt = rememberPttTarget(vm) + WhisperBanner(state) { server.setWhisper(null) } + VoiceBar(state, ptt.owner != null, ptt.talking, vm, server, onEnableMicrophone, showChat, chats.anyUnread) { + showChat = !showChat + } } }, snackbarHost = { SnackbarHost(snackbar) }, @@ -386,6 +398,11 @@ fun ServerScreen( onAddContact = { server.addContact(id, it) }, onEditContact = { clientSheet = null; onEditContact(client.uniqueId) }, onConnectionInfo = { clientSheet = null; connectionInfo = id }, + onWhisper = { clientSheet = null; server.whisperToClient(id) }, + onAddToWhisperList = { + clientSheet = null + server.clientRef(id)?.let { ref -> toWhisperList = client.name to { it.clients.add(ref) } } + }, onMove = if (server.canMoveClients) ({ clientSheet = null; moving = id }) else null, onMoveToOwnChannel = if (server.canMoveClients && tree.channel(state.channelId)?.clients?.none { it.id == id } == true) { { server.moveClient(id, state.channelId); clientSheet = null } @@ -412,6 +429,11 @@ fun ServerScreen( onJoin = { join(channel); channelSheet = null }, onSubscribe = { server.setSubscribed(id, it); channelSheet = null }, onBookmark = { channelSheet = null; bookmarkHere(id) }, + onWhisper = { channelSheet = null; server.whisperToChannel(id) }, + onAddToWhisperList = { + channelSheet = null + server.channelRef(id)?.let { ref -> toWhisperList = channel.name to { it.channels.add(ref) } } + }, onFiles = { channelSheet = null if (channel.locked) filesLocked = id else files = FilesOf(id, channel.name, "") @@ -460,6 +482,12 @@ fun ServerScreen( dismissButton = { TextButton(onClick = { deletingChannel = null }) { Text("Cancel") } }, ) } + toWhisperList?.let { (name, add) -> + AddToWhisperListDialog(vm, name, onDismiss = { toWhisperList = null }) { index, newName -> + toWhisperList = null + vm.addToWhisperList(index, newName, add) + } + } if (serverSheet) { remember(tree, infoUpdates) { server.serverDetails() }?.let { ServerSheet(it, onLink, onDismiss = { serverSheet = false }, diff --git a/android/app/src/main/java/com/ts3client/android/ui/Sheets.kt b/android/app/src/main/java/com/ts3client/android/ui/Sheets.kt index df10c92..30e3d61 100644 --- a/android/app/src/main/java/com/ts3client/android/ui/Sheets.kt +++ b/android/app/src/main/java/com/ts3client/android/ui/Sheets.kt @@ -54,6 +54,8 @@ fun ClientSheet( onAddContact: (ContactType) -> Unit, onEditContact: () -> Unit, onConnectionInfo: () -> Unit, + onWhisper: () -> Unit, + onAddToWhisperList: () -> Unit, /** Null when the client cannot be moved. */ onMove: (() -> Unit)?, /** Null when the client cannot be moved, or is in our channel already. */ @@ -95,6 +97,8 @@ fun ClientSheet( } else { Action("PLAYER_CHAT", "Send message", onClick = onMessage) Action("POKE", "Poke") { poking = true } + Action("PLAYER_WHISPER", "Whisper", onClick = onWhisper) + Action("ON_WHISPERLIST", "Add to whisper list…", onClick = onAddToWhisperList) onMove?.let { Action("CHANNEL_SWITCH", "Move to channel…", onClick = it) } onMoveToOwnChannel?.let { Action("MOVE_CLIENT_TO_OWN_CHANNEL", "Move to own channel", onClick = it) } moderation() @@ -129,7 +133,7 @@ fun ClientSheet( } } -/** What can be done with a channel: join it, whether to hear who is in it, its files, and editing it. */ +/** What can be done with a channel: join it, whether to hear who is in it, whisper to it, its files, and editing it. */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun ChannelSheet( @@ -141,6 +145,8 @@ fun ChannelSheet( onJoin: () -> Unit, onSubscribe: (Boolean) -> Unit, onBookmark: () -> Unit, + onWhisper: () -> Unit, + onAddToWhisperList: () -> Unit, onFiles: () -> Unit, /** Each null when we may not. */ onCreateSub: (() -> Unit)?, @@ -160,6 +166,8 @@ fun ChannelSheet( } else { Action("SUBSCRIBE_TO_CHANNEL", "Subscribe") { onSubscribe(true) } } + Action("WHISPER", "Whisper", onClick = onWhisper) + Action("ON_WHISPERLIST", "Add to whisper list…", onClick = onAddToWhisperList) Action("FILETRANSFER", "Browse files", onClick = onFiles) Action("BOOKMARK_ADD", "Add to bookmarks", onClick = onBookmark) onCreateSub?.let { Action("CHANNEL_CREATE_SUB", "Create sub-channel", onClick = it) } diff --git a/android/app/src/main/java/com/ts3client/android/ui/Whisper.kt b/android/app/src/main/java/com/ts3client/android/ui/Whisper.kt new file mode 100644 index 0000000..40334b2 --- /dev/null +++ b/android/app/src/main/java/com/ts3client/android/ui/Whisper.kt @@ -0,0 +1,254 @@ +package com.ts3client.android.ui + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.ts3client.android.ServerController +import com.ts3client.android.SessionController +import com.ts3client.android.SessionState +import com.ts3client.config.WhisperList +import com.ts3client.net.Whisper + +/** Says the microphone whispers instead of talking in the channel, until stopped. */ +@Composable +fun WhisperBanner(state: SessionState, onStop: () -> Unit) { + val target = state.whisper ?: return + Surface(color = MaterialTheme.colorScheme.tertiaryContainer) { + Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) { + PackIcon("WHISPER", null) + Column(Modifier.weight(1f).padding(horizontal = 12.dp)) { + Text("Whispering to $target", maxLines = 1, overflow = TextOverflow.Ellipsis, + style = MaterialTheme.typography.bodyMedium) + if (state.whisperNobody) { + Text("Nobody there", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) + } + } + TextButton(onClick = onStop) { Text("Stop") } + } + } +} + +/** The top bar's whisper button: a list to whisper to, a reply to the last whisper, the lists' editor. */ +@Composable +fun WhisperMenu(vm: SessionController, server: ServerController, state: SessionState, onManage: () -> Unit) { + val lists by vm.whisperLists.collectAsStateWithLifecycle() + var open by remember { mutableStateOf(false) } + Box { + IconButton(onClick = { open = true }) { PackIcon("WHISPER", "Whisper") } + DropdownMenu(open, { open = false }) { + val replyTo = remember(open) { server.lastWhisperer() } + replyTo?.let { client -> + DropdownMenuItem({ Text("Reply to ${client.nickname}") }, leadingIcon = { PackIcon("PLAYER_WHISPER", null) }, + onClick = { open = false; server.whisperToClient(client.id) }) + } + for (list in lists) { + DropdownMenuItem({ Text(list.name.ifBlank { "Unnamed" }) }, + leadingIcon = { PackIcon("ON_WHISPERLIST", null) }, + enabled = !list.isEmpty, + onClick = { open = false; server.setWhisper(Whisper.of(list)) }) + } + if (state.whisper != null) { + DropdownMenuItem({ Text("Stop whispering") }, leadingIcon = { PackIcon("WHISPER", null) }, + onClick = { open = false; server.setWhisper(null) }) + } + if (replyTo != null || lists.isNotEmpty() || state.whisper != null) HorizontalDivider() + DropdownMenuItem({ Text("Whisper lists…") }, leadingIcon = { PackIcon("WHISPERLISTS", null) }, + onClick = { open = false; onManage() }) + } + } +} + +/** Picks the whisper list to add something to, or names a new one. */ +@Composable +fun AddToWhisperListDialog(vm: SessionController, what: String, onDismiss: () -> Unit, onPick: (index: Int, newName: String) -> Unit) { + val lists by vm.whisperLists.collectAsStateWithLifecycle() + var naming by remember { mutableStateOf(false) } + if (naming) { + TextPrompt("New whisper list", "Name", "Add", onDismiss = onDismiss, onConfirm = { + if (it.isNotBlank()) onPick(-1, it.trim()) else onDismiss() + }) + return + } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("Add $what to") }, + text = { + Column(Modifier.verticalScroll(rememberScrollState())) { + lists.forEachIndexed { index, list -> + ListItem(headlineContent = { Text(list.name.ifBlank { "Unnamed" }) }, + modifier = Modifier.clickable { onPick(index, "") }) + } + ListItem(headlineContent = { Text("New list…") }, modifier = Modifier.clickable { naming = true }) + } + }, + confirmButton = {}, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) +} + +/** The saved whisper lists, each opening onto its channels and clients. */ +@Composable +fun WhisperListsScreen(vm: SessionController, server: ServerController, onBack: () -> Unit) { + val lists by vm.whisperLists.collectAsStateWithLifecycle() + /** The list being edited: its index, -1 for a new one; null on the overview. */ + var editing by rememberSaveable { mutableStateOf(null) } + editing?.let { index -> + WhisperListScreen(vm, server, index, lists.getOrNull(index) ?: WhisperList(), onBack = { editing = null }) + return + } + SubScreen("Whisper lists", onBack = onBack, actions = { + TextButton(onClick = { editing = -1 }) { Text("New") } + }) { padding -> + if (lists.isEmpty()) { + Box(Modifier.padding(padding).fillMaxWidth().padding(24.dp)) { + Text("No whisper lists", color = MaterialTheme.colorScheme.onSurfaceVariant) + } + return@SubScreen + } + LazyColumn(Modifier.padding(padding)) { + itemsIndexed(lists) { index, list -> + var menu by remember { mutableStateOf(false) } + ListItem( + headlineContent = { Text(list.name.ifBlank { "Unnamed" }) }, + supportingContent = { Text(summary(list)) }, + leadingContent = { PackIcon("ON_WHISPERLIST", null) }, + trailingContent = { + Box { + IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "List options") } + DropdownMenu(menu, { menu = false }) { + DropdownMenuItem({ Text("Whisper") }, enabled = !list.isEmpty, onClick = { + menu = false + server.setWhisper(Whisper.of(list)) + onBack() + }) + DropdownMenuItem({ Text("Remove") }, onClick = { menu = false; vm.removeWhisperList(index) }) + } + } + }, + modifier = Modifier.clickable { editing = index }, + ) + } + } + } +} + +private fun summary(list: WhisperList): String { + val parts = listOfNotNull( + list.channels.size.takeIf { it > 0 }?.let { if (it == 1) "1 channel" else "$it channels" }, + list.clients.size.takeIf { it > 0 }?.let { if (it == 1) "1 client" else "$it clients" }, + ) + return parts.joinToString(", ").ifEmpty { "Empty" } +} + +/** One whisper list: its name, channels and clients, saved on Save. */ +@Composable +private fun WhisperListScreen(vm: SessionController, server: ServerController, index: Int, saved: WhisperList, onBack: () -> Unit) { + var name by rememberSaveable { mutableStateOf(saved.name) } + var list by remember { mutableStateOf(saved.copy()) } + val change = { f: WhisperList.() -> Unit -> list = list.copy().apply(f) } + var addingChannel by remember { mutableStateOf(false) } + var addingClient by remember { mutableStateOf(false) } + + SubScreen(if (index < 0) "New whisper list" else "Edit whisper list", onBack = onBack, actions = { + TextButton(onClick = { + vm.saveWhisperList(index, list.copy().apply { this.name = name.trim() }) + onBack() + }, enabled = name.isNotBlank()) { Text("Save") } + }) { padding -> + LazyColumn(Modifier.padding(padding)) { + item { + OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth().padding(16.dp), label = { Text("Name") }, + singleLine = true) + } + item { Section("Channels") } + items(list.channels) { channel -> + RemovableRow("CHANNEL_GREEN", channel) { change { channels.remove(channel) } } + } + item { LinkRow("Add channel…", null, "CHANNEL_CREATE") { addingChannel = true } } + item { Section("Clients") } + items(list.clients) { client -> + RemovableRow("PLAYER_WHISPER", client.nickname.ifBlank { client.uniqueId }) { change { clients.remove(client) } } + } + item { LinkRow("Add client…", null, "ADD_FRIEND") { addingClient = true } } + } + } + + if (addingChannel) { + val paths = remember { server.channelPaths().filter { it !in list.channels } } + ChoiceDialog("Add channel", paths, { it }, onDismiss = { addingChannel = false }) { + addingChannel = false + change { channels.add(it) } + } + } + if (addingClient) { + val online = remember { server.clientRefs().filter { c -> list.clients.none { it.uniqueId == c.uniqueId } } } + ChoiceDialog("Add client", online, { it.nickname }, onDismiss = { addingClient = false }) { + addingClient = false + change { clients.add(it) } + } + } +} + +@Composable +private fun RemovableRow(iconKey: String, label: String, onRemove: () -> Unit) { + ListItem( + headlineContent = { Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + leadingContent = { PackIcon(iconKey, null) }, + trailingContent = { IconButton(onClick = onRemove) { Icon(Icons.Default.Close, "Remove") } }, + ) +} + +/** Picks one of [choices], of the server on screen; says so when it has none. */ +@Composable +private fun ChoiceDialog(title: String, choices: List, label: (T) -> String, onDismiss: () -> Unit, onPick: (T) -> Unit) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(title) }, + text = { + if (choices.isEmpty()) Text("Nothing to add on this server") + else LazyColumn(Modifier.heightIn(max = 400.dp)) { + items(choices) { choice -> + ListItem(headlineContent = { Text(label(choice), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + modifier = Modifier.clickable { onPick(choice) }) + } + } + }, + confirmButton = {}, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) +} diff --git a/ts3-client/core/src/main/java/com/ts3client/config/WhisperList.java b/ts3-client/core/src/main/java/com/ts3client/config/WhisperList.java new file mode 100644 index 0000000..fa18575 --- /dev/null +++ b/ts3-client/core/src/main/java/com/ts3client/config/WhisperList.java @@ -0,0 +1,40 @@ +package com.ts3client.config; + +import java.util.ArrayList; +import java.util.List; + +/** A saved set of channels and clients to whisper to, wherever they are on the server we are on. */ +public final class WhisperList { + + /** A client by unique id, so the list finds them under any client id; the nickname is for showing. */ + public record Client(String uniqueId, String nickname) { + } + + public String name = ""; + /** Channel references as {@link Bookmark#channel} holds them: "/"-separated paths or "/<id>". */ + public final List channels = new ArrayList<>(); + public final List clients = new ArrayList<>(); + + public WhisperList() { + } + + public WhisperList(String name) { + this.name = name; + } + + public WhisperList copy() { + WhisperList c = new WhisperList(name); + c.channels.addAll(channels); + c.clients.addAll(clients); + return c; + } + + public boolean isEmpty() { + return channels.isEmpty() && clients.isEmpty(); + } + + @Override + public String toString() { + return name; + } +} diff --git a/ts3-client/core/src/main/java/com/ts3client/config/WhisperLists.java b/ts3-client/core/src/main/java/com/ts3client/config/WhisperLists.java new file mode 100644 index 0000000..b204ac4 --- /dev/null +++ b/ts3-client/core/src/main/java/com/ts3client/config/WhisperLists.java @@ -0,0 +1,93 @@ +package com.ts3client.config; + +import java.io.File; +import java.io.FileInputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +/** The saved {@link WhisperList}s, shared by every server. */ +public final class WhisperLists { + + private static File file() { + return AppDirs.file("whisperlists.properties"); + } + + private final List entries = new ArrayList<>(); + + public List all() { + return entries; + } + + /** The list with this name, ignoring case, or null. */ + public WhisperList find(String name) { + for (WhisperList l : entries) { + if (l.name.equalsIgnoreCase(name)) return l; + } + return null; + } + + public static WhisperLists load() { + WhisperLists lists = new WhisperLists(); + if (!file().isFile()) return lists; + Properties p = new Properties(); + try (FileInputStream in = new FileInputStream(file())) { + p.load(in); + } catch (Exception e) { + return lists; + } + int count = parseInt(p.getProperty("count")); + for (int i = 0; i < count; i++) { + String prefix = "list." + i + "."; + WhisperList list = new WhisperList(p.getProperty(prefix + "name", "")); + int channels = parseInt(p.getProperty(prefix + "channels")); + for (int j = 0; j < channels; j++) { + String channel = p.getProperty(prefix + "channel." + j, ""); + if (!channel.isBlank()) list.channels.add(channel); + } + int clients = parseInt(p.getProperty(prefix + "clients")); + for (int j = 0; j < clients; j++) { + String uid = p.getProperty(prefix + "client." + j + ".uid", ""); + if (!uid.isBlank()) { + list.clients.add(new WhisperList.Client(uid, p.getProperty(prefix + "client." + j + ".name", ""))); + } + } + lists.entries.add(list); + } + return lists; + } + + public void save() { + Properties p = new Properties(); + p.setProperty("count", Integer.toString(entries.size())); + for (int i = 0; i < entries.size(); i++) { + WhisperList list = entries.get(i); + String prefix = "list." + i + "."; + p.setProperty(prefix + "name", list.name); + p.setProperty(prefix + "channels", Integer.toString(list.channels.size())); + for (int j = 0; j < list.channels.size(); j++) { + p.setProperty(prefix + "channel." + j, list.channels.get(j)); + } + p.setProperty(prefix + "clients", Integer.toString(list.clients.size())); + for (int j = 0; j < list.clients.size(); j++) { + WhisperList.Client c = list.clients.get(j); + p.setProperty(prefix + "client." + j + ".uid", c.uniqueId()); + p.setProperty(prefix + "client." + j + ".name", c.nickname() == null ? "" : c.nickname()); + } + } + try { + AppDirs.createProfile(); + ProfileFiles.write(file(), out -> p.store(out, "TS3J client whisper lists")); + } catch (Exception ignored) { + } + } + + private static int parseInt(String v) { + if (v == null) return 0; + try { + return Integer.parseInt(v.trim()); + } catch (NumberFormatException e) { + return 0; + } + } +} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/TeamspeakConnection.java b/ts3-client/core/src/main/java/com/ts3client/net/TeamspeakConnection.java index c8a0189..6fb3cae 100644 --- a/ts3-client/core/src/main/java/com/ts3client/net/TeamspeakConnection.java +++ b/ts3-client/core/src/main/java/com/ts3client/net/TeamspeakConnection.java @@ -9,6 +9,7 @@ import com.github.manevolent.ts3j.event.*; import com.github.manevolent.ts3j.identity.LocalIdentity; import com.github.manevolent.ts3j.identity.Uid; import com.github.manevolent.ts3j.protocol.ProtocolRole; +import com.github.manevolent.ts3j.protocol.packet.PacketBody1VoiceWhisper; import com.github.manevolent.ts3j.protocol.socket.client.LocalTeamspeakClientSocket; import com.github.manevolent.ts3j.util.Ts3Crypt; import com.ts3client.audio.AudioBackend; @@ -121,6 +122,8 @@ public final class TeamspeakConnection implements TS3Listener { */ /** Package-private: read directly by {@link ConnectionStatsCollector}. */ volatile LocalTeamspeakClientSocket client; + /** The client whose whisper we heard last, to reply to; 0 for none yet. */ + private volatile int lastWhisperer; private volatile VoiceInput microphone; private volatile VoiceOutput playback; private volatile LocalIdentity identity; @@ -291,6 +294,7 @@ public final class TeamspeakConnection implements TS3Listener { serverPort = port; model.clear(); + lastWhisperer = 0; playback = audio.createOutput(settings); playback.setMasterVolume(settings.effectiveOutputVolume()); playback.setReceiveBuffer(settings.receiveBuffer); @@ -336,7 +340,9 @@ public final class TeamspeakConnection implements TS3Listener { client.addListener(events); client.setVoiceHandler(playback::handleVoice); client.setWhisperHandler(whisper -> { - if (isWhisperAllowed(whisper.getClientId())) playback.handleWhisper(whisper); + if (!isWhisperAllowed(whisper.getClientId())) return; + lastWhisperer = whisper.getClientId(); + playback.handleWhisper(whisper); }); client.setExceptionHandler(t -> { // A late packet dispatched after close() rejects on the shut-down @@ -1623,6 +1629,28 @@ public final class TeamspeakConnection implements TS3Listener { return ft.downloadToMemory(0, "", "/" + name, AvatarAdmin.MAX_AVATAR_DOWNLOAD_BYTES); } + // ---- whisper ---- + + /** Sends the microphone's voice to {@code targets} as a whisper, or to our channel again with null. */ + public void setWhisperTargets(Whisper.Targets targets) { + LocalTeamspeakClientSocket sock = client; + if (sock == null) return; + if (targets == null) { + sock.setWhisperTarget(null); + return; + } + PacketBody1VoiceWhisper.WhisperTargetMultiple target = new PacketBody1VoiceWhisper.WhisperTargetMultiple(); + target.setChannelIds(targets.channelIds()); + target.setClientIds(targets.clientIds()); + sock.setWhisperTarget(target); + } + + /** The client who whispered to us last, if still on the server. */ + public ClientEntry lastWhisperer() { + int id = lastWhisperer; + return id == 0 ? null : model.getClient(id); + } + // ---- file transfers ---- /** Whether a live connection capable of file transfers is available. */ diff --git a/ts3-client/core/src/main/java/com/ts3client/net/Whisper.java b/ts3-client/core/src/main/java/com/ts3client/net/Whisper.java new file mode 100644 index 0000000..5818065 --- /dev/null +++ b/ts3-client/core/src/main/java/com/ts3client/net/Whisper.java @@ -0,0 +1,76 @@ +package com.ts3client.net; + +import com.ts3client.config.WhisperList; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * Where the microphone whispers to instead of talking in our channel: channels and clients, + * found on the server by reference so they follow renames, moves and reconnects. + */ +public final class Whisper { + + /** What the whisper is shown as: the list's, the channel's or the client's name. */ + public final String label; + /** Channel references as {@link ServerModel#findChannelByPath} reads them. */ + private final List channels; + private final List clientUniqueIds; + + private Whisper(String label, List channels, List clientUniqueIds) { + this.label = label; + this.channels = channels; + this.clientUniqueIds = clientUniqueIds; + } + + public static Whisper toChannel(ChannelNode channel) { + return new Whisper(channel.name, List.of("/" + channel.id), List.of()); + } + + public static Whisper toClient(ClientEntry client) { + return new Whisper(client.nickname, List.of(), List.of(client.uniqueId)); + } + + public static Whisper of(WhisperList list) { + List uids = new ArrayList<>(); + for (WhisperList.Client c : list.clients) uids.add(c.uniqueId()); + return new Whisper(list.name, List.copyOf(list.channels), uids); + } + + /** Who hears it on the server as it is now; what is not there is left out. */ + public Targets resolve(ServerModel model) { + Set channelIds = new LinkedHashSet<>(); + for (String ref : channels) { + ChannelNode c = model.findChannelByPath(ref); + if (c != null) channelIds.add(c.id); + } + Set clientIds = new LinkedHashSet<>(); + for (String uid : clientUniqueIds) { + ClientEntry c = model.findClientByUniqueId(uid); + if (c != null) clientIds.add(c.id); + } + return new Targets(channelIds.stream().mapToInt(Integer::intValue).toArray(), + clientIds.stream().mapToInt(Integer::intValue).toArray()); + } + + /** The channel and client ids a whisper goes to. */ + public record Targets(int[] channelIds, int[] clientIds) { + + public boolean isEmpty() { + return channelIds.length == 0 && clientIds.length == 0; + } + + @Override + public boolean equals(Object o) { + return o instanceof Targets t && Arrays.equals(channelIds, t.channelIds) && Arrays.equals(clientIds, t.clientIds); + } + + @Override + public int hashCode() { + return 31 * Arrays.hashCode(channelIds) + Arrays.hashCode(clientIds); + } + } +} diff --git a/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java b/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java index 07390c1..8e9a8d5 100644 --- a/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java +++ b/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java @@ -14,6 +14,7 @@ import com.ts3client.net.ClientEntry; import com.ts3client.net.ConnectionListener; import com.ts3client.net.ServerModel; import com.ts3client.net.TeamspeakConnection; +import com.ts3client.net.Whisper; import com.ts3client.recording.VoiceRecorder; import com.ts3client.sound.SoundNotifier; @@ -95,6 +96,10 @@ public final class ServerSession { /** Away message currently published, empty when away carries no message. */ private volatile String awayMessage = ""; private volatile boolean commander; + /** Where the microphone whispers to; null when it talks in our channel. */ + private volatile Whisper whisper; + /** {@link #whisper} as last resolved on the server, to resend only when it changes. */ + private volatile Whisper.Targets whisperTargets; public ServerSession(Settings settings, IdentityStore identities, AudioBackend audio, SoundNotifier sounds, ContactStore contacts, Listener listener) { @@ -388,6 +393,44 @@ public final class ServerSession { if (conn.isConnected()) conn.setPhoneticNickname(phoneticNickname); } + // ---- whisper ---- + + public Whisper whisper() { + return whisper; + } + + /** Whispers to {@code whisper} from now on, or talks in our channel again with null. */ + public void setWhisper(Whisper whisper) { + this.whisper = whisper; + whisperTargets = null; + if (whisper == null) conn.setWhisperTargets(null); + else updateWhisperTargets(); + listener.onSessionChanged(); + } + + /** Whether whispering finds nobody there now, so nobody hears it. */ + public boolean isWhisperingToNobody() { + Whisper.Targets targets = whisperTargets; + return whisper != null && targets != null && targets.isEmpty(); + } + + /** The client who whispered to us last, to whisper back to; null when none is on. */ + public ClientEntry lastWhisperer() { + return conn.isConnected() ? conn.lastWhisperer() : null; + } + + /** Follows the whisper's channels and clients around the server. */ + private void updateWhisperTargets() { + Whisper w = whisper; + if (w == null || !conn.isConnected()) return; + Whisper.Targets targets = w.resolve(conn.getModel()); + if (targets.equals(whisperTargets)) return; + boolean wasEmpty = isWhisperingToNobody(); + whisperTargets = targets; + conn.setWhisperTargets(targets); + if (targets.isEmpty() != wasEmpty) listener.onSessionChanged(); + } + /** What the local client looks like on this server. */ public SelfState selfState() { if (!conn.isConnected()) return SelfState.DISCONNECTED; @@ -715,6 +758,9 @@ public final class ServerSession { @Override public void onDisconnected(String reason) { connecting = false; + // Channels and clients are this server's; another one has its own. + whisper = null; + whisperTargets = null; serverIconId = -1; conn.getModel().clear(); listener.onDisconnected(reason); @@ -733,6 +779,7 @@ public final class ServerSession { listener.onSessionChanged(); } checkServerIcon(); + updateWhisperTargets(); listener.onModelChanged(); } diff --git a/ts3j b/ts3j index 2d6f5cd..1430782 160000 --- a/ts3j +++ b/ts3j @@ -1 +1 @@ -Subproject commit 2d6f5cdf787051578ea66d31737aef298f2f2352 +Subproject commit 1430782e2ae5443317af8076ca31e28507b5bf11