Compare commits

..
Author SHA1 Message Date
Möpchi b856094b48 Merge pull request #19 from VoySpeak/fix/channel-order-and-bans
Fix channel list order and ban feedback, per-identity HWID
2026-11-24 23:21:39 +01:00
Nico B.andClaude Opus 5.5 f67d171001 Fix channel list order and ban feedback, per-identity HWID
- Move-client dialog, permission editor and whisper menu list channels in
  channel-tree order (parent, then its subchannels) instead of a flat sort
  by the per-parent order index or no sort at all.
- A refused banclient now shows an error naming the usual causes; the UI
  logs "Ban requested" instead of claiming the ban succeeded.
- The connector sends a stable HWID derived from the identity's UID instead
  of tsclientlib's built-in one shared by every web user.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 20:57:20 +01:00
MoepchiandClaude Opus 5.5 762554b39d web: center the disconnected/connecting state in the channel tree
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-20 10:34:43 +00:00
MoepchiandClaude Opus 5.5 e96eb62d90 web: friendlier first screen for people without a server
- Connect dialog no longer prefills "localhost" (always rejected on the
  public gateway); empty field with an example placeholder instead.
- Empty channel tree on desktop gets a Connect button and, outside the demo,
  a "No server? Try the demo" link.
- While a connection is being set up the tree shows a spinner,
  "Connecting to <host>…" and a Cancel button instead of "Not connected".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-20 03:39:51 +00:00
MoepchiandClaude Opus 5.5 4afab66d6b Bump tsclientlib: 60 ms minimum audio pre-buffer against jitter wobble
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-14 17:09:38 +00:00
MoepchiandClaude Opus 5.5 e19ced1bd1 Optional Cloudflare Turnstile bot check before connecting
With TURNSTILE_SITE_KEY and TURNSTILE_SECRET set, the gateway answers a
connect without a valid pass with "turnstileRequired". The browser solves
the (usually invisible) check and resends the connect with the token; the
gateway verifies it and hands out a pass bound to the client IP for 12 h,
so reconnects and new tabs skip the check. Off by default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-14 16:50:10 +00:00
MoepchiandClaude Opus 5.5 4e04ddb526 Gateway: log rejected connections over the per-IP limit
Rejections at the WebSocket upgrade (429) were silent, so a client
hammering MAX_CONNECTIONS_PER_IP left no trace. Now logged as a
[ratelimit] line like the connect rate limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
2026-11-14 11:31:54 +00:00
14 changed files with 380 additions and 26 deletions

No files matched your search

