diff --git a/connector/src/main.rs b/connector/src/main.rs index 1db0fad..7c5540d 100644 --- a/connector/src/main.rs +++ b/connector/src/main.rs @@ -146,6 +146,34 @@ enum Event { #[serde(flatten)] entry: ServerLogEntry, }, + /// Reply to a "clientconninfo " request - live stats for one client's + /// connection (ping, packet loss, bytes/packets sent+received). + #[serde(rename = "clientConnectionInfo")] + ClientConnectionInfo { + client_id: u16, + ping_ms: Option, + connected_secs: Option, + ip: Option, + packets_sent: u64, + bytes_sent: u64, + packets_received: u64, + bytes_received: u64, + packet_loss_percent: f32, + }, + /// Reply to a "serverconninfo" request - aggregate connection stats for + /// the whole server-side link. + #[serde(rename = "serverConnectionInfo")] + ServerConnectionInfo { + ping_ms: f64, + connected_secs: i64, + packet_loss_percent: f32, + packets_sent_total: u64, + bytes_sent_total: u64, + packets_received_total: u64, + bytes_received_total: u64, + bandwidth_sent_last_second: u64, + bandwidth_received_last_second: u64, + }, } fn emit(event: &Event) { @@ -452,6 +480,11 @@ async fn run(args: Args) -> Result<()> { // stdin command, cleared via "unwhisper". let mut whisper_channels: Vec = Vec::new(); let mut whisper_clients: Vec = Vec::new(); + // Set by "clientconninfo"/"serverconninfo" while waiting for the server's + // reply to land in book state (it arrives async as a later BookEvents + // batch, not as a direct command result) - checked and emitted below. + let mut pending_client_conninfo: Option = None; + let mut pending_server_conninfo = false; enum LoopOutcome { StdinLine(std::io::Result>), @@ -605,6 +638,39 @@ async fn run(args: Args) -> Result<()> { } else if l == "unwhisper" { whisper_channels.clear(); whisper_clients.clear(); + } else if let Some(rest) = l.strip_prefix("clientconninfo ") { + match rest.trim().parse::() { + Ok(id) => { + let client_id = ClientId(id); + let part = con.get_state()?.clients.get(&client_id).map(|c| c.connection_info()); + match part { + // send_with_result (rather than send) so a missing-permission + // rejection (e.g. viewing another client's connection info + // without b_client_view_connection_info) surfaces as a visible + // error instead of leaving the dialog stuck loading forever. + Some(part) => match part.send_with_result(&mut con) { + Ok(handle) => { + pending_client_conninfo = Some(client_id); + pending_messages.insert(handle, "Connection info".into()); + } + Err(e) => emit(&Event::Error { message: e.to_string() }), + }, + None => { + emit(&Event::Error { message: format!("Unknown client id: {id}") }) + } + } + } + Err(_) => emit(&Event::Error { message: format!("Invalid client id: {rest}") }), + } + } else if l == "serverconninfo" { + let part = con.get_state()?.server.connection_info(); + match part.send_with_result(&mut con) { + Ok(handle) => { + pending_server_conninfo = true; + pending_messages.insert(handle, "Server connection info".into()); + } + Err(e) => emit(&Event::Error { message: e.to_string() }), + } } else if let Some(b64) = l.strip_prefix("audio ") { match base64::engine::general_purpose::STANDARD.decode(b64.trim()) { Ok(bytes) => { @@ -704,6 +770,51 @@ async fn run(args: Args) -> Result<()> { log_book_event(con.get_state()?, event); } } + if let Some(client_id) = pending_client_conninfo { + match con.get_state()?.clients.get(&client_id) { + Some(client) => { + if let Some(data) = &client.connection_data { + emit(&Event::ClientConnectionInfo { + client_id: client_id.0, + ping_ms: data.ping.map(|d| d.as_seconds_f64() * 1000.0), + connected_secs: data.connected_time.map(|d| d.whole_seconds()), + ip: data.client_address.map(|a| a.ip().to_string()), + packets_sent: data.packets_sent_speech.unwrap_or(0) + + data.packets_sent_keepalive.unwrap_or(0) + + data.packets_sent_control.unwrap_or(0), + bytes_sent: data.bytes_sent_speech.unwrap_or(0) + + data.bytes_sent_keepalive.unwrap_or(0) + + data.bytes_sent_control.unwrap_or(0), + packets_received: data.packets_received_speech.unwrap_or(0) + + data.packets_received_keepalive.unwrap_or(0) + + data.packets_received_control.unwrap_or(0), + bytes_received: data.bytes_received_speech.unwrap_or(0) + + data.bytes_received_keepalive.unwrap_or(0) + + data.bytes_received_control.unwrap_or(0), + packet_loss_percent: data.client_to_server_packetloss_total, + }); + pending_client_conninfo = None; + } + } + None => pending_client_conninfo = None, + } + } + if pending_server_conninfo { + if let Some(data) = &con.get_state()?.server.connection_data { + emit(&Event::ServerConnectionInfo { + ping_ms: data.ping.as_seconds_f64() * 1000.0, + connected_secs: data.connected_time_total.whole_seconds(), + packet_loss_percent: data.packetloss_total, + packets_sent_total: data.packets_sent_total, + bytes_sent_total: data.bytes_sent_total, + packets_received_total: data.packets_received_total, + bytes_received_total: data.bytes_received_total, + bandwidth_sent_last_second: data.bandwidth_sent_last_second_total, + bandwidth_received_last_second: data.bandwidth_received_last_second_total, + }); + pending_server_conninfo = false; + } + } emit(&snapshot(con.get_state()?)); } Some(Ok(StreamItem::Audio(packet))) => { diff --git a/gateway/src/index.ts b/gateway/src/index.ts index e1f608d..31defab 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -122,6 +122,14 @@ wss.on("connection", (socket: WebSocket) => { await connection?.setWhisperTargets(msg.channelIds ?? [], msg.clientIds ?? []); break; } + case "getClientConnectionInfo": { + await connection?.getClientConnectionInfo(msg.clientId); + break; + } + case "getServerConnectionInfo": { + await connection?.getServerConnectionInfo(); + break; + } case "disconnect": { await connection?.disconnect(msg.message ?? ""); break; diff --git a/gateway/src/ts3/connection.ts b/gateway/src/ts3/connection.ts index c54bb65..4f0cfb2 100644 --- a/gateway/src/ts3/connection.ts +++ b/gateway/src/ts3/connection.ts @@ -66,7 +66,31 @@ export type Ts3ConnectionEvent = | { type: "talkers"; clients: number[] } | { type: "disconnected"; reason: string } | { type: "error"; message: string } - | ({ type: "serverLog" } & ServerLogEntry); + | ({ type: "serverLog" } & ServerLogEntry) + | { + type: "clientConnectionInfo"; + clientId: number; + pingMs: number | null; + connectedSecs: number | null; + ip: string | null; + packetsSent: number; + bytesSent: number; + packetsReceived: number; + bytesReceived: number; + packetLossPercent: number; + } + | { + type: "serverConnectionInfo"; + pingMs: number; + connectedSecs: number; + packetLossPercent: number; + packetsSentTotal: number; + bytesSentTotal: number; + packetsReceivedTotal: number; + bytesReceivedTotal: number; + bandwidthSentLastSecond: number; + bandwidthReceivedLastSecond: number; + }; export interface Ts3ConnectOptions { host: string; @@ -157,7 +181,31 @@ export class Ts3Connection { | { type: "talkers"; clients: number[] } | { type: "disconnected"; reason: string } | { type: "error"; message: string } - | ({ type: "serverLog" } & ServerLogEntry); + | ({ type: "serverLog" } & ServerLogEntry) + | { + type: "clientConnectionInfo"; + client_id: number; + ping_ms: number | null; + connected_secs: number | null; + ip: string | null; + packets_sent: number; + bytes_sent: number; + packets_received: number; + bytes_received: number; + packet_loss_percent: number; + } + | { + type: "serverConnectionInfo"; + ping_ms: number; + connected_secs: number; + packet_loss_percent: number; + packets_sent_total: number; + bytes_sent_total: number; + packets_received_total: number; + bytes_received_total: number; + bandwidth_sent_last_second: number; + bandwidth_received_last_second: number; + }; if (event.type === "connected") { this.emit({ @@ -205,6 +253,32 @@ export class Ts3Connection { fromSelf: event.from_self, message: event.message, }); + } else if (event.type === "clientConnectionInfo") { + this.emit({ + type: "clientConnectionInfo", + clientId: event.client_id, + pingMs: event.ping_ms, + connectedSecs: event.connected_secs, + ip: event.ip, + packetsSent: event.packets_sent, + bytesSent: event.bytes_sent, + packetsReceived: event.packets_received, + bytesReceived: event.bytes_received, + packetLossPercent: event.packet_loss_percent, + }); + } else if (event.type === "serverConnectionInfo") { + this.emit({ + type: "serverConnectionInfo", + pingMs: event.ping_ms, + connectedSecs: event.connected_secs, + packetLossPercent: event.packet_loss_percent, + packetsSentTotal: event.packets_sent_total, + bytesSentTotal: event.bytes_sent_total, + packetsReceivedTotal: event.packets_received_total, + bytesReceivedTotal: event.bytes_received_total, + bandwidthSentLastSecond: event.bandwidth_sent_last_second, + bandwidthReceivedLastSecond: event.bandwidth_received_last_second, + }); } else { this.emit(event); } @@ -230,6 +304,14 @@ export class Ts3Connection { this.child?.stdin.write(`switch ${channelId}\n`); } + async getClientConnectionInfo(clientId: number): Promise { + this.child?.stdin.write(`clientconninfo ${clientId}\n`); + } + + async getServerConnectionInfo(): Promise { + this.child?.stdin.write(`serverconninfo\n`); + } + async sendChatMessage(message: string): Promise { const sanitized = message.replace(/[\r\n]+/g, " ").trim(); if (sanitized) this.child?.stdin.write(`chat ${sanitized}\n`); diff --git a/web/src/App.css b/web/src/App.css index f05fc96..863526f 100644 --- a/web/src/App.css +++ b/web/src/App.css @@ -440,6 +440,42 @@ color: var(--text-muted); } +.ts-info-connection-link { + margin-top: 0.5rem; + background: none; + border: none; + padding: 0; + color: var(--accent); + font-size: 12px; + cursor: pointer; + text-align: left; +} + +.ts-info-connection-link:hover { + text-decoration: underline; +} + +.ts-connection-info-dialog { + width: 380px; +} + +.ts-connection-info-loading { + padding: 1rem; + text-align: center; + color: var(--text-muted); +} + +.ts-connection-info-grid { + display: grid; + grid-template-columns: auto 1fr; + gap: 0.35rem 0.75rem; + font-size: 12px; +} + +.ts-connection-info-grid span:nth-child(odd) { + color: var(--text-muted); +} + .ts-row-selected { background: var(--row-hover); outline: 1px solid var(--border); diff --git a/web/src/App.tsx b/web/src/App.tsx index 5fece7e..5df602d 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -282,6 +282,50 @@ interface ClientInfo { uid: string; } +interface ClientConnectionInfoData { + clientId: number; + pingMs: number | null; + connectedSecs: number | null; + ip: string | null; + packetsSent: number; + bytesSent: number; + packetsReceived: number; + bytesReceived: number; + packetLossPercent: number; +} + +interface ServerConnectionInfoData { + pingMs: number; + connectedSecs: number; + packetLossPercent: number; + packetsSentTotal: number; + bytesSentTotal: number; + packetsReceivedTotal: number; + bytesReceivedTotal: number; + bandwidthSentLastSecond: number; + bandwidthReceivedLastSecond: number; +} + +function formatBytes(bytes: number): string { + if (bytes < 1024) return `${bytes} B`; + const units = ["KB", "MB", "GB", "TB"]; + let value = bytes / 1024; + let unitIndex = 0; + while (value >= 1024 && unitIndex < units.length - 1) { + value /= 1024; + unitIndex++; + } + return `${value.toFixed(1)} ${units[unitIndex]}`; +} + +function formatDurationSecs(totalSeconds: number): string { + const hours = Math.floor(totalSeconds / 3600); + const minutes = Math.floor((totalSeconds % 3600) / 60); + const seconds = Math.floor(totalSeconds % 60); + const pad = (n: number) => String(n).padStart(2, "0"); + return hours > 0 ? `${hours}:${pad(minutes)}:${pad(seconds)}` : `${minutes}:${pad(seconds)}`; +} + /** Converts an ISO 3166-1 alpha-2 country code (e.g. "DE") to its flag emoji * via Unicode regional indicator symbols. Returns null for codes the server * doesn't report (empty string - common when geo-IP isn't configured). */ @@ -447,6 +491,7 @@ function InfoPanel({ totalClientCount, channels, clients, + onShowServerConnectionInfo, }: { selected: SelectedItem | null; host: string; @@ -457,6 +502,7 @@ function InfoPanel({ totalClientCount: number; channels: ChannelInfo[]; clients: ClientInfo[]; + onShowServerConnectionInfo: () => void; }) { const t = useT(); if (!selected || selected.type === "server") { @@ -485,6 +531,9 @@ function InfoPanel({
{t("info.currentChannels")} {channels.length}
+ ); } @@ -1271,6 +1320,139 @@ function WhisperListsDialog({ ); } +function ClientConnectionInfoDialog({ + clientName, + info, + onClose, +}: { + clientName: string; + info: ClientConnectionInfoData | null; + onClose: () => void; +}) { + const t = useT(); + const backdrop = useBackdropDismiss(onClose); + // The server may silently decline (e.g. missing permission to view another + // client's connection info) without ever replying - fall back to an error + // instead of spinning forever. + const [timedOut, setTimedOut] = useState(false); + useEffect(() => { + setTimedOut(false); + if (info) return; + const id = window.setTimeout(() => setTimedOut(true), 6000); + return () => window.clearTimeout(id); + }, [info, clientName]); + + return ( +
+
e.stopPropagation()}> +
+ {t("connectionInfo.clientTitle", { name: clientName })} + +
+
+ {!info ? ( +
+ {timedOut ? t("connectionInfo.unavailable") : t("connectionInfo.loading")} +
+ ) : ( +
+ {t("connectionInfo.ping")} + {info.pingMs != null ? `${info.pingMs.toFixed(1)} ms` : "-"} + {t("connectionInfo.connectedSince")} + {info.connectedSecs != null ? formatDurationSecs(info.connectedSecs) : "-"} + {t("connectionInfo.ip")} + {info.ip ?? "-"} + {t("connectionInfo.packetLoss")} + {info.packetLossPercent.toFixed(2)}% + {t("connectionInfo.packetsSent")} + {info.packetsSent.toLocaleString()} + {t("connectionInfo.packetsReceived")} + {info.packetsReceived.toLocaleString()} + {t("connectionInfo.bytesSent")} + {formatBytes(info.bytesSent)} + {t("connectionInfo.bytesReceived")} + {formatBytes(info.bytesReceived)} +
+ )} +
+
+
+ +
+
+
+
+ ); +} + +function ServerConnectionInfoDialog({ + info, + onClose, +}: { + info: ServerConnectionInfoData | null; + onClose: () => void; +}) { + const t = useT(); + const backdrop = useBackdropDismiss(onClose); + // The server may silently decline (e.g. missing b_virtualserver_connectioninfo_view + // permission) without ever replying - fall back to an error instead of spinning forever. + const [timedOut, setTimedOut] = useState(false); + useEffect(() => { + setTimedOut(false); + if (info) return; + const id = window.setTimeout(() => setTimedOut(true), 6000); + return () => window.clearTimeout(id); + }, [info]); + + return ( +
+
e.stopPropagation()}> +
+ {t("connectionInfo.serverTitle")} + +
+
+ {!info ? ( +
+ {timedOut ? t("connectionInfo.unavailable") : t("connectionInfo.loading")} +
+ ) : ( +
+ {t("connectionInfo.ping")} + {info.pingMs.toFixed(1)} ms + {t("connectionInfo.connectedSince")} + {formatDurationSecs(info.connectedSecs)} + {t("connectionInfo.packetLoss")} + {info.packetLossPercent.toFixed(2)}% + {t("connectionInfo.packetsSent")} + {info.packetsSentTotal.toLocaleString()} + {t("connectionInfo.packetsReceived")} + {info.packetsReceivedTotal.toLocaleString()} + {t("connectionInfo.bytesSent")} + {formatBytes(info.bytesSentTotal)} + {t("connectionInfo.bytesReceived")} + {formatBytes(info.bytesReceivedTotal)} + {t("connectionInfo.bandwidthSent")} + {formatBytes(info.bandwidthSentLastSecond)}/s + {t("connectionInfo.bandwidthReceived")} + {formatBytes(info.bandwidthReceivedLastSecond)}/s +
+ )} +
+
+
+ +
+
+
+
+ ); +} + function IdentitiesDialog({ identities, activeId, @@ -2265,6 +2447,12 @@ function AppInner() { localStorage.getItem(ACTIVE_IDENTITY_KEY) ); const [identitiesOpen, setIdentitiesOpen] = useState(false); + const [clientConnectionInfoTarget, setClientConnectionInfoTarget] = useState<{ id: number; name: string } | null>( + null + ); + const [clientConnectionInfo, setClientConnectionInfo] = useState(null); + const [serverConnectionInfoOpen, setServerConnectionInfoOpen] = useState(false); + const [serverConnectionInfo, setServerConnectionInfo] = useState(null); const [selfMenuOpen, setSelfMenuOpen] = useState(false); const selfMenuRef = useRef(null); const [changeNicknameOpen, setChangeNicknameOpen] = useState(false); @@ -2712,6 +2900,32 @@ function AppInner() { setConnectError(data.message); } break; + case "clientConnectionInfo": + setClientConnectionInfo({ + clientId: data.clientId, + pingMs: data.pingMs, + connectedSecs: data.connectedSecs, + ip: data.ip, + packetsSent: data.packetsSent, + bytesSent: data.bytesSent, + packetsReceived: data.packetsReceived, + bytesReceived: data.bytesReceived, + packetLossPercent: data.packetLossPercent, + }); + break; + case "serverConnectionInfo": + setServerConnectionInfo({ + pingMs: data.pingMs, + connectedSecs: data.connectedSecs, + packetLossPercent: data.packetLossPercent, + packetsSentTotal: data.packetsSentTotal, + bytesSentTotal: data.bytesSentTotal, + packetsReceivedTotal: data.packetsReceivedTotal, + bytesReceivedTotal: data.bytesReceivedTotal, + bandwidthSentLastSecond: data.bandwidthSentLastSecond, + bandwidthReceivedLastSecond: data.bandwidthReceivedLastSecond, + }); + break; } }; @@ -3270,6 +3484,18 @@ function AppInner() { }); }; + const handleShowClientConnectionInfo = (clientId: number, clientName: string) => { + setClientConnectionInfoTarget({ id: clientId, name: clientName }); + setClientConnectionInfo(null); + socketRef.current?.send(JSON.stringify({ type: "getClientConnectionInfo", clientId })); + }; + + const handleShowServerConnectionInfo = () => { + setServerConnectionInfoOpen(true); + setServerConnectionInfo(null); + socketRef.current?.send(JSON.stringify({ type: "getServerConnectionInfo" })); + }; + const handleClientContextMenu = ( e: React.MouseEvent, clientId: number, @@ -3495,7 +3721,14 @@ function AppInner() { {t("menu.self.setPhoneticNickname")}
- @@ -3917,6 +4150,21 @@ function AppInner() { /> )} + {clientConnectionInfoTarget && ( + setClientConnectionInfoTarget(null)} + /> + )} + + {serverConnectionInfoOpen && ( + setServerConnectionInfoOpen(false)} + /> + )} + {contactsOpen && ( 📋 {t("clientContext.copyName")} + {!clientContextMenu.isSelf && (
diff --git a/web/src/demoMode.ts b/web/src/demoMode.ts index f6323fd..71bfb6d 100644 --- a/web/src/demoMode.ts +++ b/web/src/demoMode.ts @@ -167,6 +167,40 @@ export class DemoSocket { ); break; } + case "getClientConnectionInfo": { + this.after(400, () => + this.emit({ + type: "clientConnectionInfo", + clientId: msg.clientId, + pingMs: 12.4, + connectedSecs: 217, + ip: msg.clientId === SELF_ID ? "127.0.0.1" : null, + packetsSent: 4213, + bytesSent: 512_340, + packetsReceived: 3987, + bytesReceived: 498_120, + packetLossPercent: 0, + }) + ); + break; + } + case "getServerConnectionInfo": { + this.after(400, () => + this.emit({ + type: "serverConnectionInfo", + pingMs: 8.1, + connectedSecs: 217, + packetLossPercent: 0, + packetsSentTotal: 21_004, + bytesSentTotal: 2_411_000, + packetsReceivedTotal: 19_872, + bytesReceivedTotal: 2_198_500, + bandwidthSentLastSecond: 4200, + bandwidthReceivedLastSecond: 3900, + }) + ); + break; + } // "disconnect" is intentionally unhandled here: handleDisconnect() in // App.tsx always calls socket.close() right after sending it, and // close() already emits the "disconnected" event below. diff --git a/web/src/i18n.tsx b/web/src/i18n.tsx index 8d12182..d21d17e 100644 --- a/web/src/i18n.tsx +++ b/web/src/i18n.tsx @@ -128,6 +128,21 @@ const translations: Record> = { "identities.generated": "Erstellt", "identities.pending": "Wird bei der nächsten Verbindung erstellt", + "connectionInfo.clientTitle": "Verbindungsinformationen - {name}", + "connectionInfo.serverTitle": "Serververbindungsinformationen", + "connectionInfo.loading": "Wird geladen…", + "connectionInfo.unavailable": "Keine Antwort vom Server (fehlende Berechtigung?).", + "connectionInfo.ping": "Ping:", + "connectionInfo.connectedSince": "Verbunden seit:", + "connectionInfo.ip": "IP-Adresse:", + "connectionInfo.packetLoss": "Paketverlust:", + "connectionInfo.packetsSent": "Pakete gesendet:", + "connectionInfo.packetsReceived": "Pakete empfangen:", + "connectionInfo.bytesSent": "Daten gesendet:", + "connectionInfo.bytesReceived": "Daten empfangen:", + "connectionInfo.bandwidthSent": "Bandbreite gesendet:", + "connectionInfo.bandwidthReceived": "Bandbreite empfangen:", + "menu.self.recordingProfile": "Aufnahmeprofil", "menu.self.playbackProfile": "Wiedergabeprofil", "menu.self.hotkeyProfile": "Hotkeyprofil", @@ -291,6 +306,7 @@ const translations: Record> = { "clientContext.privateChat": "Privater Chat", "clientContext.poke": "Anstupsen", "clientContext.copyName": "Namen kopieren", + "clientContext.connectionInfo": "Verbindungsinformationen anzeigen", "clientContext.addWhisperTarget": "Als Whisper-Ziel hinzufügen", "clientContext.removeWhisperTarget": "Als Whisper-Ziel entfernen", "clientContext.assignChannelGroup": "Channel-Gruppe zuweisen", @@ -451,6 +467,21 @@ const translations: Record> = { "identities.generated": "Generated", "identities.pending": "Will be generated on next connection", + "connectionInfo.clientTitle": "Connection Info - {name}", + "connectionInfo.serverTitle": "Server Connection Info", + "connectionInfo.loading": "Loading…", + "connectionInfo.unavailable": "No response from the server (missing permission?).", + "connectionInfo.ping": "Ping:", + "connectionInfo.connectedSince": "Connected since:", + "connectionInfo.ip": "IP address:", + "connectionInfo.packetLoss": "Packet loss:", + "connectionInfo.packetsSent": "Packets sent:", + "connectionInfo.packetsReceived": "Packets received:", + "connectionInfo.bytesSent": "Data sent:", + "connectionInfo.bytesReceived": "Data received:", + "connectionInfo.bandwidthSent": "Bandwidth sent:", + "connectionInfo.bandwidthReceived": "Bandwidth received:", + "menu.self.recordingProfile": "Recording Profile", "menu.self.playbackProfile": "Playback Profile", "menu.self.hotkeyProfile": "Hotkey Profile", @@ -614,6 +645,7 @@ const translations: Record> = { "clientContext.privateChat": "Private chat", "clientContext.poke": "Poke", "clientContext.copyName": "Copy name", + "clientContext.connectionInfo": "Show connection info", "clientContext.addWhisperTarget": "Add as whisper target", "clientContext.removeWhisperTarget": "Remove as whisper target", "clientContext.assignChannelGroup": "Assign channel group",