Chat lines are routed once, in core

session.ChatFeed decides which conversation a message, history, server
event or notice goes to and renders it; frontends get the lines through
chat.ChatSink and key conversations by chat.ChatKey. ServerSession.Listener
no longer passes on raw chat events. Swing now labels our own messages
with our nickname on the server and links our name to us in private chats.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-12 23:37:33 +00:00
co-authored by Claude Opus 5.5
parent 53585994a8
commit a2a12804ad
19 changed files with 447 additions and 372 deletions
@@ -0,0 +1,30 @@
package eu.lixko.ts3j.client.chat;
/**
* One conversation on a server: its server chat, its channel chat, or the private chat with a
* client.
*
* @param clientId the peer of a private chat; 0 for the others
*/
public record ChatKey(ChatScope scope, int clientId) {
public static final ChatKey SERVER = new ChatKey(ChatScope.SERVER, 0);
public static final ChatKey CHANNEL = new ChatKey(ChatScope.CHANNEL, 0);
public static ChatKey privateWith(int clientId) {
return new ChatKey(ChatScope.PRIVATE, clientId);
}
/** The conversation a message in {@code scope} belongs to; {@code peerClientId} counts only for a private one. */
public static ChatKey of(ChatScope scope, int peerClientId) {
return switch (scope) {
case SERVER -> SERVER;
case CHANNEL -> CHANNEL;
case PRIVATE -> privateWith(peerClientId);
};
}
public boolean isPrivate() {
return scope == ChatScope.PRIVATE;
}
}
@@ -0,0 +1,30 @@
package eu.lixko.ts3j.client.chat;
import java.util.List;
/**
* Where a server's chat lines go, already rendered as {@link eu.lixko.ts3j.client.text.ChatHtml}
* HTML. The frontend keeps and shows them; calls arrive on connection threads.
*/
public interface ChatSink {
/**
* Adds a line to a conversation, opening a private one if it is not open.
*
* @param title the peer's name for a private chat; empty for the server and channel chats
*/
void append(ChatKey key, String title, String html);
/** Replaces a conversation's lines with what its log held, opening a private one if needed. */
void setHistory(ChatKey key, String title, List<String> html);
/**
* The server's or the channel's name, which their conversations go by.
*
* @param name blank while there is none, e.g. when not connected
*/
void rename(ChatKey key, String name);
/** Leaving the server ends its private chats. */
void closePrivateChats();
}
@@ -4,10 +4,7 @@ import eu.lixko.ts3j.client.chat.ChatScope;
import java.util.List;
/**
* UI-facing callbacks fired by {@link TeamspeakConnection}. Implementations are
* responsible for marshalling to the Swing EDT.
*/
/** What a {@link TeamspeakConnection} tells its session; calls arrive on connection threads. */
public interface ConnectionListener {
void onStatus(String status);
@@ -0,0 +1,75 @@
package eu.lixko.ts3j.client.session;
import eu.lixko.ts3j.client.chat.ChatKey;
import eu.lixko.ts3j.client.chat.ChatScope;
import eu.lixko.ts3j.client.chat.ChatSink;
import eu.lixko.ts3j.client.text.ChatHtml;
import java.util.List;
import java.util.function.Supplier;
/** Turns a session's chat events into the lines of its conversations. */
final class ChatFeed {
private final ChatSink sink;
/** The server's unique id, where files shared in its chats lie; empty before it is known. */
private final Supplier<String> room;
private String serverName = "";
private String channelName = "";
ChatFeed(ChatSink sink, Supplier<String> room) {
this.sink = sink;
this.room = room;
}
/** Someone else's message; a private one goes to the chat with its sender. */
void received(ChatScope scope, int fromClientId, String fromUniqueId, String fromName, String message) {
sink.append(ChatKey.of(scope, fromClientId), fromName,
ChatHtml.message(fromClientId, fromUniqueId, fromName, message, room.get()));
}
/** A message we sent; a private one goes to the chat with {@code peerClientId}. */
void sent(ChatScope scope, int peerClientId, String peerName, int selfId, String selfUniqueId, String selfName,
String message) {
sink.append(ChatKey.of(scope, peerClientId), peerName,
ChatHtml.message(selfId, selfUniqueId, selfName + " (you)", message, room.get()));
}
void history(ChatKey key, String title, List<String> logEntries) {
String room = this.room.get();
List<String> lines = logEntries.stream().map(e -> ChatHtml.logEntry(e, room)).filter(l -> !l.isEmpty())
.toList();
sink.setHistory(key, title, lines);
}
/** One of the chat's own notices: connection progress, errors, pokes. */
void system(String text) {
sink.append(ChatKey.SERVER, "", ChatHtml.system(text));
}
void serverLog(String text) {
sink.append(ChatKey.SERVER, "", ChatHtml.serverLog(text));
}
void serverLogHtml(String html) {
String line = ChatHtml.logEntry(html, room.get());
if (!line.isEmpty()) sink.append(ChatKey.SERVER, "", line);
}
/** Where we are now; the server and channel chats are renamed when it changed. */
synchronized void names(String server, String channel) {
if (!server.equals(serverName)) {
serverName = server;
sink.rename(ChatKey.SERVER, server);
}
if (!channel.equals(channelName)) {
channelName = channel;
sink.rename(ChatKey.CHANNEL, channel);
}
}
synchronized void disconnected() {
sink.closePrivateChats();
names("", "");
}
}
@@ -1,7 +1,9 @@
package eu.lixko.ts3j.client.session;
import eu.lixko.ts3j.client.audio.AudioBackend;
import eu.lixko.ts3j.client.chat.ChatKey;
import eu.lixko.ts3j.client.chat.ChatScope;
import eu.lixko.ts3j.client.chat.ChatSink;
import eu.lixko.ts3j.client.config.Bookmark;
import eu.lixko.ts3j.client.config.IdentityEntry;
import eu.lixko.ts3j.client.config.IdentityStore;
@@ -48,6 +50,7 @@ import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.stream.Collectors;
@@ -66,25 +69,45 @@ import java.util.stream.Collectors;
*/
public final class ServerSession {
/** Everything a {@link ConnectionListener} hears, plus what the session adds. */
public interface Listener extends ConnectionListener {
/** What a frontend hears of the session; the chat's lines come through {@link ChatSink}. */
public interface Listener extends ChatSink {
/**
* The session's title, status, connecting state or self flags changed. Also
* delivers what {@link #onStatus} does, so frontends usually only need this one.
*/
/** The session's title, status, connecting state or self flags changed. */
void onSessionChanged();
/** A line for the chat's own log: connection progress, errors, pokes. */
void onSystemMessage(String text);
void onConnected();
/**
* The local client sent a chat message.
*
* @param peerClientId the recipient of a private message, else 0
* @param peerName the recipient's display name for a private message, else empty
*/
void onOwnChat(ChatScope scope, int peerClientId, String peerName, String text);
void onDisconnected(String reason);
/** The channel/client model changed and any tree view should be rebuilt. */
void onModelChanged();
/** On-demand channel/client details finished loading; refresh any info view. */
void onInfoUpdated();
/** A group icon finished downloading; repaint anything showing icons. */
void onIconsUpdated();
/** A client (possibly the local one) started or stopped talking. */
void onTalkStateChanged(int clientId, boolean talking);
/** Also told in the chat and the status. */
void onError(String message);
/** Someone poked the local client; also told in the chat. */
void onPoke(String fromName, String message);
/** Our offline message inbox's unread count changed, or became known on connecting. */
default void onUnreadMessagesChanged(int unread) {
}
/** A private message came in, e.g. for a notification; its line comes through {@link #append}. */
default void onPrivateMessage(int fromClientId, String fromName, String message) {
}
/** We sent a private message; its line comes through {@link #append}. */
default void onPrivateMessageSent(int toClientId, String message) {
}
/**
* The server's icon is known or changed (0: it has none), and is on its way to the
@@ -97,6 +120,7 @@ public final class ServerSession {
private final Settings settings;
private final IdentityStore identities;
private final Listener listener;
private final ChatFeed chat;
private final TeamspeakConnection conn;
private final OwnClient own;
private final Recording recording;
@@ -130,6 +154,7 @@ public final class ServerSession {
this.identities = identities;
this.listener = listener;
this.conn = new TeamspeakConnection(settings, audio, new Events(), sounds, contacts);
this.chat = new ChatFeed(listener, () -> Objects.requireNonNullElse(conn.serverUniqueId(), ""));
this.own = conn.ownClient();
this.recording = conn.recording();
}
@@ -254,7 +279,7 @@ public final class ServerSession {
lastTarget = new Target(address, port, nickname, password, channelPassword);
lastChannelPath = channel == null ? "" : channel;
title = address + ":" + port;
listener.onSystemMessage("Connecting to " + address + ":" + port
chat.system("Connecting to " + address + ":" + port
+ (channel == null || channel.isBlank() ? "" : " (channel \"" + channel + "\")") + " …");
setStatus("Loading identity…");
@@ -270,7 +295,7 @@ public final class ServerSession {
return;
}
this.identityId = entry.getId();
listener.onSystemMessage("Using identity \"" + entry.getName() + "\".");
chat.system("Using identity \"" + entry.getName() + "\".");
conn.connect(address, port, nicknameFor(nickname, entry), entry.getPhoneticNickname(), password,
entry.getIdentity(), channel, channelPassword);
}, "identity-resolve").start();
@@ -619,17 +644,17 @@ public final class ServerSession {
if (dir != null) Files.createDirectories(dir);
rec = recording.start(mode, file);
} catch (IOException | RuntimeException e) {
listener.onSystemMessage("Failed to start recording: " + e.getMessage());
chat.system("Failed to start recording: " + e.getMessage());
return;
}
boolean multitrack = mode == VoiceRecorder.Mode.MULTITRACK;
listener.onSystemMessage((multitrack ? "Started multitrack recording: " : "Started recording: ") + file);
chat.system((multitrack ? "Started multitrack recording: " : "Started recording: ") + file);
rec.whenDone().whenComplete((files, error) -> {
if (error != null) {
Throwable cause = error.getCause() != null ? error.getCause() : error;
listener.onSystemMessage("Recording failed: " + cause.getMessage());
chat.system("Recording failed: " + cause.getMessage());
} else {
listener.onSystemMessage((multitrack ? "Stopped multitrack recording: " : "Stopped recording: ")
chat.system((multitrack ? "Stopped multitrack recording: " : "Stopped recording: ")
+ files.stream().map(Path::toString).collect(Collectors.joining(", ")));
}
listener.onSessionChanged();
@@ -644,53 +669,45 @@ public final class ServerSession {
// ---- chat ----
/**
* Sends a chat message and reports it back through {@link Listener#onOwnChat}.
*
* @param clientId the recipient of a private message; ignored otherwise
*/
public void sendChat(ChatScope scope, int clientId, String text) {
/** Sends a chat message, which then shows in the conversation like any other. */
public void sendChat(ChatKey key, String text) {
if (!conn.isConnected()) {
listener.onSystemMessage("Not connected.");
chat.system("Not connected.");
return;
}
switch (scope) {
case SERVER -> {
conn.sendServerMessage(text);
listener.onOwnChat(scope, 0, "", text);
}
case PRIVATE -> {
conn.sendPrivateMessage(clientId, text);
listener.onOwnChat(scope, clientId, peerName(clientId), text);
}
default -> {
conn.sendChannelMessage(text);
listener.onOwnChat(scope, 0, "", text);
}
switch (key.scope()) {
case SERVER -> conn.sendServerMessage(text);
case CHANNEL -> conn.sendChannelMessage(text);
case PRIVATE -> conn.sendPrivateMessage(key.clientId(), text);
}
ClientEntry self = own.entry();
String selfName = self != null ? self.nickname : settings.nickname.get();
String peerName = key.isPrivate() ? peerName(key.clientId()) : "";
chat.sent(key.scope(), key.clientId(), peerName, selfClientId(), selfUniqueId(), selfName, text);
if (key.isPrivate()) listener.onPrivateMessageSent(key.clientId(), text);
}
/**
* Shares a file in a chat as TeamSpeak 6 does: stores it in this user's myTeamSpeak
* cloud storage, then sends the message pointing to it. Runs in the background; a failure
* is reported through {@link Listener#onSystemMessage}.
* is told in the chat.
*
* @param data read and closed in the background
*/
public void sendAttachment(ChatScope scope, int clientId, ChatAttachments attachments,
public void sendAttachment(ChatKey key, ChatAttachments attachments,
InputStream data, long size, String fileName) {
String room = conn.serverUniqueId();
if (!conn.isConnected() || room == null) {
closeQuietly(data);
listener.onSystemMessage("Not connected.");
chat.system("Not connected.");
return;
}
Thread t = new Thread(() -> {
try (InputStream in = data) {
ChatAttachment attachment = attachments.upload(in, size, fileName, room);
sendChat(scope, clientId, attachment.toMessage());
sendChat(key, attachment.toMessage());
} catch (IOException | MyTsException e) {
listener.onSystemMessage("Could not share " + fileName + ": " + e.getMessage());
chat.system("Could not share " + fileName + ": " + e.getMessage());
}
}, "ts3-attachment-upload");
t.setDaemon(true);
@@ -709,7 +726,7 @@ public final class ServerSession {
return c != null ? conn.contacts().displayName(c) : "Client " + clientId;
}
/** Hands {@link Listener#onPrivateChatHistory} what was said with a client before. */
/** Loads what was said with a client before, into their private chat through {@link ChatSink#setHistory}. */
public void loadPrivateChatHistory(int clientId, String uniqueId) {
conn.loadPrivateChatHistory(clientId, uniqueId);
}
@@ -839,12 +856,11 @@ public final class ServerSession {
private void setStatus(String text) {
status = text;
listener.onStatus(text);
listener.onSessionChanged();
}
private void reportError(String message) {
listener.onSystemMessage("Error: " + message);
chat.system("Error: " + message);
listener.onError(message);
setStatus(message);
}
@@ -855,8 +871,8 @@ public final class ServerSession {
Target target = lastTarget;
if (link == null || target == null || !link.pointsAt(target.address(), target.port())) return;
Replies.handle(conn.privilegeKeys().use(link.token), Runnable::run,
() -> listener.onSystemMessage("Privilege key used."),
failure -> listener.onSystemMessage("Could not use the privilege key: " + failure.getMessage()));
() -> chat.system("Privilege key used."),
failure -> chat.system("Could not use the privilege key: " + failure.getMessage()));
}
private void checkServerIcon() {
@@ -881,7 +897,7 @@ public final class ServerSession {
connecting = false;
reconnects.connected();
listener.onConnected();
listener.onSystemMessage("Connected.");
chat.system("Connected.");
listener.onSessionChanged();
checkServerIcon();
useConnectToken();
@@ -895,8 +911,9 @@ public final class ServerSession {
whisperTargets = null;
serverIconId = -1;
conn.getModel().clear();
chat.disconnected();
listener.onDisconnected(reason);
listener.onSystemMessage("Disconnected" + (reason == null || reason.isEmpty() ? "." : ": " + reason));
chat.system("Disconnected" + (reason == null || reason.isEmpty() ? "." : ": " + reason));
reconnects.disconnected(conn.wasDropped(), conn.getConnectErrorId());
listener.onSessionChanged();
}
@@ -913,6 +930,10 @@ public final class ServerSession {
}
checkServerIcon();
updateWhisperTargets();
if (conn.isConnected()) {
ChannelNode here = currentChannel();
chat.names(Objects.requireNonNullElse(name, ""), here == null ? "" : here.name);
}
listener.onModelChanged();
}
@@ -930,17 +951,18 @@ public final class ServerSession {
@Override
public void onChat(ChatScope scope, int fromClientId, String fromUniqueId, String fromName, String message) {
String name = conn.contacts().store().displayName(fromUniqueId, fromName);
listener.onChat(scope, fromClientId, fromUniqueId, name, message);
chat.received(scope, fromClientId, fromUniqueId, name, message);
if (scope == ChatScope.PRIVATE) listener.onPrivateMessage(fromClientId, name, message);
}
@Override
public void onChatHistory(ChatScope scope, List<String> htmlEntries) {
listener.onChatHistory(scope, htmlEntries);
chat.history(ChatKey.of(scope, 0), "", htmlEntries);
}
@Override
public void onPrivateChatHistory(int clientId, String nickname, List<String> htmlEntries) {
listener.onPrivateChatHistory(clientId, nickname, htmlEntries);
chat.history(ChatKey.privateWith(clientId), nickname, htmlEntries);
}
@Override
@@ -955,18 +977,18 @@ public final class ServerSession {
@Override
public void onPoke(String fromName, String message) {
listener.onSystemMessage("You were poked by " + fromName + ": " + message);
chat.system("You were poked by " + fromName + ": " + message);
listener.onPoke(fromName, message);
}
@Override
public void onServerLog(String message) {
listener.onServerLog(message);
chat.serverLog(message);
}
@Override
public void onServerLogHtml(String html) {
listener.onServerLogHtml(html);
chat.serverLogHtml(html);
}
@Override
@@ -0,0 +1,78 @@
package eu.lixko.ts3j.client.session;
import eu.lixko.ts3j.client.chat.ChatKey;
import eu.lixko.ts3j.client.chat.ChatScope;
import eu.lixko.ts3j.client.chat.ChatSink;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ChatFeedTest {
private final List<String> calls = new ArrayList<>();
private final List<String> lines = new ArrayList<>();
private final ChatFeed feed = new ChatFeed(new ChatSink() {
@Override
public void append(ChatKey key, String title, String html) {
calls.add("append " + key + " " + title);
lines.add(html);
}
@Override
public void setHistory(ChatKey key, String title, List<String> html) {
calls.add("history " + key + " " + title + " " + html.size());
}
@Override
public void rename(ChatKey key, String name) {
calls.add("rename " + key + " " + name);
}
@Override
public void closePrivateChats() {
calls.add("close");
}
}, () -> "room");
@Test
void aPrivateMessageGoesToTheChatWithItsSender() {
feed.received(ChatScope.PRIVATE, 7, "peerUid", "Alice", "hi");
assertEquals(List.of("append " + ChatKey.privateWith(7) + " Alice"), calls);
assertTrue(lines.get(0).contains("Alice"), lines.get(0));
}
@Test
void ourOwnMessageCarriesOurNameAndIdentity() {
feed.sent(ChatScope.PRIVATE, 7, "Alice", 3, "selfUid", "Me", "hello");
assertEquals(List.of("append " + ChatKey.privateWith(7) + " Alice"), calls);
assertTrue(lines.get(0).contains("Me (you)"), lines.get(0));
assertTrue(lines.get(0).contains("selfUid"), lines.get(0));
}
@Test
void historyLeavesOutEntriesThatShowNothing() {
feed.history(ChatKey.CHANNEL, "", List.of("<p>one</p>", " ", "<p>two</p>"));
assertEquals(List.of("history " + ChatKey.CHANNEL + " 2"), calls);
}
@Test
void conversationsAreRenamedOnlyWhenTheNameChanges() {
feed.names("Server A", "Lobby");
feed.names("Server A", "Lobby");
feed.names("Server A", "AFK");
assertEquals(List.of("rename " + ChatKey.SERVER + " Server A", "rename " + ChatKey.CHANNEL + " Lobby",
"rename " + ChatKey.CHANNEL + " AFK"), calls);
}
@Test
void leavingClosesPrivateChatsAndForgetsTheNames() {
feed.names("Server A", "Lobby");
calls.clear();
feed.disconnected();
assertEquals(List.of("close", "rename " + ChatKey.SERVER + " ", "rename " + ChatKey.CHANNEL + " "), calls);
}
}