diff --git a/README.md b/README.md index 3265c44..523a342 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -

+๏ปฟ

WebSpeak3 logo

@@ -78,7 +78,8 @@ installed on the same machine, modified, or operated by you. | ๐Ÿ“ฑ **Mobile-friendly layout** | Responsive single-column layout for narrow screens, not just a shrunk desktop UI | | ๐ŸŒ **Localized UI** | Interface available in German, English, and Simplified Chinese, detected automatically or switchable in Options | | ๐ŸŒ— **Dark / light theme** | Clean, modern UI that adapts to your preference | -| ๐Ÿ” **Seamless reconnect** | Switch connections mid-session โ€” old state tears down cleanly, no leaks or duplicates | +| ๐Ÿ” **Multi-join (server tabs)** | Several TeamSpeak connections in parallel โ€” one tab per server, like GreenTeaSpeak 2. Audio stays on the active tab | +| ๐Ÿ” **Seamless reconnect** | Switch or add connections mid-session without tearing down unrelated tabs | ## ๐Ÿงฑ Tech Stack @@ -108,8 +109,9 @@ Browser (web/) <--WebSocket--> Gateway (gateway/) <--stdin/stdout JSON--> Ru - **`web/`** โ€” Vite + React frontend. TS3-lookalike UI: channel tree, chat tabs, voice controls. - **`gateway/`** โ€” Node.js/TypeScript WebSocket server. Spawns the Rust - connector per browser connection and relays newline-delimited JSON events - between it and the browser. + connector **per browser WebSocket** and relays newline-delimited JSON events + between it and the browser. Multi-join opens one `/ws` connection per server + tab (parallel connectors). - **`connector/`** โ€” Rust binary wrapping [`tsclientlib`](https://github.com/ReSpeak/tsclientlib) (vendored as a git submodule in `tsclientlib/`), the actual TS3/TS6 protocol implementation. Handles connecting, channel/client state, chat, @@ -222,7 +224,7 @@ npm install npm run dev ``` -This starts the WebSocket gateway on `ws://localhost:8080`. +This starts the WebSocket gateway on `ws://localhost:8080`. Open **http://localhost:8080** for the UI (serves `web/dist`). After UI changes run `cd web && npm run build`, then reload. Optional Vite (`npm run dev` in `web/`, typically `:5173`) is only for HMR. `WEB_STATIC=0 npm run dev` serves API/WebSocket only. **4. Install and start the web frontend** @@ -235,6 +237,9 @@ npm run dev ``` Vite will print a local dev URL (typically `http://localhost:5173`) โ€” open it in a browser. +The Vite app connects to the gateway at `ws://localhost:8080/ws`. + +> **Preferred UI:** **http://localhost:8080** (static `web/dist` โ€” refresh after `cd web && npm run build`). Vite `:5173` is optional HMR only. **5. Connect** diff --git a/connector/Cargo.lock b/connector/Cargo.lock index 011a9ee..bd2937d 100644 --- a/connector/Cargo.lock +++ b/connector/Cargo.lock @@ -2639,6 +2639,7 @@ dependencies = [ "base64", "clap", "futures", + "num-traits", "serde", "serde_json", "time", diff --git a/connector/Cargo.toml b/connector/Cargo.toml index 9b3cb80..564cfb4 100644 --- a/connector/Cargo.toml +++ b/connector/Cargo.toml @@ -13,6 +13,7 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" clap = { version = "4", features = ["derive"] } anyhow = "1" +num-traits = "0.2" tracing-subscriber = { version = "0.3", features = ["env-filter"] } base64 = "0.22" time = "0.3" diff --git a/connector/src/main.rs b/connector/src/main.rs index 032bf9b..9ba903e 100644 --- a/connector/src/main.rs +++ b/connector/src/main.rs @@ -7,6 +7,7 @@ use audiopus::coder::Encoder as OpusEncoder; use base64::Engine; use clap::Parser; use futures::prelude::*; +use num_traits::ToPrimitive; use serde::{Deserialize, Serialize}; use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; @@ -23,9 +24,10 @@ use tsclientlib::messages::c2s::{ }; use tsclientlib::prelude::*; use tsclientlib::{ - data, ChannelGroupId, ChannelId, ClientDbId, ClientId, CodecEncryptionMode, Connection, - DisconnectOptions, HostBannerMode, HostMessageMode, Identity, InMessage, MaxClients, - MessageHandle, MessageTarget, Permission, Reason, ServerGroupId, StreamItem, TextMessageTargetMode, + data, ChannelGroupId, ChannelId, ClientDbId, ClientId, ClientType, CodecEncryptionMode, + Connection, DisconnectOptions, HostBannerMode, HostMessageMode, Identity, InMessage, + LicenseType, MaxClients, MessageHandle, MessageTarget, Permission, Reason, ServerGroupId, + ServerType, StreamItem, TextMessageTargetMode, }; use tsproto_packets::packets::{AudioData, CodecType, Direction, Flags, OutAudio, OutCommand, PacketType}; @@ -58,6 +60,13 @@ struct Args { /// reported back the same way - when omitted or unparseable. #[arg(long)] identity: Option, + /// Server flavour: `teamspeak` (skip TeaSpeak handshake), `teaspeak` + /// (always handshake), or `auto` (handshake when server sends `teaspeak=1`). + #[arg(long, default_value = "auto", value_parser = ["auto", "teamspeak", "teaspeak"])] + server_type: String, + /// Privilege key / token (`client_default_token` in clientinit). + #[arg(long, alias = "token")] + privilege_key: Option, } #[derive(Serialize)] @@ -184,13 +193,26 @@ enum Event { server_max_clients: u16, server_version: String, server_license: String, + /// Raw id for UI coloring (GTS: 0=none, 1=Private, 2=Premium, 3=Authorized). + server_license_id: u8, server_banner_url: String, /// Opaque JSON blob the frontend can store and pass back as `--identity` /// on a future connection to keep the same client UID. identity: String, }, #[serde(rename = "channels")] - Channels { channels: Vec, clients: Vec }, + Channels { + channels: Vec, + clients: Vec, + /// Our own client id โ€” frontend must not guess this via nickname match. + own_client_id: u16, + /// From `virtualserver_maxclients` (updated via `notifyserverupdated`). + server_max_clients: u16, + /// From `virtualserver_clientsonline` when known, else visible client count. + server_clients_online: u16, + /// From `virtualserver_channelsonline` when known, else visible channel count. + server_channels_online: u64, + }, #[serde(rename = "chatMessage")] ChatMessage { from: String, message: String }, #[serde(rename = "serverMessage")] @@ -241,6 +263,7 @@ enum Event { #[serde(rename = "serverConnectionInfo")] ServerConnectionInfo { ping_ms: f64, + /// Server-side connection/uptime seconds (shown as Uptime, not session time). connected_secs: i64, packet_loss_percent: f32, packets_sent_total: u64, @@ -249,6 +272,12 @@ enum Event { bytes_received_total: u64, bandwidth_sent_last_second: u64, bandwidth_received_last_second: u64, + bandwidth_sent_last_minute: u64, + bandwidth_received_last_minute: u64, + filetransfer_bandwidth_sent: u64, + filetransfer_bandwidth_received: u64, + filetransfer_bytes_sent: u64, + filetransfer_bytes_received: u64, }, /// Reply to a "serverlog" request - raw lines from the virtual server's /// protocol log (distinct from `ServerLog` above, which is the synthesized @@ -538,10 +567,15 @@ fn snapshot(con: &data::Connection) -> Event { }, has_password: ch.has_password.unwrap_or(false), }) - .collect(); + .collect::>(); + // Bookkeeping includes ServerQuery clients (`ClientType::Query`); hide them + // from the channel tree / client lists. Online counters still use the + // server-reported total (often includes Query) via `client_count` below. + let all_clients_count = con.clients.len() as u16; let clients = con .clients .values() + .filter(|c| !matches!(c.client_type, ClientType::Query { .. })) .map(|c| { // A channel with no talk power requirement at all (the common // case) is never moderated, so everyone can talk regardless of @@ -569,8 +603,38 @@ fn snapshot(con: &data::Connection) -> Event { has_talk_power, } }) - .collect(); - Event::Channels { channels, clients } + .collect::>(); + + // Prefer server-reported counters (GTS/TS `virtualserver_*` via notifyserverupdated) + // but never under-report vs. the full bookkeeping client set including Query + // (stale optional_data after joins would otherwise freeze the InfoPanel left number). + let opt = con.server.optional_data.as_ref(); + let visible_channels = channels.len() as u64; + let server_clients_online = + opt.map(|d| d.client_count.max(all_clients_count)).unwrap_or(all_clients_count); + let server_channels_online = + opt.map(|d| d.channel_count.max(visible_channels)).unwrap_or(visible_channels); + + Event::Channels { + channels, + clients, + own_client_id: con.own_client.0, + server_max_clients: con.server.max_clients, + server_clients_online, + server_channels_online, + } +} + +fn send_server_get_variables(con: &mut tsclientlib::Connection) { + let packet = OutCommand::new( + Direction::C2S, + Flags::empty(), + PacketType::Command, + "servergetvariables", + ); + if let Err(e) = packet.send(con) { + emit(&Event::Error { message: format!("servergetvariables failed: {e}") }); + } } #[tokio::main] @@ -581,11 +645,74 @@ async fn main() { } } +/// GreenTeaSpeak servers report versions like `2.5.1 [Build: โ€ฆ]`. +/// Classic TeaSpeak reports `TeaSpeak 1.4.21-beta [Build: โ€ฆ]` โ€” not a GTS host. +/// Classic TeamSpeak 3 reports `3.13.8 [Build: โ€ฆ]` โ€” must not use GTS labels. +fn is_greenteaspeak_server_version(version: &str) -> bool { + let v = version.trim(); + if v.is_empty() { + return false; + } + let lower = v.to_ascii_lowercase(); + if lower.starts_with("teaspeak") || lower.starts_with("3.") { + return false; + } + let mut parts = v.split('.'); + matches!( + (parts.next(), parts.next(), parts.next()), + (Some(a), Some(b), Some(c)) + if !a.is_empty() + && a.chars().all(|ch| ch.is_ascii_digit()) + && !b.is_empty() + && b.chars().all(|ch| ch.is_ascii_digit()) + && c.chars().next().is_some_and(|ch| ch.is_ascii_digit()) + ) +} + +/// Labels match the GreenTeaSpeak desktop client (`formatLicenseLabel`). +fn format_server_license(license: LicenseType, version: &str) -> String { + if is_greenteaspeak_server_version(version) { + return match license { + LicenseType::Offline => "Private".into(), + LicenseType::Sdk => "Premium".into(), + LicenseType::SdkOffline => "Authorized GreenTeaSpeak Host Provider".into(), + _ => "Keine Lizenz".into(), + }; + } + if version.trim().to_ascii_lowercase().starts_with("teaspeak") { + return "Kein GreenTeaSpeak-Server".into(); + } + match license { + LicenseType::NoLicense => "No License".into(), + LicenseType::Offline => "Offline / LAN".into(), + LicenseType::Sdk => "SDK".into(), + LicenseType::SdkOffline => "SDK Offline".into(), + LicenseType::Npl => "NPL".into(), + LicenseType::Athp => "ATHP".into(), + LicenseType::Aal => "AAL".into(), + LicenseType::Default => "Default".into(), + LicenseType::Gamer => "Gamer".into(), + LicenseType::Sponsorship => "Sponsorship".into(), + LicenseType::Commercial => "Commercial".into(), + } +} + /// tsclientlib's error `Display` impls mostly fall back to `{:?}` for nested /// errors (e.g. `Failed to connect to server at "x": [Connect(TsProto(Timeout(..)))]`), /// which is accurate but not something an end user can act on. Map the cases /// that come up in practice to plain-language messages instead. fn friendly_connect_error(address: &str, e: tsclientlib::Error) -> anyhow::Error { + let raw = e.to_string(); + if raw.contains("client\\stype\\sis\\snot\\sallowed") + || raw.contains("client type is not allowed") + || raw.contains("id=533") + { + return anyhow::anyhow!( + "Could not connect to \"{address}\": this server rejects this client type (error 533). \ +GreenTeaSpeak public servers often only allow the official GreenTeaSpeak desktop client. \ +Try a self-hosted TeaSpeak with TeamSpeak-compat enabled, or use GreenTeaSpeak 2 for ts.greenteaspeak.de." + ); + } match &e { tsclientlib::Error::ConnectTs(inner) => { anyhow::anyhow!("The server rejected the connection: {inner}") @@ -593,7 +720,7 @@ fn friendly_connect_error(address: &str, e: tsclientlib::Error) -> anyhow::Error tsclientlib::Error::InitserverTimeout => anyhow::anyhow!( "The server did not finish logging us in within the timeout - please try again" ), - _ if e.to_string().contains("Timeout") => anyhow::anyhow!( + _ if raw.contains("Timeout") => anyhow::anyhow!( "Could not reach \"{address}\": connection timed out. Check the address/port and that the server is reachable." ), _ => anyhow::anyhow!("Could not connect to \"{address}\": {e}"), @@ -617,6 +744,15 @@ async fn run(args: Args) -> Result<()> { .unwrap_or_else(Identity::create); let identity_str = serde_json::to_string(&identity).unwrap(); let mut con_config = Connection::build(args.address).name(args.nickname).identity(identity); + let server_type = match args.server_type.as_str() { + "teaspeak" => ServerType::Teaspeak, + "teamspeak" => ServerType::Teamspeak, + _ => ServerType::Auto, + }; + con_config = con_config.server_type(server_type); + if let Some(token) = args.privilege_key { + con_config = con_config.default_token(token); + } if let Some(pwd) = args.server_password { con_config = con_config.password(pwd); } @@ -655,7 +791,8 @@ async fn run(args: Args) -> Result<()> { let server_name = server_state.server.name.clone(); let server_max_clients = server_state.server.max_clients; let server_version = server_state.server.version.clone(); - let server_license = format!("{:?}", server_state.server.license); + let server_license = format_server_license(server_state.server.license, &server_version); + let server_license_id = server_state.server.license.to_u8().unwrap_or(0); let server_banner_url = server_state.server.hostbanner_gfx_url.clone(); emit(&Event::Connected { welcome_message, @@ -663,6 +800,7 @@ async fn run(args: Args) -> Result<()> { server_max_clients, server_version, server_license, + server_license_id, server_banner_url, identity: identity_str, }); @@ -670,6 +808,10 @@ async fn run(args: Args) -> Result<()> { // Subscribe to all channels so we actually receive the full channel/client list. con.get_state()?.server.set_subscribed(true).send(&mut con)?; + // Ask for virtualserver_* counters (maxclients / clientsonline / โ€ฆ) like GTS. + // Reply arrives as notifyserverupdated and updates bookkeeping + snapshots. + send_server_get_variables(&mut con); + // Give the server a moment to send the channel/client list, then emit a // snapshot. Further snapshots are emitted below whenever book state changes. { @@ -758,19 +900,37 @@ async fn run(args: Args) -> Result<()> { // eventual emit can be routed back to it. let mut pending_perm_list: Option<(String, u64, Option)> = None; let mut pending_perm_list_raw: Option> = None; + // TeaSpeak may reveal hidden channels after a group/permission change. Debounce + // a channelsubscribeall so we pick up any channels the server only exposes then. + let mut resubscribe_at: Option = None; enum LoopOutcome { StdinLine(std::io::Result>), ConEvent(Option>), AudioTick, + Resubscribe, + ServerVarsRefresh, } + // Keep virtualserver_maxclients / clientsonline in sync (GTS-style). + let mut server_vars_ticker = tokio::time::interval(tokio::time::Duration::from_secs(20)); + server_vars_ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + // First tick fires immediately; we already requested once after connect. + server_vars_ticker.tick().await; + loop { let mut events = con.events(); let outcome = tokio::select! { line = stdin_lines.next_line() => LoopOutcome::StdinLine(line), ev = events.next() => LoopOutcome::ConEvent(ev), _ = audio_ticker.tick() => LoopOutcome::AudioTick, + _ = server_vars_ticker.tick() => LoopOutcome::ServerVarsRefresh, + _ = async { + match resubscribe_at { + Some(at) => tokio::time::sleep_until(at).await, + None => std::future::pending::<()>().await, + } + } => LoopOutcome::Resubscribe, }; drop(events); @@ -792,16 +952,39 @@ async fn run(args: Args) -> Result<()> { } else if let Some(rest) = l.strip_prefix("switch ") { match rest.trim().parse::() { Ok(id) => { - let part = { - let state = con.get_state()?; - let own = &state.clients[&state.own_client]; - own.client_move(ChannelId(id)) + // Build clientmove defensively: missing own client must not panic + // the whole connector (that looked like a dead Join from the UI). + let part = match con.get_state() { + Ok(state) => match state.clients.get(&state.own_client) { + Some(own) => { + // Always include cpw= (empty) like the GTS desktop client โ€” + // some TeaSpeak builds are picky about an omitted key. + let mut part = own.client_move(ChannelId(id)); + part.channel_password = Some(std::borrow::Cow::Borrowed("")); + Some(part) + } + None => { + emit(&Event::Error { + message: "Channel switch failed: own client not in book state" + .into(), + }); + None + } + }, + Err(e) => { + emit(&Event::Error { + message: format!("Channel switch failed: {e}"), + }); + None + } }; - match part.send_with_result(&mut con) { - Ok(handle) => { - pending_messages.insert(handle, "Channel switch".into()); + if let Some(part) = part { + match part.send_with_result(&mut con) { + Ok(handle) => { + pending_messages.insert(handle, "Channel switch".into()); + } + Err(e) => emit(&Event::Error { message: e.to_string() }), } - Err(e) => emit(&Event::Error { message: e.to_string() }), } } Err(_) => emit(&Event::Error { message: format!("Invalid channel id: {rest}") }), @@ -1075,6 +1258,9 @@ async fn run(args: Args) -> Result<()> { match part.send_with_result(&mut con) { Ok(handle) => { pending_messages.insert(handle, "Server edit".into()); + // Refresh counters/maxclients after edit (notifyserveredited + // may be partial on TeaSpeak; servergetvariables fills gaps). + send_server_get_variables(&mut con); } Err(e) => emit(&Event::Error { message: e.to_string() }), } @@ -1841,6 +2027,7 @@ async fn run(args: Args) -> Result<()> { }, LoopOutcome::ConEvent(ev) => match ev { Some(Ok(StreamItem::BookEvents(events))) => { + let own_id = con.get_state()?.own_client; for event in &events { if let BookEvent::Message { target, invoker, message } = event { match target { @@ -1857,7 +2044,6 @@ async fn run(args: Args) -> Result<()> { }); } MessageTarget::Client(other_id) => { - let own_id = con.get_state()?.own_client; if invoker.id == own_id { let partner_name = con .get_state()? @@ -1885,6 +2071,22 @@ async fn run(args: Args) -> Result<()> { } } } else { + // Group add/remove emit PropertyAdded/Removed (not Changed). + if matches!( + event, + BookEvent::PropertyAdded { + id: PropertyId::ClientServerGroup(id, _), + .. + } | BookEvent::PropertyRemoved { + id: PropertyId::ClientServerGroup(id, _), + .. + } if *id == own_id + ) { + resubscribe_at = Some( + tokio::time::Instant::now() + + tokio::time::Duration::from_millis(250), + ); + } log_book_event(con.get_state()?, event); } } @@ -1919,16 +2121,25 @@ async fn run(args: Args) -> Result<()> { } if pending_server_conninfo { if let Some(data) = &con.get_state()?.server.connection_data { + // TeaSpeak/TS may report packet loss as a fraction (0โ€“1) or percent. + let loss = data.packetloss_total; + let packet_loss_percent = if loss <= 1.0 { loss * 100.0 } else { loss }; 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, + packet_loss_percent, 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, + bandwidth_sent_last_minute: data.bandwidth_sent_last_minute_total, + bandwidth_received_last_minute: data.bandwidth_received_last_minute_total, + filetransfer_bandwidth_sent: data.filetransfer_bandwidth_sent, + filetransfer_bandwidth_received: data.filetransfer_bandwidth_received, + filetransfer_bytes_sent: data.filetransfer_bytes_sent_total, + filetransfer_bytes_received: data.filetransfer_bytes_received_total, }); pending_server_conninfo = false; } @@ -2323,6 +2534,19 @@ async fn run(args: Args) -> Result<()> { break; } }, + LoopOutcome::Resubscribe => { + resubscribe_at = None; + // Re-send channelsubscribeall so TeaSpeak pushes newly visible channels + // (and clients in them) after our own server-group change. + if let Err(e) = con.get_state()?.server.set_subscribed(true).send(&mut con) { + emit(&Event::Error { + message: format!("channelsubscribeall after perm change failed: {e}"), + }); + } + } + LoopOutcome::ServerVarsRefresh => { + send_server_get_variables(&mut con); + } LoopOutcome::AudioTick => { if !audio_handler.get_queues().is_empty() { let mut buf = vec![0.0f32; FRAME_SAMPLES * OUT_CHANNELS]; diff --git a/docs/teaspeak.md b/docs/teaspeak.md new file mode 100644 index 0000000..76824eb --- /dev/null +++ b/docs/teaspeak.md @@ -0,0 +1,24 @@ +# TeaSpeak / GreenTeaSpeak support (WebSpeak3) + +WebSpeak3 can speak the TeamSpeak 3/6 protocol via `ts-connector` / `tsclientlib`. +TeaSpeak / GreenTeaSpeak servers need an extra identity handshake before `clientinit`. + +## Implemented + +- `--server-type teamspeak|teaspeak|auto` (connector; UI Connect dialog; gateway relay) +- `--privilege-key` / `client_default_token` on connect +- `clientinitiv` with **`-teaspeak` switch** (not `teaspeak=1`), `ip=unknown`, alpha bit0 +- Classic TeaSpeak crypto via **`initivexpand`** (P-256 ECDH, 20-byte IV) when the server + answers that way โ€” required for GreenTeaSpeak hubs that disable TeamSpeak clients +- TEAMSPEAK identity handshake after crypto when needed +- DNS SRV `_gts._udp` in addition to `_ts3._udp` +- Design theme **GreenTeaSpeak** (third UI style) + +Verified against `ts.greenteaspeak.de` (Official GreenTeaSpeak Public Server). + +## Not yet (follow-up) + +- TEAFORO / forum identity (`greenteaspeak.de` login + method 0) +- Native TeaSpeak POW / `teaclient_connection.node` parity +- GTS badges / HWID extras beyond the basic handshake +- Forum-reject โ†’ automatic ECC identity retry (GreenTeaSpeak 2 desktop behavior) diff --git a/gateway/package-lock.json b/gateway/package-lock.json index 1d6c04f..e74b2e9 100644 --- a/gateway/package-lock.json +++ b/gateway/package-lock.json @@ -1,11 +1,11 @@ { - "name": "ts-web-gateway", + "name": "webspeak3-gateway", "version": "0.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "ts-web-gateway", + "name": "webspeak3-gateway", "version": "0.1.0", "dependencies": { "ws": "^8.18.0" diff --git a/gateway/src/index.ts b/gateway/src/index.ts index de5e76d..3cc18b2 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -3,15 +3,34 @@ import { readFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { WebSocketServer, type WebSocket } from "ws"; -import { Ts3Connection, type Ts3ConnectOptions } from "./ts3/connection.js"; +import { Ts3Connection, type ServerType, type Ts3ConnectOptions } from "./ts3/connection.js"; + +const SERVER_TYPES = new Set(["teamspeak", "teaspeak", "auto"]); + +function parseServerType(value: unknown): ServerType | undefined { + return typeof value === "string" && SERVER_TYPES.has(value as ServerType) + ? (value as ServerType) + : undefined; +} + +function parsePrivilegeKey(msg: { privilegeKey?: unknown; token?: unknown }): string | undefined { + const raw = msg.privilegeKey ?? msg.token; + if (typeof raw !== "string") return undefined; + const trimmed = raw.trim(); + return trimmed || undefined; +} const PORT = Number(process.env.PORT ?? 8080); // In production (Docker), the built web app lives alongside the gateway and // is served from the same port as the WebSocket endpoint, so a single // reverse-proxied origin (e.g. a Zoraxy subdomain) is enough for everything. +// Local Vite dev (`npm run dev` in web/) is a separate UI on :5173 that talks +// to this gateway only via WebSocket โ€” do not use :8080's HTML for UI work +// unless you rebuilt web/dist. Set WEB_STATIC=0 to serve API/WS only. const __dirname = path.dirname(fileURLToPath(import.meta.url)); const WEB_DIST = process.env.WEB_DIST ?? path.resolve(__dirname, "../../web/dist"); +const SERVE_STATIC = process.env.WEB_STATIC !== "0"; const MIME_TYPES: Record = { ".html": "text/html", @@ -24,9 +43,23 @@ const MIME_TYPES: Record = { ".woff2": "font/woff2", }; +const DEV_HINT = ` +