+1
View File
@@ -243,6 +243,7 @@ All optional; add them under `environment:` in your compose override next to `PO
| `TURN_URLS` | unset | Comma-separated TURN URLs (e.g. `turn:turn.example.com:3478`) offered to browsers for screen streams, for viewers or publishers behind NATs where direct P2P fails. Pair with `TURN_SECRET` (coturn's `use-auth-secret`; each browser gets its own credential valid for 24 h) or with static `TURN_USERNAME` / `TURN_CREDENTIAL`, which every visitor can read. |
| `ALLOWED_ORIGINS` | unset (any origin) | Comma-separated list of web origins allowed to open `/ws` (e.g. `https://client.example.com`). Stops other websites from silently using your gateway as their relay. |
| `MAX_CONNECTIONS_PER_IP` / `MAX_CONNECTIONS` | `10` / `60` | Concurrent `/ws` connections per client IP and in total (each can hold a live TeamSpeak session). `0` disables a limit. |
| `TURNSTILE_SITE_KEY` / `TURNSTILE_SECRET` | *(unset)* | Optional [Cloudflare Turnstile](https://developers.cloudflare.com/turnstile/) bot check before connecting. With both set, a browser solves the (usually invisible) check once and gets a pass bound to its IP for 12 h. Keeps scripts from opening TeamSpeak connections through your gateway. |
| `CONNECT_RATE_LIMIT` | `30` | Server connects per client IP per minute. Each one starts a new TeamSpeak session, so this stops anyone from flooding a server through your gateway. `0` disables it. |
| `TRUST_PROXY` | off | Only when the gateway is reachable **solely** through a proxy/tunnel, so per-IP limits see the real client instead of the proxy: `cloudflare` (Cloudflare Tunnel or proxy) uses `CF-Connecting-IP`; `1` (your own nginx/Caddy/Traefik) uses the last `X-Forwarded-For` entry, the one your proxy appended. Don't set it on a directly exposed gateway - clients could then fake their IP. |
| `TELEMETRY` | on | Set to `0` to turn off the anonymous usage ping (see below). |
+47 -1
View File
@@ -902,6 +902,29 @@ async fn main() {
}
}
/// Stable per-identity HWID in the TeamSpeak shape (`<32 hex>,<32 hex>`),
/// derived from the identity's UID hash so it survives reconnects.
fn hardware_id_for(uid: &[u8]) -> String {
let hex = |bytes: &[u8]| bytes.iter().map(|b| format!("{b:02x}")).collect::<String>();
let mut padded = uid.to_vec();
padded.resize(20, 0);
format!("{},{}", hex(&padded[..16]), hex(&padded[4..20]))
}
/// Text for a `banclient` the server refused. Permission ids differ between
/// TeamSpeak and TeaSpeak, so the usual causes are named instead of the id.
fn ban_failure_message(e: &tsclientlib::CommandError) -> String {
match e.missing_permission {
Some(perm) => format!(
"Ban failed: missing permission (id {}). Usual causes: a permanent ban (duration 0) \
without unlimited i_client_ban_max_bantime, a duration above it, too little \
i_client_ban_power, or the target has b_client_ignore_bans.",
perm.0
),
None => format!("Ban failed: {e}"),
}
}
/// VoySpeak (formerly 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.
@@ -1015,7 +1038,13 @@ async fn run(args: Args) -> Result<()> {
.and_then(|s| serde_json::from_str::<Identity>(s).ok().or_else(|| Identity::new_from_str(s).ok()))
.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);
// Without this every web user sends tsclientlib's built-in HWID, so a
// hardware-id ban on one web user would lock out all of them.
let hardware_id = hardware_id_for(&identity.key().to_pub().get_uid_no_base64());
let mut con_config = Connection::build(args.address)
.name(args.nickname)
.hardware_id(hardware_id)
.identity(identity);
let server_type = match args.server_type.as_str() {
"teaspeak" => ServerType::Teaspeak,
"teamspeak" => ServerType::Teamspeak,
@@ -2777,6 +2806,14 @@ async fn run(args: Args) -> Result<()> {
} else {
emit(&Event::Error { message: format!("{label} failed: {e}") });
}
} else if label == "Ban client" {
// A rejected ban must be visible: the UI only knows it sent one.
emit(&Event::Error { message: ban_failure_message(&e) });
if e.missing_permission.is_some() {
emit(&Event::ServerLog {
entry: ServerLogEntry::PermissionError { action: label },
});
}
} else if e.missing_permission.is_some() {
emit(&Event::ServerLog {
entry: ServerLogEntry::PermissionError { action: label },
@@ -3311,6 +3348,15 @@ mod tests {
);
}
#[test]
fn hardware_id_is_stable_and_per_identity() {
let a = hardware_id_for(&[1u8; 20]);
assert_eq!(a, hardware_id_for(&[1u8; 20]));
assert_ne!(a, hardware_id_for(&[2u8; 20]));
let (left, right) = a.split_once(',').unwrap();
assert_eq!((left.len(), right.len()), (32, 32));
}
#[test]
fn upload_chunks_assemble_in_order_and_reject_gaps() {
let mut partials = HashMap::new();
+18 -1
View File
@@ -11,6 +11,7 @@ import { handleStore } from "./store.js";
import { handleNewsConfig } from "./news.js";
import { logFeedback, logConnectionEvent } from "./activity-log.js";
import { clientIp, createRateLimiter } from "./net.js";
import { TURNSTILE_ENABLED, TURNSTILE_SITE_KEY, isValidPass, issuePass, verifyToken } from "./turnstile.js";
import "./telemetry.js";
// TeamSpeak 2 support is experimental and opt-in (ENABLE_TS2=1).
@@ -490,7 +491,7 @@ const requestHandler = (req: IncomingMessage, res: ServerResponse) => {
// Same list as the "hello" message, readable before any connect
// (the connect dialog offers TeamSpeak 2 only when it is enabled).
res.writeHead(200, { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", "Cache-Control": "public, max-age=300" });
res.end(JSON.stringify({ features: GATEWAY_FEATURES }));
res.end(JSON.stringify({ features: GATEWAY_FEATURES, ...(TURNSTILE_ENABLED ? { turnstileSiteKey: TURNSTILE_SITE_KEY } : {}) }));
return;
}
if (requestUrl.pathname === "/api/news") {
@@ -583,6 +584,7 @@ const wss = new WebSocketServer({
}
const ip = clientIp(req);
if (MAX_CONNECTIONS_PER_IP > 0 && (connectionsPerIp.get(ip) ?? 0) >= MAX_CONNECTIONS_PER_IP) {
console.warn(`[ratelimit] too many open connections from one IP (limit ${MAX_CONNECTIONS_PER_IP})`);
return done(false, 429, "Too many connections");
}
done(true);
@@ -754,6 +756,21 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
);
break;
}
if (TURNSTILE_ENABLED && !isValidPass(msg.turnstilePass, ip)) {
// No (valid) pass yet: ask the browser to solve the check, it
// resends this connect with the token.
if (msg.turnstileToken === undefined) {
socket.send(JSON.stringify({ type: "turnstileRequired" }));
break;
}
if (!(await verifyToken(msg.turnstileToken, ip))) {
socket.send(
JSON.stringify({ type: "error", code: "turnstile_failed", message: "Bot check failed. Please try again." }),
);
break;
}
socket.send(JSON.stringify({ type: "turnstilePass", pass: issuePass(ip) }));
}
// Replacing a connection on the same socket: tear down the previous
// connector so we don't leak processes.
if (connection) {
+49
View File
@@ -0,0 +1,49 @@
// Optional Cloudflare Turnstile bot check before a "connect". Off unless both
// TURNSTILE_SITE_KEY and TURNSTILE_SECRET are set. A solved check earns a
// signed pass (bound to the client IP, valid PASS_TTL_MS) that later connects
// and silent reconnects present instead, so a real user sees the check at
// most once in that window.
import { createHmac, timingSafeEqual } from "node:crypto";
export const TURNSTILE_SITE_KEY = process.env.TURNSTILE_SITE_KEY ?? "";
const SECRET = process.env.TURNSTILE_SECRET ?? "";
export const TURNSTILE_ENABLED = TURNSTILE_SITE_KEY !== "" && SECRET !== "";
const PASS_TTL_MS = 12 * 60 * 60 * 1000;
// Derived from the secret, so passes survive a gateway restart.
const PASS_KEY = createHmac("sha256", SECRET).update("webspeak3-turnstile-pass").digest();
const sign = (ip: string, expires: number) =>
createHmac("sha256", PASS_KEY).update(`${ip}|${expires}`).digest("base64url");
export function issuePass(ip: string): string {
const expires = Date.now() + PASS_TTL_MS;
return `${expires}.${sign(ip, expires)}`;
}
export function isValidPass(pass: unknown, ip: string): boolean {
if (typeof pass !== "string") return false;
const [exp, mac] = pass.split(".");
const expires = Number(exp);
if (!Number.isFinite(expires) || expires < Date.now() || !mac) return false;
const expected = Buffer.from(sign(ip, expires));
const given = Buffer.from(mac);
return given.length === expected.length && timingSafeEqual(given, expected);
}
export async function verifyToken(token: unknown, ip: string): Promise<boolean> {
if (typeof token !== "string" || token.length === 0 || token.length > 2048) return false;
try {
const res = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", {
method: "POST",
body: new URLSearchParams({ secret: SECRET, response: token, remoteip: ip }),
signal: AbortSignal.timeout(10_000),
});
const data = (await res.json()) as { success?: boolean; "error-codes"?: string[] };
if (!data.success) console.warn(`[turnstile] rejected: ${(data["error-codes"] ?? []).join(",")}`);
return data.success === true;
} catch (err) {
console.warn(`[turnstile] siteverify failed: ${err}`);
return false;
}
}
+53 -4
View File
@@ -2042,6 +2042,50 @@
font-style: italic;
}
/* Disconnected/connecting: centered in the otherwise empty tree panel. */
.ts-tree-panel > .ts-tree-empty:only-child {
box-sizing: border-box;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
}
.ts-tree-empty > button,
.ts-tree-empty > a {
display: block;
margin-top: 0.75rem;
font-style: normal;
}
.ts-tree-empty > .ts-mobile-connect-btn {
flex: none;
min-height: 40px;
padding: 0 1.5rem;
cursor: pointer;
}
.ts-tree-empty-demo {
color: var(--accent);
}
.ts-spinner {
display: inline-block;
width: 0.9em;
height: 0.9em;
vertical-align: -0.1em;
border: 2px solid var(--text-muted);
border-top-color: transparent;
border-radius: 50%;
animation: ts-spin 0.8s linear infinite;
}
@keyframes ts-spin {
to { transform: rotate(360deg); }
}
.ts-tree-list {
list-style: none;
margin: 0;
@@ -5424,10 +5468,6 @@ input.ts-identities-uid {
/* Disconnected: the header already says so, keep the panel calm and centered. */
.ts-app.ts-mobile .ts-tree-panel > .ts-tree-empty:only-child {
height: 100%;
display: flex;
align-items: center;
justify-content: center;
font-style: normal;
font-size: 16px;
color: var(--text-muted);
@@ -5915,3 +5955,12 @@ input.ts-identities-uid {
.ts-app.ts-mobile.ts-design-ide .ts-tree-panel {
max-height: none;
}
/* Cloudflare Turnstile: empty unless Cloudflare wants an interaction. */
.ts-turnstile {
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
z-index: 10000;
}
+138 -19
View File
@@ -236,6 +236,7 @@ import {
} from "./ConnectionTabs";
import { BARE_URL_REGEX, renderBbcode, wrapUrls } from "./lib/bbcode";
import { parseChannelName, spacerDisplayName } from "./lib/spacer";
import { channelsInTreeOrder } from "./lib/channelOrder";
import akimoPhoto from "./assets/akimo.jpg";
import {
applyParkedGatewayEvent,
@@ -401,14 +402,73 @@ function loadServerType(): ServerType {
// The gateway's feature list, readable before connecting. TeamSpeak 2 is
// opt-in per gateway (ENABLE_TS2), so the connect dialog only offers it then.
const FEATURES_URL = DEMO_MODE ? null : FEEDBACK_URL.replace(/\/api\/feedback$/, "/api/features");
let gatewayFeaturesPromise: Promise<string[]> | null = null;
type GatewayInfo = { features?: unknown; turnstileSiteKey?: unknown };
let gatewayInfoPromise: Promise<GatewayInfo> | null = null;
function fetchGatewayInfo(): Promise<GatewayInfo> {
if (!FEATURES_URL) return Promise.resolve({});
gatewayInfoPromise ??= fetch(FEATURES_URL)
.then((r) => (r.ok ? r.json() : {}))
.catch(() => ({}));
return gatewayInfoPromise;
}
function fetchGatewayFeatures(): Promise<string[]> {
if (!FEATURES_URL) return Promise.resolve([]);
gatewayFeaturesPromise ??= fetch(FEATURES_URL)
.then((r) => (r.ok ? r.json() : { features: [] }))
.then((d) => (Array.isArray(d.features) ? d.features : []))
.catch(() => []);
return gatewayFeaturesPromise;
return fetchGatewayInfo().then((d) => (Array.isArray(d.features) ? d.features : []));
}
// Cloudflare Turnstile bot check, only when the gateway asks for it
// ("turnstileRequired"). Invisible for most visitors; the widget only shows
// up when Cloudflare wants an interaction. The gateway then hands out a pass
// (kept here) so later connects and reconnects skip the check.
const TURNSTILE_PASS_KEY = "ws3.turnstilePass";
type TurnstileApi = {
render: (el: HTMLElement, opts: Record<string, unknown>) => string;
remove: (id: string) => void;
};
let turnstileScript: Promise<TurnstileApi> | null = null;
function loadTurnstile(): Promise<TurnstileApi> {
turnstileScript ??= new Promise((resolve, reject) => {
const s = document.createElement("script");
s.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
s.async = true;
s.onload = () => {
const api = (window as unknown as { turnstile?: TurnstileApi }).turnstile;
if (api) resolve(api);
else reject(new Error("turnstile missing"));
};
s.onerror = () => {
turnstileScript = null;
reject(new Error("turnstile blocked"));
};
document.head.appendChild(s);
});
return turnstileScript;
}
async function getTurnstileToken(): Promise<string> {
const { turnstileSiteKey } = await fetchGatewayInfo();
if (typeof turnstileSiteKey !== "string") return "";
try {
const api = await loadTurnstile();
const box = document.createElement("div");
box.className = "ts-turnstile";
document.body.appendChild(box);
return await new Promise<string>((resolve) => {
let id = "";
const done = (token: string) => {
if (id) api.remove(id);
box.remove();
resolve(token);
};
id = api.render(box, {
sitekey: turnstileSiteKey,
appearance: "interaction-only",
callback: done,
"error-callback": () => done(""),
"timeout-callback": () => done(""),
});
});
} catch {
return "";
}
}
/** Everything needed to (re)open a gateway connection for one session, kept
@@ -2273,6 +2333,7 @@ function ConnectDialog({
<input
autoFocus
value={host}
placeholder={t("connect.hostPlaceholder")}
disabled={SERVER_CHOICES.length === 1}
onChange={(e) => onHostChange(e.target.value)}
/>
@@ -4392,7 +4453,7 @@ function MoveClientDialog({
}) {
const t = useT();
const backdrop = useBackdropDismiss(onClose);
const movable = [...channels].sort((a, b) => a.order - b.order);
const movable = channelsInTreeOrder(channels);
return (
<div className="ts-dialog-backdrop" {...backdrop}>
@@ -4410,7 +4471,7 @@ function MoveClientDialog({
<div className="ts-connection-info-loading">{t("moveClient.empty")}</div>
) : (
<ul className="ts-group-assign-list">
{movable.map((ch) => {
{movable.map(({ channel: ch, depth }) => {
const current = ch.id === currentChannelId;
const spacer = spacerDisplayName(ch.name, ch.parent === 0);
const label = spacer.isSpacer
@@ -4422,6 +4483,7 @@ function MoveClientDialog({
className={`ts-menu-item${current ? " ts-group-assign-current" : ""}`}
disabled={current || spacer.isSpacer}
onClick={() => onSelect(ch.id)}
style={depth > 0 ? { paddingLeft: `${depth * 1.25}em` } : undefined}
>
<span className="ts-menu-item-icon">
{current ? "✔️" : spacer.isSpacer ? "➖" : "📁"}
@@ -5065,8 +5127,8 @@ function PermissionsEditorDialog({
))}
{(scope === "channel" || scope === "channelclient") && (
<ul className="ts-perms-editor-list">
{channels.map((c) => (
<li key={c.id}>
{channelsInTreeOrder(channels).map(({ channel: c, depth }) => (
<li key={c.id} style={depth > 0 ? { paddingLeft: `${depth * 1.25}em` } : undefined}>
<button
className={`ts-link-button${channelId === c.id ? " ts-perms-editor-selected" : ""}`}
onClick={() => {
@@ -8893,7 +8955,7 @@ function AppInner() {
const [host, setHost] = useState(
() =>
localStorage.getItem(LAST_HOST_KEY) ??
(DEMO_MODE ? DEMO_HOST : loadDesignTheme() === "nova" ? "" : "localhost")
(DEMO_MODE ? DEMO_HOST : "")
);
const [nickname, setNickname] = useState(
() => localStorage.getItem(LAST_NICKNAME_KEY) ?? (DEMO_MODE ? "Guest" : "")
@@ -9987,10 +10049,17 @@ function AppInner() {
const connectFavoriteId = params.favoriteId;
const connectIdentityBlob = identities.find((i) => i.id === connectIdentityId)?.blob ?? undefined;
const onopen = () => {
logClient("info", "Connection", `Connecting to ${connectHost}…`);
const sendConnect = (extra: Record<string, unknown> = {}) => {
let turnstilePass: string | undefined;
try {
turnstilePass = localStorage.getItem(TURNSTILE_PASS_KEY) ?? undefined;
} catch {
/* storage blocked */
}
socket.send(
JSON.stringify({
...extra,
turnstilePass,
type: "connect",
host: connectHost,
nickname: connectNickname,
@@ -10005,6 +10074,10 @@ function AppInner() {
})
);
};
const onopen = () => {
logClient("info", "Connection", `Connecting to ${connectHost}…`);
sendConnect();
};
// Downloads arrive in pieces (see the connector's TRANSFER_CHUNK_BYTES),
// keyed by channel + path; every piece but the last is a whole number of
@@ -10044,6 +10117,20 @@ function AppInner() {
setTurnServers(Array.isArray(data.iceServers) ? data.iceServers : []);
return;
}
if (data.type === "turnstileRequired") {
void getTurnstileToken().then((turnstileToken) => {
if (socket.readyState === WebSocket.OPEN) sendConnect({ turnstileToken });
});
return;
}
if (data.type === "turnstilePass") {
try {
localStorage.setItem(TURNSTILE_PASS_KEY, String(data.pass));
} catch {
/* storage blocked: the check just runs again next time */
}
return;
}
// Inactive tab: update parked snapshot only (no audio playback).
if (sessionId !== activeSessionIdRef.current) {
@@ -10424,7 +10511,13 @@ function AppInner() {
appendLog({ text: data.message, kind: "error" });
} else {
setConnecting(false);
setConnectError(data.code === "gateway_full" ? t("connectError.gatewayFull") : data.message);
setConnectError(
data.code === "gateway_full"
? t("connectError.gatewayFull")
: data.code === "turnstile_failed"
? t("connectError.botCheck")
: data.message
);
updateTabMeta(sessionId, { connecting: false, connected: false });
}
break;
@@ -12636,7 +12729,8 @@ function AppInner() {
reason: banReason,
})
);
logClient("info", "Moderation", `Banned ${banTarget.name}`);
// Only a request: the server may still refuse it (an error event follows then).
logClient("info", "Moderation", `Ban requested for ${banTarget.name}`);
setBanTarget(null);
setBanReason("");
setBanSeconds("0");
@@ -13412,8 +13506,12 @@ function AppInner() {
{whisperMenuOpen && (
<div className="ts-menu ts-menu-away" ref={focusFirstItem} onKeyDown={handleMenuKeyDown}>
<div className="ts-context-menu-title">{t("whisper.channels")}</div>
{channels.map((ch) => (
<label key={ch.id} className="ts-menu-item">
{channelsInTreeOrder(channels).map(({ channel: ch, depth }) => (
<label
key={ch.id}
className="ts-menu-item"
style={depth > 0 ? { paddingLeft: `${depth * 1.25}em` } : undefined}
>
<input
type="checkbox"
checked={whisperChannelIds.has(ch.id)}
@@ -14636,7 +14734,28 @@ function AppInner() {
/>
</>
) : (
<div className="ts-tree-empty">{t("tree.notConnected")}</div>
<div className="ts-tree-empty">
{connecting ? (
<>
<span className="ts-spinner" aria-hidden="true" /> {t("tree.connectingTo", { host })}
<button onClick={handleDisconnect}>{t("connect.cancel")}</button>
</>
) : (
<>
{t("tree.notConnected")}
{!mobile && (
<button className="ts-mobile-connect-btn" onClick={() => setConnectDialogOpen(true)}>
{t("menu.connections.connect")}
</button>
)}
{!DEMO_MODE && (
<a className="ts-tree-empty-demo" href="https://demo.webspeak3.de" target="_blank" rel="noreferrer">
{t("tree.tryDemo")}
</a>
)}
</>
)}
</div>
)}
</div>
+49
View File
@@ -0,0 +1,49 @@
/** Minimal shape needed to lay channels out like the channel tree. */
export interface OrderedChannelLike {
id: number;
parent: number;
/** Position among the siblings of the same parent (not a global index). */
order: number;
}
/**
* Flattens channels in channel-tree order: each parent is followed by its
* subchannels (recursively), siblings sorted by `order`. `order` is only
* meaningful between siblings, so a flat sort by it interleaves the levels.
* Channels whose parent is missing are appended at the end as roots.
*/
export function channelsInTreeOrder<T extends OrderedChannelLike>(
channels: readonly T[],
): { channel: T; depth: number }[] {
const byParent = new Map<number, T[]>();
for (const ch of channels) {
const list = byParent.get(ch.parent);
if (list) list.push(ch);
else byParent.set(ch.parent, [ch]);
}
for (const list of byParent.values()) list.sort((a, b) => a.order - b.order || a.id - b.id);
const out: { channel: T; depth: number }[] = [];
const seen = new Set<number>();
const walk = (parent: number, depth: number) => {
for (const ch of byParent.get(parent) ?? []) {
if (seen.has(ch.id)) continue;
seen.add(ch.id);
out.push({ channel: ch, depth });
walk(ch.id, depth + 1);
}
};
walk(0, 0);
// Orphans (parent not in the list) and anything in a parent cycle.
for (const ch of channels) {
if (seen.has(ch.id)) continue;
const orphanParent = ch.parent;
for (const sibling of byParent.get(orphanParent) ?? []) {
if (seen.has(sibling.id)) continue;
seen.add(sibling.id);
out.push({ channel: sibling, depth: 0 });
walk(sibling.id, 1);
}
}
return out;
}
+4
View File
@@ -112,6 +112,7 @@
"connect.title": "Připojit",
"connect.novaSubtitle": "WebSpeak3 běží celý v prohlížeči — není potřeba nic stahovat",
"connect.serverAddress": "Přezdívka nebo adresa serveru:",
"connect.hostPlaceholder": "např. ts.example.com:9987",
"connect.serverPassword": "Heslo serveru:",
"connect.nickname": "Přezdívka:",
"connect.phoneticNickname": "Fonetická přezdívka:",
@@ -476,6 +477,8 @@
"tree.search": "Hledat kanály a uživatele",
"tree.label": "Kanály",
"tree.notConnected": "Nepřipojeno",
"tree.connectingTo": "Připojování k {host}…",
"tree.tryDemo": "Nemáte server? Vyzkoušejte demo",
"tree.clickToSelect": "Kliknutím vyberete, dvojklikem se připojíte",
"tree.clickToJoin": "Dvojklikem se připojíte",
"tree.joinNotConnected": "Nepřipojeno — nelze přepnout kanál",
@@ -718,6 +721,7 @@
"serverContext.disconnect": "Odpojit",
"connectError.dismiss": "Zavřít",
"connectError.gatewayFull": "Brána je právě plná. Zkus to za pár minut znovu – nebo si WebSpeak3 hostuj sám: github.com/WebSpeak3/webspeak3",
"connectError.botCheck": "Kontrola proti botům selhala. Obnov stránku a zkus to znovu. Blokátory reklam nebo skriptů mohou kontrole bránit.",
"dialog.close": "Zavřít",
"sounds.title": "Zvuky",
"sounds.subtitle": "Nastavit zvuková upozornění na události",
+4
View File
@@ -112,6 +112,7 @@
"connect.title": "Verbinden",
"connect.novaSubtitle": "WebSpeak3 läuft komplett im Browser — kein Download nötig",
"connect.serverAddress": "Server Nickname oder Adresse:",
"connect.hostPlaceholder": "z. B. ts.beispiel.de:9987",
"connect.serverPassword": "Server Passwort:",
"connect.nickname": "Nickname:",
"connect.phoneticNickname": "Phonetischer Nickname:",
@@ -476,6 +477,8 @@
"tree.search": "Kanäle und Nutzer suchen",
"tree.label": "Kanäle",
"tree.notConnected": "Nicht verbunden",
"tree.connectingTo": "Verbinde mit {host}…",
"tree.tryDemo": "Kein Server? Probier die Demo",
"tree.clickToSelect": "Klicken zum Auswählen, Doppelklick zum Beitreten",
"tree.clickToJoin": "Doppelklick zum Beitreten",
"tree.joinNotConnected": "Nicht verbunden — Channel-Wechsel nicht möglich",
@@ -718,6 +721,7 @@
"serverContext.disconnect": "Verbindung trennen",
"connectError.dismiss": "Schließen",
"connectError.gatewayFull": "Das Gateway ist gerade voll. Versuch es in ein paar Minuten nochmal – oder hoste WebSpeak3 selbst: github.com/WebSpeak3/webspeak3",
"connectError.botCheck": "Bot-Prüfung fehlgeschlagen. Bitte lade die Seite neu und versuch es noch mal. Werbe- oder Skriptblocker können die Prüfung stören.",
"dialog.close": "Schließen",
"sounds.title": "Sounds",
"sounds.subtitle": "Sound-Benachrichtigungen für Ereignisse festlegen",
+4
View File
@@ -112,6 +112,7 @@
"connect.title": "Connect",
"connect.novaSubtitle": "WebSpeak3 runs entirely in the browser — no download needed",
"connect.serverAddress": "Server nickname or address:",
"connect.hostPlaceholder": "e.g. ts.example.com:9987",
"connect.serverPassword": "Server password:",
"connect.nickname": "Nickname:",
"connect.phoneticNickname": "Phonetic nickname:",
@@ -476,6 +477,8 @@
"tree.search": "Search channels and users",
"tree.label": "Channels",
"tree.notConnected": "Not connected",
"tree.connectingTo": "Connecting to {host}…",
"tree.tryDemo": "No server? Try the demo",
"tree.clickToSelect": "Click to select, double-click to join",
"tree.clickToJoin": "Double-click to join",
"tree.joinNotConnected": "Not connected — cannot switch channel",
@@ -718,6 +721,7 @@
"serverContext.disconnect": "Disconnect",
"connectError.dismiss": "Dismiss",
"connectError.gatewayFull": "The gateway is full right now. Try again in a few minutes – or host WebSpeak3 yourself: github.com/WebSpeak3/webspeak3",
"connectError.botCheck": "Bot check failed. Please reload the page and try again. Ad or script blockers can get in the way of the check.",
"dialog.close": "Close",
"sounds.title": "Sounds",
"sounds.subtitle": "Configure sound notifications for events",
+4
View File
@@ -112,6 +112,7 @@
"connect.title": "اتصال",
"connect.novaSubtitle": "WebSpeak3 به‌طور کامل در مرورگر اجرا می‌شود — بدون نیاز به دانلود",
"connect.serverAddress": "نام مستعار یا آدرس سرور:",
"connect.hostPlaceholder": "مثلاً ts.example.com:9987",
"connect.serverPassword": "رمز عبور سرور:",
"connect.nickname": "نام مستعار:",
"connect.phoneticNickname": "تلفظ نام مستعار:",
@@ -475,6 +476,8 @@
"tree.search": "جستجوی کانال‌ها و کاربران",
"tree.label": "کانال‌ها",
"tree.notConnected": "متصل نیست",
"tree.connectingTo": "در حال اتصال به {host}…",
"tree.tryDemo": "سروری ندارید؟ دمو را امتحان کنید",
"tree.clickToSelect": "برای انتخاب کلیک کن، برای ورود دوبار کلیک کن",
"tree.clickToJoin": "برای ورود دوبار کلیک کن",
"tree.joinNotConnected": "متصل نیست — نمی‌توان کانال را تغییر داد",
@@ -717,6 +720,7 @@
"serverContext.disconnect": "قطع اتصال",
"connectError.dismiss": "رد کردن",
"connectError.gatewayFull": "گیت‌وی در حال حاضر پر است. چند دقیقه دیگر دوباره امتحان کنید – یا WebSpeak3 را خودتان میزبانی کنید: github.com/WebSpeak3/webspeak3",
"connectError.botCheck": "بررسی ضد ربات ناموفق بود. لطفاً صفحه را دوباره بارگذاری کنید و دوباره امتحان کنید. مسدودکننده‌های تبلیغات یا اسکریپت ممکن است مانع بررسی شوند.",
"dialog.close": "بستن",
"sounds.title": "صداها",
"sounds.subtitle": "پیکربندی اعلان‌های صوتی برای رویدادها",
+4
View File
@@ -112,6 +112,7 @@
"connect.title": "Подключение",
"connect.novaSubtitle": "WebSpeak3 работает полностью в браузере — ничего скачивать не нужно",
"connect.serverAddress": "Имя или адрес сервера:",
"connect.hostPlaceholder": "например, ts.example.com:9987",
"connect.serverPassword": "Пароль сервера:",
"connect.nickname": "Никнейм:",
"connect.phoneticNickname": "Фонетический никнейм:",
@@ -476,6 +477,8 @@
"tree.search": "Поиск каналов и пользователей",
"tree.label": "Каналы",
"tree.notConnected": "Нет подключения",
"tree.connectingTo": "Подключение к {host}…",
"tree.tryDemo": "Нет сервера? Попробуйте демо",
"tree.clickToSelect": "Щелчок – выбрать, двойной щелчок – войти",
"tree.clickToJoin": "Двойной щелчок – войти",
"tree.joinNotConnected": "Нет подключения — нельзя сменить канал",
@@ -718,6 +721,7 @@
"serverContext.disconnect": "Отключиться",
"connectError.dismiss": "Закрыть",
"connectError.gatewayFull": "Шлюз сейчас переполнен. Попробуйте через несколько минут – или разверните WebSpeak3 у себя: github.com/WebSpeak3/webspeak3",
"connectError.botCheck": "Проверка на бота не пройдена. Обновите страницу и попробуйте снова. Блокировщики рекламы или скриптов могут мешать проверке.",
"dialog.close": "Закрыть",
"sounds.title": "Звуки",
"sounds.subtitle": "Настройка звуковых уведомлений о событиях",
+4
View File
@@ -56,6 +56,7 @@
"away.setGlobalStatus": "设置全局离开状态",
"connect.title": "连接",
"connect.serverAddress": "服务器昵称或地址:",
"connect.hostPlaceholder": "例如 ts.example.com:9987",
"connect.serverPassword": "服务器密码:",
"connect.nickname": "昵称:",
"connect.phoneticNickname": "昵称读音:",
@@ -368,6 +369,8 @@
"tree.search": "搜索频道和用户",
"tree.label": "频道",
"tree.notConnected": "未连接",
"tree.connectingTo": "正在连接到 {host}…",
"tree.tryDemo": "没有服务器?试试演示版",
"tree.clickToSelect": "单击选择,双击加入",
"tree.clickToJoin": "双击加入",
"tree.joinNotConnected": "未连接 — 无法切换频道",
@@ -559,6 +562,7 @@
"serverContext.disconnect": "断开连接",
"connectError.dismiss": "关闭",
"connectError.gatewayFull": "网关当前已满。请几分钟后再试,或自行部署 WebSpeak3:github.com/WebSpeak3/webspeak3",
"connectError.botCheck": "人机验证失败。请刷新页面后重试。广告或脚本拦截器可能会干扰验证。",
"dialog.close": "关闭",
"sounds.title": "声音",
"sounds.subtitle": "配置事件提示音",