Compare commits

...
Author SHA1 Message Date
Moepchi cf5ecb1455 docs: mention TeaSpeak/GreenTeaSpeak support in README
PR #4 added TeaSpeak/GreenTeaSpeak protocol support alongside existing
TS3/TS6, plus an optional GTS-styled theme - update the tagline, quick
start text, features table, architecture section, and trademark
disclaimer to reflect that.
2026-09-06 01:54:52 +02:00
Möpchi 9206b12e25 Merge pull request #4 from GreenTeaSpeak/main
Add TeaSpeak/GTS support and multi-join functionality
2026-09-06 01:39:07 +02:00
Nico B.andCursor 5d2b02feb0 Point tsclientlib at GreenTeaSpeak tsdeclarations fork.
Track the org-owned declarations remote via the updated tsclientlib submodule.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 01:32:53 +02:00
Nico B.andCursor 77165af5e4 Exclude ServerQuery from online total so it matches the filtered client list.
The PR #4 review fix still preferred virtualserver_clientsonline which usually includes Query; subtract bookkeeping Query count before applying the stale-data max.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 01:28:19 +02:00
Nico B. a118c0f58e Merge pull request #1 from Moepchi/fix/pr-4-review-bugs
Fix 8 correctness bugs found in review of TeaSpeak/GTS + multi-join PR
2026-09-06 01:20:59 +02:00
Nico B.andCursor 3db5d90d89 Merge upstream/main into GreenTeaSpeak main to resolve PR #4 conflicts.
Keep TeaSpeak/GTS multi-tab work while integrating channel-password prompts and the Pulse theme.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 00:54:04 +02:00
Nico B.andCursor ecdd69bceb Point tsclientlib submodule at GreenTeaSpeak fork.
The TeaSpeak commit was only local; clones and CI failed. Host it on the org fork and track that remote.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 00:48:00 +02:00
Moepchi 9702c671e8 Fix 8 correctness bugs found in code review of PR #4
- Connection log only ever rendered the single latest entry
  (log.slice(-1) -> log.slice(-50)), and appendLog grew log[] unbounded
- Mic stayed off after switching back to a parked multi-join tab
  (added ParkedSessionState.micWasOn, restore mic on switch-back)
- Packet-loss heuristic guessed fraction-vs-percent by magnitude, which
  can't disambiguate; now branches on actual server type (GTS vs TS3)
- serverGroups/channelGroups/permissionCatalog/banList/fileBrowser were
  page-global caches never invalidated on multi-join tab switch, so a
  newly active tab could show another server's stale data
- ServerQuery clients were filtered from the client list but still
  counted in the online-total fallback; total now matches the list
- gateway disconnect() resolved before the connector child process
  actually exited, allowing two connector processes to run briefly on
  a fast reconnect; now waits for exit (with a hard-kill fallback)
- switching a parked multi-join tab back in replayed a spurious
  whisper-target log entry and resent setWhisperTargets even when
  nothing changed, because the diff was against the wrong tab's ref
- double-click-to-join channel detection used module-level state,
  so a click in one multi-join tab could pair with a click in another
  tab's tree as a false double-click; now keyed per session

