import { useEffect, 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"; // In dev, the gateway runs standalone on its own port. In production it's // served from the same origin/port as the web app (single container behind a // reverse proxy), so derive the WebSocket URL from the current location. const GATEWAY_URL = import.meta.env.DEV ? "ws://localhost:8080" : `${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"; /** 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 VAD_HANGOVER_KEY = "webspeak3:vad-hangover"; 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; } function loadFavorites(): Favorite[] { try { const raw = localStorage.getItem(FAVORITES_KEY); return raw ? (JSON.parse(raw) as Favorite[]) : []; } 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 }; 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; } interface GroupEntry { id: number; name: string; } 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; } function formatBytes(bytes: number): string { if (bytes < 1024) return `${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]}`; } /** 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 ( ); } function ClientIcon() { return ( ); } function ClientStatusIcons({ client }: { client: ClientInfo }) { const t = useT(); return ( {client.isChannelCommander && ⭐} {client.away && 💤} {(client.inputMuted || !client.inputHardwareEnabled) && 🔇} {client.outputMuted && 🔕} ); } function ServerIcon() { return ( ); } function ChannelTree({ channels, clients, parent, ownClientId, talkers, selected, onSelectItem, onSwitchChannel, onOpenPrivateChat, onPokeClient, onClientContextMenu, onChannelContextMenu, }: { channels: ChannelInfo[]; clients: ClientInfo[]; parent: number; ownClientId: number | null; talkers: Set; selected: SelectedItem | null; onSelectItem: (item: SelectedItem) => void; onSwitchChannel: (channelId: number) => void; onOpenPrivateChat: (clientId: number, clientName: string) => void; onPokeClient: (clientId: number, clientName: string) => void; onClientContextMenu: (e: React.MouseEvent, clientId: number, clientName: string, isSelf: boolean) => void; onChannelContextMenu: (e: React.MouseEvent, channelId: number, channelName: string) => void; }) { const t = useT(); const children = channels.filter((c) => c.parent === parent).sort((a, b) => a.order - b.order); if (children.length === 0) return null; return (
    {children.map((channel) => (
  • onSelectItem({ type: "channel", id: channel.id })} onDoubleClick={() => onSwitchChannel(channel.id)} onContextMenu={(e) => onChannelContextMenu(e, channel.id, channel.name)} title={t("tree.clickToSelect")} > {channel.name} {channel.hasPassword && 🔒}
      {clients .filter((c) => c.channel === channel.id) .map((c) => (
    • onOpenPrivateChat(c.id, c.name)} onContextMenu={(e) => onClientContextMenu(e, c.id, c.name, c.id === ownClientId)} title={c.id === ownClientId ? undefined : `${t("tree.privateChatWith")} ${c.name}`} > {countryFlag(c.country) && {countryFlag(c.country)}} {c.name} {c.away && c.awayMessage && ( ({c.awayMessage}) )} {c.id !== ownClientId && ( )}
    • ))}
  • ))}
); } function InfoPanel({ selected, host, serverName, serverMaxClients, serverVersion, serverLicense, totalClientCount, channels, clients, onShowServerConnectionInfo, onEditServer, }: { selected: SelectedItem | null; host: string; serverName: string; serverMaxClients: number; serverVersion: string; serverLicense: string; totalClientCount: number; channels: ChannelInfo[]; clients: ClientInfo[]; onShowServerConnectionInfo: () => void; onEditServer: () => void; }) { const t = useT(); if (!selected || selected.type === "server") { return (
{serverName || host}
{t("info.address")} {host}
{serverVersion && (
{t("info.version")} {serverVersion}
)} {serverLicense && (
{t("info.license")} {serverLicense}
)}
{t("info.currentClients")} {totalClientCount} / {serverMaxClients || "∞"}
{t("info.currentChannels")} {channels.length}
); } const channel = channels.find((c) => c.id === selected.id); if (!channel) return
; const clientCount = clients.filter((c) => c.channel === channel.id).length; return (
{channel.name}
{channel.topic && (
{t("info.topic")} {channel.topic}
)}
{t("info.audioCodec")} {channel.codec}
{t("info.passwordProtected")} {channel.hasPassword ? t("info.yes") : t("info.no")}
{t("info.clients")} {clientCount} / {channel.maxClients ?? "∞"}
); } interface ChatEntry { from: string; message: string; /** Set for server-log notifications (join/leave/switch/etc.) so they render * without a "from:" prefix, like the native client's server tab. */ isLog?: boolean; } interface PmMessage { fromSelf: boolean; message: string; } interface PmThread { partnerId: number; partnerName: string; messages: PmMessage[]; unread: boolean; } type ActiveTab = "channel" | "server" | number; interface PokeNotice { id: number; from: string; message: string; } function ConnectDialog({ host, nickname, serverPassword, channelPassword, defaultChannel, expanded, connecting, identities, activeIdentityId, onHostChange, onNicknameChange, onServerPasswordChange, onChannelPasswordChange, onDefaultChannelChange, onActiveIdentityChange, onToggleExpanded, onConnect, onCancel, }: { host: string; nickname: string; serverPassword: string; channelPassword: string; defaultChannel: string; expanded: boolean; connecting: boolean; identities: Identity[]; activeIdentityId: string | null; onHostChange: (v: string) => void; onNicknameChange: (v: string) => void; onServerPasswordChange: (v: string) => void; onChannelPasswordChange: (v: string) => void; onDefaultChannelChange: (v: string) => void; onActiveIdentityChange: (id: string) => void; onToggleExpanded: () => void; onConnect: () => void; onCancel: () => void; }) { const t = useT(); const backdrop = useBackdropDismiss(onCancel); return (
e.stopPropagation()}>
{t("connect.title")}
{expanded && (
)}
); } function FavoritesDialog({ favorites, prefillNew, onSave, onClose, }: { favorites: Favorite[]; prefillNew?: Omit; onSave: (favorites: Favorite[]) => void; onClose: () => void; }) { const t = useT(); const pendingNewRef = useRef( prefillNew ? { id: crypto.randomUUID(), bookmarkName: prefillNew.host || t("favorites.newFavoriteName"), ...prefillNew, } : null ); const [draft, setDraft] = useState(() => pendingNewRef.current ? [...favorites, pendingNewRef.current] : favorites.map((f) => ({ ...f })) ); const [selectedId, setSelectedId] = useState(() => pendingNewRef.current ? pendingNewRef.current.id : (favorites[0]?.id ?? null) ); const selected = draft.find((f) => f.id === selectedId) ?? null; const updateSelected = (patch: Partial) => { if (!selectedId) return; setDraft((prev) => prev.map((f) => (f.id === selectedId ? { ...f, ...patch } : f))); }; const handleNewFavorite = () => { const nf: Favorite = { id: crypto.randomUUID(), bookmarkName: t("favorites.newFavoriteName"), nickname: "", host: "", serverPassword: "", defaultChannel: "", defaultChannelPassword: "", }; setDraft((prev) => [...prev, nf]); setSelectedId(nf.id); }; const handleRemove = () => { if (!selectedId) return; setDraft((prev) => prev.filter((f) => f.id !== selectedId)); setSelectedId(null); }; const backdrop = useBackdropDismiss(onClose); return (
e.stopPropagation()}>
{t("favorites.title")}
{t("favorites.synced")}
{t("favorites.notLoggedIn")}
{t("favorites.local")}
    {draft.map((f) => (
  • setSelectedId(f.id)} > {f.bookmarkName || t("favorites.unnamed")}
  • ))}
); } function CollectedUrlsDialog({ urls, onClear, onClose, }: { urls: CollectedUrl[]; onClear: () => void; onClose: () => void; }) { const t = useT(); const [search, setSearch] = useState(""); const backdrop = useBackdropDismiss(onClose); const filtered = urls .filter((u) => u.url.toLowerCase().includes(search.toLowerCase())) .sort((a, b) => b.lastSeen - a.lastSeen); return (
e.stopPropagation()}>
{t("collectedUrls.title")}
{filtered.map((u) => ( ))}
{t("collectedUrls.url")} {t("collectedUrls.count")} {t("collectedUrls.lastSeen")} {t("collectedUrls.mentionedBy")}
{u.url} {u.count} {new Date(u.lastSeen).toLocaleString()} {u.lastSender}
); } function InviteFriendDialog({ host, channelId, onClose, }: { host: string; channelId: number | null; onClose: () => void; }) { const t = useT(); const [includeChannel, setIncludeChannel] = useState(false); const [copied, setCopied] = useState(false); const backdrop = useBackdropDismiss(onClose); const link = `ts3server://${host}${includeChannel && channelId !== null ? `?channel=${channelId}` : ""}`; return (
e.stopPropagation()}>
{t("inviteFriend.title")}
); } function ClientLogDialog({ entries, onClose }: { entries: ClientLogEntry[]; onClose: () => void }) { const t = useT(); const [enabledLevels, setEnabledLevels] = useState>(new Set(LOG_LEVELS)); const [search, setSearch] = useState(""); const [filter, setFilter] = useState(""); const [caseSensitive, setCaseSensitive] = useState(false); const backdrop = useBackdropDismiss(onClose); const listRef = useRef(null); const toggleLevel = (level: LogLevel) => { setEnabledLevels((prev) => { const next = new Set(prev); if (next.has(level)) next.delete(level); else next.add(level); return next; }); }; const matches = (message: string, needle: string) => caseSensitive ? message.includes(needle) : message.toLowerCase().includes(needle.toLowerCase()); const visible = entries .filter((e) => enabledLevels.has(e.level)) .filter((e) => !filter || matches(e.message, filter)); const handleMark = () => { if (!search) return; const idx = visible.findIndex((e) => matches(e.message, search)); if (idx >= 0) { const row = listRef.current?.querySelector(`[data-log-id="${visible[idx].id}"]`); row?.scrollIntoView({ block: "center" }); } }; return (
e.stopPropagation()}>
{t("clientLog.title")}
{LOG_LEVELS.map((level) => ( ))}
{visible.map((e) => (
{new Date(e.timestamp).toLocaleString()} {e.category} {t(`clientLog.level.${e.level}`)} {e.message}
))}
); } function BanListDialog({ entries, onDelete, onDeleteAll, onClose, }: { entries: BanListEntry[] | null; onDelete: (banId: number) => void; onDeleteAll: () => void; onClose: () => void; }) { const t = useT(); const backdrop = useBackdropDismiss(onClose); // Same silent-decline story as connection-info/server-log: a guest account // without b_virtualserver_client_dblist/banlist permission never gets a reply. const [timedOut, setTimedOut] = useState(false); useEffect(() => { setTimedOut(false); if (entries) return; const id = window.setTimeout(() => setTimedOut(true), 6000); return () => window.clearTimeout(id); }, [entries]); return (
e.stopPropagation()}>
{t("banList.title")}
{!entries ? (
{timedOut ? t("connectionInfo.unavailable") : t("connectionInfo.loading")}
) : entries.length === 0 ? (
{t("banList.empty")}
) : ( {entries.map((e) => ( ))}
{t("banList.name")} {t("banList.ip")} {t("banList.created")} {t("banList.duration")} {t("banList.invoker")} {t("banList.reason")}
{e.name || e.lastNickname || "-"} {e.ip || "-"} {e.created} {e.durationSecs === 0 ? t("banList.permanent") : `${e.durationSecs}s`} {e.invokerName} {e.reason}
)}
{entries && entries.length > 0 && ( )}
); } function ComplainListDialog({ entries, onDelete, onClose, }: { entries: ComplainListEntry[] | null; onDelete: (targetClientDbId: number, fromClientDbId: number) => void; onClose: () => void; }) { const t = useT(); const backdrop = useBackdropDismiss(onClose); const [timedOut, setTimedOut] = useState(false); useEffect(() => { setTimedOut(false); if (entries) return; const id = window.setTimeout(() => setTimedOut(true), 6000); return () => window.clearTimeout(id); }, [entries]); return (
e.stopPropagation()}>
{t("complainList.title")}
{!entries ? (
{timedOut ? t("connectionInfo.unavailable") : t("connectionInfo.loading")}
) : entries.length === 0 ? (
{t("complainList.empty")}
) : ( {entries.map((e, i) => ( ))}
{t("complainList.target")} {t("complainList.from")} {t("complainList.message")} {t("complainList.timestamp")}
{e.targetName} {e.fromName} {e.message} {e.timestamp}
)}
); } function OfflineMessagesDialog({ entries, detail, onSelect, onDelete, onMarkRead, onSend, onClose, }: { entries: OfflineMessageListEntry[] | null; detail: { messageId: number; clientUid: string; subject: string; message: string; timestamp: string } | null; onSelect: (messageId: number) => void; onDelete: (messageId: number) => void; onMarkRead: (messageId: number) => void; onSend: (clientUid: string, subject: string, message: string) => void; onClose: () => void; }) { const t = useT(); const backdrop = useBackdropDismiss(onClose); const [timedOut, setTimedOut] = useState(false); const [composing, setComposing] = useState(false); const [composeUid, setComposeUid] = useState(""); const [composeSubject, setComposeSubject] = useState(""); const [composeMessage, setComposeMessage] = useState(""); useEffect(() => { setTimedOut(false); if (entries) return; const id = window.setTimeout(() => setTimedOut(true), 6000); return () => window.clearTimeout(id); }, [entries]); const handleSend = () => { if (!composeUid.trim() || !composeSubject.trim()) return; onSend(composeUid.trim(), composeSubject.trim(), composeMessage.trim()); setComposing(false); setComposeUid(""); setComposeSubject(""); setComposeMessage(""); }; return (
e.stopPropagation()}>
{t("offlineMessages.title")}
{composing ? (