import { useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { useRegisterSW } from "virtual:pwa-register/react"; import "./App.css"; const FOCUSABLE = 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'; /** Props for a modal dialog's backdrop. Dismisses on Escape or a genuine * backdrop click (not a text-selection drag that starts inside the dialog * and releases over the backdrop). Moves focus in on open unless an * autoFocus field already took it, keeps Tab inside, and hands focus back to * whatever had it before on close. */ function useBackdropDismiss(onDismiss: () => void) { const mouseDownOnBackdrop = useRef(false); const ref = useRef(null); useEffect(() => { const previous = document.activeElement as HTMLElement | null; const el = ref.current; if (el && !el.contains(document.activeElement)) el.querySelector(FOCUSABLE)?.focus(); return () => previous?.focus?.(); }, []); return { ref, role: "dialog", "aria-modal": true, onKeyDown: (e: React.KeyboardEvent) => { if (e.key === "Escape") { e.stopPropagation(); onDismiss(); return; } if (e.key !== "Tab") return; const items = [...e.currentTarget.querySelectorAll(FOCUSABLE)]; if (items.length === 0) return; const first = items[0]; const last = items[items.length - 1]; if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); } else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); } }, onMouseDown: (e: React.MouseEvent) => { mouseDownOnBackdrop.current = e.target === e.currentTarget; }, onClick: (e: React.MouseEvent) => { if (mouseDownOnBackdrop.current && e.target === e.currentTarget) onDismiss(); }, }; } import { AudioPlayer, MicCapture, SAMPLE_RATE, encodeWavStereo, hasNativeOutputPicker, listAudioInputDevices, listAudioOutputDevices, pickAudioOutputDevice, } from "./voice"; import { createAec3, type Aec3Instance } from "./aec3"; import { LanguageProvider, useLanguage, useT, type LangPref } from "./i18n"; import { StreamAccess, StreamMode, StreamPublisher, type PublishState, type StreamPublishOptions, } from "./publish"; import { DEFAULT_ICE_SERVERS, StreamViewer, parseStreamInfo, type StreamEvent, type StreamInfo } from "./stream"; import { DEMO_HOST, DEMO_MODE, DemoSocket } from "./demoMode"; import { SOUND_EVENTS, clearCustomSound, loadCustomSound, loadEventSoundEnabled, loadSoundsEnabled, loadSoundsVolume, playSound, saveCustomSound, saveEventSoundEnabled, saveSoundsEnabled, saveSoundsVolume, setSoundsOutputDevice, type SoundEventId, } from "./sounds"; import { parseSoundpack } from "./soundpack"; import { GREENTEASPEAK_THEME_ID, GreenteaSpeakChrome, isGreenteaSpeakTheme, } from "./themes/greenteaspeak"; import { parseChannelName, spacerDisplayName } from "./lib/spacer"; import { applyParkedGatewayEvent, emptyParkedState, sessionLabel, type ParkedSessionState, type SessionRecord, type SessionTabInfo, } from "./connectionSessions"; // In dev, the gateway runs standalone on its own port. In production it's // normally served from the same origin/port as the web app (single // container behind a reverse proxy), so the WebSocket URL is derived from // the current location by default. If the static frontend is hosted // separately from the gateway (e.g. a static host for the landing/app // bundle, with the gateway staying on your own server), set // VITE_GATEWAY_URL at build time to the gateway's public wss:// address // instead - the browser will still block a plain ws:// gateway from an // https:// page (mixed content), so that address needs real TLS. // Either way the gateway's WebSocketServer only listens on /ws (see // gateway/src/index.ts), so that path always gets appended here - a // VITE_GATEWAY_URL override only needs to name the host, not the path. const GATEWAY_URL = import.meta.env.DEV ? "ws://localhost:8080/ws" : import.meta.env.VITE_GATEWAY_URL ? `${import.meta.env.VITE_GATEWAY_URL.replace(/\/$/, "")}/ws` : `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.host}/ws`; // Same derivation as GATEWAY_URL above, but for a plain HTTP POST (the // feedback form) instead of the WebSocket - see gateway/src/index.ts's // /api/feedback handler. VITE_GATEWAY_URL names a WebSocket origin, so its // scheme has to be mapped back to http(s) here: fetch() refuses anything // else outright ("TypeError: unknown scheme"), so with VITE_GATEWAY_URL set // the form could not submit at all. const FEEDBACK_URL = import.meta.env.DEV ? "http://localhost:8080/api/feedback" : import.meta.env.VITE_GATEWAY_URL ? `${import.meta.env.VITE_GATEWAY_URL.replace(/\/$/, "").replace(/^ws(s?):\/\//, "http$1://")}/api/feedback` : `${window.location.protocol}//${window.location.host}/api/feedback`; // Unlike GATEWAY_URL/FEEDBACK_URL above, the design store is NOT per-instance: // it's a single, centrally curated catalog run on the maintainer's own VPS // (see gateway/src/store.ts), so every build - official and self-hosted // Docker image alike - points at the same one by default, regardless of // which TS3/TeaSpeak gateway that build otherwise talks to. A self-hoster who // wants to run their own separate community store instead (their own // gateway's STORE_ENABLED=1) can override with VITE_STORE_URL at build time. // DEMO_MODE keeps the old same-origin derivation instead, which 404s on the // static demo host - the public demo has no write access to the real store. const STORE_URL = import.meta.env.DEV ? "http://localhost:8080/api/store/themes" : DEMO_MODE ? `${window.location.protocol}//${window.location.host}/api/store/themes` : import.meta.env.VITE_STORE_URL || "https://gateway.webspeak3.de/api/store/themes"; // Ko-fi page of the project (.github/FUNDING.yml). Unlike the feedback button // below this is not limited to the maintainer's own instance: it ships in // every build, the Docker image included. Self-hosters who would rather not // carry someone else's donation link can build with VITE_DONATE_URL= (empty) // to drop the button, or point it somewhere else. const DONATE_URL = import.meta.env.VITE_DONATE_URL ?? "https://ko-fi.com/moepchi"; // This file's frontend is deployed as multiple Cloudflare Pages projects // from the same repo/build (see mem:deployment) - only the maintainer's own // production instance talks to a gateway they actually operate and read // feedback from, so the "Feedback" menu entry only appears there. Every // other deployment (self-hosted forks, and the public demo - which has no // real gateway at all, see DEMO_MODE) simply never shows it. This is a UI // nicety, not a security boundary: the gateway's own FEEDBACK_ENABLED // opt-in (see gateway/src/index.ts) is what actually decides whether // submissions are accepted at all. const OWN_HOSTED_HOSTNAMES = new Set(["client.webspeak3.de"]); const IS_OWN_HOSTED_INSTANCE = !DEMO_MODE && OWN_HOSTED_HOSTNAMES.has(window.location.hostname); // Auto-connect from a share link (?connect=host[:port]&nickname=&channel=&token=, // see GitHub issue #10). Parsed once at module load and immediately stripped // from the URL via replaceState so a reload/refresh doesn't silently // reconnect off a stale link sitting in the address bar or browser history. const AUTO_CONNECT_FROM_URL = (() => { const params = new URLSearchParams(window.location.search); // The token may also sit in the fragment (#token=...), which - unlike the // query - never reaches server logs or Referer headers. const hashParams = new URLSearchParams(window.location.hash.slice(1)); const connectHost = params.get("connect"); if (!connectHost) return null; const target = { host: connectHost, nickname: params.get("nickname") || undefined, defaultChannel: params.get("channel") || undefined, privilegeKey: hashParams.get("token") || params.get("token") || undefined, }; for (const key of ["connect", "nickname", "channel", "token"]) params.delete(key); let hash = window.location.hash; if (hashParams.has("token")) { hashParams.delete("token"); hash = hashParams.size ? `#${hashParams}` : ""; } const rest = params.toString(); window.history.replaceState(null, "", window.location.pathname + (rest ? `?${rest}` : "") + hash); return target; })(); // A self-hosted build can also bake in a default server so the page // auto-connects with zero URL params at all - set via `docker compose build // --build-arg DEFAULT_SERVER=...` (see Dockerfile/README) or plain // VITE_DEFAULT_SERVER= at build time. The Docker image can set the same thing // at runtime instead (DEFAULT_SERVER/DEFAULT_CHANNEL env vars, issue #12): the // gateway passes them in as tags, which take precedence over the build // values. AUTO_CONNECT_FROM_URL above always wins when a share link is present. const runtimeConfig = (name: string) => document.querySelector(`meta[name="webspeak3-${name}"]`)?.content; const DEFAULT_SERVER = runtimeConfig("default-server") || import.meta.env.VITE_DEFAULT_SERVER || null; const DEFAULT_CHANNEL = runtimeConfig("default-channel") || import.meta.env.VITE_DEFAULT_CHANNEL || ""; // Terms of use, own-hosted instance only (see TODO.md #2/#7.1). Versioned so // a rule change can re-surface the modal: bump TOS_VERSION and everyone who // accepted an older version is asked again. const TOS_VERSION = "v1"; const TOS_KEY = "webspeak3-tos-accepted"; function hasAcceptedToS(): boolean { return (localStorage.getItem(TOS_KEY) ?? "").startsWith(TOS_VERSION + ":"); } // One-time migration from the pre-rename "ts-web-client:*" localStorage // namespace so existing users don't lose their favorites/preferences. (function migrateLegacyStorageKeys() { const oldPrefix = "ts-web-client:"; const newPrefix = "webspeak3:"; for (const oldKey of Object.keys(localStorage).filter((k) => k.startsWith(oldPrefix))) { const newKey = newPrefix + oldKey.slice(oldPrefix.length); if (localStorage.getItem(newKey) === null) { localStorage.setItem(newKey, localStorage.getItem(oldKey)!); } localStorage.removeItem(oldKey); } })(); const LAST_HOST_KEY = "webspeak3:last-host"; const LAST_NICKNAME_KEY = "webspeak3:last-nickname"; // Privilege keys are one-shot grants, so they're no longer remembered across // reloads; drop what older versions stored in plain text. localStorage.removeItem("webspeak3:last-privilege-key"); const LAST_SERVER_TYPE_KEY = "webspeak3:last-server-type"; type ServerType = "teamspeak" | "teaspeak" | "auto"; function loadServerType(): ServerType { const raw = localStorage.getItem(LAST_SERVER_TYPE_KEY); return raw === "teamspeak" || raw === "teaspeak" || raw === "auto" ? raw : "auto"; } /** Everything needed to (re)open a gateway connection for one session, kept * around per session id so a dropped socket β€” active tab or a parked * background one β€” can be silently reconnected. */ type ConnectParams = { host: string; nickname: string; serverPassword: string; channelPassword: string; defaultChannel: string; privilegeKey: string; serverType: ServerType; identityId: string | null; favoriteId: string | null; }; /** Identity persisted across sessions so the server sees the same client UID * each time, instead of a fresh one being generated per connection. */ const IDENTITY_KEY = "webspeak3:identity"; const IDENTITIES_KEY = "webspeak3:identities"; const ACTIVE_IDENTITY_KEY = "webspeak3:active-identity"; interface Identity { id: string; name: string; /** Per-identity nickname/phonetic nickname, like the native client - selecting * an identity in the connect dialog fills these in. Empty until first set. */ nickname: string; phoneticName: string; /** Opaque tsclientlib identity blob - null until the first successful connect generates one. */ blob: string | null; } // randomId() only exists in a secure context, so it is missing on a // plain-http origin - which is exactly how a self-hosted instance is reached // on a LAN before TLS is set up. It used to throw at module load and leave a // blank page; these ids are local identifiers, not secrets, so fall back. function randomId(): string { if (typeof crypto.randomUUID === "function") return crypto.randomUUID(); const bytes = new Uint8Array(16); crypto.getRandomValues(bytes); bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80; const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join(""); return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; } // One-time migration from the old single flat identity key to a list of named // identities (so users can maintain more than one persona), and to seed a // default entry for users who never had one either. Runs once at module load. (function ensureIdentitiesSeeded() { if (localStorage.getItem(IDENTITIES_KEY) !== null) return; const legacyBlob = localStorage.getItem(IDENTITY_KEY); const legacyNickname = localStorage.getItem(LAST_NICKNAME_KEY) ?? ""; const id = randomId(); const identities: Identity[] = [ { id, name: "Standard", nickname: legacyNickname, phoneticName: "", blob: legacyBlob }, ]; localStorage.setItem(IDENTITIES_KEY, JSON.stringify(identities)); localStorage.setItem(ACTIVE_IDENTITY_KEY, id); localStorage.removeItem(IDENTITY_KEY); })(); function loadIdentities(): Identity[] { try { const raw = localStorage.getItem(IDENTITIES_KEY); const parsed = raw ? (JSON.parse(raw) as Partial[]) : []; if (parsed.length > 0) { // Backfill fields older saves (before per-identity nickname/phonetic // name existed) don't have. return parsed.map((i) => ({ id: i.id ?? randomId(), name: i.name ?? "Standard", nickname: i.nickname ?? "", phoneticName: i.phoneticName ?? "", blob: i.blob ?? null, })); } } catch { // fall through } return [{ id: randomId(), name: "Standard", nickname: "", phoneticName: "", blob: null }]; } const FAVORITES_KEY = "webspeak3:favorites"; const INPUT_DEVICE_KEY = "webspeak3:input-device"; const PLAYBACK_VOLUME_KEY = "webspeak3:playback-volume"; const NOISE_SUPPRESSION_KEY = "webspeak3:noise-suppression"; const ECHO_CANCELLATION_KEY = "webspeak3:echo-cancellation"; const AUTO_GAIN_CONTROL_KEY = "webspeak3:auto-gain-control"; const AEC3_ENABLED_KEY = "webspeak3:aec3-enabled"; const VAD_HANGOVER_KEY = "webspeak3:vad-hangover"; const DESIGN_THEME_KEY = "webspeak3:design-theme"; // The user's actual pick - "standard" | "nova" | "greenteaspeak" | "custom:". // DESIGN_THEME_KEY above keeps tracking just the resolved structural base, since a // couple of early call sites (e.g. the host-field default below) need that cheaply, // before customThemes is loaded. const DESIGN_SELECTION_KEY = "webspeak3:design-selection"; const CUSTOM_THEMES_KEY = "webspeak3:custom-themes"; type DesignTheme = "standard" | "nova" | "greenteaspeak" | "pulse"; /** A user-authored theme package: a name, which built-in layout it behaves like * (Standard's plain chrome, Nova's collapsed menu/splash, GreenTeaSpeak shell, * or Pulse's card/sidebar layout), and raw CSS that gets injected while it's * active - free-form, so it can restyle or even reflow the existing markup * (e.g. via flex `order`, `display:none`, overlays). */ type CustomTheme = { id: string; name: string; baseTheme: DesignTheme; css: string; }; /** Metadata for one theme listed by GET /api/store/themes - deliberately * without `css`, so browsing the store doesn't pull every submission's full * stylesheet up front. The full package (matching CustomTheme's export * shape) is fetched separately per-id on install, see STORE_URL above. */ type StoreThemeSummary = { id: string; name: string; baseTheme: DesignTheme; author: string; description: string; hasScreenshot: boolean; rating: { average: number; count: number }; createdAt: string; }; // The operator's own admin token for publishing under a reserved author name // (see STORE_RESERVED_AUTHORS in gateway/src/index.ts) - kept in localStorage // so it only has to be entered once per browser, same idea as the last-used // connection fields above. const STORE_ADMIN_TOKEN_KEY = "webspeak3:store-admin-token"; // Mirrors the gateway's STORE_SCREENSHOT_MAX_DATA_URL_LENGTH - checked client-side // too so a rejected upload doesn't cost a round trip. const STORE_SCREENSHOT_MAX_DATA_URL_LENGTH = 400_000; function isDesignTheme(value: string): value is DesignTheme { return value === "standard" || value === "nova" || value === "greenteaspeak" || value === "pulse"; } function loadDesignTheme(): DesignTheme { const raw = localStorage.getItem(DESIGN_THEME_KEY); if (raw && isDesignTheme(raw)) return raw; return "standard"; } function resolveDesignThemeBase(selection: string, customThemes: CustomTheme[]): DesignTheme { if (selection.startsWith("custom:")) { return customThemes.find((th) => `custom:${th.id}` === selection)?.baseTheme ?? "standard"; } return isDesignTheme(selection) ? selection : "standard"; } function designThemeClassName(theme: DesignTheme): string { if (theme === "nova") return " ts-design-nova"; if (theme === "pulse") return " ts-design-pulse"; if (isGreenteaSpeakTheme(theme)) return " ts-design-greenteaspeak"; return ""; } function designThemeLabel(theme: DesignTheme, t: (key: string) => string): string { if (theme === "nova") return t("design.theme.nova"); if (theme === "greenteaspeak") return t("design.theme.greenteaspeak"); if (theme === "pulse") return t("design.theme.pulse"); return t("design.theme.standard"); } function loadCustomThemes(): CustomTheme[] { try { const raw = localStorage.getItem(CUSTOM_THEMES_KEY); if (!raw) return []; const parsed = JSON.parse(raw); if (!Array.isArray(parsed)) return []; return parsed.filter( (v): v is CustomTheme => v && typeof v.id === "string" && typeof v.name === "string" && isDesignTheme(v.baseTheme) && typeof v.css === "string" ); } catch { return []; } } function saveCustomThemes(list: CustomTheme[]) { localStorage.setItem(CUSTOM_THEMES_KEY, JSON.stringify(list)); } function loadDesignSelection(): string { return localStorage.getItem(DESIGN_SELECTION_KEY) ?? loadDesignTheme(); } function loadBoolPref(key: string, fallback: boolean): boolean { const raw = localStorage.getItem(key); return raw === null ? fallback : raw === "1"; } function loadNumberPref(key: string, fallback: number): number { const raw = localStorage.getItem(key); const parsed = raw === null ? NaN : Number(raw); return Number.isFinite(parsed) ? parsed : fallback; } interface Favorite { id: string; bookmarkName: string; nickname: string; host: string; serverPassword: string; defaultChannel: string; defaultChannelPassword: string; /** When true, ServerQuery clients appear in the channel tree. Default: false. */ showServerQueryClients: boolean; } function normalizeFavorite(raw: Partial & Pick): Favorite { return { id: raw.id, bookmarkName: typeof raw.bookmarkName === "string" ? raw.bookmarkName : "", nickname: typeof raw.nickname === "string" ? raw.nickname : "", host: typeof raw.host === "string" ? raw.host : "", serverPassword: typeof raw.serverPassword === "string" ? raw.serverPassword : "", defaultChannel: typeof raw.defaultChannel === "string" ? raw.defaultChannel : "", defaultChannelPassword: typeof raw.defaultChannelPassword === "string" ? raw.defaultChannelPassword : "", showServerQueryClients: raw.showServerQueryClients === true, }; } function loadFavorites(): Favorite[] { try { const raw = localStorage.getItem(FAVORITES_KEY); if (!raw) return []; const parsed = JSON.parse(raw); if (!Array.isArray(parsed)) return []; return parsed .filter((v): v is Partial & Pick => v && typeof v.id === "string") .map(normalizeFavorite); } catch { return []; } } // Only Chromium hands out tab/system audio via getDisplayMedia; Firefox and // Safari return video only, so the button would just say "no audio" there. // userAgentData itself only exists in Chromium-based browsers. // Switched off for now (2026-10-03): clicks in the mix, and Edge delivers // Windows system audio as silence. Code stays; flip back once that's solved. const TAB_AUDIO_SUPPORTED = false && typeof navigator.mediaDevices?.getDisplayMedia === "function" && !!(navigator as Navigator & { userAgentData?: { brands: { brand: string }[] } }).userAgentData?.brands.some( (b) => b.brand === "Chromium" ); const AWAY_PRESETS_KEY = "webspeak3:away-presets"; /** "off" hides the server banner: it loads from whatever host the server * admin picked, which then sees the viewer's IP (review S12). */ const SERVER_BANNER_KEY = "webspeak3:server-banner"; const DISCONNECT_MESSAGE_KEY = "webspeak3:disconnect-message"; const COLLECTED_URLS_KEY = "webspeak3:collected-urls"; interface CollectedUrl { url: string; count: number; lastSeen: number; lastSender: string; } function loadCollectedUrls(): CollectedUrl[] { try { const raw = localStorage.getItem(COLLECTED_URLS_KEY); return raw ? (JSON.parse(raw) as CollectedUrl[]) : []; } catch { return []; } } const URL_REGEX = /https?:\/\/[^\s<>"]+/g; type LogLevel = "critical" | "error" | "warning" | "info" | "debug"; interface ClientLogEntry { id: number; timestamp: number; category: string; level: LogLevel; message: string; } const LOG_LEVELS: LogLevel[] = ["critical", "error", "warning", "info", "debug"]; const MAX_LOG_ENTRIES = 500; interface WhisperLogEntry { id: number; timestamp: number; description: string; } interface BanListEntry { banId: number; ip: string; name: string; uid: string; lastNickname: string; created: string; durationSecs: number; invokerName: string; reason: string; enforcements: number; } interface ComplainListEntry { targetClientDbId: number; targetName: string; fromClientDbId: number; fromName: string; message: string; timestamp: string; } interface OfflineMessageListEntry { messageId: number; clientUid: string; subject: string; timestamp: string; isRead: boolean; } type ContactCategory = "acquaintance" | "blocked" | "friend"; interface Contact { uid: string; customName: string; category: ContactCategory; phoneticName: string; ignored: boolean; } const CONTACTS_KEY = "webspeak3:contacts"; // Per-speaker playback volume by client UID (1 = unchanged), mixed in the // connector. Keyed by UID so it follows a person across servers and reconnects. const CLIENT_VOLUMES_KEY = "webspeak3:client-volumes"; function loadClientVolumes(): Record { try { const raw = localStorage.getItem(CLIENT_VOLUMES_KEY); return raw ? (JSON.parse(raw) as Record) : {}; } catch { return {}; } } function loadContacts(): Contact[] { try { const raw = localStorage.getItem(CONTACTS_KEY); return raw ? (JSON.parse(raw) as Contact[]) : []; } catch { return []; } } interface MessagePreset { name: string; message: string; } /** A saved whisper target selection. Channels/clients are matched by name when * activated (rather than by id), since ids are only stable for the current * connection - the same names are what a user would recognize across sessions. */ interface WhisperList { id: string; name: string; channelNames: string[]; clientNames: string[]; } const WHISPER_LISTS_KEY = "webspeak3:whisper-lists"; function loadWhisperLists(): WhisperList[] { try { const raw = localStorage.getItem(WHISPER_LISTS_KEY); return raw ? (JSON.parse(raw) as WhisperList[]) : []; } catch { return []; } } function loadAwayPresets(): MessagePreset[] { try { const raw = localStorage.getItem(AWAY_PRESETS_KEY); if (!raw) return []; const parsed = JSON.parse(raw) as unknown; if (!Array.isArray(parsed)) return []; // Older versions stored presets as plain strings (name == message) - migrate on read. return parsed.map((p) => (typeof p === "string" ? { name: p, message: p } : (p as MessagePreset))); } catch { return []; } } function saveAwayPresets(presets: MessagePreset[]): void { localStorage.setItem(AWAY_PRESETS_KEY, JSON.stringify(presets)); } function loadDisconnectMessage(): string { return localStorage.getItem(DISCONNECT_MESSAGE_KEY) ?? ""; } function saveDisconnectMessage(message: string): void { localStorage.setItem(DISCONNECT_MESSAGE_KEY, message); } type LogEntry = { text: string; kind: "info" | "error" }; interface ChannelInfo { id: number; parent: number; order: number; name: string; topic: string; codec: string; maxClients: number | null; hasPassword: boolean; } type SelectedItem = | { type: "server" } | { type: "channel"; id: number } | { type: "client"; id: number }; interface 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; /** TS6 Stream/Call broadcast running; absent on servers that don't report it. */ isStreaming?: boolean; /** ServerQuery client; filtered from the tree unless a favorite enables them. */ isQuery?: boolean; /** MD5 of the avatar, empty without one; missing from gateways before v0.15. */ avatarHash?: string; } interface GroupEntry { id: number; name: string; iconId: number; } interface PermissionOverviewEntry { name: string; description: string; value: number; negated: boolean; skip: boolean; } interface FileListEntry { path: string; name: string; size: number; isFile: boolean; timestamp: string; } interface PermissionCatalogEntry { id: number; name: string; description: string; } type PermScope = "server" | "channelgroup" | "channel" | "client" | "channelclient"; interface ClientConnectionInfoData { clientId: number; pingMs: number | null; connectedSecs: number | null; ip: string | null; packetsSent: number; bytesSent: number; packetsReceived: number; bytesReceived: number; packetLossPercent: number; } interface ServerConnectionInfoData { pingMs: number; connectedSecs: number; packetLossPercent: number; packetsSentTotal: number; bytesSentTotal: number; packetsReceivedTotal: number; bytesReceivedTotal: number; bandwidthSentLastSecond: number; bandwidthReceivedLastSecond: number; bandwidthSentLastMinute: number; bandwidthReceivedLastMinute: number; filetransferBandwidthSent: number; filetransferBandwidthReceived: number; filetransferBytesSent: number; filetransferBytesReceived: number; } function formatBytes(bytes: number): string { if (!Number.isFinite(bytes) || bytes < 0) return "0 B"; if (bytes < 1024) return `${Math.round(bytes)} B`; const units = ["KB", "MB", "GB", "TB"]; let value = bytes / 1024; let unitIndex = 0; while (value >= 1024 && unitIndex < units.length - 1) { value /= 1024; unitIndex++; } return `${value.toFixed(1)} ${units[unitIndex]}`; } /** Compact counts like GreenTeaSpeak (`772.92 k`) β€” avoids DE locale `772.920`. */ function formatCount(value: number): string { if (!Number.isFinite(value) || value < 0) return "0"; if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(2)} M`; if (value >= 1_000) return `${(value / 1_000).toFixed(2)} k`; return value.toFixed(value % 1 === 0 ? 0 : 2); } function formatRate(bytesPerSec: number): string { return `${formatBytes(bytesPerSec)}/s`; } /** Turns a base64-encoded file (as delivered by the "fileDownloadData" event) * into an actual browser download, without ever round-tripping through the * gateway's HTTP surface - it's all-in-memory via a Blob + object URL. */ function triggerBrowserDownload(filename: string, base64Data: string): void { const binary = atob(base64Data); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); downloadBlob(new Blob([bytes]), filename); } function downloadBlob(blob: Blob, filename: string) { const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); a.remove(); // Revoking right after click() can cancel the download in some browsers. setTimeout(() => URL.revokeObjectURL(url), 60_000); } function formatDurationSecs(totalSeconds: number): string { const hours = Math.floor(totalSeconds / 3600); const minutes = Math.floor((totalSeconds % 3600) / 60); const seconds = Math.floor(totalSeconds % 60); const pad = (n: number) => String(n).padStart(2, "0"); return hours > 0 ? `${hours}:${pad(minutes)}:${pad(seconds)}` : `${minutes}:${pad(seconds)}`; } /** Converts an ISO 3166-1 alpha-2 country code (e.g. "DE") to its flag emoji * via Unicode regional indicator symbols. Returns null for codes the server * doesn't report (empty string - common when geo-IP isn't configured). */ function countryFlag(code: string): string | null { if (!/^[A-Za-z]{2}$/.test(code)) return null; const codePoints = [...code.toUpperCase()].map((c) => 0x1f1e6 + c.charCodeAt(0) - 65); return String.fromCodePoint(...codePoints); } function ChannelIcon() { return ( ); } /** GTS2-style talk lamp: blue idle / green talking / muted mic. */ function TalkLamp({ talking, inputMuted, inputHardwareEnabled, }: { talking: boolean; inputMuted: boolean; inputHardwareEnabled: boolean; }) { const t = useT(); const muted = inputMuted || !inputHardwareEnabled; if (muted) { return ( ); } if (talking) { return (