Note: could not verify with a full cargo build - the PR's own
'Update tsclientlib' commit (cd6928b) points at a tsclientlib submodule
commit that isn't pushed to any reachable branch (not even the PR
author's own fork), so nobody can currently build this PR end-to-end.
That is unrelated to these fixes.
2026-09-06 00:20:33 +02:00
Moepchi 27ac828641 Add channel password prompt on mid-session join (fixes #3)
Joining a password-protected channel after connecting silently failed
with only a generic error in the log - there was no way to enter a
password except the initial-connect "default channel" field.

- connector: "switch" now accepts an optional base64-encoded password
  and wires it through tsclientlib's existing set_password() API; a
  ChannelInvalidPassword failure is reported as a distinct
  channelPasswordRequired event instead of a generic error.
- gateway: forwards channelPassword through switchChannel and remaps
  the connector's snake_case event to the frontend's camelCase shape.
- web: new ChannelPasswordDialog prompts for the password (and flags
  a wrong retry); the password is cached in memory for the session so
  re-entering an already-unlocked channel doesn't prompt again, and
  the cache is cleared on disconnect.

Also includes two earlier Pulse-theme CSS fixes (bottom-toolbar
dropdowns opening off-screen; caret button height mismatch) and the
Speaking Now bar / Pulse Phase D wiring from this session.
2026-09-05 23:49:43 +02:00
Nico B. cd6928b407 Update tsclientlib 2026-09-05 22:48:31 +02:00
Nico B. e9ee12c7b5 Add TeaSpeak/GTS support, multi-join & GTS theme
Adds TeaSpeak/GreenTeaSpeak protocol support and multi-join session tabs plus a GreenteaSpeak UI theme. Key changes: connector (Rust) supports --server-type, privilege key, server variables, license formatting, Query-client filtering and extra metrics; gateway accepts serverType/privilegeKey, optional static serving (WEB_STATIC), and per-tab /ws sessions; web frontend: multi-session parking (connectionSessions), channel spacer parsing, talk-lamp UI, extended server connection info, connect dialog serverType/privilegeKey, GreenteaSpeak CSS & chrome, i18n updates, and demo updates. Also adds docs/teaspeak.md and dependency num-traits.
2026-09-05 22:45:21 +02:00
MoepchiandClaude Sonnet 5 804fa44ab6 fix: update stale moepchi.de OG/Twitter meta tags to webspeak3.de
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-03 20:35:49 +02:00
23 changed files with 4095 additions and 238 deletions

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
+29 -17
View File
@@ -1,4 +1,4 @@
<p align="center">
<p align="center">
<img src="web/public/logo.png" width="140" alt="WebSpeak3 logo">
</p>
@@ -14,7 +14,7 @@
</p>
<p align="center">
<b>A modern, self-hosted browser client for TeamSpeak 3 servers — no install, just open a tab.</b>
<b>A modern, self-hosted browser client for TeamSpeak, TeaSpeak, and GreenTeaSpeak servers — no install, just open a tab.</b>
</p>
<p align="center">
@@ -52,9 +52,9 @@ Run the ready-made container and open **http://localhost:8080**:
docker run -d --name webspeak3 --restart unless-stopped -p 8080:8080 moepchi/webspeak3:latest
```
Enter the address and port of **any reachable TeamSpeak 3 or TeamSpeak 6
server** in the connection dialog. The TeamSpeak server does not need to be
installed on the same machine, modified, or operated by you.
Enter the address and port of **any reachable TeamSpeak 3, TeamSpeak 6,
TeaSpeak, or GreenTeaSpeak server** in the connection dialog. The server does
not need to be installed on the same machine, modified, or operated by you.
> Voice requires a secure context. Microphone access works on `localhost`; for
> access from other devices, place WebSpeak3 behind an HTTPS reverse proxy.
@@ -63,7 +63,7 @@ installed on the same machine, modified, or operated by you.
| | |
|---|---|
| 🔌 **Real TeamSpeak protocol** | Connects to actual TS3/TS6 servers over a WebSocket gateway — the server stays exactly as-is |
| 🔌 **Real TeamSpeak protocol** | Connects to actual TS3/TS6, TeaSpeak, and GreenTeaSpeak servers over a WebSocket gateway — the server stays exactly as-is |
| 🎙️ **Low-latency voice** | Opus-encoded voice with voice activation ("Sprachaktivierung") and adjustable sensitivity |
| 🤫 **Whisper** | Target your voice at specific channels or clients instead of your whole current channel |
| 🔊 **Custom audio output picker** | Route playback to any output device — works even in browsers without `AudioContext.setSinkId` |
@@ -78,7 +78,9 @@ 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 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 |
| 🍵 **GreenTeaSpeak theme** | Optional GTS-styled UI chrome (dark panels, gold menu bar, connection-tab strip) alongside the default look |
## 🧱 Tech Stack
@@ -102,18 +104,22 @@ gateway is required that speaks the real TS protocol on one side and
WebSocket to the browser on the other.
```
Browser (web/) <--WebSocket--> Gateway (gateway/) <--stdin/stdout JSON--> Rust connector (connector/) <--TS3/TS6 protocol--> TeamSpeak Server
Browser (web/) <--WebSocket--> Gateway (gateway/) <--stdin/stdout JSON--> Rust connector (connector/) <--TS3/TS6/TeaSpeak protocol--> Server
```
- **`web/`** — Vite + React frontend. TS3-lookalike UI: channel tree, chat
tabs, voice controls.
tabs, voice controls. Optional GreenTeaSpeak-styled chrome for the
connection-tab strip and menu bar.
- **`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
(vendored as a git submodule in `tsclientlib/`, currently tracking a fork
with TeaSpeak/GreenTeaSpeak protocol support), the actual TS3/TS6/TeaSpeak
protocol implementation. Handles connecting, channel/client state, chat,
and Opus-encoded voice.
and Opus-encoded voice. Auto-detects the server dialect on connect (or it
can be forced via `--server-type`).
</details>
@@ -222,7 +228,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 +241,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**
@@ -260,6 +269,9 @@ The vast majority of this project's code was written by [Claude Code](https://cl
any way officially connected with TeamSpeak Systems GmbH.
"TeamSpeak", "TS3", and related logos or names are registered trademarks of
TeamSpeak Systems GmbH. All product and company names are trademarks™ or
registered® trademarks of their respective holders. Use of them does not
imply any affiliation with or endorsement by them.
TeamSpeak Systems GmbH. Likewise, WebSpeak3 is not affiliated with,
associated with, authorized by, or endorsed by TeaSpeak or GreenTeaSpeak;
"TeaSpeak" and "GreenTeaSpeak" are names of their respective projects/
operators. All product and company names are trademarks™ or registered®
trademarks of their respective holders. Use of them does not imply any
affiliation with or endorsement by them.
+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"
+297 -24
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,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, TsError,
};
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<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)]
@@ -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<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")]
@@ -215,6 +237,11 @@ enum Event {
Disconnected { reason: String },
#[serde(rename = "error")]
Error { message: String },
/// A "switch" to a password-protected channel was rejected because no (or
/// the wrong) password was supplied. The frontend should prompt for a
/// password and retry with it rather than showing a generic error.
#[serde(rename = "channelPasswordRequired")]
ChannelPasswordRequired { channel_id: u64 },
/// Server-tab log notification (client join/leave/switch, channel group
/// assignment, channel/server changes, own permission errors).
#[serde(rename = "serverLog")]
@@ -241,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,
@@ -249,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
@@ -538,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
@@ -569,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]
@@ -581,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}")
@@ -593,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}"),
@@ -617,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);
}
@@ -655,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,
@@ -663,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,
});
@@ -670,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.
{
@@ -698,6 +852,10 @@ async fn run(args: Args) -> Result<()> {
// `send_with_result()` for text messages gets us a `MessageResult` event we
// can surface as a visible error instead of the message just vanishing.
let mut pending_messages: HashMap<MessageHandle, String> = HashMap::new();
// Tracks which channel a pending "Channel switch" MessageResult is for, so
// a ChannelInvalidPassword failure can be reported as ChannelPasswordRequired
// for that specific channel instead of a generic error.
let mut pending_switch_channel: HashMap<MessageHandle, u64> = HashMap::new();
// When non-empty, outgoing voice is whispered to just these channels/clients
// instead of being sent to the current channel - set via the "whisper "
// stdin command, cleared via "unwhisper".
@@ -758,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);
@@ -790,21 +966,65 @@ async fn run(args: Args) -> Result<()> {
emit(&Event::Disconnected { reason: "client requested".into() });
break;
} else if let Some(rest) = l.strip_prefix("switch ") {
match rest.trim().parse::<u64>() {
// "switch <id>" or "switch <id> <base64-encoded password>" - the
// password travels base64-encoded since this is a line-based
// stdin protocol and a password could contain spaces/newlines.
let mut switch_args = rest.trim().splitn(2, ' ');
let id_arg = switch_args.next().unwrap_or("");
let password_arg = switch_args.next();
match id_arg.parse::<u64>() {
Ok(id) => {
let part = {
let state = con.get_state()?;
let own = &state.clients[&state.own_client];
own.client_move(ChannelId(id))
let password = password_arg.and_then(|p| {
base64::engine::general_purpose::STANDARD
.decode(p)
.ok()
.and_then(|bytes| String::from_utf8(bytes).ok())
});
// 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());
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: {rest}") }),
}
Err(_) => emit(&Event::Error { message: format!("Invalid channel id: {id_arg}") }),
}
} else if let Some(message) = l.strip_prefix("chat ") {
let part = OutSendTextMessagePart {
@@ -1075,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() }),
}
@@ -1841,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 {
@@ -1857,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()?
@@ -1885,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);
}
}
@@ -1918,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;
}
@@ -1951,8 +2204,15 @@ async fn run(args: Args) -> Result<()> {
}
Some(Ok(StreamItem::MessageResult(handle, result))) => {
if let Some(label) = pending_messages.remove(&handle) {
let switch_channel_id = pending_switch_channel.remove(&handle);
if let Err(e) = result {
if e.missing_permission.is_some() {
if label == "Channel switch" && e.error == TsError::ChannelInvalidPassword {
if let Some(channel_id) = switch_channel_id {
emit(&Event::ChannelPasswordRequired { channel_id });
} else {
emit(&Event::Error { message: format!("{label} failed: {e}") });
}
} else if e.missing_permission.is_some() {
emit(&Event::ServerLog {
entry: ServerLogEntry::PermissionError { action: label },
});
@@ -2323,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);
const channelId = Number(msg.channelId);
if (Number.isFinite(channelId)) {
await connection?.switchChannel(channelId, msg.channelPassword);
}
break;
}
case "sendChatMessage": {
+72 -6
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 }
@@ -130,6 +131,7 @@ export type Ts3ConnectionEvent =
| { type: "talkers"; clients: number[] }
| { type: "disconnected"; reason: string }
| { type: "error"; message: string }
| { type: "channelPasswordRequired"; channelId: number }
| ({ type: "serverLog" } & ServerLogEntry)
| {
type: "clientConnectionInfo";
@@ -154,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[] }
@@ -176,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;
@@ -185,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));
@@ -216,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) => {
@@ -257,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 }
@@ -269,6 +294,7 @@ export class Ts3Connection {
| { type: "talkers"; clients: number[] }
| { type: "disconnected"; reason: string }
| { type: "error"; message: string }
| { type: "channelPasswordRequired"; channel_id: number }
| ({ type: "serverLog" } & ServerLogEntry)
| {
type: "clientConnectionInfo";
@@ -293,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[] }
| {
@@ -359,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,
});
@@ -392,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({
@@ -426,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({
@@ -475,6 +518,8 @@ export class Ts3Connection {
message: event.message,
timestamp: event.timestamp,
});
} else if (event.type === "channelPasswordRequired") {
this.emit({ type: "channelPasswordRequired", channelId: event.channel_id });
} else {
this.emit(event);
}
@@ -496,8 +541,13 @@ export class Ts3Connection {
});
}
async switchChannel(channelId: number): Promise<void> {
this.child?.stdin.write(`switch ${channelId}\n`);
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 ${id}${passwordArg}\n`);
}
async getClientConnectionInfo(clientId: number): Promise<void> {
@@ -746,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();
}
+3 -3
View File
@@ -13,13 +13,13 @@
<meta property="og:type" content="website" />
<meta property="og:title" content="WebSpeak3" />
<meta property="og:description" content="An independent, self-hosted web client for TeamSpeak 3 servers." />
<meta property="og:url" content="https://ts.moepchi.de/" />
<meta property="og:image" content="https://ts.moepchi.de/og-image.png" />
<meta property="og:url" content="https://client.webspeak3.de/" />
<meta property="og:image" content="https://client.webspeak3.de/og-image.png" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="WebSpeak3" />
<meta name="twitter:description" content="An independent, self-hosted web client for TeamSpeak 3 servers." />
<meta name="twitter:image" content="https://ts.moepchi.de/og-image.png" />
<meta name="twitter:image" content="https://client.webspeak3.de/og-image.png" />
</head>
<body>
<div id="root"></div>
+694 -3
View File
@@ -796,6 +796,487 @@
border: 2px solid var(--bg);
}
/* Pulse: alternate design, independent of the light/dark toggle (always
dark). Visual reference: a Discord-style client with a dark rounded
sidebar, pill-shaped channel/client rows and a floating card-based main
panel - reimplemented from scratch in our own markup/CSS (no code or
assets borrowed), reusing the same DOM/class names as Standard/Nova the
way Nova does, with its own indigo/violet accent (colors need not match
any particular reference client). */
:where(.ts-app.ts-design-pulse) {
--success: oklch(0.75 0.15 150);
--bg: oklch(0.19 0.02 290);
--bg-toolbar-1: oklch(0.155 0.018 290);
--bg-toolbar-2: oklch(0.235 0.024 290);
--border: oklch(0.32 0.02 290);
--border-soft: oklch(0.27 0.02 290);
--text: oklch(0.95 0.006 290);
--text-muted: oklch(0.64 0.014 290);
--text-faint: oklch(0.48 0.012 290);
--accent: #9d8cf0;
--input-bg: oklch(0.235 0.024 290);
--input-text: oklch(0.95 0.006 290);
--button-bg-1: oklch(0.235 0.024 290);
--button-bg-2: oklch(0.155 0.018 290);
--button-bg-hover-1: oklch(0.28 0.026 290);
--button-bg-hover-2: oklch(0.235 0.024 290);
--row-hover: oklch(0.27 0.03 290);
--client-text: oklch(0.95 0.006 290);
--self-text: #9d8cf0;
--log-bg: oklch(0.155 0.018 290);
--log-text: oklch(0.64 0.014 290);
--log-error: oklch(0.68 0.16 25);
color-scheme: dark;
font-family: "Manrope", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
}
.ts-app.ts-design-pulse button,
.ts-app.ts-design-pulse select,
.ts-app.ts-design-pulse input[type="text"],
.ts-app.ts-design-pulse input[type="password"],
.ts-app.ts-design-pulse input[type="search"],
.ts-app.ts-design-pulse .ts-dialog {
border-radius: 10px;
}
/* Top bar: rendered as a breadcrumb - app logo, then the server name, then
(when a channel is selected) a chevron and the channel name - instead of
Standard's menu-item row. The menu items themselves fold into a single
overflow button so the breadcrumb reads clean, mirroring the reference
client's header. */
.ts-app.ts-design-pulse > .ts-menubar {
order: 0;
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.65rem 1.2rem;
background: var(--bg-toolbar-1);
border-bottom: 1px solid var(--border-soft);
}
.ts-app.ts-design-pulse > .ts-menubar .ts-nova-menu-dropdown {
order: 1;
}
.ts-app.ts-design-pulse > .ts-menubar .ts-menubar-item {
border-radius: 8px;
color: var(--text-muted);
}
.ts-app.ts-design-pulse > .ts-menubar .ts-menubar-item-active {
background: var(--bg-toolbar-2);
color: var(--text);
}
.ts-app.ts-design-pulse > .ts-body {
order: 1;
}
.ts-app.ts-design-pulse > .ts-log {
order: 2;
}
/* Voice control bar, bottom-docked like Nova's, but pill-shaped controls on
a flat strip instead of Nova's rounded-square icon buttons. */
.ts-app.ts-design-pulse > .ts-toolbar {
order: 3;
flex-direction: row;
align-items: center;
background: var(--bg-toolbar-1);
border-bottom: none;
border-top: 1px solid var(--border-soft);
padding: 0.6rem 1.2rem;
}
.ts-app.ts-design-pulse > .ts-toolbar .ts-toolbar-icons {
flex: 1;
justify-content: center;
gap: 0.6rem;
flex-wrap: wrap;
}
.ts-app.ts-design-pulse > .ts-toolbar .ts-icon-button {
width: 40px;
height: 40px;
border-radius: 999px;
font-size: 16px;
}
.ts-app.ts-design-pulse > .ts-toolbar .ts-toolbar-sep {
height: 24px;
align-self: center;
margin: 0 0.3rem;
}
.ts-app.ts-design-pulse > .ts-toolbar .ts-app-logo {
border-radius: 999px;
}
.ts-pulse-topbar-server {
display: flex;
align-items: center;
gap: 0.55rem;
font-weight: 700;
font-size: 14px;
}
.ts-pulse-topbar-logo {
display: flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
border-radius: 7px;
background: var(--accent);
color: var(--bg-toolbar-1);
font-weight: 800;
font-size: 12px;
flex-shrink: 0;
}
.ts-pulse-topbar-crumb-sep {
color: var(--text-faint);
font-weight: 400;
}
.ts-pulse-topbar-channel {
color: var(--text-muted);
font-weight: 600;
}
.ts-app.ts-design-pulse .ts-icon-button,
.ts-app.ts-design-pulse .ts-toolbar-fields button,
.ts-app.ts-design-pulse .ts-chat-input-row button {
border-radius: 999px;
background: var(--button-bg-1);
padding: 0.35rem 0.6rem;
}
.ts-app.ts-design-pulse .ts-icon-button:hover,
.ts-app.ts-design-pulse .ts-toolbar-fields button:hover,
.ts-app.ts-design-pulse .ts-chat-input-row button:hover {
background: var(--button-bg-hover-1);
}
.ts-app.ts-design-pulse .ts-icon-caret {
height: 40px;
display: inline-flex;
align-items: center;
border-radius: 0 999px 999px 0;
background: var(--button-bg-1);
}
.ts-app.ts-design-pulse .ts-toolbar-away .ts-icon-button {
border-radius: 999px 0 0 999px;
}
/* Floating-card layout: sidebar and chat panel read as separate rounded
cards with a gap between them (and against the window edges), instead of
Standard's flush panes or Nova's single joined pair. */
.ts-app.ts-design-pulse .ts-upper {
gap: 0.7rem;
padding: 0.7rem 0.7rem 0;
}
.ts-app.ts-design-pulse .ts-tree-panel,
.ts-app.ts-design-pulse .ts-info-panel {
background: var(--bg-toolbar-1);
border: 1px solid var(--border-soft);
border-radius: 14px;
}
.ts-app.ts-design-pulse .ts-resize-handle-vertical,
.ts-app.ts-design-pulse .ts-resize-handle-horizontal {
background: transparent;
}
.ts-app.ts-design-pulse .ts-banner-panel {
border-radius: 14px;
border: 1px solid var(--border-soft);
margin: 0 0.7rem;
}
.ts-app.ts-design-pulse .ts-chat-panel {
background: var(--bg-toolbar-1);
border: 1px solid var(--border-soft);
border-radius: 14px;
overflow: hidden;
margin: 0.7rem;
}
/* Speaking Now strip: a row of avatar tiles for everyone in the player's
current channel, with the talking member's avatar highlighted - the
"who's speaking" strip from the reference client's connected view. */
.ts-app.ts-design-pulse .ts-speaking-now {
display: flex;
flex-wrap: wrap;
gap: 0.6rem;
padding: 0.7rem 0.9rem;
border-bottom: 1px solid var(--border-soft);
}
.ts-app.ts-design-pulse .ts-speaking-now-tile {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.3rem;
width: 52px;
}
.ts-app.ts-design-pulse .ts-speaking-now-avatar {
display: inline-flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
border-radius: 50%;
font-size: 14px;
font-weight: 800;
color: oklch(0.18 0.02 290);
box-shadow: 0 0 0 2px transparent;
transition: box-shadow 0.15s ease;
}
.ts-app.ts-design-pulse .ts-speaking-now-tile-active .ts-speaking-now-avatar {
box-shadow: 0 0 0 3px var(--success);
}
.ts-app.ts-design-pulse .ts-speaking-now-name {
font-size: 10px;
color: var(--text-muted);
max-width: 52px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ts-app.ts-design-pulse .ts-speaking-now-tile-active .ts-speaking-now-name {
color: var(--text);
}
/* Pill-shaped sidebar rows for channels/clients, accent bar on the
selected row instead of a full-row outline. */
.ts-app.ts-design-pulse .ts-row {
padding: 5px 8px;
border-radius: 999px;
margin: 1px 0;
}
.ts-app.ts-design-pulse .ts-client-row {
padding-left: 1.2rem;
}
.ts-app.ts-design-pulse .ts-row-selected {
border-radius: 999px;
outline: none;
background: var(--bg-toolbar-2);
box-shadow: inset 3px 0 0 var(--accent);
}
.ts-app.ts-design-pulse .ts-row:hover:not(.ts-row-selected) {
background: var(--row-hover);
}
/* Rounded circular avatar chips (vs. Nova's rounded squares), matching the
reference client's member-list look. */
.ts-app.ts-design-pulse .ts-client-avatar {
display: inline-flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
border-radius: 50%;
flex-shrink: 0;
font-size: 9.5px;
font-weight: 800;
color: oklch(0.18 0.02 290);
}
.ts-app.ts-design-pulse .ts-talking .ts-client-avatar {
box-shadow: 0 0 0 2px var(--success);
}
/* Rounded pill tab bar for the channel/server/PM chat tabs, sitting above
the message list rather than flush against it. */
.ts-app.ts-design-pulse .ts-chat-tabs {
order: -1;
border-top: none;
border-bottom: 1px solid var(--border-soft);
padding: 0.55rem 0.7rem 0.4rem;
gap: 0.35rem;
}
.ts-app.ts-design-pulse .ts-chat-tab {
border: none;
border-radius: 999px;
background: var(--bg-toolbar-2);
color: var(--text-muted);
padding: 0.4rem 0.85rem;
font-weight: 600;
}
.ts-app.ts-design-pulse .ts-chat-tab:hover:not(.ts-chat-tab-active) {
color: var(--text);
}
.ts-app.ts-design-pulse .ts-chat-tab-active {
background: var(--accent);
color: var(--bg-toolbar-1);
font-weight: 700;
}
/* Bubble-style chat messages, own messages right-aligned in an accent
bubble, others left-aligned in a muted-surface bubble; log lines render
as a centered, faint pill. */
.ts-app.ts-design-pulse .ts-chat-messages {
padding: 0.9rem 1rem;
display: flex;
flex-direction: column;
gap: 0.6rem;
}
.ts-app.ts-design-pulse .ts-chat-line {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 2px;
max-width: 70%;
padding: 0;
}
.ts-app.ts-design-pulse .ts-chat-line-self {
align-self: flex-end;
align-items: flex-end;
}
.ts-app.ts-design-pulse .ts-chat-from {
font-size: 11.5px;
font-weight: 700;
color: var(--text-muted);
}
.ts-app.ts-design-pulse .ts-chat-line-self .ts-chat-from {
color: var(--accent);
}
.ts-app.ts-design-pulse .ts-chat-bubble {
display: inline-block;
background: var(--bg-toolbar-2);
padding: 0.5rem 0.75rem;
border-radius: 14px 14px 14px 4px;
line-height: 1.45;
}
.ts-app.ts-design-pulse .ts-chat-line-self .ts-chat-bubble {
background: var(--accent);
color: var(--bg-toolbar-1);
border-radius: 14px 14px 4px 14px;
font-weight: 600;
}
.ts-app.ts-design-pulse .ts-chat-line-log {
align-self: center;
align-items: center;
max-width: none;
background: var(--bg-toolbar-2);
color: var(--text-faint);
font-style: italic;
font-size: 11.5px;
padding: 0.25rem 0.75rem;
border-radius: 999px;
}
.ts-app.ts-design-pulse .ts-chat-input-row {
border-top: 1px solid var(--border-soft);
padding: 0.6rem 0.8rem;
align-items: center;
}
.ts-app.ts-design-pulse .ts-chat-input-row textarea {
border-radius: 999px;
border-color: var(--border-soft);
background: var(--bg-toolbar-2);
padding: 0.55rem 1rem;
}
.ts-app.ts-design-pulse .ts-chat-input-row button {
width: 40px;
height: 40px;
padding: 0;
border: none;
border-radius: 50%;
background: var(--accent);
color: transparent;
font-size: 0;
flex-shrink: 0;
position: relative;
}
.ts-app.ts-design-pulse .ts-chat-input-row button:hover {
background: var(--accent);
filter: brightness(1.08);
}
.ts-app.ts-design-pulse .ts-chat-input-row button:disabled {
opacity: 0.4;
}
.ts-app.ts-design-pulse .ts-chat-input-row button::before {
content: "➤";
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
font-size: 15px;
color: var(--bg-toolbar-1);
}
.ts-app.ts-design-pulse .ts-log {
border-top: 1px solid var(--border-soft);
margin: 0 0.7rem 0.7rem;
border: 1px solid var(--border-soft);
border-radius: 12px;
}
.ts-app.ts-design-pulse .ts-dialog {
border-radius: 14px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
}
.ts-app.ts-design-pulse .ts-menu {
border-radius: 10px;
overflow: hidden;
}
.ts-app.ts-design-pulse .ts-menu-item:hover:not(:disabled) {
border-radius: 8px;
}
.ts-app.ts-design-pulse ::-webkit-scrollbar {
width: 10px;
height: 10px;
}
.ts-app.ts-design-pulse ::-webkit-scrollbar-track {
background: transparent;
}
.ts-app.ts-design-pulse ::-webkit-scrollbar-thumb {
background: var(--border);
border-radius: 999px;
border: 2px solid var(--bg);
}
/* Demo mode banner */
.ts-demo-banner {
@@ -1178,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;
@@ -1197,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;
@@ -1214,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);
@@ -1259,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 {
@@ -1278,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 {
@@ -1406,6 +2084,11 @@
.ts-menu-away {
min-width: 220px;
/* This dropdown hangs off the bottom toolbar, so opening downward (the
.ts-menu default) would push it below the viewport and force the whole
page to scroll - open upward instead. */
top: auto;
bottom: 100%;
}
/* Chat */
@@ -2416,6 +3099,14 @@
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;
}
.ts-design-theme-card-name {
font-weight: 600;
font-size: 13px;
+1147 -176
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,
});
}
}
+72
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",
@@ -86,6 +90,12 @@ const translations: Record<Lang, Record<string, string>> = {
"connect.newTab": "In neuem Tab",
"connect.cancel": "Abbrechen",
"channelPasswordDialog.title": "Channel-Passwort erforderlich",
"channelPasswordDialog.prompt": "Dieser Channel ist passwortgeschützt. Bitte Passwort eingeben:",
"channelPasswordDialog.wrongPassword": "Falsches Passwort, bitte erneut versuchen:",
"channelPasswordDialog.submit": "Beitreten",
"channelPasswordDialog.cancel": "Abbrechen",
"collectedUrls.title": "Gesammelte URLs",
"collectedUrls.search": "Suchen:",
"collectedUrls.url": "URL",
@@ -151,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:",
@@ -228,6 +250,10 @@ 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",
"design.custom.new": "+ Neues Design",
"design.custom.import": "Design importieren",
@@ -302,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)",
@@ -459,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",
@@ -601,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",
@@ -610,6 +650,12 @@ const translations: Record<Lang, Record<string, string>> = {
"connect.newTab": "In new tab",
"connect.cancel": "Cancel",
"channelPasswordDialog.title": "Channel password required",
"channelPasswordDialog.prompt": "This channel is password-protected. Please enter the password:",
"channelPasswordDialog.wrongPassword": "Wrong password, please try again:",
"channelPasswordDialog.submit": "Join",
"channelPasswordDialog.cancel": "Cancel",
"collectedUrls.title": "Collected URLs",
"collectedUrls.search": "Search:",
"collectedUrls.url": "URL",
@@ -675,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:",
@@ -752,6 +810,10 @@ 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",
"design.custom.new": "+ New design",
"design.custom.import": "Import design",
@@ -826,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)",
@@ -983,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";