diff --git a/android/app/src/main/java/com/ts3client/android/ui/ConnectionInfoScreen.kt b/android/app/src/main/java/com/ts3client/android/ui/ConnectionInfoScreen.kt index 7bfb74f..078787e 100644 --- a/android/app/src/main/java/com/ts3client/android/ui/ConnectionInfoScreen.kt +++ b/android/app/src/main/java/com/ts3client/android/ui/ConnectionInfoScreen.kt @@ -1,32 +1,54 @@ package com.ts3client.android.ui +import android.content.ClipData +import android.content.ClipboardManager +import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.PrimaryScrollableTabRow +import androidx.compose.material3.Tab import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf 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.platform.LocalContext +import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp +import com.ts3client.android.ClientItem import com.ts3client.android.ServerController import com.ts3client.net.ConnectionStats import com.ts3client.net.ConnectionStatsFormat import kotlinx.coroutines.delay private const val REFRESH_MS = 1000L -private const val SELF_ADDRESS = "This device" -/** A client's connection figures, read again every second while shown, and what our playback made of their voice. */ +private val TABS = ConnectionStatsFormat.TRAFFIC_TABS.map { it.title() } + + listOf(ConnectionStatsFormat.QUOTA_TAB, ConnectionStatsFormat.VOICE_TAB) + +/** + * A client's connection figures, read again every second while shown, laid out as TeamSpeak's + * Connection Info window: name, times, ping and address beside the avatar, then a tab per + * traffic category with Total / In / Out columns, Quota, and what our playback made of their voice. + */ @Composable -fun ConnectionInfoScreen(server: ServerController, clientId: Int, nickname: String, onBack: () -> Unit) { +fun ConnectionInfoScreen(server: ServerController, clientId: Int, client: ClientItem?, onBack: () -> Unit) { var stats by remember { mutableStateOf(null) } LaunchedEffect(clientId) { while (true) { @@ -34,35 +56,95 @@ fun ConnectionInfoScreen(server: ServerController, clientId: Int, nickname: Stri delay(REFRESH_MS) } } + var tab by rememberSaveable { mutableIntStateOf(0) } val s = stats SubScreen("Connection info", onBack) { padding -> Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { - Text(nickname, Modifier.padding(horizontal = 16.dp, vertical = 8.dp), style = MaterialTheme.typography.titleLarge) - Figures(ConnectionStatsFormat.summaryRows(s, SELF_ADDRESS)) - Section("Voice received") - Figures(ConnectionStatsFormat.voiceRows(s?.voiceReceived)) - Section("Total") - Figures(ConnectionStatsFormat.trafficRows(s, null)) - for ((kind, title) in KINDS) { - Section(title) - Figures(ConnectionStatsFormat.trafficRows(s, kind)) + Row(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) { + Summary(s, client?.nickname ?: "", Modifier.weight(1f)) + if (client != null && client.avatarFlag.isNotEmpty()) { + Avatar(client.uniqueId, client.avatarFlag, Modifier.padding(start = 12.dp), size = 72.dp) + } + } + PrimaryScrollableTabRow(selectedTabIndex = tab, edgePadding = 8.dp) { + TABS.forEachIndexed { i, title -> Tab(tab == i, onClick = { tab = i }, text = { Text(title) }) } + } + val traffic = ConnectionStatsFormat.TRAFFIC_TABS + Column(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) { + when { + tab < traffic.size -> TrafficTable(ConnectionStatsFormat.trafficRows(s, traffic[tab].kind())) + tab == traffic.size -> Figures(ConnectionStatsFormat.quotaGroups(s)) + else -> Figures(listOf(ConnectionStatsFormat.voiceRows(s?.voiceReceived))) + } } } } } -private val KINDS = listOf( - ConnectionStats.Kind.SPEECH to "Speech", - ConnectionStats.Kind.KEEPALIVE to "Keep alive", - ConnectionStats.Kind.CONTROL to "Control", -) - @Composable -private fun Figures(rows: List) { - for (row in rows) { - Row(Modifier.padding(horizontal = 16.dp, vertical = 4.dp)) { - Text(row.label, Modifier.weight(1f), color = MaterialTheme.colorScheme.onSurfaceVariant) - Text(row.value, Modifier.weight(1f), textAlign = TextAlign.End) +private fun Summary(s: ConnectionStats?, nickname: String, modifier: Modifier) { + val context = LocalContext.current + val address = ConnectionStatsFormat.copyableAddress(s) + val rows = ConnectionStatsFormat.summaryRows(s, nickname) + Column(modifier) { + rows.forEachIndexed { i, row -> + Row(Modifier.heightIn(min = 32.dp), verticalAlignment = Alignment.CenterVertically) { + Text(row.label, Modifier.weight(1f), color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(row.value, textAlign = TextAlign.End) + if (i == rows.lastIndex) { + IconButton( + onClick = { + // The system confirms the copy itself. + context.getSystemService(ClipboardManager::class.java) + .setPrimaryClip(ClipData.newPlainText("Client address", address)) + }, + enabled = address != null, + modifier = Modifier.size(32.dp), + ) { PackIcon("COPY", "Copy client address", size = 18.dp) } + } + } } } } + +/** Labelled figures in groups set apart by a rule. */ +@Composable +private fun Figures(groups: List>) { + groups.forEachIndexed { g, rows -> + if (g > 0) HorizontalDivider(Modifier.padding(vertical = 8.dp)) + for (row in rows) { + Row(Modifier.padding(vertical = 4.dp)) { + Text(row.label, Modifier.weight(1f), color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(row.value, textAlign = TextAlign.End) + } + } + } +} + +@Composable +private fun TrafficTable(rows: List) { + Row(Modifier.padding(vertical = 4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp)) { + LabelCell("") + ConnectionStatsFormat.COLUMNS.forEachIndexed { i, column -> ValueCell(column, i == 0, FontStyle.Italic) } + } + for (row in rows) { + Row(Modifier.padding(vertical = 4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp), + verticalAlignment = Alignment.CenterVertically) { + LabelCell(row.label) + ValueCell(row.total, narrow = true) + ValueCell(row.`in`) + ValueCell(row.out) + } + } +} + +@Composable +private fun RowScope.LabelCell(text: String) = + Text(text, Modifier.weight(1.5f), color = MaterialTheme.colorScheme.onSurfaceVariant, + style = MaterialTheme.typography.bodySmall) + +/** The Total column only ever holds the loss percentage. */ +@Composable +private fun RowScope.ValueCell(text: String, narrow: Boolean = false, fontStyle: FontStyle? = null) = + Text(text, Modifier.weight(if (narrow) 0.7f else 1f), style = MaterialTheme.typography.bodySmall, fontStyle = fontStyle, + textAlign = TextAlign.End) 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 d70aaa7..3e09a49 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 @@ -209,7 +209,7 @@ fun ServerScreen( return } connectionInfo?.let { id -> - ConnectionInfoScreen(server, id, tree.client(id)?.name ?: "", onBack = { connectionInfo = null }) + ConnectionInfoScreen(server, id, tree.client(id), onBack = { connectionInfo = null }) return } diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ClientEntry.java b/ts3-client/core/src/main/java/com/ts3client/net/ClientEntry.java index d5a304f..f963354 100644 --- a/ts3-client/core/src/main/java/com/ts3client/net/ClientEntry.java +++ b/ts3-client/core/src/main/java/com/ts3client/net/ClientEntry.java @@ -29,6 +29,9 @@ public final class ClientEntry { public volatile String avatarFlag = ""; /** Where the server places the client ({@code client_country}), as an ISO code; empty when it cannot tell. */ public volatile String country = ""; + /** File transfer traffic this month ({@code client_month_bytes_*}), -1 until asked for. */ + public volatile long monthBytesDownloaded = -1; + public volatile long monthBytesUploaded = -1; public volatile boolean talking; public volatile boolean inputMuted; // microphone muted (client_input_muted) diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionEventHandler.java b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionEventHandler.java index 968c51a..77434d4 100644 --- a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionEventHandler.java +++ b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionEventHandler.java @@ -342,6 +342,10 @@ final class ConnectionEventHandler implements TS3Listener { if (has(e, "client_platform")) c.platform = e.get("client_platform"); conn.ui.onInfoUpdated(); } + if (has(e, "client_month_bytes_downloaded")) + c.monthBytesDownloaded = TeamspeakConnection.safeLong(e, "client_month_bytes_downloaded"); + if (has(e, "client_month_bytes_uploaded")) + c.monthBytesUploaded = TeamspeakConnection.safeLong(e, "client_month_bytes_uploaded"); if (has(e, "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")); diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStats.java b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStats.java index fb1eae4..1c8ccc2 100644 --- a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStats.java +++ b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStats.java @@ -2,55 +2,51 @@ package com.ts3client.net; import com.ts3client.audio.VoiceReceiveStats; -import java.util.ArrayList; -import java.util.List; +import java.util.EnumMap; +import java.util.Map; /** * A snapshot of a client's connection statistics, as shown in the Connection * Info window. Values default to {@code -1} meaning "unknown / not reported", * which callers should render as a dash. * - *

For the local client the figures are read live from the socket's own - * packet counters and are fully populated, including the per-{@link Kind} - * breakdown. For a remote client the figures come from the server's - * {@code notifyconnectioninfo} report and only the aggregate totals are - * available; {@link #perKind} is then empty. + *

Traffic is seen from the client's side, as TeamSpeak shows it: in is what + * the client received, out what it sent. For a remote client the figures come + * from {@code notifyconnectioninfo} (the server relays the client's own counters, plus + * the loss it measured itself); for the local client they are read from our own socket. */ public final class ConnectionStats { /** The three traffic categories TeamSpeak accounts separately. */ - public enum Kind {KEEPALIVE, CONTROL, SPEECH} + public enum Kind {SPEECH, KEEPALIVE, CONTROL} + + /** A quota permission's value for "no limit". */ + public static final long UNLIMITED = -1; public int clientId; public String nickname = ""; public boolean self; - /** True when derived from local live counters (self); false for a server snapshot. */ - public boolean live; - + /** Empty when the server withholds it. */ public String ip = ""; - public String version = ""; - public String platform = ""; + public int port = -1; public double pingMs = -1; public double pingDeviationMs = -1; - /** Total packet loss as a fraction 0..1, or -1 if unknown. */ - public double packetLoss = -1; public long connectedTimeMs = -1; public long idleTimeMs = -1; public long filetransferBandwidthSent = -1; public long filetransferBandwidthReceived = -1; - // Aggregate totals across all traffic kinds. - public long packetsSentTotal = -1; - public long packetsReceivedTotal = -1; - public long bytesSentTotal = -1; - public long bytesReceivedTotal = -1; - public long bandwidthSentLastSecond = -1; - public long bandwidthReceivedLastSecond = -1; - public long bandwidthSentLastMinute = -1; - public long bandwidthReceivedLastMinute = -1; + public final Traffic total = new Traffic(); + private final Map perKind = new EnumMap<>(Kind.class); + + public long monthBytesDownloaded = -1; + public long monthBytesUploaded = -1; + /** Our own transfer quota in MiB, or {@link #UNLIMITED}; only known for ourselves. */ + public long downloadQuotaMb = UNLIMITED; + public long uploadQuotaMb = UNLIMITED; /** * How voice has been coming in here, measured by this client's own playback: from this @@ -58,45 +54,30 @@ public final class ConnectionStats { */ public VoiceReceiveStats voiceReceived; - /** Per-category breakdown (one row per {@link Kind}); empty when unavailable. */ - public final List perKind = new ArrayList<>(); - - public boolean hasBreakdown() { - return !perKind.isEmpty(); + /** One category's figures, or {@link #total} for a null {@code kind}. */ + public Traffic traffic(Kind kind) { + return kind == null ? total : perKind.computeIfAbsent(kind, k -> new Traffic()); } - /** Returns the stats for {@code kind}, or {@code null} if not present. */ - public KindStats kind(Kind kind) { - for (KindStats k : perKind) { - if (k.kind == kind) return k; - } - return null; - } + /** One direction pair of counters. Values default to {@code -1} meaning "unknown". */ + public static final class Traffic { + /** Fractions 0..1: server to client, and client to server. */ + public double lossIn = -1; + public double lossOut = -1; + public long packetsIn = -1; + public long packetsOut = -1; + public long bytesIn = -1; + public long bytesOut = -1; + public long bandwidthInLastSecond = -1; + public long bandwidthOutLastSecond = -1; + public long bandwidthInLastMinute = -1; + public long bandwidthOutLastMinute = -1; - /** Returns the stats for {@code kind}, creating and registering the row if needed. */ - public KindStats getOrCreateKind(Kind kind) { - KindStats existing = kind(kind); - if (existing != null) return existing; - KindStats created = new KindStats(kind); - perKind.add(created); - return created; - } - - /** One category's counters. Values default to {@code -1} meaning "unknown". */ - public static final class KindStats { - public final Kind kind; - public double packetLoss = -1; // fraction 0..1 - public long packetsSent = -1; - public long packetsReceived = -1; - public long bytesSent = -1; - public long bytesReceived = -1; - public long bandwidthSentLastSecond = -1; - public long bandwidthReceivedLastSecond = -1; - public long bandwidthSentLastMinute = -1; - public long bandwidthReceivedLastMinute = -1; - - public KindStats(Kind kind) { - this.kind = kind; + /** The chance a packet is lost either way, or whichever direction is known. */ + public double lossTotal() { + if (lossIn < 0) return lossOut; + if (lossOut < 0) return lossIn; + return 1 - (1 - lossIn) * (1 - lossOut); } } } diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsCollector.java b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsCollector.java index ce9225f..3123926 100644 --- a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsCollector.java +++ b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsCollector.java @@ -9,23 +9,36 @@ import com.github.manevolent.ts3j.protocol.packet.statistics.PacketStatistics; import com.github.manevolent.ts3j.protocol.socket.client.LocalTeamspeakClientSocket; import com.github.manevolent.ts3j.util.Pair; import com.ts3client.audio.VoiceOutput; +import com.ts3client.net.filetransfer.FileTransferManager; +import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import java.util.function.Consumer; /** - * Builds {@link ConnectionStats} snapshots for the info dialog. The local client's own - * figures are read straight from its live packet counters; a remote client's come from - * {@code getconnectioninfo}, whose {@code notifyconnectioninfo} report arrives - * asynchronously via {@link #onReport} and is matched back up by client id. + * Builds {@link ConnectionStats} snapshots for the info window from {@code getconnectioninfo}. + * + *

For another client the server answers twice: at once with the figures it last + * heard, then again once the client has sent fresh ones ({@code setconnectioninfo}). + * For ourselves it answers once, with only what it measures itself (address, idle time, + * the loss on the way in); the traffic comes from our own socket's counters. */ final class ConnectionStatsCollector { + private static final long REPORT_WAIT_MS = 1000; + /** {@code clientgetvariables} for the month's transfer figures, which change slowly. */ + private static final long VARIABLES_REFRESH_MS = 10_000; + private final TeamspeakConnection conn; - /** Outstanding {@code getconnectioninfo} requests awaiting a server report, keyed by client id. */ - private final Map pending = new ConcurrentHashMap<>(); + /** Requests awaiting their reports, keyed by client id. */ + private final Map pending = new ConcurrentHashMap<>(); + private final Map variablesAskedAt = new ConcurrentHashMap<>(); + /** The file transfer byte counts at the previous poll: time, sent, received. */ + private long[] lastTransferSample; ConnectionStatsCollector(TeamspeakConnection conn) { this.conn = conn; @@ -34,61 +47,94 @@ final class ConnectionStatsCollector { /** Drops any requests left over from a connection that just went away. */ void clear() { pending.clear(); + variablesAskedAt.clear(); + lastTransferSample = null; } /** - * Fetches connection statistics for a client and delivers them to - * {@code callback} (invoked off the Swing EDT — the callback is responsible - * for marshalling). May be called repeatedly to poll. + * Fetches a client's statistics and delivers them to {@code callback} exactly once, + * on a background thread. May be called repeatedly to poll. */ void request(int clientId, Consumer callback) { - if (clientId == conn.getSelfClientId()) { - new Thread(() -> callback.accept(withVoice(buildLocalStats(), clientId)), "ts3j-conninfo-self").start(); - } else { - new Thread(() -> requestRemote(clientId, s -> callback.accept(withVoice(s, clientId))), - "ts3j-conninfo").start(); - } + new Thread(() -> callback.accept(collect(clientId)), "ts3j-conninfo").start(); } - /** Adds what our playback saw of the client's voice, or everyone's for ourselves. */ - private ConnectionStats withVoice(ConnectionStats s, int clientId) { - VoiceOutput playback = conn.getPlayback(); - if (playback != null) { - s.voiceReceived = s.self ? playback.receiveStats() : playback.receiveStats(clientId); + /** Folds an arriving {@code notifyconnectioninfo} report into its request. */ + void onReport(UnknownTeamspeakEvent e) { + Pending p = pending.get(safeInt(e.get("clid"))); + if (p == null) return; + synchronized (p.stats) { + applyReport(p.stats, e.getMap()); + } + p.reports.countDown(); + } + + private ConnectionStats collect(int clientId) { + ConnectionStats s = new ConnectionStats(); + s.clientId = clientId; + s.self = clientId == conn.getSelfClientId(); + refreshVariables(clientId); + awaitReports(s, s.self ? 1 : 2); + + synchronized (s) { + if (s.self) { + applyLocal(s); + applyTransferRate(s); + } + sumKinds(s); + ClientEntry entry = conn.getModel().getClient(clientId); + if (entry != null) { + s.nickname = entry.nickname; + s.monthBytesDownloaded = entry.monthBytesDownloaded; + s.monthBytesUploaded = entry.monthBytesUploaded; + } + if (s.self) { + ServerModel model = conn.getModel(); + s.downloadQuotaMb = model.selfPermissionValue("i_ft_quota_mb_download_per_client", -1); + s.uploadQuotaMb = model.selfPermissionValue("i_ft_quota_mb_upload_per_client", -1); + } + VoiceOutput playback = conn.getPlayback(); + if (playback != null) { + s.voiceReceived = s.self ? playback.receiveStats() : playback.receiveStats(clientId); + } } return s; } - /** Matches an asynchronously arriving {@code notifyconnectioninfo} report to its request. */ - void onReport(UnknownTeamspeakEvent e) { - int clid = safeInt(e.get("clid")); - PendingConnInfo p = pending.remove(clid); - if (p == null) return; - applyConnectionFields(p.stats, e.getMap()); - p.callback.accept(p.stats); + private void awaitReports(ConnectionStats s, int expected) { + LocalTeamspeakClientSocket client = conn.client; + if (client == null) return; + Pending p = new Pending(s, expected); + pending.put(s.clientId, p); + try { + client.executeCommand(new SingleCommand("getconnectioninfo", ProtocolRole.CLIENT, + new CommandSingleParameter("clid", Integer.toString(s.clientId)))).complete(); + p.reports.await(REPORT_WAIT_MS, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (Exception ignored) { + // refused (e.g. no permission to view it); what is known locally still shows + } finally { + pending.remove(s.clientId, p); + } } - /** Builds a live snapshot of the local client's connection from its own counters. */ - private ConnectionStats buildLocalStats() { - ConnectionStats s = new ConnectionStats(); - s.clientId = conn.getSelfClientId(); - s.self = true; - s.live = true; - s.packetLoss = 0; // the local client has no server->client loss figure + /** Asks for the month's transfer figures now and then; they land in the model. */ + private void refreshVariables(int clientId) { + long now = System.currentTimeMillis(); + Long last = variablesAskedAt.get(clientId); + if (last != null && now - last < VARIABLES_REFRESH_MS) return; + variablesAskedAt.put(clientId, now); + conn.requestClientInfo(clientId); + } - ClientEntry self = conn.getModel().getClient(conn.getSelfClientId()); - if (self != null) { - s.nickname = self.nickname; - s.version = self.version; - s.platform = self.platform; - s.idleTimeMs = self.idleTimeMs; - } + /** Our own traffic, straight from the socket. */ + private void applyLocal(ConnectionStats s) { long connectedAt = conn.connectedAtMs; if (connectedAt > 0) s.connectedTimeMs = System.currentTimeMillis() - connectedAt; LocalTeamspeakClientSocket c = conn.client; - if (c == null) return s; - + if (c == null) return; try { Pair ping = c.getPing(); s.pingMs = ping.getKey() * 1000.0; @@ -96,158 +142,87 @@ final class ConnectionStatsCollector { } catch (Exception ignored) { // ping unavailable; leave as unknown } - - long pSent = 0, pRecv = 0, bSent = 0, bRecv = 0; - long bwSs = 0, bwRs = 0, bwSm = 0, bwRm = 0; for (PacketKind kind : PacketKind.values()) { PacketStatistics st = c.getStatistics(kind); - ConnectionStats.KindStats ks = new ConnectionStats.KindStats(mapKind(kind)); - ks.packetLoss = 0; // the local client cannot measure its own server->client loss - ks.packetsSent = st.getSentPackets(); - ks.packetsReceived = st.getReceivedPackets(); - ks.bytesSent = st.getSentBytes(); - ks.bytesReceived = st.getReceivedBytes(); - ks.bandwidthSentLastSecond = st.getSentBytesLastSecond(); - ks.bandwidthReceivedLastSecond = st.getReceivedBytesLastSecond(); - ks.bandwidthSentLastMinute = st.getSentBandwidthLastMinute(); - ks.bandwidthReceivedLastMinute = st.getReceivedBandwidthLastMinute(); - s.perKind.add(ks); - - pSent += ks.packetsSent; - pRecv += ks.packetsReceived; - bSent += ks.bytesSent; - bRecv += ks.bytesReceived; - bwSs += ks.bandwidthSentLastSecond; - bwRs += ks.bandwidthReceivedLastSecond; - bwSm += ks.bandwidthSentLastMinute; - bwRm += ks.bandwidthReceivedLastMinute; - } - s.packetsSentTotal = pSent; - s.packetsReceivedTotal = pRecv; - s.bytesSentTotal = bSent; - s.bytesReceivedTotal = bRecv; - s.bandwidthSentLastSecond = bwSs; - s.bandwidthReceivedLastSecond = bwRs; - s.bandwidthSentLastMinute = bwSm; - s.bandwidthReceivedLastMinute = bwRm; - return s; - } - - /** - * Requests a remote client's connection info: {@code getconnectioninfo}, whose - * {@code notifyconnectioninfo} report arrives asynchronously via {@link #onReport}. - * Version and platform come from the model; {@code clientinfo} would have them too, - * but it counts heavily against the server's flood protection, and this is polled. - * If the report does not arrive shortly (e.g. the server withholds it), the - * model-only snapshot is delivered instead. - */ - private void requestRemote(int clientId, Consumer callback) { - ConnectionStats s = new ConnectionStats(); - s.clientId = clientId; - ClientEntry entry = conn.getModel().getClient(clientId); - if (entry != null) { - s.nickname = entry.nickname; - s.version = entry.version; - s.platform = entry.platform; - } - - LocalTeamspeakClientSocket client = conn.client; - PendingConnInfo p = new PendingConnInfo(callback, s); - pending.put(clientId, p); - - boolean sent = false; - try { - SingleCommand cmd = new SingleCommand("getconnectioninfo", ProtocolRole.CLIENT, - new CommandSingleParameter("clid", Integer.toString(clientId))); - client.executeCommand(cmd).complete(); - sent = true; - } catch (Exception ignored) { - // command failed; fall back to the model snapshot below - } - - if (sent) { - try { - Thread.sleep(700); // give notifyconnectioninfo a chance to arrive - } catch (InterruptedException ignored) { - Thread.currentThread().interrupt(); - } - } - // If the report already arrived, onReport removed and delivered it. - if (pending.remove(clientId, p)) { - callback.accept(s); + ConnectionStats.Traffic t = s.traffic(mapKind(kind)); + t.packetsIn = add(t.packetsIn, st.getReceivedPackets()); + t.packetsOut = add(t.packetsOut, st.getSentPackets()); + t.bytesIn = add(t.bytesIn, st.getReceivedBytes()); + t.bytesOut = add(t.bytesOut, st.getSentBytes()); + t.bandwidthInLastSecond = add(t.bandwidthInLastSecond, st.getReceivedBytesLastSecond()); + t.bandwidthOutLastSecond = add(t.bandwidthOutLastSecond, st.getSentBytesLastSecond()); + t.bandwidthInLastMinute = add(t.bandwidthInLastMinute, st.getReceivedBandwidthLastMinute()); + t.bandwidthOutLastMinute = add(t.bandwidthOutLastMinute, st.getSentBandwidthLastMinute()); } } - /** Parses TeamSpeak {@code connection_*} fields from a command map into {@code s}. */ - private static void applyConnectionFields(ConnectionStats s, Map m) { - double ping = parseDouble(m.get("connection_ping")); - if (ping >= 0) s.pingMs = ping; - double dev = parseDouble(m.get("connection_ping_deviation")); - if (dev >= 0) s.pingDeviationMs = dev; - double loss = parseDouble(m.get("connection_packetloss_total")); - if (loss < 0) loss = parseDouble(m.get("connection_server2client_packetloss_total")); - if (loss >= 0) s.packetLoss = loss; + /** Our file transfer rate since the previous poll; the server reports it only for others. */ + private synchronized void applyTransferRate(ConnectionStats s) { + FileTransferManager ft = conn.fileTransfers(); + if (ft == null) return; + long[] now = {System.currentTimeMillis(), ft.bytesSent(), ft.bytesReceived()}; + long[] last = lastTransferSample; + lastTransferSample = now; + long elapsed = last == null ? 0 : now[0] - last[0]; + s.filetransferBandwidthSent = elapsed <= 0 ? 0 : (now[1] - last[1]) * 1000 / elapsed; + s.filetransferBandwidthReceived = elapsed <= 0 ? 0 : (now[2] - last[2]) * 1000 / elapsed; + } - long connected = parseLong(m.get("connection_connected_time")); - if (connected >= 0) s.connectedTimeMs = connected; - long idle = parseLong(m.get("connection_idle_time")); - if (idle >= 0) s.idleTimeMs = idle; + /** Several of ts3j's packet kinds (commands and their acks) make up one TeamSpeak category. */ + private static long add(long current, long value) { + return Math.max(current, 0) + value; + } + + /** Fills the totals from the categories: clients report only those. */ + private static void sumKinds(ConnectionStats s) { + ConnectionStats.Traffic total = s.total; + if (total.packetsIn >= 0) return; + total.packetsIn = total.packetsOut = total.bytesIn = total.bytesOut = 0; + total.bandwidthInLastSecond = total.bandwidthOutLastSecond = 0; + total.bandwidthInLastMinute = total.bandwidthOutLastMinute = 0; + for (ConnectionStats.Kind kind : ConnectionStats.Kind.values()) { + ConnectionStats.Traffic t = s.traffic(kind); + total.packetsIn += Math.max(t.packetsIn, 0); + total.packetsOut += Math.max(t.packetsOut, 0); + total.bytesIn += Math.max(t.bytesIn, 0); + total.bytesOut += Math.max(t.bytesOut, 0); + total.bandwidthInLastSecond += Math.max(t.bandwidthInLastSecond, 0); + total.bandwidthOutLastSecond += Math.max(t.bandwidthOutLastSecond, 0); + total.bandwidthInLastMinute += Math.max(t.bandwidthInLastMinute, 0); + total.bandwidthOutLastMinute += Math.max(t.bandwidthOutLastMinute, 0); + } + } + + /** Parses TeamSpeak's {@code connection_*} fields; ones the report leaves out stay as they are. */ + private static void applyReport(ConnectionStats s, Map m) { + s.pingMs = pickDouble(s.pingMs, m.get("connection_ping")); + s.pingDeviationMs = pickDouble(s.pingDeviationMs, m.get("connection_ping_deviation")); + s.connectedTimeMs = pick(s.connectedTimeMs, m.get("connection_connected_time")); + s.idleTimeMs = pick(s.idleTimeMs, m.get("connection_idle_time")); String ip = m.get("connection_client_ip"); if (ip != null && !ip.isEmpty()) s.ip = ip; - - s.packetsSentTotal = pick(s.packetsSentTotal, m.get("connection_packets_sent_total")); - s.packetsReceivedTotal = pick(s.packetsReceivedTotal, m.get("connection_packets_received_total")); - s.bytesSentTotal = pick(s.bytesSentTotal, m.get("connection_bytes_sent_total")); - s.bytesReceivedTotal = pick(s.bytesReceivedTotal, m.get("connection_bytes_received_total")); - s.bandwidthSentLastSecond = - pick(s.bandwidthSentLastSecond, m.get("connection_bandwidth_sent_last_second_total")); - s.bandwidthReceivedLastSecond = - pick(s.bandwidthReceivedLastSecond, m.get("connection_bandwidth_received_last_second_total")); - s.bandwidthSentLastMinute = - pick(s.bandwidthSentLastMinute, m.get("connection_bandwidth_sent_last_minute_total")); - s.bandwidthReceivedLastMinute = - pick(s.bandwidthReceivedLastMinute, m.get("connection_bandwidth_received_last_minute_total")); - s.filetransferBandwidthSent = - pick(s.filetransferBandwidthSent, m.get("connection_filetransfer_bandwidth_sent")); + s.port = (int) pick(s.port, m.get("connection_client_port")); + s.filetransferBandwidthSent = pick(s.filetransferBandwidthSent, m.get("connection_filetransfer_bandwidth_sent")); s.filetransferBandwidthReceived = pick(s.filetransferBandwidthReceived, m.get("connection_filetransfer_bandwidth_received")); - applyPerKindFields(s, m); - } - - /** - * Parses the per-category {@code connection_*_} fields (as sent in a - * {@code notifyconnectioninfo} report) into {@code s}, merging into any - * existing rows. Categories absent from the map are left untouched. - */ - private static void applyPerKindFields(ConnectionStats s, Map m) { + applyTraffic(s.total, m, "total"); for (ConnectionStats.Kind kind : ConnectionStats.Kind.values()) { - String suffix = kind.name().toLowerCase(java.util.Locale.ROOT); // keepalive/control/speech - String probe = m.get("connection_packets_sent_" + suffix); - String probe2 = m.get("connection_server2client_packetloss_" + suffix); - if (probe == null && probe2 == null) continue; // this category not reported - - ConnectionStats.KindStats ks = s.getOrCreateKind(kind); - ks.packetsSent = pick(ks.packetsSent, m.get("connection_packets_sent_" + suffix)); - ks.packetsReceived = pick(ks.packetsReceived, m.get("connection_packets_received_" + suffix)); - ks.bytesSent = pick(ks.bytesSent, m.get("connection_bytes_sent_" + suffix)); - ks.bytesReceived = pick(ks.bytesReceived, m.get("connection_bytes_received_" + suffix)); - ks.bandwidthSentLastSecond = - pick(ks.bandwidthSentLastSecond, m.get("connection_bandwidth_sent_last_second_" + suffix)); - ks.bandwidthReceivedLastSecond = - pick(ks.bandwidthReceivedLastSecond, m.get("connection_bandwidth_received_last_second_" + suffix)); - ks.bandwidthSentLastMinute = - pick(ks.bandwidthSentLastMinute, m.get("connection_bandwidth_sent_last_minute_" + suffix)); - ks.bandwidthReceivedLastMinute = - pick(ks.bandwidthReceivedLastMinute, m.get("connection_bandwidth_received_last_minute_" + suffix)); - double kloss = parseDouble(m.get("connection_server2client_packetloss_" + suffix)); - if (kloss >= 0) ks.packetLoss = kloss; + applyTraffic(s.traffic(kind), m, kind.name().toLowerCase(Locale.ROOT)); } } - private static long pick(long current, String value) { - long v = parseLong(value); - return v >= 0 ? v : current; + private static void applyTraffic(ConnectionStats.Traffic t, Map m, String suffix) { + t.lossIn = pickDouble(t.lossIn, m.get("connection_server2client_packetloss_" + suffix)); + t.lossOut = pickDouble(t.lossOut, m.get("connection_client2server_packetloss_" + suffix)); + t.packetsIn = pick(t.packetsIn, m.get("connection_packets_received_" + suffix)); + t.packetsOut = pick(t.packetsOut, m.get("connection_packets_sent_" + suffix)); + t.bytesIn = pick(t.bytesIn, m.get("connection_bytes_received_" + suffix)); + t.bytesOut = pick(t.bytesOut, m.get("connection_bytes_sent_" + suffix)); + t.bandwidthInLastSecond = pick(t.bandwidthInLastSecond, m.get("connection_bandwidth_received_last_second_" + suffix)); + t.bandwidthOutLastSecond = pick(t.bandwidthOutLastSecond, m.get("connection_bandwidth_sent_last_second_" + suffix)); + t.bandwidthInLastMinute = pick(t.bandwidthInLastMinute, m.get("connection_bandwidth_received_last_minute_" + suffix)); + t.bandwidthOutLastMinute = pick(t.bandwidthOutLastMinute, m.get("connection_bandwidth_sent_last_minute_" + suffix)); } private static ConnectionStats.Kind mapKind(PacketKind kind) { @@ -261,6 +236,16 @@ final class ConnectionStatsCollector { } } + private static long pick(long current, String value) { + long v = parseLong(value); + return v >= 0 ? v : current; + } + + private static double pickDouble(double current, String value) { + double v = parseDouble(value); + return v >= 0 ? v : current; + } + /** Parses a long, returning -1 for null/blank/non-numeric input. */ private static long parseLong(String s) { if (s == null || s.isEmpty()) return -1; @@ -290,14 +275,14 @@ final class ConnectionStatsCollector { } } - /** Callback + accumulating snapshot for an in-flight {@code getconnectioninfo}. */ - private static final class PendingConnInfo { - final Consumer callback; + /** A request's snapshot, filled in by its reports as they arrive. */ + private static final class Pending { final ConnectionStats stats; + final CountDownLatch reports; - PendingConnInfo(Consumer callback, ConnectionStats stats) { - this.callback = callback; + Pending(ConnectionStats stats, int expected) { this.stats = stats; + this.reports = new CountDownLatch(expected); } } } diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsFormat.java b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsFormat.java index 791216f..1b91bfd 100644 --- a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsFormat.java +++ b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsFormat.java @@ -3,114 +3,112 @@ package com.ts3client.net; import com.ts3client.audio.VoiceReceiveStats; import java.text.DecimalFormat; +import java.util.ArrayList; import java.util.List; -/** Renders {@link ConnectionStats} figures for display; an unknown value (negative) shows as a dash. */ +/** + * Renders {@link ConnectionStats} the way the official Connection Info window does: a + * summary, one traffic table per tab with Total / In / Out columns, and a quota tab. + * An unknown value (negative) shows as a dash. + */ public final class ConnectionStatsFormat { public static final String UNKNOWN = "—"; + public static final String HIDDEN = "Hidden"; + public static final String UNLIMITED = "Unlimited"; + public static final String EXCEEDED = "Exceeded"; + + /** The traffic table's column headings, after the row labels. */ + public static final List COLUMNS = List.of("Total", "In", "Out"); private ConnectionStatsFormat() { } - public static String orDash(String s) { - return (s == null || s.isEmpty()) ? UNKNOWN : s; - } - - public static String ping(double ms, double deviationMs) { - if (ms < 0) return UNKNOWN; - String base = Math.round(ms) + " ms"; - if (deviationMs > 0) base += " (± " + Math.round(deviationMs) + " ms)"; - return base; - } - - /** A fraction 0..1 as a percentage. */ - public static String loss(double fraction) { - if (fraction < 0) return UNKNOWN; - return new DecimalFormat("0.00").format(fraction * 100.0) + " %"; - } - - public static String count(long n) { - return n < 0 ? UNKNOWN : new DecimalFormat("#,##0").format(n); - } - - /** A count with its share of {@code of}, e.g. {@code 12 (0.4 %)}. */ - public static String countOf(long n, long of) { - if (n < 0) return UNKNOWN; - if (of <= 0) return count(n); - return count(n) + " (" + new DecimalFormat("0.0").format(100.0 * n / of) + " %)"; - } - - public static String bytes(long bytes) { - if (bytes < 0) return UNKNOWN; - if (bytes < 1024) return bytes + " B"; - double kib = bytes / 1024.0; - if (kib < 1024) return new DecimalFormat("0.0").format(kib) + " KiB"; - double mib = kib / 1024.0; - if (mib < 1024) return new DecimalFormat("0.00").format(mib) + " MiB"; - return new DecimalFormat("0.00").format(mib / 1024.0) + " GiB"; - } - - public static String rate(long bytesPerSecond) { - return bytesPerSecond < 0 ? UNKNOWN : bytes(bytesPerSecond) + "/s"; - } - - /** Sent and received side by side. */ - public static String upDown(String up, String down) { - return up + " / " + down; - } - /** A labelled figure. */ public record Row(String label, String value) { } - /** Who the client is and how the link to them is doing; {@code s} may be null while loading. */ - public static List summaryRows(ConnectionStats s, String selfAddress) { - ConnectionStats k = s == null ? new ConnectionStats() : s; - return List.of( - new Row("Address", k.self ? selfAddress : orDash(k.ip)), - new Row("Client version", orDash(k.version)), - new Row("Platform", orDash(k.platform)), - new Row("Ping", ping(k.pingMs, k.pingDeviationMs)), - new Row("Idle time", duration(k.idleTimeMs)), - new Row("Connected", duration(k.connectedTimeMs)), - new Row("Filetransfer (↑/↓)", - upDown(rate(k.filetransferBandwidthSent), rate(k.filetransferBandwidthReceived)))); + /** A traffic table row; {@code total} is empty where the official client leaves it blank. */ + public record TrafficRow(String label, String total, String in, String out) { } - /** One traffic category's figures, or the totals for a null {@code kind}. */ - public static List trafficRows(ConnectionStats s, ConnectionStats.Kind kind) { - double loss = -1; - long packetsSent = -1, packetsReceived = -1, bytesSent = -1, bytesReceived = -1; - long secondSent = -1, secondReceived = -1, minuteSent = -1, minuteReceived = -1; - if (s != null && kind == null) { - loss = s.packetLoss; - packetsSent = s.packetsSentTotal; - packetsReceived = s.packetsReceivedTotal; - bytesSent = s.bytesSentTotal; - bytesReceived = s.bytesReceivedTotal; - secondSent = s.bandwidthSentLastSecond; - secondReceived = s.bandwidthReceivedLastSecond; - minuteSent = s.bandwidthSentLastMinute; - minuteReceived = s.bandwidthReceivedLastMinute; - } else if (s != null && s.kind(kind) != null) { - ConnectionStats.KindStats k = s.kind(kind); - loss = k.packetLoss; - packetsSent = k.packetsSent; - packetsReceived = k.packetsReceived; - bytesSent = k.bytesSent; - bytesReceived = k.bytesReceived; - secondSent = k.bandwidthSentLastSecond; - secondReceived = k.bandwidthReceivedLastSecond; - minuteSent = k.bandwidthSentLastMinute; - minuteReceived = k.bandwidthReceivedLastMinute; - } + /** A traffic tab: the totals for a null {@code kind}, else one category. */ + public record Tab(String title, ConnectionStats.Kind kind) { + } + + public static final List TRAFFIC_TABS = List.of( + new Tab("Total", null), + new Tab("Speech", ConnectionStats.Kind.SPEECH), + new Tab("Keep Alive", ConnectionStats.Kind.KEEPALIVE), + new Tab("Control", ConnectionStats.Kind.CONTROL)); + + public static final String QUOTA_TAB = "Quota"; + public static final String VOICE_TAB = "Voice received"; + + /** Who the client is and how the link to them is doing; {@code s} may be null while loading. */ + public static List summaryRows(ConnectionStats s, String nickname) { + ConnectionStats k = s == null ? new ConnectionStats() : s; return List.of( - new Row("Packet loss", loss(loss)), - new Row("Packets (↑/↓)", upDown(count(packetsSent), count(packetsReceived))), - new Row("Transferred (↑/↓)", upDown(bytes(bytesSent), bytes(bytesReceived))), - new Row("Bandwidth · last second (↑/↓)", upDown(rate(secondSent), rate(secondReceived))), - new Row("Bandwidth · last minute (↑/↓)", upDown(rate(minuteSent), rate(minuteReceived)))); + new Row("Client name", nickname), + new Row("Connection time", duration(k.connectedTimeMs)), + new Row("Idle time", duration(k.idleTimeMs)), + new Row("Ping", ping(k.pingMs, k.pingDeviationMs)), + new Row("Client address", s == null ? UNKNOWN : address(s))); + } + + /** {@code ip:port}, what the copy button next to it puts on the clipboard; null when unknown. */ + public static String copyableAddress(ConnectionStats s) { + if (s == null || s.ip.isEmpty()) return null; + return s.port > 0 ? s.ip + ":" + s.port : s.ip; + } + + private static String address(ConnectionStats s) { + String address = copyableAddress(s); + return address == null ? HIDDEN : address; + } + + /** One traffic tab's table; only the totals carry the file transfer row. */ + public static List trafficRows(ConnectionStats s, ConnectionStats.Kind kind) { + ConnectionStats.Traffic t = s == null ? new ConnectionStats.Traffic() : s.traffic(kind); + List rows = new ArrayList<>(List.of( + new TrafficRow("Packet loss", loss(t.lossTotal()), loss(t.lossIn), loss(t.lossOut)), + new TrafficRow("Packets transferred", "", count(t.packetsIn), count(t.packetsOut)), + new TrafficRow("Bytes transferred", "", bytes(t.bytesIn), bytes(t.bytesOut)), + new TrafficRow("Bandwidth last second", "", + rate(t.bandwidthInLastSecond), rate(t.bandwidthOutLastSecond)), + new TrafficRow("Bandwidth last minute", "", + rate(t.bandwidthInLastMinute), rate(t.bandwidthOutLastMinute)))); + if (kind == null) { + long in = s == null ? -1 : s.filetransferBandwidthReceived; + long out = s == null ? -1 : s.filetransferBandwidthSent; + rows.add(new TrafficRow("File transfer bandwidth", "", rate(in), rate(out))); + } + return rows; + } + + /** + * The quota tab: downloads, then uploads. Only our own limits are known, so another + * client's groups hold just the month's figure. + */ + public static List> quotaGroups(ConnectionStats s) { + ConnectionStats k = s == null ? new ConnectionStats() : s; + return List.of( + quota(k, "download", "Downloaded this month:", k.monthBytesDownloaded, k.downloadQuotaMb), + quota(k, "upload", "Uploaded this month:", k.monthBytesUploaded, k.uploadQuotaMb)); + } + + private static List quota(ConnectionStats s, String direction, String label, long used, long quotaMb) { + Row month = new Row(label, bytes(used)); + if (!s.self) return List.of(month); + String available = quotaMb < 0 ? UNLIMITED : bytes(quotaMb * 1024 * 1024); + String remaining; + if (quotaMb < 0) remaining = UNLIMITED; + else if (used < 0) remaining = UNKNOWN; + else if (used > quotaMb * 1024 * 1024) remaining = EXCEEDED; + else remaining = bytes(quotaMb * 1024 * 1024 - used); + return List.of(month, + new Row("Available " + direction + " quota:", available), + new Row("Remaining " + direction + " this month:", remaining)); } /** The voice our playback received; every value is a dash when nothing was heard. */ @@ -127,18 +125,62 @@ public final class ConnectionStatsFormat { new Row("Discarded (copies)", known ? countOf(s.duplicates(), s.received()) : UNKNOWN)); } + // ---- figures ---- + + /** {@code 153 ms ± 217.0}. */ + public static String ping(double ms, double deviationMs) { + if (ms < 0) return UNKNOWN; + String base = Math.round(ms) + " ms"; + if (deviationMs >= 0) base += " ± " + new DecimalFormat("0.0").format(deviationMs); + return base; + } + + /** A fraction 0..1 as a percentage. */ + public static String loss(double fraction) { + if (fraction < 0) return UNKNOWN; + return new DecimalFormat("0.00").format(fraction * 100.0) + " %"; + } + + /** {@code 133}, {@code 2.12 k}, {@code 1.05 M}. */ + public static String count(long n) { + if (n < 0) return UNKNOWN; + if (n < 1000) return Long.toString(n); + DecimalFormat f = new DecimalFormat("0.00"); + if (n < 1_000_000) return f.format(n / 1e3) + " k"; + return f.format(n / 1e6) + " M"; + } + + /** A count with its share of {@code of}, e.g. {@code 12 (0.4 %)}. */ + public static String countOf(long n, long of) { + if (n < 0) return UNKNOWN; + if (of <= 0) return count(n); + return count(n) + " (" + new DecimalFormat("0.0").format(100.0 * n / of) + " %)"; + } + + public static String bytes(long bytes) { + if (bytes < 0) return UNKNOWN; + if (bytes < 1024) return bytes + " Bytes"; + DecimalFormat f = new DecimalFormat("0.00"); + double kib = bytes / 1024.0; + if (kib < 1024) return f.format(kib) + " KiB"; + double mib = kib / 1024.0; + if (mib < 1024) return f.format(mib) + " MiB"; + return f.format(mib / 1024.0) + " GiB"; + } + + public static String rate(long bytesPerSecond) { + return bytesPerSecond < 0 ? UNKNOWN : bytes(bytesPerSecond) + "/s"; + } + + /** {@code 04:34}, or {@code 15:35:17} from an hour on. */ public static String duration(long ms) { if (ms < 0) return UNKNOWN; long totalSeconds = ms / 1000; - long days = totalSeconds / 86400; - long hours = (totalSeconds % 86400) / 3600; + long hours = totalSeconds / 3600; long minutes = (totalSeconds % 3600) / 60; long seconds = totalSeconds % 60; - StringBuilder sb = new StringBuilder(); - if (days > 0) sb.append(days).append("d "); - if (days > 0 || hours > 0) sb.append(hours).append("h "); - if (days > 0 || hours > 0 || minutes > 0) sb.append(minutes).append("m "); - sb.append(seconds).append("s"); - return sb.toString(); + return hours > 0 + ? String.format("%02d:%02d:%02d", hours, minutes, seconds) + : String.format("%02d:%02d", minutes, seconds); } } diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ServerModel.java b/ts3-client/core/src/main/java/com/ts3client/net/ServerModel.java index c9d56a9..b30505a 100644 --- a/ts3-client/core/src/main/java/com/ts3client/net/ServerModel.java +++ b/ts3-client/core/src/main/java/com/ts3client/net/ServerModel.java @@ -155,9 +155,14 @@ public final class ServerModel { * never reported a non-default value for it). */ public synchronized int selfPermissionValue(String name) { + return selfPermissionValue(name, 0); + } + + /** As {@link #selfPermissionValue(String)}, with {@code absent} for a permission not (yet) reported. */ + public synchronized int selfPermissionValue(String name, int absent) { Integer id = permissionIds.get(name); Integer value = id == null ? null : selfPermissionValues.get(id); - return value == null ? 0 : value; + return value == null ? absent : value; } /** 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 250b648..3c6ca52 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 @@ -1421,7 +1421,7 @@ public final class TeamspeakConnection implements TS3Listener { return sock; } - /** Package-private for {@link ChannelAdmin}. */ + /** Package-private for {@link ChannelAdmin} and {@link ConnectionStatsCollector}. */ FileTransferManager fileTransfers() { return fileTransfers; } diff --git a/ts3-client/core/src/main/java/com/ts3client/net/filetransfer/FileTransferManager.java b/ts3-client/core/src/main/java/com/ts3client/net/filetransfer/FileTransferManager.java index 41157aa..5d3e3cd 100644 --- a/ts3-client/core/src/main/java/com/ts3client/net/filetransfer/FileTransferManager.java +++ b/ts3-client/core/src/main/java/com/ts3client/net/filetransfer/FileTransferManager.java @@ -30,6 +30,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; import java.util.function.Supplier; /** @@ -61,6 +62,9 @@ public final class FileTransferManager { /** Host we are connected to, used when the server reports no dedicated file-transfer host. */ private final Supplier fallbackHost; private final AtomicInteger clientTransferId = new AtomicInteger(1); + /** Every byte moved so far, for the connection info's transfer rate. */ + private final AtomicLong bytesSent = new AtomicLong(); + private final AtomicLong bytesReceived = new AtomicLong(); private final ExecutorService transferPool = Executors.newCachedThreadPool(r -> { Thread t = new Thread(r, "ts3j-filetransfer"); t.setDaemon(true); @@ -95,6 +99,14 @@ public final class FileTransferManager { socket.addListener(ftEventListener); } + public long bytesSent() { + return bytesSent.get(); + } + + public long bytesReceived() { + return bytesReceived.get(); + } + // ---- directory operations ---- /** @@ -233,6 +245,7 @@ public final class FileTransferManager { int read = in.read(data, offset, data.length - offset); if (read < 0) throw new IOException("File server closed the connection early"); offset += read; + bytesReceived.addAndGet(read); } } return data; @@ -274,6 +287,7 @@ public final class FileTransferManager { if (read < 0) throw new IOException("File server closed the connection early"); fileOut.write(buffer, 0, read); remaining -= read; + bytesReceived.addAndGet(read); transfer.addTransferred(read); } } @@ -328,6 +342,7 @@ public final class FileTransferManager { if (read < 0) break; // file shorter than announced; stop out.write(buffer, 0, read); remaining -= read; + bytesSent.addAndGet(read); transfer.addTransferred(read); } out.flush(); diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ConnectionInfoDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ConnectionInfoDialog.java index b93d21b..f136006 100644 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ConnectionInfoDialog.java +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/ConnectionInfoDialog.java @@ -2,72 +2,84 @@ package com.ts3client.ui; import com.formdev.flatlaf.util.ScaledEmptyBorder; import com.formdev.flatlaf.util.UIScale; +import com.ts3client.net.ClientEntry; import com.ts3client.net.ConnectionStats; import com.ts3client.net.ConnectionStatsFormat; import com.ts3client.net.ConnectionStatsFormat.Row; +import com.ts3client.net.ConnectionStatsFormat.TrafficRow; import com.ts3client.net.TeamspeakConnection; +import com.ts3client.net.avatar.Avatar; import javax.swing.Box; import javax.swing.BoxLayout; +import javax.swing.ImageIcon; import javax.swing.JButton; +import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; +import javax.swing.JSeparator; import javax.swing.JTabbedPane; +import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import java.awt.BorderLayout; -import java.awt.Color; import java.awt.Dimension; +import java.awt.Font; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; +import java.awt.Image; import java.awt.Insets; +import java.awt.Toolkit; +import java.awt.datatransfer.StringSelection; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; +import java.util.ArrayList; import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; /** - * Live "Client Connection Info" window, reachable from a client's right-click - * menu. Mirrors the TeamSpeak 3 dialog: a summary header (address, version, - * platform, idle/connected time, ping, filetransfer) above a - * Total / Speech / Keep Alive / Control tab strip, each tab showing - * that category's packet loss, packet and byte totals and live bandwidth, plus a - * Voice received tab with what our own playback made of the client's voice - * (everyone's, for ourselves): missed, out-of-order, late and duplicate packets. - * - *

Polls the {@link TeamspeakConnection} once a second while open; for the - * local client the figures update live from local counters, for a remote client - * they refresh from the server's connection report. + * Live "Client Connection Info" window, laid out as TeamSpeak 3's: name, times, ping and + * address beside the avatar, above a tab per traffic category whose table has Total / In / + * Out columns, and a Quota tab. A Voice received tab adds what our own playback + * made of the client's voice (everyone's, for ourselves). Polls once a second while open. */ public final class ConnectionInfoDialog extends JDialog { private static final int REFRESH_MS = 1000; - /** Wide enough for the tab strip to stay on one row. */ - private static final int MIN_WIDTH = 560; - private static final String SELF_ADDRESS = "This computer"; + /** Avatar box, about the official window's. */ + private static final int AVATAR_SIZE = 80; + /** Sample texts sizing the columns, as the official window does, so they don't jitter. */ + private static final String TOTAL_SAMPLE = "100.00 %"; + private static final String VALUE_SAMPLE = "1023.00 KiB/s"; private final TeamspeakConnection conn; private final int clientId; + private final String nickname; private final javax.swing.Timer timer; - private final java.util.concurrent.atomic.AtomicBoolean inFlight = - new java.util.concurrent.atomic.AtomicBoolean(); + private final AtomicBoolean inFlight = new AtomicBoolean(); - private final Rows summary = new Rows(ConnectionStatsFormat.summaryRows(null, SELF_ADDRESS)); - private final Rows total = tab(ConnectionStatsFormat.trafficRows(null, null)); - private final Rows speech = tab(ConnectionStatsFormat.trafficRows(null, ConnectionStats.Kind.SPEECH)); - private final Rows keepAlive = tab(ConnectionStatsFormat.trafficRows(null, ConnectionStats.Kind.KEEPALIVE)); - private final Rows control = tab(ConnectionStatsFormat.trafficRows(null, ConnectionStats.Kind.CONTROL)); - private final Rows voice = tab(ConnectionStatsFormat.voiceRows(null)); + private final Figures summary; + private final JButton copyAddress = new JButton(Icons.of("COPY")); + private final JLabel avatar = new JLabel(); + private Avatar shownAvatar; + private ConnectionStats latest; + + private final List traffic = new ArrayList<>(); + private Figures quota; + private final Figures voice = new Figures(List.of(ConnectionStatsFormat.voiceRows(null)), false); public ConnectionInfoDialog(Frame owner, TeamspeakConnection conn, int clientId, String nickname) { - super(owner, "Connection Info — " + nickname, false); + super(owner, "Connection Info - " + nickname, false); this.conn = conn; this.clientId = clientId; + this.nickname = nickname; + this.summary = new Figures(List.of(ConnectionStatsFormat.summaryRows(null, nickname)), true); - JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(10))); + JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(12))); content.setBackground(Theme.windowBg()); - content.setBorder(new ScaledEmptyBorder(12, 14, 12, 14)); - content.add(summary, BorderLayout.NORTH); + content.setBorder(new ScaledEmptyBorder(10, 10, 10, 10)); + content.add(buildHeader(), BorderLayout.NORTH); content.add(buildTabs(), BorderLayout.CENTER); content.add(buildButtons(), BorderLayout.SOUTH); setContentPane(content); @@ -75,7 +87,7 @@ public final class ConnectionInfoDialog extends JDialog { Dialogs.closeOnEscape(this); // Disposing is what stops the refresh timer, so the window button must not merely hide. setDefaultCloseOperation(DISPOSE_ON_CLOSE); - fit(); + pack(); setLocationRelativeTo(owner); addWindowListener(new WindowAdapter() { @@ -92,35 +104,68 @@ public final class ConnectionInfoDialog extends JDialog { // ---- construction ---- + private JPanel buildHeader() { + copyAddress.setToolTipText("Copy client address to clipboard"); + copyAddress.setMargin(UIScale.scale(new Insets(1, 1, 1, 1))); + copyAddress.setEnabled(false); + copyAddress.addActionListener(e -> { + String address = ConnectionStatsFormat.copyableAddress(latest); + if (address != null) { + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(address), null); + } + }); + summary.addTrailing(copyAddress); + + avatar.setVerticalAlignment(SwingConstants.TOP); + avatar.setBorder(new ScaledEmptyBorder(0, 16, 0, 0)); + + JPanel header = new JPanel(new BorderLayout()); + header.setOpaque(false); + header.add(summary, BorderLayout.CENTER); + header.add(avatar, BorderLayout.EAST); + return header; + } + private JTabbedPane buildTabs() { JTabbedPane tabs = new JTabbedPane(); tabs.setFont(Theme.uiFont()); - tabs.setBackground(Theme.windowBg()); - tabs.addTab("Total", total); - tabs.addTab("Speech", speech); - tabs.addTab("Keep Alive", keepAlive); - tabs.addTab("Control", control); - tabs.addTab("Voice received", voice); + for (ConnectionStatsFormat.Tab tab : ConnectionStatsFormat.TRAFFIC_TABS) { + TrafficTable table = new TrafficTable(tab.kind()); + traffic.add(table); + tabs.addTab(tab.title(), table); + } + tabs.addTab(ConnectionStatsFormat.QUOTA_TAB, buildQuota()); + tabs.addTab(ConnectionStatsFormat.VOICE_TAB, page(voice)); return tabs; } + private JComponent buildQuota() { + // Laid out for ourselves, the longer form; another client's extra rows hide on the first update. + ConnectionStats self = new ConnectionStats(); + self.self = true; + quota = new Figures(ConnectionStatsFormat.quotaGroups(self), false); + return page(quota); + } + + private static JComponent page(JComponent body) { + JPanel page = new JPanel(new BorderLayout()); + page.setOpaque(false); + page.setBorder(new ScaledEmptyBorder(8, 10, 8, 10)); + page.add(body, BorderLayout.NORTH); + return page; + } + private JPanel buildButtons() { JPanel bar = new JPanel(); bar.setLayout(new BoxLayout(bar, BoxLayout.X_AXIS)); - bar.setBackground(Theme.windowBg()); + bar.setOpaque(false); bar.add(Box.createHorizontalGlue()); - JButton close = new JButton("Close"); + JButton close = new JButton("Close", Icons.of("CLOSE")); close.addActionListener(e -> dispose()); bar.add(close); return bar; } - private static Rows tab(List rows) { - Rows tab = new Rows(rows); - tab.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); - return tab; - } - // ---- live update ---- private void refresh() { @@ -137,72 +182,156 @@ public final class ConnectionInfoDialog extends JDialog { private void apply(ConnectionStats s) { if (!isDisplayable()) return; - summary.update(ConnectionStatsFormat.summaryRows(s, SELF_ADDRESS)); - total.update(ConnectionStatsFormat.trafficRows(s, null)); - speech.update(ConnectionStatsFormat.trafficRows(s, ConnectionStats.Kind.SPEECH)); - keepAlive.update(ConnectionStatsFormat.trafficRows(s, ConnectionStats.Kind.KEEPALIVE)); - control.update(ConnectionStatsFormat.trafficRows(s, ConnectionStats.Kind.CONTROL)); - voice.update(ConnectionStatsFormat.voiceRows(s.voiceReceived)); - growToFit(); + latest = s; + summary.update(List.of(ConnectionStatsFormat.summaryRows(s, nickname))); + copyAddress.setEnabled(ConnectionStatsFormat.copyableAddress(s) != null); + for (TrafficTable table : traffic) table.update(s); + quota.update(ConnectionStatsFormat.quotaGroups(s)); + voice.update(List.of(ConnectionStatsFormat.voiceRows(s.voiceReceived))); + showAvatar(); + } + + private void showAvatar() { + ClientEntry client = conn.getModel().getClient(clientId); + Avatar current = conn.avatarOf(client); + if (current == shownAvatar) return; + shownAvatar = current; + avatar.setIcon(current == null ? null : avatarIcon(current)); + pack(); + } + + private static ImageIcon avatarIcon(Avatar avatar) { + if (avatar.file() == null) return null; + Dimension size = AvatarHtml.fit(AvatarHtml.dimensions(avatar.data()), UIScale.scale(AVATAR_SIZE)); + ImageIcon icon = new ImageIcon(avatar.data()); + if (size == null) return icon; + return new ImageIcon(icon.getImage().getScaledInstance(size.width, size.height, Image.SCALE_SMOOTH)); + } + + // ---- figures ---- + + private static JLabel label(String text) { + JLabel l = new JLabel(text); + l.setFont(Theme.uiFont()); + return l; + } + + /** Pins a label's width to that of {@code sample}, so a growing figure doesn't resize the window. */ + private static JLabel sized(JLabel l, String sample) { + Dimension pref = l.getPreferredSize(); + int width = l.getFontMetrics(l.getFont()).stringWidth(sample); + l.setPreferredSize(new Dimension(Math.max(pref.width, width), pref.height)); + return l; + } + + private static GridBagConstraints cell(int x, int y, int anchor, Insets insets) { + GridBagConstraints c = new GridBagConstraints(); + c.gridx = x; + c.gridy = y; + c.anchor = anchor; + c.insets = UIScale.scale(insets); + return c; } /** - * The window is first packed around placeholder text; once real (longer) - * values arrive it may need more room. Grow to fit, but never shrink, so the - * window doesn't jitter as counters tick up each second. + * Labelled figures, one per row, in groups set apart by a rule; refreshed in place, and + * rows an update leaves out hide. */ - private void growToFit() { - Dimension pref = getContentPane().getPreferredSize(); - Dimension have = getContentPane().getSize(); - if (pref.width > have.width || pref.height > have.height) { - fit(); - } - } + private static final class Figures extends JPanel { + private final List> groups = new ArrayList<>(); + private int lastRow; - private void fit() { - pack(); - setSize(Math.max(getWidth(), UIScale.scale(MIN_WIDTH)), getHeight()); - } - - /** A grid of labelled figures, laid out once and refreshed in place. */ - private static final class Rows extends JPanel { - private final JLabel[] values; - - Rows(List rows) { + Figures(List> rows, boolean valuesRight) { super(new GridBagLayout()); - setBackground(Theme.windowBg()); - values = new JLabel[rows.size()]; - for (int i = 0; i < values.length; i++) { - values[i] = new JLabel(rows.get(i).value()); - values[i].setFont(Theme.uiFont()); - values[i].setForeground(Theme.treeText()); - addRow(i, rows.get(i).label(), values[i]); + setOpaque(false); + int y = 0; + for (List group : rows) { + if (y > 0) { + GridBagConstraints rule = cell(0, y++, GridBagConstraints.WEST, new Insets(6, 0, 6, 0)); + rule.gridwidth = 2; + rule.fill = GridBagConstraints.HORIZONTAL; + add(new JSeparator(), rule); + } + List labels = new ArrayList<>(); + for (Row row : group) { + JLabel key = label(row.label()); + JLabel value = label(row.value()); + labels.add(new JLabel[]{key, value}); + add(key, cell(0, y, GridBagConstraints.WEST, new Insets(3, 0, 3, 16))); + GridBagConstraints vc = cell(1, y, valuesRight ? GridBagConstraints.EAST : GridBagConstraints.WEST, + new Insets(3, 0, 3, 0)); + vc.weightx = 1; + add(value, vc); + lastRow = y++; + } + groups.add(labels); } } - void update(List rows) { - for (int i = 0; i < values.length; i++) values[i].setText(rows.get(i).value()); + /** Puts {@code c} after the last row's value. */ + void addTrailing(JComponent c) { + add(c, cell(2, lastRow, GridBagConstraints.EAST, new Insets(0, 6, 0, 0))); } - private void addRow(int row, String label, JLabel valueLabel) { - GridBagConstraints lc = new GridBagConstraints(); - lc.gridx = 0; - lc.gridy = row; - lc.anchor = GridBagConstraints.WEST; - lc.insets = UIScale.scale(new Insets(2, 0, 2, 16)); - JLabel key = new JLabel(label); - key.setFont(Theme.uiFont()); - key.setForeground(new Color(0x5A6B7B)); - add(key, lc); + void update(List> rows) { + for (int g = 0; g < groups.size(); g++) { + List labels = groups.get(g); + List group = rows.get(g); + for (int i = 0; i < labels.size(); i++) { + boolean shown = i < group.size(); + labels.get(i)[0].setVisible(shown); + labels.get(i)[1].setVisible(shown); + if (shown) labels.get(i)[1].setText(group.get(i).value()); + } + } + } + } - GridBagConstraints vc = new GridBagConstraints(); - vc.gridx = 1; - vc.gridy = row; - vc.weightx = 1; - vc.anchor = GridBagConstraints.WEST; - vc.fill = GridBagConstraints.HORIZONTAL; - vc.insets = UIScale.scale(new Insets(2, 0, 2, 0)); - add(valueLabel, vc); + /** One traffic category: a row per figure under Total / In / Out headings. */ + private static final class TrafficTable extends JPanel { + private final ConnectionStats.Kind kind; + private final JLabel[][] cells; + + TrafficTable(ConnectionStats.Kind kind) { + super(new GridBagLayout()); + this.kind = kind; + setOpaque(false); + setBorder(new ScaledEmptyBorder(8, 10, 8, 10)); + + List columns = ConnectionStatsFormat.COLUMNS; + for (int c = 0; c < columns.size(); c++) { + JLabel heading = label(columns.get(c)); + heading.setFont(heading.getFont().deriveFont(Font.ITALIC)); + add(heading, column(c + 1, 0)); + } + List rows = ConnectionStatsFormat.trafficRows(null, kind); + cells = new JLabel[rows.size()][]; + for (int r = 0; r < rows.size(); r++) { + TrafficRow row = rows.get(r); + add(label(row.label()), cell(0, r + 1, GridBagConstraints.WEST, new Insets(3, 0, 3, 8))); + cells[r] = new JLabel[]{ + sized(label(row.total()), TOTAL_SAMPLE), sized(label(row.in()), VALUE_SAMPLE), + sized(label(row.out()), VALUE_SAMPLE)}; + for (int c = 0; c < cells[r].length; c++) add(cells[r][c], column(c + 1, r + 1)); + } + GridBagConstraints filler = cell(0, rows.size() + 1, GridBagConstraints.WEST, new Insets(0, 0, 0, 0)); + filler.weighty = 1; + add(Box.createGlue(), filler); + } + + private static GridBagConstraints column(int x, int y) { + GridBagConstraints c = cell(x, y, GridBagConstraints.WEST, new Insets(3, 8, 3, 8)); + c.weightx = 1; + return c; + } + + void update(ConnectionStats s) { + List rows = ConnectionStatsFormat.trafficRows(s, kind); + for (int r = 0; r < rows.size(); r++) { + cells[r][0].setText(rows.get(r).total()); + cells[r][1].setText(rows.get(r).in()); + cells[r][2].setText(rows.get(r).out()); + } } } }