import { useEffect, useMemo, useRef, useState } from "react"; import "./App.css"; /** Only dismiss on a genuine backdrop click, not a text-selection drag that * starts inside the dialog and releases over the backdrop. */ function useBackdropDismiss(onDismiss: () => void) { const mouseDownOnBackdrop = useRef(false); return { 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 { LanguageProvider, useLanguage, useT, type LangPref } from "./i18n"; 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`; // 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"; const LAST_PRIVILEGE_KEY = "webspeak3:last-privilege-key"; const LAST_SERVER_TYPE_KEY = "webspeak3:last-server-type"; type ServerType = "teamspeak" | "teaspeak" | "auto"; function loadServerType(): ServerType { const raw = localStorage.getItem(LAST_SERVER_TYPE_KEY); return raw === "teamspeak" || raw === "teaspeak" || raw === "auto" ? raw : "auto"; } /** 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; } // 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 = crypto.randomUUID(); 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 ?? crypto.randomUUID(), name: i.name ?? "Standard", nickname: i.nickname ?? "", phoneticName: i.phoneticName ?? "", blob: i.blob ?? null, })); } } catch { // fall through } return [{ id: crypto.randomUUID(), 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 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; }; 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 []; } } const AWAY_PRESETS_KEY = "webspeak3:away-presets"; 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"; 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; /** ServerQuery client; filtered from the tree unless a favorite enables them. */ isQuery?: boolean; } 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); const blob = new Blob([bytes]); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); } 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 (