Merge pull request #4 from GreenTeaSpeak/main

Add TeaSpeak/GTS support and multi-join functionality
This commit is contained in:
Möpchi authored and GitHub committed 2026-09-06 01:39:07 +02:00
commit 9206b12e25
22 files changed
+3384 -240

No files matched your search

+2 -1
View File
@@ -1,3 +1,4 @@
[submodule "tsclientlib"]
path = tsclientlib
url = https://github.com/Moepchi/tsclientlib.git
url = https://github.com/GreenTeaSpeak/tsclientlib.git
branch = webspeak3
+10 -5
View File
@@ -1,4 +1,4 @@
<p align="center">
<p align="center">
<img src="web/public/logo.png" width="140" alt="WebSpeak3 logo">
</p>
@@ -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**
+1
View File
@@ -2639,6 +2639,7 @@ dependencies = [
"base64",
"clap",
"futures",
"num-traits",
"serde",
"serde_json",
"time",
+1
View File
@@ -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"
+265 -26
View File
@@ -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,10 +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,
TsError,
data, ChannelGroupId, ChannelId, ClientDbId, ClientId, ClientType, CodecEncryptionMode,
Connection, DisconnectOptions, HostBannerMode, HostMessageMode, Identity, InMessage,
LicenseType, MaxClients, MessageHandle, MessageTarget, Permission, Reason, ServerGroupId,
ServerType, StreamItem, TextMessageTargetMode, TsError,
};
use tsproto_packets::packets::{AudioData, CodecType, Direction, Flags, OutAudio, OutCommand, PacketType};
@@ -59,6 +60,13 @@ struct Args {
/// reported back the same way - when omitted or unparseable.
#[arg(long)]
identity: Option<String>,
/// 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<String>,
}
#[derive(Serialize)]
@@ -185,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<ChannelInfo>, clients: Vec<ClientInfo> },
Channels {
channels: Vec<ChannelInfo>,
clients: Vec<ClientInfo>,
/// 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")]
@@ -247,6 +268,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,
@@ -255,6 +277,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
@@ -544,10 +572,14 @@ fn snapshot(con: &data::Connection) -> Event {
},
has_password: ch.has_password.unwrap_or(false),
})
.collect();
.collect::<Vec<_>>();
// Bookkeeping includes ServerQuery clients (`ClientType::Query`); hide them
// from the channel tree / client lists, and from the online-count fallback
// below too, so the number shown never counts a client the list doesn't.
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
@@ -575,8 +607,46 @@ fn snapshot(con: &data::Connection) -> Event {
has_talk_power,
}
})
.collect();
Event::Channels { channels, clients }
.collect::<Vec<_>>();
// Prefer server-reported counters (GTS/TS `virtualserver_*` via notifyserverupdated)
// but never under-report vs. the visible (non-Query) client set (stale
// optional_data after joins would otherwise freeze the InfoPanel left number).
// `virtualserver_clientsonline` usually includes ServerQuery; subtract the
// Query clients we filtered from the list so the headline matches the tree.
let opt = con.server.optional_data.as_ref();
let visible_channels = channels.len() as u64;
let visible_clients_count = clients.len() as u16;
let query_count = (con.clients.len() as u16).saturating_sub(visible_clients_count);
let server_clients_online = opt
.map(|d| {
let without_query = d.client_count.saturating_sub(query_count);
without_query.max(visible_clients_count)
})
.unwrap_or(visible_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]
@@ -587,11 +657,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}")
@@ -599,7 +732,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}"),
@@ -623,6 +756,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);
}
@@ -661,7 +803,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,
@@ -669,6 +812,7 @@ async fn run(args: Args) -> Result<()> {
server_max_clients,
server_version,
server_license,
server_license_id,
server_banner_url,
identity: identity_str,
});
@@ -676,6 +820,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.
{
@@ -768,19 +916,37 @@ async fn run(args: Args) -> Result<()> {
// eventual emit can be routed back to it.
let mut pending_perm_list: Option<(String, u64, Option<u64>)> = None;
let mut pending_perm_list_raw: Option<Vec<(u32, i32, bool, bool)>> = 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<tokio::time::Instant> = None;
enum LoopOutcome {
StdinLine(std::io::Result<Option<String>>),
ConEvent(Option<Result<StreamItem, tsclientlib::Error>>),
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);
@@ -814,23 +980,50 @@ async fn run(args: Args) -> Result<()> {
.ok()
.and_then(|bytes| String::from_utf8(bytes).ok())
});
let part = {
let state = con.get_state()?;
let own = &state.clients[&state.own_client];
let mv = own.client_move(ChannelId(id));
match &password {
Some(pwd) => mv.set_password(pwd),
None => mv,
// 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) => {
let mut part = own.client_move(ChannelId(id));
match &password {
Some(pwd) => {
part = part.set_password(pwd);
}
None => {
// Always include cpw= (empty) like the GTS desktop client -
// some TeaSpeak builds are picky about an omitted key.
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());
pending_switch_channel.insert(handle, id);
if let Some(part) = part {
match part.send_with_result(&mut con) {
Ok(handle) => {
pending_messages.insert(handle, "Channel switch".into());
pending_switch_channel.insert(handle, id);
}
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: {id_arg}") }),
}
} else if let Some(message) = l.strip_prefix("chat ") {
@@ -1102,6 +1295,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() }),
}
@@ -1868,6 +2064,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 {
@@ -1884,7 +2081,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()?
@@ -1912,6 +2108,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);
}
}
@@ -1945,17 +2157,31 @@ async fn run(args: Args) -> Result<()> {
}
}
if pending_server_conninfo {
if let Some(data) = &con.get_state()?.server.connection_data {
let state = con.get_state()?;
// GreenTeaSpeak reports packet loss already as a percent; classic
// TeamSpeak3/TeaSpeak report it as a fraction (0-1). A value's magnitude
// alone can't disambiguate a healthy GTS server (e.g. 0.5%) from a bad
// TS3 one (e.g. 0.5 = 50%), so branch on the actual server type instead.
let is_gts = is_greenteaspeak_server_version(&state.server.version);
if let Some(data) = &state.server.connection_data {
let loss = data.packetloss_total;
let packet_loss_percent = if is_gts { loss } else { loss * 100.0 };
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;
}
@@ -2357,6 +2583,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];
+24
View File
@@ -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)
+2 -2
View File
@@ -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"
+60 -4
View File
@@ -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<ServerType>(["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<string, string> = {
".html": "text/html",
@@ -24,9 +43,23 @@ const MIME_TYPES: Record<string, string> = {
".woff2": "font/woff2",
};
const DEV_HINT = `<!doctype html><html><body style="font:14px system-ui;padding:2rem;max-width:40rem">
<h1>WebSpeak3 gateway</h1>
<p>WebSocket: <code>/ws</code></p>
<p>Static UI is disabled (<code>WEB_STATIC=0</code>) or <code>web/dist</code> is missing.</p>
<p>For local development open the Vite app at <a href="http://localhost:5173/">http://localhost:5173/</a>
(run <code>npm run dev</code> in <code>web/</code>). Rebuild with <code>npm run build</code> in <code>web/</code>
to serve the UI from this port again.</p>
</body></html>`;
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, msg.channelPassword);
const channelId = Number(msg.channelId);
if (Number.isFinite(channelId)) {
await connection?.switchChannel(channelId, msg.channelPassword);
}
break;
}
case "sendChatMessage": {
+64 -5
View File
@@ -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 }
@@ -155,6 +156,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[] }
@@ -177,6 +184,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;
@@ -186,6 +195,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));
@@ -217,6 +230,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) => {
@@ -258,10 +273,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 }
@@ -295,6 +319,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[] }
| {
@@ -361,6 +391,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,
});
@@ -394,6 +425,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({
@@ -428,6 +463,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({
@@ -501,10 +542,12 @@ export class Ts3Connection {
}
async switchChannel(channelId: number, channelPassword?: string): Promise<void> {
const id = Number(channelId);
if (!Number.isFinite(id)) return;
// The password travels base64-encoded on this line-based stdin protocol
// so it can safely contain spaces or other characters.
const passwordArg = channelPassword ? ` ${Buffer.from(channelPassword, "utf8").toString("base64")}` : "";
this.child?.stdin.write(`switch ${channelId}${passwordArg}\n`);
this.child?.stdin.write(`switch ${id}${passwordArg}\n`);
}
async getClientConnectionInfo(clientId: number): Promise<void> {
@@ -753,9 +796,25 @@ export class Ts3Connection {
async disconnect(message = ""): Promise<void> {
if (this.child && !this.child.killed) {
const child = this.child;
const sanitized = message.replace(/[\r\n]+/g, " ").trim();
this.child.stdin.write(`disconnect ${sanitized}\n`);
this.child.stdin.end();
child.stdin.write(`disconnect ${sanitized}\n`);
child.stdin.end();
// Wait for the connector process to actually exit before returning, so a
// caller that immediately reconnects (index.ts's "connect" handler) never
// spawns a replacement while this one is still shutting down - two
// connector processes would otherwise briefly hold the same audio/socket
// resources. Fall back to a hard kill if it doesn't exit on its own.
await new Promise<void>((resolve) => {
const timeout = setTimeout(() => {
child.kill();
resolve();
}, 3000);
child.once("exit", () => {
clearTimeout(timeout);
resolve();
});
});
}
this.listeners.clear();
}
+203 -3
View File
@@ -1659,6 +1659,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;
@@ -1678,6 +1695,10 @@
width: 380px;
}
.ts-connection-info-dialog.ts-server-conn-info {
width: min(520px, 94vw);
}
.ts-connection-info-loading {
padding: 1rem;
text-align: center;
@@ -1695,6 +1716,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);
@@ -1740,9 +1787,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 {
@@ -1759,9 +1915,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 {
@@ -2902,6 +3099,9 @@
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-swatch-pulse {
background: linear-gradient(135deg, oklch(0.22 0.02 285) 0%, oklch(0.15 0.03 290) 100%);
box-shadow: inset 0 0 0 1px #9d8cf0;
+1005 -192
View File
File diff suppressed because it is too large. Load diff
+331
View File
@@ -0,0 +1,331 @@
/**
* Multi-join session bookkeeping. The active tab keeps its UI in React state
* (App.tsx); inactive tabs park a snapshot here and keep their WebSocket alive.
* Audio is intentionally active-tab-only (see README / known limits).
*/
export type ConnectionSessionId = string;
export type SelectedItem =
| { type: "server" }
| { type: "channel"; id: number }
| { type: "client"; id: number };
export type ChatEntry = { from: string; message: string; isLog?: boolean };
export type PmMessage = { fromSelf: boolean; message: string };
export type PmThread = {
partnerId: number;
partnerName: string;
messages: PmMessage[];
unread: boolean;
};
export type ActiveChatTab = "channel" | "server" | number;
export type PokeNotice = { id: number; from: string; message: string };
export type LogEntry = { text: string; kind: "info" | "error" };
export type ChannelInfo = {
id: number;
parent: number;
order: number;
name: string;
topic: string;
codec: string;
maxClients: number | null;
hasPassword: boolean;
};
export type ClientInfo = {
id: number;
channel: number;
name: string;
inputMuted: boolean;
outputMuted: boolean;
inputHardwareEnabled: boolean;
away: boolean;
awayMessage: string;
isChannelCommander: boolean;
country: string;
uid: string;
databaseId: number;
channelGroup: number;
serverGroups: number[];
hasTalkPower: boolean;
};
export type WhisperLogEntry = {
id: number;
timestamp: number;
description: string;
};
/** Snapshot of per-connection UI state for a parked (inactive) tab. */
export type ParkedSessionState = {
host: string;
nickname: string;
connected: boolean;
connecting: boolean;
connectError: string | null;
channels: ChannelInfo[];
clients: ClientInfo[];
ownClientId: number | null;
serverName: string;
serverMaxClients: number;
serverClientsOnline: number;
serverChannelsOnline: number;
serverVersion: string;
serverLicense: string;
serverLicenseId: number;
serverBannerUrl: string;
serverWelcomeMessage: string;
selected: SelectedItem | null;
chat: ChatEntry[];
serverChat: ChatEntry[];
pmThreads: Record<number, PmThread>;
pokes: PokeNotice[];
chatTab: ActiveChatTab;
talkers: number[];
whisperChannelIds: number[];
whisperClientIds: number[];
whisperLog: WhisperLogEntry[];
log: LogEntry[];
hasConnected: boolean;
previousClients: ClientInfo[] | null;
/** Whether the mic was on for this tab when it was parked, so switching back restores it. */
micWasOn: boolean;
};
export type SessionTabInfo = {
id: ConnectionSessionId;
label: string;
connected: boolean;
connecting: boolean;
};
export type SessionSocket = WebSocket | { close: () => void; readyState: number; send: (data: string) => void };
export type SessionRecord = {
id: ConnectionSessionId;
socket: SessionSocket | null;
/** null while this session is the active React UI. */
parked: ParkedSessionState | null;
};
export function emptyParkedState(partial?: Partial<ParkedSessionState>): ParkedSessionState {
return {
host: "",
nickname: "",
connected: false,
connecting: false,
connectError: null,
channels: [],
clients: [],
ownClientId: null,
serverName: "",
serverMaxClients: 0,
serverClientsOnline: 0,
serverChannelsOnline: 0,
serverVersion: "",
serverLicense: "",
serverLicenseId: 0,
serverBannerUrl: "",
serverWelcomeMessage: "",
selected: null,
chat: [],
serverChat: [],
pmThreads: {},
pokes: [],
chatTab: "channel",
talkers: [],
whisperChannelIds: [],
whisperClientIds: [],
whisperLog: [],
log: [],
hasConnected: false,
previousClients: null,
micWasOn: false,
...partial,
};
}
export function sessionLabel(state: Pick<ParkedSessionState, "serverName" | "host">): string {
const name = state.serverName.trim() || state.host.trim();
return name || "…";
}
/** Apply a gateway event to a parked session. Returns whether the tab label may have changed. */
export function applyParkedGatewayEvent(
state: ParkedSessionState,
data: { type: string; [key: string]: unknown },
opts: { connectNickname: string; chatTab: ActiveChatTab }
): { state: ParkedSessionState; labelChanged: boolean } {
let labelChanged = false;
switch (data.type) {
case "connected": {
const serverName = String(data.serverName ?? "");
labelChanged = serverName !== state.serverName;
return {
labelChanged,
state: {
...state,
connecting: false,
connectError: null,
connected: true,
hasConnected: true,
serverName,
serverMaxClients: Number(data.serverMaxClients) || 0,
serverClientsOnline: 0,
serverChannelsOnline: 0,
serverVersion: String(data.serverVersion ?? ""),
serverLicense: String(data.serverLicense ?? ""),
serverLicenseId: typeof data.serverLicenseId === "number" ? data.serverLicenseId : 0,
serverBannerUrl: String(data.serverBannerUrl ?? ""),
serverWelcomeMessage: String(data.welcomeMessage ?? ""),
selected: { type: "server" },
serverChat: [
...state.serverChat,
{ from: "Server", message: String(data.welcomeMessage ?? "") },
],
previousClients: null,
},
};
}
case "channels": {
const newClients = (data.clients as ClientInfo[]) ?? [];
const ownClientId =
typeof data.ownClientId === "number" && data.ownClientId > 0
? data.ownClientId
: state.ownClientId;
return {
labelChanged: false,
state: {
...state,
channels: (data.channels as ChannelInfo[]) ?? state.channels,
clients: newClients,
ownClientId,
serverMaxClients:
typeof data.serverMaxClients === "number" && data.serverMaxClients > 0
? data.serverMaxClients
: state.serverMaxClients,
serverClientsOnline:
typeof data.serverClientsOnline === "number" && data.serverClientsOnline >= 0
? data.serverClientsOnline
: state.serverClientsOnline,
serverChannelsOnline:
typeof data.serverChannelsOnline === "number" && data.serverChannelsOnline >= 0
? data.serverChannelsOnline
: state.serverChannelsOnline,
previousClients: newClients,
},
};
}
case "chatMessage":
return {
labelChanged: false,
state: {
...state,
chat: [...state.chat, { from: String(data.from), message: String(data.message) }],
},
};
case "serverMessage":
return {
labelChanged: false,
state: {
...state,
serverChat: [
...state.serverChat,
{ from: String(data.from), message: String(data.message) },
],
},
};
case "privateMessage": {
const partnerId = Number(data.partnerId);
const existing = state.pmThreads[partnerId];
const thread: PmThread = existing ?? {
partnerId,
partnerName: String(data.partnerName),
messages: [],
unread: false,
};
return {
labelChanged: false,
state: {
...state,
pmThreads: {
...state.pmThreads,
[partnerId]: {
...thread,
partnerName: String(data.partnerName),
messages: [
...thread.messages,
{ fromSelf: Boolean(data.fromSelf), message: String(data.message) },
],
unread:
thread.unread || (!data.fromSelf && opts.chatTab !== partnerId),
},
},
},
};
}
case "talkers":
return {
labelChanged: false,
state: {
...state,
talkers: Array.isArray(data.clients) ? (data.clients as number[]) : [],
},
};
case "poke": {
const id = Date.now() + Math.floor(Math.random() * 1000);
return {
labelChanged: false,
state: {
...state,
pokes: [
...state.pokes,
{ id, from: String(data.from), message: String(data.message ?? "") },
],
},
};
}
case "disconnected":
return {
labelChanged: true,
state: {
...emptyParkedState({
host: state.host,
nickname: state.nickname,
}),
connecting: false,
connected: false,
hasConnected: false,
log: [
...state.log,
{ text: `Disconnected: ${String(data.reason ?? "")}`, kind: "info" },
],
},
};
case "error":
if (state.hasConnected) {
return {
labelChanged: false,
state: {
...state,
log: [...state.log, { text: String(data.message), kind: "error" }],
},
};
}
return {
labelChanged: false,
state: {
...state,
connecting: false,
connectError: String(data.message),
},
};
case "audioOut":
// Background tabs never play audio (active-tab-only shortcut).
return { state, labelChanged: false };
default:
return { state, labelChanged: false };
}
}
+10 -1
View File
@@ -228,6 +228,7 @@ export class DemoSocket {
serverMaxClients: 32,
serverVersion: "3.13.7 [Build: demo]",
serverLicense: "Demo License",
serverLicenseId: 2,
serverBannerUrl: null,
welcomeMessage: "This is a simulated demo - no real TeamSpeak server is involved. Connect with any name/address you like.",
});
@@ -620,6 +621,14 @@ export class DemoSocket {
serverGroups: [...this.selfServerGroups],
hasTalkPower: true,
};
this.emit({ type: "channels", channels: DEMO_CHANNELS, clients: [self, ...DEMO_NPCS] });
this.emit({
type: "channels",
channels: DEMO_CHANNELS,
clients: [self, ...DEMO_NPCS],
ownClientId: SELF_ID,
serverMaxClients: 32,
serverClientsOnline: 1 + DEMO_NPCS.length,
serverChannelsOnline: DEMO_CHANNELS.length,
});
}
}
+56
View File
@@ -77,6 +77,10 @@ const translations: Record<Lang, Record<string, string>> = {
"connect.channelPassword": "Channel Passwort:",
"connect.playbackProfile": "Wiedergabeprofil:",
"connect.onetimeGrant": "Einmalige Berechtigung:",
"connect.serverType": "Server-Typ:",
"connect.serverType.auto": "Auto",
"connect.serverType.teamspeak": "TeamSpeak",
"connect.serverType.teaspeak": "TeaSpeak",
"connect.hotkeyProfile": "Hotkeyprofil:",
"connect.soundPack": "Sound Pack:",
"connect.more": "Mehr",
@@ -157,6 +161,18 @@ const translations: Record<Lang, Record<string, string>> = {
"connectionInfo.unavailable": "Keine Antwort vom Server (fehlende Berechtigung?).",
"connectionInfo.ping": "Ping:",
"connectionInfo.connectedSince": "Verbunden seit:",
"connectionInfo.uptime": "Uptime:",
"connectionInfo.name": "Name:",
"connectionInfo.avgPing": "Mittlerer Ping:",
"connectionInfo.avgPacketLoss": "Mittlerer Paketverlust:",
"connectionInfo.incoming": "Eingehend",
"connectionInfo.outgoing": "Ausgehend",
"connectionInfo.packetsTransferred": "Übertragene Pakete",
"connectionInfo.bytesTransferred": "Übertragene Bytes",
"connectionInfo.bandwidthLastSecond": "Bandbreite letzte Sekunde",
"connectionInfo.bandwidthLastMinute": "Bandbreite letzte Minute",
"connectionInfo.ftBandwidth": "Dateitransfer Bandbreite",
"connectionInfo.ftBytes": "Dateitransfer übertragene Bytes",
"connectionInfo.ip": "IP-Adresse:",
"connectionInfo.packetLoss": "Paketverlust:",
"connectionInfo.packetsSent": "Pakete gesendet:",
@@ -234,6 +250,8 @@ const translations: Record<Lang, Record<string, string>> = {
"design.theme.standard.desc": "Das originale WebSpeak3-Design.",
"design.theme.nova": "Nova",
"design.theme.nova.desc": "Moderneres, dunkles Design mit abgerundeten Elementen.",
"design.theme.greenteaspeak": "GreenTeaSpeak",
"design.theme.greenteaspeak.desc": "Klassisches GreenTeaSpeak-Client-Layout mit dunklen Panels und goldener Menüleiste.",
"design.theme.pulse": "Pulse",
"design.theme.pulse.desc": "Karten-Layout mit Breadcrumb-Leiste und farbigem Akzent.",
"design.status.connected": "Verbunden",
@@ -310,19 +328,28 @@ const translations: Record<Lang, Record<string, string>> = {
"info.currentChannels": "Aktuelle Channel:",
"info.topic": "Topic:",
"info.audioCodec": "Audio Codec:",
"info.spacer": "Spacer:",
"info.rawName": "Rohname:",
"info.passwordProtected": "Passwort geschützt:",
"info.clients": "Clients:",
"info.country": "Land:",
"info.muted": "Mikrofon stumm:",
"info.outputMuted": "Lautsprecher stumm:",
"info.serverGroups": "Servergruppen:",
"info.yes": "Ja",
"info.no": "Nein",
"tree.notConnected": "Nicht verbunden",
"tree.clickToSelect": "Klicken zum Auswählen, Doppelklick zum Beitreten",
"tree.clickToJoin": "Doppelklick zum Beitreten",
"tree.joinNotConnected": "Nicht verbunden — Channel-Wechsel nicht möglich",
"tree.passwordProtected": "Passwortgeschützt",
"tree.privateChatWith": "Privater Chat mit",
"tree.poke": "Anstupsen",
"tree.channelCommander": "Channel Commander",
"tree.away": "Abwesend",
"tree.micMuted": "Mikrofon stummgeschaltet",
"tree.talking": "Spricht",
"tree.noTalkPower": "Keine Redeerlaubnis in diesem Channel",
"tree.soundMuted": "Ton stummgeschaltet (deafened)",
@@ -467,6 +494,7 @@ const translations: Record<Lang, Record<string, string>> = {
"permsEditor.searchPermission": "Recht suchen...",
"dialog.ok": "OK",
"channelContext.join": "Channel wechseln",
"channelContext.files": "Dateien...",
"fileBrowser.title": "Dateitransfers",
"fileBrowser.up": "Nach oben",
@@ -609,6 +637,10 @@ const translations: Record<Lang, Record<string, string>> = {
"connect.channelPassword": "Channel password:",
"connect.playbackProfile": "Playback profile:",
"connect.onetimeGrant": "One-time privilege key:",
"connect.serverType": "Server type:",
"connect.serverType.auto": "Auto",
"connect.serverType.teamspeak": "TeamSpeak",
"connect.serverType.teaspeak": "TeaSpeak",
"connect.hotkeyProfile": "Hotkey profile:",
"connect.soundPack": "Sound pack:",
"connect.more": "More",
@@ -689,6 +721,18 @@ const translations: Record<Lang, Record<string, string>> = {
"connectionInfo.unavailable": "No response from the server (missing permission?).",
"connectionInfo.ping": "Ping:",
"connectionInfo.connectedSince": "Connected since:",
"connectionInfo.uptime": "Uptime:",
"connectionInfo.name": "Name:",
"connectionInfo.avgPing": "Average ping:",
"connectionInfo.avgPacketLoss": "Average packet loss:",
"connectionInfo.incoming": "Incoming",
"connectionInfo.outgoing": "Outgoing",
"connectionInfo.packetsTransferred": "Packets transferred",
"connectionInfo.bytesTransferred": "Bytes transferred",
"connectionInfo.bandwidthLastSecond": "Bandwidth last second",
"connectionInfo.bandwidthLastMinute": "Bandwidth last minute",
"connectionInfo.ftBandwidth": "File transfer bandwidth",
"connectionInfo.ftBytes": "File transfer bytes",
"connectionInfo.ip": "IP address:",
"connectionInfo.packetLoss": "Packet loss:",
"connectionInfo.packetsSent": "Packets sent:",
@@ -766,6 +810,8 @@ const translations: Record<Lang, Record<string, string>> = {
"design.theme.standard.desc": "The original WebSpeak3 design.",
"design.theme.nova": "Nova",
"design.theme.nova.desc": "A more modern, dark design with rounded elements.",
"design.theme.greenteaspeak": "GreenTeaSpeak",
"design.theme.greenteaspeak.desc": "Classic GreenTeaSpeak client layout with dark panels and a gold menu bar.",
"design.theme.pulse": "Pulse",
"design.theme.pulse.desc": "Card-based layout with a breadcrumb bar and a color accent.",
"design.status.connected": "Connected",
@@ -842,19 +888,28 @@ const translations: Record<Lang, Record<string, string>> = {
"info.currentChannels": "Current channels:",
"info.topic": "Topic:",
"info.audioCodec": "Audio codec:",
"info.spacer": "Spacer:",
"info.rawName": "Raw name:",
"info.passwordProtected": "Password protected:",
"info.clients": "Clients:",
"info.country": "Country:",
"info.muted": "Microphone muted:",
"info.outputMuted": "Speakers muted:",
"info.serverGroups": "Server groups:",
"info.yes": "Yes",
"info.no": "No",
"tree.notConnected": "Not connected",
"tree.clickToSelect": "Click to select, double-click to join",
"tree.clickToJoin": "Double-click to join",
"tree.joinNotConnected": "Not connected — cannot switch channel",
"tree.passwordProtected": "Password protected",
"tree.privateChatWith": "Private chat with",
"tree.poke": "Poke",
"tree.channelCommander": "Channel commander",
"tree.away": "Away",
"tree.micMuted": "Microphone muted",
"tree.talking": "Talking",
"tree.noTalkPower": "No talk power in this channel",
"tree.soundMuted": "Sound muted (deafened)",
@@ -999,6 +1054,7 @@ const translations: Record<Lang, Record<string, string>> = {
"permsEditor.searchPermission": "Search permission...",
"dialog.ok": "OK",
"channelContext.join": "Switch to channel",
"channelContext.files": "Files...",
"fileBrowser.title": "File Transfers",
"fileBrowser.up": "Up",
+114
View File
@@ -0,0 +1,114 @@
/** TeamSpeak / TeaSpeak / GreenTeaSpeak channel spacer helpers.
*
* Mirrors GreenTeaSpeak `ChannelTreeBuilder.parseChannelName` / oldclient
* `ChannelNameParser`: only root channels, tag must contain "spacer", alignment
* prefix l/c/r/* (empty → left), unique id after "spacer" may be any string
* (e.g. `[*spacer01]`, `[cspacerabc]`).
*/
export type SpacerAlignment = "left" | "center" | "right" | "repetitive";
export type ParsedChannelName = {
/** Label shown in the tree (tag stripped for spacers). */
name: string;
alignment: SpacerAlignment | null;
};
/** Pure line fillers that look better as a CSS rule than raw `---` / `***`. */
const LINE_FILLER_RE = /^[\-\u2013\u2014\u2500\u2501\u2550=\*\.·_\s]+$/;
/** Corners / verticals of box-frame spacers (not pure horizontal fills). */
const BOX_FRAME_RE = /[╔╗╚╝╒╓╕╖╘╙╛╜┌┐└┘├┤┬┴┼║│╟╢╤╧╪╫╬╒╓╕╖╘╙╛╜]/;
export function parseChannelName(name: string, isRoot: boolean): ParsedChannelName {
if (!isRoot || name.length < 3 || name.charAt(0) !== "[") {
return { name, alignment: null };
}
const end = name.indexOf("]");
if (end === -1) return { name, alignment: null };
let options = name.substring(1, end);
const spacerIndex = options.indexOf("spacer");
if (spacerIndex === -1) return { name, alignment: null };
options = options.substring(0, spacerIndex);
if (options.length === 0) {
options = "l";
} else if (options.length > 1) {
options = options.charAt(0);
}
const alignmentByPrefix: Record<string, SpacerAlignment> = {
l: "left",
c: "center",
r: "right",
"*": "repetitive",
};
const alignment = alignmentByPrefix[options];
if (!alignment) return { name, alignment: null };
return {
name: name.substring(end + 1),
alignment,
};
}
/** Same as oldclient `ChannelName`: repeat filler until it fills the tree row. */
export function expandRepetitiveSpacerName(name: string): string {
if (!name.length) return name;
let expanded = name;
while (expanded.length < 8000) {
expanded += expanded;
}
return expanded;
}
export function isLineSpacerFiller(text: string): boolean {
const trimmed = text.trim();
return trimmed.length > 0 && LINE_FILLER_RE.test(trimmed);
}
export function hasBoxArtChars(text: string): boolean {
return BOX_FRAME_RE.test(text);
}
export function spacerDisplayName(rawName: string, isRoot: boolean): {
label: string;
alignment: SpacerAlignment | null;
isSpacer: boolean;
/** Repetitive `---` / `***` / `═══` → render as CSS line, not character soup. */
isLine: boolean;
/** Box-frame spacers (╔╗ / ═) need monospace for GTS look. */
isBoxArt: boolean;
} {
const parsed = parseChannelName(rawName, isRoot);
if (!parsed.alignment) {
return {
label: rawName,
alignment: null,
isSpacer: false,
isLine: false,
isBoxArt: false,
};
}
const isBoxArt = hasBoxArtChars(parsed.name);
const isLine =
!isBoxArt &&
isLineSpacerFiller(parsed.name) &&
(parsed.alignment === "repetitive" || parsed.alignment === "center");
let label = parsed.name;
if (parsed.alignment === "repetitive" && !isLine) {
label = expandRepetitiveSpacerName(parsed.name);
}
return {
label,
alignment: parsed.alignment,
isSpacer: true,
isLine,
isBoxArt,
};
}
+36
View File
@@ -63,6 +63,10 @@ export const zhCN: Record<string, string> = {
"connect.channelPassword": "频道密码:",
"connect.playbackProfile": "播放配置:",
"connect.onetimeGrant": "一次性权限密钥:",
"connect.serverType": "服务器类型:",
"connect.serverType.auto": "自动",
"connect.serverType.teamspeak": "TeamSpeak",
"connect.serverType.teaspeak": "TeaSpeak",
"connect.hotkeyProfile": "快捷键配置:",
"connect.sendMyTeamSpeakId": "发送 myTeamSpeak ID",
"connect.soundPack": "声音包:",
@@ -138,6 +142,18 @@ export const zhCN: Record<string, string> = {
"connectionInfo.unavailable": "服务器无响应(可能缺少权限)。",
"connectionInfo.ping": "延迟:",
"connectionInfo.connectedSince": "连接时间:",
"connectionInfo.uptime": "运行时间:",
"connectionInfo.name": "名称:",
"connectionInfo.avgPing": "平均延迟:",
"connectionInfo.avgPacketLoss": "平均丢包率:",
"connectionInfo.incoming": "传入",
"connectionInfo.outgoing": "传出",
"connectionInfo.packetsTransferred": "传输数据包",
"connectionInfo.bytesTransferred": "传输字节",
"connectionInfo.bandwidthLastSecond": "上一秒带宽",
"connectionInfo.bandwidthLastMinute": "上一分钟带宽",
"connectionInfo.ftBandwidth": "文件传输带宽",
"connectionInfo.ftBytes": "文件传输字节",
"connectionInfo.ip": "IP 地址:",
"connectionInfo.packetLoss": "丢包率:",
"connectionInfo.packetsSent": "已发送数据包:",
@@ -211,6 +227,16 @@ export const zhCN: Record<string, string> = {
"options.section.wiedergabe": "播放",
"options.section.aufnahme": "录音",
"options.section.design": "外观",
"design.subtitle": "选择应用外观。",
"design.theme.standard": "标准",
"design.theme.standard.desc": "原始 WebSpeak3 设计。",
"design.theme.nova": "Nova",
"design.theme.nova.desc": "更现代的深色设计,带圆角元素。",
"design.theme.greenteaspeak": "GreenTeaSpeak",
"design.theme.greenteaspeak.desc": "经典 GreenTeaSpeak 客户端布局:深色面板与金色菜单栏。",
"design.theme.pulse": "Pulse",
"design.theme.pulse.desc": "卡片式布局,带面包屑栏和彩色强调。",
"design.status.connected": "已连接",
"options.section.erweiterungen": "扩展",
"options.section.hotkeys": "快捷键",
"options.section.whispern": "悄悄话",
@@ -267,19 +293,28 @@ export const zhCN: Record<string, string> = {
"info.currentChannels": "当前频道:",
"info.topic": "主题:",
"info.audioCodec": "音频编解码器:",
"info.spacer": "间隔符:",
"info.rawName": "原始名称:",
"info.passwordProtected": "密码保护:",
"info.clients": "用户:",
"info.country": "国家:",
"info.muted": "麦克风静音:",
"info.outputMuted": "扬声器静音:",
"info.serverGroups": "服务器组:",
"info.yes": "是",
"info.no": "否",
"tree.notConnected": "未连接",
"tree.clickToSelect": "单击选择,双击加入",
"tree.clickToJoin": "双击加入",
"tree.joinNotConnected": "未连接 — 无法切换频道",
"tree.passwordProtected": "受密码保护",
"tree.privateChatWith": "与其私聊",
"tree.poke": "戳一戳",
"tree.channelCommander": "频道指挥官",
"tree.away": "离开",
"tree.micMuted": "麦克风已静音",
"tree.talking": "正在说话",
"tree.noTalkPower": "在此频道中没有发言权限",
"tree.soundMuted": "声音已关闭(拒听)",
@@ -424,6 +459,7 @@ export const zhCN: Record<string, string> = {
"permsEditor.searchPermission": "搜索权限...",
"dialog.ok": "确定",
"channelContext.join": "切换到频道",
"channelContext.files": "文件...",
"fileBrowser.title": "文件传输",
"fileBrowser.up": "上一级",
+1
View File
@@ -1,6 +1,7 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import './styles/greenteaspeak.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,87 @@
import type { ReactNode } from "react";
export type ConnectionTabItem = {
id: string;
label: string;
connected?: boolean;
connecting?: boolean;
};
export type GreenteaSpeakChromeProps = {
/** @deprecated Prefer `tabs` + `activeTabId` for multi-join. */
connected?: boolean;
/** @deprecated Prefer `tabs`. */
serverName?: string;
tabs?: ConnectionTabItem[];
activeTabId?: string | null;
onSelectTab?: (id: string) => void;
onCloseTab?: (id: string) => void;
children?: ReactNode;
};
/**
* GTS branding chrome: connection-tab strip (multi-join) + brand label when empty.
* Renders children unchanged — WebSpeak keeps its own React state/handlers.
*/
export function GreenteaSpeakChrome({
connected,
serverName,
tabs,
activeTabId,
onSelectTab,
onCloseTab,
children,
}: GreenteaSpeakChromeProps) {
const resolvedTabs: ConnectionTabItem[] =
tabs ??
(connected
? [{ id: "legacy", label: (serverName ?? "").trim() || "GreenTeaSpeak", connected: true }]
: []);
const hasTabs = resolvedTabs.length > 0;
return (
<>
{hasTabs ? (
<div className="gts-connection-tabs" role="tablist" aria-label="Server-Verbindungen">
{resolvedTabs.map((tab) => {
const isActive = tab.id === (activeTabId ?? resolvedTabs[0]?.id);
return (
<div
key={tab.id}
role="tab"
aria-selected={isActive}
className={`gts-connection-tab${isActive ? " gts-connection-tab-active" : ""}${
tab.connecting ? " gts-connection-tab-connecting" : ""
}`}
onClick={() => onSelectTab?.(tab.id)}
title={tab.label}
>
<span className="gts-connection-tab-label">{tab.label}</span>
{onCloseTab ? (
<button
type="button"
className="gts-connection-tab-close"
title="Verbindung trennen"
aria-label={`Tab schließen: ${tab.label}`}
onClick={(e) => {
e.stopPropagation();
onCloseTab(tab.id);
}}
>
×
</button>
) : null}
</div>
);
})}
</div>
) : (
<div className="gts-connection-tabs gts-brand-strip">
<span className="gts-brand-label">GreenTeaSpeak</span>
</div>
)}
{children}
</>
);
}
@@ -0,0 +1,56 @@
/**
* Maps WebSpeak gateway WebSocket payloads to the shape the GreenTeaSpeak
* shell expects. The browser UI still uses App.tsx state; this module is the
* contract layer so GTS chrome never talks to Electron IPC.
*/
export type GatewayServerType = "auto" | "teamspeak" | "teaspeak";
export type GatewayConnectPayload = {
type: "connect";
host: string;
nickname: string;
serverPassword?: string;
channelPassword?: string;
defaultChannel?: string;
identity?: string;
privilegeKey?: string;
serverType?: GatewayServerType;
};
export type GatewayOutboundAction =
| GatewayConnectPayload
| { type: "disconnect" }
| { type: "switchChannel"; channelId: number }
| { type: "sendChat"; message: string; target?: "channel" | "server" | number }
| { type: string; [key: string]: unknown };
/** Build the connect message sent on the WebSpeak gateway socket. */
export function buildGatewayConnect(input: {
host: string;
nickname: string;
serverPassword?: string;
channelPassword?: string;
defaultChannel?: string;
identity?: string;
privilegeKey?: string;
serverType?: GatewayServerType;
}): GatewayConnectPayload {
return {
type: "connect",
host: input.host.trim(),
nickname: input.nickname.trim(),
serverPassword: input.serverPassword?.trim() || undefined,
channelPassword: input.channelPassword?.trim() || undefined,
defaultChannel: input.defaultChannel?.trim() || undefined,
identity: input.identity || undefined,
privilegeKey: input.privilegeKey?.trim() || undefined,
serverType: input.serverType || "auto",
};
}
export function sendGatewayAction(ws: WebSocket | null, action: GatewayOutboundAction): boolean {
if (!ws || ws.readyState !== WebSocket.OPEN) return false;
ws.send(JSON.stringify(action));
return true;
}
+19
View File
@@ -0,0 +1,19 @@
export const GREENTEASPEAK_THEME_ID = "greenteaspeak" as const;
export function isGreenteaSpeakTheme(theme: string): boolean {
return theme === GREENTEASPEAK_THEME_ID;
}
export {
GreenteaSpeakChrome,
type GreenteaSpeakChromeProps,
type ConnectionTabItem,
} from "./GreenteaSpeakChrome";
export {
buildGatewayConnect,
sendGatewayAction,
type GatewayConnectPayload,
type GatewayOutboundAction,
type GatewayServerType,
} from "./gatewayAdapter";