WebSpeak3 gateway

+

WebSocket: /ws

+

Static UI is disabled (WEB_STATIC=0) or web/dist is missing.

+

For local development open the Vite app at http://localhost:5173/ +(run npm run dev in web/). Rebuild with npm run build in web/ +to serve the UI from this port again.

+`; + const server = createServer((req, res) => { void (async () => { try { + if (!SERVE_STATIC) { + res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); + res.end(DEV_HINT); + return; + } const url = new URL(req.url ?? "/", "http://localhost"); let filePath = path.join(WEB_DIST, decodeURIComponent(url.pathname)); if (!filePath.startsWith(WEB_DIST)) { @@ -45,8 +78,8 @@ const server = createServer((req, res) => { res.writeHead(200, { "Content-Type": MIME_TYPES[path.extname(filePath)] ?? "application/octet-stream" }); res.end(body); } catch { - res.writeHead(404); - res.end("Not found"); + res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); + res.end(DEV_HINT); } })(); }); @@ -55,9 +88,17 @@ const wss = new WebSocketServer({ server, path: "/ws" }); server.listen(PORT, () => { console.log(`WebSpeak3 gateway listening on http://localhost:${PORT} (WebSocket at /ws)`); + if (SERVE_STATIC) { + console.log(`Serving static UI from ${WEB_DIST}`); + console.log(`Dev tip: use http://localhost:5173/ for live UI; rebuild web/dist after UI changes if you open :${PORT}`); + } else { + console.log(`Static UI disabled (WEB_STATIC=0) โ€” open http://localhost:5173/ for the Vite dev UI`); + } }); wss.on("connection", (socket: WebSocket) => { + // One browser WebSocket โ†” one Rust connector. Multi-join in the UI opens + // multiple /ws connections in parallel (one per server tab). let connection: Ts3Connection | undefined; socket.on("message", async (raw) => { @@ -65,6 +106,16 @@ wss.on("connection", (socket: WebSocket) => { switch (msg.type) { case "connect": { + // Replacing a connection on the same socket: tear down the previous + // connector so we don't leak processes. + if (connection) { + try { + await connection.disconnect(); + } catch { + /* ignore */ + } + connection = undefined; + } const options: Ts3ConnectOptions = { host: msg.host, nickname: msg.nickname, @@ -72,6 +123,8 @@ wss.on("connection", (socket: WebSocket) => { channelPassword: msg.channelPassword, defaultChannel: msg.defaultChannel, identity: msg.identity, + serverType: parseServerType(msg.serverType), + privilegeKey: parsePrivilegeKey(msg), }; connection = new Ts3Connection(options); connection.onEvent((event) => socket.send(JSON.stringify(event))); @@ -79,7 +132,10 @@ wss.on("connection", (socket: WebSocket) => { break; } case "switchChannel": { - await connection?.switchChannel(msg.channelId); + const channelId = Number(msg.channelId); + if (Number.isFinite(channelId)) { + await connection?.switchChannel(channelId); + } break; } case "sendChatMessage": { diff --git a/gateway/src/ts3/connection.ts b/gateway/src/ts3/connection.ts index e59349a..b6c7d65 100644 --- a/gateway/src/ts3/connection.ts +++ b/gateway/src/ts3/connection.ts @@ -118,10 +118,11 @@ export type Ts3ConnectionEvent = serverMaxClients: number; serverVersion: string; serverLicense: string; + serverLicenseId: number; serverBannerUrl: string; identity: string; } - | { type: "channels"; channels: ChannelInfo[]; clients: ClientInfo[] } + | { type: "channels"; channels: ChannelInfo[]; clients: ClientInfo[]; ownClientId: number; serverMaxClients: number; serverClientsOnline: number; serverChannelsOnline: number } | { type: "chatMessage"; from: string; message: string } | { type: "serverMessage"; from: string; message: string } | { type: "privateMessage"; partnerId: number; partnerName: string; fromSelf: boolean; message: string } @@ -154,6 +155,12 @@ export type Ts3ConnectionEvent = bytesReceivedTotal: number; bandwidthSentLastSecond: number; bandwidthReceivedLastSecond: number; + bandwidthSentLastMinute: number; + bandwidthReceivedLastMinute: number; + filetransferBandwidthSent: number; + filetransferBandwidthReceived: number; + filetransferBytesSent: number; + filetransferBytesReceived: number; } | { type: "serverProtocolLog"; lines: string[] } | { type: "banList"; entries: BanListEntry[] } @@ -176,6 +183,8 @@ export type Ts3ConnectionEvent = | { type: "permList"; scope: PermScope; id1: number; id2: number | null; entries: PermissionOverviewEntry[] } | { type: "permissionCatalog"; entries: PermissionCatalogEntry[] }; +export type ServerType = "teamspeak" | "teaspeak" | "auto"; + export interface Ts3ConnectOptions { host: string; nickname: string; @@ -185,6 +194,10 @@ export interface Ts3ConnectOptions { /** Previously-issued identity (from a prior "connected" event) to keep * the same client UID across sessions. Omit to get a freshly generated one. */ identity?: string; + /** Protocol / server dialect hint for the connector (`auto` when omitted). */ + serverType?: ServerType; + /** One-time privilege key / token to redeem on connect. */ + privilegeKey?: string; } const __dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -216,6 +229,8 @@ export class Ts3Connection { if (this.options.channelPassword) args.push("--channel-password", this.options.channelPassword); if (this.options.defaultChannel) args.push("--default-channel", this.options.defaultChannel); if (this.options.identity) args.push("--identity", this.options.identity); + if (this.options.serverType) args.push("--server-type", this.options.serverType); + if (this.options.privilegeKey) args.push("--privilege-key", this.options.privilegeKey); this.child = spawn(CONNECTOR_BIN, args); createInterface({ input: this.child.stdout }).on("line", (line) => { @@ -257,10 +272,19 @@ export class Ts3Connection { server_max_clients: number; server_version: string; server_license: string; + server_license_id?: number; server_banner_url: string; identity: string; } - | { type: "channels"; channels: RawChannelInfo[]; clients: RawClientInfo[] } + | { + type: "channels"; + channels: RawChannelInfo[]; + clients: RawClientInfo[]; + own_client_id?: number; + server_max_clients?: number; + server_clients_online?: number; + server_channels_online?: number; + } | { type: "chatMessage"; from: string; message: string } | { type: "serverMessage"; from: string; message: string } | { type: "privateMessage"; partner_id: number; partner_name: string; from_self: boolean; message: string } @@ -293,6 +317,12 @@ export class Ts3Connection { bytes_received_total: number; bandwidth_sent_last_second: number; bandwidth_received_last_second: number; + bandwidth_sent_last_minute?: number; + bandwidth_received_last_minute?: number; + filetransfer_bandwidth_sent?: number; + filetransfer_bandwidth_received?: number; + filetransfer_bytes_sent?: number; + filetransfer_bytes_received?: number; } | { type: "serverProtocolLog"; lines: string[] } | { @@ -359,6 +389,7 @@ export class Ts3Connection { serverMaxClients: event.server_max_clients, serverVersion: event.server_version, serverLicense: event.server_license, + serverLicenseId: event.server_license_id ?? 0, serverBannerUrl: event.server_banner_url, identity: event.identity, }); @@ -392,6 +423,10 @@ export class Ts3Connection { serverGroups: c.server_groups, hasTalkPower: c.has_talk_power, })), + ownClientId: event.own_client_id ?? 0, + serverMaxClients: event.server_max_clients ?? 0, + serverClientsOnline: event.server_clients_online ?? event.clients.length, + serverChannelsOnline: event.server_channels_online ?? event.channels.length, }); } else if (event.type === "privateMessage") { this.emit({ @@ -426,6 +461,12 @@ export class Ts3Connection { bytesReceivedTotal: event.bytes_received_total, bandwidthSentLastSecond: event.bandwidth_sent_last_second, bandwidthReceivedLastSecond: event.bandwidth_received_last_second, + bandwidthSentLastMinute: event.bandwidth_sent_last_minute ?? 0, + bandwidthReceivedLastMinute: event.bandwidth_received_last_minute ?? 0, + filetransferBandwidthSent: event.filetransfer_bandwidth_sent ?? 0, + filetransferBandwidthReceived: event.filetransfer_bandwidth_received ?? 0, + filetransferBytesSent: event.filetransfer_bytes_sent ?? 0, + filetransferBytesReceived: event.filetransfer_bytes_received ?? 0, }); } else if (event.type === "banList") { this.emit({ @@ -497,7 +538,9 @@ export class Ts3Connection { } async switchChannel(channelId: number): Promise { - this.child?.stdin.write(`switch ${channelId}\n`); + const id = Number(channelId); + if (!Number.isFinite(id)) return; + this.child?.stdin.write(`switch ${id}\n`); } async getClientConnectionInfo(clientId: number): Promise { diff --git a/web/src/App.css b/web/src/App.css index ab37fad..330bee3 100644 --- a/web/src/App.css +++ b/web/src/App.css @@ -1178,6 +1178,23 @@ color: var(--text-muted); } +/* GreenTeaSpeak / TeaSpeak license badge colors (ids 0โ€“3) */ +.ts-license-label.ts-license-0 { + color: #9a9aa3; +} + +.ts-license-label.ts-license-1 { + color: #8fbf7a; +} + +.ts-license-label.ts-license-2 { + color: #d4b45a; +} + +.ts-license-label.ts-license-3 { + color: #6eb0e0; +} + .ts-info-connection-link { margin-top: 0.5rem; background: none; @@ -1197,6 +1214,10 @@ width: 380px; } +.ts-connection-info-dialog.ts-server-conn-info { + width: min(520px, 94vw); +} + .ts-connection-info-loading { padding: 1rem; text-align: center; @@ -1214,6 +1235,32 @@ color: var(--text-muted); } +.ts-server-conn-table { + width: 100%; + margin-top: 0.85rem; + border-collapse: collapse; + font-size: 12px; +} + +.ts-server-conn-table th, +.ts-server-conn-table td { + padding: 0.3rem 0.4rem; + text-align: right; + border-bottom: 1px solid var(--border); +} + +.ts-server-conn-table th:first-child, +.ts-server-conn-table td:first-child { + text-align: left; + color: var(--text-muted); +} + +.ts-server-conn-table th { + font-style: italic; + font-weight: 600; + color: var(--text-muted); +} + .ts-row-selected { background: var(--row-hover); outline: 1px solid var(--border); @@ -1259,9 +1306,118 @@ background: var(--row-hover); } +/* Channel spacers ([cspacer], [*spacer01], โ€ฆ) โ€” GreenTeaSpeak / TS parity */ +.ts-channel-row.ts-spacer { + position: relative; + justify-content: center; + min-height: 19px; + color: var(--text); + cursor: pointer; +} + +.ts-channel-row.ts-spacer:hover { + background: var(--row-hover); +} + +.ts-channel-row.ts-spacer .ts-spacer-label { + position: absolute; + left: 0.35rem; + right: 0.35rem; + overflow: hidden; + white-space: nowrap; + text-align: center; + pointer-events: none; +} + +.ts-channel-row.ts-spacer-align-left .ts-spacer-label { + text-align: left; +} + +.ts-channel-row.ts-spacer-align-right .ts-spacer-label { + text-align: right; +} + +.ts-channel-row.ts-spacer-align-center .ts-spacer-label, +.ts-channel-row.ts-spacer-align-repetitive .ts-spacer-label { + text-align: center; +} + +.ts-channel-row.ts-spacer-align-repetitive .ts-spacer-label { + text-overflow: clip; +} + +.ts-channel-row.ts-spacer-line .ts-spacer-line-rule { + position: absolute; + left: 0.5rem; + right: 0.5rem; + top: 50%; + height: 0; + border-top: 1px solid currentColor; + opacity: 0.7; + overflow: hidden; + pointer-events: none; +} + +.ts-channel-row.ts-spacer-boxart .ts-spacer-label { + font-family: Consolas, "Courier New", monospace; + letter-spacing: 0.02em; +} + +.ts-tree-expander { + display: grid; + place-items: center; + width: 12px; + height: 16px; + flex: 0 0 12px; + padding: 0; + border: 0; + background: transparent; + cursor: pointer; +} + +.ts-tree-expander span { + width: 0; + height: 0; + border-left: 3px solid transparent; + border-right: 3px solid transparent; + border-top: 5px solid #c8c8c8; +} + +.ts-tree-expander-collapsed span { + border-top: 3px solid transparent; + border-bottom: 3px solid transparent; + border-left: 5px solid #c8c8c8; + border-right: 0; +} + +.ts-tree-expander-empty { + visibility: hidden; + cursor: default; +} + +.ts-client-status-leading { + display: inline-flex; + align-items: center; + gap: 0.1rem; + flex-shrink: 0; +} + +.ts-client-status-leading:empty { + display: none; +} + +.ts-tree-label { + overflow: hidden; + text-overflow: ellipsis; +} + +.ts-tree-list-root { + padding-left: 0.15rem; +} + .ts-client-row { color: var(--client-text); - padding-left: 0.65rem; + padding-left: 0; } .ts-client-row.ts-self { @@ -1278,9 +1434,50 @@ } .ts-client-row.ts-talking { - outline: 1px solid #4caf50; + outline: 1px solid color-mix(in srgb, #4caf50 55%, transparent); border-radius: 2px; - background: color-mix(in srgb, #4caf50 15%, transparent); + background: color-mix(in srgb, #4caf50 10%, transparent); +} + +/* Talk lamps (GTS2-style status orbs left of the nickname) */ +.ts-talk-lamp { + display: inline-flex; + align-items: center; + justify-content: center; + width: 14px; + height: 14px; + flex-shrink: 0; + border-radius: 50%; + box-sizing: border-box; +} + +.ts-talk-lamp-idle { + background: + radial-gradient(circle at 32% 28%, #9fd0ff 0%, #3a7ec4 45%, #1a4a7a 100%); + box-shadow: + inset 0 1px 1px rgba(255, 255, 255, 0.55), + inset 0 -1px 2px rgba(0, 0, 0, 0.35), + 0 0 0 1px rgba(0, 0, 0, 0.25); +} + +.ts-talk-lamp-talking { + background: + radial-gradient(circle at 32% 28%, #c8f59a 0%, #4caf50 42%, #1e7a28 100%); + box-shadow: + inset 0 1px 1px rgba(255, 255, 255, 0.6), + inset 0 -1px 2px rgba(0, 0, 0, 0.3), + 0 0 4px rgba(76, 175, 80, 0.55), + 0 0 0 1px rgba(0, 0, 0, 0.2); +} + +.ts-talk-lamp-muted { + border-radius: 0; + background: transparent; + box-shadow: none; +} + +.ts-talk-lamp-muted svg { + display: block; } .ts-client-icons { @@ -2416,6 +2613,10 @@ box-shadow: inset 0 0 0 1px #7fb0e8; } +.ts-design-theme-swatch-greenteaspeak { + background: linear-gradient(135deg, #1f2329 40%, #6fbf5c 40%, #386896 70%, #c8b882 70%); +} + .ts-design-theme-card-name { font-weight: 600; font-size: 13px; diff --git a/web/src/App.tsx b/web/src/App.tsx index f15f6c0..86b6322 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -42,6 +42,20 @@ import { type SoundEventId, } from "./sounds"; import { parseSoundpack } from "./soundpack"; +import { + GREENTEASPEAK_THEME_ID, + GreenteaSpeakChrome, + isGreenteaSpeakTheme, +} from "./themes/greenteaspeak"; +import { parseChannelName, spacerDisplayName } from "./lib/spacer"; +import { + applyParkedGatewayEvent, + emptyParkedState, + sessionLabel, + type ParkedSessionState, + type SessionRecord, + type SessionTabInfo, +} from "./connectionSessions"; // In dev, the gateway runs standalone on its own port. In production it's // normally served from the same origin/port as the web app (single @@ -56,7 +70,7 @@ import { parseSoundpack } from "./soundpack"; // gateway/src/index.ts), so that path always gets appended here - a // VITE_GATEWAY_URL override only needs to name the host, not the path. const GATEWAY_URL = import.meta.env.DEV - ? "ws://localhost:8080" + ? "ws://localhost:8080/ws" : import.meta.env.VITE_GATEWAY_URL ? `${import.meta.env.VITE_GATEWAY_URL.replace(/\/$/, "")}/ws` : `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.host}/ws`; @@ -77,6 +91,15 @@ const GATEWAY_URL = import.meta.env.DEV const LAST_HOST_KEY = "webspeak3:last-host"; const LAST_NICKNAME_KEY = "webspeak3:last-nickname"; +const LAST_PRIVILEGE_KEY = "webspeak3:last-privilege-key"; +const LAST_SERVER_TYPE_KEY = "webspeak3:last-server-type"; + +type ServerType = "teamspeak" | "teaspeak" | "auto"; + +function loadServerType(): ServerType { + const raw = localStorage.getItem(LAST_SERVER_TYPE_KEY); + return raw === "teamspeak" || raw === "teaspeak" || raw === "auto" ? raw : "auto"; +} /** Identity persisted across sessions so the server sees the same client UID * each time, instead of a fresh one being generated per connection. */ const IDENTITY_KEY = "webspeak3:identity"; @@ -139,18 +162,19 @@ const ECHO_CANCELLATION_KEY = "webspeak3:echo-cancellation"; const AUTO_GAIN_CONTROL_KEY = "webspeak3:auto-gain-control"; const VAD_HANGOVER_KEY = "webspeak3:vad-hangover"; const DESIGN_THEME_KEY = "webspeak3:design-theme"; -// The user's actual pick - "standard" | "nova" | "custom:". DESIGN_THEME_KEY above -// keeps tracking just the resolved structural base, since a couple of early call sites -// (e.g. the host-field default below) need that cheaply, before customThemes is loaded. +// The user's actual pick - "standard" | "nova" | "greenteaspeak" | "custom:". +// DESIGN_THEME_KEY above keeps tracking just the resolved structural base, since a +// couple of early call sites (e.g. the host-field default below) need that cheaply, +// before customThemes is loaded. const DESIGN_SELECTION_KEY = "webspeak3:design-selection"; const CUSTOM_THEMES_KEY = "webspeak3:custom-themes"; -type DesignTheme = "standard" | "nova"; +type DesignTheme = "standard" | "nova" | "greenteaspeak"; /** A user-authored theme package: a name, which built-in layout it behaves like - * (Standard's plain chrome vs Nova's collapsed menu/splash behavior), and raw CSS - * that gets injected while it's active - free-form, so it can restyle or even - * reflow the existing markup (e.g. via flex `order`, `display:none`, overlays). */ + * (Standard's plain chrome vs Nova's collapsed menu/splash vs GreenTeaSpeak shell), + * and raw CSS that gets injected while it's active - free-form, so it can restyle + * or even reflow the existing markup. */ type CustomTheme = { id: string; name: string; @@ -158,8 +182,33 @@ type CustomTheme = { css: string; }; +function isDesignTheme(value: string): value is DesignTheme { + return value === "standard" || value === "nova" || value === "greenteaspeak"; +} + function loadDesignTheme(): DesignTheme { - return localStorage.getItem(DESIGN_THEME_KEY) === "nova" ? "nova" : "standard"; + const raw = localStorage.getItem(DESIGN_THEME_KEY); + if (raw && isDesignTheme(raw)) return raw; + return "standard"; +} + +function resolveDesignThemeBase(selection: string, customThemes: CustomTheme[]): DesignTheme { + if (selection.startsWith("custom:")) { + return customThemes.find((th) => `custom:${th.id}` === selection)?.baseTheme ?? "standard"; + } + return isDesignTheme(selection) ? selection : "standard"; +} + +function designThemeClassName(theme: DesignTheme): string { + if (theme === "nova") return " ts-design-nova"; + if (isGreenteaSpeakTheme(theme)) return " ts-design-greenteaspeak"; + return ""; +} + +function designThemeLabel(theme: DesignTheme, t: (key: string) => string): string { + if (theme === "nova") return t("design.theme.nova"); + if (theme === "greenteaspeak") return t("design.theme.greenteaspeak"); + return t("design.theme.standard"); } function loadCustomThemes(): CustomTheme[] { @@ -173,7 +222,7 @@ function loadCustomThemes(): CustomTheme[] { v && typeof v.id === "string" && typeof v.name === "string" && - (v.baseTheme === "standard" || v.baseTheme === "nova") && + isDesignTheme(v.baseTheme) && typeof v.css === "string" ); } catch { @@ -375,7 +424,10 @@ interface ChannelInfo { hasPassword: boolean; } -type SelectedItem = { type: "server" } | { type: "channel"; id: number }; +type SelectedItem = + | { type: "server" } + | { type: "channel"; id: number } + | { type: "client"; id: number }; interface ClientInfo { id: number; @@ -447,10 +499,17 @@ interface ServerConnectionInfoData { bytesReceivedTotal: number; bandwidthSentLastSecond: number; bandwidthReceivedLastSecond: number; + bandwidthSentLastMinute: number; + bandwidthReceivedLastMinute: number; + filetransferBandwidthSent: number; + filetransferBandwidthReceived: number; + filetransferBytesSent: number; + filetransferBytesReceived: number; } function formatBytes(bytes: number): string { - if (bytes < 1024) return `${bytes} B`; + if (!Number.isFinite(bytes) || bytes < 0) return "0 B"; + if (bytes < 1024) return `${Math.round(bytes)} B`; const units = ["KB", "MB", "GB", "TB"]; let value = bytes / 1024; let unitIndex = 0; @@ -461,6 +520,18 @@ function formatBytes(bytes: number): string { return `${value.toFixed(1)} ${units[unitIndex]}`; } +/** Compact counts like GreenTeaSpeak (`772.92 k`) โ€” avoids DE locale `772.920`. */ +function formatCount(value: number): string { + if (!Number.isFinite(value) || value < 0) return "0"; + if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(2)} M`; + if (value >= 1_000) return `${(value / 1_000).toFixed(2)} k`; + return value.toFixed(value % 1 === 0 ? 0 : 2); +} + +function formatRate(bytesPerSec: number): string { + return `${formatBytes(bytesPerSec)}/s`; +} + /** Turns a base64-encoded file (as delivered by the "fileDownloadData" event) * into an actual browser download, without ever round-tripping through the * gateway's HTTP surface - it's all-in-memory via a Blob + object URL. */ @@ -509,23 +580,64 @@ function ChannelIcon() { ); } -function ClientIcon() { - return ( - - ); +/** GTS2-style talk lamp: blue idle / green talking / muted mic. */ +function TalkLamp({ + talking, + inputMuted, + inputHardwareEnabled, +}: { + talking: boolean; + inputMuted: boolean; + inputHardwareEnabled: boolean; +}) { + const t = useT(); + const muted = inputMuted || !inputHardwareEnabled; + + if (muted) { + return ( + + ); + } + + if (talking) { + return ( +