Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ee4a7e09b8 | ||
|
|
e0d5916a86 | ||
|
|
e8dc71329b | ||
|
|
30682cd659 | ||
|
|
e09a19b7b4 | ||
|
|
2b7e908d31 | ||
|
|
0ea85752fd | ||
|
|
97b7127ca3 | ||
|
|
db38feba52 | ||
|
|
1bab4df64e | ||
|
|
193130c50f | ||
|
|
c7794a12e7 | ||
|
|
408d8bcda4 | ||
|
|
5a3eebecbd | ||
|
|
713716dacc | ||
|
|
3a7a162f97 | ||
|
|
2f8614d53a | ||
|
|
bdac15afac | ||
|
|
7f49e2f2d7 | ||
|
|
24f1b9a4b8 | ||
|
|
79b91fca44 | ||
|
|
6a821b760e | ||
|
|
6539479d10 | ||
|
|
8ed3e788be | ||
|
|
de8f6a11c9 | ||
|
|
21d53a30c9 | ||
|
|
22656b2e7d | ||
|
|
3a18bcebbc | ||
|
|
7b35c63a74 | ||
|
|
6b9038da6c | ||
|
|
1dd04bf7ca | ||
|
|
15af861389 | ||
|
|
7ea63c525e | ||
|
|
3d0b8a5c97 | ||
|
|
fb39d82c01 | ||
|
|
ae530963bf | ||
|
|
f8554fc991 | ||
|
|
a3dad55c76 | ||
|
|
0b29742bce | ||
|
|
c2c38fa011 | ||
|
|
578217ba41 | ||
|
|
d75bdccfd9 | ||
|
|
412f560677 | ||
|
|
fdccf86458 | ||
|
|
d43a33aa15 | ||
|
|
056b57bcd1 | ||
|
|
688eb3174e | ||
|
|
c38f67bc3b | ||
|
|
67c7a27af6 | ||
|
|
6d1d2a1f92 | ||
|
|
faff7a2237 | ||
|
|
dc63f4b45b | ||
|
|
380fb67090 | ||
|
|
b71632cc29 | ||
|
|
38f7c94a65 | ||
|
|
d91a145657 | ||
|
|
a2e33ff176 | ||
|
|
010b8ef072 | ||
|
|
883703dd0c | ||
|
|
bcf212738b | ||
|
|
fae21ec086 | ||
|
|
22dcf93925 | ||
|
|
4df59b80d0 | ||
|
|
c49b4ec715 | ||
|
|
1c80791109 | ||
|
|
85f87ecd0b | ||
|
|
3d6752a5e4 | ||
|
|
a0921c35b2 | ||
|
|
ace9e84889 | ||
|
|
4ead174c04 | ||
|
|
f628d19ebf | ||
|
|
75de8f1d2b | ||
|
|
1ba8cd5ee1 | ||
|
|
f639825775 | ||
|
|
0b40a69d74 | ||
|
|
6defbff591 | ||
|
|
b5d167e1e7 | ||
|
|
7f97d54206 | ||
|
|
ef3e65ea0b | ||
|
|
d13b3207a9 | ||
|
|
7e08ee54a5 | ||
|
|
6d8e289b81 | ||
|
|
defbb766e4 | ||
|
|
69043748a1 | ||
|
|
8046985574 |
No files matched your search
@@ -0,0 +1,32 @@
|
||||
---
|
||||
name: webspeak-skin-development
|
||||
description: Create, refine, package, and verify WebSpeak visual skins while preserving the product's translated content, fixed component geometry, and interactions.
|
||||
---
|
||||
|
||||
# WebSpeak skin development
|
||||
|
||||
Use this skill when editing or authoring a WebSpeak `.wskin` package, the ILLUSIA built-in skin, or skin-facing UI hooks. A skin changes artwork and visual treatment; WebSpeak owns page structure, text, and behavior. The administrator console is deliberately outside the skin scope.
|
||||
|
||||
## Before editing
|
||||
|
||||
- Read [`docs/SKIN_DEVELOPMENT.md`](../../../docs/SKIN_DEVELOPMENT.md) for the current package validator and public hooks.
|
||||
- Use [`docs/examples/illusia-voice/`](../../../docs/examples/illusia-voice/) and [`docs/examples/ILLUSIA-VOICE.md`](../../../docs/examples/ILLUSIA-VOICE.md) as the reference implementation. Do not restore the removed Aurora Voice sample.
|
||||
- Inspect the actual component markup for `data-ws-page`, `data-ws-part`, and `data-ws-state` hooks. Treat Vue classes and incidental DOM structure as private.
|
||||
|
||||
## Preserve the interface
|
||||
|
||||
- Keep WebSpeak's translations and semantic content as the baseline. Add `content.json` only when a text override is an explicit part of the request; never use it to implement visual artwork.
|
||||
- Skin only with supported visual CSS and package-local images/fonts. The upload validator rejects layout, positioning, sizing, spacing, clipping, text-flow, and interaction-geometry changes. Do not work around it with selectors, pseudo-elements, or animation.
|
||||
- Never hide or obstruct critical controls, make a card or player move/resize, change a floating menu into a modal, or make artwork intercept pointer input. Keep `/admin/**` unskinned.
|
||||
- Use the host's reserved artwork hooks for layered character art and the headphone scene. Prefer transparent assets and `background-size: contain` where the reference requires the full character or chibi to remain visible; arrange the artwork around the fixed hook rather than changing its geometry.
|
||||
- Build visual depth with separate background, surface, and foreground artwork already exposed by the hooks. Avoid duplicate static decorations when an animated replacement exists. For motion, keep waveforms/sonar smooth and restrained, honor reduced-motion preferences, and retain readable focus, error, mute, and speaking states.
|
||||
- Keep skin-specific CSS variables under `--skin-*`. Use only package-local assets and confirm their redistribution rights.
|
||||
|
||||
## Verify and package
|
||||
|
||||
1. Compare the implementation with its visual reference at desktop and narrow widths. Check the homepage, voice workspace, empty chat, member list, screen-share player, selectors, and `/demo`; verify no crop, overflow, text collision, or control overlap.
|
||||
2. Check all five interface languages, day/night modes, keyboard focus, and reduced-motion behavior. Confirm the admin console is unchanged.
|
||||
3. Run `npm test` and `npm --prefix web run build`. Fix validator or build failures rather than weakening the layout guardrails.
|
||||
4. Package the contents of the skin directory so `manifest.json` is at the archive root, then import it through `/admin/skins` and retest the installed `.wskin` in a visitor session.
|
||||
|
||||
The three shipped skins—default day, default night, and ILLUSIA—are protected built-ins. Do not change their IDs or introduce upload/update flows that can disable, replace, or remove them.
|
||||
@@ -1,5 +1,195 @@
|
||||
# Changelog
|
||||
|
||||
## [0.2.5] — 2026-09-27(相对 0.2.4)
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增 `.wskin` 视觉皮肤系统:用户可在首页、语音工作区和 `/demo` 选择外观;皮肤可更换背景、美术素材与组件视觉,但页面结构、排版空间、控件位置和交互仍由 WebSpeak 固定提供,管理后台不受皮肤影响。
|
||||
- 管理员可在皮肤库启用/停用自定义皮肤并指定实例默认皮肤;访客手动选择会保留,未手动选择的访客采用实例默认。默认日间、默认夜间和 ILLUSIA 风是受保护内置皮肤,不能删除、停用或替换。
|
||||
- 将完成度不足的 Aurora Voice 示例移除,以 ILLUSIA 风作为完整皮肤开发样例;细化首页装饰、语音区跨层级立绘、耳机场景、聊天空状态和屏幕播放器表现,并修复深色模式控件可读性、组件溢出和皮肤加载闪烁。
|
||||
- 新增官方仓库皮肤开发 Agent Skill,配套更新开发规范与多语言功能说明;访客总数在统计暂不可用时也不会低于当前访客序号。
|
||||
- 缩小 ILLUSIA 语音活动立绘并固定在容器右下角,避免遮挡成员名单和屏幕共享播放器。
|
||||
|
||||
### English
|
||||
|
||||
- Added the `.wskin` visual skin system. Visitors can choose appearances on the home page, voice workspace, and `/demo`; skins may customize artwork and component visuals while WebSpeak retains page structure, layout, control placement, and behavior. The administration console remains unskinned.
|
||||
- Administrators can enable/disable custom skins and set an instance default. Deliberate visitor choices are preserved; visitors without an explicit choice receive the instance default. Default Day, Default Night, and ILLUSIA are protected built-ins that cannot be removed, disabled, or replaced.
|
||||
- Removed the unfinished Aurora Voice sample and made ILLUSIA the complete reference skin. Refined homepage artwork, layered voice-room character art and headphone scene, the empty-chat backdrop, and the screen-share player; fixed dark-mode control contrast, overflow, and skin-load flashes.
|
||||
- Added the repository's official skin-development Agent Skill and synchronized the guide and localized feature notes. The displayed visitor total also remains at least as high as the current visitor ordinal when the counter is unavailable.
|
||||
- Reduced and anchored the ILLUSIA voice-activity artwork to the lower-right corner so it no longer obscures member cards or the screen-share player.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Das visuelle `.wskin`-System wurde ergänzt. Besucher können das Design auf der Startseite, im Sprachbereich und unter `/demo` wählen. Skins dürfen Grafiken und die visuelle Darstellung anpassen; Seitenstruktur, Layout, Positionen der Bedienelemente und Verhalten bleiben von WebSpeak vorgegeben. Die Administrationskonsole bleibt ungestaltet.
|
||||
- Administratoren können eigene Skins aktivieren/deaktivieren und ein Standarddesign für die Instanz festlegen. Eine bewusst getroffene Besucherauswahl bleibt erhalten; ohne eigene Auswahl gilt der Instanzstandard. Tagesmodus, Nachtmodus und ILLUSIA sind geschützte integrierte Skins und können weder gelöscht noch deaktiviert oder ersetzt werden.
|
||||
- Das unfertige Aurora-Voice-Beispiel wurde entfernt; ILLUSIA ist nun das vollständige Referenzdesign. Startseitenkunst, Ebenenillustration und Kopfhörerszene im Sprachbereich, leerer Chat-Hintergrund und Bildschirmfreigabe-Player wurden verfeinert. Außerdem wurden dunkle Bedienelemente, Überläufe und Skin-Ladeblitze korrigiert.
|
||||
- Der offizielle Skin-Entwicklungs-Agent-Skill des Repositorys wurde ergänzt; Anleitung und lokalisierte Funktionsübersichten wurden aktualisiert. Die Besucher-Gesamtzahl fällt bei nicht verfügbarem Zähler nicht unter die aktuelle Besuchernummer.
|
||||
- Die ILLUSIA-Illustration im Sprachbereich wurde verkleinert und unten rechts verankert, damit sie weder Mitgliederkarten noch den Bildschirmfreigabe-Player verdeckt.
|
||||
|
||||
### Русский
|
||||
|
||||
- Добавлена визуальная система скинов `.wskin`: посетители могут выбирать оформление на главной странице, в голосовом пространстве и в `/demo`. Скины меняют иллюстрации и внешний вид компонентов, а структуру, компоновку, расположение элементов управления и поведение задаёт WebSpeak. Панель администратора не оформляется скинами.
|
||||
- Администраторы могут включать и отключать пользовательские скины и задавать оформление по умолчанию для экземпляра. Явный выбор посетителя сохраняется; без него используется настройка экземпляра. Дневная тема, ночная тема и ILLUSIA — защищённые встроенные скины, которые нельзя удалить, отключить или заменить.
|
||||
- Удалён незавершённый пример Aurora Voice; полной эталонной темой стала ILLUSIA. Улучшены иллюстрации главной страницы, многослойный персонаж и сцена с наушниками в голосовой комнате, фон пустого чата и проигрыватель трансляции экрана. Исправлены контраст элементов в тёмном режиме, переполнение и вспышки при загрузке скина.
|
||||
- В официальный репозиторий добавлен Agent Skill для разработки скинов, обновлены руководство и локализованные описания функций. При недоступности счётчика общее число посетителей не опускается ниже текущего номера посетителя.
|
||||
- Иллюстрация ILLUSIA в голосовой активности уменьшена и закреплена внизу справа, чтобы не перекрывать список участников и проигрыватель трансляции экрана.
|
||||
|
||||
### 日本語
|
||||
|
||||
- `.wskin` ビジュアルスキン機能を追加しました。ホーム、音声ワークスペース、`/demo` で外観を選択できます。背景や素材、コンポーネントの見た目を変更できますが、ページ構造、レイアウト、操作部品の位置と動作は WebSpeak が管理します。管理コンソールには適用されません。
|
||||
- 管理者はカスタムスキンの有効/無効と、インスタンスのデフォルトスキンを設定できます。訪問者が明示的に選んだスキンは維持され、未選択の場合はインスタンスのデフォルトを使用します。昼、夜、ILLUSIA の3種類は保護された内蔵スキンで、削除・無効化・置換できません。
|
||||
- 未完成の Aurora Voice サンプルを削除し、ILLUSIA を完成版のリファレンスにしました。ホームのアート、音声画面の重ね合わせ立ち絵とヘッドホン背景、空のチャット背景、画面共有プレーヤーを調整し、ダークモードの視認性、はみ出し、読み込み時のちらつきを修正しました。
|
||||
- 公式リポジトリにスキン開発 Agent Skill を追加し、ガイドと各言語の機能説明を更新しました。カウンターを取得できない場合も、訪問者総数が現在の訪問者番号を下回らないようにしました。
|
||||
- 音声アクティビティの ILLUSIA 立ち絵を縮小して右下に固定し、メンバー一覧や画面共有プレーヤーを隠さないようにしました。
|
||||
|
||||
## [0.2.4] — 2026-09-22
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增跨端 P2P 屏幕共享:浏览器用户可以与 TeamSpeak 6 原生客户端互相发现、发起和观看屏幕共享;浏览器之间以及浏览器与原生客户端之间的媒体流优先通过 WebRTC/ICE 直连,WebSpeak 仅负责会话鉴权、共享状态和 SDP/ICE 信令转发,不承载屏幕媒体流量。
|
||||
- 默认使用 TeamSpeak 官方 STUN 服务发现直连候选,并支持管理员显式配置外部 TURN;即使使用 TURN,媒体也经过外部服务而不是 WebSpeak 网关。
|
||||
- 新增屏幕共享直播状态、观众人数、播放器音量、全屏和退出控制,并提供发送端/接收端 WebRTC 实时统计。
|
||||
- 提供浏览器屏幕采集分辨率和帧率设置,最高支持 1080p、60 FPS;设置改为独立弹窗,避免成员卡片被撑高。
|
||||
- 新增首页访客编号,并优化屏幕共享成员卡片和观看交互。
|
||||
- 修正输出限制的应用方式:保持所选桌面或窗口的原始采集尺寸,由发送端编码器按设置缩放和限帧;首页同时显示当前访客序号和累计访客数。
|
||||
- 修复 TeamSpeak 握手期间服务器拒绝错误被误报为连接超时的问题;昵称长度不符合要求时会显示明确的修改提示。
|
||||
|
||||
### English
|
||||
|
||||
- Added cross-platform P2P screen sharing: browser users can discover, start, and watch screen shares with native TeamSpeak 6 clients. Media between browsers, and between a browser and a native client, prefers a direct WebRTC/ICE path; WebSpeak handles session authorization, share state, and SDP/ICE signaling only and does not carry screen media.
|
||||
- Added TeamSpeak's public STUN services for direct-candidate discovery by default, with optional administrator-configured external TURN. Even with TURN, media uses the external service rather than the WebSpeak gateway.
|
||||
- Added live screen-share status, viewer counts, player volume, fullscreen, and exit controls, plus live sender/receiver WebRTC statistics.
|
||||
- Added browser capture-resolution and frame-rate controls up to 1080p and 60 FPS; moved the controls into a standalone modal so member cards no longer stretch.
|
||||
- Added homepage visitor numbering and refined screen-share member-card and viewing interactions.
|
||||
- Fixed output-limit handling so the selected desktop or window keeps its native capture size while the sender encoder applies the requested scale and frame-rate cap; the homepage now also shows the total visitor count.
|
||||
- Fixed handshake refusals being reported as connection timeouts; invalid nickname lengths now show a clear prompt to change the nickname.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Plattformübergreifendes P2P-Bildschirmteilen ergänzt: Browsernutzer können Bildschirmfreigaben mit nativen TeamSpeak-6-Clients erkennen, starten und ansehen. Die Medienübertragung zwischen Browsern sowie zwischen Browser und nativem Client nutzt möglichst direkte WebRTC-/ICE-Verbindungen; WebSpeak übernimmt nur Sitzungsberechtigung, Freigabestatus und SDP-/ICE-Signalisierung und transportiert keine Bildschirmmedien.
|
||||
- Öffentliche TeamSpeak-STUN-Dienste werden standardmäßig zur Ermittlung direkter Kandidaten verwendet; ein externes TURN kann ausdrücklich durch den Administrator konfiguriert werden. Auch mit TURN läuft die Medienübertragung über den externen Dienst und nicht über das WebSpeak-Gateway.
|
||||
- Live-Status, Zuschauerzahl, Lautstärke, Vollbild- und Beenden-Steuerung für Bildschirmfreigaben sowie laufende WebRTC-Statistiken für Sender und Empfänger ergänzt.
|
||||
- Aufnahmeauflösung und Bildrate im Browser bis 1080p und 60 FPS konfigurierbar; die Einstellungen wurden in ein eigenes Modal verschoben, damit Mitgliederkarten nicht mehr in die Höhe wachsen.
|
||||
- Besucherzählung auf der Startseite ergänzt und die Interaktion von Bildschirmfreigabe-Karten und Player verbessert.
|
||||
- Die Ausgabelimits werden nun am Sender-Encoder angewendet, während die native Aufnahmegröße des ausgewählten Desktops oder Fensters erhalten bleibt; auf der Startseite wird zusätzlich die Gesamtzahl der Besucher angezeigt.
|
||||
- Behoben, dass Ablehnungen während des TeamSpeak-Handshakes als Zeitüberschreitung angezeigt wurden; bei ungültiger Nicknamenslänge erscheint nun ein klarer Änderungshinweis.
|
||||
|
||||
### Русский
|
||||
|
||||
- Добавлена кроссплатформенная P2P-трансляция экрана: пользователи браузера могут обнаруживать, запускать и смотреть трансляции вместе с нативными клиентами TeamSpeak 6. Медиа между браузерами, а также между браузером и нативным клиентом по возможности передаётся напрямую через WebRTC/ICE; WebSpeak отвечает только за авторизацию сессии, состояние трансляции и SDP/ICE-сигналы и не переносит медиаданные экрана.
|
||||
- По умолчанию добавлено обнаружение прямых кандидатов через публичные STUN-сервисы TeamSpeak; администратор может явно настроить внешний TURN. Даже при использовании TURN медиа идёт через внешний сервис, а не через шлюз WebSpeak.
|
||||
- Добавлены статус трансляции, число зрителей, громкость проигрывателя, полноэкранный режим и выход, а также текущая статистика WebRTC для отправителя и получателя.
|
||||
- Добавлены настройки разрешения и частоты кадров захвата в браузере до 1080p и 60 FPS; настройки вынесены в отдельное окно, чтобы карточки участников не растягивались.
|
||||
- Добавлен номер посетителя на главной странице и улучшено управление карточками и просмотром трансляций.
|
||||
- Исправлено применение ограничений вывода: выбранный рабочий стол или окно сохраняет исходный размер захвата, а запрошенное масштабирование и ограничение частоты кадров применяются кодировщиком отправителя; на главной странице также показывается общее число посетителей.
|
||||
- Исправлено ошибочное отображение отказов TeamSpeak во время рукопожатия как тайм-аута; при недопустимой длине имени показывается понятная просьба изменить его.
|
||||
|
||||
### 日本語
|
||||
|
||||
- クロスプラットフォーム P2P 画面共有を追加しました。ブラウザユーザーは TeamSpeak 6 ネイティブクライアントと互いに画面共有を検出・開始・視聴できます。ブラウザ間、およびブラウザとネイティブクライアント間のメディアは可能な限り WebRTC/ICE で直接送信され、WebSpeak はセッション認証、共有状態、SDP/ICE シグナリングだけを担当し、画面メディアは運びません。
|
||||
- 初期設定で TeamSpeak 公開 STUN サービスによる直接候補の検出に対応し、管理者が外部 TURN を明示的に設定できるようにしました。TURN 使用時もメディアは外部サービスを経由し、WebSpeak ゲートウェイは経由しません。
|
||||
- 配信状態、視聴者数、プレーヤー音量、全画面、終了操作と、送信側・受信側の WebRTC 統計を追加しました。
|
||||
- ブラウザの画面取得設定で最大 1080p / 60 FPS を選択できます。設定を独立したモーダルに移し、メンバーカードが縦に伸びないようにしました。
|
||||
- ホームページの訪問者番号を追加し、画面共有カードと視聴操作を改善しました。
|
||||
- 出力制限を送信側エンコーダーで適用するよう修正し、選択したデスクトップやウィンドウの元の取得サイズを維持します。ホームページには訪問者番号に加えて累計訪問者数も表示します。
|
||||
- TeamSpeak の接続ハンドシェイク中の拒否がタイムアウトとして表示される問題を修正しました。ニックネームの長さが不適切な場合は、変更を促すメッセージを表示します。
|
||||
|
||||
## [0.2.3] — 2026-09-19
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增频道成员调度入口:保留拖放移动,并在右键菜单提供“调度到”二级菜单和“我所在的频道”快捷项。
|
||||
- 支持按 TeamSpeak 权限直接移动成员;具备权限时无需重复输入频道密码,无权限时不提供该操作。
|
||||
- 支持成员头像显示、麦克风静音状态同步和保存身份恢复,并增强指针拖动兼容性。
|
||||
- 更新中文、English、Deutsch、Русский、日本語五种语言的功能截图和文档页面。
|
||||
- 修复高分辨率桌面端管理员设置页面底部内容被裁切的问题,并收紧中继卡片的宽度约束。
|
||||
|
||||
### English
|
||||
|
||||
- Added member-management entry points: drag-and-drop remains available, while the context menu now provides a “Move to” submenu with a “My channel” shortcut.
|
||||
- Added permission-aware direct member moves: authorized users can move clients without redundant channel-password prompts, while the action is unavailable without the required TeamSpeak permission.
|
||||
- Added client-avatar display, microphone mute-state synchronization, and remembered-identity recovery, with improved pointer-drag compatibility.
|
||||
- Refreshed feature screenshots and documentation pages for all five supported languages.
|
||||
- Fixed clipped lower content in the high-resolution desktop admin settings page and tightened relay-card width constraints.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Neue Einstiege für die Mitgliederverwaltung: Ziehen und Ablegen bleibt verfügbar, zusätzlich bietet das Kontextmenü ein Untermenü „Verschieben nach“ mit dem Eintrag „Mein Kanal“.
|
||||
- Direkte, berechtigungsabhängige Mitgliederverschiebung ergänzt: Benutzer mit den erforderlichen TeamSpeak-Rechten benötigen keine erneute Kanalpasswortabfrage; ohne diese Rechte steht die Aktion nicht zur Verfügung.
|
||||
- Anzeige von Client-Avataren, Synchronisierung des Mikrofon-Stummschaltstatus und Wiederherstellung gespeicherter Identitäten ergänzt; Zeigerbedienung verbessert.
|
||||
- Funktionsscreenshots und Dokumentationsseiten für alle fünf unterstützten Sprachen aktualisiert.
|
||||
- Das Abschneiden unterer Inhalte in den Admin-Einstellungen bei hoher Desktop-Auflösung behoben und die Breitenbegrenzung der Relay-Karten verbessert.
|
||||
|
||||
### Русский
|
||||
|
||||
- Добавлены способы управления участниками: перетаскивание сохранено, а в контекстном меню появился пункт «Переместить в» с быстрым вариантом «Мой канал».
|
||||
- Добавлено прямое перемещение с учётом прав TeamSpeak: пользователям с нужными правами не нужно повторно вводить пароль канала, а без этих прав действие недоступно.
|
||||
- Добавлены отображение аватаров клиентов, синхронизация состояния микрофона и восстановление сохранённой идентичности; улучшено перетаскивание указателем.
|
||||
- Обновлены функциональные скриншоты и страницы документации для всех пяти поддерживаемых языков.
|
||||
- Исправлено обрезание нижнего содержимого настроек администратора на десктопах с высоким разрешением и ограничена ширина карточек ретрансляторов.
|
||||
|
||||
### 日本語
|
||||
|
||||
- メンバー操作を追加しました。ドラッグ&ドロップに加えて、コンテキストメニューに「移動先」サブメニューと「自分のチャンネル」ショートカットを用意しました。
|
||||
- TeamSpeak 権限に応じた直接移動を追加しました。必要な権限があればチャンネルパスワードを再入力せずに移動でき、権限がなければ操作は表示されません。
|
||||
- クライアントアバターの表示、マイクミュート状態の同期、保存した ID の復元に対応し、ポインター操作も改善しました。
|
||||
- 対応する 5 言語すべての機能スクリーンショットとドキュメントページを更新しました。
|
||||
- 高解像度デスクトップで管理設定の下部が切れる問題を修正し、中継カードの幅制約を改善しました。
|
||||
|
||||
## [0.2.2] — 2026-09-17
|
||||
|
||||
### 中文
|
||||
|
||||
- 提供可开关的浏览器端麦克风降噪功能。
|
||||
- 优化前端音量交互逻辑:桌面端悬停麦克风和整体音量按钮即可调整,降噪开关收纳在麦克风菜单中。
|
||||
- 在 PR #2 基础上优化错误提示和错误代码显示。
|
||||
- 提供俄语和日语界面支持,并支持按语言单独调整欢迎文字。
|
||||
|
||||
### English
|
||||
|
||||
- Added optional browser-side microphone noise suppression.
|
||||
- Refined volume interaction: desktop microphone and master-volume controls open on hover, with noise suppression in the microphone menu.
|
||||
- Improved error messages and error-code display on top of PR #2.
|
||||
- Added Russian and Japanese UI support and per-language welcome text configuration.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Optionale browserseitige Mikrofon-Geräuschunterdrückung hinzugefügt.
|
||||
- Lautstärkeinteraktion verbessert: Desktop-Mikrofon- und Gesamtlautstärkeregler öffnen sich beim Überfahren; die Geräuschunterdrückung befindet sich im Mikrofonmenü.
|
||||
- Fehlertexte und Fehlercodes auf Basis von PR #2 verbessert.
|
||||
- Russische und japanische Oberfläche sowie sprachabhängige Begrüßungstexte ergänzt.
|
||||
|
||||
### Русский
|
||||
|
||||
- Добавлено опциональное шумоподавление микрофона в браузере.
|
||||
- Улучшено управление громкостью: на компьютере регуляторы открываются при наведении, а шумоподавление находится в меню микрофона.
|
||||
- Улучшены сообщения и коды ошибок на основе PR #2.
|
||||
- Добавлены русский и японский интерфейсы и отдельная настройка приветствия для каждого языка.
|
||||
|
||||
### 日本語
|
||||
|
||||
- ブラウザ側で任意に使えるマイクノイズ抑制を追加しました。
|
||||
- 音量操作を改善し、デスクトップではマイクと全体音量のボタンにカーソルを合わせると調整画面を表示し、ノイズ抑制をマイクメニューにまとめました。
|
||||
- PR #2 を基にエラー表示とエラーコードを改善しました。
|
||||
- ロシア語・日本語 UI と言語別ウェルカム文の設定を追加しました。
|
||||
|
||||
## [0.2.1] — 2026-09-13
|
||||
|
||||
### 中文
|
||||
|
||||
- 统一首页连接错误显示:保留错误代码,未知错误安全截断,并显示可追溯的服务端原因。
|
||||
- 默认支持 IPv6 TeamSpeak 目标,并补充主机、运行时和网络条件说明。
|
||||
|
||||
### English
|
||||
|
||||
- Unified connection-error display on the welcome page: preserve error codes, safely truncate unknown codes, and show traceable server reasons.
|
||||
- Added default IPv6 TeamSpeak target support and documented the required host, runtime, and network conditions.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Verbindungsfehler auf der Willkommensseite vereinheitlicht: Fehlercodes bleiben erhalten, unbekannte Codes werden sicher gekürzt und nachvollziehbare Serverursachen angezeigt.
|
||||
- IPv6-Ziele für TeamSpeak standardmäßig unterstützt und erforderliche Host-, Laufzeit- und Netzwerkbedingungen dokumentiert.
|
||||
|
||||
## [0.2.0] — 2026-09-10
|
||||
|
||||
### 中文
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<div align="center">
|
||||
<a id="readme-top"></a>
|
||||
|
||||
<img src="./image.png" alt="WebSpeak 项目图标"/>
|
||||
<img src="./image.png" alt="WebSpeak 项目横幅" width="100%" />
|
||||
|
||||
<h1>WebSpeak</h1>
|
||||
|
||||
@@ -18,73 +18,33 @@
|
||||
[](https://vuejs.org/)
|
||||
[](https://www.typescriptlang.org/)
|
||||
[](https://github.com/users/EchoSixHIYA/packages/container/package/webspeak)
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)
|
||||
|
||||
<p>
|
||||
<a href="#简体中文">简体中文</a> ·
|
||||
<a href="#english">English</a> ·
|
||||
<a href="#deutsch">Deutsch</a> ·
|
||||
<a href="#demo">在线 Demo</a> ·
|
||||
<a href="#community">社区 / Community</a> ·
|
||||
<a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest">下载</a>
|
||||
<a href="./docs/README.zh-CN.md">简体中文文档</a> ·
|
||||
<a href="./docs/README.en.md">English documentation</a> ·
|
||||
<a href="./docs/README.de.md">Deutsche Dokumentation</a> ·
|
||||
<a href="./docs/README.ru.md">Русская документация</a> ·
|
||||
<a href="./docs/README.ja.md">日本語ドキュメント</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<details>
|
||||
<summary><kbd>目录 / Table of contents</kbd></summary>
|
||||
|
||||
- [项目简介 · Overview](#overview)
|
||||
- [在线 Demo · Live Demo](#demo)
|
||||
- [社区 · Community](#community)
|
||||
- [简体中文](#简体中文)
|
||||
- [界面截图](#zh-screenshots)
|
||||
- [特性](#zh-features)
|
||||
- [高级功能](#zh-advanced)
|
||||
- [更新日志](#zh-changelog)
|
||||
- [部署方案](#zh-deployment)
|
||||
- [要求和注意事项](#zh-requirements)
|
||||
- [许可证](#zh-license)
|
||||
- [English](#english)
|
||||
- [Screenshots](#en-screenshots)
|
||||
- [Features](#en-features)
|
||||
- [Advanced features](#en-advanced)
|
||||
- [Changelog](#en-changelog)
|
||||
- [Deployment](#en-deployment)
|
||||
- [Requirements and notes](#en-requirements)
|
||||
- [License](#en-license)
|
||||
- [Deutsch](#deutsch)
|
||||
- [Screenshots](#de-screenshots)
|
||||
- [Funktionen](#de-features)
|
||||
- [Erweiterte Funktionen](#de-advanced)
|
||||
- [Änderungsprotokoll](#de-changelog)
|
||||
- [Bereitstellung](#de-deployment)
|
||||
- [Voraussetzungen und Hinweise](#de-requirements)
|
||||
- [Lizenz](#de-license)
|
||||
|
||||
</details>
|
||||
|
||||
<a id="overview"></a>
|
||||
|
||||
## 项目简介 · Overview
|
||||
|
||||
| 逻辑 | 中文 | English |
|
||||
| --- | --- | --- |
|
||||
| **WHAT** | WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。用户打开网页即可进入频道、交流和管理自己的音频设备。 | WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. Users can join channels, communicate, and manage their audio devices directly in a browser. |
|
||||
| **WHY** | 它降低了临时加入 TeamSpeak 的门槛:无需安装桌面客户端,只需分享一个网页地址,同时仍由部署者控制目标服务器、访问方式和数据。 | It lowers the barrier to joining TeamSpeak: no desktop installation is required, only a web address, while the operator keeps control of targets, access policies, and data. |
|
||||
| **HOW** | 部署 WebSpeak 后,管理员在网页控制台设置默认 TeamSpeak 目标和访问策略。浏览器负责交互与音频,WebSpeak 负责连接 TeamSpeak;需要更低延迟时可启用内置 WebRTC。 | After deployment, the administrator configures the default TeamSpeak target and access policy in the web console. The browser handles interaction and audio, WebSpeak connects to TeamSpeak, and the bundled WebRTC path can be enabled for lower latency. |
|
||||
| **WHAT** | WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。 | WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. |
|
||||
| **WHY** | 无需安装桌面客户端,用户打开网页即可加入频道;部署者仍然掌控目标服务器、访问策略和数据。 | Users can join a voice channel from a browser without installing a desktop client, while the operator keeps control of servers, access, and data. |
|
||||
| **HOW** | 部署后在管理员控制台配置 TeamSpeak 目标和访问方式,浏览器负责交互与音频,WebSpeak 负责网关连接。 | Configure the TeamSpeak target and access policy in the administration console. The browser handles interaction and audio; WebSpeak provides the gateway connection. |
|
||||
|
||||
<a id="demo"></a>
|
||||
## 文档 · Documentation
|
||||
|
||||
## 在线 Demo · Live Demo
|
||||
|
||||
**在线地址 / Live URL:<https://webspeak.example.invalid>**
|
||||
|
||||
> [!WARNING]
|
||||
> **中文:** 公共演示服务器位于香港,网络和运行负载可能不稳定。延迟、断线或暂时不可用不代表自行部署后的实际表现,请勿将该节点用于重要或长期会话。
|
||||
>
|
||||
> **English:** The public demo is hosted in Hong Kong and its network conditions and load may be unstable. Latency, disconnections, or temporary downtime do not represent a self-hosted deployment. Do not rely on this node for important or long-running sessions.
|
||||
|
||||
<a id="community"></a>
|
||||
- [简体中文](./docs/README.zh-CN.md)
|
||||
- [English](./docs/README.en.md)
|
||||
- [Deutsch](./docs/README.de.md)
|
||||
- [Русский](./docs/README.ru.md)
|
||||
- [日本語](./docs/README.ja.md)
|
||||
- [皮肤开发规范](./docs/SKIN_DEVELOPMENT.md)
|
||||
- [WebSpeak 皮肤开发 Agent Skill](./.agents/skills/webspeak-skin-development/SKILL.md)
|
||||
|
||||
## 社区 · Community
|
||||
|
||||
@@ -94,639 +54,44 @@
|
||||
<img src="./web/public/qq-group-qr.jpg" alt="WebSpeak QQ 群二维码" width="290" />
|
||||
</a>
|
||||
|
||||
**群号 / Group ID:`869500475`**
|
||||
**QQ群 / QQ group:`869500475`**
|
||||
|
||||
[通过群聊链接直接加入 / Join directly through the group link](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
|
||||
[通过群聊链接直接加入 / Join directly](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
|
||||
|
||||
中文:在群内获取部署帮助、版本通知和使用交流。<br />
|
||||
English: Join for deployment help, release announcements, and user discussion.<br />
|
||||
Deutsch: Hilfe bei der Bereitstellung, Versionsankündigungen und Austausch in der Community.<br />
|
||||
Telegram: [Join the Telegram group](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
[Telegram 群组 / Telegram group](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
## 友链项目 · Friend projects
|
||||
|
||||
<a id="简体中文"></a>
|
||||
### [NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot)
|
||||
|
||||
## 简体中文
|
||||
面向 TeamSpeak 3/6 的多平台音乐点播机器人,支持网易云音乐、QQ 音乐和 Bilibili 音频播放,并提供 Web 控制台。<br />
|
||||
A multi-platform music bot for TeamSpeak 3/6 with Netease Cloud Music, QQ Music, and Bilibili playback, plus a web console.<br />
|
||||
Ein plattformübergreifender Musikbot für TeamSpeak 3/6 mit Netease Cloud Music, QQ Music und Bilibili sowie Webkonsole.
|
||||
|
||||
WebSpeak 面向希望通过网页提供 TeamSpeak 语音服务的个人、社区和服务器管理员。它提供完整的访客页面、语音工作区和管理控制台,并可使用 Docker、预编译包或源码部署。
|
||||
## Contributors · 贡献者
|
||||
|
||||
<a id="zh-screenshots"></a>
|
||||
感谢提交 PR 的贡献者:
|
||||
|
||||
### 🖼️ 界面截图
|
||||
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2):浏览器端报错翻译与提示改造。
|
||||
|
||||
以下截图来自上海测试节点,展示中文界面下的欢迎页、语音工作区、音量控制和成员操作菜单。
|
||||
|
||||
#### 欢迎页
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-zh-home.png" alt="WebSpeak 中文欢迎页" width="100%" />
|
||||
</p>
|
||||
|
||||
#### 语音工作区
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-zh.png" alt="WebSpeak 中文语音工作区" width="100%" />
|
||||
</p>
|
||||
|
||||
#### 音量控制
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-zh-audio.png" alt="WebSpeak 中文音量控制" width="100%" />
|
||||
</p>
|
||||
|
||||
#### 成员右键菜单
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-zh-menu.png" alt="WebSpeak 中文成员右键菜单" width="100%" />
|
||||
</p>
|
||||
|
||||
<a id="zh-features"></a>
|
||||
|
||||
### ✨ 特性
|
||||
|
||||
| 能力 | 说明 |
|
||||
| --- | --- |
|
||||
| TeamSpeak 兼容 | 支持 TeamSpeak 3 与 TeamSpeak 6,并自动探测目标服务器协议。 |
|
||||
| 频道与成员 | 浏览完整频道树、查看各频道成员和实时状态,并可切换频道。 |
|
||||
| 实时语音 | 使用 Opus 语音;支持兼容传输和可选的内置 WebRTC 低延迟传输。 |
|
||||
| 音频控制 | 选择麦克风与扬声器、调节输入/输出音量、测试麦克风、闭麦、VOX,以及单独调整成员音量。 |
|
||||
| 消息与互动 | 支持频道消息、服务器消息、私聊、戳一戳和耳语目标。 |
|
||||
| 桌面端伴奏 | 在桌面浏览器中选择带音频的窗口或标签页,将其声音分享给当前 TeamSpeak 频道。 |
|
||||
| 身份与访问 | 支持浏览器身份保持、默认目标、访客自定义目标及可撤销、可过期的邀请链接。 |
|
||||
| 管理控制台 | 管理默认目标、访问策略、WebRTC、邀请链接、活动会话、连接历史、日志、诊断与数据库备份。 |
|
||||
| 界面体验 | 提供中文、English 和 Deutsch 界面、浅色/深色主题,以及桌面端和移动端响应式布局。 |
|
||||
| 自托管 | 数据由部署者保存;提供 Docker 镜像、Windows x64 和 Linux x64 发布包。 |
|
||||
|
||||
<a id="zh-advanced"></a>
|
||||
|
||||
### 🧩 高级功能
|
||||
|
||||
高级功能都是可选项;不开启时,WebSpeak 仍可使用兼容语音传输。配置入口均在管理员控制台的“服务器”页,保存后对新连接生效。
|
||||
|
||||
#### WebRTC 低延迟语音
|
||||
|
||||
WebRTC 将浏览器的实时语音从兼容传输切换为更适合实时音频的媒体通道,也支持桌面端伴奏。它由当前 WebSpeak 网关直接提供,不需要另设媒体服务器。
|
||||
|
||||
1. 登录 `/admin`,打开“服务器”页的“高级参数”。
|
||||
2. 关闭 WebRTC 时设置 UDP 起止端口;默认范围为 `40000–40099`。
|
||||
3. 在 WebSpeak 主机的云安全组和防火墙中放行完整 UDP 范围。Docker Compose 使用项目默认配置时,应让宿主机直接承载这些端口。
|
||||
4. 勾选“启用 WebRTC”并保存。用户重新进入后即可协商 WebRTC;浏览器或网络不支持时会自动回退到兼容模式。
|
||||
|
||||
启用后端口范围会锁定;要修改范围,先关闭 WebRTC 并保存,再修改端口并重新放行。公网使用时还需要 HTTPS,浏览器才会稳定提供麦克风和窗口音频权限。
|
||||
|
||||
#### 中继服务器 / 国内服务器加速
|
||||
|
||||
中继用于目标 TeamSpeak 服务器拒绝境外连接或直连不稳定的场景。它不是 VPN,只转发当前 WebSpeak 会话的 TeamSpeak UDP 数据;目标服务器仍由用户在网页中选择。
|
||||
|
||||
**部署中继模式:**
|
||||
|
||||
中继模式是 WebSpeak 的专用转发实例:不提供欢迎页、管理员后台,也不允许用户直接登录,只接受已配置网关使用匹配令牌转发的会话。令牌必须是至少 16 个字符的随机值,并在中继与网关管理控制台中保持一致:
|
||||
|
||||
```bash
|
||||
WEBSPEAK_MODE=relay \
|
||||
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
WEBSPEAK_RELAY_HOST='0.0.0.0' \
|
||||
WEBSPEAK_RELAY_PORT='39087' \
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
也可以使用发布的 Docker 镜像启动独立中继:
|
||||
|
||||
```bash
|
||||
docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
-e WEBSPEAK_MODE=relay \
|
||||
-e WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
-e WEBSPEAK_RELAY_PORT='39087' \
|
||||
ghcr.io/echosixhiya/webspeak:latest
|
||||
```
|
||||
|
||||
放行中继主机的 UDP 监听端口(默认 `39087`)。默认情况下,中继拒绝显式写入的回环、私网和保留地址;只有在可信内网中确实需要访问这类目标时,才在中继进程设置 `WEBSPEAK_RELAY_ALLOW_PRIVATE=true`。
|
||||
|
||||
**在 WebSpeak 中启用:**
|
||||
|
||||
1. 管理员控制台 → “服务器” → “中继服务器”,添加一个或多个节点。
|
||||
2. 为每个节点填写显示名称、地址(例如 `relay.example.com#39087`)和匹配令牌,并保存。
|
||||
3. 访客欢迎页会显示可用节点;用户可为当前连接选择直连或其中一个中继。
|
||||
|
||||
关闭并保存中继配置后,访客页面不会继续显示该选项;环境变量不会替代管理员控制台中的公开网关配置。
|
||||
|
||||
#### 依赖与归属
|
||||
|
||||
- **中继服务:** WebSpeak 自带实现,基于 Node.js 标准库 `node:dgram`、`node:crypto`、`node:dns/promises` 和 `node:net`,不使用 GOST、sing-box 或其他代理框架。
|
||||
- **WebRTC:** 使用 [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`,其上游项目采用 MIT 许可证。
|
||||
- **TeamSpeak 协议:** 使用项目维护的 [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js) SDK fork;它负责 TeamSpeak 协议连接,不是中继服务本身。
|
||||
|
||||
<a id="zh-changelog"></a>
|
||||
|
||||
### 🧾 更新日志
|
||||
|
||||
| 版本 | 日期 | 摘要 |
|
||||
| --- | --- | --- |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | 2026-09-10 | 修复连接错误显示并增加服务器密码提示与重试;加入正式中继部署模式、多中继节点选择和高级功能配置教程,优化管理员历史连接日志的原因显示。 |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | 2026-09-08 | 简化 Docker 部署并支持连接同机 TeamSpeak;开放模式加强目标校验;SDK 增加 15 秒连接超时;网络性能面板改为每 3 秒持续监测。 |
|
||||
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | 增加德语支持、Telegram 群组入口、网络性能面板和丢包率测试;管理员测试不再创建临时客户端,并修复语言菜单留白与伴奏音量波动。 |
|
||||
| [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) | 2026-09-04 | 新增桌面端伴奏、身份保持提醒和网站图标,并修复 WebRTC 下的成员独立音量。 |
|
||||
| [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) | 2026-09-04 | 修复身份保持逻辑,优化主题切换按钮。 |
|
||||
| [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) | 2026-09-03 | 修复 WebRTC 语音和频道聊天,优化管理页、日志与移动端布局。 |
|
||||
| [v0.1.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.3) | 2026-09-03 | 引入内置 WebRTC,迁移 TeamSpeak SDK,并改善成员同步和语音缓冲。 |
|
||||
| [v0.1.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.2) | 2026-09-02 | 大幅改进移动端、设备选择、AudioWorklet 和响应式顶部操作。 |
|
||||
| [v0.1.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.1) | 2026-09-02 | 完成网页客户端、管理后台、邀请链接及运维能力的首轮规范化。 |
|
||||
| [v0.1.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.0) | 2026-08-31 | 首个规范化版本。 |
|
||||
|
||||
完整记录见 [CHANGELOG.md](./CHANGELOG.md)。
|
||||
|
||||
<a id="zh-deployment"></a>
|
||||
|
||||
### 🚀 部署方案
|
||||
|
||||
| 方案 | 适用场景 | 运行环境 |
|
||||
| --- | --- | --- |
|
||||
| **Docker Compose(推荐)** | 服务器长期运行、便于升级和持久化 | Docker Engine + Docker Compose |
|
||||
| **发布包** | 不希望安装 Node.js 或构建依赖 | Windows x64 或 Linux x64 |
|
||||
| **源码运行** | 开发、调试或二次开发 | Node.js 22.5+、Git 与本地编译工具 |
|
||||
|
||||
#### Docker Compose(推荐)
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
启动后访问 `http://<你的主机>:3040`。如使用反向代理,将上游设置为 `http://<你的主机>:3040`;启用 WebRTC 时,放行管理后台显示的 UDP 端口范围。数据保存在 Docker volume `webspeak-data`。查看状态:
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
升级:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
不要执行 `docker compose down -v`,否则会删除数据库、管理员设置和其他持久化数据。
|
||||
|
||||
#### Windows / Linux 发布包
|
||||
|
||||
1. 从 [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 下载对应的 `windows-x64.zip` 或 `linux-x64.tar.gz`。
|
||||
2. 解压到独立目录。
|
||||
3. Windows 运行 `start-webspeak.cmd`;Linux 运行 `./start-webspeak.sh`。
|
||||
4. 发布包自带 Node.js 运行时和生产依赖,无需再次执行 `npm install`。
|
||||
|
||||
#### 源码运行
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
源码构建 `@discordjs/opus` 时需要 Python、Make 和 C/C++ 编译工具。开发模式可分别使用 `npm run dev` 与 `npm run web:dev`。
|
||||
|
||||
#### 首次配置(所有方案)
|
||||
|
||||
1. 打开 `http://<你的主机>:3040/admin`。
|
||||
2. 使用默认账号 `admin`、默认密码 `admin` 登录,并按提示立即设置至少 12 位的新密码。
|
||||
3. 在“服务器”页填写默认 TeamSpeak 目标和访问方式;目标可写为 `voice.example.com#9987`。
|
||||
4. 公网使用时为站点配置 HTTPS。若启用 WebRTC,还需放行管理后台显示的 UDP 端口范围。
|
||||
|
||||
<a id="zh-requirements"></a>
|
||||
|
||||
### ⚠️ 要求和注意事项
|
||||
|
||||
| 项目 | 要求或注意事项 |
|
||||
| --- | --- |
|
||||
| 浏览器 | 建议使用最新版 Chrome、Edge 或其他支持 WebRTC 的现代浏览器。麦克风和屏幕音频通常要求 HTTPS 安全上下文。 |
|
||||
| TeamSpeak 网络 | WebSpeak 主机必须能够访问目标 TeamSpeak 服务器。目标默认语音端口为 `9987`,也可在网页中填写其他端口。 |
|
||||
| Web 服务网络 | 服务使用 `3040/TCP`。公网部署建议通过 HTTPS 反向代理提供网页和 WebSocket。 |
|
||||
| WebRTC | 默认使用 `40000–40099/UDP`,请在云安全组和主机防火墙中放行。自定义范围时同步放行对应端口;启用 WebRTC 后需先关闭它才能修改端口范围。 |
|
||||
| 身份保持 | 同一浏览器身份同时只能保持一条活动连接。需要并行连接时,请取消第二条连接的“保持身份”,或使用另一个浏览器/浏览器配置文件。 |
|
||||
| 伴奏 | 仅桌面端提供,并要求启用 WebRTC。选择窗口或标签页时必须同时勾选共享音频;浏览器无法直接任意读取本地应用音频。 |
|
||||
| 数据 | Docker 数据位于 `webspeak-data` volume;发布包和源码运行的数据位于程序目录的 `data/`。升级或迁移前建议从管理后台导出数据库备份。 |
|
||||
| 会话上限 | 单实例最多允许 100 个活动网页会话。 |
|
||||
| 项目关系 | WebSpeak 是社区项目,不是 TeamSpeak 官方产品;TeamSpeak 名称及商标归其权利人所有。 |
|
||||
|
||||
<a id="zh-license"></a>
|
||||
|
||||
### 📜 许可证
|
||||
## 许可证 · License · Lizenz · Лицензия · ライセンス
|
||||
|
||||
WebSpeak 使用 [GNU Affero General Public License v3.0 only](./LICENSE) 发布。你可以使用、研究、修改和再分发本项目;如果修改后的版本通过网络向用户提供服务,需要按照 AGPL-3.0 向这些用户提供对应源代码。
|
||||
|
||||
<div align="right"><a href="#readme-top">返回顶部 ↑</a></div>
|
||||
WebSpeak is released under the [GNU Affero General Public License v3.0 only](./LICENSE). If a modified version is offered to users over a network, its corresponding source code must be offered under AGPL-3.0.
|
||||
|
||||
---
|
||||
WebSpeak wird unter der [GNU Affero General Public License v3.0 only](./LICENSE) veröffentlicht. Bei Bereitstellung einer veränderten Version über ein Netzwerk muss der entsprechende Quellcode unter AGPL-3.0 angeboten werden.
|
||||
|
||||
<a id="english"></a>
|
||||
WebSpeak распространяется по лицензии [GNU Affero General Public License v3.0 only](./LICENSE). Если изменённая версия предоставляется пользователям через сеть, соответствующий исходный код должен быть доступен этим пользователям на условиях AGPL-3.0.
|
||||
|
||||
## English
|
||||
WebSpeak は [GNU Affero General Public License v3.0 only](./LICENSE) の下で公開されています。変更版をネットワーク経由でユーザーに提供する場合は、対応するソースコードを AGPL-3.0 に従ってユーザーに提供する必要があります。
|
||||
|
||||
WebSpeak is built for individuals, communities, and server operators who want to offer TeamSpeak voice access through the web. It includes a complete visitor page, voice workspace, and administration console, with Docker, prebuilt-package, and source deployment options.
|
||||
## Star History
|
||||
|
||||
<a id="en-screenshots"></a>
|
||||
<a href="https://star-history.com/#EchoSixHIYA/WebSpeak-client-for-TeamSpeak&Date">
|
||||
<img src="https://api.star-history.com/svg?repos=EchoSixHIYA/WebSpeak-client-for-TeamSpeak&type=Date" alt="WebSpeak Star History" width="100%" />
|
||||
</a>
|
||||
|
||||
### 🖼️ Screenshots
|
||||
|
||||
These screenshots come from the Shanghai test node and show the welcome page, voice workspace, audio controls, and member actions in English.
|
||||
|
||||
#### Welcome page
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-en-home.png" alt="WebSpeak English welcome page" width="100%" />
|
||||
</p>
|
||||
|
||||
#### Voice workspace
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-en.png" alt="WebSpeak English voice workspace" width="100%" />
|
||||
</p>
|
||||
|
||||
#### Audio controls
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-en-audio.png" alt="WebSpeak English audio controls" width="100%" />
|
||||
</p>
|
||||
|
||||
#### Member context menu
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-en-menu.png" alt="WebSpeak English member context menu" width="100%" />
|
||||
</p>
|
||||
|
||||
<a id="en-features"></a>
|
||||
|
||||
### ✨ Features
|
||||
|
||||
| Capability | Description |
|
||||
| --- | --- |
|
||||
| TeamSpeak compatibility | Supports TeamSpeak 3 and TeamSpeak 6 and automatically detects the target server protocol. |
|
||||
| Channels and members | Browse the complete channel tree, see members and live states in each channel, and switch channels. |
|
||||
| Realtime voice | Uses Opus audio with a compatibility transport and an optional bundled WebRTC low-latency transport. |
|
||||
| Audio controls | Select microphones and speakers, adjust input/output volume, test the microphone, mute, use VOX, and control each member's volume. |
|
||||
| Messaging and actions | Supports channel chat, server chat, private messages, poke actions, and whisper targets. |
|
||||
| Desktop accompaniment | Select an audio-enabled window or browser tab on desktop and share its sound with the current TeamSpeak channel. |
|
||||
| Identity and access | Supports remembered browser identities, a default target, visitor-defined targets, and revocable expiring invite links. |
|
||||
| Administration | Manage the default target, access policy, WebRTC, invites, active sessions, connection history, logs, diagnostics, and database backups. |
|
||||
| User experience | Chinese, English, and German interfaces, light/dark themes, and responsive desktop/mobile layouts. |
|
||||
| Self-hosting | Data stays with the operator; Docker images and Windows x64 / Linux x64 packages are provided. |
|
||||
|
||||
<a id="en-advanced"></a>
|
||||
|
||||
### 🧩 Advanced features
|
||||
|
||||
These features are optional. WebSpeak continues to work with its compatibility voice transport when they are disabled. Configure them from **Administration → Servers**; saved changes apply to new connections.
|
||||
|
||||
#### WebRTC low-latency voice
|
||||
|
||||
WebRTC moves browser voice from the compatibility transport to a realtime media path and also enables desktop accompaniment. The current WebSpeak gateway provides it directly; no separate media server is required.
|
||||
|
||||
1. Sign in at `/admin` and open **Advanced settings** on the **Servers** page.
|
||||
2. While WebRTC is disabled, choose the UDP start and end ports. The default range is `40000–40099`.
|
||||
3. Allow the complete UDP range in the WebSpeak host's cloud security group and firewall. With the default Docker Compose file, let the host receive these ports directly.
|
||||
4. Enable **WebRTC** and save. New visitors will negotiate WebRTC; unsupported browsers or networks fall back to the compatibility transport.
|
||||
|
||||
The port range is locked while WebRTC is enabled. Disable and save WebRTC before changing it, then update the firewall rules. Public deployments also need HTTPS for reliable microphone and window-audio permissions.
|
||||
|
||||
#### Relay server / mainland acceleration
|
||||
|
||||
Use a relay when a TeamSpeak server rejects connections from outside its region or when a direct path is unstable. It is not a VPN: it forwards only the TeamSpeak UDP traffic of the current WebSpeak session, while the visitor still chooses the target server in the web page.
|
||||
|
||||
**Run relay mode:**
|
||||
|
||||
Relay mode is a dedicated WebSpeak forwarding instance: it exposes no welcome page or administration console and does not accept direct user sessions. It only accepts gateway sessions carrying a matching relay token. Use a random token of at least 16 characters and configure the same token on the relay and in the gateway administration console:
|
||||
|
||||
```bash
|
||||
WEBSPEAK_MODE=relay \
|
||||
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
WEBSPEAK_RELAY_HOST='0.0.0.0' \
|
||||
WEBSPEAK_RELAY_PORT='39087' \
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
You can also run a standalone relay from the published Docker image:
|
||||
|
||||
```bash
|
||||
docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
-e WEBSPEAK_MODE=relay \
|
||||
-e WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
-e WEBSPEAK_RELAY_PORT='39087' \
|
||||
ghcr.io/echosixhiya/webspeak:latest
|
||||
```
|
||||
|
||||
Allow the relay host's UDP listen port (default `39087`). The relay blocks explicitly entered loopback, private, and reserved targets by default. Only set `WEBSPEAK_RELAY_ALLOW_PRIVATE=true` when a trusted internal deployment deliberately needs those targets.
|
||||
|
||||
**Enable it in WebSpeak:**
|
||||
|
||||
1. Open **Administration → Servers → Relay server** and add one or more nodes.
|
||||
2. Set each node's display name, endpoint (for example `relay.example.com#39087`), and matching token, then save.
|
||||
3. The welcome page lists the available nodes; visitors can choose direct access or one relay for the current connection.
|
||||
|
||||
Disable and save the relay configuration to remove the option from the welcome page. Environment variables do not replace the public gateway configuration saved in the administration console.
|
||||
|
||||
#### Dependencies and attribution
|
||||
|
||||
- **Relay service:** built into WebSpeak with Node.js built-ins (`node:dgram`, `node:crypto`, `node:dns/promises`, and `node:net`); it does not use GOST, sing-box, or another proxy framework.
|
||||
- **WebRTC:** uses [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`, whose upstream project is licensed under MIT.
|
||||
- **TeamSpeak protocol:** uses the project-maintained [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js) SDK fork. This handles TeamSpeak protocol connectivity; it is not the relay implementation.
|
||||
|
||||
<a id="en-changelog"></a>
|
||||
|
||||
### 🧾 Changelog
|
||||
|
||||
| Version | Date | Summary |
|
||||
| --- | --- | --- |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | 2026-09-10 | Fixed connection-error reporting, added server-password prompts and retry, introduced formal relay deployment, multi-relay selection, and advanced-feature guidance, and improved reason reporting in administrator connection history. |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | 2026-09-08 | Simplified Docker deployment for local TeamSpeak targets; hardened open-target validation; added a 15-second SDK connection timeout; network metrics now refresh every 3 seconds. |
|
||||
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | Added German support, a Telegram community link, network performance and packet-loss checks; admin tests no longer create temporary clients, and language-menu spacing and accompaniment volume fluctuations were fixed. |
|
||||
| [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) | 2026-09-04 | Added desktop accompaniment, remembered-identity guidance, and the site icon; fixed per-member volume under WebRTC. |
|
||||
| [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) | 2026-09-04 | Fixed identity persistence and refined the theme switch. |
|
||||
| [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) | 2026-09-03 | Fixed WebRTC voice and channel chat; improved administration, logs, and mobile layouts. |
|
||||
| [v0.1.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.3) | 2026-09-03 | Added bundled WebRTC, migrated the TeamSpeak SDK, and improved member sync and voice buffering. |
|
||||
| [v0.1.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.2) | 2026-09-02 | Major mobile, device-selection, AudioWorklet, and responsive-header improvements. |
|
||||
| [v0.1.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.1) | 2026-09-02 | First normalized browser client, admin console, invite, and operations feature set. |
|
||||
| [v0.1.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.0) | 2026-08-31 | First normalized release. |
|
||||
|
||||
See [CHANGELOG.md](./CHANGELOG.md) for the complete history.
|
||||
|
||||
<a id="en-deployment"></a>
|
||||
|
||||
### 🚀 Deployment
|
||||
|
||||
| Method | Best for | Runtime |
|
||||
| --- | --- | --- |
|
||||
| **Docker Compose (recommended)** | Long-running servers, simple upgrades, and persistent data | Docker Engine + Docker Compose |
|
||||
| **Release packages** | Running without installing Node.js or build dependencies | Windows x64 or Linux x64 |
|
||||
| **From source** | Development, debugging, and customization | Node.js 22.5+, Git, and native build tools |
|
||||
|
||||
#### Docker Compose (recommended)
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
After startup, open `http://<your-host>:3040`. If you use a reverse proxy, set its upstream to `http://<your-host>:3040`. When WebRTC is enabled, allow the UDP range shown in the administration console. Persistent data is stored in the `webspeak-data` Docker volume. Check the service with:
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
Upgrade with:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Do not run `docker compose down -v`; it removes the database, administrator settings, and other persistent data.
|
||||
|
||||
#### Windows / Linux release packages
|
||||
|
||||
1. Download the matching `windows-x64.zip` or `linux-x64.tar.gz` from [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest).
|
||||
2. Extract it into a dedicated directory.
|
||||
3. Run `start-webspeak.cmd` on Windows or `./start-webspeak.sh` on Linux.
|
||||
4. Release packages include the Node.js runtime and production dependencies; do not run `npm install` inside them.
|
||||
|
||||
#### Run from source
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
Building `@discordjs/opus` requires Python, Make, and a C/C++ toolchain. For development, run `npm run dev` and `npm run web:dev` separately.
|
||||
|
||||
#### First-time setup (all methods)
|
||||
|
||||
1. Open `http://<your-host>:3040/admin`.
|
||||
2. Sign in with the default username `admin` and password `admin`, then immediately set a new password of at least 12 characters as prompted.
|
||||
3. Configure the default TeamSpeak target and access mode on the **Servers** page. A target can be written as `voice.example.com#9987`.
|
||||
4. Configure HTTPS for public access. If WebRTC is enabled, also allow the UDP range shown in the administration console.
|
||||
|
||||
<a id="en-requirements"></a>
|
||||
|
||||
### ⚠️ Requirements and notes
|
||||
|
||||
| Area | Requirement or note |
|
||||
| --- | --- |
|
||||
| Browser | Use a current Chrome, Edge, or another modern browser with WebRTC support. Microphone and shared-screen audio normally require an HTTPS secure context. |
|
||||
| TeamSpeak network | The WebSpeak host must be able to reach the target TeamSpeak server. The default voice port is `9987`, and other ports can be entered in the web interface. |
|
||||
| Web network | The service uses `3040/TCP`. Public deployments should expose the page and WebSocket through an HTTPS reverse proxy. |
|
||||
| WebRTC | The default range is `40000–40099/UDP`; allow it in the cloud security group and host firewall. For a custom range, allow the corresponding ports. Disable WebRTC before changing the range. |
|
||||
| Remembered identity | One browser identity can hold only one active remembered connection at a time. For parallel connections, disable **Remember identity** on the second connection or use another browser/profile. |
|
||||
| Accompaniment | Desktop only and requires WebRTC. When selecting a window or tab, enable audio sharing as well. Browsers cannot arbitrarily capture every local application's audio. |
|
||||
| Data | Docker data is stored in the `webspeak-data` volume. Release packages and source installs store data in the program directory's `data/` folder. Export a database backup from the admin console before upgrades or migration. |
|
||||
| Session limit | One instance accepts up to 100 active browser sessions. |
|
||||
| Project relationship | WebSpeak is a community project and is not an official TeamSpeak product. TeamSpeak names and trademarks belong to their respective owners. |
|
||||
|
||||
<a id="en-license"></a>
|
||||
|
||||
### 📜 License
|
||||
|
||||
WebSpeak is released under the [GNU Affero General Public License v3.0 only](./LICENSE). You may use, study, modify, and redistribute the project. If a modified version is made available to users over a network, the corresponding source code must be offered to those users under AGPL-3.0.
|
||||
|
||||
<div align="right"><a href="#readme-top">Back to top ↑</a></div>
|
||||
|
||||
---
|
||||
|
||||
<a id="deutsch"></a>
|
||||
|
||||
## Deutsch
|
||||
|
||||
WebSpeak ist ein selbst gehosteter TeamSpeak-3-/TeamSpeak-6-Webclient und ein Sprach-Gateway. Nutzer können direkt im Browser Kanälen beitreten, sprechen und chatten; Administratoren verwalten Zielserver und Zugriff über die Webkonsole.
|
||||
|
||||
<a id="de-screenshots"></a>
|
||||
|
||||
### 🖼️ Screenshots
|
||||
|
||||
Diese Screenshots stammen vom Shanghai-Testknoten und zeigen die Willkommensseite, den Sprachbereich, die Audiosteuerung und das Mitglieder-Menü auf Deutsch.
|
||||
|
||||
#### Willkommensseite
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-de-home.png" alt="WebSpeak deutsche Willkommensseite" width="100%" />
|
||||
</p>
|
||||
|
||||
#### Sprachbereich
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-de.png" alt="WebSpeak deutscher Sprachbereich" width="100%" />
|
||||
</p>
|
||||
|
||||
#### Audiosteuerung
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-de-audio.png" alt="WebSpeak deutsche Audiosteuerung" width="100%" />
|
||||
</p>
|
||||
|
||||
#### Mitglieder-Menü
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-de-menu.png" alt="WebSpeak deutsches Mitglieder-Menü" width="100%" />
|
||||
</p>
|
||||
|
||||
<a id="de-features"></a>
|
||||
|
||||
### ✨ Funktionen
|
||||
|
||||
| Funktion | Beschreibung |
|
||||
| --- | --- |
|
||||
| TeamSpeak-Kompatibilität | Unterstützt TeamSpeak 3 und TeamSpeak 6 und erkennt das Protokoll des Zielservers automatisch. |
|
||||
| Kanäle und Mitglieder | Zeigt die Kanalstruktur, Mitglieder und ihren aktuellen Status an. |
|
||||
| Echtzeit-Sprache | Opus-Audio mit kompatiblem Transport und optionalem integriertem WebRTC für geringere Latenz. |
|
||||
| Audiosteuerung | Mikrofon und Lautsprecher auswählen, Lautstärke anpassen, testen und einzelne Mitglieder regeln. |
|
||||
| Nachrichten und Interaktion | Kanal- und Serverchat, private Nachrichten, Anstupsen und Flüsterziele. |
|
||||
| Begleitton auf dem Desktop | Audio eines freigegebenen Fensters oder Browser-Tabs mit dem TeamSpeak-Kanal teilen. |
|
||||
| Identität und Zugriff | Geräteidentität speichern, Standardziele verwalten, eigene Ziele erlauben und zeitlich begrenzte Einladungen erstellen. |
|
||||
| Administrationskonsole | Ziele, Zugriff, WebRTC, Sitzungen, Verbindungen, Protokolle, Diagnosen und Datenbanksicherungen verwalten. |
|
||||
| Responsive Oberfläche | Deutsche, englische und chinesische Oberfläche, helle/dunkle Designs sowie Desktop- und Mobilansicht. |
|
||||
| Selbst gehostet | Die Daten bleiben beim Betreiber; Docker-, Windows-x64- und Linux-x64-Pakete sind verfügbar. |
|
||||
|
||||
<a id="de-advanced"></a>
|
||||
|
||||
### 🧩 Erweiterte Funktionen
|
||||
|
||||
Diese Funktionen sind optional. Ohne sie arbeitet WebSpeak weiterhin mit dem kompatiblen Sprachtransport. Die Einstellungen befinden sich unter **Administration → Server** und gelten für neue Verbindungen.
|
||||
|
||||
#### WebRTC-Sprache mit niedriger Latenz
|
||||
|
||||
WebRTC verwendet für Browser-Sprache einen Echtzeit-Medienpfad und ermöglicht außerdem Desktop-Begleitton. Der aktuelle WebSpeak-Gateway stellt WebRTC selbst bereit; ein zusätzlicher Medienserver ist nicht erforderlich.
|
||||
|
||||
1. Unter `/admin` anmelden und auf der Seite **Server** die **Erweiterten Einstellungen** öffnen.
|
||||
2. Bei deaktiviertem WebRTC Start- und Endport für UDP festlegen. Der Standardbereich ist `40000–40099`.
|
||||
3. Den gesamten UDP-Bereich in Sicherheitsgruppe und Firewall des WebSpeak-Hosts freigeben. Bei der Standard-Docker-Compose-Datei müssen diese Ports direkt am Host erreichbar sein.
|
||||
4. **WebRTC** aktivieren und speichern. Neue Besucher handeln WebRTC aus; nicht unterstützte Browser oder Netzwerke wechseln automatisch zum kompatiblen Transport.
|
||||
|
||||
Der Portbereich ist bei aktiviertem WebRTC gesperrt. Zum Ändern WebRTC zuerst deaktivieren und speichern, danach Firewall-Regeln anpassen. Für öffentliche Bereitstellungen ist außerdem HTTPS für Mikrofon- und Fenster-Audio-Berechtigungen erforderlich.
|
||||
|
||||
#### Relay-Server / Beschleunigung
|
||||
|
||||
Ein Relay hilft, wenn ein TeamSpeak-Server Verbindungen aus anderen Regionen ablehnt oder der direkte Weg instabil ist. Es ist kein VPN, sondern leitet nur den TeamSpeak-UDP-Verkehr der aktuellen WebSpeak-Sitzung weiter.
|
||||
|
||||
**Relay-Modus starten:**
|
||||
|
||||
Der Relay-Modus ist eine dedizierte WebSpeak-Weiterleitungsinstanz: Er stellt keine Willkommensseite und keine Administrationskonsole bereit und akzeptiert keine direkten Benutzersitzungen. Er akzeptiert nur Gateway-Sitzungen mit passendem Relay-Token. Ein zufälliges Token mit mindestens 16 Zeichen verwenden und dasselbe Token im Relay sowie in der WebSpeak-Administrationskonsole eintragen:
|
||||
|
||||
```bash
|
||||
WEBSPEAK_MODE=relay \
|
||||
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
WEBSPEAK_RELAY_HOST='0.0.0.0' \
|
||||
WEBSPEAK_RELAY_PORT='39087' \
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
Das UDP-Listening-Port des Relay-Hosts freigeben (Standard `39087`). Explizit eingetragene Loopback-, private und reservierte Ziele werden standardmäßig abgelehnt. `WEBSPEAK_RELAY_ALLOW_PRIVATE=true` nur in einer vertrauenswürdigen internen Umgebung setzen, wenn solche Ziele absichtlich benötigt werden.
|
||||
|
||||
Für Docker denselben veröffentlichten WebSpeak-Container im Relay-Modus starten:
|
||||
|
||||
```bash
|
||||
docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
-e WEBSPEAK_MODE=relay \
|
||||
-e WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
-e WEBSPEAK_RELAY_PORT='39087' \
|
||||
ghcr.io/echosixhiya/webspeak:latest
|
||||
```
|
||||
|
||||
**In WebSpeak aktivieren:**
|
||||
|
||||
1. **Administration → Server → Relay-Server** öffnen und einen oder mehrere Knoten hinzufügen.
|
||||
2. Für jeden Knoten Anzeigenamen, Endpunkt (zum Beispiel `relay.example.com#39087`) und passendes Token eintragen und speichern.
|
||||
3. Auf der Willkommensseite können Besucher eine direkte Verbindung oder einen der verfügbaren Relays auswählen.
|
||||
|
||||
Relay deaktivieren und speichern, um die Option von der Willkommensseite zu entfernen. Umgebungsvariablen ersetzen nicht die im Administrationsbereich gespeicherte öffentliche Gateway-Konfiguration.
|
||||
|
||||
#### Abhängigkeiten und Hinweise zur Herkunft
|
||||
|
||||
- **Relay-Dienst:** Bestandteil von WebSpeak und mit Node.js-Standardmodulen (`node:dgram`, `node:crypto`, `node:dns/promises`, `node:net`) implementiert; GOST, sing-box oder ein anderes Proxy-Framework wird nicht verwendet.
|
||||
- **WebRTC:** verwendet [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`; das Upstream-Projekt steht unter MIT-Lizenz.
|
||||
- **TeamSpeak-Protokoll:** verwendet den projektgepflegten [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js)-SDK-Fork. Dieser ist für die TeamSpeak-Protokollverbindung zuständig, nicht für den Relay-Dienst.
|
||||
|
||||
<a id="de-changelog"></a>
|
||||
|
||||
### 🧾 Änderungsprotokoll
|
||||
|
||||
| Version | Datum | Zusammenfassung |
|
||||
| --- | --- | --- |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | 2026-09-10 | Verbindungsfehleranzeigen korrigiert, Passwortabfrage und Wiederholung ergänzt, dedizierten Relay-Modus, Auswahl mehrerer Relay-Knoten und Anleitungen für erweiterte Funktionen hinzugefügt sowie die Ursachendarstellung im Verbindungsverlauf verbessert. |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | 2026-09-08 | Docker-Bereitstellung für lokale TeamSpeak-Ziele vereinfacht; Zielprüfung im offenen Modus gehärtet; 15-Sekunden-Timeout für SDK-Verbindungen ergänzt; Netzwerkmetriken werden alle 3 Sekunden aktualisiert. |
|
||||
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | Deutsche Oberfläche, Telegram-Link sowie Netzwerk- und Paketverlustprüfung hinzugefügt; Admin-Tests erzeugen keine temporären Clients mehr, außerdem wurden Sprachmenü-Leerraum und Begleitton-Schwankungen behoben. |
|
||||
| [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) | 2026-09-04 | Desktop-Begleitton, Hinweise zur Identität und Website-Symbol hinzugefügt; individuelle Lautstärke unter WebRTC korrigiert. |
|
||||
| [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) | 2026-09-04 | Identitätsspeicherung korrigiert und Designumschaltung verbessert. |
|
||||
| [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) | 2026-09-03 | WebRTC und Kanalchat korrigiert; Administrationsseite, Protokolle und Mobilansicht verbessert. |
|
||||
| [v0.1.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.3) | 2026-09-03 | Integriertes WebRTC, aktualisiertes TeamSpeak-SDK und bessere Mitgliedersynchronisierung. |
|
||||
|
||||
Vollständige Historie: [CHANGELOG.md](./CHANGELOG.md).
|
||||
|
||||
<a id="de-deployment"></a>
|
||||
|
||||
### 🚀 Bereitstellung
|
||||
|
||||
| Methode | Geeignet für | Umgebung |
|
||||
| --- | --- | --- |
|
||||
| **Docker Compose (empfohlen)** | Dauerbetrieb, einfache Updates und persistente Daten | Docker Engine + Docker Compose |
|
||||
| **Release-Paket** | Betrieb ohne Node.js und Build-Werkzeuge | Windows x64 oder Linux x64 |
|
||||
| **Aus dem Quellcode** | Entwicklung und Anpassungen | Node.js 22.5+, Git und native Build-Werkzeuge |
|
||||
|
||||
#### Docker Compose
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Nach dem Start ist WebSpeak unter `http://<dein-host>:3040` erreichbar. Bei einem Reverse Proxy muss das Upstream-Ziel `http://<dein-host>:3040` sein. Für WebRTC muss der im Adminbereich angezeigte UDP-Portbereich freigegeben werden. Die persistenten Daten liegen im Docker-Volume `webspeak-data`.
|
||||
|
||||
#### Release-Pakete
|
||||
|
||||
Lade das passende Paket von [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest), entpacke es in ein eigenes Verzeichnis und starte unter Windows `start-webspeak.cmd` bzw. unter Linux `./start-webspeak.sh`.
|
||||
|
||||
#### Erste Konfiguration
|
||||
|
||||
Öffne `/admin`, melde dich zunächst mit `admin` / `admin` an und ändere das Passwort. Konfiguriere anschließend das Standard-TeamSpeak-Ziel und die gewünschte Zugriffsmethode.
|
||||
|
||||
<a id="de-requirements"></a>
|
||||
|
||||
### ⚠️ Voraussetzungen und Hinweise
|
||||
|
||||
| Bereich | Hinweis |
|
||||
| --- | --- |
|
||||
| Browser | Aktuelles Chrome, Edge oder ein moderner WebRTC-fähiger Browser wird empfohlen. Für Mikrofon- und Bildschirm-Audio ist normalerweise HTTPS erforderlich. |
|
||||
| TeamSpeak-Netzwerk | Der WebSpeak-Host muss den Zielserver erreichen können. Der Standard-Sprachport ist `9987`; andere Ports können im Webinterface eingetragen werden. |
|
||||
| WebRTC | Der Standardbereich ist `40000–40099/UDP`; Firewall und Sicherheitsgruppe müssen den gesamten Bereich erlauben. Bei einem benutzerdefinierten Bereich sind die entsprechenden Ports freizugeben. |
|
||||
| Gespeicherte Identität | Eine Browseridentität kann nur eine aktive gespeicherte Verbindung gleichzeitig halten. Für parallele Verbindungen die Option deaktivieren oder ein anderes Browserprofil verwenden. |
|
||||
| Begleitton | Nur auf Desktop-Browsern verfügbar und WebRTC erforderlich. Bei der Freigabe eines Fensters oder Tabs muss auch Audio freigegeben werden. |
|
||||
| Selbsthosting | WebSpeak ist kein offizielles TeamSpeak-Produkt. Namen und Marken gehören den jeweiligen Rechteinhabern. |
|
||||
|
||||
<a id="de-license"></a>
|
||||
|
||||
### 📜 Lizenz
|
||||
|
||||
WebSpeak wird unter der [GNU Affero General Public License v3.0 only](./LICENSE) veröffentlicht. Bei Bereitstellung einer veränderten Version über ein Netzwerk muss der entsprechende Quellcode den Nutzern unter AGPL-3.0 angeboten werden.
|
||||
|
||||
<div align="right"><a href="#readme-top">Nach oben ↑</a></div>
|
||||
<div align="right"><a href="#readme-top">返回顶部 · Back to top ↑</a></div>
|
||||
@@ -0,0 +1,245 @@
|
||||
# WebSpeak · Deutsch
|
||||
|
||||
[Projektstartseite](../README.md) · [简体中文](./README.zh-CN.md) · [English](./README.en.md) · [Русский](./README.ru.md) · [日本語](./README.ja.md)
|
||||
|
||||
WebSpeak ist ein selbst gehosteter Webclient und ein Sprach-Gateway für TeamSpeak 3 und TeamSpeak 6. Nutzer können ohne Desktop-Client im Browser Kanälen beitreten; Administratoren verwalten Zielserver, Zugriff und Laufzeitstatus über die Webkonsole.
|
||||
|
||||
## Live-Demo
|
||||
|
||||
Adresse: <https://webspeak.example.invalid>
|
||||
|
||||
Die öffentliche Demo läuft in Hongkong. Netzwerkbedingungen und Auslastung können instabil sein; Latenz, Verbindungsabbrüche oder kurze Ausfälle beschreiben nicht jede eigene Bereitstellung.
|
||||
|
||||
## ✨ Funktionen
|
||||
|
||||
| Funktion | Beschreibung |
|
||||
| --- | --- |
|
||||
| TeamSpeak-Kompatibilität | Unterstützt TeamSpeak 3 und TeamSpeak 6 und erkennt das Zielprotokoll automatisch. |
|
||||
| Plattformübergreifendes P2P-Bildschirmteilen | Browsernutzer und native TeamSpeak-6-Clients können die Bildschirmfreigabe gegenseitig starten und ansehen; WebRTC/ICE überträgt Medien direkt, WebSpeak leitet nur die Signalisierung weiter. |
|
||||
| IPv6-Ziele | IPv6-TeamSpeak-Ziele und über DNS aufgelöste IPv6-Adressen werden standardmäßig unterstützt. |
|
||||
| Kanäle und Mitglieder | Kanalstruktur und aktuelle Mitglieder anzeigen und Kanäle wechseln. |
|
||||
| Echtzeit-Sprache | Opus-Audio mit kompatiblem Transport und optional integriertem WebRTC für geringere Latenz. |
|
||||
| Audiosteuerung | Mikrofon und Lautsprecher auswählen, Lautstärke regeln, testen, stummschalten, VOX und individuelle Mitgliedslautstärke. |
|
||||
| Browserseitige Geräuschunterdrückung | Optionale Mikrofon-Geräuschunterdrückung in der Browseraufnahme, ohne zusätzliche serverseitige Audioverarbeitung. |
|
||||
| Nachrichten und Aktionen | Kanal- und Serverchat, private Nachrichten, Anstupsen und Flüsterziele. |
|
||||
| Desktop-Begleitton | Audio eines freigegebenen Fensters oder Browser-Tabs im aktuellen Kanal teilen. |
|
||||
| Identität und Zugriff | Gespeicherte Identität, eigene Ziele und widerrufbare Einladungslinks mit Ablaufzeit. |
|
||||
| Administration | Ziele, Zugriff, WebRTC, Relays, Einladungen, Sitzungen, Protokolle, Diagnosen und Backups verwalten. |
|
||||
| Skins | Geschützte Tages-, Nacht- und ILLUSIA-Skins sowie instanzverwaltete `.wskin`-Designs mit Aktivierungs- und Standardauswahl im Adminbereich. |
|
||||
| Oberfläche | Chinesische, englische, deutsche, russische und japanische Oberfläche sowie responsive Desktop-/Mobilansicht. |
|
||||
| Selbsthosting | Daten bleiben beim Betreiber; Docker-, Windows-x64- und Linux-x64-Bereitstellung sind verfügbar. |
|
||||
|
||||
## 🖼️ Screenshots
|
||||
|
||||
Die Screenshots zeigen die deutsche Willkommensseite, den Sprachbereich, die Audiosteuerung und das Mitgliedermenü.
|
||||
|
||||
### Willkommensseite
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-de-home.png" alt="WebSpeak deutsche Willkommensseite" width="100%" /></p>
|
||||
|
||||
### Sprachbereich
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-de.png" alt="WebSpeak deutscher Sprachbereich" width="100%" /></p>
|
||||
|
||||
### Audiosteuerung
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-de-audio.png" alt="WebSpeak deutsche Audiosteuerung" width="100%" /></p>
|
||||
|
||||
### Mitgliedermenü
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-de-menu.png" alt="WebSpeak deutsches Mitgliedermenü" width="100%" /></p>
|
||||
|
||||
## 🧩 Erweiterte Funktionen
|
||||
|
||||
Diese Funktionen sind optional. Ohne sie arbeitet WebSpeak weiterhin mit dem kompatiblen Sprachtransport. Die Einstellungen befinden sich unter **Administration → Server** und gelten für neue Verbindungen.
|
||||
|
||||
### 1. WebRTC-Sprache mit niedriger Latenz
|
||||
|
||||
WebRTC verwendet für Browser-Sprache einen Echtzeit-Medienpfad und ermöglicht außerdem Desktop-Begleitton. Das aktuelle WebSpeak-Gateway stellt WebRTC selbst bereit; ein zusätzlicher Medienserver ist nicht erforderlich.
|
||||
|
||||
1. Unter `/admin` anmelden und auf der Seite **Server** die **Erweiterten Einstellungen** öffnen.
|
||||
2. Bei deaktiviertem WebRTC Start- und Endport für UDP festlegen. Der Standardbereich ist `40000–40099`.
|
||||
3. Den gesamten UDP-Bereich in Sicherheitsgruppe und Firewall des WebSpeak-Hosts freigeben.
|
||||
4. **WebRTC** aktivieren und speichern. Nicht unterstützte Browser oder Netzwerke wechseln automatisch zum kompatiblen Transport.
|
||||
|
||||
Der Portbereich ist bei aktiviertem WebRTC gesperrt. Zum Ändern WebRTC zuerst deaktivieren und speichern, danach die Firewall-Regeln anpassen. Für öffentliche Bereitstellungen ist HTTPS erforderlich.
|
||||
|
||||
### ICE-Kandidaten für Bildschirmfreigabe
|
||||
|
||||
Die Medien der Bildschirmfreigabe versuchen weiterhin eine direkte Browser-zu-Browser-Verbindung; WebSpeak leitet nur die Signalisierung weiter. Standardmäßig werden die öffentlichen TeamSpeak-STUN-Dienste zur Ermittlung öffentlicher Kandidaten verwendet. STUN überträgt keine Medien. Ein autorisierter externer TURN-Dienst kann über `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` als JSON-Array konfiguriert werden, zum Beispiel:
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
Mit TURN kann die Medienübertragung diesen externen Dienst verwenden, aber niemals das WebSpeak-Gateway. Ohne TURN werden nur direkte ICE-Pfade und STUN verwendet.
|
||||
|
||||
### Plattformübergreifendes P2P-Bildschirmteilen
|
||||
|
||||
Browsernutzer und native TeamSpeak-6-Clients können Bildschirmfreigaben gegenseitig erkennen, starten und ansehen. Zwischen Browsern sowie zwischen Browser und nativem Client werden die Bildschirmmedien möglichst über eine direkte WebRTC/ICE-Peer-to-Peer-Verbindung übertragen; WebSpeak übernimmt Sitzungsberechtigung, Freigabestatus und SDP-/ICE-Signalisierung, transportiert aber keine Bildschirmmedien. Die Oberfläche zeigt Live-Status und Zuschauerzahl und bietet Lautstärke-, Vollbild- und Beenden-Steuerung. Für die Aufnahme stehen bis zu 1080p und 60 FPS sowie WebRTC-Statistiken zur Verfügung.
|
||||
|
||||
### 2. Relay-Modus
|
||||
|
||||
Ein Relay hilft, wenn ein TeamSpeak-Server Verbindungen aus einer anderen Region ablehnt oder der direkte Weg instabil ist. Es ist kein VPN, sondern leitet nur den TeamSpeak-Verkehr der aktuellen WebSpeak-Sitzung weiter.
|
||||
|
||||
Eine Relay-Instanz ist ein dedizierter Weiterleitungsdienst ohne Besucher- oder Administrationsseite. Sie akzeptiert nur Gateway-Sitzungen mit passendem Token. Ein zufälliges Token mit mindestens 16 Zeichen verwenden.
|
||||
|
||||
#### Aus dem Quellcode starten
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm run build
|
||||
WEBSPEAK_MODE=relay \
|
||||
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
WEBSPEAK_RELAY_HOST='0.0.0.0' \
|
||||
WEBSPEAK_RELAY_PORT='39087' \
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
$env:WEBSPEAK_MODE = "relay"
|
||||
$env:WEBSPEAK_RELAY_TOKEN = "replace-with-a-long-random-token"
|
||||
$env:WEBSPEAK_RELAY_HOST = "0.0.0.0"
|
||||
$env:WEBSPEAK_RELAY_PORT = "39087"
|
||||
node .\dist\index.js
|
||||
```
|
||||
|
||||
#### Aus einem Release-Paket starten
|
||||
|
||||
Das passende Paket aus den [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) herunterladen und entpacken:
|
||||
|
||||
```bash
|
||||
# Linux
|
||||
export WEBSPEAK_MODE=relay
|
||||
export WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token'
|
||||
export WEBSPEAK_RELAY_HOST='0.0.0.0'
|
||||
export WEBSPEAK_RELAY_PORT='39087'
|
||||
./runtime/node ./dist/index.js
|
||||
```
|
||||
|
||||
Unter Windows PowerShell dieselben Variablen setzen und `.\runtime\node.exe .\dist\index.js` ausführen.
|
||||
|
||||
#### Mit Docker starten
|
||||
|
||||
```bash
|
||||
docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
-e WEBSPEAK_MODE=relay \
|
||||
-e WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
-e WEBSPEAK_RELAY_PORT='39087' \
|
||||
ghcr.io/echosixhiya/webspeak:latest
|
||||
```
|
||||
|
||||
Den UDP-Listening-Port des Relay-Hosts freigeben, standardmäßig `39087`.
|
||||
|
||||
#### Im Gateway aktivieren
|
||||
|
||||
1. **Administration → Server → Relay-Server** öffnen und einen oder mehrere Knoten hinzufügen.
|
||||
2. Für jeden Knoten einen Anzeigenamen, einen Endpunkt wie `relay.example.com#39087` und das passende Token eintragen und speichern.
|
||||
3. Besucher können auf der Willkommensseite Direktzugriff oder einen konfigurierten Relay-Knoten auswählen.
|
||||
|
||||
Relay deaktivieren und speichern, um die Option von der Willkommensseite zu entfernen.
|
||||
|
||||
### 3. Abhängigkeiten und Hinweise zur Herkunft
|
||||
|
||||
- Der Relay-Dienst ist Bestandteil von WebSpeak und verwendet Node.js-Standardbibliotheken; GOST, sing-box oder ein anderes Proxy-Framework werden nicht verwendet.
|
||||
- WebRTC verwendet [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`; das Upstream-Projekt steht unter MIT-Lizenz.
|
||||
- Die TeamSpeak-Protokollverbindung verwendet den projektgepflegten [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js)-SDK-Fork.
|
||||
|
||||
## 🧾 Änderungsprotokoll
|
||||
|
||||
| Version | Datum | Zusammenfassung |
|
||||
| --- | --- | --- |
|
||||
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | `.wskin`-Skins, Aktivierungs-/Standardverwaltung und geschützte Tages-, Nacht- und ILLUSIA-Skins ergänzt; unfertiges Aurora-Voice-Beispiel entfernt, Skin-Ladeblitze, dunkle Bedienelemente und Artwork-Ebenen im Sprachbereich korrigiert sowie offiziellen Skin-Entwicklungs-Agent-Skill hinzugefügt; ILLUSIA-Sprachillustration verkleinert und rechts unten verankert, damit Mitglieder und geteilte Videos sichtbar bleiben. |
|
||||
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | 2026-09-22 | Plattformübergreifendes P2P-Bildschirmteilen zwischen Browsern und nativen TeamSpeak-6-Clients ergänzt; STUN-/externes-TURN-Konfiguration, Live-Player und Zuschauerstatus, Aufnahmeoptionen bis 1080p/60 FPS und WebRTC-Statistiken hinzugefügt; Bildschirmfreigabe-Interaktion verbessert und Besucherzählung ergänzt. |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | Mitgliederplanung und direkte Verschiebung nach Berechtigung ergänzt; Avatar-, Stummschaltstatus- und Identitätsunterstützung hinzugefügt; Screenshots und Dokumentation für alle fünf Sprachen aktualisiert. |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | 2026-09-17 | Browserseitige Mikrofon-Geräuschunterdrückung, russische und japanische Oberfläche sowie sprachabhängige Begrüßungstexte ergänzt; Lautstärkeinteraktion und Fehlertexte/-codes auf Basis von PR #2 verbessert. |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | 2026-09-13 | Verbindungsfehler auf der Willkommensseite verbessert, Fehlercodes erhalten und sicher gekürzt sowie IPv6-Ziele standardmäßig unterstützt. |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | 2026-09-10 | Passwortabfrage, dedizierter Relay-Modus, Auswahl mehrerer Relays und Ursachendarstellung in der Administration ergänzt. |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | 2026-09-08 | Docker-Bereitstellung vereinfacht, lokale TeamSpeak-Ziele unterstützt, 15-Sekunden-Timeout ergänzt und kontinuierliche Netzwerküberwachung eingeführt. |
|
||||
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | Deutsch, Telegram, Netzwerkleistung und Gesamtlautstärke ergänzt; Lautstärkeschwankungen beim Begleitton behoben. |
|
||||
| [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) | 2026-09-04 | Desktop-Begleitton, Hinweise zur gespeicherten Identität und Website-Symbol ergänzt; WebRTC-Mitgliederlautstärke korrigiert. |
|
||||
| [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) | 2026-09-04 | Identitätsspeicherung korrigiert und Designumschaltung verbessert. |
|
||||
| [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) | 2026-09-03 | WebRTC und Kanalchat korrigiert sowie Administration, Protokolle und Mobilansicht verbessert. |
|
||||
| [v0.1.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.3) | 2026-09-03 | Integriertes WebRTC, aktualisiertes TeamSpeak-SDK und bessere Mitgliedersynchronisierung und Sprachpufferung. |
|
||||
|
||||
Vollständige Historie: [CHANGELOG.md](../CHANGELOG.md).
|
||||
|
||||
## 🚀 Bereitstellung
|
||||
|
||||
| Methode | Geeignet für | Umgebung |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose (empfohlen) | Dauerbetrieb, einfache Updates und persistente Daten | Docker Engine + Docker Compose |
|
||||
| Release-Paket | Betrieb ohne Node.js und Build-Werkzeuge | Windows x64 oder Linux x64 |
|
||||
| Aus dem Quellcode | Entwicklung und Anpassungen | Node.js 22.5+, Git und native Build-Werkzeuge |
|
||||
|
||||
### Docker Compose (empfohlen)
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Nach dem Start ist WebSpeak unter `http://<dein-host>:3040` erreichbar. Bei einem Reverse Proxy auf diese Adresse zeigen; für WebRTC den im Adminbereich angezeigten UDP-Bereich freigeben. Die Daten liegen im Volume `webspeak-data`.
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
Upgrade:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
`docker compose down -v` nicht ausführen, da dadurch Datenbank und Administratoreinstellungen gelöscht werden.
|
||||
|
||||
### Release-Paket
|
||||
|
||||
Das passende `windows-x64.zip` oder `linux-x64.tar.gz` aus den [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) herunterladen, in ein eigenes Verzeichnis entpacken und `start-webspeak.cmd` bzw. `./start-webspeak.sh` starten. Die Pakete enthalten Node.js und Produktionsabhängigkeiten.
|
||||
|
||||
### Aus dem Quellcode
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
Für den Bau von `@discordjs/opus` werden Python, Make und eine C/C++-Toolchain benötigt.
|
||||
|
||||
### Erste Konfiguration
|
||||
|
||||
1. `http://<dein-host>:3040/admin` öffnen.
|
||||
2. Mit `admin` / `admin` anmelden und sofort ein neues Passwort mit mindestens 12 Zeichen setzen.
|
||||
3. Unter **Server** TeamSpeak-Ziel und Zugriffsmethode konfigurieren, zum Beispiel `voice.example.com#9987`.
|
||||
4. Für öffentliche Nutzung HTTPS einrichten; bei aktiviertem WebRTC den im Adminbereich angezeigten UDP-Bereich freigeben.
|
||||
|
||||
## ⚠️ Voraussetzungen und Hinweise
|
||||
|
||||
| Bereich | Hinweis |
|
||||
| --- | --- |
|
||||
| Browser | Aktuelles Chrome, Edge oder ein moderner WebRTC-fähiger Browser wird empfohlen. Mikrofon- und Fenster-Audio benötigen normalerweise HTTPS. |
|
||||
| TeamSpeak-Netzwerk | Der WebSpeak-Host muss den Zielserver erreichen können; der Standard-Sprachport ist `9987`. |
|
||||
| Webnetzwerk | Der Dienst verwendet `3040/TCP`; öffentlich sollte ein HTTPS-Reverse-Proxy für Seite und WebSocket verwendet werden. |
|
||||
| IPv6 | Literale Ziele als `[2001:db8::1]#9987` eintragen. Host/Container benötigen geroutetes IPv6, aktiviertes IPv6 in Betriebssystem und Node.js sowie passende Firewall-Regeln. |
|
||||
| WebRTC | Standardbereich `40000–40099/UDP`; den gesamten Bereich freigeben und WebRTC vor einer Änderung deaktivieren. |
|
||||
| Gespeicherte Identität | Eine Browseridentität kann nur eine aktive gespeicherte Verbindung halten. Für parallele Verbindungen deaktivieren oder ein anderes Browserprofil verwenden. |
|
||||
| Begleitton | Nur auf dem Desktop verfügbar und WebRTC erforderlich. Bei Fenster- oder Tab-Freigabe auch Audio freigeben. |
|
||||
| Daten | Docker verwendet `webspeak-data`; Release-Pakete und Quellcode verwenden `data/`. Vor Updates sichern. |
|
||||
| Sitzungslimit | Eine Instanz akzeptiert bis zu 100 aktive Browser-Sitzungen. |
|
||||
@@ -0,0 +1,245 @@
|
||||
# WebSpeak · English
|
||||
|
||||
[Project home](../README.md) · [简体中文](./README.zh-CN.md) · [Deutsch](./README.de.md) · [Русский](./README.ru.md) · [日本語](./README.ja.md)
|
||||
|
||||
WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. Visitors can join channels without installing a desktop client, while administrators manage the target servers, access policy, and runtime state from the web console.
|
||||
|
||||
## Live demo
|
||||
|
||||
URL: <https://webspeak.example.invalid>
|
||||
|
||||
The public demo is hosted in Hong Kong and its network conditions and load may be unstable. Latency, disconnections, or temporary downtime do not represent every self-hosted deployment.
|
||||
|
||||
## ✨ Features
|
||||
|
||||
| Capability | Description |
|
||||
| --- | --- |
|
||||
| TeamSpeak compatibility | Supports TeamSpeak 3 and TeamSpeak 6 and automatically detects the target protocol. |
|
||||
| Cross-platform P2P screen sharing | Browser users and native TeamSpeak 6 clients can start and watch each other's screen shares; WebRTC/ICE carries media directly while WebSpeak relays negotiation signaling only. |
|
||||
| IPv6 targets | IPv6 TeamSpeak targets and IPv6 addresses resolved from hostnames are supported by default. |
|
||||
| Channels and members | Browse the channel tree, see live member states, and switch channels. |
|
||||
| Realtime voice | Opus audio with a compatibility transport and optional bundled WebRTC low-latency transport. |
|
||||
| Audio controls | Select microphones and speakers, adjust volume, test the microphone, mute, use VOX, and control member volume. |
|
||||
| Browser-side noise suppression | Optional microphone noise suppression runs at the browser capture stage, without adding server-side audio processing. |
|
||||
| Messaging and actions | Channel chat, server chat, private messages, poke actions, and whisper targets. |
|
||||
| Desktop accompaniment | Select an audio-enabled window or browser tab and share its sound with the current channel. |
|
||||
| Identity and access | Remembered identity, visitor-defined targets, and revocable expiring invite links. |
|
||||
| Administration | Manage targets, access policy, WebRTC, relays, invites, sessions, logs, diagnostics, and backups. |
|
||||
| Skins | Protected Day, Night, and ILLUSIA skins, plus instance-managed `.wskin` appearances with administrator enable/default controls. |
|
||||
| User experience | Chinese, English, German, Russian, and Japanese UI with responsive desktop/mobile layouts. |
|
||||
| Self-hosting | Data stays with the operator; Docker, Windows x64, and Linux x64 deployment options are provided. |
|
||||
|
||||
## 🖼️ Screenshots
|
||||
|
||||
The screenshots show the English welcome page, voice workspace, audio controls, and member menu.
|
||||
|
||||
### Welcome page
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-en-home.png" alt="WebSpeak English welcome page" width="100%" /></p>
|
||||
|
||||
### Voice workspace
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-en.png" alt="WebSpeak English voice workspace" width="100%" /></p>
|
||||
|
||||
### Audio controls
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-en-audio.png" alt="WebSpeak English audio controls" width="100%" /></p>
|
||||
|
||||
### Member menu
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-en-menu.png" alt="WebSpeak English member menu" width="100%" /></p>
|
||||
|
||||
## 🧩 Advanced features
|
||||
|
||||
These features are optional. WebSpeak continues to work with the compatibility voice transport when they are disabled. Configure them under **Administration → Servers**; saved changes apply to new connections.
|
||||
|
||||
### 1. WebRTC low-latency voice
|
||||
|
||||
WebRTC moves browser voice to a realtime media path and also enables desktop accompaniment. The current WebSpeak gateway provides it directly; no separate media server is required.
|
||||
|
||||
1. Sign in at `/admin` and open **Advanced settings** on the **Servers** page.
|
||||
2. While WebRTC is disabled, choose the UDP start and end ports. The default range is `40000–40099`.
|
||||
3. Allow the complete UDP range in the WebSpeak host's security group and firewall.
|
||||
4. Enable **WebRTC** and save. New visitors will negotiate WebRTC; unsupported browsers and networks fall back to the compatibility transport.
|
||||
|
||||
The port range is locked while WebRTC is enabled. Disable and save WebRTC before changing it, then update the firewall rules. Public deployments also need HTTPS.
|
||||
|
||||
### Screen-share ICE candidates
|
||||
|
||||
Screen-share media still prefers a direct browser-to-browser path; WebSpeak only relays negotiation signaling. By default it uses TeamSpeak's public STUN services to discover server-reflexive candidates; STUN does not carry media. If the deployment has an authorized external TURN service, set `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` before starting WebSpeak with a JSON array, for example:
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
With TURN configured, media may use that external TURN service but never the WebSpeak gateway; without it, only direct ICE paths and STUN are used.
|
||||
|
||||
### Cross-platform P2P screen sharing
|
||||
|
||||
Browser users and native TeamSpeak 6 clients can discover, start, and watch each other's screen shares. Screen media between browsers, and between a browser and a native client, is sent over a WebRTC/ICE peer-to-peer path whenever possible; WebSpeak handles session authorization, share state, and SDP/ICE signaling, but does not carry the screen media. The UI includes live status, viewer count, player volume, fullscreen, and exit controls. Share settings support up to 1080p and 60 FPS, with live WebRTC statistics for diagnosis.
|
||||
|
||||
### 2. Relay mode
|
||||
|
||||
Use a relay when a TeamSpeak server rejects connections from another region or when the direct path is unstable. It is not a VPN: it forwards only the TeamSpeak traffic of the current WebSpeak session, while the visitor still chooses the target server in the web page.
|
||||
|
||||
A relay instance is a dedicated forwarding service with no visitor page or administration console. It accepts only gateway sessions with a matching token. Use a random token of at least 16 characters.
|
||||
|
||||
#### Run from source
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm run build
|
||||
WEBSPEAK_MODE=relay \
|
||||
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
WEBSPEAK_RELAY_HOST='0.0.0.0' \
|
||||
WEBSPEAK_RELAY_PORT='39087' \
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
$env:WEBSPEAK_MODE = "relay"
|
||||
$env:WEBSPEAK_RELAY_TOKEN = "replace-with-a-long-random-token"
|
||||
$env:WEBSPEAK_RELAY_HOST = "0.0.0.0"
|
||||
$env:WEBSPEAK_RELAY_PORT = "39087"
|
||||
node .\dist\index.js
|
||||
```
|
||||
|
||||
#### Run from a release package
|
||||
|
||||
Download and extract the appropriate package from [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest):
|
||||
|
||||
```bash
|
||||
# Linux
|
||||
export WEBSPEAK_MODE=relay
|
||||
export WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token'
|
||||
export WEBSPEAK_RELAY_HOST='0.0.0.0'
|
||||
export WEBSPEAK_RELAY_PORT='39087'
|
||||
./runtime/node ./dist/index.js
|
||||
```
|
||||
|
||||
On Windows PowerShell, set the same variables and run `.\runtime\node.exe .\dist\index.js`.
|
||||
|
||||
#### Run with Docker
|
||||
|
||||
```bash
|
||||
docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
-e WEBSPEAK_MODE=relay \
|
||||
-e WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
-e WEBSPEAK_RELAY_PORT='39087' \
|
||||
ghcr.io/echosixhiya/webspeak:latest
|
||||
```
|
||||
|
||||
Allow the relay host's UDP listen port, `39087` by default.
|
||||
|
||||
#### Enable it in the gateway
|
||||
|
||||
1. Open **Administration → Servers → Relay server** and add one or more nodes.
|
||||
2. Set a custom display name, endpoint such as `relay.example.com#39087`, and matching token for each node, then save.
|
||||
3. Visitors can choose direct access or one of the configured relays on the welcome page.
|
||||
|
||||
Disable and save the relay configuration to remove the relay option from the welcome page.
|
||||
|
||||
### 3. Dependencies and attribution
|
||||
|
||||
- The relay service is built into WebSpeak with Node.js standard libraries; it does not use GOST, sing-box, or another proxy framework.
|
||||
- WebRTC uses [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`, whose upstream project is licensed under MIT.
|
||||
- TeamSpeak protocol connectivity uses the project-maintained [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js) SDK fork.
|
||||
|
||||
## 🧾 Changelog
|
||||
|
||||
| Version | Date | Summary |
|
||||
| --- | --- | --- |
|
||||
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | Added `.wskin` skins, administrator enable/default controls, and protected Day/Night/ILLUSIA built-ins; removed the unfinished Aurora Voice sample, fixed skin-load flashes, dark-control contrast, and voice-room artwork layering, and added the official skin-development Agent Skill; reduced and anchored the ILLUSIA voice artwork to avoid covering members or shared video. |
|
||||
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | 2026-09-22 | Added cross-platform P2P screen sharing between browsers and native TeamSpeak 6 clients; added STUN/external-TURN configuration, live player and viewer state, 1080p/60 FPS capture settings, and WebRTC statistics; refined screen-share interactions and added visitor numbering. |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | Added channel member scheduling and permission-aware direct moves; added avatar, mute-state, and remembered-identity support; refreshed feature screenshots and documentation for all five languages. |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | 2026-09-17 | Added browser-side microphone noise suppression, Russian and Japanese UI, and per-language welcome text; refined volume interaction and error messages/codes on top of PR #2. |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | 2026-09-13 | Improved welcome-page connection errors, preserved and safely truncated error codes, and added default IPv6 target support. |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | 2026-09-10 | Added server-password prompts, formal relay mode, multiple relay selection, and administrator connection-reason reporting. |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | 2026-09-08 | Simplified Docker deployment, supported local TeamSpeak targets, added a 15-second connection timeout, and made network monitoring continuous. |
|
||||
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | Added German, Telegram, network performance, and master-volume features; fixed accompaniment volume fluctuation. |
|
||||
| [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) | 2026-09-04 | Added desktop accompaniment, remembered-identity guidance, and the site icon; fixed WebRTC member volume. |
|
||||
| [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) | 2026-09-04 | Fixed identity persistence and refined the theme toggle. |
|
||||
| [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) | 2026-09-03 | Fixed WebRTC and channel chat and refined administration, logs, and mobile layouts. |
|
||||
| [v0.1.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.3) | 2026-09-03 | Added bundled WebRTC, migrated the TeamSpeak SDK, and improved member synchronization and voice buffering. |
|
||||
|
||||
See the complete history in [CHANGELOG.md](../CHANGELOG.md).
|
||||
|
||||
## 🚀 Deployment
|
||||
|
||||
| Method | Best for | Environment |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose (recommended) | Long-running servers, simple upgrades, and persistent data | Docker Engine + Docker Compose |
|
||||
| Release package | Running without Node.js or build dependencies | Windows x64 or Linux x64 |
|
||||
| From source | Development, debugging, and customization | Node.js 22.5+, Git, and native build tools |
|
||||
|
||||
### Docker Compose (recommended)
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Open `http://<your-host>:3040` after startup. If using a reverse proxy, point it to that address. When WebRTC is enabled, allow the UDP range shown in the administration console. Data is stored in the `webspeak-data` volume.
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
Upgrade:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Do not run `docker compose down -v`; it removes the database and administrator settings.
|
||||
|
||||
### Release package
|
||||
|
||||
Download the matching `windows-x64.zip` or `linux-x64.tar.gz` from [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest), extract it into a dedicated directory, and run `start-webspeak.cmd` on Windows or `./start-webspeak.sh` on Linux. Packages include the Node.js runtime and production dependencies.
|
||||
|
||||
### From source
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
Building `@discordjs/opus` requires Python, Make, and a C/C++ toolchain.
|
||||
|
||||
### First-time setup
|
||||
|
||||
1. Open `http://<your-host>:3040/admin`.
|
||||
2. Sign in with `admin` / `admin` and immediately set a new password of at least 12 characters.
|
||||
3. Configure the TeamSpeak target and access mode under **Servers**, for example `voice.example.com#9987`.
|
||||
4. Configure HTTPS for public access; when WebRTC is enabled, allow the UDP range shown in the console.
|
||||
|
||||
## ⚠️ Requirements and notes
|
||||
|
||||
| Area | Requirement or note |
|
||||
| --- | --- |
|
||||
| Browser | Use a current Chrome, Edge, or other modern browser with WebRTC support. Microphone and window audio normally require HTTPS. |
|
||||
| TeamSpeak network | The WebSpeak host must reach the target TeamSpeak server; the default voice port is `9987`. |
|
||||
| Web network | The service uses `3040/TCP`; public deployments should expose the page and WebSocket through an HTTPS reverse proxy. |
|
||||
| IPv6 | Write literal targets as `[2001:db8::1]#9987`. The host/container needs routed IPv6, IPv6 enabled in the OS and Node.js, and the relevant firewall rules. |
|
||||
| WebRTC | The default range is `40000–40099/UDP`; allow it and disable WebRTC before changing the range. |
|
||||
| Remembered identity | One browser identity can hold one active remembered connection. Disable it for parallel connections or use another browser profile. |
|
||||
| Accompaniment | Desktop only and requires WebRTC. Enable audio sharing when selecting a window or tab. |
|
||||
| Data | Docker data is in `webspeak-data`; release packages and source installs use `data/`. Back up before upgrades. |
|
||||
| Session limit | One instance accepts up to 100 active browser sessions. |
|
||||
@@ -0,0 +1,150 @@
|
||||
# WebSpeak · 日本語
|
||||
|
||||
[プロジェクトトップ](../README.md) · [简体中文](./README.zh-CN.md) · [English](./README.en.md) · [Deutsch](./README.de.md) · [Русский](./README.ru.md)
|
||||
|
||||
## プロジェクト概要
|
||||
|
||||
| 観点 | 説明 |
|
||||
| --- | --- |
|
||||
| **WHAT** | WebSpeak は TeamSpeak 3 / TeamSpeak 6 向けのセルフホスト型ブラウザクライアント兼音声ゲートウェイです。 |
|
||||
| **WHY** | デスクトップクライアントをインストールせず、ブラウザからチャンネルに参加できます。運用者はサーバーとデータを管理できます。 |
|
||||
| **HOW** | 起動後、管理コンソールで TeamSpeak の接続先とアクセス方針を設定します。ブラウザが画面と音声を担当し、WebSpeak がゲートウェイとして接続します。 |
|
||||
|
||||
## オンラインデモ
|
||||
|
||||
アドレス: <https://webspeak.example.invalid>
|
||||
|
||||
デモは香港にあります。ネットワークと負荷が不安定な場合があるため、遅延、切断、一時的な利用不可は各自の環境での動作を示すものではありません。
|
||||
|
||||
## ✨ 機能
|
||||
|
||||
| 機能 | 説明 |
|
||||
| --- | --- |
|
||||
| TeamSpeak | TeamSpeak 3 / 6 に対応し、対象プロトコルを自動検出します。 |
|
||||
| クロスプラットフォーム P2P 画面共有 | ブラウザユーザーと TeamSpeak 6 ネイティブクライアントが互いに画面共有を開始・視聴できます。メディアは WebRTC/ICE で直接送信し、WebSpeak はシグナリングだけを中継します。 |
|
||||
| IPv6 | IPv6 の接続先と DNS から解決された IPv6 アドレスに標準対応します。 |
|
||||
| チャンネルとメンバー | チャンネルツリー、リアルタイムのメンバー状態、チャンネル移動。 |
|
||||
| リアルタイム音声 | Opus、互換トランスポート、内蔵 WebRTC による低遅延音声。 |
|
||||
| 音声操作 | マイク、スピーカー、音量、VOX、ミュート、メンバーごとの音量調整。 |
|
||||
| ブラウザ側ノイズ抑制 | マイクのノイズ抑制をブラウザの音声取得段階で任意に使用でき、サーバー側の追加処理は不要です。 |
|
||||
| チャットと操作 | チャンネル/サーバーチャット、個人メッセージ、つつく、ウィスパー対象。 |
|
||||
| BGM共有 | デスクトップブラウザで音声付きウィンドウやタブの音をチャンネルに共有。 |
|
||||
| ID とアクセス | ID の保存、接続先の指定、期限・回数付き招待リンク。 |
|
||||
| 管理コンソール | 接続先、アクセス、WebRTC、中継、招待、セッション、ログ、診断、バックアップ。 |
|
||||
| スキン | 保護された昼・夜・ILLUSIA スキンに加え、管理者が有効化とデフォルトを管理するインスタンス `.wskin` に対応。 |
|
||||
| インターフェース | 中文、English、Deutsch、Русский、日本語、レスポンシブ表示。 |
|
||||
|
||||
## 🖼️ インターフェースのスクリーンショット
|
||||
|
||||
日本語のホーム、音声ワークスペース、オーディオ設定、メンバー操作メニューを掲載しています。
|
||||
|
||||
### ホーム
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja-home.png" alt="WebSpeak 日本語ホーム" width="100%" /></p>
|
||||
|
||||
### 音声ワークスペース
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja.png" alt="WebSpeak 日本語音声ワークスペース" width="100%" /></p>
|
||||
|
||||
### オーディオ設定
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja-audio.png" alt="WebSpeak 日本語オーディオ設定" width="100%" /></p>
|
||||
|
||||
### メンバーメニュー
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja-menu.png" alt="WebSpeak 日本語メンバーメニュー" width="100%" /></p>
|
||||
|
||||
## 🧩 高度な機能
|
||||
|
||||
### WebRTC
|
||||
|
||||
**管理コンソール → サーバー → 詳細設定** で有効にします。無効の状態で UDP ポート範囲(初期値 `40000–40099`)を設定し、ファイアウォールで許可して保存してください。有効中は範囲がロックされ、新しい接続で WebRTC を使用します。非対応のブラウザは互換トランスポートに戻ります。公開サイトでは HTTPS が必要です。
|
||||
|
||||
### 画面共有の ICE 候補
|
||||
|
||||
画面共有のメディアは引き続きブラウザ間の直接接続を優先し、WebSpeak はシグナリングだけを中継します。初期状態では TeamSpeak の公開 STUN サービスで外部候補を検出します。STUN はメディアを運びません。認可済みの外部 TURN を使う場合は、起動前に `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` を JSON 配列で設定できます。
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
TURN を設定した場合、メディアは外部 TURN サービスを経由することがありますが、WebSpeak ゲートウェイは経由しません。未設定時は直接接続と STUN のみを使用します。
|
||||
|
||||
### クロスプラットフォーム P2P 画面共有
|
||||
|
||||
ブラウザユーザーと TeamSpeak 6 ネイティブクライアントは、互いの画面共有を検出・開始・視聴できます。ブラウザ間、およびブラウザとネイティブクライアント間の画面メディアは、可能な限り WebRTC/ICE の直接接続で送信されます。WebSpeak はセッション認証、共有状態、SDP/ICE シグナリングを担当しますが、画面メディア自体は転送しません。画面には配信中の状態と視聴者数が表示され、音量、全画面、終了を操作できます。取得設定は最大 1080p / 60 FPS に対応し、WebRTC 統計も確認できます。
|
||||
|
||||
### 中継サーバー
|
||||
|
||||
中継は現在の WebSpeak セッションの TeamSpeak 通信だけを転送し、VPN ではありません。管理コンソールで複数のノードに名前、アドレス、トークンを設定すると、ユーザーは直接接続または中継を選択できます。中継モードは専用の転送サービスとして動作し、ゲスト画面や管理コンソールを提供しません。
|
||||
|
||||
中継サービスは WebSpeak に組み込まれており、Node.js の標準ライブラリを使用します。GOST や sing-box などのプロキシフレームワークは不要です。WebRTC は [werift](https://github.com/shinyoshiaki/werift-webrtc)、TeamSpeak 接続はプロジェクトが保守する [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js) SDK を使用します。
|
||||
|
||||
## 🚀 デプロイ
|
||||
|
||||
| 方法 | 用途 |
|
||||
| --- | --- |
|
||||
| Docker Compose | 常時稼働サーバーと簡単な更新 |
|
||||
| Release パッケージ | Node.js やビルドツールを使わない起動 |
|
||||
| ソースから | 開発やカスタマイズ |
|
||||
|
||||
### Docker Compose
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
起動後に `http://<your-host>:3040/admin` を開き、`admin` / `admin` でログインして直ちにパスワードを変更し、TeamSpeak を設定します。データは `webspeak-data` volume に保存されます。データベースを消さない場合は `docker compose down -v` を実行しないでください。
|
||||
|
||||
### Release パッケージ
|
||||
|
||||
[Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) から Windows x64 または Linux x64 のパッケージを取得し、専用フォルダーに展開して `start-webspeak.cmd` または `./start-webspeak.sh` を実行します。
|
||||
|
||||
### ソースから
|
||||
|
||||
```bash
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
## ⚠️ 要件と注意
|
||||
|
||||
- ソースからのビルドには Node.js `>=22.5` が必要です。Docker と Release には必要な実行環境が含まれます。
|
||||
- WebRTC に対応した最新の Chrome、Edge などを使用してください。マイクとウィンドウ音声には通常 HTTPS が必要です。
|
||||
- WebSpeak のホストから TeamSpeak に到達できる必要があります。標準音声ポートは `9987` です。
|
||||
- Web サービスは `3040/TCP` を使用します。公開時は HTTPS と WebSocket をリバースプロキシ経由で公開してください。
|
||||
- IPv6 にはルーティング可能な IPv6、OS/コンテナで有効な IPv6、適切なファイアウォール設定が必要です。リテラルは `[2001:db8::1]#9987` の形式です。
|
||||
- 保存したブラウザ ID は同じブラウザで同時に1接続だけ使用できます。
|
||||
- BGM共有はデスクトップのみで、WebRTC が必要です。
|
||||
|
||||
## コミュニティと関連プロジェクト
|
||||
|
||||
- [QQ グループ](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
|
||||
- [Telegram グループ](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
- [NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot) — Web コンソール付き TeamSpeak 音楽ボット。
|
||||
|
||||
## 🧾 更新履歴
|
||||
|
||||
| バージョン | 内容 |
|
||||
| --- | --- |
|
||||
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | `.wskin` スキン、管理者向けの有効化/デフォルト設定、保護された昼・夜・ILLUSIA 内蔵スキンを追加。未完成の Aurora Voice サンプルを削除し、読み込み時のちらつき、ダークモードの視認性、音声画面のアートレイヤーを修正。公式スキン開発 Agent Skill も追加し、音声アクティビティの立ち絵を縮小して右下に固定し、メンバーや共有動画を隠さないようにしました。 |
|
||||
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | ブラウザと TeamSpeak 6 ネイティブクライアント間のクロスプラットフォーム P2P 画面共有を追加しました。STUN/外部 TURN 設定、プレーヤーと視聴者状態、1080p/60 FPS 取得設定、WebRTC 統計に対応し、共有操作と訪問者番号も改善しました。 |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | チャンネルメンバーの移動操作と権限に応じた直接移動を追加し、アバター表示、ミュート状態の同期、保存 ID の復元に対応しました。5 言語のスクリーンショットとドキュメントも更新しました。 |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | ブラウザ側マイクノイズ抑制、ロシア語・日本語 UI、言語別ウェルカム文を追加。音量操作と PR #2 を基にしたエラー表示・エラーコードを改善しました。 |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | 接続エラー表示を改善し、IPv6 接続先を標準対応しました。 |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | パスワード案内、正式な中継モード、複数中継選択、接続診断を追加しました。 |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | Docker 起動を簡略化し、15秒の接続タイムアウトと継続的なネットワーク監視を追加しました。 |
|
||||
|
||||
完全な履歴は [CHANGELOG.md](../CHANGELOG.md) を参照してください。
|
||||
|
||||
## ライセンス
|
||||
|
||||
WebSpeak は [GNU Affero General Public License v3.0 only](../LICENSE) の下で公開されています。
|
||||
@@ -0,0 +1,150 @@
|
||||
# WebSpeak · Русский
|
||||
|
||||
[Главная проекта](../README.md) · [简体中文](./README.zh-CN.md) · [English](./README.en.md) · [Deutsch](./README.de.md) · [日本語](./README.ja.md)
|
||||
|
||||
## О проекте
|
||||
|
||||
| Логика | Описание |
|
||||
| --- | --- |
|
||||
| **WHAT** | WebSpeak — самостоятельно размещаемый веб-клиент и голосовой шлюз для TeamSpeak 3 и TeamSpeak 6. |
|
||||
| **WHY** | Пользователям не нужно устанавливать настольный клиент: достаточно открыть браузер, а оператор сохраняет контроль над сервером и данными. |
|
||||
| **HOW** | После запуска настройте цель TeamSpeak и политику доступа в панели администратора. Браузер отвечает за интерфейс и аудио, WebSpeak — за шлюз. |
|
||||
|
||||
## Онлайн-демо
|
||||
|
||||
Адрес: <https://webspeak.example.invalid>
|
||||
|
||||
Демо-сервер находится в Гонконге; сеть и нагрузка могут быть нестабильными. Задержки, разрывы или временная недоступность демо не характеризуют самостоятельное развертывание.
|
||||
|
||||
## ✨ Возможности
|
||||
|
||||
| Возможность | Описание |
|
||||
| --- | --- |
|
||||
| TeamSpeak | Поддержка TeamSpeak 3 и TeamSpeak 6 с автоматическим определением протокола. |
|
||||
| Кроссплатформенная P2P-трансляция экрана | Пользователи браузера и нативные клиенты TeamSpeak 6 могут запускать и смотреть трансляции друг друга; медиаданные идут напрямую по WebRTC/ICE, а WebSpeak передаёт только сигнальные сообщения. |
|
||||
| IPv6 | IPv6-цели и IPv6-адреса, полученные через DNS, поддерживаются по умолчанию. |
|
||||
| Каналы и участники | Дерево каналов, состояние участников в реальном времени и переход между каналами. |
|
||||
| Голос в реальном времени | Opus, совместимый транспорт и встроенный WebRTC с низкой задержкой. |
|
||||
| Управление аудио | Микрофон, динамики, громкость, VOX, отключение микрофона и отдельная громкость участников. |
|
||||
| Шумоподавление в браузере | Опциональное шумоподавление микрофона на этапе захвата в браузере без дополнительной обработки звука на сервере. |
|
||||
| Чат и действия | Чат канала и сервера, личные сообщения, толчки и цели шёпота. |
|
||||
| Фоновая музыка | На компьютере можно поделиться звуком окна или вкладки с текущим каналом. |
|
||||
| Идентичность и доступ | Сохранение идентичности, собственные цели и приглашения с ограничением срока и числа использований. |
|
||||
| Панель администратора | Цели, доступ, WebRTC, ретрансляторы, приглашения, сессии, логи, диагностика и резервные копии. |
|
||||
| Скины | Защищённые дневная, ночная и ILLUSIA-темы, а также `.wskin` экземпляра с управлением включением и темой по умолчанию в панели администратора. |
|
||||
| Интерфейс | 中文, English, Deutsch, Русский и 日本語, адаптивная верстка. |
|
||||
|
||||
## 🖼️ Скриншоты интерфейса
|
||||
|
||||
Скриншоты показывают русскую главную страницу, голосовое пространство, настройки аудио и меню участника.
|
||||
|
||||
### Главная страница
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru-home.png" alt="Главная страница WebSpeak на русском" width="100%" /></p>
|
||||
|
||||
### Голосовое пространство
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru.png" alt="Русское голосовое пространство WebSpeak" width="100%" /></p>
|
||||
|
||||
### Настройки аудио
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru-audio.png" alt="Настройки аудио WebSpeak на русском" width="100%" /></p>
|
||||
|
||||
### Меню участника
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru-menu.png" alt="Меню участника WebSpeak на русском" width="100%" /></p>
|
||||
|
||||
## 🧩 Расширенные функции
|
||||
|
||||
### WebRTC
|
||||
|
||||
Включается в **Панель администратора → Сервер → Расширенные настройки**. До включения задайте диапазон UDP-портов (по умолчанию `40000–40099`), откройте его в firewall и сохраните. При включённом WebRTC диапазон заблокирован; новые подключения используют WebRTC, а неподдерживаемые браузеры переходят на совместимый транспорт. Для публичного доступа нужен HTTPS.
|
||||
|
||||
### ICE для демонстрации экрана
|
||||
|
||||
Медиа демонстрации экрана по-прежнему предпочитает прямое соединение между браузерами; WebSpeak только передаёт сигнальные сообщения. По умолчанию используются публичные STUN-серверы TeamSpeak для поиска внешних кандидатов, STUN не передаёт медиаданные. Авторизованный внешний TURN можно задать через `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` в виде JSON-массива, например:
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
При настроенном TURN медиа может идти через этот внешний сервис, но не через шлюз WebSpeak. Без TURN используются только прямые ICE-пути и STUN.
|
||||
|
||||
### Кроссплатформенная P2P-трансляция экрана
|
||||
|
||||
Пользователи браузера и нативные клиенты TeamSpeak 6 могут обнаруживать, запускать и смотреть трансляции друг друга. Между браузерами, а также между браузером и нативным клиентом, экран передаётся по прямому соединению WebRTC/ICE, когда это возможно; WebSpeak отвечает за авторизацию сессии, состояние трансляции и передачу SDP/ICE-сигналов, но не переносит медиаданные экрана. Интерфейс показывает статус трансляции и число зрителей и предоставляет регулировку громкости, полноэкранный режим и выход. Для захвата доступны настройки до 1080p и 60 FPS, а также статистика WebRTC.
|
||||
|
||||
### Ретрансляторы
|
||||
|
||||
Ретранслятор передаёт только TeamSpeak-трафик текущей сессии и не является VPN. В панели администратора добавьте один или несколько узлов, задайте имя, адрес и токен. Пользователь сможет выбрать прямое подключение или настроенный ретранслятор. Режим ретранслятора запускается отдельно и не предоставляет страницу посетителя или панель администратора.
|
||||
|
||||
Сервис ретрансляции встроен в WebSpeak и использует стандартные библиотеки Node.js; GOST, sing-box и другие прокси-фреймворки не требуются. WebRTC использует [werift](https://github.com/shinyoshiaki/werift-webrtc), а TeamSpeak — поддерживаемый проектом [SDK EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js).
|
||||
|
||||
## 🚀 Развертывание
|
||||
|
||||
| Способ | Подходит для |
|
||||
| --- | --- |
|
||||
| Docker Compose | Постоянного сервера и простых обновлений |
|
||||
| Пакет Release | Запуска без Node.js и инструментов сборки |
|
||||
| Из исходников | Разработки и настройки проекта |
|
||||
|
||||
### Docker Compose
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
После запуска откройте `http://<ваш-хост>:3040/admin`, войдите с `admin` / `admin`, сразу смените пароль и настройте TeamSpeak. Данные хранятся в volume `webspeak-data`. Не используйте `docker compose down -v`, если не хотите удалить базу и настройки.
|
||||
|
||||
### Пакет Release
|
||||
|
||||
Скачайте подходящий пакет Windows x64 или Linux x64 из [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest), распакуйте в отдельную папку и запустите `start-webspeak.cmd` или `./start-webspeak.sh`.
|
||||
|
||||
### Из исходников
|
||||
|
||||
```bash
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
## ⚠️ Требования и замечания
|
||||
|
||||
- Node.js `>=22.5` нужен для сборки из исходников; Docker и Release уже содержат необходимые компоненты.
|
||||
- Нужен современный Chrome, Edge или другой браузер с WebRTC. Микрофон и звук окна обычно требуют HTTPS.
|
||||
- WebSpeak должен иметь доступ к TeamSpeak; стандартный голосовой порт — `9987`.
|
||||
- Веб-сервис использует `3040/TCP`; для публичного сайта направьте HTTPS и WebSocket через обратный прокси.
|
||||
- Для IPv6 нужен маршрутизируемый IPv6, включённый IPv6 в ОС/контейнере и правила firewall. Литерал задаётся как `[2001:db8::1]#9987`.
|
||||
- Одна сохранённая браузерная идентичность может использоваться только одним активным подключением.
|
||||
- Фоновая музыка доступна только на компьютере и требует WebRTC.
|
||||
|
||||
## Сообщество и проекты
|
||||
|
||||
- [QQ-группа](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
|
||||
- [Telegram-группа](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
- [NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot) — музыкальный бот для TeamSpeak с веб-консолью.
|
||||
|
||||
## 🧾 История изменений
|
||||
|
||||
| Версия | Изменения |
|
||||
| --- | --- |
|
||||
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | Добавлены скины `.wskin`, управление включением и темой по умолчанию, а также защищённые темы «День», «Ночь» и ILLUSIA; удалён незавершённый пример Aurora Voice, исправлены мерцание при загрузке скина, контраст элементов в тёмном режиме и слои иллюстраций в голосовом пространстве; добавлен официальный Agent Skill; иллюстрация ILLUSIA уменьшена и закреплена справа внизу, чтобы не перекрывать участников и видео. |
|
||||
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | Добавлена кроссплатформенная P2P-трансляция экрана между браузерами и нативными клиентами TeamSpeak 6; добавлены настройка STUN/внешнего TURN, проигрыватель и состояние зрителей, захват до 1080p/60 FPS и статистика WebRTC; улучшено управление трансляцией и добавлен номер посетителя. |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | Добавлены управление перемещением участников и прямое перемещение с учётом прав; поддержаны аватары, синхронизация микрофона и восстановление идентичности; обновлены скриншоты и документация для пяти языков. |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | Добавлены браузерное шумоподавление микрофона, русский и японский интерфейсы и отдельные тексты приветствия; улучшены управление громкостью и сообщения/коды ошибок на основе PR #2. |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | Улучшены ошибки на странице входа и добавлена поддержка IPv6-целей по умолчанию. |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | Добавлены подсказки пароля, режим ретранслятора, выбор нескольких узлов и диагностика подключений. |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | Упрощён Docker-запуск, добавлен тайм-аут подключения 15 секунд и непрерывный сетевой мониторинг. |
|
||||
|
||||
Полная история находится в [CHANGELOG.md](../CHANGELOG.md).
|
||||
|
||||
## Лицензия
|
||||
|
||||
WebSpeak распространяется по [GNU Affero General Public License v3.0 only](../LICENSE).
|
||||
@@ -0,0 +1,245 @@
|
||||
# WebSpeak · 简体中文
|
||||
|
||||
[返回项目首页](../README.md) · [English](./README.en.md) · [Deutsch](./README.de.md) · [Русский](./README.ru.md) · [日本語](./README.ja.md)
|
||||
|
||||
WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。用户无需安装桌面客户端即可从浏览器加入频道,管理员可以在控制台管理目标服务器、访问方式和运行状态。
|
||||
|
||||
## 在线 Demo
|
||||
|
||||
地址:<https://webspeak.example.invalid>
|
||||
|
||||
公共 Demo 位于香港,网络和负载可能不稳定。延迟、断线或暂时不可用不代表自行部署后的实际表现。
|
||||
|
||||
## ✨ 特性
|
||||
|
||||
| 能力 | 说明 |
|
||||
| --- | --- |
|
||||
| TeamSpeak 兼容 | 支持 TeamSpeak 3 与 TeamSpeak 6,并自动探测目标服务器协议。 |
|
||||
| 跨端 P2P 屏幕共享 | 支持浏览器用户与 TeamSpeak 6 原生客户端互相发起和观看屏幕共享;媒体优先通过 WebRTC/ICE 直连,WebSpeak 仅转发协商信令。 |
|
||||
| IPv6 目标 | 默认支持 IPv6 TeamSpeak 目标和域名解析出的 IPv6 地址。 |
|
||||
| 频道与成员 | 浏览频道树、查看实时成员状态并切换频道。 |
|
||||
| 实时语音 | 使用 Opus,支持兼容传输和可选的内置 WebRTC 低延迟传输。 |
|
||||
| 音频控制 | 选择麦克风与扬声器、调节音量、测试麦克风、闭麦、VOX 和成员独立音量。 |
|
||||
| 浏览器端降噪 | 提供可开关的麦克风降噪,在浏览器采集端处理,不增加服务器端音频处理压力。 |
|
||||
| 消息与互动 | 支持频道消息、服务器消息、私聊、戳一戳和耳语目标。 |
|
||||
| 桌面端伴奏 | 在桌面浏览器选择带音频的窗口或标签页,将声音分享给当前频道。 |
|
||||
| 身份与访问 | 支持身份保持、访客自定义目标和可撤销、可过期的邀请链接。 |
|
||||
| 管理控制台 | 管理目标、访问策略、WebRTC、中继、邀请、会话、日志、诊断和备份。 |
|
||||
| 皮肤 | 提供日间、夜间和 ILLUSIA 三款受保护皮肤,并支持实例自定义 `.wskin` 外观与管理员默认/启用管理。 |
|
||||
| 界面体验 | 提供中文、English、Deutsch、Русский、日本語及响应式桌面/移动布局。 |
|
||||
| 自托管 | 数据由部署者保存,提供 Docker、Windows x64 和 Linux x64 方案。 |
|
||||
|
||||
## 🖼️ 界面截图
|
||||
|
||||
以下截图展示中文界面的欢迎页、语音工作区、音量控制和成员操作菜单。
|
||||
|
||||
### 欢迎页
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-zh-home.png" alt="WebSpeak 中文欢迎页" width="100%" /></p>
|
||||
|
||||
### 语音工作区
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-zh.png" alt="WebSpeak 中文语音工作区" width="100%" /></p>
|
||||
|
||||
### 音量控制
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-zh-audio.png" alt="WebSpeak 中文音量控制" width="100%" /></p>
|
||||
|
||||
### 成员菜单
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-zh-menu.png" alt="WebSpeak 中文成员菜单" width="100%" /></p>
|
||||
|
||||
## 🧩 高级功能
|
||||
|
||||
高级功能均为可选项;关闭时仍可使用兼容语音传输。配置入口在管理员控制台的“服务器”页,保存后对新连接生效。
|
||||
|
||||
### 1. WebRTC 低延迟语音
|
||||
|
||||
WebRTC 将浏览器语音切换到实时媒体通道,也支持桌面端伴奏。媒体服务由当前 WebSpeak 网关直接提供,不需要另设媒体服务器。
|
||||
|
||||
1. 登录 `/admin`,打开“服务器”页的“高级参数”。
|
||||
2. 关闭 WebRTC 时设置 UDP 起止端口,默认范围为 `40000–40099`。
|
||||
3. 在 WebSpeak 主机的安全组和防火墙中放行整个 UDP 范围。
|
||||
4. 勾选“启用 WebRTC”并保存,用户重新进入后即可协商;不支持时会回退到兼容传输。
|
||||
|
||||
WebRTC 启用后端口范围会锁定。要修改端口,先关闭 WebRTC 并保存,再修改端口并同步防火墙规则。公网使用还需要 HTTPS。
|
||||
|
||||
### 屏幕共享的 ICE 候选
|
||||
|
||||
屏幕共享媒体仍优先走浏览器之间的直连,WebSpeak 只转发协商信令。默认使用 TeamSpeak 官方 STUN 服务发现公网候选地址;STUN 不承载媒体。若部署者有合规的外部 TURN 服务,可在启动 WebSpeak 前设置 `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS`,值为 JSON 数组,例如:
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
配置 TURN 后,媒体可能经过该外部 TURN 服务,但不会经过 WebSpeak 网关;未配置时只使用直连和 STUN。
|
||||
|
||||
### 跨端 P2P 屏幕共享
|
||||
|
||||
浏览器用户与 TeamSpeak 6 原生客户端可以互相发现、发起和观看屏幕共享。浏览器之间以及浏览器与原生客户端之间的屏幕媒体优先通过 WebRTC/ICE 端到端传输;WebSpeak 负责会话鉴权、共享状态和 SDP/ICE 信令转发,不承载屏幕媒体流量。页面提供直播状态、观众人数、播放器音量、全屏和退出控制,也可在共享设置窗口中选择最高 1080p 与 60 FPS,并查看 WebRTC 统计。
|
||||
|
||||
### 2. 中继模式
|
||||
|
||||
中继适用于 TeamSpeak 拒绝境外连接或直连不稳定的情况。它不是 VPN,只转发当前 WebSpeak 会话的 TeamSpeak 数据;目标服务器仍由用户在网页中选择。
|
||||
|
||||
中继实例是专用转发服务,不提供前台和管理员后台,只接受带匹配令牌的 WebSpeak 网关会话。令牌至少使用 16 个字符的随机值。
|
||||
|
||||
#### 源码启动
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm run build
|
||||
WEBSPEAK_MODE=relay \
|
||||
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
WEBSPEAK_RELAY_HOST='0.0.0.0' \
|
||||
WEBSPEAK_RELAY_PORT='39087' \
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
$env:WEBSPEAK_MODE = "relay"
|
||||
$env:WEBSPEAK_RELAY_TOKEN = "replace-with-a-long-random-token"
|
||||
$env:WEBSPEAK_RELAY_HOST = "0.0.0.0"
|
||||
$env:WEBSPEAK_RELAY_PORT = "39087"
|
||||
node .\dist\index.js
|
||||
```
|
||||
|
||||
#### 发布包启动
|
||||
|
||||
从 [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 下载并解压对应平台的包:
|
||||
|
||||
```bash
|
||||
# Linux
|
||||
export WEBSPEAK_MODE=relay
|
||||
export WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token'
|
||||
export WEBSPEAK_RELAY_HOST='0.0.0.0'
|
||||
export WEBSPEAK_RELAY_PORT='39087'
|
||||
./runtime/node ./dist/index.js
|
||||
```
|
||||
|
||||
Windows PowerShell 使用同名环境变量后运行 `.\runtime\node.exe .\dist\index.js`。
|
||||
|
||||
#### Docker 启动
|
||||
|
||||
```bash
|
||||
docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
-e WEBSPEAK_MODE=relay \
|
||||
-e WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
-e WEBSPEAK_RELAY_PORT='39087' \
|
||||
ghcr.io/echosixhiya/webspeak:latest
|
||||
```
|
||||
|
||||
放行中继主机的 UDP 监听端口,默认是 `39087`。
|
||||
|
||||
#### 在网关中启用
|
||||
|
||||
1. 管理员控制台 → “服务器” → “中继服务器”,添加一个或多个节点。
|
||||
2. 为每个节点填写自定义名称、地址(例如 `relay.example.com#39087`)和匹配令牌并保存。
|
||||
3. 访客欢迎页即可选择直连或其中一个中继。
|
||||
|
||||
关闭并保存中继配置后,访客页面不会显示中继选项。
|
||||
|
||||
### 3. 依赖与归属
|
||||
|
||||
- 中继服务是 WebSpeak 自带实现,使用 Node.js 标准库,不依赖 GOST、sing-box 或其他代理框架。
|
||||
- WebRTC 使用 [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`,上游采用 MIT 许可证。
|
||||
- TeamSpeak 协议使用项目维护的 [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js) SDK fork。
|
||||
|
||||
## 🧾 更新日志
|
||||
|
||||
| 版本 | 日期 | 摘要 |
|
||||
| --- | --- | --- |
|
||||
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | 新增 `.wskin` 皮肤系统、管理员启用/默认管理和受保护的日间/夜间/ILLUSIA 内置皮肤;移除未完成 Aurora Voice 样例,修复皮肤加载闪烁、暗色控件可读性与语音界面美术层级,并加入官方皮肤开发 Agent Skill;缩小 ILLUSIA 语音立绘并固定在右下角,避免遮挡成员与共享画面。 |
|
||||
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | 2026-09-22 | 新增浏览器与 TeamSpeak 6 原生客户端之间的跨端 P2P 屏幕共享;提供 STUN/外部 TURN 配置、直播播放器、观众状态、1080p/60 FPS 采集设置和 WebRTC 统计;优化屏幕共享交互并新增访客编号。 |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | 新增频道成员调度与按权限直接移动;支持头像、静音状态同步和身份恢复;更新五种语言的功能截图与文档。 |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | 2026-09-17 | 提供浏览器端麦克风降噪、俄语和日语支持及按语言欢迎词配置;优化音量交互和 PR #2 基础上的错误提示与错误代码。 |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | 2026-09-13 | 优化首页连接错误显示,保留并安全截断错误代码;默认支持 IPv6 TeamSpeak 目标。 |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | 2026-09-10 | 增加服务器密码提示、正式中继部署模式、多中继选择和管理员日志原因显示。 |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | 2026-09-08 | 简化 Docker 部署,支持同机 TeamSpeak,增加 15 秒连接超时和持续网络监测。 |
|
||||
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | 增加德语、Telegram、网络性能面板和整体音量;修复伴奏音量波动。 |
|
||||
| [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) | 2026-09-04 | 增加桌面端伴奏、身份保持提醒和网站图标;修复 WebRTC 成员独立音量。 |
|
||||
| [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) | 2026-09-04 | 修复身份保存逻辑并优化主题切换。 |
|
||||
| [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) | 2026-09-03 | 修复 WebRTC、频道聊天并优化管理页、日志和移动端布局。 |
|
||||
| [v0.1.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.3) | 2026-09-03 | 引入内置 WebRTC、迁移 TeamSpeak SDK 并改善成员同步和语音缓冲。 |
|
||||
|
||||
完整记录见 [CHANGELOG.md](../CHANGELOG.md)。
|
||||
|
||||
## 🚀 部署方案
|
||||
|
||||
| 方案 | 适用场景 | 环境 |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose(推荐) | 长期运行、升级简单、数据持久化 | Docker Engine + Docker Compose |
|
||||
| 发布包 | 不安装 Node.js 和构建依赖 | Windows x64 或 Linux x64 |
|
||||
| 源码运行 | 开发、调试和二次开发 | Node.js 22.5+、Git 和本地编译工具 |
|
||||
|
||||
### Docker Compose(推荐)
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
启动后访问 `http://<你的主机>:3040`。使用反向代理时将上游指向该地址;启用 WebRTC 时放行控制台显示的 UDP 端口范围。数据保存在 `webspeak-data` volume 中。
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
升级:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
不要执行 `docker compose down -v`,否则会删除数据库和管理员设置。
|
||||
|
||||
### 发布包
|
||||
|
||||
从 [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 下载对应的 `windows-x64.zip` 或 `linux-x64.tar.gz`,解压后运行 Windows 的 `start-webspeak.cmd` 或 Linux 的 `./start-webspeak.sh`。发布包自带 Node.js 运行时和生产依赖。
|
||||
|
||||
### 源码运行
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
构建 `@discordjs/opus` 需要 Python、Make 和 C/C++ 编译工具。
|
||||
|
||||
### 首次配置
|
||||
|
||||
1. 打开 `http://<你的主机>:3040/admin`。
|
||||
2. 使用默认账号 `admin` / `admin` 登录,并立即设置至少 12 位的新密码。
|
||||
3. 在“服务器”页配置 TeamSpeak 目标和访问方式,例如 `voice.example.com#9987`。
|
||||
4. 公网使用时配置 HTTPS;启用 WebRTC 时放行控制台显示的 UDP 范围。
|
||||
|
||||
## ⚠️ 要求和注意事项
|
||||
|
||||
| 项目 | 要求或注意事项 |
|
||||
| --- | --- |
|
||||
| 浏览器 | 建议使用最新版 Chrome、Edge 或其他支持 WebRTC 的现代浏览器。麦克风和窗口音频通常要求 HTTPS。 |
|
||||
| TeamSpeak 网络 | WebSpeak 主机必须能够访问目标 TeamSpeak;默认语音端口为 `9987`。 |
|
||||
| Web 服务网络 | 服务使用 `3040/TCP`,公网建议通过 HTTPS 反向代理提供网页和 WebSocket。 |
|
||||
| IPv6 | IPv6 字面量写为 `[2001:db8::1]#9987`。主机/容器需要可路由 IPv6、启用 IPv6 的操作系统和 Node.js,以及相应防火墙放行。 |
|
||||
| WebRTC | 默认使用 `40000–40099/UDP`,启用后需放行整个范围;修改范围前先关闭 WebRTC。 |
|
||||
| 身份保持 | 同一浏览器身份同时只能保持一条活动连接;并行连接请关闭第二条的身份保持或使用其他浏览器配置文件。 |
|
||||
| 伴奏 | 仅桌面端提供且要求 WebRTC;选择窗口或标签页时还要勾选共享音频。 |
|
||||
| 数据 | Docker 数据在 `webspeak-data` volume;发布包和源码运行数据在 `data/`。升级前建议备份。 |
|
||||
| 会话上限 | 单实例最多允许 100 个活动网页会话。 |
|
||||
@@ -0,0 +1,249 @@
|
||||
# WebSpeak 皮肤开发规范
|
||||
|
||||
本文说明如何制作、校验并发布 WebSpeak `.wskin` 皮肤包。皮肤可为公开页面逐个部件定制二次元美术表现:背景、素材、配色、轮廓、圆角、阴影、头像装饰、按钮质感、滚动条颜色和播放器外观都可以自定义;但组件的位置、尺寸、排列、文字排版空间及交互结构由 WebSpeak 固定提供,皮肤不得重排或覆盖。
|
||||
|
||||
页面结构、必要控件和所有基础翻译均由 WebSpeak 提供。皮肤包不必携带文案;如果只包含样式与美术素材,所有界面文字仍由 WebSpeak 按当前语言显示。`content.json` 仅用于可选覆盖,缺少的语言或字段回退到 WebSpeak 的基础内容。皮肤不注入 HTML 或 JavaScript,也不改变语音、权限、连接、拖动和屏幕共享行为。**管理后台 `/admin/**` 不属于皮肤范围,始终使用 WebSpeak 自己的固定样式。**
|
||||
|
||||
可直接查看 [ILLUSIA 风示例源码](examples/illusia-voice/) 与 [示例说明](examples/ILLUSIA-VOICE.md)。它使用本地美术素材和 CSS 完整定制首页、语音房间、成员区、聊天空状态及播放器,同时沿用 WebSpeak 提供的基础翻译;也是管理控制台内置且不可移除的示例皮肤。
|
||||
|
||||
## 使用与发布
|
||||
|
||||
管理员在 `/admin/skins` 查看三款随 WebSpeak 提供的内置皮肤,并可导入、替换、启用/停用或删除实例自定义皮肤;还可指定访客首次访问时使用的默认皮肤。默认日间、默认夜间和 ILLUSIA 风为受保护内置项,不可替换、停用或移除。访客手动选择的皮肤保存在该浏览器,后续实例默认值变更不会覆盖该明确选择;仅自动套用过旧默认值的浏览器会采用最新实例默认值。皮肤包会缓存在浏览器本地;页面启动时会查询实例目录,目录可用且版本更新时拉取新包。若网络不可用,已缓存的版本仍可使用。
|
||||
|
||||
选择器提供默认日间、默认夜间、内置 ILLUSIA 风和已启用的实例皮肤;没有“跟随系统”选项。停用的实例皮肤不向访客展示,也不能从服务端下载;若它是当前默认皮肤,系统会安全回退到默认日间。管理员设置的默认值只影响未手动选择皮肤的访客。自定义皮肤是独立的外观选择,不继承之前的日间或夜间模式;皮肤未覆盖的部件回退到浅色基础外观,避免一套组件混入另一套模式。自定义皮肤可自行声明 `color-scheme` 并定义深色外观;切换为日间或夜间时,会停用当前自定义包。文档级 `data-theme` 仍由 WebSpeak 保留给管理后台使用。
|
||||
|
||||
## 包结构
|
||||
|
||||
`.wskin` 是标准 ZIP 容器,推荐把下列文件直接放在 ZIP 根目录:
|
||||
|
||||
```text
|
||||
manifest.json # 必需:身份、版本与入口
|
||||
skin.css # 必需:皮肤样式
|
||||
content.json # 可选:首页内容与多语言界面文案
|
||||
assets/preview.jpg # 可选:管理后台显示的预览图,也可在 CSS 中使用
|
||||
assets/background.webp # 可选:页面艺术素材
|
||||
assets/brand.woff2 # 可选:自带字体
|
||||
```
|
||||
|
||||
所有资源路径使用 `/`,区分大小写,并相对于包根目录。CSS 的 `url()` 使用同样的包根相对路径,例如 `url("assets/background.webp")`。不得使用机器本地路径、站点绝对路径或远程 URL。
|
||||
|
||||
### `manifest.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "community.illusia-voice",
|
||||
"name": "ILLUSIA风",
|
||||
"version": "1.0.25",
|
||||
"author": "WebSpeak Project",
|
||||
"license": "All rights reserved",
|
||||
"description": "A visual-only art skin using the WebSpeak interface translations.",
|
||||
"entry": "skin.css",
|
||||
"preview": "assets/background-composite.webp",
|
||||
"minAppVersion": "0.2.5"
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 规则 |
|
||||
| --- | --- |
|
||||
| `schemaVersion` | 当前必须为数字 `1`。 |
|
||||
| `id` | 必需,最多 80 个字符;只允许小写字母、数字、点和连字符;不能以 `builtin.` 开头,也不能使用受保护 ID `builtin.light`、`builtin.dark` 或 `community.illusia-voice`。发布后不要更改。 |
|
||||
| `name`、`author`、`license` | 必需,各最多 80 个字符。资源授权由作者负责确认。 |
|
||||
| `version`、`minAppVersion` | 必需,使用语义化版本号,例如 `1.2.0`。 |
|
||||
| `entry` | 必需,包内 CSS 文件路径,最多 120 个字符。 |
|
||||
| `content` | 可选,包内 JSON 文件路径,最多 120 个字符。 |
|
||||
| `preview` | 可选,包内 PNG、JPG/JPEG、WebP、AVIF 或 GIF 图片路径,最多 120 个字符。 |
|
||||
| `description` | 可选,最多 400 个字符。 |
|
||||
|
||||
清单不得重复声明同一个文件为 CSS、内容或预览入口。
|
||||
|
||||
## 首页内容和文案
|
||||
|
||||
`content.json` 完全可选。WebSpeak 自带中文、英语、德语、俄语和日语的基础内容,因此纯美术皮肤无需复制翻译文件。若希望为皮肤定制部分文案,可按 locale 覆盖连接首页内容和公开界面文案;未定义的语言、字段或翻译键会回退到 WebSpeak 内容,不要求皮肤重复提供整套文字。当前允许 1–20 个 locale,locale 写作 `en`、`zh-CN`、`ja-JP` 等形式。`defaultLocale` 必须指向一个已定义的 locale。示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"defaultLocale": "en",
|
||||
"locales": {
|
||||
"en": {
|
||||
"home": {
|
||||
"eyebrow": "A room of your own",
|
||||
"title": "Talk",
|
||||
"titleAccent": "together",
|
||||
"description": "Join a voice room from your browser.",
|
||||
"welcomeTitle": "Join the room",
|
||||
"welcomeDescription": "Choose a name and connect.",
|
||||
"features": [
|
||||
{ "title": "Clear voice", "description": "Low-latency Opus audio." }
|
||||
]
|
||||
},
|
||||
"messages": {
|
||||
"home.connect": "Enter the room",
|
||||
"voice.activity-heading": "Voice activity",
|
||||
"demo.heroLead": "A preview customized by this skin."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`home` 支持 `brandName`、`eyebrow`、`title`、`titleAccent`、`description`、`welcomeTitle`、`welcomeDescription` 和 `features`。普通文字最多 500 个字符;`features` 最多 8 项,每项的 `title` 最多 80 个字符、`description` 最多 240 个字符。功能卡片图标和状态由应用提供,皮肤不能通过 JSON 注入节点。
|
||||
|
||||
`messages` 的键是公开页面中翻译调用使用的键;首页/语音页键可在 `web/src/i18n/web-client.ts` 查找,演示页键使用 `demo.` 前缀加字段名(例如 `demo.heroLead`、`demo.speakingNow`)。每个 locale 最多覆盖 200 条,每条文案最多 500 个字符。键只能由小写字母开头,并包含字母、数字或点。语言回退顺序为默认 locale、当前语言和更具体的 locale;之后回退到 WebSpeak 原文。
|
||||
|
||||
管理后台的文字不读取皮肤包,不能通过 `messages` 修改。
|
||||
|
||||
## CSS 皮肤接口
|
||||
|
||||
### 自动隔离
|
||||
|
||||
运行时把 `skin.css` 的每个选择器限定在皮肤自己的公开页面根节点内:
|
||||
|
||||
```css
|
||||
/* 选择器必须使用公开的页面/部件钩子;运行时再加上皮肤根作用域。 */
|
||||
[data-ws-page="voice"] [data-ws-part="voice.member.avatar"] {
|
||||
outline: 2px solid var(--skin-accent);
|
||||
outline-offset: 4px;
|
||||
}
|
||||
```
|
||||
|
||||
实际规则会被限定在类似下面的根节点内,不会匹配 `/admin/**`:
|
||||
|
||||
```css
|
||||
[data-ws-page="voice"] [data-ws-part="voice.member.avatar"]
|
||||
```
|
||||
|
||||
也可以写 `:root { --skin-accent: ... }` 设置皮肤自己的变量;`:root` 会被转换成当前皮肤根。选择器必须包含 `:root`、`[data-ws-page]` 或 `[data-ws-part]`。不要写 `:global()`、`html`、`body` 或 Vue 内部 class 作为公开接口。组件 class 可能随版本调整,`data-ws-part` 才是皮肤作者接口。自定义变量名必须使用 `--skin-` 前缀,不能覆盖 WebSpeak 的内部令牌。
|
||||
|
||||
页面根节点使用 `data-ws-page` 区分 `home`、`voice` 和 `demo`。使用 `data-ws-state` 选择明确状态,如 `active`、`idle`、`current`、`open`、`closed`、`drag-over`、`dragging`、`speaking`、`connected`、`self`、`mine` 或 `other`。语音成员还提供 `data-ws-speaking="true|false"` 和 `data-ws-self="true|false"`。交互元素会带有 `data-ws-critical="true"`;没有专属部件名称的按钮、链接、输入框、滑块和可拖动成员会使用通用部件 `data-ws-part="control"`,并以 `data-ws-control-kind` 标出 `button`、`link`、`input`、`checkbox`、`range`、`select`、`textarea`、`menuitem` 或 `draggable`。
|
||||
|
||||
### 已发布的部件名称
|
||||
|
||||
下列名称来自当前前端模板。对新功能,作者可以先用通用 `control` 部件;后续新增稳定部件会更新本目录。
|
||||
|
||||
| 页面区域 | `data-ws-part` |
|
||||
| --- | --- |
|
||||
| 通用 | `app`、`app.toast`、`control`、`skin.trigger`、`skin.menu`、`skin.option`、`language.trigger`、`language.menu`、`language.option` |
|
||||
| 首页 | `home`、`home.header`、`home.brand`、`home.header-tools`、`home.gateway-status`、`home.content`、`home.hero`、`home.hero.eyebrow`、`home.hero.title`、`home.hero.description`、`home.features`、`home.feature`、`home.visitors`、`home.join-card`、`home.join-card.waveform`、`home.join-card.sonar`、`home.join-title`、`home.join-description`、`home.notice`、`home.form`、`home.server-target`、`home.field-label`、`home.field`、`home.relay-choice`、`home.relay-choice.copy`、`home.server-history`、`home.server-history.group`、`home.favorite-toggle`、`home.identity`、`home.connect`、`home.security-note`、`home.footer`、`home.community-dialog` |
|
||||
| 语音工作区 | `voice.shell`、`voice.workspace`、`voice.header`、`voice.header-actions`、`voice.breadcrumbs`、`voice.performance`、`voice.performance.panel`、`voice.performance.route`、`voice.performance.metrics`、`voice.performance.status`、`voice.performance.webrtc-stats`、`voice.connection-status`、`voice.audio-status`、`voice.poke`、`voice.scroll`、`voice.content`、`voice.activity`、`voice.activity.artwork`、`voice.activity-heading`、`voice.screen-share-error`、`voice.members`、`voice.members.empty`、`voice.member`、`voice.member.avatar-wrap`、`voice.member.avatar`、`voice.member.name`、`voice.member.status`、`voice.member.live-indicator`、`voice.member.stop-share`、`voice.member.share-actions`、`voice.member-panel`、`voice.member-panel.heading`、`voice.member-panel.search`、`voice.member-panel.channels`、`voice.channel-group`、`voice.channel-group.heading`、`voice.channel-group.members`、`voice.member-row`、`voice.member-row.avatar`、`voice.member-row.copy`、`voice.member-row.flags`、`voice.member-row.volume`、`voice.whisper-strip`、`voice.audio-dock`、`voice.audio-dock.microphone`、`voice.audio-dock.microphone-panel`、`voice.audio-dock.output`、`voice.audio-dock.output-panel`、`voice.audio-settings`、`voice.mobile-more`、`voice.mobile-nav` |
|
||||
| 聊天与菜单 | `voice.chat`、`voice.chat.tabs`、`voice.chat.tab`、`voice.chat.heading`、`voice.chat.messages`、`voice.chat.event`、`voice.chat.message`、`voice.chat.message-avatar`、`voice.chat.message-body`、`voice.chat.message-bubble`、`voice.chat.empty`、`voice.chat.composer`、`voice.context-menu-backdrop`、`voice.context-menu`、`voice.context-menu.header`、`voice.context-menu.move-submenu` |
|
||||
| 屏幕共享 | `voice.screen-share-settings`、`voice.screen-share-settings.heading`、`voice.screen-share-settings.fields`、`voice.screen-share-settings.note`、`voice.screen-share-settings.actions`、`voice.screen-player`、`voice.screen-player.stage`、`voice.screen-player.video`、`voice.screen-player.placeholder`、`voice.screen-player.exit`、`voice.screen-player.viewers`、`voice.screen-player.viewer-avatar`、`voice.screen-player.live`、`voice.screen-player.source`、`voice.screen-player.controls`、`voice.screen-player.volume`、`voice.screen-player.fullscreen` |
|
||||
| `/demo` 演示页 | `demo.header`、`demo.brand`、`demo.header-tools`、`demo.badge`、`demo.skin-switcher`、`demo.language-switcher`、`demo.home-link`、`demo.reconnect`、`demo.reconnect.restore`、`demo.layout`、`demo.channels`、`demo.channels.heading`、`demo.channel`、`demo.channel.select`、`demo.channel.members`、`demo.main`、`demo.hero`、`demo.live`、`demo.hero.title`、`demo.hero.description`、`demo.hero.online`、`demo.wave`、`demo.voice-heading`、`demo.voice-grid`、`demo.voice-card`、`demo.avatar`、`demo.member-name`、`demo.member-status`、`demo.chat.heading`、`demo.chat.tabs`、`demo.chat.tab`、`demo.chat.messages`、`demo.chat.message`、`demo.chat.empty`、`demo.chat.composer`、`demo.chat.input`、`demo.chat.send`、`demo.actions`、`demo.actions.heading`、`demo.action.speaking`、`demo.action.poke`、`demo.action.reconnect`、`demo.note`、`demo.user`、`demo.poke-notification`、`demo.poke.dismiss` |
|
||||
|
||||
`voice.member.avatar` 是语音活动区头像;`voice.member-row.avatar` 是右侧成员树头像。状态属性还会使用 `current`、`drag-over`、`dragging`、`self`、`events-empty` 和 `messages-empty`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。
|
||||
|
||||
`voice.activity.artwork` 是位于语音活动区内容上方的固定装饰平面。皮肤可以在其上绘制带透明背景的立绘,让角色压住成员卡片或直播画面的边缘;平面本身不占布局空间、不拦截点击,成员和播放器控件仍保持可交互。只通过背景图及背景定位/缩放来适配素材,不改变其定位和层级。
|
||||
|
||||
`voice.member-panel` 的 `::before` 是成员栏耳机/场景插画层,宿主已固定它的尺寸、位置、透视和前后层级;皮肤只需提供透明背景素材并调整背景显示、滤镜或阴影,不能自行定位或改变尺寸。消息空状态的 `::before` / `::after` 预留给气泡等小型装饰,宿主负责形状位置;皮肤可以绘制边框、底色和点状背景,但标题和说明文字仍由 WebSpeak 翻译并保持可见。
|
||||
|
||||
皮肤与语言选择器的触发按钮、菜单和每个选项都提供上述通用部件钩子。`skin.option` 另带有 `data-ws-skin-id`(内置项为 `builtin.light`、`builtin.dark` 和 `community.illusia-voice`,实例皮肤项为其清单 ID);`language.option` 带有 `data-ws-language`。皮肤可以据此只装饰自己的选择项,而不影响其他皮肤、语言选项或选择器交互。例如:
|
||||
|
||||
```css
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"] {
|
||||
background-image: linear-gradient(110deg, #efffff, #c8f3f2);
|
||||
}
|
||||
```
|
||||
|
||||
### 令牌、字体、动效和图片
|
||||
|
||||
皮肤只负责“画什么样”,不负责“放在哪里”。可用的视觉规则包括文字/背景颜色、背景图片及其裁切、圆角、轮廓、阴影、滤镜和动画;边框可用不占空间的内阴影绘制。推荐先定义皮肤变量,再为公开部件编写视觉规则:
|
||||
|
||||
```css
|
||||
:root {
|
||||
--skin-page-bg: #091317;
|
||||
--skin-panel: #142329;
|
||||
--skin-text: #edf8f5;
|
||||
--skin-muted: #9db5af;
|
||||
--skin-accent: #47dcc4;
|
||||
--skin-card-radius: 20px;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player"] {
|
||||
border-radius: var(--skin-card-radius);
|
||||
box-shadow: 0 18px 50px #0008, inset 0 0 0 1px color-mix(in srgb, var(--skin-accent) 50%, transparent);
|
||||
}
|
||||
```
|
||||
|
||||
`url()` 只允许引用包内图片或 WOFF2 字体。支持 PNG、JPG/JPEG、WebP、AVIF、GIF 和 WOFF2;SVG 不接受。自带字体示例:
|
||||
|
||||
```css
|
||||
@font-face {
|
||||
font-family: "ILLUSIA Sans";
|
||||
src: url("assets/illusia-sans.woff2") format("woff2");
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
[data-ws-page="voice"] { font-family: "ILLUSIA Sans", sans-serif; }
|
||||
```
|
||||
|
||||
字体必须随包附带并拥有可再分发许可。自定义字体可能改变不同语言的字宽,因此校验器会给出提示;发布前必须检查中文、英语、德语、俄语和日语下的标题、按钮和长文案是否仍完整可读。字体族名和 `@keyframes` / `@layer` 名称会自动隔离,避免与其他皮肤冲突。请支持 `prefers-reduced-motion`,并确保焦点、错误、静音、正在说话等状态仍容易辨认。
|
||||
|
||||
### 固定布局与交互边界
|
||||
|
||||
皮肤校验器会拒绝改变布局、定位、尺寸、文字流向/换行或交互命中区域的 CSS 声明,包括 `display`、`position`、`inset`、`z-index`、宽高、内外边距、网格/弹性布局、间距、溢出裁切、变换、指针事件、字号、行高、字距、大小写转换和换行方式等。也不能通过 `all` 重置组件或用伪元素生成/替换文字。动画可以用于颜色、阴影、滤镜等装饰效果,但关键帧同样不能动画化布局属性。
|
||||
|
||||
因此,皮肤可以把成员头像绘制成角色徽章、给屏幕播放器加主题边框和背景、换首页美术素材,但不能移动播放器、压缩文字、扩大/缩小成员卡片、把锚定浮层改成模态弹窗,或挪动按钮的点击区域。用 `background-position` / `background-size` 只调整图片在既有区域中的裁切,不改变组件盒子。轮廓或内阴影可作为不参与排版的描边。
|
||||
|
||||
外观可以因窄屏而更换图片裁切或装饰,但 `@media` 规则也受同一限制,不能用来重排组件。上线前仍需预览桌面与窄屏、所有五种语言、日夜基础主题、键盘焦点、减少动效偏好,并确认浮层和必要控件保持在原位、文字未被裁切。
|
||||
|
||||
## 安全边界和限制
|
||||
|
||||
校验在上传端和服务端执行;服务端只登记有效皮肤包,访客只能下载登记的包。当前限制如下:
|
||||
|
||||
| 项目 | 上限 |
|
||||
| --- | ---: |
|
||||
| ZIP `.wskin` | 20 MiB |
|
||||
| 解压总大小 | 50 MiB |
|
||||
| ZIP 条目数 | 128 |
|
||||
| 单个 CSS 文件 | 512 KiB |
|
||||
| `content.json` | 256 KiB |
|
||||
| 单张图片(包括预览) | 16 MiB |
|
||||
| 单个 WOFF2 字体 | 4 MiB |
|
||||
| 每实例皮肤数 | 50 |
|
||||
| 每实例皮肤包总存储 | 200 MiB |
|
||||
|
||||
压缩包路径穿越、重复/冲突路径、符号链接、异常 ZIP 元数据和本地文件头/目录不一致都会被拒绝。仅允许受支持的 CSS at-rule:`@media`、`@supports`、`@container`、具名 `@layer`、`@font-face` 和 keyframes。`@import`、脚本、HTML、外部网络资源会被拒绝;`!important` 可用于皮肤作用域内的样式。字体 `local()` 也会拒绝,避免绕过包内字体来源。
|
||||
|
||||
必要操作控件(加入/退出、麦克风、设置、菜单、屏幕共享退出、音量、全屏等)及其布局容器不能被隐藏或整体重置。只有下列明确标记为可选的装饰部件,才允许通过不改变排版盒子的透明度效果淡出:
|
||||
|
||||
```css
|
||||
[data-ws-part="home.hero.eyebrow"]
|
||||
[data-ws-part="home.gateway-status"]
|
||||
[data-ws-part="home.features"]
|
||||
[data-ws-part="home.feature"]
|
||||
[data-ws-part="home.visitors"]
|
||||
[data-ws-part="voice.activity-heading"]
|
||||
[data-ws-part="voice.member.avatar"]
|
||||
[data-ws-part="voice.member.live-indicator"]
|
||||
[data-ws-part="voice.member-row.avatar"]
|
||||
[data-ws-part="voice.screen-player.viewer-avatar"]
|
||||
[data-ws-part="voice.screen-player.live"]
|
||||
[data-ws-part="demo.badge"]
|
||||
[data-ws-part="demo.wave"]
|
||||
[data-ws-part="demo.avatar"]
|
||||
[data-ws-part="demo.member-status"]
|
||||
[data-ws-part="demo.note"]
|
||||
```
|
||||
|
||||
上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。关键帧只有在其动画仅被这些可选部件引用时,才可使用透明度归零;若关键帧也被必要控件引用或动画名通过变量指定,则会被拒绝。`clip`、`clip-path` 和 `mask` 一律不允许,避免视觉裁切误伤真实控件。校验器是防止布局回归的边界,不是视觉质量证明;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。
|
||||
|
||||
皮肤可以重画控制外观,但不能重新布置或阻断加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等必要操作。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、日夜基础主题、键盘焦点与减少动效设置。
|
||||
|
||||
CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删除实例里的包会停止从服务器提供该包;已经下载过的浏览器副本会保留在本地存储,因此仍可能在该浏览器的选择器中出现。清除该站点的浏览器数据可移除本地副本。
|
||||
|
||||
## 制作与验收
|
||||
|
||||
1. 复制 `docs/examples/illusia-voice/`,先修改 `manifest.json` 的唯一 `id`、名称、作者、版本和授权。ILLUSIA 是完整的美术参考,不是必须沿用的角色或配色。
|
||||
2. 只使用本目录公开的 `data-ws-part`、`data-ws-page`、状态属性和包内静态资源。不要依赖 Vue 内部 class。
|
||||
3. 使用本地资源编写 `skin.css`;需要改首页文字或公开翻译时补充 `content.json`。
|
||||
4. 在包根目录生成 ZIP,再改扩展名为 `.wskin`。PowerShell 示例:
|
||||
|
||||
```powershell
|
||||
Compress-Archive -Path .\docs\examples\illusia-voice\* -DestinationPath .\illusia-voice.zip -Force
|
||||
Rename-Item .\illusia-voice.zip illusia-voice.wskin
|
||||
```
|
||||
|
||||
5. 在管理员后台 `/admin/skins` 上传。用访客浏览器分别检查连接首页、进入语音页和 `/demo`;测试自定义图片、所有交互控件、语音/静音状态、成员列表、聊天、屏幕共享播放器和设置,确认组件位置、尺寸、排列与未启用皮肤时一致。
|
||||
6. 检查至少一个窄屏尺寸和桌面尺寸,并检查焦点可见、对比度、动效偏好;确认没有第三方素材授权问题。
|
||||
|
||||
当前自动化回归涵盖 ZIP/清单验证、资源路径、CSS 隔离与拒绝规则、文案结构和服务端皮肤目录读写。视觉排版、内容遮挡和浏览器间表现仍须人工预览。
|
||||
@@ -0,0 +1,14 @@
|
||||
# ILLUSIA风
|
||||
|
||||
ILLUSIA风 is a visual-only `.wskin` example built from the local artwork in `illusia-voice/assets/`. It styles the WebSpeak home page, voice workspace, screen-share player, and `/demo` with bright glass surfaces and cyan accents. The homepage skin follows the supplied reference art for the translucent navigation, matching glass skin and language selectors, an illustrated animated ILLUSIA skin option, a floating mascot with a visibly pulsing cyan waveform and expanding halo in the join card, a softly animated cyan aurora inspired by the visitor badge, three feature tiles, character visitor badge, mascot-accented join action, and full-width curved footer. The ambient waveform and halo slow down when reduced motion is enabled instead of disappearing. The voice-room skin uses the resting chibi illustration as the message-empty backdrop and places the main character illustration on the dedicated non-interactive artwork layer so it can rest over the edge of member cards or a live screen-share player without moving or blocking their controls.
|
||||
|
||||
This package intentionally omits `content.json`: the existing WebSpeak translations supply every label and message, including the current and total visitor counts. A skin may optionally add localized copy overrides, but missing locales and fields continue to use WebSpeak's base content. Its CSS is visual-only: WebSpeak retains its component positions, dimensions, text flow, and interactions. In the voice room, the main illustration and headset use separate, non-interactive foreground layers with restrained perspective and shadows; the chat's empty state includes a CSS-drawn speech-bubble ornament, while its translated copy remains visible. The footer wave is a pre-rendered transparent asset sampled from the example's original curve, so it decorates the existing footer instead of introducing another layout element.
|
||||
|
||||
The package source is in [`illusia-voice/`](illusia-voice/). To build it from the repository root:
|
||||
|
||||
```powershell
|
||||
Compress-Archive -Path .\docs\examples\illusia-voice\* -DestinationPath .\docs\examples\illusia-voice.zip -Force
|
||||
Rename-Item .\docs\examples\illusia-voice.zip illusia-voice.wskin -Force
|
||||
```
|
||||
|
||||
Use only artwork you have permission to redistribute when publishing a skin to other WebSpeak instances.
|
||||
|
After Width: | Height: | Size: 1014 KiB |
|
After Width: | Height: | Size: 365 KiB |
|
After Width: | Height: | Size: 113 KiB |
|
After Width: | Height: | Size: 74 KiB |
|
After Width: | Height: | Size: 358 KiB |
|
After Width: | Height: | Size: 738 KiB |
|
After Width: | Height: | Size: 72 KiB |
|
After Width: | Height: | Size: 249 KiB |
|
After Width: | Height: | Size: 7.7 KiB |
|
After Width: | Height: | Size: 168 KiB |
|
After Width: | Height: | Size: 217 KiB |
|
After Width: | Height: | Size: 85 KiB |
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "community.illusia-voice",
|
||||
"name": "ILLUSIA风",
|
||||
"version": "1.0.27",
|
||||
"author": "WebSpeak Project",
|
||||
"license": "All rights reserved",
|
||||
"description": "A bright original-character art skin for the home, voice room, and demo pages.",
|
||||
"entry": "skin.css",
|
||||
"preview": "assets/background-composite.webp",
|
||||
"minAppVersion": "0.2.5"
|
||||
}
|
||||
@@ -0,0 +1,972 @@
|
||||
/* ILLUSIA风: bright glass surfaces, cyan accents, and project artwork. */
|
||||
:root {
|
||||
--skin-illusia-ink: #123849;
|
||||
--skin-illusia-muted: #4f6974;
|
||||
--skin-illusia-teal: #087e86;
|
||||
--skin-illusia-aqua: #47c9d4;
|
||||
--skin-illusia-glass: rgba(250, 254, 255, .96);
|
||||
--skin-illusia-line: rgba(115, 205, 218, .38);
|
||||
--skin-illusia-shadow: 0 20px 56px rgba(29, 91, 113, .16);
|
||||
}
|
||||
|
||||
/* Homepage uses the full-resolution original-character composition. */
|
||||
[data-ws-part="home"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
background-color: #eaf7fc;
|
||||
background-image:
|
||||
radial-gradient(ellipse at 14% 78%, rgba(90, 222, 230, .28), transparent 34%),
|
||||
radial-gradient(ellipse at 83% 21%, rgba(94, 190, 255, .24), transparent 30%),
|
||||
radial-gradient(ellipse at 52% 56%, rgba(190, 239, 255, .16), transparent 42%),
|
||||
linear-gradient(90deg, rgba(246, 252, 255, .91) 0%, rgba(246, 252, 255, .82) 33%, rgba(246, 252, 255, .32) 60%, rgba(246, 252, 255, .08) 100%),
|
||||
url("assets/background-composite.webp");
|
||||
background-position: 0% 100%, 100% 0%, 50% 50%, center, center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: 132% 130%, 122% 124%, 116% 116%, cover, cover;
|
||||
animation: illusia-home-aura 18s ease-in-out infinite alternate;
|
||||
}
|
||||
|
||||
@keyframes illusia-home-aura {
|
||||
from { background-position: 0% 100%, 100% 0%, 50% 50%, center, center; }
|
||||
to { background-position: 20% 82%, 78% 18%, 55% 45%, center, center; }
|
||||
}
|
||||
|
||||
[data-ws-part="home.header"] {
|
||||
border-color: rgba(255, 255, 255, .85);
|
||||
border-radius: 999px;
|
||||
background: linear-gradient(135deg, rgba(255, 255, 255, .8), rgba(255, 255, 255, .45));
|
||||
box-shadow: 0 26px 80px rgba(78, 150, 173, .17), inset 0 1px 0 rgba(255, 255, 255, .9);
|
||||
backdrop-filter: blur(22px) saturate(1.18);
|
||||
}
|
||||
|
||||
[data-ws-part="home.header"] [data-ws-part="control"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(255, 255, 255, .76);
|
||||
border-radius: 999px;
|
||||
background: rgba(250, 254, 255, .84);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .42);
|
||||
}
|
||||
|
||||
[data-ws-part="home.header"] [data-ws-part="control"]:hover {
|
||||
background: rgba(255, 255, 255, .98);
|
||||
}
|
||||
|
||||
/* ARIA selectors raise specificity over component defaults without private classes. */
|
||||
[data-ws-part="skin.trigger"][aria-haspopup="listbox"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(255, 255, 255, .82);
|
||||
border-radius: 999px;
|
||||
background: rgba(250, 254, 255, .86);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .5);
|
||||
}
|
||||
|
||||
[data-ws-part="skin.trigger"][aria-haspopup="listbox"]:hover,
|
||||
[data-ws-part="skin.trigger"][aria-haspopup="listbox"]:focus-visible,
|
||||
[data-ws-part="skin.trigger"][aria-haspopup="listbox"][aria-expanded="true"][data-ws-state="open"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(71, 201, 212, .52);
|
||||
background: rgba(255, 255, 255, .98);
|
||||
}
|
||||
|
||||
[data-ws-part="skin.menu"][role="listbox"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(104, 196, 211, .58);
|
||||
border-radius: 15px;
|
||||
background: linear-gradient(145deg, rgba(250, 255, 255, .98), rgba(222, 246, 250, .96));
|
||||
box-shadow: 0 18px 42px rgba(29, 115, 139, .22), inset 0 1px 0 rgba(255, 255, 255, .96);
|
||||
backdrop-filter: blur(18px) saturate(1.18);
|
||||
}
|
||||
|
||||
[data-ws-part="skin.option"][role="option"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-radius: 9px;
|
||||
background: rgba(255, 255, 255, .54);
|
||||
transition: color .16s, background .16s, border-color .16s, box-shadow .16s;
|
||||
}
|
||||
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"] {
|
||||
color: #075e68;
|
||||
border-color: rgba(82, 195, 204, .46);
|
||||
background-image: linear-gradient(112deg, rgba(255, 255, 255, .96), rgba(225, 250, 249, .96), rgba(188, 241, 237, .94), rgba(255, 255, 255, .96));
|
||||
background-position: 0% 50%;
|
||||
background-size: 240% 100%;
|
||||
box-shadow: 0 4px 14px rgba(30, 170, 184, .17), inset 0 0 0 1px rgba(255, 255, 255, .86);
|
||||
animation: illusia-option-gradient 8s ease-in-out infinite alternate;
|
||||
}
|
||||
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"] > :first-child {
|
||||
color: #07858a;
|
||||
filter: drop-shadow(0 0 5px rgba(71, 201, 212, .54));
|
||||
}
|
||||
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"]:hover,
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"]:focus-visible,
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"][aria-selected="true"] {
|
||||
color: #056e76;
|
||||
border-color: rgba(44, 186, 197, .7);
|
||||
background-image: linear-gradient(112deg, #faffff 0%, #c8f5f1 36%, #82e2dc 70%, #d9fbf8 100%);
|
||||
background-position: 100% 50%;
|
||||
box-shadow: 0 5px 18px rgba(30, 170, 184, .23), inset 0 0 0 1px rgba(255, 255, 255, .94);
|
||||
}
|
||||
|
||||
@keyframes illusia-option-gradient {
|
||||
from { background-position: 0% 50%; }
|
||||
to { background-position: 100% 50%; }
|
||||
}
|
||||
|
||||
[data-ws-part="language.trigger"][aria-haspopup="listbox"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(255, 255, 255, .82);
|
||||
border-radius: 999px;
|
||||
background: rgba(250, 254, 255, .86);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .5);
|
||||
}
|
||||
|
||||
[data-ws-part="language.trigger"][aria-haspopup="listbox"]:hover,
|
||||
[data-ws-part="language.trigger"][aria-haspopup="listbox"]:focus-visible,
|
||||
[data-ws-part="language.trigger"][aria-haspopup="listbox"][aria-expanded="true"][data-ws-state="open"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(71, 201, 212, .52);
|
||||
background: rgba(255, 255, 255, .98);
|
||||
}
|
||||
|
||||
[data-ws-part="language.menu"][role="listbox"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(104, 196, 211, .58);
|
||||
border-radius: 15px;
|
||||
background: linear-gradient(145deg, rgba(250, 255, 255, .98), rgba(222, 246, 250, .96));
|
||||
box-shadow: 0 18px 42px rgba(29, 115, 139, .22), inset 0 1px 0 rgba(255, 255, 255, .96);
|
||||
backdrop-filter: blur(18px) saturate(1.18);
|
||||
}
|
||||
|
||||
[data-ws-part="language.option"][role="option"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-radius: 9px;
|
||||
background: rgba(255, 255, 255, .54);
|
||||
}
|
||||
|
||||
[data-ws-part="language.option"][role="option"]:hover,
|
||||
[data-ws-part="language.option"][role="option"]:focus-visible,
|
||||
[data-ws-part="language.option"][role="option"][aria-selected="true"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(71, 201, 212, .42);
|
||||
background: rgba(211, 245, 248, .92);
|
||||
}
|
||||
|
||||
[data-ws-part="skin.option"][role="option"]:hover,
|
||||
[data-ws-part="skin.option"][role="option"]:focus-visible,
|
||||
[data-ws-part="skin.option"][role="option"][aria-selected="true"] {
|
||||
color: #087e86;
|
||||
border-color: rgba(71, 201, 212, .42);
|
||||
background: rgba(211, 245, 248, .92);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .82);
|
||||
}
|
||||
|
||||
[data-ws-part="home.brand"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
}
|
||||
|
||||
[data-ws-part="home.brand"] strong,
|
||||
[data-ws-part="home.hero.title"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="home.brand"] small,
|
||||
[data-ws-part="home.hero.description"],
|
||||
[data-ws-part="home.join-description"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="home.hero.title"] em {
|
||||
color: var(--skin-illusia-teal);
|
||||
text-shadow: 0 8px 28px rgba(47, 192, 202, .2);
|
||||
}
|
||||
|
||||
[data-ws-part="home.hero.eyebrow"] {
|
||||
color: #087a76;
|
||||
}
|
||||
|
||||
[data-ws-part="home.feature"] {
|
||||
border-color: rgba(255, 255, 255, .94);
|
||||
border-radius: 18px;
|
||||
background: rgba(255, 255, 255, .79);
|
||||
box-shadow: 0 14px 28px rgba(68, 158, 173, .12), inset 0 0 0 1px rgba(255, 255, 255, .42);
|
||||
backdrop-filter: blur(12px) saturate(1.08);
|
||||
}
|
||||
|
||||
[data-ws-part="home.feature"] > span:first-child {
|
||||
box-shadow: 0 5px 14px rgba(43, 157, 167, .12), inset 0 0 0 1px rgba(255, 255, 255, .56);
|
||||
}
|
||||
|
||||
[data-ws-part="home.feature"] b {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="home.feature"] small {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="home.visitors"] {
|
||||
color: #075c67;
|
||||
border-color: var(--skin-illusia-line);
|
||||
background-color: rgba(247, 254, 255, .9);
|
||||
background-image: linear-gradient(105deg, rgba(247, 254, 255, .98), rgba(237, 252, 253, .84));
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: cover;
|
||||
box-shadow: 0 10px 28px rgba(19, 142, 157, .14), inset 0 0 0 1px rgba(255, 255, 255, .72);
|
||||
backdrop-filter: blur(14px) saturate(1.12);
|
||||
}
|
||||
|
||||
[data-ws-part="home.visitors"] > span:nth-child(2) {
|
||||
color: transparent;
|
||||
background-color: transparent;
|
||||
background-image: url("assets/visitor-avatar.webp");
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: cover;
|
||||
box-shadow: 0 0 0 3px rgba(71, 201, 212, .26), 0 5px 16px rgba(19, 142, 157, .2);
|
||||
}
|
||||
|
||||
[data-ws-part="home.visitors"] > span:nth-child(2) svg {
|
||||
color: transparent;
|
||||
}
|
||||
|
||||
[data-ws-part="home.visitors"] > span:last-child {
|
||||
color: #41bdcc;
|
||||
text-shadow: 0 0 12px rgba(71, 201, 212, .42);
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(255, 255, 255, .9);
|
||||
border-radius: 26px;
|
||||
background-color: var(--skin-illusia-glass);
|
||||
background-image: url("assets/banner-mascot-blob.webp");
|
||||
background-position: right 18px top 10px;
|
||||
background-repeat: no-repeat;
|
||||
background-size: 96px 68px;
|
||||
box-shadow: var(--skin-illusia-shadow), 0 0 15px rgba(71, 201, 212, .14), inset 0 0 0 1px rgba(255, 255, 255, .84);
|
||||
backdrop-filter: blur(22px);
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card.waveform"] {
|
||||
color: #47c9d4;
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card.waveform"] i {
|
||||
box-shadow: 0 0 8px rgba(71, 201, 212, .52);
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card.sonar"] {
|
||||
color: rgba(71, 201, 212, .72);
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card.sonar"] i {
|
||||
box-shadow: 0 0 12px rgba(71, 201, 212, .16);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"] {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-title"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="home.field"] {
|
||||
color: #4f6974;
|
||||
border-color: rgba(134, 190, 200, .42);
|
||||
border-radius: 12px;
|
||||
background: rgba(232, 244, 247, .96);
|
||||
box-shadow: inset 0 0 0 1px rgba(134, 190, 200, .24);
|
||||
}
|
||||
|
||||
[data-ws-part="home.field"] input {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="home.field"] input::placeholder {
|
||||
color: #8ba4aa;
|
||||
}
|
||||
|
||||
[data-ws-part="home.field-label"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="home"] [data-ws-part="home.connect"] {
|
||||
color: #fff;
|
||||
border-radius: 14px;
|
||||
background-color: var(--skin-illusia-teal);
|
||||
background:
|
||||
url("assets/button-mascot.webp") right 4px center / 112px 74px no-repeat,
|
||||
linear-gradient(100deg, #38d6d0 0%, #0c9caf 62%, #08788d 100%) center / cover no-repeat;
|
||||
box-shadow: 0 12px 22px rgba(16, 181, 192, .24), inset 0 1px 0 rgba(255, 255, 255, .55), inset 0 0 0 1px rgba(141, 255, 255, .52);
|
||||
}
|
||||
|
||||
[data-ws-part="home"] [data-ws-part="home.connect"]:hover {
|
||||
background-color: #087078;
|
||||
box-shadow: 0 14px 30px rgba(8, 126, 134, .3);
|
||||
}
|
||||
|
||||
[data-ws-part="home.security-note"],
|
||||
[data-ws-part="home.footer"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="home.footer"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
border-color: transparent;
|
||||
background-color: transparent;
|
||||
background-image: url("assets/footer-wave.png");
|
||||
background-position: center top;
|
||||
background-repeat: no-repeat;
|
||||
background-size: 100% 58px;
|
||||
box-shadow: none;
|
||||
backdrop-filter: blur(8px) saturate(1.04);
|
||||
}
|
||||
|
||||
/* Voice room: let the artwork flow through the UI instead of stacking opaque cards. */
|
||||
:root {
|
||||
--skin-room-line: rgba(76, 176, 193, .3);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.shell"] {
|
||||
color-scheme: light;
|
||||
color: var(--skin-illusia-ink);
|
||||
background-color: #dff4f8;
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(21, 139, 157, .075) 1px, transparent 1.55px),
|
||||
radial-gradient(circle at 100% 0%, transparent 0 188px, rgba(71, 201, 212, .13) 189px 190px, transparent 191px 229px, rgba(71, 201, 212, .09) 230px 231px, transparent 232px),
|
||||
radial-gradient(ellipse at 13% 5%, rgba(107, 226, 232, .2), transparent 36%),
|
||||
linear-gradient(125deg, rgba(229, 248, 251, .19), rgba(239, 251, 253, .06) 48%, rgba(190, 235, 242, .22)),
|
||||
url("assets/bg-room-main.webp");
|
||||
background-position: 0 0, right top, left top, center, center;
|
||||
background-repeat: repeat, no-repeat, no-repeat, no-repeat, no-repeat;
|
||||
background-size: 24px 24px, 560px 450px, auto, auto, cover;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.workspace"] {
|
||||
background: linear-gradient(145deg, rgba(239, 251, 253, .22), rgba(218, 244, 248, .12) 48%, rgba(245, 253, 254, .2));
|
||||
backdrop-filter: blur(2px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity"] {
|
||||
border-color: rgba(113, 211, 222, .62);
|
||||
border-radius: 24px;
|
||||
background-color: rgba(227, 247, 250, .64);
|
||||
background-image:
|
||||
radial-gradient(ellipse at 82% 48%, rgba(91, 215, 224, .19), rgba(91, 215, 224, .04) 34%, transparent 65%),
|
||||
linear-gradient(90deg, rgba(230, 248, 251, .78), rgba(230, 248, 251, .36) 38%, rgba(230, 248, 251, .08) 72%),
|
||||
url("assets/bg-room-main.webp");
|
||||
background-position: right 5% center, center, center 48%;
|
||||
background-repeat: no-repeat;
|
||||
background-size: 48% 100%, 100% 100%, cover;
|
||||
box-shadow: 0 15px 38px rgba(30, 111, 132, .13), inset 0 0 0 1px rgba(255, 255, 255, .7);
|
||||
backdrop-filter: blur(10px) saturate(1.08);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity.artwork"] {
|
||||
background-image: url("assets/banner-character-main.webp");
|
||||
background-position: right 16px bottom 8px;
|
||||
background-size: auto 150px;
|
||||
filter: drop-shadow(0 18px 22px rgba(30, 113, 134, .2));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.header"] {
|
||||
border-color: rgba(126, 191, 203, .36);
|
||||
background: linear-gradient(105deg, rgba(249, 254, 255, .76), rgba(222, 246, 250, .57) 56%, rgba(247, 253, 254, .72));
|
||||
box-shadow: 0 8px 28px rgba(27, 92, 112, .08), inset 0 1px 0 rgba(255, 255, 255, .62);
|
||||
backdrop-filter: blur(16px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-panel"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: var(--skin-room-line);
|
||||
background-color: rgba(221, 245, 249, .66);
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(25, 145, 161, .065) 1px, transparent 1.5px),
|
||||
radial-gradient(circle at 100% 0%, transparent 0 86px, rgba(71, 201, 212, .16) 87px 88px, transparent 89px 119px, rgba(71, 201, 212, .1) 120px 121px, transparent 122px),
|
||||
radial-gradient(ellipse at 100% 0%, rgba(107, 226, 232, .2), transparent 43%),
|
||||
linear-gradient(155deg, rgba(248, 254, 255, .75), rgba(222, 246, 249, .58) 48%, rgba(213, 241, 246, .7));
|
||||
background-position: 0 0, right top, right top, center;
|
||||
background-repeat: repeat, no-repeat, no-repeat, no-repeat;
|
||||
background-size: 22px 22px, 360px 320px, auto, auto;
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
/* Keep the headset as an independent foreground object instead of flattening
|
||||
it into the member rail's background. Its slight perspective and shadow
|
||||
make it sit in front of the room, while the actual controls remain above it. */
|
||||
[data-ws-part="voice.member-panel"]::before {
|
||||
background-image: url("assets/foreground-headphone.webp");
|
||||
background-position: left bottom;
|
||||
background-repeat: no-repeat;
|
||||
background-size: contain;
|
||||
filter: drop-shadow(16px 18px 17px rgba(36, 105, 119, .24));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-panel.search"] {
|
||||
color: #4f7982;
|
||||
border-color: rgba(103, 186, 198, .28);
|
||||
background: linear-gradient(110deg, rgba(232, 249, 251, .86), rgba(216, 242, 247, .68));
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .58);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-panel.search"] input {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-panel.search"] input::placeholder {
|
||||
color: #78979d;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.channel-group"] {
|
||||
border-color: rgba(8, 126, 134, .32);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.channel-group"][data-ws-state="current"] {
|
||||
border-color: rgba(8, 126, 134, .48);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.channel-group.heading"] {
|
||||
color: #386b75;
|
||||
border-radius: 10px;
|
||||
background: linear-gradient(100deg, rgba(223, 246, 249, .68), rgba(237, 250, 251, .34));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.channel-group.heading"][data-ws-state="current"] {
|
||||
color: #087e86;
|
||||
background: linear-gradient(100deg, rgba(179, 235, 239, .78), rgba(224, 248, 249, .5));
|
||||
box-shadow: inset 3px 0 0 rgba(37, 175, 188, .74);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-row"] {
|
||||
border-radius: 11px;
|
||||
transition: background .16s ease, box-shadow .16s ease;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-row"]:hover,
|
||||
[data-ws-part="voice.member-row"][data-ws-state="speaking"] {
|
||||
background: linear-gradient(100deg, rgba(198, 240, 243, .38), rgba(238, 251, 252, .28));
|
||||
box-shadow: inset 0 0 0 1px rgba(92, 190, 202, .16);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member"] {
|
||||
border-color: rgba(91, 184, 198, .36);
|
||||
border-radius: 20px;
|
||||
background-color: rgba(222, 246, 249, .7);
|
||||
background-image:
|
||||
radial-gradient(ellipse at 100% 0%, rgba(102, 220, 226, .24), transparent 62%),
|
||||
linear-gradient(145deg, rgba(250, 255, 255, .72), rgba(224, 246, 249, .62) 56%, rgba(210, 241, 246, .66));
|
||||
box-shadow: 0 12px 32px rgba(31, 99, 123, .12), inset 0 1px 0 rgba(255, 255, 255, .76);
|
||||
backdrop-filter: blur(12px) saturate(1.08);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.avatar"] {
|
||||
outline: 2px solid rgba(71, 201, 212, .8);
|
||||
outline-offset: 4px;
|
||||
box-shadow: 0 0 24px rgba(71, 201, 212, .28);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.live-indicator"] {
|
||||
color: #08706f;
|
||||
border-radius: 999px;
|
||||
background: rgba(237, 255, 251, .96);
|
||||
box-shadow: 0 6px 20px rgba(42, 160, 162, .18), inset 0 0 0 1px rgba(71, 201, 212, .5);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
border-color: rgba(116, 194, 205, .42);
|
||||
border-radius: 22px;
|
||||
background-color: rgba(222, 246, 249, .8);
|
||||
background-image:
|
||||
radial-gradient(circle at 0% 100%, transparent 0 35px, rgba(71, 201, 212, .16) 36px 37px, transparent 38px 57px, rgba(71, 201, 212, .1) 58px 59px, transparent 60px),
|
||||
linear-gradient(125deg, rgba(250, 255, 255, .76), rgba(222, 246, 249, .68) 55%, rgba(205, 238, 244, .76));
|
||||
box-shadow: 0 12px 34px rgba(28, 91, 111, .16), inset 0 1px 0 rgba(255, 255, 255, .74);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat"] {
|
||||
border-color: rgba(100, 184, 198, .34);
|
||||
border-radius: 20px;
|
||||
background-color: rgba(221, 245, 249, .58);
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(21, 139, 157, .055) 1px, transparent 1.5px),
|
||||
radial-gradient(ellipse at 0% 100%, rgba(102, 220, 226, .16), transparent 42%),
|
||||
linear-gradient(145deg, rgba(249, 254, 255, .72), rgba(226, 247, 250, .48) 52%, rgba(214, 242, 247, .62));
|
||||
background-position: 0 0, left bottom, center;
|
||||
background-repeat: repeat, no-repeat, no-repeat;
|
||||
background-size: 24px 24px, auto, auto;
|
||||
backdrop-filter: blur(14px) saturate(1.05);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.tab"] {
|
||||
color: #547780;
|
||||
border-color: rgba(95, 180, 193, .24);
|
||||
background: linear-gradient(115deg, rgba(242, 252, 253, .72), rgba(217, 243, 247, .56));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.tab"]:hover,
|
||||
[data-ws-part="voice.chat.tab"][data-ws-state="active"] {
|
||||
color: #087e86;
|
||||
border-color: rgba(71, 201, 212, .48);
|
||||
background: linear-gradient(115deg, rgba(207, 242, 245, .86), rgba(232, 250, 251, .72));
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .6);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
background-color: rgba(218, 244, 248, .4);
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(21, 139, 157, .075) 1px, transparent 1.5px),
|
||||
radial-gradient(circle at 100% 50%, transparent 0 102px, rgba(71, 201, 212, .13) 103px 104px, transparent 105px 137px, rgba(71, 201, 212, .09) 138px 139px, transparent 140px),
|
||||
linear-gradient(100deg, rgba(237, 250, 252, .76), rgba(228, 247, 250, .38) 52%, rgba(205, 240, 245, .26)),
|
||||
url("assets/chat-empty-chibi.webp");
|
||||
background-position: 0 0, right center, center, center 10px;
|
||||
background-repeat: repeat, no-repeat, no-repeat, no-repeat;
|
||||
background-size: 22px 22px, 300px 250px, cover, min(340px, 46vw) auto;
|
||||
backdrop-filter: blur(8px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
background-color: rgba(218, 244, 248, .4);
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(21, 139, 157, .075) 1px, transparent 1.5px),
|
||||
radial-gradient(circle at 100% 50%, transparent 0 102px, rgba(71, 201, 212, .13) 103px 104px, transparent 105px 137px, rgba(71, 201, 212, .09) 138px 139px, transparent 140px),
|
||||
linear-gradient(100deg, rgba(237, 250, 252, .68), rgba(228, 247, 250, .34) 50%, rgba(205, 240, 245, .08)),
|
||||
url("assets/chat-empty-chibi.webp");
|
||||
background-position: 0 0, right center, center, center 8px;
|
||||
background-repeat: repeat, no-repeat, no-repeat, no-repeat;
|
||||
background-size: 22px 22px, 300px 250px, cover, min(340px, 46vw) auto;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"]::before {
|
||||
color: rgba(71, 126, 148, .9);
|
||||
border-radius: 50%;
|
||||
background-color: rgba(250, 255, 255, .66);
|
||||
background-image:
|
||||
radial-gradient(circle, #527f91 0 1.6px, transparent 1.9px),
|
||||
radial-gradient(circle, #527f91 0 1.6px, transparent 1.9px),
|
||||
radial-gradient(circle, #527f91 0 1.6px, transparent 1.9px);
|
||||
background-position: 12px 16px, 22px 12px, 32px 9px;
|
||||
background-repeat: no-repeat;
|
||||
box-shadow: 0 3px 8px rgba(48, 115, 132, .1);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"]::after {
|
||||
color: rgba(71, 126, 148, .9);
|
||||
background: rgba(250, 255, 255, .7);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"] > strong,
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"] > span {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"] strong {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"] span {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.members.empty"] {
|
||||
color: #587a82;
|
||||
border-color: rgba(78, 176, 191, .38);
|
||||
background: linear-gradient(120deg, rgba(223, 247, 249, .68), rgba(235, 250, 251, .42));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.members.empty"] strong {
|
||||
color: #315c66;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.message-bubble"] {
|
||||
color: #315360;
|
||||
background: linear-gradient(135deg, rgba(250, 255, 255, .78), rgba(216, 243, 247, .68));
|
||||
box-shadow: 0 4px 14px rgba(34, 117, 136, .08), inset 0 0 0 1px rgba(255, 255, 255, .54);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.message"][data-ws-state="mine"] [data-ws-part="voice.chat.message-bubble"] {
|
||||
color: #fff;
|
||||
background: linear-gradient(130deg, #0b9da1, #087985);
|
||||
box-shadow: 0 5px 16px rgba(8, 126, 134, .2);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity-heading"] h2,
|
||||
[data-ws-part="voice.chat.heading"] h2 {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity-heading"] span,
|
||||
[data-ws-part="voice.chat.heading"] span {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.name"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.status"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
/* These controls use the active day/night palette by default. Give them the
|
||||
same readable glass treatment as the rest of this intentionally bright skin. */
|
||||
[data-ws-part="voice.performance"] > [data-ws-part="control"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(115, 205, 218, .42);
|
||||
background: rgba(249, 253, 255, .9);
|
||||
box-shadow: 0 5px 16px rgba(29, 91, 113, .1), inset 0 1px 0 rgba(255, 255, 255, .9);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance"] > [data-ws-part="control"]:hover,
|
||||
[data-ws-part="voice.performance"] > [data-ws-part="control"][aria-expanded="true"] {
|
||||
color: #075f69;
|
||||
border-color: rgba(71, 201, 212, .72);
|
||||
background: rgba(255, 255, 255, .98);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.panel"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .4);
|
||||
background-color: rgba(223, 246, 249, .96);
|
||||
background-image:
|
||||
radial-gradient(circle at 100% 0%, rgba(71, 201, 212, .16), transparent 52%),
|
||||
linear-gradient(145deg, rgba(250, 255, 255, .96), rgba(224, 246, 249, .94));
|
||||
box-shadow: var(--skin-illusia-shadow);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.panel"] small,
|
||||
[data-ws-part="voice.performance.status"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.panel"] [data-ws-part="control"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(115, 205, 218, .36);
|
||||
background: rgba(232, 247, 248, .9);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.route"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.route"] span,
|
||||
[data-ws-part="voice.performance.metrics"] article,
|
||||
[data-ws-part="voice.performance.webrtc-stats"] [data-ws-part="control"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
border-color: rgba(115, 205, 218, .28);
|
||||
background: linear-gradient(135deg, rgba(232, 248, 250, .88), rgba(212, 241, 245, .72));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.metrics"] strong,
|
||||
[data-ws-part="voice.performance.webrtc-stats"] strong {
|
||||
color: var(--skin-illusia-teal);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.metrics"] small,
|
||||
[data-ws-part="voice.performance.metrics"] span,
|
||||
[data-ws-part="voice.performance.webrtc-stats"] small,
|
||||
[data-ws-part="voice.performance.webrtc-stats"] span {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] strong {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] span {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] button[data-ws-part="control"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: transparent;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] button[data-ws-part="control"]:hover,
|
||||
[data-ws-part="voice.audio-dock"] button[data-ws-part="control"]:focus-visible {
|
||||
color: #075f69;
|
||||
border-color: rgba(71, 201, 212, .4);
|
||||
background: rgba(221, 246, 247, .86);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock.microphone-panel"],
|
||||
[data-ws-part="voice.audio-dock.output-panel"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .38);
|
||||
background: linear-gradient(145deg, rgba(250, 255, 255, .98), rgba(221, 246, 249, .96));
|
||||
box-shadow: var(--skin-illusia-shadow);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock.microphone-panel"] strong,
|
||||
[data-ws-part="voice.audio-dock.output-panel"] strong {
|
||||
color: var(--skin-illusia-teal);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.composer"] {
|
||||
background: linear-gradient(110deg, rgba(249, 254, 255, .82), rgba(225, 247, 250, .76) 58%, rgba(214, 242, 247, .82));
|
||||
box-shadow: inset 0 0 0 1px rgba(115, 205, 218, .32), 0 5px 18px rgba(36, 130, 148, .07);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.composer"]:focus-within {
|
||||
background: linear-gradient(110deg, rgba(250, 255, 255, .9), rgba(211, 242, 246, .82));
|
||||
box-shadow: inset 0 0 0 1px rgba(71, 201, 212, .55), 0 6px 20px rgba(36, 130, 148, .11);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.composer"] input {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.composer"] input::placeholder {
|
||||
color: #718b92;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.composer"] button[data-ws-part="control"] {
|
||||
color: #fff;
|
||||
border-color: rgba(8, 126, 134, .18);
|
||||
background: linear-gradient(135deg, #0a9291, #087580);
|
||||
box-shadow: 0 5px 13px rgba(8, 126, 134, .2);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.share-actions"] button[data-ws-part="control"] {
|
||||
color: #086b72;
|
||||
border-color: rgba(71, 201, 212, .45);
|
||||
background: rgba(237, 252, 251, .96);
|
||||
box-shadow: 0 3px 10px rgba(29, 120, 130, .12);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.share-actions"] button[data-ws-part="control"]:hover,
|
||||
[data-ws-part="voice.member.share-actions"] button[data-ws-part="control"]:focus-visible {
|
||||
color: #064f59;
|
||||
border-color: rgba(8, 126, 134, .58);
|
||||
background: rgba(219, 247, 246, .98);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.share-actions"] button[data-ws-part="control"][data-ws-state="viewing"] {
|
||||
color: #fff;
|
||||
border-color: #087e86;
|
||||
background: linear-gradient(135deg, #0a9291, #087580);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.stop-share"] {
|
||||
color: #a43e48;
|
||||
border-color: rgba(255, 255, 255, .96);
|
||||
background: #fff6f5;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .42);
|
||||
background: rgba(250, 254, 255, .98);
|
||||
box-shadow: var(--skin-illusia-shadow);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings.heading"] h2 {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings.heading"] p,
|
||||
[data-ws-part="voice.screen-share-settings.fields"] label,
|
||||
[data-ws-part="voice.screen-share-settings.note"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings"] select {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .42);
|
||||
background: rgba(235, 247, 248, .94);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings"] [data-ws-part="control"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(115, 205, 218, .38);
|
||||
background: rgba(232, 247, 248, .92);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings.actions"] [data-ws-part="control"] {
|
||||
color: #fff;
|
||||
border-color: rgba(8, 126, 134, .2);
|
||||
background: linear-gradient(135deg, #0a9291, #087580);
|
||||
}
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
[data-ws-part="voice.chat.empty"] {
|
||||
background-position: 0 0, right 8px center, center, center 8px;
|
||||
background-size: 22px 22px, 260px 220px, cover, min(300px, 66vw) auto;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity"] {
|
||||
background-position: right 1% center, center, center 48%;
|
||||
background-size: 56% 100%, 100% 100%, cover;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity.artwork"] {
|
||||
background-position: right 12px bottom 6px;
|
||||
background-size: auto 118px;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"] {
|
||||
background-position: 0 0, right center, center, center 8px;
|
||||
background-size: 22px 22px, 260px 220px, cover, min(300px, 66vw) auto;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 740px) {
|
||||
[data-ws-part="voice.activity"] {
|
||||
background-image: none;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity.artwork"] {
|
||||
background-image: none;
|
||||
}
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player"] {
|
||||
border-radius: 24px;
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .58);
|
||||
background: linear-gradient(135deg, rgba(250, 255, 255, .96), rgba(220, 245, 250, .94));
|
||||
box-shadow: 0 22px 60px rgba(10, 68, 88, .3), inset 0 0 0 1px rgba(185, 246, 249, .55);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.stage"] {
|
||||
border-radius: 22px;
|
||||
background: radial-gradient(ellipse at 50% 38%, rgba(248, 255, 255, .98), rgba(220, 246, 250, .92) 58%, rgba(202, 237, 244, .9));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.video"] {
|
||||
background: #e5f4f8;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.placeholder"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.placeholder"] strong {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.exit"],
|
||||
[data-ws-part="voice.screen-player.fullscreen"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .62);
|
||||
background: rgba(250, 255, 255, .9);
|
||||
box-shadow: 0 5px 18px rgba(40, 126, 148, .18);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.viewers"],
|
||||
[data-ws-part="voice.screen-player.volume"],
|
||||
[data-ws-part="voice.screen-player.source"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .58);
|
||||
background: rgba(250, 255, 255, .88);
|
||||
box-shadow: 0 5px 18px rgba(40, 126, 148, .16);
|
||||
backdrop-filter: blur(12px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.viewer-avatar"] {
|
||||
border-color: rgba(250, 255, 255, .96);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.live"] {
|
||||
border-radius: 999px;
|
||||
color: #075e68;
|
||||
border-color: rgba(82, 195, 204, .56);
|
||||
background: rgba(239, 253, 254, .94);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .76), 0 5px 18px rgba(40, 126, 148, .16);
|
||||
text-shadow: none;
|
||||
backdrop-filter: blur(12px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.viewer-avatar"] {
|
||||
box-shadow: 0 0 0 2px rgba(255, 255, 255, .94), 0 0 0 4px rgba(71, 201, 212, .72);
|
||||
}
|
||||
|
||||
/* The demo keeps its original controls, labels, and interactions. */
|
||||
[data-ws-page="demo"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
background-color: #eaf7fc;
|
||||
background-image: url("assets/foreground-headphone.webp"), linear-gradient(rgba(239, 250, 253, .7), rgba(239, 250, 253, .82)), url("assets/bg-room-main.webp");
|
||||
background-position: left bottom, center, center;
|
||||
background-repeat: no-repeat, no-repeat, no-repeat;
|
||||
background-size: min(34vw, 430px) auto, auto, cover;
|
||||
background-attachment: fixed, scroll, scroll;
|
||||
}
|
||||
|
||||
[data-ws-part="demo.header"] {
|
||||
border-color: rgba(126, 191, 203, .3);
|
||||
background: rgba(250, 254, 255, .72);
|
||||
backdrop-filter: blur(16px);
|
||||
}
|
||||
|
||||
[data-ws-part="demo.channels"],
|
||||
[data-ws-part="demo.actions"],
|
||||
[data-ws-part="demo.main"] {
|
||||
border-color: rgba(255, 255, 255, .8);
|
||||
border-radius: 20px;
|
||||
background: rgba(249, 253, 255, .84);
|
||||
box-shadow: var(--skin-illusia-shadow);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
[data-ws-part="demo.hero"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-radius: 22px;
|
||||
background-color: #d7f3f7;
|
||||
background-image: linear-gradient(90deg, rgba(239, 251, 254, .94), rgba(227, 248, 251, .48)), url("assets/banner-character-main.webp"), url("assets/banner-mascot-blob.webp");
|
||||
background-position: center, right 46px bottom, right 16px center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: cover, auto 112%, auto 72%;
|
||||
box-shadow: 0 14px 38px rgba(31, 99, 123, .12), inset 0 0 0 1px rgba(255, 255, 255, .8);
|
||||
}
|
||||
|
||||
[data-ws-part="demo.voice-card"] {
|
||||
border-color: rgba(115, 205, 218, .35);
|
||||
border-radius: 19px;
|
||||
background: rgba(255, 255, 255, .76);
|
||||
box-shadow: 0 10px 28px rgba(31, 99, 123, .1);
|
||||
}
|
||||
|
||||
[data-ws-part="demo.avatar"] {
|
||||
outline: 2px solid rgba(71, 201, 212, .7);
|
||||
outline-offset: 4px;
|
||||
}
|
||||
|
||||
[data-ws-part="demo.chat.send"] {
|
||||
color: #fff;
|
||||
border-radius: 12px;
|
||||
background: linear-gradient(110deg, #0a9291, #087580);
|
||||
}
|
||||
|
||||
@media (max-width: 740px) {
|
||||
[data-ws-page="demo"] {
|
||||
background-size: min(62vw, 300px) auto, auto, cover;
|
||||
background-attachment: scroll, scroll, scroll;
|
||||
}
|
||||
|
||||
[data-ws-part="demo.hero"] {
|
||||
background-position: center, right center;
|
||||
background-size: cover, auto 65%;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
[data-ws-part="home"] {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
[data-ws-part="home.connect"],
|
||||
[data-ws-part="voice.member"],
|
||||
[data-ws-part="demo.voice-card"] {
|
||||
transition-duration: .01ms;
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 67 KiB After Width: | Height: | Size: 53 KiB |
|
Before Width: | Height: | Size: 115 KiB After Width: | Height: | Size: 117 KiB |
|
Before Width: | Height: | Size: 68 KiB After Width: | Height: | Size: 76 KiB |
|
Before Width: | Height: | Size: 62 KiB After Width: | Height: | Size: 69 KiB |
|
Before Width: | Height: | Size: 63 KiB After Width: | Height: | Size: 50 KiB |
|
Before Width: | Height: | Size: 106 KiB After Width: | Height: | Size: 102 KiB |
|
Before Width: | Height: | Size: 63 KiB After Width: | Height: | Size: 72 KiB |
|
Before Width: | Height: | Size: 58 KiB After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 71 KiB |
|
After Width: | Height: | Size: 65 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
Before Width: | Height: | Size: 56 KiB After Width: | Height: | Size: 46 KiB |
|
Before Width: | Height: | Size: 97 KiB After Width: | Height: | Size: 103 KiB |
|
Before Width: | Height: | Size: 60 KiB After Width: | Height: | Size: 67 KiB |
|
Before Width: | Height: | Size: 56 KiB After Width: | Height: | Size: 61 KiB |
@@ -1,16 +1,16 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.2.0",
|
||||
"version": "0.2.5",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.2.0",
|
||||
"version": "0.2.5",
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#a145338",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"werift": "0.24.4",
|
||||
@@ -63,7 +63,7 @@
|
||||
},
|
||||
"node_modules/@echosixhiya/teamspeak-client": {
|
||||
"version": "0.2.4",
|
||||
"resolved": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#a145338c7a83044dee0951c412ad91292b570215",
|
||||
"resolved": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.2.0",
|
||||
"version": "0.2.5",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-only",
|
||||
"type": "module",
|
||||
@@ -11,6 +11,7 @@
|
||||
"scripts": {
|
||||
"dev": "tsx src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "node --import tsx --test src/admin/skin-registry.test.ts src/server/visitor-count.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-pack.test.ts",
|
||||
"start": "node dist/index.js",
|
||||
"web:dev": "cd web && npx vite --host",
|
||||
"web:build": "cd web && npx vite build",
|
||||
@@ -22,7 +23,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#a145338",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"werift": "0.24.4",
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
|
||||
$width = 3200
|
||||
$height = 116
|
||||
$outputPath = Join-Path $PSScriptRoot "..\docs\examples\illusia-voice\assets\footer-wave.png"
|
||||
$bitmap = [System.Drawing.Bitmap]::new($width, $height, [System.Drawing.Imaging.PixelFormat]::Format32bppArgb)
|
||||
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
|
||||
$graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
|
||||
$graphics.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::HighQuality
|
||||
$graphics.CompositingQuality = [System.Drawing.Drawing2D.CompositingQuality]::HighQuality
|
||||
$graphics.Clear([System.Drawing.Color]::Transparent)
|
||||
|
||||
$topEdge = [System.Drawing.Drawing2D.GraphicsPath]::new()
|
||||
$topEdge.StartFigure()
|
||||
$topEdge.AddBezier(
|
||||
[System.Drawing.PointF]::new(0, 20),
|
||||
[System.Drawing.PointF]::new(240, 4),
|
||||
[System.Drawing.PointF]::new(460, 0),
|
||||
[System.Drawing.PointF]::new(700, 10)
|
||||
)
|
||||
$topEdge.AddBezier(
|
||||
[System.Drawing.PointF]::new(700, 10),
|
||||
[System.Drawing.PointF]::new(1000, 26),
|
||||
[System.Drawing.PointF]::new(1200, 36),
|
||||
[System.Drawing.PointF]::new(1600, 36)
|
||||
)
|
||||
$topEdge.AddBezier(
|
||||
[System.Drawing.PointF]::new(1600, 36),
|
||||
[System.Drawing.PointF]::new(2000, 36),
|
||||
[System.Drawing.PointF]::new(2200, 26),
|
||||
[System.Drawing.PointF]::new(2500, 10)
|
||||
)
|
||||
$topEdge.AddBezier(
|
||||
[System.Drawing.PointF]::new(2500, 10),
|
||||
[System.Drawing.PointF]::new(2740, 0),
|
||||
[System.Drawing.PointF]::new(2960, 4),
|
||||
[System.Drawing.PointF]::new(3200, 20)
|
||||
)
|
||||
|
||||
$surface = [System.Drawing.Drawing2D.GraphicsPath]::new()
|
||||
$surface.AddPath($topEdge, $false)
|
||||
$surface.AddLine(3200, 20, 3200, $height)
|
||||
$surface.AddLine(3200, $height, 0, $height)
|
||||
$surface.CloseFigure()
|
||||
|
||||
$brush = [System.Drawing.Drawing2D.LinearGradientBrush]::new(
|
||||
[System.Drawing.Rectangle]::new(0, 0, $width, $height),
|
||||
[System.Drawing.Color]::FromArgb(138, 244, 252, 254),
|
||||
[System.Drawing.Color]::FromArgb(245, 252, 255, 255),
|
||||
[System.Drawing.Drawing2D.LinearGradientMode]::Vertical
|
||||
)
|
||||
$blend = [System.Drawing.Drawing2D.ColorBlend]::new(3)
|
||||
$blend.Colors = [System.Drawing.Color[]]@(
|
||||
[System.Drawing.Color]::FromArgb(138, 244, 252, 254),
|
||||
[System.Drawing.Color]::FromArgb(194, 248, 253, 254),
|
||||
[System.Drawing.Color]::FromArgb(245, 252, 255, 255)
|
||||
)
|
||||
$blend.Positions = [single[]]@(0.0, 0.58, 1.0)
|
||||
$brush.InterpolationColors = $blend
|
||||
$pen = [System.Drawing.Pen]::new([System.Drawing.Color]::FromArgb(118, 103, 210, 221), 1.5)
|
||||
$pen.LineJoin = [System.Drawing.Drawing2D.LineJoin]::Round
|
||||
$accentBrush = [System.Drawing.SolidBrush]::new([System.Drawing.Color]::FromArgb(150, 99, 216, 225))
|
||||
$accentPath = [System.Drawing.Drawing2D.GraphicsPath]::new()
|
||||
$leftDiamond = [System.Drawing.PointF[]]@(
|
||||
[System.Drawing.PointF]::new(126, 47),
|
||||
[System.Drawing.PointF]::new(136, 58),
|
||||
[System.Drawing.PointF]::new(126, 69),
|
||||
[System.Drawing.PointF]::new(116, 58)
|
||||
)
|
||||
$rightDiamond = [System.Drawing.PointF[]]@(
|
||||
[System.Drawing.PointF]::new(3074, 47),
|
||||
[System.Drawing.PointF]::new(3084, 58),
|
||||
[System.Drawing.PointF]::new(3074, 69),
|
||||
[System.Drawing.PointF]::new(3064, 58)
|
||||
)
|
||||
$accentPen = [System.Drawing.Pen]::new([System.Drawing.Color]::FromArgb(94, 91, 211, 223), 1.2)
|
||||
$accentPen.StartCap = [System.Drawing.Drawing2D.LineCap]::Round
|
||||
$accentPen.EndCap = [System.Drawing.Drawing2D.LineCap]::Round
|
||||
|
||||
$graphics.FillPath($brush, $surface)
|
||||
$graphics.DrawPath($pen, $topEdge)
|
||||
$graphics.DrawLine($accentPen, 82, 58, 116, 58)
|
||||
$graphics.DrawLine($accentPen, 136, 58, 170, 58)
|
||||
$graphics.DrawLine($accentPen, 3030, 58, 3064, 58)
|
||||
$graphics.DrawLine($accentPen, 3084, 58, 3118, 58)
|
||||
$accentPath.AddPolygon($leftDiamond)
|
||||
$accentPath.AddPolygon($rightDiamond)
|
||||
$graphics.FillPath($accentBrush, $accentPath)
|
||||
[System.IO.Directory]::CreateDirectory((Split-Path -Parent $outputPath)) | Out-Null
|
||||
$bitmap.Save($outputPath, [System.Drawing.Imaging.ImageFormat]::Png)
|
||||
|
||||
$accentPen.Dispose()
|
||||
$accentBrush.Dispose()
|
||||
$accentPath.Dispose()
|
||||
$pen.Dispose()
|
||||
$brush.Dispose()
|
||||
$surface.Dispose()
|
||||
$topEdge.Dispose()
|
||||
$graphics.Dispose()
|
||||
$bitmap.Dispose()
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Router, type NextFunction, type Request, type Response } from "express";
|
||||
import { Router, raw as expressRaw, type NextFunction, type Request, type Response } from "express";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { AdminInputError, AdminService, type AdminSettingsInput, type RelayNodeInput } from "./admin-service.js";
|
||||
@@ -6,17 +6,22 @@ import { AdminSessionStore, isSecureRequest } from "./admin-session.js";
|
||||
import { AdminLoginRateLimiter, waitFor } from "./login-rate-limit.js";
|
||||
import { TeamSpeakProbeError } from "../server/teamspeak-probe.js";
|
||||
import type { AdminSessionSummary } from "../server/voice-bridge.js";
|
||||
import { SkinRegistry, SkinRegistryError } from "./skin-registry.js";
|
||||
|
||||
export interface AdminConnectionRecord {
|
||||
id: string;
|
||||
nickname: string;
|
||||
clientIp: string;
|
||||
target: string;
|
||||
relayName: string | null;
|
||||
relayTarget: string | null;
|
||||
startedAt: string;
|
||||
connectedAt: string | null;
|
||||
disconnectedAt: string | null;
|
||||
durationSeconds: number | null;
|
||||
status: "active" | "connecting" | "disconnected" | "failed";
|
||||
reason: string | null;
|
||||
failureDetail: string | null;
|
||||
}
|
||||
|
||||
export interface AdminRouterOptions {
|
||||
@@ -30,6 +35,7 @@ export interface AdminRouterOptions {
|
||||
terminateSession?: (id: string) => Promise<boolean>;
|
||||
version?: string;
|
||||
logFile?: string;
|
||||
skinRegistry?: SkinRegistry;
|
||||
startedAt: number;
|
||||
}
|
||||
|
||||
@@ -116,6 +122,81 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
response.json(options.service.getAdminSettings());
|
||||
});
|
||||
|
||||
router.get("/skins", async (_request, response) => {
|
||||
response.json({
|
||||
skins: await options.skinRegistry?.list() ?? [],
|
||||
defaultSkinId: await options.skinRegistry?.getDefaultSkinId() ?? "builtin.light",
|
||||
});
|
||||
});
|
||||
|
||||
router.put("/skins/default", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
|
||||
try {
|
||||
if (!options.skinRegistry) throw new SkinRegistryError("Skin storage is unavailable.", "SKIN_STORAGE_UNAVAILABLE");
|
||||
const id = typeof asRecord(request.body).id === "string" ? (asRecord(request.body).id as string).trim() : "";
|
||||
const settings = await options.skinRegistry.setDefaultSkin(id);
|
||||
response.json({ ok: true, defaultSkinId: settings.defaultSkinId });
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SkinRegistryError) {
|
||||
response.status(error.code === "SKIN_DEFAULT_INVALID" ? 400 : 409).json({ ok: false, code: error.code, message: error.message });
|
||||
return;
|
||||
}
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.put("/skins/:id/enabled", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
|
||||
try {
|
||||
const id = typeof request.params.id === "string" ? request.params.id : "";
|
||||
const body = asRecord(request.body);
|
||||
if (!options.skinRegistry || typeof body.enabled !== "boolean") throw new SkinRegistryError("A skin and boolean enabled value are required.", "SKIN_ENABLE_INVALID");
|
||||
const skin = await options.skinRegistry.setEnabled(id, body.enabled);
|
||||
options.service.database.addAudit(body.enabled ? "ADMIN_SKIN_ENABLED" : "ADMIN_SKIN_DISABLED", { id });
|
||||
response.json({ ok: true, skin, defaultSkinId: await options.skinRegistry.getDefaultSkinId() });
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SkinRegistryError) {
|
||||
const status = error.code === "SKIN_NOT_FOUND" ? 404 : error.code === "SKIN_ENABLE_INVALID" ? 400 : 409;
|
||||
response.status(status).json({ ok: false, code: error.code, message: error.message });
|
||||
return;
|
||||
}
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.put("/skins/:id", requireSameOriginBinary, requireCsrf(options.sessions), expressRaw({ type: "application/octet-stream", limit: "20mb" }), async (request, response) => {
|
||||
try {
|
||||
const id = typeof request.params.id === "string" ? request.params.id : "";
|
||||
if (!options.skinRegistry || !Buffer.isBuffer(request.body)) throw new SkinRegistryError("Skin storage is unavailable.", "SKIN_STORAGE_UNAVAILABLE");
|
||||
const skin = await options.skinRegistry.save(request.body, id);
|
||||
options.service.database.addAudit("ADMIN_SKIN_INSTALLED", { id: skin.id, version: skin.version });
|
||||
response.status(201).json({ ok: true, skin });
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SkinRegistryError) {
|
||||
const status = error.code === "SKIN_LIMIT" || error.code === "SKIN_STORAGE_LIMIT" || error.code === "SKIN_BUILTIN_PROTECTED" ? 409 : 400;
|
||||
response.status(status).json({ ok: false, code: error.code, message: error.message });
|
||||
return;
|
||||
}
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete("/skins/:id", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
|
||||
const id = typeof request.params.id === "string" ? request.params.id : "";
|
||||
try {
|
||||
if (!options.skinRegistry || !await options.skinRegistry.remove(id)) {
|
||||
response.status(404).json({ ok: false, code: "SKIN_NOT_FOUND" });
|
||||
return;
|
||||
}
|
||||
options.service.database.addAudit("ADMIN_SKIN_REMOVED", { id });
|
||||
response.json({ ok: true });
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SkinRegistryError) {
|
||||
response.status(error.code === "SKIN_BUILTIN_PROTECTED" ? 409 : 400).json({ ok: false, code: error.code, message: error.message });
|
||||
return;
|
||||
}
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/sessions", (_request, response) => {
|
||||
response.json({ sessions: options.getSessionSummaries?.() ?? [] });
|
||||
});
|
||||
@@ -323,6 +404,22 @@ function requireSameOrigin(request: Request, response: Response, next: NextFunct
|
||||
next();
|
||||
}
|
||||
|
||||
function requireSameOriginBinary(request: Request, response: Response, next: NextFunction): void {
|
||||
if (!request.is("application/octet-stream")) {
|
||||
response.status(415).json({ ok: false, code: "BINARY_REQUIRED" });
|
||||
return;
|
||||
}
|
||||
const origin = request.header("origin");
|
||||
const host = request.header("host");
|
||||
try {
|
||||
if (!origin || !host || new URL(origin).host !== host) throw new Error("origin mismatch");
|
||||
} catch {
|
||||
response.status(403).json({ ok: false, code: "ORIGIN_REJECTED" });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
async function runProbe(
|
||||
service: AdminService,
|
||||
response: Response,
|
||||
@@ -363,6 +460,9 @@ function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
|
||||
siteName: readString(body, "siteName", 80),
|
||||
welcomeText: readOptionalString(body, "welcomeText", 500),
|
||||
welcomeTextEn: typeof body.welcomeTextEn === "string" ? body.welcomeTextEn.slice(0, 500) : undefined,
|
||||
welcomeTextDe: typeof body.welcomeTextDe === "string" ? body.welcomeTextDe.slice(0, 500) : undefined,
|
||||
welcomeTextRu: typeof body.welcomeTextRu === "string" ? body.welcomeTextRu.slice(0, 500) : undefined,
|
||||
welcomeTextJa: typeof body.welcomeTextJa === "string" ? body.welcomeTextJa.slice(0, 500) : undefined,
|
||||
webRtcEnabled: body.webRtcEnabled === true,
|
||||
webRtcUdpStart: readOptionalInteger(body, "webRtcUdpStart"),
|
||||
webRtcUdpEnd: readOptionalInteger(body, "webRtcUdpEnd"),
|
||||
@@ -430,7 +530,7 @@ function readRecentLogs(logFile: string | undefined, limit: number): AdminLogEnt
|
||||
try {
|
||||
const raw = JSON.parse(line) as Record<string, unknown>;
|
||||
const context: Record<string, string | number | boolean> = {};
|
||||
for (const key of ["component", "entryId", "code", "reason", "attempt", "target", "nickname", "channel", "reconnect", "port"]) {
|
||||
for (const key of ["component", "entryId", "code", "reason", "attempt", "target", "nickname", "clientIp", "relayName", "relayTarget", "channel", "reconnect", "port"]) {
|
||||
const value = raw[key];
|
||||
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") context[key] = value;
|
||||
}
|
||||
@@ -460,13 +560,17 @@ export function readConnectionHistory(logFile: string | undefined, limit: number
|
||||
const records = new Map<string, {
|
||||
id: string;
|
||||
nickname: string;
|
||||
clientIp: string;
|
||||
target: string;
|
||||
relayName: string;
|
||||
relayTarget: string;
|
||||
startedAt: string | null;
|
||||
connectedAt: string | null;
|
||||
disconnectedAt: string | null;
|
||||
durationSeconds: number | null;
|
||||
status: AdminConnectionRecord["status"];
|
||||
reason: string | null;
|
||||
failureDetail: string | null;
|
||||
}>();
|
||||
for (const log of readStructuredLogs(logFile)) {
|
||||
const entryId = typeof log.raw.entryId === "string" ? log.raw.entryId : "";
|
||||
@@ -474,21 +578,35 @@ export function readConnectionHistory(logFile: string | undefined, limit: number
|
||||
const current = records.get(entryId) ?? {
|
||||
id: entryId,
|
||||
nickname: "",
|
||||
clientIp: "",
|
||||
target: "",
|
||||
relayName: "",
|
||||
relayTarget: "",
|
||||
startedAt: null,
|
||||
connectedAt: null,
|
||||
disconnectedAt: null,
|
||||
durationSeconds: null,
|
||||
status: "connecting" as const,
|
||||
reason: null,
|
||||
failureDetail: null,
|
||||
};
|
||||
const nickname = typeof log.raw.nickname === "string" ? log.raw.nickname : "";
|
||||
const clientIp = typeof log.raw.clientIp === "string" ? log.raw.clientIp : "";
|
||||
const target = typeof log.raw.target === "string" ? log.raw.target : "";
|
||||
const relayName = typeof log.raw.relayName === "string" ? log.raw.relayName : "";
|
||||
const relayTarget = typeof log.raw.relayTarget === "string" ? log.raw.relayTarget : "";
|
||||
if (nickname) current.nickname = nickname;
|
||||
if (clientIp) current.clientIp = clientIp;
|
||||
if (target) current.target = target;
|
||||
if (relayName) current.relayName = relayName;
|
||||
if (relayTarget) current.relayTarget = relayTarget;
|
||||
if (typeof log.raw.failureDetail === "string" && log.raw.failureDetail) current.failureDetail = log.raw.failureDetail;
|
||||
if (log.message === "WebClient connecting") {
|
||||
current.startedAt ??= log.timestamp;
|
||||
current.status = "connecting";
|
||||
} else if (log.message === "TS connect failed") {
|
||||
current.reason = typeof log.raw.code === "string" ? log.raw.code : current.reason;
|
||||
current.status = "failed";
|
||||
} else if (log.message === "Web client connected to TeamSpeak") {
|
||||
current.startedAt ??= log.timestamp;
|
||||
current.connectedAt = log.timestamp;
|
||||
@@ -508,7 +626,7 @@ export function readConnectionHistory(logFile: string | undefined, limit: number
|
||||
// rendered by the admin UI as the generic request-failed message.
|
||||
current.reason = typeof log.raw.failureCode === "string" && log.raw.failureCode
|
||||
? log.raw.failureCode
|
||||
: null;
|
||||
: current.reason;
|
||||
}
|
||||
records.set(entryId, current);
|
||||
}
|
||||
@@ -521,7 +639,10 @@ export function readConnectionHistory(logFile: string | undefined, limit: number
|
||||
return {
|
||||
id: record.id,
|
||||
nickname: record.nickname || "—",
|
||||
clientIp: record.clientIp || "—",
|
||||
target: record.target || "—",
|
||||
relayName: record.relayName || null,
|
||||
relayTarget: record.relayTarget || null,
|
||||
startedAt: record.startedAt,
|
||||
connectedAt: record.connectedAt,
|
||||
disconnectedAt: record.disconnectedAt,
|
||||
@@ -534,6 +655,7 @@ export function readConnectionHistory(logFile: string | undefined, limit: number
|
||||
// an untraceable failed connection explicitly visible as the generic
|
||||
// request-failed message instead of implying a guessed cause.
|
||||
reason: record.reason ?? (record.status === "failed" ? "CONNECTION_FAILED" : null),
|
||||
failureDetail: record.failureDetail,
|
||||
};
|
||||
})
|
||||
.sort((left, right) => Date.parse(right.disconnectedAt ?? right.startedAt) - Date.parse(left.disconnectedAt ?? left.startedAt))
|
||||
|
||||
@@ -11,6 +11,7 @@ import { pingTeamSpeakHost } from "../server/network-probe.js";
|
||||
import type { WebRtcAudioOptions } from "../server/webrtc-audio.js";
|
||||
import { DEFAULT_ACCELERATION_RELAY_PORT, type ConfiguredAccelerationRelay } from "../server/acceleration-relay.js";
|
||||
import { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_MAX, WEBRTC_UDP_PORT_MIN } from "../server/webrtc-config.js";
|
||||
import { DEFAULT_WELCOME_TEXTS, resolveWelcomeTexts } from "../site-copy.js";
|
||||
|
||||
export interface AdminSettingsInput {
|
||||
target: string;
|
||||
@@ -20,6 +21,9 @@ export interface AdminSettingsInput {
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
welcomeTextEn?: string;
|
||||
welcomeTextDe?: string;
|
||||
welcomeTextRu?: string;
|
||||
welcomeTextJa?: string;
|
||||
webRtcEnabled: boolean;
|
||||
webRtcUdpStart?: number;
|
||||
webRtcUdpEnd?: number;
|
||||
@@ -111,12 +115,22 @@ export class AdminService {
|
||||
|
||||
getPublicConfig(): Record<string, unknown> {
|
||||
const settings = this.database.getSettings();
|
||||
const welcomeTexts = resolveWelcomeTexts({
|
||||
zh: settings.welcomeText,
|
||||
en: settings.welcomeTextEn,
|
||||
de: settings.welcomeTextDe,
|
||||
ru: settings.welcomeTextRu,
|
||||
ja: settings.welcomeTextJa,
|
||||
});
|
||||
return {
|
||||
version: this.version,
|
||||
initialized: this.isInitialized(),
|
||||
siteName: settings.siteName,
|
||||
welcomeText: settings.welcomeText,
|
||||
welcomeTextEn: settings.welcomeTextEn,
|
||||
// Keep the old fields for older clients, but return the complete,
|
||||
// already-fallback-resolved map for current clients.
|
||||
welcomeText: welcomeTexts.zh,
|
||||
welcomeTextEn: welcomeTexts.en,
|
||||
welcomeTexts,
|
||||
accessMode: settings.accessMode,
|
||||
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
|
||||
};
|
||||
@@ -131,6 +145,10 @@ export class AdminService {
|
||||
siteName: settings.siteName,
|
||||
welcomeText: settings.welcomeText,
|
||||
welcomeTextEn: settings.welcomeTextEn,
|
||||
welcomeTextDe: settings.welcomeTextDe,
|
||||
welcomeTextRu: settings.welcomeTextRu,
|
||||
welcomeTextJa: settings.welcomeTextJa,
|
||||
welcomeDefaults: DEFAULT_WELCOME_TEXTS,
|
||||
lastTestAt: settings.lastTestAt,
|
||||
lastTestLatencyMs: settings.lastTestLatencyMs,
|
||||
lastTestError: settings.lastTestError,
|
||||
@@ -343,9 +361,15 @@ export class AdminService {
|
||||
const siteName = input.siteName.trim();
|
||||
const welcomeText = input.welcomeText.trim();
|
||||
const welcomeTextEn = typeof input.welcomeTextEn === "string" ? input.welcomeTextEn.trim() : current.welcomeTextEn;
|
||||
const welcomeTextDe = typeof input.welcomeTextDe === "string" ? input.welcomeTextDe.trim() : current.welcomeTextDe;
|
||||
const welcomeTextRu = typeof input.welcomeTextRu === "string" ? input.welcomeTextRu.trim() : current.welcomeTextRu;
|
||||
const welcomeTextJa = typeof input.welcomeTextJa === "string" ? input.welcomeTextJa.trim() : current.welcomeTextJa;
|
||||
if (!siteName || siteName.length > 80) throw new AdminInputError("INVALID_SITE_NAME", "Site name must contain 1 to 80 characters");
|
||||
if (welcomeText.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT", "Welcome text cannot exceed 500 characters");
|
||||
if (welcomeTextEn.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT_EN", "English welcome text cannot exceed 500 characters");
|
||||
if (welcomeTextDe.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT_DE", "German welcome text cannot exceed 500 characters");
|
||||
if (welcomeTextRu.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT_RU", "Russian welcome text cannot exceed 500 characters");
|
||||
if (welcomeTextJa.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT_JA", "Japanese welcome text cannot exceed 500 characters");
|
||||
if (input.accessMode !== "fixed" && input.accessMode !== "open") {
|
||||
throw new AdminInputError("INVALID_ACCESS_MODE", "Access mode is invalid");
|
||||
}
|
||||
@@ -424,6 +448,9 @@ export class AdminService {
|
||||
siteName,
|
||||
welcomeText,
|
||||
welcomeTextEn,
|
||||
welcomeTextDe,
|
||||
welcomeTextRu,
|
||||
welcomeTextJa,
|
||||
accessMode: input.accessMode,
|
||||
tsHost: target.host,
|
||||
tsPort: target.port,
|
||||
@@ -538,6 +565,9 @@ export class AdminService {
|
||||
siteName: settings.siteName,
|
||||
welcomeText: settings.welcomeText,
|
||||
welcomeTextEn: settings.welcomeTextEn,
|
||||
welcomeTextDe: settings.welcomeTextDe,
|
||||
welcomeTextRu: settings.welcomeTextRu,
|
||||
welcomeTextJa: settings.welcomeTextJa,
|
||||
accessMode: settings.accessMode,
|
||||
tsHost: settings.tsHost,
|
||||
tsPort: settings.tsPort,
|
||||
@@ -563,6 +593,9 @@ export class AdminService {
|
||||
siteName: current.siteName,
|
||||
welcomeText: current.welcomeText,
|
||||
welcomeTextEn: current.welcomeTextEn,
|
||||
welcomeTextDe: current.welcomeTextDe,
|
||||
welcomeTextRu: current.welcomeTextRu,
|
||||
welcomeTextJa: current.welcomeTextJa,
|
||||
accessMode: current.accessMode,
|
||||
tsHost: legacy.tsHost,
|
||||
tsPort: legacy.tsPort,
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { SkinRegistry, SkinRegistryError } from "./skin-registry.js";
|
||||
|
||||
const manifest = {
|
||||
schemaVersion: 1,
|
||||
id: "sample-skin",
|
||||
name: "Sample skin",
|
||||
version: "1.0.0",
|
||||
author: "WebSpeak test",
|
||||
license: "MIT",
|
||||
minAppVersion: "0.2.4",
|
||||
entry: "skin.css",
|
||||
content: "content.json",
|
||||
preview: "assets/preview.png",
|
||||
};
|
||||
|
||||
test("skin registry validates, lists, replaces, serves, and removes packages", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-registry-"));
|
||||
context.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const registry = new SkinRegistry(directory);
|
||||
|
||||
assert.equal(await registry.readArchive("sample-skin"), null);
|
||||
const firstArchive = createZip([
|
||||
["manifest.json", Buffer.from(JSON.stringify(manifest))],
|
||||
["skin.css", Buffer.from(".voice-card { background: url(assets/background.png); }")],
|
||||
["content.json", Buffer.from(JSON.stringify({ defaultLocale: "en", locales: { en: { home: { title: "Hello" } } } }))],
|
||||
["assets/background.png", Buffer.from([1, 2, 3, 4])],
|
||||
["assets/preview.png", Buffer.from([5, 6, 7, 8])],
|
||||
]);
|
||||
const first = await registry.save(firstArchive, "sample-skin");
|
||||
assert.equal(first.id, "sample-skin");
|
||||
assert.equal(first.previewUrl, "/api/skins/sample-skin/preview");
|
||||
assert.equal((await registry.list()).length, 1);
|
||||
assert.deepEqual(await registry.readArchive("sample-skin"), firstArchive);
|
||||
assert.deepEqual((await registry.readPreview("sample-skin"))?.bytes, Buffer.from([5, 6, 7, 8]));
|
||||
await registry.setEnabled("sample-skin", false);
|
||||
assert.equal(await registry.readArchive("sample-skin"), null);
|
||||
assert.equal(await registry.readPreview("sample-skin"), null);
|
||||
await registry.setEnabled("sample-skin", true);
|
||||
|
||||
const replacement = { ...manifest, version: "2.0.0", content: undefined, preview: undefined };
|
||||
const secondArchive = createZip([
|
||||
["manifest.json", Buffer.from(JSON.stringify(replacement))],
|
||||
["skin.css", Buffer.from(".voice-card { border-radius: 0; }")],
|
||||
]);
|
||||
const second = await registry.save(secondArchive, "sample-skin");
|
||||
assert.equal(second.version, "2.0.0");
|
||||
assert.equal(second.installedAt, first.installedAt);
|
||||
assert.equal(await registry.readPreview("sample-skin"), null);
|
||||
assert.deepEqual(await registry.readArchive("sample-skin"), secondArchive);
|
||||
|
||||
assert.equal(await registry.remove("sample-skin"), true);
|
||||
assert.deepEqual(await registry.list(), []);
|
||||
assert.equal(await registry.readArchive("sample-skin"), null);
|
||||
assert.equal(await registry.remove("sample-skin"), false);
|
||||
});
|
||||
|
||||
test("custom skins can be enabled, disabled, and selected as the instance default", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-settings-"));
|
||||
context.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const registry = new SkinRegistry(directory);
|
||||
const archive = createZip([
|
||||
["manifest.json", Buffer.from(JSON.stringify({ ...manifest, content: undefined, preview: undefined }))],
|
||||
["skin.css", Buffer.from("[data-ws-part=\"demo.voice-card\"] { color: teal; }")],
|
||||
]);
|
||||
|
||||
const skin = await registry.save(archive, "sample-skin");
|
||||
assert.equal(skin.enabled, true);
|
||||
assert.equal(await registry.getDefaultSkinId(), "builtin.light");
|
||||
await registry.setDefaultSkin("sample-skin");
|
||||
assert.equal(await registry.getDefaultSkinId(), "sample-skin");
|
||||
|
||||
const disabled = await registry.setEnabled("sample-skin", false);
|
||||
assert.equal(disabled.enabled, false);
|
||||
assert.equal(await registry.readArchive("sample-skin"), null);
|
||||
assert.equal(await registry.getDefaultSkinId(), "builtin.light");
|
||||
await assert.rejects(registry.setDefaultSkin("sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_DEFAULT_INVALID");
|
||||
|
||||
await registry.setEnabled("sample-skin", true);
|
||||
assert.deepEqual(await registry.readArchive("sample-skin"), archive);
|
||||
await registry.setDefaultSkin("sample-skin");
|
||||
assert.equal(await registry.remove("sample-skin"), true);
|
||||
assert.equal(await registry.getDefaultSkinId(), "builtin.light");
|
||||
});
|
||||
|
||||
test("skin registry rejects path traversal and mismatched local ZIP headers", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-invalid-"));
|
||||
context.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const registry = new SkinRegistry(directory);
|
||||
const goodFiles: Array<[string, Buffer]> = [
|
||||
["manifest.json", Buffer.from(JSON.stringify({ ...manifest, content: undefined, preview: undefined }))],
|
||||
["skin.css", Buffer.from(".voice-card { color: teal; }")],
|
||||
];
|
||||
|
||||
await assert.rejects(registry.save(createZip([["../escape.png", Buffer.from([1])], ...goodFiles]), "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_PATH_INVALID");
|
||||
const mismatched = createZip(goodFiles);
|
||||
mismatched[30] ^= 1;
|
||||
await assert.rejects(registry.save(mismatched, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_ZIP_INVALID");
|
||||
|
||||
await writeFile(path.join(directory, "orphan.wskin"), createZip(goodFiles));
|
||||
assert.equal(await registry.readArchive("orphan"), null);
|
||||
assert.deepEqual(await registry.list(), []);
|
||||
});
|
||||
|
||||
test("the three bundled skins cannot be replaced or removed through the registry", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-builtins-"));
|
||||
context.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const registry = new SkinRegistry(directory);
|
||||
for (const id of ["builtin.light", "builtin.dark", "community.illusia-voice"]) {
|
||||
await assert.rejects(registry.save(Buffer.alloc(22), id), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_BUILTIN_PROTECTED");
|
||||
await assert.rejects(registry.remove(id), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_BUILTIN_PROTECTED");
|
||||
await assert.rejects(registry.setEnabled(id, false), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_BUILTIN_PROTECTED");
|
||||
}
|
||||
});
|
||||
|
||||
function createZip(files: Array<[string, Buffer]>): Buffer {
|
||||
const localRecords: Buffer[] = [];
|
||||
const centralRecords: Buffer[] = [];
|
||||
let localOffset = 0;
|
||||
for (const [name, bytes] of files) {
|
||||
const filename = Buffer.from(name, "utf8");
|
||||
const checksum = crc32(bytes);
|
||||
const local = Buffer.alloc(30 + filename.length + bytes.length);
|
||||
local.writeUInt32LE(0x04034b50, 0);
|
||||
local.writeUInt16LE(20, 4);
|
||||
local.writeUInt16LE(0, 6);
|
||||
local.writeUInt16LE(0, 8);
|
||||
local.writeUInt32LE(checksum, 14);
|
||||
local.writeUInt32LE(bytes.length, 18);
|
||||
local.writeUInt32LE(bytes.length, 22);
|
||||
local.writeUInt16LE(filename.length, 26);
|
||||
filename.copy(local, 30);
|
||||
bytes.copy(local, 30 + filename.length);
|
||||
localRecords.push(local);
|
||||
|
||||
const central = Buffer.alloc(46 + filename.length);
|
||||
central.writeUInt32LE(0x02014b50, 0);
|
||||
central.writeUInt16LE(0x0314, 4);
|
||||
central.writeUInt16LE(20, 6);
|
||||
central.writeUInt16LE(0, 8);
|
||||
central.writeUInt16LE(0, 10);
|
||||
central.writeUInt32LE(checksum, 16);
|
||||
central.writeUInt32LE(bytes.length, 20);
|
||||
central.writeUInt32LE(bytes.length, 24);
|
||||
central.writeUInt16LE(filename.length, 28);
|
||||
central.writeUInt32LE(0x81a40000, 38);
|
||||
central.writeUInt32LE(localOffset, 42);
|
||||
filename.copy(central, 46);
|
||||
centralRecords.push(central);
|
||||
localOffset += local.length;
|
||||
}
|
||||
const centralDirectory = Buffer.concat(centralRecords);
|
||||
const end = Buffer.alloc(22);
|
||||
end.writeUInt32LE(0x06054b50, 0);
|
||||
end.writeUInt16LE(files.length, 8);
|
||||
end.writeUInt16LE(files.length, 10);
|
||||
end.writeUInt32LE(centralDirectory.length, 12);
|
||||
end.writeUInt32LE(localOffset, 16);
|
||||
return Buffer.concat([...localRecords, centralDirectory, end]);
|
||||
}
|
||||
|
||||
function crc32(bytes: Buffer): number {
|
||||
let crc = 0xffffffff;
|
||||
for (const byte of bytes) {
|
||||
crc ^= byte;
|
||||
for (let bit = 0; bit < 8; bit += 1) crc = crc & 1 ? (crc >>> 1) ^ 0xedb88320 : crc >>> 1;
|
||||
}
|
||||
return (crc ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
@@ -0,0 +1,464 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { inflateRawSync } from "node:zlib";
|
||||
|
||||
const MAX_ARCHIVE_BYTES = 20 * 1024 * 1024;
|
||||
const MAX_EXPANDED_BYTES = 50 * 1024 * 1024;
|
||||
const MAX_FILE_COUNT = 128;
|
||||
const MAX_CSS_BYTES = 512 * 1024;
|
||||
const MAX_CONTENT_BYTES = 256 * 1024;
|
||||
const MAX_IMAGE_BYTES = 16 * 1024 * 1024;
|
||||
const MAX_FONT_BYTES = 4 * 1024 * 1024;
|
||||
const MAX_SKINS = 50;
|
||||
const MAX_TOTAL_ARCHIVES = 200 * 1024 * 1024;
|
||||
export const BUILTIN_SKIN_IDS = ["builtin.light", "builtin.dark", "community.illusia-voice"] as const;
|
||||
const BUILTIN_SKIN_ID_SET = new Set<string>(BUILTIN_SKIN_IDS);
|
||||
const EOCD_SIGNATURE = 0x06054b50;
|
||||
const CENTRAL_SIGNATURE = 0x02014b50;
|
||||
const LOCAL_SIGNATURE = 0x04034b50;
|
||||
|
||||
export interface SkinCatalogEntry {
|
||||
id: string;
|
||||
name: string;
|
||||
version: string;
|
||||
author: string;
|
||||
license: string;
|
||||
description?: string;
|
||||
minAppVersion: string;
|
||||
previewUrl?: string;
|
||||
previewMimeType?: string;
|
||||
installedAt: number;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export interface SkinRegistrySettings {
|
||||
defaultSkinId: string;
|
||||
}
|
||||
|
||||
interface SkinArchiveEntry {
|
||||
path: string;
|
||||
compressedSize: number;
|
||||
expandedSize: number;
|
||||
compression: number;
|
||||
crc: number;
|
||||
localOffset: number;
|
||||
flags: number;
|
||||
isDirectory: boolean;
|
||||
unixFileType: number;
|
||||
}
|
||||
|
||||
type ParsedSkinManifest = Omit<SkinCatalogEntry, "installedAt" | "previewUrl" | "previewMimeType" | "enabled"> & {
|
||||
entry: string;
|
||||
content?: string;
|
||||
preview?: string;
|
||||
};
|
||||
|
||||
export class SkinRegistryError extends Error {
|
||||
constructor(message: string, readonly code: string) {
|
||||
super(message);
|
||||
this.name = "SkinRegistryError";
|
||||
}
|
||||
}
|
||||
|
||||
export function isBuiltinSkinId(id: string): boolean {
|
||||
return BUILTIN_SKIN_ID_SET.has(id);
|
||||
}
|
||||
|
||||
export class SkinRegistry {
|
||||
constructor(private readonly directory: string) {}
|
||||
|
||||
async list(): Promise<SkinCatalogEntry[]> {
|
||||
await mkdir(this.directory, { recursive: true });
|
||||
const names = await readdir(this.directory);
|
||||
const entries: SkinCatalogEntry[] = [];
|
||||
for (const filename of names.filter((item) => item.endsWith(".json"))) {
|
||||
try {
|
||||
const value: unknown = JSON.parse(await readFile(path.join(this.directory, filename), "utf8"));
|
||||
if (!isCatalogEntry(value) || filename !== `${value.id}.json`) continue;
|
||||
const archiveInfo = await stat(path.join(this.directory, `${value.id}.wskin`)).catch(() => null);
|
||||
if (!archiveInfo?.isFile() || archiveInfo.size < 22 || archiveInfo.size > MAX_ARCHIVE_BYTES) continue;
|
||||
entries.push({ ...value, enabled: value.enabled !== false });
|
||||
} catch {
|
||||
// Ignore incomplete or stale metadata. The archive itself remains untouched.
|
||||
}
|
||||
}
|
||||
return entries.sort((left, right) => left.name.localeCompare(right.name));
|
||||
}
|
||||
|
||||
async save(bytes: Buffer, expectedId: string): Promise<SkinCatalogEntry> {
|
||||
if (isBuiltinSkinId(expectedId)) throw new SkinRegistryError("Built-in skins cannot be replaced.", "SKIN_BUILTIN_PROTECTED");
|
||||
if (!isSafeSkinId(expectedId)) throw new SkinRegistryError("Skin ID is invalid.", "SKIN_ID_INVALID");
|
||||
const parsed = validateSkinArchive(bytes, expectedId);
|
||||
await mkdir(this.directory, { recursive: true });
|
||||
const current = await this.list();
|
||||
const replacing = current.some((entry) => entry.id === expectedId);
|
||||
if (!replacing && current.length >= MAX_SKINS) throw new SkinRegistryError("The instance already has the maximum number of skins.", "SKIN_LIMIT");
|
||||
const archivePaths = await Promise.all(current.map(async (entry) => ({ id: entry.id, size: (await stat(path.join(this.directory, `${entry.id}.wskin`)).catch(() => ({ size: 0 }))).size })));
|
||||
const totalBytes = archivePaths.reduce((sum, entry) => sum + (entry.id === expectedId ? 0 : entry.size), bytes.byteLength);
|
||||
if (totalBytes > MAX_TOTAL_ARCHIVES) throw new SkinRegistryError("The total skin storage limit is 200 MiB.", "SKIN_STORAGE_LIMIT");
|
||||
|
||||
const previous = current.find((entry) => entry.id === expectedId);
|
||||
const installedAt = previous?.installedAt ?? Date.now();
|
||||
const catalog: SkinCatalogEntry = {
|
||||
...parsed.manifest,
|
||||
installedAt,
|
||||
enabled: previous?.enabled ?? true,
|
||||
...(parsed.previewMime ? { previewUrl: `/api/skins/${expectedId}/preview`, previewMimeType: parsed.previewMime } : {}),
|
||||
};
|
||||
const nonce = randomBytes(6).toString("hex");
|
||||
const archiveTemp = path.join(this.directory, `.${expectedId}.${nonce}.tmp`);
|
||||
const catalogTemp = path.join(this.directory, `.${expectedId}.${nonce}.json.tmp`);
|
||||
const previewTemp = path.join(this.directory, `.${expectedId}.${nonce}.preview.tmp`);
|
||||
try {
|
||||
await writeFile(archiveTemp, bytes, { flag: "wx", mode: 0o600 });
|
||||
await writeFile(catalogTemp, JSON.stringify(catalog), { flag: "wx", mode: 0o600 });
|
||||
if (parsed.previewBytes) await writeFile(previewTemp, parsed.previewBytes, { flag: "wx", mode: 0o600 });
|
||||
await rename(archiveTemp, path.join(this.directory, `${expectedId}.wskin`));
|
||||
await rename(catalogTemp, path.join(this.directory, `${expectedId}.json`));
|
||||
const previewPath = path.join(this.directory, `${expectedId}.preview`);
|
||||
if (parsed.previewBytes) await rename(previewTemp, previewPath);
|
||||
else await unlink(previewPath).catch(() => undefined);
|
||||
} catch (error) {
|
||||
await Promise.all([archiveTemp, catalogTemp, previewTemp].map((file) => unlink(file).catch(() => undefined)));
|
||||
throw error;
|
||||
}
|
||||
return catalog;
|
||||
}
|
||||
|
||||
async readArchive(id: string): Promise<Buffer | null> {
|
||||
if (!isSafeSkinId(id)) return null;
|
||||
if (!(await this.list()).some((entry) => entry.id === id && entry.enabled)) return null;
|
||||
try { return await readFile(path.join(this.directory, `${id}.wskin`)); }
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
async readPreview(id: string): Promise<{ bytes: Buffer; mimeType: string } | null> {
|
||||
if (!isSafeSkinId(id)) return null;
|
||||
const catalog = (await this.list()).find((entry) => entry.id === id);
|
||||
if (!catalog?.enabled || !catalog.previewUrl) return null;
|
||||
const mimeType = catalog.previewMimeType || "application/octet-stream";
|
||||
try {
|
||||
const bytes = await readFile(path.join(this.directory, `${id}.preview`));
|
||||
return { bytes, mimeType };
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
async remove(id: string): Promise<boolean> {
|
||||
if (isBuiltinSkinId(id)) throw new SkinRegistryError("Built-in skins cannot be removed.", "SKIN_BUILTIN_PROTECTED");
|
||||
if (!isSafeSkinId(id)) return false;
|
||||
const wasDefault = await this.getDefaultSkinId() === id;
|
||||
const archive = path.join(this.directory, `${id}.wskin`);
|
||||
const catalog = path.join(this.directory, `${id}.json`);
|
||||
const preview = path.join(this.directory, `${id}.preview`);
|
||||
const present = await Promise.all([archive, catalog, preview].map((file) => stat(file).then(() => true).catch(() => false))).then((items) => items.some(Boolean));
|
||||
if (!present) return false;
|
||||
await Promise.all([archive, catalog, preview].map((file) => unlink(file).catch((error: unknown) => {
|
||||
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
|
||||
})));
|
||||
if (wasDefault) await this.setDefaultSkin("builtin.light");
|
||||
return true;
|
||||
}
|
||||
|
||||
async setEnabled(id: string, enabled: boolean): Promise<SkinCatalogEntry> {
|
||||
if (isBuiltinSkinId(id)) throw new SkinRegistryError("Built-in skins cannot be disabled.", "SKIN_BUILTIN_PROTECTED");
|
||||
const entry = (await this.list()).find((item) => item.id === id);
|
||||
if (!entry) throw new SkinRegistryError("The skin was not found.", "SKIN_NOT_FOUND");
|
||||
const wasDefault = await this.getDefaultSkinId() === id;
|
||||
const updated = { ...entry, enabled };
|
||||
await writeAtomicJson(path.join(this.directory, `${id}.json`), updated);
|
||||
if (!enabled && wasDefault) await this.setDefaultSkin("builtin.light");
|
||||
return updated;
|
||||
}
|
||||
|
||||
async getDefaultSkinId(): Promise<string> {
|
||||
try {
|
||||
const value: unknown = JSON.parse(await readFile(path.join(this.directory, "settings.json"), "utf8"));
|
||||
const id = value && typeof value === "object" ? (value as Record<string, unknown>).defaultSkinId : null;
|
||||
if (typeof id !== "string") return "builtin.light";
|
||||
if (isBuiltinSkinId(id)) return id;
|
||||
const entry = (await this.list()).find((skin) => skin.id === id && skin.enabled);
|
||||
return entry ? id : "builtin.light";
|
||||
} catch {
|
||||
return "builtin.light";
|
||||
}
|
||||
}
|
||||
|
||||
async setDefaultSkin(id: string): Promise<SkinRegistrySettings> {
|
||||
if (!isBuiltinSkinId(id)) {
|
||||
const entry = (await this.list()).find((skin) => skin.id === id && skin.enabled);
|
||||
if (!entry) throw new SkinRegistryError("The default skin must be enabled and installed.", "SKIN_DEFAULT_INVALID");
|
||||
}
|
||||
await mkdir(this.directory, { recursive: true });
|
||||
const settings = { defaultSkinId: id };
|
||||
await writeAtomicJson(path.join(this.directory, "settings.json"), settings);
|
||||
return settings;
|
||||
}
|
||||
}
|
||||
|
||||
async function writeAtomicJson(filename: string, value: unknown): Promise<void> {
|
||||
const temporary = `${filename}.${randomBytes(6).toString("hex")}.tmp`;
|
||||
try {
|
||||
await writeFile(temporary, JSON.stringify(value), { flag: "wx", mode: 0o600 });
|
||||
await rename(temporary, filename);
|
||||
} catch (error) {
|
||||
await unlink(temporary).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: ParsedSkinManifest; previewBytes?: Buffer; previewMime?: string } {
|
||||
const entries = inspectArchive(bytes);
|
||||
const regularEntries = entries.filter((entry) => !entry.isDirectory);
|
||||
const rootPrefix = singleRootPrefix(regularEntries.map((entry) => entry.path));
|
||||
const fileBytes = new Map<string, Buffer>();
|
||||
for (const entry of regularEntries) {
|
||||
const packagePath = rootPrefix ? entry.path.slice(rootPrefix.length) : entry.path;
|
||||
if (!isSafePackagePath(packagePath)) throw new SkinRegistryError("The package contains an unsafe path.", "SKIN_PATH_INVALID");
|
||||
const content = extractEntry(bytes, entry);
|
||||
if (content.byteLength !== entry.expandedSize || crc32(content) !== entry.crc) throw new SkinRegistryError("The package has a damaged file entry.", "SKIN_ZIP_INVALID");
|
||||
if (fileBytes.has(packagePath.toLowerCase())) throw new SkinRegistryError("The package contains duplicate paths.", "SKIN_PATH_DUPLICATE");
|
||||
fileBytes.set(packagePath, content);
|
||||
}
|
||||
const manifestBytes = fileBytes.get("manifest.json");
|
||||
if (!manifestBytes || manifestBytes.byteLength > 32 * 1024) throw new SkinRegistryError("The package needs a small root-level manifest.json.", "SKIN_MANIFEST_MISSING");
|
||||
const manifest = parseManifest(manifestBytes);
|
||||
if (expectedId && manifest.id !== expectedId) throw new SkinRegistryError("The skin ID does not match the upload target.", "SKIN_ID_MISMATCH");
|
||||
const cssBytes = fileBytes.get(manifest.entry);
|
||||
if (!cssBytes || !cssBytes.byteLength || cssBytes.byteLength > MAX_CSS_BYTES) throw new SkinRegistryError("The CSS entry is missing or exceeds 512 KiB.", "SKIN_CSS_SIZE");
|
||||
decodeUtf8(cssBytes, "The CSS entry is not valid UTF-8.");
|
||||
|
||||
let previewBytes: Buffer | undefined;
|
||||
let previewMime: string | undefined;
|
||||
for (const [packagePath, data] of fileBytes) {
|
||||
if (["manifest.json", manifest.entry, manifest.content, manifest.preview].includes(packagePath)) continue;
|
||||
const mimeType = imageMime(packagePath) ?? (packagePath.toLowerCase().endsWith(".woff2") ? "font/woff2" : null);
|
||||
if (!mimeType) throw new SkinRegistryError(`Unsupported package file: ${packagePath}`, "SKIN_FILE_UNSUPPORTED");
|
||||
if (mimeType.startsWith("image/") && data.byteLength > MAX_IMAGE_BYTES) throw new SkinRegistryError("Each image must be smaller than 16 MiB.", "SKIN_IMAGE_SIZE");
|
||||
if (mimeType.startsWith("font/") && data.byteLength > MAX_FONT_BYTES) throw new SkinRegistryError("Fonts must be smaller than 4 MiB.", "SKIN_FONT_SIZE");
|
||||
}
|
||||
if (manifest.content) {
|
||||
const content = fileBytes.get(manifest.content);
|
||||
if (!content || content.byteLength > MAX_CONTENT_BYTES) throw new SkinRegistryError("content.json is missing or exceeds 256 KiB.", "SKIN_CONTENT_SIZE");
|
||||
decodeUtf8(content, "content.json is not valid UTF-8.");
|
||||
try { JSON.parse(content.toString("utf8")); }
|
||||
catch { throw new SkinRegistryError("content.json is not valid JSON.", "SKIN_CONTENT_INVALID"); }
|
||||
}
|
||||
if (manifest.preview) {
|
||||
previewBytes = fileBytes.get(manifest.preview);
|
||||
previewMime = imageMime(manifest.preview) ?? undefined;
|
||||
if (!previewBytes || !previewMime || previewBytes.byteLength > MAX_IMAGE_BYTES) throw new SkinRegistryError("The preview must be a supported image inside the package.", "SKIN_PREVIEW_INVALID");
|
||||
}
|
||||
return { manifest, ...(previewBytes ? { previewBytes, previewMime } : {}) };
|
||||
}
|
||||
|
||||
function inspectArchive(bytes: Buffer): SkinArchiveEntry[] {
|
||||
if (bytes.byteLength < 22 || bytes.byteLength > MAX_ARCHIVE_BYTES) throw new SkinRegistryError("A skin package must be smaller than 20 MiB.", "SKIN_ARCHIVE_SIZE");
|
||||
const minOffset = Math.max(0, bytes.byteLength - 22 - 0xffff);
|
||||
let endOffset = -1;
|
||||
for (let offset = bytes.byteLength - 22; offset >= minOffset; offset -= 1) {
|
||||
if (bytes.readUInt32LE(offset) === EOCD_SIGNATURE) { endOffset = offset; break; }
|
||||
}
|
||||
if (endOffset < 0) throw new SkinRegistryError("The upload is not a valid ZIP package.", "SKIN_ZIP_INVALID");
|
||||
const disk = bytes.readUInt16LE(endOffset + 4);
|
||||
const centralDisk = bytes.readUInt16LE(endOffset + 6);
|
||||
const entriesOnDisk = bytes.readUInt16LE(endOffset + 8);
|
||||
const entryCount = bytes.readUInt16LE(endOffset + 10);
|
||||
const centralSize = bytes.readUInt32LE(endOffset + 12);
|
||||
const centralOffset = bytes.readUInt32LE(endOffset + 16);
|
||||
const commentLength = bytes.readUInt16LE(endOffset + 20);
|
||||
if (disk !== 0 || centralDisk !== 0 || entriesOnDisk !== entryCount || entryCount === 0xffff || centralSize === 0xffffffff || centralOffset === 0xffffffff || endOffset + 22 + commentLength !== bytes.byteLength) {
|
||||
throw new SkinRegistryError("Multi-disk and ZIP64 packages are not supported.", "SKIN_ZIP_FORMAT");
|
||||
}
|
||||
if (!entryCount || entryCount > MAX_FILE_COUNT || centralOffset + centralSize !== endOffset) throw new SkinRegistryError("The ZIP directory is invalid or contains too many files.", "SKIN_FILE_COUNT");
|
||||
|
||||
const decoder = new TextDecoder("utf-8", { fatal: true });
|
||||
const entries: SkinArchiveEntry[] = [];
|
||||
const seenPaths = new Set<string>();
|
||||
let offset = centralOffset;
|
||||
let totalExpanded = 0;
|
||||
for (let index = 0; index < entryCount; index += 1) {
|
||||
if (offset + 46 > endOffset || bytes.readUInt32LE(offset) !== CENTRAL_SIGNATURE) throw new SkinRegistryError("The ZIP directory entry is invalid.", "SKIN_ZIP_INVALID");
|
||||
const madeBy = bytes.readUInt16LE(offset + 4);
|
||||
const flags = bytes.readUInt16LE(offset + 8);
|
||||
const compression = bytes.readUInt16LE(offset + 10);
|
||||
const crc = bytes.readUInt32LE(offset + 16);
|
||||
const compressedSize = bytes.readUInt32LE(offset + 20);
|
||||
const expandedSize = bytes.readUInt32LE(offset + 24);
|
||||
const nameLength = bytes.readUInt16LE(offset + 28);
|
||||
const extraLength = bytes.readUInt16LE(offset + 30);
|
||||
const fileCommentLength = bytes.readUInt16LE(offset + 32);
|
||||
const diskStart = bytes.readUInt16LE(offset + 34);
|
||||
const externalAttributes = bytes.readUInt32LE(offset + 38);
|
||||
const localOffset = bytes.readUInt32LE(offset + 42);
|
||||
const recordEnd = offset + 46 + nameLength + extraLength + fileCommentLength;
|
||||
if (recordEnd > endOffset || diskStart !== 0 || flags & ~0x0800 || (compression !== 0 && compression !== 8) || compressedSize === 0xffffffff || expandedSize === 0xffffffff || localOffset === 0xffffffff) {
|
||||
throw new SkinRegistryError("Encrypted, multi-disk, and unsupported ZIP entries are not allowed.", "SKIN_ZIP_FORMAT");
|
||||
}
|
||||
let entryPath: string;
|
||||
try { entryPath = decoder.decode(bytes.subarray(offset + 46, offset + 46 + nameLength)); }
|
||||
catch { throw new SkinRegistryError("ZIP filenames must be valid UTF-8.", "SKIN_PATH_INVALID"); }
|
||||
if (!(flags & 0x800) && /[^\x00-\x7f]/.test(entryPath)) throw new SkinRegistryError("Non-ASCII ZIP filenames must be encoded as UTF-8.", "SKIN_PATH_INVALID");
|
||||
if (!isSafePackagePath(entryPath, entryPath.endsWith("/"))) throw new SkinRegistryError("The package contains an unsafe path.", "SKIN_PATH_INVALID");
|
||||
const normalizedPath = entryPath.toLowerCase();
|
||||
if (seenPaths.has(normalizedPath)) throw new SkinRegistryError("The package contains duplicate or case-conflicting paths.", "SKIN_PATH_DUPLICATE");
|
||||
seenPaths.add(normalizedPath);
|
||||
const unixFileType = madeBy >> 8 === 3 ? (externalAttributes >>> 16) & 0xf000 : 0;
|
||||
if (unixFileType !== 0 && unixFileType !== 0x8000 && unixFileType !== 0x4000) throw new SkinRegistryError("Only regular files and directories are allowed in a skin package.", "SKIN_FILE_TYPE");
|
||||
const isDirectory = entryPath.endsWith("/");
|
||||
if ((unixFileType === 0x4000) !== isDirectory && unixFileType !== 0) throw new SkinRegistryError("ZIP file type does not match its path.", "SKIN_FILE_TYPE");
|
||||
if (isDirectory && (compressedSize !== 0 || expandedSize !== 0)) throw new SkinRegistryError("ZIP directory entries cannot contain data.", "SKIN_ZIP_INVALID");
|
||||
if (compression === 0 && compressedSize !== expandedSize) throw new SkinRegistryError("A stored ZIP entry has inconsistent sizes.", "SKIN_ZIP_INVALID");
|
||||
if (!isDirectory) {
|
||||
totalExpanded += expandedSize;
|
||||
if (totalExpanded > MAX_EXPANDED_BYTES) throw new SkinRegistryError("The expanded package exceeds 50 MiB.", "SKIN_EXPANDED_SIZE");
|
||||
if (expandedSize > 1024 * 1024 && expandedSize > Math.max(compressedSize, 1) * 250) throw new SkinRegistryError("The package has an abnormal compression ratio.", "SKIN_COMPRESSION_RATIO");
|
||||
}
|
||||
entries.push({ path: entryPath, compressedSize, expandedSize, compression, crc, localOffset, flags, isDirectory, unixFileType });
|
||||
offset = recordEnd;
|
||||
}
|
||||
if (offset !== centralOffset + centralSize) throw new SkinRegistryError("The ZIP directory length is inconsistent.", "SKIN_ZIP_INVALID");
|
||||
validateLocalEntries(bytes, entries, centralOffset, decoder);
|
||||
return entries;
|
||||
}
|
||||
|
||||
function validateLocalEntries(bytes: Buffer, entries: SkinArchiveEntry[], centralOffset: number, decoder: TextDecoder): void {
|
||||
const spans: Array<{ start: number; end: number }> = [];
|
||||
for (const entry of entries) {
|
||||
const offset = entry.localOffset;
|
||||
if (offset + 30 > centralOffset || bytes.readUInt32LE(offset) !== LOCAL_SIGNATURE) throw new SkinRegistryError("A ZIP local file header is invalid.", "SKIN_ZIP_INVALID");
|
||||
const flags = bytes.readUInt16LE(offset + 6);
|
||||
const compression = bytes.readUInt16LE(offset + 8);
|
||||
const crc = bytes.readUInt32LE(offset + 14);
|
||||
const compressedSize = bytes.readUInt32LE(offset + 18);
|
||||
const expandedSize = bytes.readUInt32LE(offset + 22);
|
||||
const nameLength = bytes.readUInt16LE(offset + 26);
|
||||
const extraLength = bytes.readUInt16LE(offset + 28);
|
||||
const headerEnd = offset + 30 + nameLength + extraLength;
|
||||
if (headerEnd > centralOffset || flags !== entry.flags || compression !== entry.compression || crc !== entry.crc || compressedSize !== entry.compressedSize || expandedSize !== entry.expandedSize) {
|
||||
throw new SkinRegistryError("ZIP local and central headers disagree.", "SKIN_ZIP_INVALID");
|
||||
}
|
||||
let localPath: string;
|
||||
try { localPath = decoder.decode(bytes.subarray(offset + 30, offset + 30 + nameLength)); }
|
||||
catch { throw new SkinRegistryError("ZIP filenames must be valid UTF-8.", "SKIN_PATH_INVALID"); }
|
||||
if (localPath !== entry.path) throw new SkinRegistryError("ZIP local and central filenames disagree.", "SKIN_ZIP_INVALID");
|
||||
const end = headerEnd + entry.compressedSize;
|
||||
if (end > centralOffset) throw new SkinRegistryError("A ZIP entry overlaps the central directory.", "SKIN_ZIP_INVALID");
|
||||
spans.push({ start: offset, end });
|
||||
}
|
||||
spans.sort((left, right) => left.start - right.start);
|
||||
for (let index = 1; index < spans.length; index += 1) {
|
||||
if (spans[index].start < spans[index - 1].end) throw new SkinRegistryError("ZIP local file entries overlap.", "SKIN_ZIP_INVALID");
|
||||
}
|
||||
}
|
||||
|
||||
function extractEntry(archive: Buffer, entry: SkinArchiveEntry): Buffer {
|
||||
const offset = entry.localOffset;
|
||||
if (offset + 30 > archive.byteLength || archive.readUInt32LE(offset) !== LOCAL_SIGNATURE) throw new SkinRegistryError("A ZIP local file header is invalid.", "SKIN_ZIP_INVALID");
|
||||
const flags = archive.readUInt16LE(offset + 6);
|
||||
const compression = archive.readUInt16LE(offset + 8);
|
||||
const nameLength = archive.readUInt16LE(offset + 26);
|
||||
const extraLength = archive.readUInt16LE(offset + 28);
|
||||
if (flags !== entry.flags || compression !== entry.compression) throw new SkinRegistryError("ZIP headers disagree about file compression.", "SKIN_ZIP_INVALID");
|
||||
const dataStart = offset + 30 + nameLength + extraLength;
|
||||
const dataEnd = dataStart + entry.compressedSize;
|
||||
if (dataEnd > archive.byteLength) throw new SkinRegistryError("A ZIP entry extends past the archive.", "SKIN_ZIP_INVALID");
|
||||
const compressed = archive.subarray(dataStart, dataEnd);
|
||||
if (entry.compression === 0) return Buffer.from(compressed);
|
||||
try { return inflateRawSync(compressed, { maxOutputLength: entry.expandedSize + 1 }); }
|
||||
catch { throw new SkinRegistryError("A ZIP entry could not be safely decompressed.", "SKIN_ZIP_INVALID"); }
|
||||
}
|
||||
|
||||
function parseManifest(bytes: Buffer): ParsedSkinManifest {
|
||||
let raw: unknown;
|
||||
try { raw = JSON.parse(decodeUtf8(bytes, "manifest.json is not valid UTF-8.")); }
|
||||
catch { throw new SkinRegistryError("manifest.json must contain valid JSON.", "SKIN_MANIFEST_INVALID"); }
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new SkinRegistryError("manifest.json must be an object.", "SKIN_MANIFEST_INVALID");
|
||||
const value = raw as Record<string, unknown>;
|
||||
const read = (key: string, max: number): string => {
|
||||
const item = value[key];
|
||||
if (typeof item !== "string" || !item.trim() || item.length > max) throw new SkinRegistryError(`manifest.json has an invalid ${key} field.`, "SKIN_MANIFEST_INVALID");
|
||||
return item.trim();
|
||||
};
|
||||
const id = read("id", 80);
|
||||
if (value.schemaVersion !== 1 || !isSafeSkinId(id)) throw new SkinRegistryError("The skin schema version or ID is unsupported.", "SKIN_SCHEMA_VERSION");
|
||||
const version = read("version", 32);
|
||||
const minAppVersion = read("minAppVersion", 32);
|
||||
if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version) || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(minAppVersion)) throw new SkinRegistryError("Skin and minimum app versions must use semantic version format.", "SKIN_MANIFEST_INVALID");
|
||||
const entry = read("entry", 120);
|
||||
const readOptional = (key: string, max: number): string | undefined => value[key] == null ? undefined : read(key, max);
|
||||
const content = readOptional("content", 120);
|
||||
const preview = readOptional("preview", 120);
|
||||
for (const candidate of [entry, content, preview].filter((item): item is string => Boolean(item))) if (!isSafePackagePath(candidate)) throw new SkinRegistryError("The manifest references an unsafe path.", "SKIN_PATH_INVALID");
|
||||
if (!entry.toLowerCase().endsWith(".css") || (content && !content.toLowerCase().endsWith(".json")) || (preview && !imageMime(preview))) throw new SkinRegistryError("The entry must be CSS, content must be JSON, and preview must be a supported image.", "SKIN_MANIFEST_INVALID");
|
||||
if (new Set(["manifest.json", entry, ...(content ? [content] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase())).size !== 2 + Number(Boolean(content)) + Number(Boolean(preview))) throw new SkinRegistryError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID");
|
||||
const description = readOptional("description", 400);
|
||||
return { id, name: read("name", 80), version, author: read("author", 80), license: read("license", 80), minAppVersion, entry, ...(content ? { content } : {}), ...(preview ? { preview } : {}), ...(description ? { description } : {}) };
|
||||
}
|
||||
|
||||
function singleRootPrefix(paths: string[]): string {
|
||||
if (!paths.length) return "";
|
||||
const firstSlash = paths[0].indexOf("/");
|
||||
if (firstSlash < 1) return "";
|
||||
const prefix = paths[0].slice(0, firstSlash + 1);
|
||||
return paths.every((item) => item.startsWith(prefix)) ? prefix : "";
|
||||
}
|
||||
|
||||
function isSafePackagePath(value: string, allowDirectory = false): boolean {
|
||||
const candidate = allowDirectory ? value.slice(0, -1) : value;
|
||||
return Boolean(candidate) && !candidate.startsWith("/") && !candidate.includes("\\") && !candidate.includes("\0") && !/^[a-z]:/i.test(candidate)
|
||||
&& candidate.split("/").every((part) => Boolean(part) && part !== "." && part !== ".." && !part.includes(":"));
|
||||
}
|
||||
|
||||
function isSafeSkinId(value: unknown): value is string {
|
||||
return typeof value === "string" && value.length <= 80 && /^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(value) && !value.startsWith("builtin.");
|
||||
}
|
||||
|
||||
function imageMime(filename: string): string | null {
|
||||
switch (path.extname(filename).toLowerCase()) {
|
||||
case ".png": return "image/png";
|
||||
case ".jpg": case ".jpeg": return "image/jpeg";
|
||||
case ".webp": return "image/webp";
|
||||
case ".avif": return "image/avif";
|
||||
case ".gif": return "image/gif";
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
function decodeUtf8(bytes: Buffer, message: string): string {
|
||||
try { return new TextDecoder("utf-8", { fatal: true }).decode(bytes); }
|
||||
catch { throw new SkinRegistryError(message, "SKIN_ENCODING_INVALID"); }
|
||||
}
|
||||
|
||||
function isCatalogEntry(value: unknown): value is SkinCatalogEntry {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
||||
const item = value as Record<string, unknown>;
|
||||
const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
|
||||
if (!isSafeSkinId(item.id) || !isShortText(item.name, 80) || !isShortText(item.author, 80) || !isShortText(item.license, 80)) return false;
|
||||
if (typeof item.version !== "string" || !semver.test(item.version) || typeof item.minAppVersion !== "string" || !semver.test(item.minAppVersion)) return false;
|
||||
if (!Number.isSafeInteger(item.installedAt) || (item.installedAt as number) < 0) return false;
|
||||
if (item.enabled !== undefined && typeof item.enabled !== "boolean") return false;
|
||||
if (item.description !== undefined && (typeof item.description !== "string" || item.description.length > 400)) return false;
|
||||
const hasPreview = item.previewUrl !== undefined || item.previewMimeType !== undefined;
|
||||
return !hasPreview || (item.previewUrl === `/api/skins/${item.id}/preview` && ["image/png", "image/jpeg", "image/webp", "image/avif", "image/gif"].includes(String(item.previewMimeType)));
|
||||
}
|
||||
|
||||
function isShortText(value: unknown, limit: number): value is string {
|
||||
return typeof value === "string" && value.trim().length > 0 && value.length <= limit;
|
||||
}
|
||||
|
||||
const crcTable = (() => {
|
||||
const table = new Uint32Array(256);
|
||||
for (let index = 0; index < table.length; index += 1) {
|
||||
let value = index;
|
||||
for (let bit = 0; bit < 8; bit += 1) value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
|
||||
table[index] = value >>> 0;
|
||||
}
|
||||
return table;
|
||||
})();
|
||||
|
||||
function crc32(bytes: Buffer): number {
|
||||
let value = 0xffffffff;
|
||||
for (const byte of bytes) value = crcTable[(value ^ byte) & 0xff] ^ (value >>> 8);
|
||||
return (value ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
@@ -1,59 +1,294 @@
|
||||
export type WebSpeakErrorCode =
|
||||
| "invalid_target"
|
||||
| "invalid_nickname"
|
||||
| "nickname_in_use"
|
||||
| "host_not_found"
|
||||
| "unreachable"
|
||||
| "connection_refused"
|
||||
| "connection_reset"
|
||||
| "timeout"
|
||||
| "authentication_failed"
|
||||
| "protocol_negotiation_failed"
|
||||
| "channel_password_required"
|
||||
| "identity_security_level_too_low"
|
||||
| "identity_limit_reached"
|
||||
| "client_version_outdated"
|
||||
| "flooding"
|
||||
| "banned"
|
||||
| "kicked"
|
||||
| "server_shutting_down"
|
||||
| "server_full"
|
||||
| "invalid_parameter_size"
|
||||
| "connection_initialisation_failed"
|
||||
| "protocol_negotiation_failed"
|
||||
| "unknown";
|
||||
|
||||
export type ClientConnectionFailureCode =
|
||||
| "INVALID_TARGET"
|
||||
| "INVALID_NICKNAME"
|
||||
| "NICKNAME_IN_USE"
|
||||
| "HOST_NOT_FOUND"
|
||||
| "UNREACHABLE"
|
||||
| "CONNECTION_REFUSED"
|
||||
| "CONNECTION_RESET"
|
||||
| "TIMEOUT"
|
||||
| "SERVER_PASSWORD_REQUIRED"
|
||||
| "INVALID_SERVER_PASSWORD"
|
||||
| "CHANNEL_PASSWORD_REQUIRED"
|
||||
| "IDENTITY_SECURITY_LEVEL_TOO_LOW"
|
||||
| "IDENTITY_LIMIT_REACHED"
|
||||
| "CLIENT_VERSION_OUTDATED"
|
||||
| "FLOOD_PROTECTION"
|
||||
| "BANNED"
|
||||
| "KICKED"
|
||||
| "SERVER_SHUTTING_DOWN"
|
||||
| "SERVER_FULL"
|
||||
| "INVALID_PARAMETER"
|
||||
| "PROTOCOL_NEGOTIATION_FAILED"
|
||||
| "SERVER_REJECTED"
|
||||
| "CONNECTION_INITIALISATION_FAILED"
|
||||
| "CONNECTION_FAILED";
|
||||
|
||||
export interface TeamSpeakErrorDiagnostics {
|
||||
name?: string;
|
||||
code?: string;
|
||||
id?: string;
|
||||
serverMessage?: string;
|
||||
message?: string;
|
||||
syscall?: string;
|
||||
address?: string;
|
||||
port?: number | string;
|
||||
cause?: string;
|
||||
}
|
||||
|
||||
export class WebSpeakError extends Error {
|
||||
readonly code: WebSpeakErrorCode;
|
||||
readonly retryable: boolean;
|
||||
readonly cause?: unknown;
|
||||
readonly diagnostics: TeamSpeakErrorDiagnostics;
|
||||
|
||||
constructor(code: WebSpeakErrorCode, message: string, retryable: boolean, cause?: unknown) {
|
||||
constructor(code: WebSpeakErrorCode, message: string, retryable: boolean, cause?: unknown, diagnostics: TeamSpeakErrorDiagnostics = {}) {
|
||||
super(message);
|
||||
this.name = "WebSpeakError";
|
||||
this.code = code;
|
||||
this.retryable = retryable;
|
||||
this.cause = cause;
|
||||
this.diagnostics = diagnostics;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* TeamSpeak server error ids (SDK `public_errors.h`, shared by TS3 and TS6) that
|
||||
* the gateway can name precisely. Ids that are absent on purpose fall through to
|
||||
* the text heuristics below and finally to `unknown`, which still carries the raw
|
||||
* server detail to the browser.
|
||||
*/
|
||||
export const TEAMSPEAK_SERVER_ERROR_IDS: Readonly<Record<string, WebSpeakErrorCode>> = {
|
||||
// Client (0x02xx): nickname, capacity, identity, password, version, flooding.
|
||||
"513": "nickname_in_use",
|
||||
"515": "server_full",
|
||||
"519": "identity_security_level_too_low",
|
||||
"520": "authentication_failed",
|
||||
"521": "identity_limit_reached",
|
||||
"522": "client_version_outdated",
|
||||
"524": "flooding",
|
||||
// Parameter (0x06xx). 1541 is the generic "invalid parameter size" error;
|
||||
// connection-specific classification decides whether that means a nickname.
|
||||
"1536": "invalid_parameter_size",
|
||||
"1537": "invalid_parameter_size",
|
||||
"1538": "invalid_parameter_size",
|
||||
"1539": "invalid_parameter_size",
|
||||
"1540": "invalid_parameter_size",
|
||||
"1541": "invalid_parameter_size",
|
||||
"1542": "invalid_parameter_size",
|
||||
"1543": "protocol_negotiation_failed",
|
||||
// Connection (0x07xx). Keep only ids whose official meaning matches the
|
||||
// normalized code; unrelated SDK operation errors must not be relabelled.
|
||||
"1797": "connection_initialisation_failed",
|
||||
"1798": "host_not_found",
|
||||
"1805": "protocol_negotiation_failed",
|
||||
"1806": "protocol_negotiation_failed",
|
||||
// Server (0x04xx).
|
||||
"1026": "server_shutting_down",
|
||||
"1027": "server_full",
|
||||
"1028": "authentication_failed",
|
||||
"781": "channel_password_required",
|
||||
// Accounting (0x0bxx): the slot and virtual-server limits both surface as a
|
||||
// full server from the user's point of view.
|
||||
"2816": "server_full",
|
||||
"2817": "server_full",
|
||||
// Ban (0x0dxx).
|
||||
"3329": "banned",
|
||||
"3330": "banned",
|
||||
"3331": "flooding",
|
||||
};
|
||||
|
||||
/**
|
||||
* Default (English) message per normalized code. The browser translates these
|
||||
* strings for zh/en/de, so keep them stable and never embed a raw server id here:
|
||||
* the raw detail travels separately in `diagnostics`.
|
||||
*/
|
||||
export const WEBSPEAK_ERROR_MESSAGES: Readonly<Record<WebSpeakErrorCode, string>> = {
|
||||
invalid_target: "The TeamSpeak server address is invalid",
|
||||
invalid_nickname: "TeamSpeak refused the nickname: it must be 3-30 characters long",
|
||||
nickname_in_use: "This nickname is already used by another user on the TeamSpeak server",
|
||||
host_not_found: "TeamSpeak server hostname could not be resolved",
|
||||
unreachable: "TeamSpeak server is unreachable",
|
||||
connection_refused: "TeamSpeak server refused the connection",
|
||||
connection_reset: "TeamSpeak connection was reset",
|
||||
timeout: "TeamSpeak connection timed out",
|
||||
authentication_failed: "TeamSpeak authentication failed",
|
||||
channel_password_required: "The TeamSpeak channel requires a password",
|
||||
identity_security_level_too_low: "This TeamSpeak identity's security level is below the server requirement",
|
||||
identity_limit_reached: "This TeamSpeak identity already holds the maximum number of connections",
|
||||
client_version_outdated: "The TeamSpeak server requires a newer client version",
|
||||
flooding: "The TeamSpeak server's flood protection refused the connection",
|
||||
banned: "You are banned from this TeamSpeak server",
|
||||
kicked: "You were kicked from the TeamSpeak server",
|
||||
server_shutting_down: "The TeamSpeak server is shutting down",
|
||||
connection_initialisation_failed: "The TeamSpeak server refused the connection during initialisation",
|
||||
server_full: "The TeamSpeak server is full",
|
||||
invalid_parameter_size: "TeamSpeak refused a parameter because its length or value is out of range",
|
||||
protocol_negotiation_failed: "TeamSpeak protocol negotiation failed",
|
||||
unknown: "TeamSpeak connection failed",
|
||||
};
|
||||
|
||||
// 不可重连的错误码集合:这些错误原样重连必然失败(如被封禁、昵称被占用等),
|
||||
// 集合与消息表相邻存放便于审计重连决策;unknown 保持不可重连,防止未映射的
|
||||
// 服务器拒绝演变成无限重连循环。
|
||||
/**
|
||||
* Codes for which reconnecting unchanged cannot succeed. Keeping the list next to
|
||||
* the messages makes the retry decision auditable; `unknown` stays non-retryable
|
||||
* so an unmapped server refusal can never turn into a reconnect loop.
|
||||
*/
|
||||
const NON_RETRYABLE_CODES: ReadonlySet<WebSpeakErrorCode> = new Set<WebSpeakErrorCode>([
|
||||
"invalid_target",
|
||||
"invalid_nickname",
|
||||
"nickname_in_use",
|
||||
"authentication_failed",
|
||||
"channel_password_required",
|
||||
"identity_security_level_too_low",
|
||||
"identity_limit_reached",
|
||||
"client_version_outdated",
|
||||
"banned",
|
||||
"kicked",
|
||||
"invalid_parameter_size",
|
||||
"connection_initialisation_failed",
|
||||
"unknown",
|
||||
]);
|
||||
|
||||
function createTeamSpeakError(code: WebSpeakErrorCode, cause: unknown, diagnostics: TeamSpeakErrorDiagnostics): WebSpeakError {
|
||||
return new WebSpeakError(code, WEBSPEAK_ERROR_MESSAGES[code], !NON_RETRYABLE_CODES.has(code), cause, diagnostics);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a raw TeamSpeak server error id to a normalized code. Accepts the
|
||||
* decimal form the SDK forwards (`err.id`, `id=515`) and the hex form used by the
|
||||
* official headers (`0x0203`), because both shapes show up in logs.
|
||||
*/
|
||||
export function teamSpeakServerErrorCode(id: unknown): WebSpeakErrorCode | null {
|
||||
if (id === undefined || id === null) return null;
|
||||
const text = String(id).trim().toLocaleLowerCase();
|
||||
if (/^\d{1,6}$/.test(text)) return TEAMSPEAK_SERVER_ERROR_IDS[String(Number(text))] ?? null;
|
||||
const hexMatch = /^(?:0x)?([0-9a-f]{4,6})$/.exec(text);
|
||||
if (hexMatch) return TEAMSPEAK_SERVER_ERROR_IDS[String(parseInt(hexMatch[1], 16))] ?? null;
|
||||
return null;
|
||||
}
|
||||
|
||||
// 归一化入口:按「服务器错误ID → 关键词启发式 → 异常类名 → 传输层特征」的
|
||||
// 优先级,把 SDK/Node 抛出的原始错误收敛为带稳定错误码的 WebSpeakError。
|
||||
export function normalizeTeamSpeakError(error: unknown): WebSpeakError {
|
||||
if (error instanceof WebSpeakError) return error;
|
||||
|
||||
const candidate = error as { code?: unknown; id?: unknown; serverMessage?: unknown; message?: unknown } | null;
|
||||
const code = typeof candidate?.code === "string" ? candidate.code : "";
|
||||
const id = typeof candidate?.id === "string" || typeof candidate?.id === "number" ? String(candidate.id) : "";
|
||||
const serverMessage = typeof candidate?.serverMessage === "string" ? candidate.serverMessage : "";
|
||||
const message = typeof candidate?.message === "string" ? candidate.message : String(error);
|
||||
const text = `${code} ${id} ${serverMessage} ${message}`.toLocaleLowerCase();
|
||||
const diagnostics = collectDiagnostics(error);
|
||||
const text = diagnosticText(error).toLocaleLowerCase();
|
||||
|
||||
if (/password|authenticate|authentication|not authorized|invalid.*(credential|password)/.test(text)) {
|
||||
return new WebSpeakError("authentication_failed", "TeamSpeak authentication failed", false, error);
|
||||
// 1) A TeamSpeak server error id names the exact reason, so it outranks every
|
||||
// keyword heuristic below. The inline scan keeps the `id=515` shape
|
||||
// working even when the SDK does not attach the id as a structured field.
|
||||
const inlineId = /\bid[\s=:]*(\d{3,5})\b/.exec(text)?.[1];
|
||||
const serverErrorCode =
|
||||
teamSpeakServerErrorCode(diagnostics.id) ?? teamSpeakServerErrorCode(diagnostics.code) ?? teamSpeakServerErrorCode(inlineId);
|
||||
if (serverErrorCode) return createTeamSpeakError(serverErrorCode, error, diagnostics);
|
||||
|
||||
// 2) Explicit refusals that arrive without a stable id. Every pattern stays
|
||||
// narrow on purpose: bare words such as "password", "network", "socket",
|
||||
// "crypto" or "denied" also appear in unrelated Teamspeak messages and used
|
||||
// to steal the classification from the real cause.
|
||||
if (/nickname.{0,20}(length|size)/.test(text)) {
|
||||
return createTeamSpeakError("invalid_nickname", error, diagnostics);
|
||||
}
|
||||
if (/timeout|timed out|ack timeout|idle timeout/.test(text)) {
|
||||
return new WebSpeakError("timeout", "TeamSpeak connection timed out", true, error);
|
||||
if (/invalid[\s_-]*parameter[\s_-]*size|parameter.{0,20}(size|out of range)/.test(text)) {
|
||||
return createTeamSpeakError("invalid_parameter_size", error, diagnostics);
|
||||
}
|
||||
if (/econnrefused|enotfound|ehostunreach|enetunreach|network|socket|dns/.test(text)) {
|
||||
return new WebSpeakError("unreachable", "TeamSpeak server is unreachable", true, error);
|
||||
if (/nickname.{0,30}(in use|already (in )?use|taken|exists)|nickname_in_use/.test(text)) {
|
||||
return createTeamSpeakError("nickname_in_use", error, diagnostics);
|
||||
}
|
||||
if (/protocol|handshake|crypto|init1/.test(text)) {
|
||||
return new WebSpeakError("protocol_negotiation_failed", "TeamSpeak protocol negotiation failed", true, error);
|
||||
if (/channel.{0,30}password|password.{0,30}channel|i_channel_password/.test(text)) {
|
||||
return createTeamSpeakError("channel_password_required", error, diagnostics);
|
||||
}
|
||||
return new WebSpeakError("unknown", "TeamSpeak connection failed", false, error);
|
||||
if (/security ?level|insufficient security|could not validate identity/.test(text)) {
|
||||
return createTeamSpeakError("identity_security_level_too_low", error, diagnostics);
|
||||
}
|
||||
if (/too many clones|clone.{0,20}(limit|connected)|identity.{0,20}(limit|maximum|max).{0,20}connection/.test(text)) {
|
||||
return createTeamSpeakError("identity_limit_reached", error, diagnostics);
|
||||
}
|
||||
if (/version.{0,25}(outdated|out of date|too old|not allowed|unsupported)|outdated.{0,25}version/.test(text)) {
|
||||
return createTeamSpeakError("client_version_outdated", error, diagnostics);
|
||||
}
|
||||
if (/flood/.test(text)) {
|
||||
return createTeamSpeakError("flooding", error, diagnostics);
|
||||
}
|
||||
if (/\bban(ned)?\b|blacklist|you may retry in/.test(text)) {
|
||||
return createTeamSpeakError("banned", error, diagnostics);
|
||||
}
|
||||
if (/kicked/.test(text)) {
|
||||
return createTeamSpeakError("kicked", error, diagnostics);
|
||||
}
|
||||
if (/server.{0,20}shut ?down|server_shutdown|server is shutting down/.test(text)) {
|
||||
return createTeamSpeakError("server_shutting_down", error, diagnostics);
|
||||
}
|
||||
if (/failed[\s_-]*connection[\s_-]*initiali[sz]ation|connection initiali[sz]ation failed|failed to (initialise|initialize) the connection/.test(text)) {
|
||||
return createTeamSpeakError("connection_initialisation_failed", error, diagnostics);
|
||||
}
|
||||
if (/server.{0,25}full|server is full|maximum (number of )?(clients|slots)|slot limit|client protocol limit/.test(text)) {
|
||||
return createTeamSpeakError("server_full", error, diagnostics);
|
||||
}
|
||||
if (/invalid (server )?password|wrong (server )?password|password (is )?(invalid|incorrect|wrong)|password required|i_server_password|authentication failed|not authorized|invalid credential|login (failed|refused)/.test(text)) {
|
||||
return createTeamSpeakError("authentication_failed", error, diagnostics);
|
||||
}
|
||||
|
||||
// 3) SDK handshake/crypto error classes carry no numeric id at all, so match
|
||||
// the class name before falling back to the message text.
|
||||
const errorName = (diagnostics.name ?? "").toLocaleLowerCase();
|
||||
if (/eaxtagmismatch|fakesignaturemismatch|cryptoinit|invalididentity|license/.test(errorName)) {
|
||||
return createTeamSpeakError("protocol_negotiation_failed", error, diagnostics);
|
||||
}
|
||||
if (/alreadyconnected/.test(errorName)) {
|
||||
return createTeamSpeakError("identity_limit_reached", error, diagnostics);
|
||||
}
|
||||
if (/timeout/.test(errorName)) {
|
||||
return createTeamSpeakError("timeout", error, diagnostics);
|
||||
}
|
||||
|
||||
// 4) Transport level failures reported by Node or the TLS layer.
|
||||
if (/enotfound|eai_again|host not found|name or service not known|getaddrinfo/.test(text)) {
|
||||
return createTeamSpeakError("host_not_found", error, diagnostics);
|
||||
}
|
||||
if (/econnrefused|connection refused/.test(text)) {
|
||||
return createTeamSpeakError("connection_refused", error, diagnostics);
|
||||
}
|
||||
if (/econnreset|econnaborted|connection reset|connection aborted|socket hang up/.test(text)) {
|
||||
return createTeamSpeakError("connection_reset", error, diagnostics);
|
||||
}
|
||||
if (/timeout|timed out|ack timeout|idle timeout|etimedout/.test(text)) {
|
||||
return createTeamSpeakError("timeout", error, diagnostics);
|
||||
}
|
||||
if (/ehostunreach|enetunreach|network is unreachable|no route to host|unable to connect|transport error|unexpected eof/.test(text)) {
|
||||
return createTeamSpeakError("unreachable", error, diagnostics);
|
||||
}
|
||||
if (/handshake|protocol|eax|crypto ?(init|handshake|setup)|init1|signature|license/.test(text)) {
|
||||
return createTeamSpeakError("protocol_negotiation_failed", error, diagnostics);
|
||||
}
|
||||
return createTeamSpeakError("unknown", error, diagnostics);
|
||||
}
|
||||
|
||||
export function clientConnectionFailureCode(error: WebSpeakError, serverPassword = ""): ClientConnectionFailureCode {
|
||||
@@ -62,12 +297,120 @@ export function clientConnectionFailureCode(error: WebSpeakError, serverPassword
|
||||
}
|
||||
const mapping: Record<WebSpeakErrorCode, ClientConnectionFailureCode> = {
|
||||
invalid_target: "INVALID_TARGET",
|
||||
invalid_nickname: "INVALID_NICKNAME",
|
||||
nickname_in_use: "NICKNAME_IN_USE",
|
||||
host_not_found: "HOST_NOT_FOUND",
|
||||
unreachable: "UNREACHABLE",
|
||||
connection_refused: "CONNECTION_REFUSED",
|
||||
connection_reset: "CONNECTION_RESET",
|
||||
timeout: "TIMEOUT",
|
||||
authentication_failed: "SERVER_PASSWORD_REQUIRED",
|
||||
channel_password_required: "CHANNEL_PASSWORD_REQUIRED",
|
||||
identity_security_level_too_low: "IDENTITY_SECURITY_LEVEL_TOO_LOW",
|
||||
identity_limit_reached: "IDENTITY_LIMIT_REACHED",
|
||||
client_version_outdated: "CLIENT_VERSION_OUTDATED",
|
||||
flooding: "FLOOD_PROTECTION",
|
||||
banned: "BANNED",
|
||||
kicked: "KICKED",
|
||||
server_shutting_down: "SERVER_SHUTTING_DOWN",
|
||||
connection_initialisation_failed: "CONNECTION_INITIALISATION_FAILED",
|
||||
server_full: "SERVER_FULL",
|
||||
// During the initial connect handshake this generic TeamSpeak id is most
|
||||
// commonly emitted for an invalid nickname length/format. Operation errors
|
||||
// still retain the generic invalid_parameter_size message.
|
||||
invalid_parameter_size: "INVALID_NICKNAME",
|
||||
protocol_negotiation_failed: "PROTOCOL_NEGOTIATION_FAILED",
|
||||
server_full: "SERVER_REJECTED",
|
||||
unknown: "CONNECTION_FAILED",
|
||||
};
|
||||
return mapping[error.code];
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize the SDK `kicked` event. TeamSpeak reports a kick/ban as a
|
||||
* `clientleftview` whose reason id is 4 (kicked) or 5 (kicked with ban) and whose
|
||||
* `reasonMsg` is written by the admin, e.g. "Slow down!" or "you may retry in
|
||||
* 300 seconds". Before this helper existed the reason text was dropped and the
|
||||
* browser only showed a generic connection failure, which is exactly the
|
||||
* experience this translation layer removes. The ban/kick split prefers the
|
||||
* server text and falls back to reason id 5.
|
||||
*/
|
||||
export function normalizeTeamSpeakKickedReason(reasonMsg: unknown, reasonId?: unknown): WebSpeakError {
|
||||
const text = typeof reasonMsg === "string" ? reasonMsg.trim() : "";
|
||||
const numericReasonId = typeof reasonId === "number" ? reasonId : Number(reasonId);
|
||||
const isBan = /\bban(ned)?\b|blacklist|you may retry in/i.test(text) || numericReasonId === 5;
|
||||
const diagnostics: TeamSpeakErrorDiagnostics = { name: isBan ? "TeamSpeakBan" : "TeamSpeakKick" };
|
||||
if (text) diagnostics.serverMessage = text;
|
||||
if (Number.isFinite(numericReasonId)) diagnostics.id = String(numericReasonId);
|
||||
return createTeamSpeakError(isBan ? "banned" : "kicked", reasonMsg, diagnostics);
|
||||
}
|
||||
|
||||
/** Format useful SDK/Node details for a safe operational log field. */
|
||||
export function describeTeamSpeakError(error: WebSpeakError): string {
|
||||
const details = error.diagnostics;
|
||||
const parts = [
|
||||
details.name,
|
||||
details.code,
|
||||
details.id ? `id=${details.id}` : "",
|
||||
details.serverMessage,
|
||||
details.syscall,
|
||||
details.address ? `address=${details.address}` : "",
|
||||
details.port !== undefined ? `port=${details.port}` : "",
|
||||
details.cause,
|
||||
details.message,
|
||||
].filter(Boolean);
|
||||
return parts.length ? parts.join("; ") : error.message;
|
||||
}
|
||||
|
||||
function diagnosticText(error: unknown): string {
|
||||
const values: string[] = [];
|
||||
let current: unknown = error;
|
||||
const seen = new Set<unknown>();
|
||||
for (let depth = 0; depth < 4 && current && !seen.has(current); depth += 1) {
|
||||
seen.add(current);
|
||||
if (current instanceof Error) values.push(current.name, current.message);
|
||||
else values.push(String(current));
|
||||
if (typeof current === "object") {
|
||||
const candidate = current as { code?: unknown; id?: unknown; serverMessage?: unknown; cause?: unknown };
|
||||
for (const value of [candidate.code, candidate.id, candidate.serverMessage]) if (value !== undefined) values.push(String(value));
|
||||
current = candidate.cause;
|
||||
} else break;
|
||||
}
|
||||
return values.join(" ");
|
||||
}
|
||||
|
||||
function collectDiagnostics(error: unknown): TeamSpeakErrorDiagnostics {
|
||||
const result: TeamSpeakErrorDiagnostics = {};
|
||||
let current: unknown = error;
|
||||
const seen = new Set<unknown>();
|
||||
for (let depth = 0; depth < 4 && current && !seen.has(current); depth += 1) {
|
||||
seen.add(current);
|
||||
if (current instanceof Error) {
|
||||
result.name ??= current.name;
|
||||
result.message ??= current.message;
|
||||
const errorRecord = current as Error & Record<string, unknown>;
|
||||
if (typeof errorRecord.code === "string" || typeof errorRecord.code === "number") result.code ??= String(errorRecord.code);
|
||||
if (typeof errorRecord.id === "string" || typeof errorRecord.id === "number") result.id ??= String(errorRecord.id);
|
||||
if (typeof errorRecord.serverMessage === "string") result.serverMessage ??= errorRecord.serverMessage;
|
||||
if (typeof errorRecord.syscall === "string") result.syscall ??= errorRecord.syscall;
|
||||
if (typeof errorRecord.address === "string") result.address ??= errorRecord.address;
|
||||
if (typeof errorRecord.port === "string" || typeof errorRecord.port === "number") result.port ??= errorRecord.port;
|
||||
const cause = current.cause;
|
||||
if (cause && cause !== current) { current = cause; continue; }
|
||||
break;
|
||||
}
|
||||
if (typeof current !== "object") { result.cause ??= String(current); break; }
|
||||
const candidate = current as Record<string, unknown>;
|
||||
if (typeof candidate.name === "string") result.name ??= candidate.name;
|
||||
if (typeof candidate.code === "string" || typeof candidate.code === "number") result.code ??= String(candidate.code);
|
||||
if (typeof candidate.id === "string" || typeof candidate.id === "number") result.id ??= String(candidate.id);
|
||||
if (typeof candidate.serverMessage === "string") result.serverMessage ??= candidate.serverMessage;
|
||||
if (typeof candidate.message === "string") result.message ??= candidate.message;
|
||||
if (typeof candidate.syscall === "string") result.syscall ??= candidate.syscall;
|
||||
if (typeof candidate.address === "string") result.address ??= candidate.address;
|
||||
if (typeof candidate.port === "string" || typeof candidate.port === "number") result.port ??= candidate.port;
|
||||
const cause = candidate.cause;
|
||||
if (cause && cause !== current) { current = cause; continue; }
|
||||
break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import path from "node:path";
|
||||
import { existsSync, readFileSync, unlinkSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createAccelerationRelayServer } from "./server/acceleration-relay.js";
|
||||
import { normalizeScreenShareIceServers, type ScreenShareIceServer } from "./server/screen-share.js";
|
||||
import { SkinRegistry } from "./admin/skin-registry.js";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT_DIR = path.resolve(__dirname, "..");
|
||||
@@ -13,6 +15,7 @@ const DATA_DIR = process.env.WEBSPEAK_DATA_DIR?.trim() || path.join(ROOT_DIR, "d
|
||||
const LOG_DIR = path.join(DATA_DIR, "logs");
|
||||
const STATIC_DIR = path.join(ROOT_DIR, "web", "dist");
|
||||
const APP_VERSION = readPackageVersion();
|
||||
const SCREEN_SHARE_ICE_SERVERS = readScreenShareIceServers(process.env.WEBSPEAK_SCREEN_SHARE_ICE_SERVERS);
|
||||
|
||||
async function main() {
|
||||
if (process.env.WEBSPEAK_MODE?.trim().toLowerCase() === "relay") {
|
||||
@@ -56,6 +59,7 @@ async function main() {
|
||||
voiceBridgeOptions: {
|
||||
joinTickets,
|
||||
webRtc: () => adminService.getWebRtcAudioOptions(),
|
||||
screenShareIceServers: () => SCREEN_SHARE_ICE_SERVERS,
|
||||
// The public gateway only uses the relay configuration explicitly
|
||||
// saved in the admin console. Environment variables belong to the
|
||||
// standalone relay process and must never make the relay option appear
|
||||
@@ -64,7 +68,10 @@ async function main() {
|
||||
accelerationName: () => adminService.getAccelerationRelayName(),
|
||||
},
|
||||
adminService,
|
||||
skinRegistry: new SkinRegistry(path.join(DATA_DIR, "skins")),
|
||||
logger,
|
||||
nextVisitorNumber: () => database.nextVisitorNumber(),
|
||||
visitorCount: () => database.getVisitorCount(),
|
||||
});
|
||||
|
||||
await webServer.start();
|
||||
@@ -123,6 +130,18 @@ function parseBoolean(value: string | undefined): boolean {
|
||||
return value === "1" || value?.toLowerCase() === "true";
|
||||
}
|
||||
|
||||
function readScreenShareIceServers(value: string | undefined): ScreenShareIceServer[] {
|
||||
const raw = value?.trim();
|
||||
if (!raw) return normalizeScreenShareIceServers();
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
return normalizeScreenShareIceServers(Array.isArray(parsed) ? parsed : undefined);
|
||||
} catch {
|
||||
// A simple comma/space-separated list is convenient for STUN-only setups.
|
||||
return normalizeScreenShareIceServers(raw.split(/[\s,]+/).filter(Boolean).map((urls) => ({ urls })));
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error("Fatal error:", err);
|
||||
process.exit(1);
|
||||
|
||||
@@ -6,13 +6,16 @@ import type { AdminCredential } from "../security/admin-password.js";
|
||||
import type { TeamSpeakProtocol } from "../server/teamspeak-adapter.js";
|
||||
import { DEFAULT_WEBRTC_UDP_PORT_RANGE } from "../server/webrtc-config.js";
|
||||
|
||||
export const DATABASE_SCHEMA_VERSION = 6;
|
||||
export const DATABASE_SCHEMA_VERSION = 7;
|
||||
export type AccessMode = "fixed" | "open";
|
||||
|
||||
export interface PersistedSettings {
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
welcomeTextEn: string;
|
||||
welcomeTextDe: string;
|
||||
welcomeTextRu: string;
|
||||
welcomeTextJa: string;
|
||||
accessMode: AccessMode;
|
||||
tsHost: string;
|
||||
tsPort: number;
|
||||
@@ -37,6 +40,9 @@ export interface SettingsUpdate {
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
welcomeTextEn?: string;
|
||||
welcomeTextDe?: string;
|
||||
welcomeTextRu?: string;
|
||||
welcomeTextJa?: string;
|
||||
accessMode: AccessMode;
|
||||
tsHost: string;
|
||||
tsPort: number;
|
||||
@@ -95,6 +101,9 @@ interface SettingsRow extends Record<string, unknown> {
|
||||
site_name: string;
|
||||
welcome_text: string;
|
||||
welcome_text_en: string;
|
||||
welcome_text_de: string;
|
||||
welcome_text_ru: string;
|
||||
welcome_text_ja: string;
|
||||
access_mode: string;
|
||||
ts_host: string;
|
||||
ts_port: number;
|
||||
@@ -187,6 +196,9 @@ export class WebSpeakDatabase {
|
||||
siteName: row.site_name,
|
||||
welcomeText: row.welcome_text,
|
||||
welcomeTextEn: row.welcome_text_en,
|
||||
welcomeTextDe: row.welcome_text_de,
|
||||
welcomeTextRu: row.welcome_text_ru,
|
||||
welcomeTextJa: row.welcome_text_ja,
|
||||
accessMode: row.access_mode === "open" ? "open" : "fixed",
|
||||
tsHost: row.ts_host,
|
||||
tsPort: row.ts_port,
|
||||
@@ -365,6 +377,25 @@ export class WebSpeakDatabase {
|
||||
).run(key, value);
|
||||
}
|
||||
|
||||
nextVisitorNumber(): number {
|
||||
let nextNumber = 1;
|
||||
this.transaction(() => {
|
||||
const currentValue = this.getMeta("visitor_count");
|
||||
const current = currentValue ? Number.parseInt(currentValue, 10) : 0;
|
||||
nextNumber = Number.isSafeInteger(current) && current >= 0 && current < Number.MAX_SAFE_INTEGER
|
||||
? current + 1
|
||||
: 1;
|
||||
this.setMeta("visitor_count", String(nextNumber));
|
||||
});
|
||||
return nextNumber;
|
||||
}
|
||||
|
||||
getVisitorCount(): number {
|
||||
const value = this.getMeta("visitor_count");
|
||||
const count = value ? Number.parseInt(value, 10) : 0;
|
||||
return Number.isSafeInteger(count) && count >= 0 ? count : 0;
|
||||
}
|
||||
|
||||
addAudit(event: string, details: Record<string, unknown> = {}): void {
|
||||
this.insertAudit(event, details, new Date().toISOString());
|
||||
}
|
||||
@@ -534,13 +565,24 @@ export class WebSpeakDatabase {
|
||||
}
|
||||
this.database.exec("PRAGMA user_version = 6");
|
||||
});
|
||||
version = 6;
|
||||
}
|
||||
if (version === 6) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
ALTER TABLE settings ADD COLUMN welcome_text_de TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE settings ADD COLUMN welcome_text_ru TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE settings ADD COLUMN welcome_text_ja TEXT NOT NULL DEFAULT '';
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 7");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private writeSettings(settings: SettingsUpdate, now: string): void {
|
||||
this.database.prepare(
|
||||
`UPDATE settings SET
|
||||
site_name = ?, welcome_text = ?, welcome_text_en = ?, access_mode = ?, ts_host = ?, ts_port = ?,
|
||||
site_name = ?, welcome_text = ?, welcome_text_en = ?, welcome_text_de = ?, welcome_text_ru = ?, welcome_text_ja = ?, access_mode = ?, ts_host = ?, ts_port = ?,
|
||||
ts_password_encrypted = ?, webrtc_enabled = ?, webrtc_udp_start = ?,
|
||||
webrtc_udp_end = ?, relay_configured = ?, relay_enabled = ?, relay_name = ?,
|
||||
relay_host = ?, relay_port = ?, relay_token_encrypted = ?, updated_at = ?
|
||||
@@ -549,6 +591,9 @@ export class WebSpeakDatabase {
|
||||
settings.siteName,
|
||||
settings.welcomeText,
|
||||
settings.welcomeTextEn ?? "",
|
||||
settings.welcomeTextDe ?? "",
|
||||
settings.welcomeTextRu ?? "",
|
||||
settings.welcomeTextJa ?? "",
|
||||
settings.accessMode,
|
||||
settings.tsHost,
|
||||
settings.tsPort,
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { ClientInfo } from "@echosixhiya/teamspeak-client";
|
||||
import type { ClientInfo, DirectoryClientInfo } from "@echosixhiya/teamspeak-client";
|
||||
import type { TSDirectorySnapshot } from "./ts-client.js";
|
||||
|
||||
type DirectoryDelta =
|
||||
| { type: "clientEnter"; info: ClientInfo }
|
||||
| { type: "clientLeave"; id: number }
|
||||
| { type: "clientMoved"; id: number; channelID: bigint };
|
||||
| { type: "clientMoved"; id: number; channelID: bigint }
|
||||
| { type: "clientUpdated"; info: DirectoryClientInfo };
|
||||
|
||||
/**
|
||||
* Merges staged welcome snapshots with events received while the snapshot is
|
||||
@@ -14,7 +15,7 @@ type DirectoryDelta =
|
||||
*/
|
||||
export class DirectorySynchronizer {
|
||||
private snapshot: TSDirectorySnapshot | null = null;
|
||||
private clients = new Map<number, ClientInfo>();
|
||||
private clients = new Map<number, DirectoryClientInfo>();
|
||||
private pending: DirectoryDelta[] = [];
|
||||
|
||||
get ready(): boolean {
|
||||
@@ -43,6 +44,10 @@ export class DirectorySynchronizer {
|
||||
this.applyOrQueue({ type: "clientMoved", id, channelID });
|
||||
}
|
||||
|
||||
applyClientUpdated(info: DirectoryClientInfo): void {
|
||||
this.applyOrQueue({ type: "clientUpdated", info });
|
||||
}
|
||||
|
||||
getSnapshot(): TSDirectorySnapshot | null {
|
||||
if (!this.snapshot) return null;
|
||||
return {
|
||||
@@ -74,6 +79,11 @@ export class DirectorySynchronizer {
|
||||
this.clients.delete(delta.id);
|
||||
return;
|
||||
}
|
||||
if (delta.type === "clientUpdated") {
|
||||
const current = this.clients.get(delta.info.id);
|
||||
this.clients.set(delta.info.id, current ? { ...current, ...delta.info } : delta.info);
|
||||
return;
|
||||
}
|
||||
const current = this.clients.get(delta.id);
|
||||
if (current) this.clients.set(delta.id, { ...current, channelID: delta.channelID });
|
||||
}
|
||||
|
||||
@@ -114,9 +114,14 @@ function classifyProbeError(error: unknown): TeamSpeakPingErrorCode {
|
||||
if (/enoent|spawn\s+(?:ping(?:\.exe)?|ping)\s+.*not found|command not found/.test(lower)) return "PING_UNAVAILABLE";
|
||||
if (/enotfound|eai_again|getaddrinfo|host not found|unknown host|could not find host|name or service not known/.test(lower)) return "HOST_NOT_FOUND";
|
||||
if (/timeout|timed out|packet ack timeout|idle timeout/.test(lower)) return "TIMEOUT";
|
||||
if (/password|authentication|invalid.*credential/.test(lower)) return "INVALID_PASSWORD";
|
||||
if (/protocol|version|handshake|negotiat/.test(lower)) return "PROTOCOL_NEGOTIATION_FAILED";
|
||||
if (/reject|full|denied/.test(lower)) return "SERVER_REJECTED";
|
||||
// 关键词刻意收窄:裸的 password/version/denied 会出现在大量无关的 ping/传输
|
||||
// 输出中,误判会把用户引向错误的排查方向,只把明确的短语视为证据。
|
||||
// Keep the keywords narrow: a bare "password", "version" or "denied" appears in
|
||||
// plenty of unrelated ping/transport output, and guessing here used to send the
|
||||
// user to the wrong remedy. Only explicit phrases are treated as evidence.
|
||||
if (/invalid password|password (?:required|incorrect|wrong|rejected)|authentication failed|invalid credential/.test(lower)) return "INVALID_PASSWORD";
|
||||
if (/protocol (?:version )?(?:mismatch|not supported|error)|version (?:is )?(?:outdated|too old|not supported)|handshake (?:failed|error|timeout)|negotiation failed/.test(lower)) return "PROTOCOL_NEGOTIATION_FAILED";
|
||||
if (/server (?:is )?full|slot limit|client protocol limit|banned?|flooding|server rejected|connection (?:denied|refused) by (?:the )?server/.test(lower)) return "SERVER_REJECTED";
|
||||
return "UNREACHABLE";
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
/**
|
||||
* Screen-share signaling for browser peers and native TeamSpeak peers.
|
||||
*
|
||||
* Media never passes through this module. The gateway only authenticates the
|
||||
* connected TeamSpeak session and relays SDP/ICE messages. Browser peers use
|
||||
* the configured ICE servers only for candidate discovery/negotiation; this
|
||||
* module never handles the resulting media packets.
|
||||
*/
|
||||
|
||||
export interface ScreenShareIceServer {
|
||||
urls: string | string[];
|
||||
username?: string;
|
||||
credential?: string;
|
||||
}
|
||||
|
||||
/** TeamSpeak's public ICE services are STUN-only, so media remains peer-to-peer. */
|
||||
export const DEFAULT_SCREEN_SHARE_ICE_SERVERS: readonly ScreenShareIceServer[] = [
|
||||
{ urls: "stun:turn.teamspeak.com:3478" },
|
||||
{ urls: "stun:turn2.teamspeak.com:3478" },
|
||||
];
|
||||
|
||||
const SCREEN_SHARE_ICE_URL_PATTERN = /^(?:stun|stuns|turn|turns):/i;
|
||||
const MAX_ICE_SERVER_COUNT = 8;
|
||||
const MAX_ICE_URL_LENGTH = 512;
|
||||
const MAX_ICE_CREDENTIAL_LENGTH = 512;
|
||||
|
||||
/**
|
||||
* Keep ICE configuration server-owned and bounded before exposing it to a
|
||||
* browser. TURN is accepted only as an explicitly configured external server;
|
||||
* the WebSpeak gateway is never inserted into this list.
|
||||
*/
|
||||
export function normalizeScreenShareIceServers(value?: readonly unknown[]): ScreenShareIceServer[] {
|
||||
const source: readonly unknown[] = value ?? DEFAULT_SCREEN_SHARE_ICE_SERVERS;
|
||||
const normalized: ScreenShareIceServer[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const raw of source) {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
|
||||
const candidate = raw as Record<string, unknown>;
|
||||
const rawUrls = candidate.urls;
|
||||
const urls = (Array.isArray(rawUrls) ? rawUrls : [rawUrls])
|
||||
.filter((url): url is string => typeof url === "string" && url.trim().length > 0 && url.trim().length <= MAX_ICE_URL_LENGTH)
|
||||
.map((url) => url.trim())
|
||||
.filter((url) => SCREEN_SHARE_ICE_URL_PATTERN.test(url));
|
||||
const uniqueUrls = [...new Set(urls)];
|
||||
if (!uniqueUrls.length) continue;
|
||||
const username = typeof candidate.username === "string" && candidate.username.length <= MAX_ICE_CREDENTIAL_LENGTH
|
||||
? candidate.username
|
||||
: undefined;
|
||||
const credential = typeof candidate.credential === "string" && candidate.credential.length <= MAX_ICE_CREDENTIAL_LENGTH
|
||||
? candidate.credential
|
||||
: undefined;
|
||||
const key = JSON.stringify([uniqueUrls, username ?? ""]);
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
normalized.push({
|
||||
urls: uniqueUrls.length === 1 ? uniqueUrls[0] : uniqueUrls,
|
||||
...(username !== undefined ? { username } : {}),
|
||||
...(credential !== undefined ? { credential } : {}),
|
||||
});
|
||||
if (normalized.length >= MAX_ICE_SERVER_COUNT) break;
|
||||
}
|
||||
if (normalized.length) return normalized;
|
||||
return DEFAULT_SCREEN_SHARE_ICE_SERVERS.map((server) => ({ ...server }));
|
||||
}
|
||||
|
||||
export type ScreenSharePeerSignal =
|
||||
| {
|
||||
kind: "offer" | "answer";
|
||||
sdp: string;
|
||||
}
|
||||
| {
|
||||
kind: "iceCandidate";
|
||||
candidate: string;
|
||||
sdpMid?: string | null;
|
||||
sdpMLineIndex?: number | null;
|
||||
}
|
||||
| {
|
||||
kind: "close";
|
||||
};
|
||||
|
||||
export interface ScreenShareViewerDescription {
|
||||
peerId: string;
|
||||
nickname: string;
|
||||
avatar?: string;
|
||||
}
|
||||
|
||||
export interface ScreenShareStreamDescription {
|
||||
streamId: string;
|
||||
source: "browser" | "teamspeak";
|
||||
ownerPeerId: string;
|
||||
/** TeamSpeak client id used to match a stream to the member card. */
|
||||
ownerClientId?: number;
|
||||
ownerNickname: string;
|
||||
name: string;
|
||||
audio: boolean;
|
||||
createdAt: number;
|
||||
viewerCount: number;
|
||||
viewers: ScreenShareViewerDescription[];
|
||||
}
|
||||
|
||||
export type ScreenShareClientMessage =
|
||||
| {
|
||||
type: "screenShareList";
|
||||
}
|
||||
| {
|
||||
type: "screenShareStart";
|
||||
requestId?: string;
|
||||
name?: string;
|
||||
audio?: boolean;
|
||||
}
|
||||
| {
|
||||
type: "screenShareStop";
|
||||
requestId?: string;
|
||||
streamId: string;
|
||||
}
|
||||
| {
|
||||
type: "screenShareJoin";
|
||||
requestId?: string;
|
||||
streamId: string;
|
||||
}
|
||||
| {
|
||||
type: "screenShareLeave";
|
||||
requestId?: string;
|
||||
streamId: string;
|
||||
}
|
||||
| {
|
||||
type: "screenShareSignal";
|
||||
streamId: string;
|
||||
targetPeerId: string;
|
||||
signal: ScreenSharePeerSignal;
|
||||
};
|
||||
|
||||
export type ScreenShareMessageParseResult =
|
||||
| ScreenShareClientMessage
|
||||
| { error: { code: string; message: string } };
|
||||
|
||||
const MAX_STREAM_ID_LENGTH = 128;
|
||||
const MAX_PEER_ID_LENGTH = 128;
|
||||
const MAX_NAME_LENGTH = 120;
|
||||
const MAX_SDP_LENGTH = 256 * 1024;
|
||||
const MAX_CANDIDATE_LENGTH = 8 * 1024;
|
||||
|
||||
export function parseScreenShareMessage(raw: string): ScreenShareMessageParseResult | null {
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!isRecord(value) || typeof value.type !== "string" || !value.type.startsWith("screenShare")) return null;
|
||||
const requestId = parseRequestId(value.requestId);
|
||||
if (requestId === false) return invalid("INVALID_SCREEN_SHARE_REQUEST", "屏幕共享请求标识无效");
|
||||
|
||||
switch (value.type) {
|
||||
case "screenShareList":
|
||||
return { type: "screenShareList" };
|
||||
case "screenShareStart": {
|
||||
const name = value.name === undefined ? undefined : parseName(value.name);
|
||||
if (name === false) return invalid("INVALID_SCREEN_SHARE_NAME", "屏幕共享名称无效");
|
||||
if (value.audio !== undefined && typeof value.audio !== "boolean") return invalid("INVALID_SCREEN_SHARE_AUDIO", "共享音频选项无效");
|
||||
return {
|
||||
type: "screenShareStart",
|
||||
...(requestId ? { requestId } : {}),
|
||||
...(name ? { name } : {}),
|
||||
...(value.audio === true ? { audio: true } : {}),
|
||||
};
|
||||
}
|
||||
case "screenShareStop":
|
||||
case "screenShareJoin":
|
||||
case "screenShareLeave": {
|
||||
const streamId = parseIdentifier(value.streamId, MAX_STREAM_ID_LENGTH);
|
||||
if (!streamId) return invalid("INVALID_SCREEN_SHARE_STREAM", "屏幕共享标识无效");
|
||||
return {
|
||||
type: value.type,
|
||||
...(requestId ? { requestId } : {}),
|
||||
streamId,
|
||||
};
|
||||
}
|
||||
case "screenShareSignal": {
|
||||
const streamId = parseIdentifier(value.streamId, MAX_STREAM_ID_LENGTH);
|
||||
const targetPeerId = parseIdentifier(value.targetPeerId, MAX_PEER_ID_LENGTH);
|
||||
const signal = parseSignal(value.signal);
|
||||
if (!streamId) return invalid("INVALID_SCREEN_SHARE_STREAM", "屏幕共享标识无效");
|
||||
if (!targetPeerId) return invalid("INVALID_SCREEN_SHARE_PEER", "屏幕共享对端无效");
|
||||
if (!signal) return invalid("INVALID_SCREEN_SHARE_SIGNAL", "屏幕共享信令无效");
|
||||
return { type: "screenShareSignal", streamId, targetPeerId, signal };
|
||||
}
|
||||
default:
|
||||
return invalid("UNKNOWN_SCREEN_SHARE_MESSAGE", "不支持的屏幕共享消息");
|
||||
}
|
||||
}
|
||||
|
||||
function parseSignal(value: unknown): ScreenSharePeerSignal | null {
|
||||
if (!isRecord(value) || typeof value.kind !== "string") return null;
|
||||
if (value.kind === "close") return { kind: "close" };
|
||||
if (value.kind === "offer" || value.kind === "answer") {
|
||||
if (typeof value.sdp !== "string" || value.sdp.length === 0 || value.sdp.length > MAX_SDP_LENGTH) return null;
|
||||
return { kind: value.kind, sdp: value.sdp };
|
||||
}
|
||||
if (value.kind !== "iceCandidate" || typeof value.candidate !== "string" || value.candidate.length > MAX_CANDIDATE_LENGTH) return null;
|
||||
if (value.sdpMid !== undefined && value.sdpMid !== null && typeof value.sdpMid !== "string") return null;
|
||||
const sdpMLineIndex = value.sdpMLineIndex;
|
||||
if (sdpMLineIndex !== undefined && sdpMLineIndex !== null && (typeof sdpMLineIndex !== "number" || !Number.isInteger(sdpMLineIndex) || sdpMLineIndex < 0 || sdpMLineIndex > 255)) return null;
|
||||
return {
|
||||
kind: "iceCandidate",
|
||||
candidate: value.candidate,
|
||||
...(value.sdpMid === null || typeof value.sdpMid === "string" ? { sdpMid: value.sdpMid } : {}),
|
||||
...(sdpMLineIndex === null || typeof sdpMLineIndex === "number" ? { sdpMLineIndex } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function parseRequestId(value: unknown): string | undefined | false {
|
||||
if (value === undefined) return undefined;
|
||||
return typeof value === "string" && value.length > 0 && value.length <= 64 ? value : false;
|
||||
}
|
||||
|
||||
function parseName(value: unknown): string | false {
|
||||
if (typeof value !== "string") return false;
|
||||
const name = value.trim();
|
||||
return name.length > 0 && name.length <= MAX_NAME_LENGTH ? name : false;
|
||||
}
|
||||
|
||||
function parseIdentifier(value: unknown, maxLength: number): string | null {
|
||||
if (typeof value !== "string" || value.length === 0 || value.length > maxLength) return null;
|
||||
return value;
|
||||
}
|
||||
|
||||
function invalid(code: string, message: string): { error: { code: string; message: string } } {
|
||||
return { error: { code, message } };
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
@@ -13,6 +13,8 @@ import { resolveSafeOpenTarget } from "../security/open-target-policy.js";
|
||||
import { identityFromString } from "@echosixhiya/teamspeak-client";
|
||||
import { JoinRateLimiter } from "./join-rate-limit.js";
|
||||
import type { ConfiguredAccelerationRelay } from "./acceleration-relay.js";
|
||||
import type { SkinRegistry } from "../admin/skin-registry.js";
|
||||
import { resolveVisitorTotal } from "./visitor-count.js";
|
||||
|
||||
export interface WebServerOptions {
|
||||
port: number;
|
||||
@@ -22,7 +24,10 @@ export interface WebServerOptions {
|
||||
certDir?: string; // path to cert.pem + key.pem for HTTPS
|
||||
voiceBridgeOptions: VoiceBridgeOptions;
|
||||
adminService: AdminService;
|
||||
skinRegistry?: SkinRegistry;
|
||||
logger: Logger;
|
||||
nextVisitorNumber?: () => number;
|
||||
visitorCount?: () => number;
|
||||
}
|
||||
|
||||
export interface WebServer {
|
||||
@@ -30,6 +35,8 @@ export interface WebServer {
|
||||
stop(): Promise<void>;
|
||||
}
|
||||
|
||||
const VISITOR_NUMBER_COOKIE = "webspeak_visitor_number";
|
||||
|
||||
export function createWebServer(options: WebServerOptions): WebServer {
|
||||
const app = express();
|
||||
const logger = options.logger.child({ component: "web" });
|
||||
@@ -58,16 +65,75 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
app.get("/health", healthHandler);
|
||||
app.get("/api/health", healthHandler);
|
||||
|
||||
app.get("/api/public-config", (_request, response) => {
|
||||
app.get("/api/public-config", (request, response) => {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
const acceleration = resolveAccelerationOptions(options.voiceBridgeOptions.acceleration);
|
||||
let visitorNumber = readVisitorNumberCookie(request.header("cookie"));
|
||||
if (visitorNumber === null && options.nextVisitorNumber) {
|
||||
try {
|
||||
visitorNumber = options.nextVisitorNumber();
|
||||
response.setHeader(
|
||||
"Set-Cookie",
|
||||
`${VISITOR_NUMBER_COOKIE}=${visitorNumber}; Max-Age=31536000; Path=/; SameSite=Lax${options.certDir ? "; Secure" : ""}`,
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Visitor number could not be assigned");
|
||||
}
|
||||
}
|
||||
let visitorTotal = resolveVisitorTotal(visitorNumber, null);
|
||||
if (options.visitorCount) {
|
||||
try {
|
||||
visitorTotal = resolveVisitorTotal(visitorNumber, options.visitorCount());
|
||||
} catch (error: unknown) {
|
||||
logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Visitor total could not be read");
|
||||
}
|
||||
} else if (visitorNumber !== null) {
|
||||
visitorTotal = visitorNumber;
|
||||
}
|
||||
response.json({
|
||||
...options.adminService.getPublicConfig(),
|
||||
...(visitorNumber === null ? {} : { visitorNumber }),
|
||||
...(visitorTotal === null ? {} : { visitorTotal }),
|
||||
accelerationAvailable: acceleration.length > 0,
|
||||
accelerationRelays: acceleration.map((relay) => ({ id: relay.id, name: relay.name })),
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/skins", async (_request, response) => {
|
||||
response.setHeader("Cache-Control", "no-cache");
|
||||
response.json({
|
||||
skins: await options.skinRegistry?.list() ?? [],
|
||||
defaultSkinId: await options.skinRegistry?.getDefaultSkinId() ?? "builtin.light",
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/skins/:id/package", async (request, response) => {
|
||||
const id = typeof request.params.id === "string" ? request.params.id : "";
|
||||
const archive = await options.skinRegistry?.readArchive(id);
|
||||
if (!archive) {
|
||||
response.status(404).json({ ok: false, code: "SKIN_NOT_FOUND" });
|
||||
return;
|
||||
}
|
||||
response.setHeader("Cache-Control", "no-cache");
|
||||
response.setHeader("Content-Type", "application/octet-stream");
|
||||
response.setHeader("Content-Disposition", `attachment; filename="${id}.wskin"`);
|
||||
response.setHeader("X-Content-Type-Options", "nosniff");
|
||||
response.send(archive);
|
||||
});
|
||||
|
||||
app.get("/api/skins/:id/preview", async (request, response) => {
|
||||
const id = typeof request.params.id === "string" ? request.params.id : "";
|
||||
const preview = await options.skinRegistry?.readPreview(id);
|
||||
if (!preview) {
|
||||
response.status(404).end();
|
||||
return;
|
||||
}
|
||||
response.setHeader("Cache-Control", "public, max-age=300");
|
||||
response.setHeader("Content-Type", preview.mimeType);
|
||||
response.setHeader("X-Content-Type-Options", "nosniff");
|
||||
response.send(preview.bytes);
|
||||
});
|
||||
|
||||
app.post("/api/join-ticket", async (request, response) => {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
if (!request.is("application/json") || !isSameOrigin(request)) {
|
||||
@@ -165,6 +231,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
getCreatedSessions: () => voiceBridge.getCreatedCount(),
|
||||
getSessionSummaries: () => voiceBridge.getSessionSummaries(),
|
||||
terminateSession: (id) => voiceBridge.terminateSession(id),
|
||||
skinRegistry: options.skinRegistry,
|
||||
version: options.version,
|
||||
logFile: options.logFile,
|
||||
startedAt,
|
||||
@@ -211,6 +278,20 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readVisitorNumberCookie(header: string | undefined): number | null {
|
||||
if (!header) return null;
|
||||
for (const entry of header.split(";")) {
|
||||
const separator = entry.indexOf("=");
|
||||
if (separator < 0) continue;
|
||||
const name = entry.slice(0, separator).trim();
|
||||
if (name !== VISITOR_NUMBER_COOKIE) continue;
|
||||
const rawValue = entry.slice(separator + 1).trim();
|
||||
const number = Number.parseInt(rawValue, 10);
|
||||
return Number.isSafeInteger(number) && number > 0 ? number : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isSameOrigin(request: express.Request): boolean {
|
||||
const origin = request.header("origin");
|
||||
const host = request.header("host");
|
||||
|
||||
@@ -17,6 +17,7 @@ export type SessionTeardownReason =
|
||||
| "websocket-error"
|
||||
| "protocol-error"
|
||||
| "teamSpeak-disconnect"
|
||||
| "teamSpeak-kicked" // 会话被 TeamSpeak 服务器踢出/封禁时拆除
|
||||
| "teamSpeak-connect-failed"
|
||||
| "heartbeat-timeout"
|
||||
| "admin-terminated"
|
||||
|
||||
@@ -5,8 +5,11 @@ import { TSClient } from "./ts-client.js";
|
||||
import type { TeamSpeakProtocol } from "./teamspeak-adapter.js";
|
||||
|
||||
export type ProbeErrorCode =
|
||||
| "INVALID_NICKNAME"
|
||||
| "HOST_NOT_FOUND"
|
||||
| "UNREACHABLE"
|
||||
| "CONNECTION_REFUSED"
|
||||
| "CONNECTION_RESET"
|
||||
| "TIMEOUT"
|
||||
| "PASSWORD_REQUIRED"
|
||||
| "INVALID_PASSWORD"
|
||||
@@ -100,11 +103,31 @@ export function toProbeError(error: unknown, password = ""): TeamSpeakProbeError
|
||||
if (/enotfound|eai_again|getaddrinfo|host not found/.test(raw)) {
|
||||
return new TeamSpeakProbeError("HOST_NOT_FOUND", "TeamSpeak host was not found", error);
|
||||
}
|
||||
// 探测只回答「该地址是否可用」,因此把网关能细分的拒绝原因收敛到既有探测码,
|
||||
// 具体原因由连接/重连路径向浏览器上报。
|
||||
// The probe only answers "can this address be used at all", so the richer
|
||||
// rejection reasons the gateway can now name are bucketed into the existing
|
||||
// probe codes; the exact reason is reported by the connect/reconnect path.
|
||||
const mapping: Record<WebSpeakErrorCode, ProbeErrorCode> = {
|
||||
invalid_target: "INTERNAL_ERROR",
|
||||
invalid_nickname: "INVALID_NICKNAME",
|
||||
nickname_in_use: "INVALID_NICKNAME",
|
||||
invalid_parameter_size: "INVALID_NICKNAME",
|
||||
unreachable: "UNREACHABLE",
|
||||
host_not_found: "HOST_NOT_FOUND",
|
||||
connection_refused: "CONNECTION_REFUSED",
|
||||
connection_reset: "CONNECTION_RESET",
|
||||
timeout: "TIMEOUT",
|
||||
authentication_failed: password.trim() ? "INVALID_PASSWORD" : "PASSWORD_REQUIRED",
|
||||
channel_password_required: "PASSWORD_REQUIRED",
|
||||
identity_security_level_too_low: "SERVER_REJECTED",
|
||||
identity_limit_reached: "SERVER_REJECTED",
|
||||
client_version_outdated: "SERVER_REJECTED",
|
||||
flooding: "SERVER_REJECTED",
|
||||
banned: "SERVER_REJECTED",
|
||||
kicked: "SERVER_REJECTED",
|
||||
server_shutting_down: "SERVER_REJECTED",
|
||||
connection_initialisation_failed: "SERVER_REJECTED",
|
||||
protocol_negotiation_failed: "PROTOCOL_NEGOTIATION_FAILED",
|
||||
server_full: "SERVER_REJECTED",
|
||||
unknown: "SERVER_REJECTED",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { Writable } from "node:stream";
|
||||
import {
|
||||
Client as TS3FullClient,
|
||||
clientMove as tsClientMove,
|
||||
@@ -11,9 +12,11 @@ import {
|
||||
type VoiceData,
|
||||
type DirectoryClientInfo,
|
||||
type DirectorySnapshot,
|
||||
type RawNotification,
|
||||
type TextMessage,
|
||||
} from "@echosixhiya/teamspeak-client";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { describeTeamSpeakError, normalizeTeamSpeakError, normalizeTeamSpeakKickedReason } from "../errors.js";
|
||||
import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js";
|
||||
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { createAccelerationRelayClient, type AccelerationRelayClient, type AccelerationRelayOptions } from "./acceleration-relay.js";
|
||||
@@ -34,8 +37,20 @@ export interface TSVoiceData {
|
||||
data: Buffer;
|
||||
}
|
||||
|
||||
export interface TSClientAvatar {
|
||||
/** TeamSpeak's avatar content marker, used to invalidate a cached avatar. */
|
||||
cacheKey: string;
|
||||
data: Buffer;
|
||||
}
|
||||
|
||||
// Keep enough room for avatars produced by the native client. The previous
|
||||
// 120 KiB limit rejected the 134 KiB PNG used by the Shanghai test account,
|
||||
// so every avatar silently fell back to its initial letter.
|
||||
const MAX_CLIENT_AVATAR_BYTES = 256 * 1024;
|
||||
|
||||
export type TSDirectorySnapshot = DirectorySnapshot;
|
||||
export type TSDirectoryClient = DirectoryClientInfo;
|
||||
export type TSRawNotification = RawNotification;
|
||||
|
||||
export type TSChatScope = "channel" | "server" | "private";
|
||||
|
||||
@@ -73,6 +88,10 @@ export class TSClient extends EventEmitter {
|
||||
private connected = false;
|
||||
private preferredChannelId = 0n;
|
||||
private accelerationClient: AccelerationRelayClient | null = null;
|
||||
// Reason id of the most recent self leave, kept so the SDK `kicked` event can
|
||||
// tell a plain kick (4) from a kick with ban (5). The SDK only forwards the
|
||||
// reason message to its `kicked` handler, not the reason id.
|
||||
private selfLeaveReasonId: number | null = null;
|
||||
|
||||
constructor(private options: TSClientOptions, logger: Logger) {
|
||||
super();
|
||||
@@ -81,6 +100,7 @@ export class TSClient extends EventEmitter {
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
this.selfLeaveReasonId = null;
|
||||
if (!this.adapter || !this.client) {
|
||||
let transportTarget = this.options.target;
|
||||
if (this.options.acceleration && !this.accelerationClient) {
|
||||
@@ -138,8 +158,9 @@ export class TSClient extends EventEmitter {
|
||||
this.emit("directorySnapshot", { channels, clients });
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({
|
||||
err: error instanceof Error ? error.message : String(error),
|
||||
}, "Could not reconcile the TeamSpeak directory snapshot");
|
||||
failureCode: "DIRECTORY_SNAPSHOT_UNAVAILABLE",
|
||||
failureDetail: error instanceof Error ? error.message : String(error),
|
||||
}, "TeamSpeak directory snapshot unavailable");
|
||||
}
|
||||
|
||||
const connectedChannelId = client.channelID();
|
||||
@@ -165,6 +186,46 @@ export class TSClient extends EventEmitter {
|
||||
this.emit("connected", this.clientId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a visible client's TeamSpeak avatar through the client protocol.
|
||||
*
|
||||
* TeamSpeak does not include the avatar bytes in directory notifications.
|
||||
* `clientinfo` exposes the avatar marker and the per-identity filename; the
|
||||
* file itself is then read through the normal TeamSpeak file-transfer port.
|
||||
* A missing permission, missing avatar, blocked file-transfer port, or an
|
||||
* oversized image is intentionally reported as `null` so the web client can
|
||||
* keep its generated initial avatar.
|
||||
*/
|
||||
async getClientAvatar(clientId: number, expectedUid = ""): Promise<TSClientAvatar | null> {
|
||||
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
|
||||
if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535) throw new Error("Invalid TeamSpeak client id");
|
||||
const rows = await this.client.execCommandWithResponse(`clientinfo clid=${clientId}`, 5_000);
|
||||
const info = rows.find((row) => {
|
||||
if (expectedUid && row.client_unique_identifier !== expectedUid) return false;
|
||||
return typeof row.client_flag_avatar === "string" && typeof row.client_base64HashClientUID === "string";
|
||||
});
|
||||
if (!info) return null;
|
||||
const cacheKey = info.client_flag_avatar?.trim() ?? "";
|
||||
const avatarFileKey = info.client_base64HashClientUID?.trim() ?? "";
|
||||
if (!cacheKey || !/^[A-Za-z0-9+/=_-]{8,256}$/.test(avatarFileKey)) return null;
|
||||
|
||||
const transfer = await this.client.fileTransferInitDownload(0n, `/avatar_${avatarFileKey}`, "");
|
||||
const size = Number(transfer.size);
|
||||
if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_CLIENT_AVATAR_BYTES) return null;
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
const destination = new Writable({
|
||||
write(chunk: Buffer | string, _encoding, callback) {
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
||||
callback();
|
||||
},
|
||||
});
|
||||
await this.client.downloadFileData(this.options.target.host, transfer, destination);
|
||||
const data = Buffer.concat(chunks);
|
||||
if (data.length === 0 || data.length > MAX_CLIENT_AVATAR_BYTES) return null;
|
||||
return { cacheKey, data };
|
||||
}
|
||||
|
||||
private attachClientListeners(client: TS3FullClient): void {
|
||||
client.on("voiceData", (data: VoiceData) => {
|
||||
this.emit("voiceData", {
|
||||
@@ -184,6 +245,13 @@ export class TSClient extends EventEmitter {
|
||||
});
|
||||
});
|
||||
|
||||
client.on("rawNotification", (notification: RawNotification) => {
|
||||
this.emit("rawNotification", {
|
||||
name: notification.name,
|
||||
params: { ...notification.params },
|
||||
} satisfies TSRawNotification);
|
||||
});
|
||||
|
||||
client.on("textMessage", (msg) => {
|
||||
this.emit("textMessage", toTSChatMessage(msg));
|
||||
});
|
||||
@@ -193,7 +261,15 @@ export class TSClient extends EventEmitter {
|
||||
});
|
||||
|
||||
client.on("disconnected", (err) => {
|
||||
this.logger.warn({ err: err?.message }, "Disconnected from TS");
|
||||
if (err) {
|
||||
const normalized = normalizeTeamSpeakError(err);
|
||||
this.logger.warn({
|
||||
failureCode: normalized.code.toUpperCase(),
|
||||
failureDetail: describeTeamSpeakError(normalized),
|
||||
}, "TeamSpeak transport disconnected unexpectedly");
|
||||
} else {
|
||||
this.logger.info("TeamSpeak transport disconnected");
|
||||
}
|
||||
this.connected = false;
|
||||
this.clientId = 0;
|
||||
this.emit("disconnected", err);
|
||||
@@ -204,13 +280,31 @@ export class TSClient extends EventEmitter {
|
||||
});
|
||||
|
||||
client.on("clientLeave", (info) => {
|
||||
// 仅记录本客户端的踢出(4)/踢出并封禁(5)退出原因,供 kicked 事件区分普通踢出与封禁
|
||||
if (info.id === this.clientId && (info.reasonID === 4 || info.reasonID === 5)) this.selfLeaveReasonId = info.reasonID;
|
||||
this.emit("clientLeave", info);
|
||||
});
|
||||
|
||||
// 转发 SDK 的 kicked 事件:不转发的话管理员填写的踢出原因会被丢弃,浏览器
|
||||
// 只能看到笼统的「连接失败」。这里把原因连同 reason id 一起归一化后向上抛。
|
||||
// The SDK emits `kicked` only for a self leave with reason 4 (kick) or 5
|
||||
// (kick with ban) and hands over the admin written reason message. Without
|
||||
// this listener the reason was dropped, so the browser degraded to a generic
|
||||
// "connection failed" right after the transport went away.
|
||||
client.on("kicked", (reasonMsg) => {
|
||||
const reasonId = this.selfLeaveReasonId;
|
||||
this.selfLeaveReasonId = null;
|
||||
this.emit("kicked", normalizeTeamSpeakKickedReason(reasonMsg, reasonId));
|
||||
});
|
||||
|
||||
client.on("clientMoved", (info) => {
|
||||
if (info.id === this.clientId && info.targetChannelID !== 0n) this.preferredChannelId = info.targetChannelID;
|
||||
this.emit("clientMoved", info);
|
||||
});
|
||||
|
||||
client.on("clientUpdated", (event) => {
|
||||
this.emit("clientUpdated", event.info);
|
||||
});
|
||||
}
|
||||
|
||||
sendVoice(data: Buffer, codec: number = 4): void {
|
||||
@@ -242,12 +336,24 @@ export class TSClient extends EventEmitter {
|
||||
await this.client.execCommand(`clientupdate client_away=${away ? 1 : 0} client_away_message=${escaped}`);
|
||||
}
|
||||
|
||||
async setInputMuted(muted: boolean): Promise<void> {
|
||||
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
|
||||
await this.client.execCommand(`clientupdate client_input_muted=${muted ? 1 : 0}`);
|
||||
}
|
||||
|
||||
async switchChannel(channelId: bigint, password?: string): Promise<void> {
|
||||
if (!this.client || !this.connected) return;
|
||||
await tsClientMove(this.client, this.clientId, channelId, password);
|
||||
this.preferredChannelId = channelId;
|
||||
}
|
||||
|
||||
/** Move another visible TeamSpeak client; the server enforces both move powers. */
|
||||
async moveClient(clientId: number, channelId: bigint, password?: string): Promise<void> {
|
||||
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
|
||||
if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535) throw new Error("Invalid TeamSpeak client id");
|
||||
await tsClientMove(this.client, clientId, channelId, password);
|
||||
}
|
||||
|
||||
getClientId(): number {
|
||||
// The SDK learns the real client id during the welcome sequence, before
|
||||
// TSClient.connect() resumes. Reading it from the SDK prevents the first
|
||||
@@ -264,6 +370,16 @@ export class TSClient extends EventEmitter {
|
||||
return this.client.execCommandWithResponse(command, timeoutMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a TeamSpeak protocol command whose response is delivered later as a
|
||||
* notification (for example setupstream/streamsignaling). The command is
|
||||
* assembled by the trusted server-side stream adapter, never by the browser.
|
||||
*/
|
||||
async sendProtocolCommand(command: string): Promise<void> {
|
||||
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
|
||||
await this.client.sendCommandNoWait(command);
|
||||
}
|
||||
|
||||
getIdentityString(): string {
|
||||
return this.identity.toString();
|
||||
}
|
||||
@@ -280,6 +396,7 @@ export class TSClient extends EventEmitter {
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
this.connected = false;
|
||||
this.selfLeaveReasonId = null;
|
||||
try {
|
||||
if (this.adapter) await this.adapter.disconnect();
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { resolveVisitorTotal } from "./visitor-count.js";
|
||||
|
||||
test("visitor total never disappears or falls below the current visitor ordinal", () => {
|
||||
assert.equal(resolveVisitorTotal(3, 0), 3);
|
||||
assert.equal(resolveVisitorTotal(3, 5), 5);
|
||||
assert.equal(resolveVisitorTotal(3, undefined), 3);
|
||||
assert.equal(resolveVisitorTotal(null, 8), 8);
|
||||
assert.equal(resolveVisitorTotal(null, -1), null);
|
||||
assert.equal(resolveVisitorTotal(0, 2), 2);
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
export function resolveVisitorTotal(visitorNumber: number | null, recordedTotal: unknown): number | null {
|
||||
const currentVisitor = Number.isSafeInteger(visitorNumber) && Number(visitorNumber) > 0
|
||||
? Number(visitorNumber)
|
||||
: null;
|
||||
const total = typeof recordedTotal === "number" && Number.isSafeInteger(recordedTotal) && recordedTotal >= 0
|
||||
? recordedTotal
|
||||
: null;
|
||||
|
||||
if (total === null) return currentVisitor;
|
||||
return Math.max(total, currentVisitor ?? 0);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
export interface ClientCommand {
|
||||
type: "switchChannel" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway" | "setWhisperTargets" | "setWhisperActive" | "setMicrophoneMuted" | "setAccompanimentActive" | "setMemberVolume" | "latencyProbe";
|
||||
type: "switchChannel" | "moveClient" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway" | "setWhisperTargets" | "setWhisperActive" | "setMicrophoneMuted" | "setAccompanimentActive" | "setMemberVolume" | "latencyProbe";
|
||||
requestId?: string;
|
||||
payload: Record<string, unknown>;
|
||||
}
|
||||
@@ -19,7 +19,7 @@ export function parseClientCommand(raw: string): ClientCommandResult {
|
||||
if (value.requestId !== undefined && (typeof value.requestId !== "string" || value.requestId.length > 64)) {
|
||||
return { error: { code: "INVALID_REQUEST_ID", message: "请求标识无效" } };
|
||||
}
|
||||
const supportedTypes = new Set(["switchChannel", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume", "latencyProbe"]);
|
||||
const supportedTypes = new Set(["switchChannel", "moveClient", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume", "latencyProbe"]);
|
||||
if (!supportedTypes.has(value.type)) {
|
||||
return { error: { code: "UNKNOWN_MESSAGE_TYPE", message: "不支持的消息类型" } };
|
||||
}
|
||||
@@ -32,6 +32,15 @@ export function parseClientCommand(raw: string): ClientCommandResult {
|
||||
if (value.type === "switchChannel" && value.payload.password !== undefined && (typeof value.payload.password !== "string" || value.payload.password.length > 512)) {
|
||||
return { error: { code: "INVALID_CHANNEL_PASSWORD", message: "频道密码无效" } };
|
||||
}
|
||||
if (value.type === "moveClient" && (typeof value.payload.clientId !== "number" || !Number.isInteger(value.payload.clientId) || value.payload.clientId <= 0 || value.payload.clientId > 65535)) {
|
||||
return { error: { code: "INVALID_CLIENT_ID", message: "成员标识无效" } };
|
||||
}
|
||||
if (value.type === "moveClient" && (typeof value.payload.channelId !== "string" || !/^\d{1,20}$/.test(value.payload.channelId))) {
|
||||
return { error: { code: "INVALID_CHANNEL_ID", message: "频道标识无效" } };
|
||||
}
|
||||
if (value.type === "moveClient" && value.payload.password !== undefined && (typeof value.payload.password !== "string" || value.payload.password.length > 512)) {
|
||||
return { error: { code: "INVALID_CHANNEL_PASSWORD", message: "频道密码无效" } };
|
||||
}
|
||||
if (value.type === "sendTextMessage" && (typeof value.payload.message !== "string" || value.payload.message.length > 500)) {
|
||||
return { error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" } };
|
||||
}
|
||||
|
||||
@@ -127,6 +127,7 @@ export class WebRtcAudioSession {
|
||||
private lastIngressRtpAt: number | null = null;
|
||||
private lastEgressRtpAt: number | null = null;
|
||||
private lastQueueEnqueuedAt: number | null = null;
|
||||
private microphoneMuted: boolean;
|
||||
private accompanimentActive: boolean;
|
||||
private readonly stats: WebRtcAudioStats = {
|
||||
webrtcIngressRtpFrames: 0,
|
||||
@@ -153,6 +154,7 @@ export class WebRtcAudioSession {
|
||||
this.logger = options.logger.child({ component: "webrtc-audio", connectionId: options.connectionId });
|
||||
this.onVoiceFrame = options.onVoiceFrame;
|
||||
this.onVoiceActivity = options.onVoiceActivity;
|
||||
this.microphoneMuted = options.microphoneMuted === true;
|
||||
this.accompanimentActive = options.accompanimentActive === true;
|
||||
this.outgoingTrack = new MediaStreamTrack({ kind: "audio" });
|
||||
|
||||
@@ -179,6 +181,13 @@ export class WebRtcAudioSession {
|
||||
this.stats.webrtcIngressRtpFrames++;
|
||||
if (!this.opusPayloadTypes.has(rtp.header.payloadType)) return;
|
||||
const payload = Buffer.from(rtp.payload);
|
||||
// A muted microphone must stop the browser user's TeamSpeak voice
|
||||
// packets at the gateway. Browser-side track.enabled/gain changes
|
||||
// still produce RTP comfort-silence on some browsers, and forwarding
|
||||
// those packets makes TeamSpeak keep the user in the speaking state.
|
||||
// When accompaniment is active, keep forwarding the mixed track: the
|
||||
// browser has already removed only the microphone component.
|
||||
if (this.microphoneMuted && !this.accompanimentActive) return;
|
||||
// Forward every valid negotiated Opus payload unchanged. Do not
|
||||
// decode it for RMS analysis or pass it through a speech/silence gate:
|
||||
// quiet frames are still part of the codec timeline and dropping them
|
||||
@@ -406,10 +415,7 @@ export class WebRtcAudioSession {
|
||||
}
|
||||
|
||||
setMicrophoneMuted(muted: boolean): void {
|
||||
// The browser sends a mixed microphone/accompaniment track. The mute gain
|
||||
// is applied before RTP encoding, so a server-side mute flag must not drop
|
||||
// the whole packet and silence a still-playing accompaniment.
|
||||
void muted;
|
||||
this.microphoneMuted = muted;
|
||||
}
|
||||
|
||||
setAccompanimentActive(active: boolean): void {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
export type SiteLanguage = "zh" | "en" | "de" | "ru" | "ja";
|
||||
|
||||
/**
|
||||
* Built-in welcome-page templates. An empty administrator value always falls
|
||||
* back to one of these strings, so adding a language never leaves the page
|
||||
* with a blank welcome message.
|
||||
*/
|
||||
export const DEFAULT_WELCOME_TEXTS: Record<SiteLanguage, string> = {
|
||||
zh: "无需安装 TeamSpeak 客户端,打开浏览器即可加入语音频道。低延迟、轻量、专注于每一次对话。",
|
||||
en: "No TeamSpeak client installation required. Open your browser and join a voice channel with low-latency audio built for conversation.",
|
||||
de: "Keine Installation des TeamSpeak-Clients nötig. Öffne den Browser und tritt einem Sprachkanal bei – leichtgewichtig und mit geringer Latenz.",
|
||||
ru: "Устанавливать клиент TeamSpeak не нужно: откройте браузер и присоединитесь к голосовому каналу. Низкая задержка и удобное общение в каждом разговоре.",
|
||||
ja: "TeamSpeak クライアントのインストールは不要です。ブラウザを開くだけで音声チャンネルに参加できます。低遅延で軽快な会話を楽しめます。",
|
||||
};
|
||||
|
||||
export function resolveWelcomeTexts(values: Partial<Record<SiteLanguage, string>>): Record<SiteLanguage, string> {
|
||||
return {
|
||||
zh: values.zh?.trim() || DEFAULT_WELCOME_TEXTS.zh,
|
||||
en: values.en?.trim() || DEFAULT_WELCOME_TEXTS.en,
|
||||
de: values.de?.trim() || DEFAULT_WELCOME_TEXTS.de,
|
||||
ru: values.ru?.trim() || DEFAULT_WELCOME_TEXTS.ru,
|
||||
ja: values.ja?.trim() || DEFAULT_WELCOME_TEXTS.ja,
|
||||
};
|
||||
}
|
||||
@@ -6,7 +6,12 @@
|
||||
"": {
|
||||
"name": "webspeak-webclient-frontend",
|
||||
"dependencies": {
|
||||
"@sapphi-red/web-noise-suppressor": "^0.4.0",
|
||||
"fflate": "^0.8.3",
|
||||
"pinia": "^3.0.2",
|
||||
"postcss": "^8.5.28",
|
||||
"postcss-selector-parser": "^7.1.6",
|
||||
"postcss-value-parser": "^4.2.0",
|
||||
"vue": "^3.5.13",
|
||||
"vue-router": "^4.5.1"
|
||||
},
|
||||
@@ -861,6 +866,16 @@
|
||||
"win32"
|
||||
]
|
||||
},
|
||||
"node_modules/@sapphi-red/web-noise-suppressor": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@sapphi-red/web-noise-suppressor/-/web-noise-suppressor-0.4.0.tgz",
|
||||
"integrity": "sha512-vkBEL/VDkbeP3qqSRQFRtPLGa19a38JUzO6J0r5D/MQSumrlERy671DAMaETgY6etXjDCoJcD7JBIaXnuGVtVw==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/sapphi-red"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/estree": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
|
||||
@@ -1128,6 +1143,18 @@
|
||||
"url": "https://github.com/sponsors/mesqueeb"
|
||||
}
|
||||
},
|
||||
"node_modules/cssesc": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz",
|
||||
"integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==",
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"cssesc": "bin/cssesc"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/csstype": {
|
||||
"version": "3.2.3",
|
||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
||||
@@ -1219,6 +1246,12 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/fflate": {
|
||||
"version": "0.8.3",
|
||||
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
|
||||
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fsevents": {
|
||||
"version": "2.3.3",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
||||
@@ -1343,6 +1376,7 @@
|
||||
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -1372,9 +1406,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/postcss": {
|
||||
"version": "8.5.26",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",
|
||||
"integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==",
|
||||
"version": "8.5.28",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
|
||||
"integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "opencollective",
|
||||
@@ -1391,7 +1425,7 @@
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.17",
|
||||
"nanoid": "^3.3.18",
|
||||
"picocolors": "^1.1.1",
|
||||
"source-map-js": "^1.2.1"
|
||||
},
|
||||
@@ -1399,6 +1433,25 @@
|
||||
"node": "^10 || ^12 || >=14"
|
||||
}
|
||||
},
|
||||
"node_modules/postcss-selector-parser": {
|
||||
"version": "7.1.6",
|
||||
"resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.6.tgz",
|
||||
"integrity": "sha512-7qASPzhKF2l2KLboRZux8CCTRMdGiV08vWmyKzPz22qZ7ZjQBOeY7rNzNoCLSUiftJ7HUq0GERHmxw/t0dCdMw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cssesc": "^3.0.0",
|
||||
"util-deprecate": "^1.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/postcss-value-parser": {
|
||||
"version": "4.2.0",
|
||||
"resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz",
|
||||
"integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/rfdc": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz",
|
||||
@@ -1503,6 +1556,7 @@
|
||||
"integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==",
|
||||
"devOptional": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -1511,12 +1565,19 @@
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/util-deprecate": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
|
||||
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "6.4.3",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",
|
||||
"integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"esbuild": "^0.25.0",
|
||||
"fdir": "^6.4.4",
|
||||
@@ -1598,6 +1659,7 @@
|
||||
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.34.tgz",
|
||||
"integrity": "sha512-WdLBG9gm02OgJIG9axd5Hpx0TFLdzVgfG2evFFu8Rur5O/IoGc5cMjnjh3tPL6GnRGsYvUhBSKVPYVcxRKpMCA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@vue/compiler-dom": "3.5.34",
|
||||
"@vue/compiler-sfc": "3.5.34",
|
||||
|
||||
@@ -8,7 +8,12 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@sapphi-red/web-noise-suppressor": "^0.4.0",
|
||||
"fflate": "^0.8.3",
|
||||
"pinia": "^3.0.2",
|
||||
"postcss": "^8.5.28",
|
||||
"postcss-selector-parser": "^7.1.6",
|
||||
"postcss-value-parser": "^4.2.0",
|
||||
"vue": "^3.5.13",
|
||||
"vue-router": "^4.5.1"
|
||||
},
|
||||
|
||||
|
After Width: | Height: | Size: 1014 KiB |
@@ -1,3 +1,16 @@
|
||||
<template>
|
||||
<router-view />
|
||||
</template>
|
||||
|
||||
<style>
|
||||
:root {
|
||||
--ui-scale: 1;
|
||||
}
|
||||
|
||||
/* Scale the complete application from the 1920×1080 reference viewport so
|
||||
typography, spacing, controls, and icons grow together instead of drifting
|
||||
apart when the browser has a high-resolution viewport. */
|
||||
#app {
|
||||
zoom: var(--ui-scale);
|
||||
}
|
||||
</style>
|
||||
@@ -79,6 +79,8 @@
|
||||
</template>
|
||||
<path v-else-if="name === 'moon'" d="M20.4 15.2A8.5 8.5 0 0 1 8.8 3.6 8.5 8.5 0 1 0 20.4 15.2Z" />
|
||||
<path v-else-if="name === 'monitor'" d="M4 4h16v12H4zM8 20h8M12 16v4" />
|
||||
<path v-else-if="name === 'fullscreen'" d="M4 9V4h5M15 4h5v5M20 15v5h-5M9 20H4v-5" />
|
||||
<path v-else-if="name === 'fullscreen-exit'" d="M9 4v5H4M20 9h-5V4M15 20v-5h5M4 15h5v5" />
|
||||
<path v-else-if="name === 'github'" fill="currentColor" stroke="none" d="M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56 0-.28-.01-1.02-.02-2-3.2.7-3.88-1.54-3.88-1.54-.53-1.33-1.28-1.68-1.28-1.68-1.04-.71.08-.7.08-.7 1.15.08 1.75 1.18 1.75 1.18 1.02 1.75 2.68 1.24 3.33.95.1-.74.4-1.24.73-1.52-2.55-.29-5.23-1.28-5.23-5.68 0-1.25.45-2.27 1.18-3.07-.12-.29-.51-1.45.11-3.03 0 0 .96-.31 3.15 1.17.91-.25 1.88-.38 2.85-.38.97 0 1.94.13 2.85.38 2.19-1.48 3.15-1.17 3.15-1.17.62 1.58.23 2.74.11 3.03.73.8 1.18 1.82 1.18 3.07 0 4.41-2.69 5.38-5.25 5.67.41.35.78 1.04.78 2.1 0 1.52-.01 2.75-.01 3.12 0 .3.21.67.8.56C20.71 21.39 24 17.08 24 12 24 5.65 18.35.5 12 .5Z" />
|
||||
<template v-else-if="name === 'qq'">
|
||||
<ellipse cx="12" cy="12.3" rx="7.25" ry="8.85" fill="#202a2a" stroke="none" />
|
||||
|
||||
@@ -3,9 +3,11 @@
|
||||
<button
|
||||
type="button"
|
||||
class="language-trigger"
|
||||
data-ws-part="language.trigger"
|
||||
:aria-label="menuLabel"
|
||||
aria-haspopup="listbox"
|
||||
:aria-expanded="open"
|
||||
:data-ws-state="open ? 'open' : 'closed'"
|
||||
:aria-controls="menuId"
|
||||
@click.stop="toggle"
|
||||
>
|
||||
@@ -14,12 +16,14 @@
|
||||
<Icon name="chevron-down" :size="13" />
|
||||
</button>
|
||||
|
||||
<div v-if="open" :id="menuId" class="language-dropdown" role="listbox" :aria-label="menuLabel" @click.stop>
|
||||
<div v-if="open" :id="menuId" class="language-dropdown" data-ws-part="language.menu" role="listbox" :aria-label="menuLabel" @click.stop>
|
||||
<button
|
||||
v-for="option in options"
|
||||
:key="option.value"
|
||||
type="button"
|
||||
class="language-option"
|
||||
data-ws-part="language.option"
|
||||
:data-ws-language="option.value"
|
||||
:class="{ selected: modelValue === option.value }"
|
||||
role="option"
|
||||
:aria-selected="modelValue === option.value"
|
||||
@@ -42,7 +46,7 @@
|
||||
import { computed, onMounted, onUnmounted, ref } from "vue";
|
||||
import Icon from "./Icon.vue";
|
||||
|
||||
type Language = "zh" | "en" | "de";
|
||||
type Language = "zh" | "en" | "de" | "ru" | "ja";
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue: Language;
|
||||
@@ -60,6 +64,8 @@ const options: Array<{ value: Language; code: string; label: string; flag: strin
|
||||
{ value: "zh", code: "ZH", label: "中文", flag: "🇨🇳" },
|
||||
{ value: "en", code: "EN", label: "English", flag: "🇬🇧" },
|
||||
{ value: "de", code: "DE", label: "Deutsch", flag: "🇩🇪" },
|
||||
{ value: "ru", code: "RU", label: "Русский", flag: "🇷🇺" },
|
||||
{ value: "ja", code: "JA", label: "日本語", flag: "🇯🇵" },
|
||||
];
|
||||
|
||||
const root = ref<HTMLElement | null>(null);
|
||||
@@ -237,40 +243,40 @@ onUnmounted(() => document.removeEventListener("pointerdown", onDocumentPointerD
|
||||
to { opacity: 1; transform: translateY(0) scale(1); }
|
||||
}
|
||||
|
||||
:global(html[data-theme="dark"]) .language-trigger,
|
||||
:global(:root[data-theme="dark"]) .language-trigger {
|
||||
:global(html[data-theme="dark"] .admin-root) .language-trigger,
|
||||
:global(:root[data-theme="dark"] .admin-root) .language-trigger {
|
||||
color: #a9d9d1;
|
||||
background: #203531;
|
||||
border-color: #38564f;
|
||||
}
|
||||
|
||||
:global(html[data-theme="dark"]) .language-trigger:hover,
|
||||
:global(html[data-theme="dark"]) .language-switcher.open .language-trigger,
|
||||
:global(:root[data-theme="dark"]) .language-trigger:hover,
|
||||
:global(:root[data-theme="dark"]) .language-switcher.open .language-trigger {
|
||||
:global(html[data-theme="dark"] .admin-root) .language-trigger:hover,
|
||||
:global(html[data-theme="dark"] .admin-root) .language-switcher.open .language-trigger,
|
||||
:global(:root[data-theme="dark"] .admin-root) .language-trigger:hover,
|
||||
:global(:root[data-theme="dark"] .admin-root) .language-switcher.open .language-trigger {
|
||||
color: #10201d;
|
||||
background: #69d2c7;
|
||||
border-color: #69d2c7;
|
||||
}
|
||||
|
||||
:global(html[data-theme="dark"]) .language-dropdown,
|
||||
:global(:root[data-theme="dark"]) .language-dropdown {
|
||||
:global(html[data-theme="dark"] .admin-root) .language-dropdown,
|
||||
:global(:root[data-theme="dark"] .admin-root) .language-dropdown {
|
||||
background: #172321;
|
||||
border-color: #30413d;
|
||||
box-shadow: 0 16px 36px rgba(0, 0, 0, .32);
|
||||
}
|
||||
|
||||
:global(html[data-theme="dark"]) .language-option,
|
||||
:global(:root[data-theme="dark"]) .language-option {
|
||||
:global(html[data-theme="dark"] .admin-root) .language-option,
|
||||
:global(:root[data-theme="dark"] .admin-root) .language-option {
|
||||
color: #d7e7e3;
|
||||
}
|
||||
|
||||
:global(html[data-theme="dark"]) .language-option:hover,
|
||||
:global(html[data-theme="dark"]) .language-option:focus-visible,
|
||||
:global(html[data-theme="dark"]) .language-option.selected,
|
||||
:global(:root[data-theme="dark"]) .language-option:hover,
|
||||
:global(:root[data-theme="dark"]) .language-option:focus-visible,
|
||||
:global(:root[data-theme="dark"]) .language-option.selected {
|
||||
:global(html[data-theme="dark"] .admin-root) .language-option:hover,
|
||||
:global(html[data-theme="dark"] .admin-root) .language-option:focus-visible,
|
||||
:global(html[data-theme="dark"] .admin-root) .language-option.selected,
|
||||
:global(:root[data-theme="dark"] .admin-root) .language-option:hover,
|
||||
:global(:root[data-theme="dark"] .admin-root) .language-option:focus-visible,
|
||||
:global(:root[data-theme="dark"] .admin-root) .language-option.selected {
|
||||
color: #69d2c7;
|
||||
background: #203531;
|
||||
border-color: #38564f;
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
<template>
|
||||
<div ref="root" class="skin-switcher" :class="{ open }" @keydown.esc="close">
|
||||
<button
|
||||
type="button"
|
||||
class="skin-trigger"
|
||||
data-ws-part="skin.trigger"
|
||||
:aria-label="menuLabel"
|
||||
:title="`${menuLabel}: ${selectedOption.label}`"
|
||||
aria-haspopup="listbox"
|
||||
:aria-expanded="open"
|
||||
:data-ws-state="open ? 'open' : 'closed'"
|
||||
:aria-controls="menuId"
|
||||
@click.stop="toggle"
|
||||
>
|
||||
<Icon :name="selectedOption.icon || 'compass'" :size="15" />
|
||||
<span>{{ menuLabel }}</span>
|
||||
<Icon name="chevron-down" :size="12" />
|
||||
</button>
|
||||
|
||||
<div v-if="open" :id="menuId" class="skin-dropdown" data-ws-part="skin.menu" role="listbox" :aria-label="menuLabel" @click.stop>
|
||||
<button
|
||||
v-for="option in options"
|
||||
:key="option.value"
|
||||
type="button"
|
||||
class="skin-option"
|
||||
data-ws-part="skin.option"
|
||||
:data-ws-skin-id="option.value"
|
||||
:class="{ selected: modelValue === option.value }"
|
||||
role="option"
|
||||
:aria-selected="modelValue === option.value"
|
||||
@click="select(option.value)"
|
||||
>
|
||||
<Icon :name="option.icon || 'compass'" :size="16" />
|
||||
<span>{{ option.label }}</span>
|
||||
<Icon v-if="modelValue === option.value" name="check" :size="14" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from "vue";
|
||||
import Icon from "./Icon.vue";
|
||||
|
||||
export interface SkinOption {
|
||||
value: string;
|
||||
label: string;
|
||||
icon?: string;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: string;
|
||||
menuLabel: string;
|
||||
options: SkinOption[];
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [value: string];
|
||||
change: [value: string];
|
||||
}>();
|
||||
|
||||
const options = computed(() => props.options);
|
||||
const selectedOption = computed(() => options.value.find((option) => option.value === props.modelValue) ?? options.value[0]);
|
||||
const root = ref<HTMLElement | null>(null);
|
||||
const open = ref(false);
|
||||
const menuId = `skin-menu-${Math.random().toString(36).slice(2, 9)}`;
|
||||
|
||||
function toggle() { open.value = !open.value; }
|
||||
function close() { open.value = false; }
|
||||
function select(value: string) {
|
||||
emit("update:modelValue", value);
|
||||
emit("change", value);
|
||||
close();
|
||||
}
|
||||
function onDocumentPointerDown(event: PointerEvent) {
|
||||
if (root.value && !root.value.contains(event.target as Node)) close();
|
||||
}
|
||||
|
||||
onMounted(() => document.addEventListener("pointerdown", onDocumentPointerDown));
|
||||
onUnmounted(() => document.removeEventListener("pointerdown", onDocumentPointerDown));
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.skin-switcher {
|
||||
position: relative;
|
||||
z-index: 20;
|
||||
flex: 0 0 auto;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.skin-trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 5px;
|
||||
min-width: 34px;
|
||||
min-height: 32px;
|
||||
padding: 0 8px;
|
||||
color: #08766f;
|
||||
background: rgba(250, 254, 255, .94);
|
||||
border: 1px solid #c8e6e1;
|
||||
border-radius: 8px;
|
||||
font: inherit;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 4px 12px rgba(8, 126, 134, .08);
|
||||
transition: color .16s, background .16s, border-color .16s, box-shadow .16s;
|
||||
}
|
||||
|
||||
.skin-trigger:hover,
|
||||
.skin-switcher.open .skin-trigger {
|
||||
color: #056e76;
|
||||
background: #edfafa;
|
||||
border-color: #8fd7d9;
|
||||
box-shadow: 0 6px 16px rgba(30, 170, 184, .14);
|
||||
}
|
||||
|
||||
.skin-trigger > .ui-icon:last-child { margin-left: 1px; }
|
||||
|
||||
.skin-dropdown {
|
||||
position: absolute;
|
||||
top: calc(100% + 7px);
|
||||
right: 0;
|
||||
display: grid;
|
||||
gap: 3px;
|
||||
min-width: 176px;
|
||||
padding: 6px;
|
||||
color: #123849;
|
||||
background: linear-gradient(145deg, rgba(250, 255, 255, .99), rgba(232, 249, 250, .98));
|
||||
border: 1px solid rgba(104, 196, 211, .58);
|
||||
border-radius: 11px;
|
||||
box-shadow: 0 18px 42px rgba(29, 115, 139, .2), inset 0 1px 0 rgba(255, 255, 255, .96);
|
||||
backdrop-filter: blur(18px) saturate(1.12);
|
||||
}
|
||||
|
||||
.skin-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 9px;
|
||||
min-height: 36px;
|
||||
padding: 0 9px;
|
||||
color: #123849;
|
||||
background: linear-gradient(112deg, rgba(255, 255, 255, .96), rgba(225, 250, 249, .96), rgba(188, 241, 237, .94), rgba(255, 255, 255, .96));
|
||||
background-size: 240% 100%;
|
||||
border: 1px solid rgba(139, 218, 216, .46);
|
||||
border-radius: 7px;
|
||||
font: inherit;
|
||||
font-size: 11px;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
animation: skin-option-gradient 8s ease-in-out infinite alternate;
|
||||
transition: color .18s, border-color .18s, box-shadow .18s, background-position .4s ease;
|
||||
}
|
||||
|
||||
.skin-option > .ui-icon:first-child { color: #64858a; }
|
||||
.skin-option > .ui-icon:last-child { margin-left: auto; color: #087e86; }
|
||||
.skin-option:hover,
|
||||
.skin-option:focus-visible {
|
||||
color: #087e86;
|
||||
border-color: rgba(57, 195, 193, .74);
|
||||
background-position: 100% 50%;
|
||||
box-shadow: 0 4px 13px rgba(43, 179, 181, .16), inset 0 0 0 1px rgba(255, 255, 255, .84);
|
||||
}
|
||||
|
||||
.skin-option.selected {
|
||||
color: #056f73;
|
||||
border-color: rgba(44, 183, 181, .78);
|
||||
background-image: linear-gradient(112deg, #faffff 0%, #c8f5f1 36%, #82e2dc 70%, #d9fbf8 100%);
|
||||
background-position: 100% 50%;
|
||||
box-shadow: 0 5px 16px rgba(37, 170, 171, .22), inset 0 0 0 1px rgba(255, 255, 255, .94), inset 0 -1px 0 rgba(31, 164, 163, .12);
|
||||
}
|
||||
|
||||
.skin-option.selected > .ui-icon:first-child,
|
||||
.skin-option.selected > .ui-icon:last-child { color: #087e86; }
|
||||
|
||||
@keyframes skin-option-gradient {
|
||||
from { background-position: 0% 50%; }
|
||||
to { background-position: 100% 50%; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.skin-option { animation: none; }
|
||||
}
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.skin-trigger { min-height: 36px; }
|
||||
.skin-dropdown { min-width: 190px; }
|
||||
}
|
||||
|
||||
.skin-switcher.mobile-skin-switcher .skin-trigger {
|
||||
width: 100%;
|
||||
min-height: 44px;
|
||||
justify-content: flex-start;
|
||||
padding-inline: 12px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
@media (max-width: 420px) {
|
||||
.skin-switcher.join-skin-switcher .skin-trigger {
|
||||
width: 28px;
|
||||
min-width: 28px;
|
||||
min-height: 28px;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.skin-switcher.join-skin-switcher .skin-trigger > span,
|
||||
.skin-switcher.join-skin-switcher .skin-trigger > .ui-icon:last-child { display: none; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,209 @@
|
||||
import { computed, ref, watch, type Ref } from "vue";
|
||||
|
||||
interface UseWebClientAudioControlsOptions {
|
||||
settingsOpen: Ref<boolean>;
|
||||
microphoneMuted: Readonly<Ref<boolean>>;
|
||||
inputVolume: Readonly<Ref<number>>;
|
||||
voxThreshold: Readonly<Ref<number>>;
|
||||
notificationVolume: Readonly<Ref<number>>;
|
||||
micLevel: Readonly<Ref<number>>;
|
||||
microphoneTestActive: Readonly<Ref<boolean>>;
|
||||
accompanimentActive: Readonly<Ref<boolean>>;
|
||||
accompanimentErrorCode: Readonly<Ref<string>>;
|
||||
whisperTargetIds: Set<number>;
|
||||
prepareInputDevices: () => Promise<void>;
|
||||
setInputVolume: (value: number) => void;
|
||||
setNoiseSuppressionEnabled: (enabled: boolean) => Promise<void>;
|
||||
setOutputVolume: (value: number) => void;
|
||||
setVoxThreshold: (value: number) => void;
|
||||
setNotificationVolume: (value: number) => void;
|
||||
setInputDevice: (deviceId: string) => Promise<void>;
|
||||
setOutputDevice: (deviceId: string) => Promise<void>;
|
||||
setMicrophoneMuted: (muted: boolean) => void;
|
||||
startMicrophoneTest: () => Promise<void>;
|
||||
stopMicrophoneTest: () => void;
|
||||
startAccompaniment: () => Promise<void>;
|
||||
stopAccompaniment: () => Promise<void>;
|
||||
setWhisperActive: (active: boolean) => void;
|
||||
localizedMessage: (message: string) => string;
|
||||
showToast: (message: string) => void;
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
export function useWebClientAudioControls({
|
||||
settingsOpen,
|
||||
microphoneMuted,
|
||||
inputVolume,
|
||||
voxThreshold,
|
||||
notificationVolume,
|
||||
micLevel,
|
||||
microphoneTestActive,
|
||||
accompanimentActive,
|
||||
accompanimentErrorCode,
|
||||
whisperTargetIds,
|
||||
prepareInputDevices,
|
||||
setInputVolume,
|
||||
setNoiseSuppressionEnabled,
|
||||
setOutputVolume,
|
||||
setVoxThreshold,
|
||||
setNotificationVolume,
|
||||
setInputDevice,
|
||||
setOutputDevice,
|
||||
setMicrophoneMuted,
|
||||
startMicrophoneTest,
|
||||
stopMicrophoneTest,
|
||||
startAccompaniment,
|
||||
stopAccompaniment,
|
||||
setWhisperActive,
|
||||
localizedMessage,
|
||||
showToast,
|
||||
t,
|
||||
}: UseWebClientAudioControlsOptions) {
|
||||
const settingsError = ref("");
|
||||
const whisperPttActive = ref(false);
|
||||
const micMeterBars = computed(() => Math.round(micLevel.value * 24));
|
||||
|
||||
function microphoneErrorMessage(error: unknown, fallback = "请检查浏览器权限"): string {
|
||||
const name = error instanceof DOMException ? error.name : "";
|
||||
const reasons: Record<string, string> = {
|
||||
NotAllowedError: "浏览器未授予麦克风权限",
|
||||
NotFoundError: "未找到可用的麦克风",
|
||||
NotReadableError: "麦克风可能正被其他程序占用",
|
||||
OverconstrainedError: "所选麦克风当前不可用",
|
||||
SecurityError: "浏览器阻止了麦克风访问",
|
||||
};
|
||||
return `麦克风访问失败:${reasons[name] ?? fallback}`;
|
||||
}
|
||||
|
||||
function onInputVolume(event: Event): void {
|
||||
setInputVolume(Number((event.target as HTMLInputElement).value) / 100);
|
||||
}
|
||||
|
||||
function onNoiseSuppressionToggle(event: Event): void {
|
||||
void setNoiseSuppressionEnabled((event.target as HTMLInputElement).checked);
|
||||
}
|
||||
|
||||
function onOutputVolume(event: Event): void {
|
||||
setOutputVolume(Number((event.target as HTMLInputElement).value) / 100);
|
||||
}
|
||||
|
||||
function onVoxThreshold(event: Event): void {
|
||||
setVoxThreshold(Number((event.target as HTMLInputElement).value) / 1000);
|
||||
}
|
||||
|
||||
function onNotificationVolume(event: Event): void {
|
||||
setNotificationVolume(Number((event.target as HTMLInputElement).value) / 100);
|
||||
}
|
||||
|
||||
async function onInputDeviceChange(event: Event): Promise<void> {
|
||||
settingsError.value = "";
|
||||
try {
|
||||
await setInputDevice((event.target as HTMLSelectElement).value);
|
||||
} catch (error: unknown) {
|
||||
settingsError.value = microphoneErrorMessage(error, "无法切换麦克风");
|
||||
}
|
||||
}
|
||||
|
||||
async function onOutputDeviceChange(event: Event): Promise<void> {
|
||||
settingsError.value = "";
|
||||
try {
|
||||
await setOutputDevice((event.target as HTMLSelectElement).value);
|
||||
} catch (error: unknown) {
|
||||
settingsError.value = localizedMessage(error instanceof Error ? error.message : "无法切换扬声器");
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleMicTest(): Promise<void> {
|
||||
settingsError.value = "";
|
||||
try {
|
||||
if (microphoneTestActive.value) stopMicrophoneTest();
|
||||
else await startMicrophoneTest();
|
||||
} catch (error: unknown) {
|
||||
settingsError.value = microphoneErrorMessage(error);
|
||||
}
|
||||
}
|
||||
|
||||
function meterBarHeight(index: number): number {
|
||||
if (!microphoneTestActive.value) return 5;
|
||||
const intensity = Math.max(0, micLevel.value - (index / 24) * 0.65);
|
||||
return 5 + Math.round(intensity * 34);
|
||||
}
|
||||
|
||||
function toggleMicrophone(): void {
|
||||
setMicrophoneMuted(!microphoneMuted.value);
|
||||
showToast(t(microphoneMuted.value ? "microphoneMuted" : "microphoneActive"));
|
||||
}
|
||||
|
||||
async function toggleAccompaniment(): Promise<void> {
|
||||
try {
|
||||
if (accompanimentActive.value) {
|
||||
await stopAccompaniment();
|
||||
showToast(t("accompanimentStopped"));
|
||||
return;
|
||||
}
|
||||
await startAccompaniment();
|
||||
if (accompanimentActive.value) showToast(t("accompanimentStarted"));
|
||||
} catch {
|
||||
const messageKey = accompanimentErrorCode.value === "needsWebRtc"
|
||||
? "accompanimentNeedsWebRtc"
|
||||
: accompanimentErrorCode.value === "noAudio"
|
||||
? "accompanimentNoAudio"
|
||||
: accompanimentErrorCode.value === "unsupported"
|
||||
? "accompanimentUnsupported"
|
||||
: "accompanimentPermissionDenied";
|
||||
showToast(t(messageKey));
|
||||
}
|
||||
}
|
||||
|
||||
function onWhisperPttDown(event: PointerEvent): void {
|
||||
if (!whisperTargetIds.size) return;
|
||||
const target = event.currentTarget as HTMLElement | null;
|
||||
if (target?.setPointerCapture && !target.hasPointerCapture(event.pointerId)) target.setPointerCapture(event.pointerId);
|
||||
whisperPttActive.value = true;
|
||||
setWhisperActive(true);
|
||||
}
|
||||
|
||||
function onWhisperPttUp(event: PointerEvent): void {
|
||||
const target = event.currentTarget as HTMLElement | null;
|
||||
if (target?.releasePointerCapture && target.hasPointerCapture(event.pointerId)) target.releasePointerCapture(event.pointerId);
|
||||
stopWhisperTalk();
|
||||
}
|
||||
|
||||
function stopWhisperTalk(): void {
|
||||
if (!whisperPttActive.value) return;
|
||||
whisperPttActive.value = false;
|
||||
setWhisperActive(false);
|
||||
}
|
||||
|
||||
watch(settingsOpen, (open) => {
|
||||
if (open) {
|
||||
settingsError.value = "";
|
||||
prepareInputDevices().catch((error: unknown) => {
|
||||
settingsError.value = microphoneErrorMessage(error);
|
||||
});
|
||||
} else {
|
||||
stopMicrophoneTest();
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
settingsError,
|
||||
whisperPttActive,
|
||||
micMeterBars,
|
||||
onInputVolume,
|
||||
onNoiseSuppressionToggle,
|
||||
onOutputVolume,
|
||||
onVoxThreshold,
|
||||
onNotificationVolume,
|
||||
onInputDeviceChange,
|
||||
onOutputDeviceChange,
|
||||
toggleMicTest,
|
||||
microphoneErrorMessage,
|
||||
meterBarHeight,
|
||||
toggleMicrophone,
|
||||
toggleAccompaniment,
|
||||
onWhisperPttDown,
|
||||
onWhisperPttUp,
|
||||
stopWhisperTalk,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { computed, watch, type Ref } from "vue";
|
||||
import type { ChannelInfo, ChannelMember } from "./useVoiceWebSocket.js";
|
||||
|
||||
export interface TreeChannel extends ChannelInfo {
|
||||
depth: number;
|
||||
members: ChannelMember[];
|
||||
}
|
||||
|
||||
interface UseWebClientChannelsOptions {
|
||||
channels: ChannelInfo[];
|
||||
members: ChannelMember[];
|
||||
clientId: Readonly<Ref<number>>;
|
||||
selectedChannelId: Ref<string>;
|
||||
channelName: Ref<string>;
|
||||
memberQuery: Ref<string>;
|
||||
whisperTargetIds: Set<number>;
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
export function useWebClientChannels({
|
||||
channels,
|
||||
members,
|
||||
clientId,
|
||||
selectedChannelId,
|
||||
channelName,
|
||||
memberQuery,
|
||||
whisperTargetIds,
|
||||
t,
|
||||
}: UseWebClientChannelsOptions) {
|
||||
const channelTree = computed<TreeChannel[]>(() => {
|
||||
const source = [...channels];
|
||||
const sourceIndex = new Map(source.map((item, index) => [item.id, index]));
|
||||
const enriched = source.map((item) => ({
|
||||
...item,
|
||||
members: (item.members ?? []).map((member) => ({ ...member, isSelf: member.id === clientId.value })),
|
||||
}));
|
||||
const byId = new Map(enriched.map((item) => [item.id, item]));
|
||||
const depthCache = new Map<string, number>();
|
||||
|
||||
function depthOf(item: ChannelInfo, visiting = new Set<string>()): number {
|
||||
if (depthCache.has(item.id)) return depthCache.get(item.id)!;
|
||||
if (!item.parentID || item.parentID === "0" || visiting.has(item.id)) return 0;
|
||||
const parent = byId.get(item.parentID);
|
||||
const depth = parent ? depthOf(parent, new Set(visiting).add(item.id)) + 1 : 0;
|
||||
depthCache.set(item.id, depth);
|
||||
return depth;
|
||||
}
|
||||
|
||||
const childrenByParent = new Map<string, TreeChannel[]>();
|
||||
for (const item of enriched) {
|
||||
const treeChannel = { ...item, depth: depthOf(item) };
|
||||
const siblings = childrenByParent.get(treeChannel.parentID) ?? [];
|
||||
siblings.push(treeChannel);
|
||||
childrenByParent.set(treeChannel.parentID, siblings);
|
||||
}
|
||||
|
||||
function orderSiblings(siblings: TreeChannel[]): TreeChannel[] {
|
||||
const bySiblingId = new Map(siblings.map((item) => [item.id, item]));
|
||||
const successors = new Map<string, TreeChannel[]>();
|
||||
const roots: TreeChannel[] = [];
|
||||
const sourceOrder = (left: TreeChannel, right: TreeChannel) =>
|
||||
(sourceIndex.get(left.id) ?? Number.MAX_SAFE_INTEGER) - (sourceIndex.get(right.id) ?? Number.MAX_SAFE_INTEGER);
|
||||
|
||||
for (const item of siblings) {
|
||||
const predecessor = item.order && item.order !== "0" && bySiblingId.has(item.order) ? item.order : "";
|
||||
if (!predecessor) roots.push(item);
|
||||
else successors.set(predecessor, [...(successors.get(predecessor) ?? []), item]);
|
||||
}
|
||||
|
||||
roots.sort(sourceOrder);
|
||||
for (const items of successors.values()) items.sort(sourceOrder);
|
||||
|
||||
const ordered: TreeChannel[] = [];
|
||||
const visited = new Set<string>();
|
||||
const append = (item: TreeChannel) => {
|
||||
if (visited.has(item.id)) return;
|
||||
visited.add(item.id);
|
||||
ordered.push(item);
|
||||
for (const successor of successors.get(item.id) ?? []) append(successor);
|
||||
};
|
||||
for (const root of roots) append(root);
|
||||
for (const item of [...siblings].sort(sourceOrder)) append(item);
|
||||
return ordered;
|
||||
}
|
||||
|
||||
const orderedTree: TreeChannel[] = [];
|
||||
const visit = (parentID: string) => {
|
||||
for (const treeChannel of orderSiblings(childrenByParent.get(parentID) ?? [])) {
|
||||
orderedTree.push(treeChannel);
|
||||
visit(treeChannel.id);
|
||||
}
|
||||
};
|
||||
visit("0");
|
||||
for (const item of enriched) {
|
||||
if (!orderedTree.some((treeChannel) => treeChannel.id === item.id)) {
|
||||
orderedTree.push({ ...item, depth: depthOf(item) });
|
||||
visit(item.id);
|
||||
}
|
||||
}
|
||||
return orderedTree;
|
||||
});
|
||||
|
||||
const currentChannel = computed<TreeChannel | undefined>(() => {
|
||||
const explicitlySelected = channelTree.value.find((item) => item.id === selectedChannelId.value);
|
||||
if (explicitlySelected) return explicitlySelected;
|
||||
const fromSelf = channelTree.value.find((item) => item.members.some((member) => member.id === clientId.value));
|
||||
if (fromSelf) return fromSelf;
|
||||
return channelTree.value.find((item) => item.name === channelName.value) ?? channelTree.value[0];
|
||||
});
|
||||
const currentChannelName = computed(() => (currentChannel.value?.name ?? channelName.value) || t("voiceLobby"));
|
||||
const currentChannelDescription = computed(() => currentChannel.value?.description ?? "");
|
||||
const currentMembers = computed<ChannelMember[]>(() => {
|
||||
const source = currentChannel.value ? currentChannel.value.members : members;
|
||||
return source.map((member) => ({ ...member, isSelf: member.isSelf || member.id === clientId.value }));
|
||||
});
|
||||
const memberChannels = computed<TreeChannel[]>(() => {
|
||||
if (channelTree.value.length) return channelTree.value;
|
||||
return [{
|
||||
id: "__current__",
|
||||
parentID: "0",
|
||||
name: currentChannelName.value,
|
||||
description: currentChannelDescription.value,
|
||||
members: currentMembers.value,
|
||||
depth: 0,
|
||||
}];
|
||||
});
|
||||
const filteredMemberChannels = computed(() => {
|
||||
const search = memberQuery.value.trim().toLowerCase();
|
||||
if (!search) return memberChannels.value;
|
||||
return memberChannels.value.filter((item) => item.name.toLowerCase().includes(search)
|
||||
|| item.members.some((member) => member.nickname.toLowerCase().includes(search)));
|
||||
});
|
||||
const whisperTargets = computed(() => [...whisperTargetIds]
|
||||
.map((id) => members.find((member) => member.id === id))
|
||||
.filter((member): member is ChannelMember => Boolean(member)));
|
||||
|
||||
watch(channelTree, (list) => {
|
||||
if (!selectedChannelId.value && list[0]) {
|
||||
selectedChannelId.value = list.find((item) => item.name === channelName.value)?.id
|
||||
?? list.find((item) => item.members.some((member) => member.id === clientId.value))?.id
|
||||
?? "";
|
||||
}
|
||||
}, { deep: true });
|
||||
|
||||
return {
|
||||
channelTree,
|
||||
currentChannel,
|
||||
currentChannelName,
|
||||
currentChannelDescription,
|
||||
currentMembers,
|
||||
memberChannels,
|
||||
filteredMemberChannels,
|
||||
whisperTargets,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { computed, nextTick, ref, watch, type Ref } from "vue";
|
||||
import type { ChannelInfo, ChannelMember, ChatMessage } from "./useVoiceWebSocket.js";
|
||||
|
||||
export type WebClientChatTab = "channel" | "server" | "private" | "events";
|
||||
|
||||
interface PrivateConversation {
|
||||
id: number;
|
||||
name: string;
|
||||
lastMessage: number;
|
||||
}
|
||||
|
||||
interface UseWebClientChatOptions {
|
||||
messages: ChatMessage[];
|
||||
members: ChannelMember[];
|
||||
currentChannel: Readonly<Ref<ChannelInfo | undefined>>;
|
||||
currentChannelName: Readonly<Ref<string>>;
|
||||
selectedChannelId: Ref<string>;
|
||||
clientId: Readonly<Ref<number>>;
|
||||
isMobileViewport: Readonly<Ref<boolean>>;
|
||||
mobileSection: Ref<"channels" | "chat" | "voice" | "more">;
|
||||
closeMemberMenu: () => void;
|
||||
sendTextMessage: (text: string, targetId?: string) => void;
|
||||
sendServerMessage: (text: string) => void;
|
||||
sendPrivateMessage: (clientId: number, text: string, conversationId?: string) => void;
|
||||
notifyPrivateMessage: () => void;
|
||||
t: (key: string, variables?: Record<string, string | number>) => string;
|
||||
}
|
||||
|
||||
export function useWebClientChat({
|
||||
messages,
|
||||
members,
|
||||
currentChannel,
|
||||
currentChannelName,
|
||||
selectedChannelId,
|
||||
clientId,
|
||||
isMobileViewport,
|
||||
mobileSection,
|
||||
closeMemberMenu,
|
||||
sendTextMessage,
|
||||
sendServerMessage,
|
||||
sendPrivateMessage,
|
||||
notifyPrivateMessage,
|
||||
t,
|
||||
}: UseWebClientChatOptions) {
|
||||
const tab = ref<WebClientChatTab>("channel");
|
||||
const privateClientId = ref(0);
|
||||
const messageDraft = ref("");
|
||||
const listElement = ref<HTMLElement | null>(null);
|
||||
|
||||
const conversations = computed<PrivateConversation[]>(() => {
|
||||
const byConversation = new Map<string, PrivateConversation>();
|
||||
for (const message of messages) {
|
||||
if (message.scope !== "private" || !message.conversationId) continue;
|
||||
const id = Number(message.conversationId);
|
||||
if (!id) continue;
|
||||
const member = members.find((candidate) => candidate.id === id);
|
||||
const existing = byConversation.get(message.conversationId);
|
||||
byConversation.set(message.conversationId, {
|
||||
id,
|
||||
name: member?.nickname ?? existing?.name ?? message.invokerName,
|
||||
lastMessage: Math.max(existing?.lastMessage ?? 0, message.timestamp),
|
||||
});
|
||||
}
|
||||
return [...byConversation.values()].sort((left, right) => right.lastMessage - left.lastMessage);
|
||||
});
|
||||
|
||||
const visibleMessages = computed(() => {
|
||||
if (tab.value === "server") return messages.filter((message) => message.scope === "server");
|
||||
if (tab.value === "private") return messages.filter((message) => message.scope === "private" && message.conversationId === String(privateClientId.value));
|
||||
if (tab.value !== "channel") return [];
|
||||
const channelId = currentChannel.value?.id;
|
||||
return messages.filter((message) => message.scope === "channel" && (!message.targetId || message.targetId === "0" || !channelId || message.targetId === channelId));
|
||||
});
|
||||
|
||||
const tabLabel = computed(() => tab.value === "channel" ? t("textChannel") : tab.value === "server" ? t("serverChat") : tab.value === "private" ? t("privateMessage") : t("eventLog"));
|
||||
const title = computed(() => tab.value === "channel"
|
||||
? t("channelChat", { channel: currentChannelName.value })
|
||||
: tab.value === "server"
|
||||
? t("serverChat")
|
||||
: tab.value === "events"
|
||||
? t("eventLog")
|
||||
: conversations.value.find((conversation) => conversation.id === privateClientId.value)?.name ?? t("privateMessage"));
|
||||
const placeholder = computed(() => tab.value === "private" ? t("privateMessagePlaceholder") : tab.value === "server" ? t("serverMessagePlaceholder") : t("sendMessagePlaceholder"));
|
||||
|
||||
function scrollToEnd(): void {
|
||||
const list = listElement.value;
|
||||
if (list) list.scrollTo({ top: list.scrollHeight, behavior: "smooth" });
|
||||
}
|
||||
|
||||
function openPrivateChat(targetClientId: number): void {
|
||||
if (!targetClientId || targetClientId === clientId.value) return;
|
||||
privateClientId.value = targetClientId;
|
||||
tab.value = "private";
|
||||
if (isMobileViewport.value) mobileSection.value = "chat";
|
||||
closeMemberMenu();
|
||||
void nextTick(scrollToEnd);
|
||||
}
|
||||
|
||||
function submitMessage(): void {
|
||||
if (!messageDraft.value.trim()) return;
|
||||
if (tab.value === "channel") sendTextMessage(messageDraft.value, currentChannel.value?.id ?? selectedChannelId.value);
|
||||
else if (tab.value === "server") sendServerMessage(messageDraft.value);
|
||||
else if (tab.value === "private" && privateClientId.value) sendPrivateMessage(privateClientId.value, messageDraft.value, String(privateClientId.value));
|
||||
messageDraft.value = "";
|
||||
}
|
||||
|
||||
watch([() => messages.length, tab, privateClientId], () => { void nextTick(scrollToEnd); });
|
||||
watch(() => messages.length, (length, previousLength) => {
|
||||
const latest = messages[length - 1];
|
||||
if (latest && length > previousLength && latest.scope === "private" && !latest.isSelf) notifyPrivateMessage();
|
||||
});
|
||||
|
||||
return {
|
||||
tab,
|
||||
privateClientId,
|
||||
messageDraft,
|
||||
listElement,
|
||||
conversations,
|
||||
visibleMessages,
|
||||
tabLabel,
|
||||
title,
|
||||
placeholder,
|
||||
openPrivateChat,
|
||||
submitMessage,
|
||||
scrollToEnd,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import { computed, nextTick, watch, type Ref } from "vue";
|
||||
import type { WebClientChatTab } from "./useWebClientChat.js";
|
||||
import type { TreeChannel } from "./useWebClientChannels.js";
|
||||
import { combineTeamSpeakTarget, isValidTeamSpeakPort } from "../services/teamspeak-target.js";
|
||||
|
||||
interface ChannelPasswordDialogState {
|
||||
open: boolean;
|
||||
channelId: string;
|
||||
password: string;
|
||||
error: string;
|
||||
submitting: boolean;
|
||||
}
|
||||
|
||||
interface ServerPasswordDialogState {
|
||||
open: boolean;
|
||||
password: string;
|
||||
errorCode: string;
|
||||
}
|
||||
|
||||
interface UseWebClientConnectionOptions {
|
||||
initialized: Readonly<Ref<boolean>>;
|
||||
accessMode: Readonly<Ref<string>>;
|
||||
isConnecting: Readonly<Ref<boolean>>;
|
||||
errorCode: Readonly<Ref<string>>;
|
||||
channelSwitchedChannelId: Readonly<Ref<string>>;
|
||||
nickname: Ref<string>;
|
||||
channelName: Ref<string>;
|
||||
serverHost: Ref<string>;
|
||||
serverPort: Ref<string>;
|
||||
serverPassword: Ref<string>;
|
||||
rememberIdentity: Readonly<Ref<boolean>>;
|
||||
identityMaterial: Ref<string>;
|
||||
accelerationRelayId: Ref<string>;
|
||||
inviteToken: string;
|
||||
selectedChannelId: Ref<string>;
|
||||
channels: Readonly<Ref<TreeChannel[]>>;
|
||||
clientId: Readonly<Ref<number>>;
|
||||
channelPasswordDialog: ChannelPasswordDialogState;
|
||||
serverPasswordDialog: ServerPasswordDialogState;
|
||||
chatTab: Ref<WebClientChatTab>;
|
||||
connect: (target: string, channel: string, nickname: string, password: string, identity: string, remember: boolean, invite: string, useRelay: boolean, relayId: string) => void;
|
||||
disconnect: () => void;
|
||||
switchChannel: (channelId: string, password?: string) => void;
|
||||
clearError: () => void;
|
||||
saveNickname: (nickname: string) => void;
|
||||
showToast: (message: string) => void;
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
export function useWebClientConnection({
|
||||
initialized,
|
||||
accessMode,
|
||||
isConnecting,
|
||||
errorCode,
|
||||
channelSwitchedChannelId,
|
||||
nickname,
|
||||
channelName,
|
||||
serverHost,
|
||||
serverPort,
|
||||
serverPassword,
|
||||
rememberIdentity,
|
||||
identityMaterial,
|
||||
accelerationRelayId,
|
||||
inviteToken,
|
||||
selectedChannelId,
|
||||
channels,
|
||||
clientId,
|
||||
channelPasswordDialog,
|
||||
serverPasswordDialog,
|
||||
chatTab,
|
||||
connect,
|
||||
disconnect,
|
||||
switchChannel,
|
||||
clearError,
|
||||
saveNickname,
|
||||
showToast,
|
||||
t,
|
||||
}: UseWebClientConnectionOptions) {
|
||||
const canJoin = computed(() => Boolean(
|
||||
initialized.value
|
||||
&& nickname.value.trim()
|
||||
&& (accessMode.value === "fixed" || (serverHost.value.trim() && isValidTeamSpeakPort(serverPort.value))),
|
||||
));
|
||||
|
||||
function currentServerTarget(): string {
|
||||
return combineTeamSpeakTarget(serverHost.value, serverPort.value);
|
||||
}
|
||||
|
||||
function doConnect(): void {
|
||||
if (!canJoin.value || isConnecting.value) return;
|
||||
clearError();
|
||||
nickname.value = nickname.value.trim();
|
||||
saveNickname(nickname.value);
|
||||
if (accessMode.value === "open") {
|
||||
serverHost.value = serverHost.value.trim();
|
||||
serverPort.value = serverPort.value.trim();
|
||||
}
|
||||
selectedChannelId.value = "";
|
||||
// Keep the password available for retry even if the target is administrator-managed.
|
||||
connect(
|
||||
currentServerTarget(),
|
||||
channelName.value.trim(),
|
||||
nickname.value,
|
||||
serverPassword.value,
|
||||
rememberIdentity.value ? identityMaterial.value : "",
|
||||
rememberIdentity.value,
|
||||
inviteToken,
|
||||
Boolean(accelerationRelayId.value),
|
||||
accelerationRelayId.value,
|
||||
);
|
||||
}
|
||||
|
||||
function doDisconnect(): void {
|
||||
disconnect();
|
||||
selectedChannelId.value = "";
|
||||
showToast(t("leftToast"));
|
||||
}
|
||||
|
||||
function submitServerPassword(): void {
|
||||
if (!serverPasswordDialog.open || !serverPasswordDialog.password) return;
|
||||
serverPassword.value = serverPasswordDialog.password;
|
||||
serverPasswordDialog.open = false;
|
||||
serverPasswordDialog.password = "";
|
||||
serverPasswordDialog.errorCode = "";
|
||||
doConnect();
|
||||
}
|
||||
|
||||
function cancelServerPassword(): void {
|
||||
serverPasswordDialog.open = false;
|
||||
serverPasswordDialog.password = "";
|
||||
serverPasswordDialog.errorCode = "";
|
||||
clearError();
|
||||
}
|
||||
|
||||
function selectChannel(channel: TreeChannel): void {
|
||||
selectedChannelId.value = channel.id;
|
||||
channelName.value = channel.name;
|
||||
chatTab.value = "channel";
|
||||
switchChannel(channel.id);
|
||||
}
|
||||
|
||||
function submitChannelPassword(): void {
|
||||
if (!channelPasswordDialog.open || !channelPasswordDialog.channelId || !channelPasswordDialog.password) return;
|
||||
channelPasswordDialog.error = "";
|
||||
channelPasswordDialog.submitting = true;
|
||||
switchChannel(channelPasswordDialog.channelId, channelPasswordDialog.password);
|
||||
}
|
||||
|
||||
function cancelChannelPassword(): void {
|
||||
const ownChannel = channels.value.find((item) => item.members.some((member) => member.id === clientId.value));
|
||||
if (ownChannel) selectedChannelId.value = ownChannel.id;
|
||||
channelPasswordDialog.open = false;
|
||||
channelPasswordDialog.channelId = "";
|
||||
channelPasswordDialog.password = "";
|
||||
channelPasswordDialog.error = "";
|
||||
channelPasswordDialog.submitting = false;
|
||||
clearError();
|
||||
}
|
||||
|
||||
function selectChannelById(): void {
|
||||
const channel = channels.value.find((item) => item.id === selectedChannelId.value);
|
||||
if (channel) selectChannel(channel);
|
||||
}
|
||||
|
||||
watch(errorCode, (code) => {
|
||||
if (code !== "CHANNEL_PASSWORD_REQUIRED" || !selectedChannelId.value) return;
|
||||
channelPasswordDialog.open = true;
|
||||
channelPasswordDialog.channelId = selectedChannelId.value;
|
||||
channelPasswordDialog.password = "";
|
||||
channelPasswordDialog.error = t("channelPasswordRetry");
|
||||
channelPasswordDialog.submitting = false;
|
||||
clearError();
|
||||
void nextTick(() => document.getElementById("channel-password-input")?.focus());
|
||||
});
|
||||
watch(errorCode, (code) => {
|
||||
if (code !== "SERVER_PASSWORD_REQUIRED" && code !== "INVALID_SERVER_PASSWORD") return;
|
||||
serverPasswordDialog.open = true;
|
||||
serverPasswordDialog.password = "";
|
||||
serverPasswordDialog.errorCode = code;
|
||||
clearError();
|
||||
void nextTick(() => document.getElementById("retry-server-password-input")?.focus());
|
||||
});
|
||||
watch(channelSwitchedChannelId, (channelId) => {
|
||||
if (!channelPasswordDialog.open || !channelId || channelId !== channelPasswordDialog.channelId) return;
|
||||
channelPasswordDialog.open = false;
|
||||
channelPasswordDialog.channelId = "";
|
||||
channelPasswordDialog.password = "";
|
||||
channelPasswordDialog.error = "";
|
||||
channelPasswordDialog.submitting = false;
|
||||
});
|
||||
|
||||
return {
|
||||
canJoin,
|
||||
currentServerTarget,
|
||||
doConnect,
|
||||
doDisconnect,
|
||||
submitServerPassword,
|
||||
cancelServerPassword,
|
||||
selectChannel,
|
||||
submitChannelPassword,
|
||||
cancelChannelPassword,
|
||||
selectChannelById,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
import type { Ref } from "vue";
|
||||
|
||||
import { webClientTranslations, type Language } from "../i18n/web-client.js";
|
||||
|
||||
export function useWebClientI18n(language: Ref<Language>) {
|
||||
|
||||
function t(key: string, variables: Record<string, string | number> = {}) {
|
||||
let value = webClientTranslations[language.value][key] ?? webClientTranslations.en[key] ?? webClientTranslations.zh[key] ?? key;
|
||||
for (const [name, replacement] of Object.entries(variables)) value = value.replaceAll(`{{${name}}}`, String(replacement));
|
||||
return value;
|
||||
}
|
||||
|
||||
function localizedMessage(message: string) {
|
||||
if (language.value === "zh") return message;
|
||||
const localizedExact: Record<string, string> = language.value === "ru" ? {
|
||||
"该服务器需要密码,请输入密码后重试": "Для этого сервера требуется пароль. Введите его и повторите попытку",
|
||||
"服务器密码错误,请重新输入": "Неверный пароль сервера. Введите его ещё раз",
|
||||
"昵称长度不符合 TeamSpeak 服务器要求,至少 3 个字符,请修改后重试": "Длина имени не соответствует требованиям TeamSpeak (не менее 3 символов). Измените имя и повторите попытку",
|
||||
"TeamSpeak 服务器地址无效": "Неверный адрес сервера TeamSpeak",
|
||||
"找不到 TeamSpeak 服务器主机名,请检查地址": "Не удалось найти сервер TeamSpeak. Проверьте адрес",
|
||||
"无法到达 TeamSpeak 服务器,请检查网络或地址": "Сервер TeamSpeak недоступен. Проверьте сеть или адрес",
|
||||
"TeamSpeak 服务器拒绝了连接,请检查端口和服务状态": "Сервер TeamSpeak отклонил подключение. Проверьте порт и состояние службы",
|
||||
"连接 TeamSpeak 超时,请检查网络或服务器状态": "Истекло время подключения к TeamSpeak. Проверьте сеть и состояние сервера",
|
||||
"你没有执行此操作的权限": "У вас нет права выполнять это действие",
|
||||
} : {
|
||||
"该服务器需要密码,请输入密码后重试": "このサーバーにはパスワードが必要です。入力して再試行してください",
|
||||
"服务器密码错误,请重新输入": "サーバーパスワードが正しくありません。もう一度入力してください",
|
||||
"昵称长度不符合 TeamSpeak 服务器要求,至少 3 个字符,请修改后重试": "ニックネームの長さが TeamSpeak の要件を満たしていません(3文字以上)。変更して再試行してください",
|
||||
"TeamSpeak 服务器地址无效": "TeamSpeak サーバーアドレスが正しくありません",
|
||||
"找不到 TeamSpeak 服务器主机名,请检查地址": "TeamSpeak サーバーが見つかりません。アドレスを確認してください",
|
||||
"无法到达 TeamSpeak 服务器,请检查网络或地址": "TeamSpeak サーバーに到達できません。ネットワークまたはアドレスを確認してください",
|
||||
"TeamSpeak 服务器拒绝了连接,请检查端口和服务状态": "TeamSpeak サーバーが接続を拒否しました。ポートとサービスの状態を確認してください",
|
||||
"连接 TeamSpeak 超时,请检查网络或服务器状态": "TeamSpeak への接続がタイムアウトしました。ネットワークとサーバーの状態を確認してください",
|
||||
"你没有执行此操作的权限": "この操作を実行する権限がありません",
|
||||
};
|
||||
if ((language.value === "ru" || language.value === "ja") && localizedExact[message]) return localizedExact[message];
|
||||
const errorCodeMatch = message.match(/错误代码:([A-Z0-9_-]{1,64}))(?::([^,。]+))?/);
|
||||
if (errorCodeMatch) {
|
||||
const code = errorCodeMatch[1];
|
||||
const detail = errorCodeMatch[2] ? `: ${errorCodeMatch[2]}` : "";
|
||||
const operation = message.startsWith("操作失败");
|
||||
if (language.value === "de") return `${operation ? "Vorgang" : "TeamSpeak-Verbindung"} fehlgeschlagen (Fehlercode: ${code})${detail}. Prüfe Eingaben, Netzwerk und Serverstatus`;
|
||||
if (language.value === "ru") return `${operation ? "Операция" : "Подключение TeamSpeak"} не выполнена (код ошибки: ${code})${detail}. Проверьте ввод, сеть и состояние сервера`;
|
||||
if (language.value === "ja") return `${operation ? "操作" : "TeamSpeak 接続"}に失敗しました(エラーコード: ${code})${detail}。入力、ネットワーク、サーバーの状態を確認してください`;
|
||||
return `${operation ? "Operation" : "TeamSpeak connection"} failed (error code: ${code})${detail}. Check your input, network, and server status`;
|
||||
}
|
||||
const exact: Record<string, string> = {
|
||||
"语音功能需要 HTTPS 安全连接": "Voice requires a secure HTTPS connection",
|
||||
"当前浏览器不支持麦克风访问": "This browser does not support microphone access",
|
||||
"当前浏览器不支持 Web Audio 音频处理": "This browser does not support Web Audio processing",
|
||||
"当前浏览器不支持音频解码,请使用最新版 Chrome 或 Edge": "Audio decoding is unavailable. Use the latest Chrome or Edge",
|
||||
"当前浏览器不支持扬声器设备选择,将使用默认输出设备": "Output device selection is not supported by this browser. Using the default output device",
|
||||
"所选扬声器当前不可用": "The selected speaker is not available",
|
||||
"连接服务器失败,请检查邀请链接或服务器状态": "Could not connect. Check the invite link or server status",
|
||||
"请求来源不受信任,请从正确的网站入口重新打开": "The request origin is not trusted. Reopen the official WebSpeak page",
|
||||
"WebSpeak 尚未完成配置,请联系管理员": "WebSpeak has not been configured yet. Contact the administrator",
|
||||
"请求过于频繁,请稍后重试": "Too many requests. Try again shortly",
|
||||
"当前中继加速不可用,请关闭加速或联系管理员": "The selected relay is unavailable. Turn off relay mode or contact the administrator",
|
||||
"邀请链接已失效或已被撤销": "The invite link is invalid, expired, or revoked",
|
||||
"TeamSpeak 连接已断开": "The TeamSpeak connection was closed",
|
||||
"连接已断开": "The connection was closed",
|
||||
"此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试": "This TeamSpeak identity is already used by another browser page. Close that connection or clear ‘Remember identity’ and try again",
|
||||
"TeamSpeak 服务器地址无效": "The TeamSpeak server address is invalid",
|
||||
"昵称长度不符合 TeamSpeak 服务器要求,至少 3 个字符,请修改后重试": "The nickname length does not meet the TeamSpeak server requirements (at least 3 characters). Change it and try again",
|
||||
"TeamSpeak 服务器连接失败": "Could not connect to the TeamSpeak server",
|
||||
"找不到 TeamSpeak 服务器主机名,请检查地址": "The TeamSpeak server hostname could not be resolved. Check the address",
|
||||
"无法到达 TeamSpeak 服务器,请检查网络或地址": "The TeamSpeak server is unreachable. Check the network or address",
|
||||
"TeamSpeak 服务器拒绝了连接,请检查端口和服务状态": "The TeamSpeak server refused the connection. Check the port and server status",
|
||||
"TeamSpeak 连接被服务器或网络重置,请稍后重试": "The TeamSpeak connection was reset by the server or network. Try again shortly",
|
||||
"连接 TeamSpeak 超时,请检查网络或服务器状态": "The TeamSpeak connection timed out. Check the network or server status",
|
||||
"该服务器需要密码,请输入密码后重试": "This server requires a password. Enter it and try again",
|
||||
"服务器密码错误,请重新输入": "The server password is incorrect. Enter it again",
|
||||
"TeamSpeak 协议协商失败": "TeamSpeak protocol negotiation failed",
|
||||
"TeamSpeak 服务器拒绝了连接": "The TeamSpeak server rejected the connection",
|
||||
"TeamSpeak 连接失败,请检查地址、网络或服务器状态": "TeamSpeak connection failed. Check the address, network, or server status",
|
||||
"服务器当前已满,请稍后重试": "The server is full. Try again shortly",
|
||||
"服务器当前已满或拒绝了连接,请稍后重试": "The server is full or rejected the connection. Try again shortly",
|
||||
"WebSpeak 尚未配置 TeamSpeak 目标。": "The WebSpeak TeamSpeak target has not been configured",
|
||||
"此 TeamSpeak 服务器地址不允许连接": "This TeamSpeak server address is not allowed",
|
||||
"请输入有效的昵称": "Enter a valid nickname",
|
||||
"消息格式无效": "The message format is invalid",
|
||||
"请求标识无效": "The request id is invalid",
|
||||
"不支持的操作": "This operation is not supported",
|
||||
"操作参数无效": "The operation payload is invalid",
|
||||
"频道标识无效": "The channel id is invalid",
|
||||
"成员标识无效": "The member id is invalid",
|
||||
"频道密码无效": "The channel password is invalid",
|
||||
"文字消息无效": "The text message is invalid",
|
||||
"戳一戳消息无效": "The poke message is invalid",
|
||||
"离开状态无效": "The away status is invalid",
|
||||
"音频帧格式无效": "The audio frame is invalid",
|
||||
"私语目标无效": "The whisper targets are invalid",
|
||||
"私语状态无效": "The whisper state is invalid",
|
||||
"请先选择私语目标": "Choose a whisper target first",
|
||||
"私语目标已离线": "A whisper target is offline",
|
||||
"TeamSpeak 会话尚未就绪": "The TeamSpeak session is not ready",
|
||||
"频道切换失败": "Channel switch failed",
|
||||
"该频道需要密码": "This channel requires a password",
|
||||
"该频道已满": "This channel is full",
|
||||
"你没有执行此操作的权限": "You do not have permission to perform this action",
|
||||
"不能移动自己的客户端": "You cannot move yourself",
|
||||
"目标频道不可用": "The target channel is unavailable",
|
||||
"成员已离线或当前不可见": "The member is offline or no longer visible",
|
||||
"成员已离线": "This member is offline",
|
||||
"操作失败": "The operation failed",
|
||||
"语音会话票据缺失或已过期,请返回列表重新进入语音空间": "The voice session token is missing or expired. Return to the list and enter the voice space again",
|
||||
"语音网关拒绝了本次连接:身份无效,请取消“保持身份”后重新进入": "The voice gateway rejected the connection because the identity is invalid. Clear ‘Remember identity’ and try again",
|
||||
"语音网关拒绝了本次连接:身份无效或无法在此页面使用,请取消“保持身份”后重新进入": "The voice gateway rejected the connection because the identity is invalid or unavailable on this page. Clear ‘Remember identity’ and try again",
|
||||
"当前中继加速不可用,请关闭加速后重试或联系管理员": "The selected relay is unavailable. Turn off relay mode and try again, or contact the administrator",
|
||||
"与语音网关的网络连接异常中断(掉线或代理断开),并非 TeamSpeak 服务器拒绝连接,请检查网络后重新进入": "The voice gateway connection was interrupted (offline or proxy disconnected); the TeamSpeak server did not reject it. Check your network and enter again",
|
||||
"语音网关会话意外结束,请重新进入语音空间": "The voice gateway session ended unexpectedly. Enter the voice space again",
|
||||
"语音网关未能创建 TeamSpeak 客户端(服务器可能已关闭或地址不可达),请确认服务器地址或稍后重试": "The voice gateway could not create a TeamSpeak client. The server may be offline or unreachable; check the address and try again",
|
||||
"该昵称已被服务器上的其他用户占用,请更换昵称": "This nickname is already in use on the server. Choose another one",
|
||||
"该昵称已被占用,请更换昵称": "This nickname is already in use. Choose another one",
|
||||
"你的身份安全等级低于该服务器要求,请提升后重试": "Your identity security level is below what this server requires. Raise it and try again",
|
||||
"该身份建立的连接数已达上限,请关闭其他连接后重试": "This identity reached its connection limit. Close the other connections and try again",
|
||||
"客户端版本过旧,服务器拒绝连接,请升级后重试": "Your client version is outdated and the server rejected the connection. Update and try again",
|
||||
"客户端版本过旧,服务器拒绝了该操作": "Your client version is outdated, so the server rejected this action",
|
||||
"操作过于频繁,已被服务器洪水防护暂时拒绝,请稍后重试": "Too many requests: the server flood protection rejected you temporarily. Try again shortly",
|
||||
"操作过于频繁,请稍后重试": "Too many requests. Try again shortly",
|
||||
"你已被该服务器封禁,无法连接": "You are banned from this server, so the connection is refused",
|
||||
"你已被该服务器封禁": "You are banned from this server",
|
||||
"你已被服务器移出": "You were removed from the server",
|
||||
"TeamSpeak 服务器正在关闭,暂时无法连接": "The TeamSpeak server is shutting down and is unreachable right now",
|
||||
"TeamSpeak 服务器未能完成连接初始化,请检查地址、端口或稍后重试": "The TeamSpeak server could not finish initialising the connection. Check the address and port, or try again shortly",
|
||||
"TeamSpeak 服务器拒绝了参数,通常是昵称长度或格式不合规": "The TeamSpeak server rejected the parameters, usually because the nickname length or format is invalid",
|
||||
};
|
||||
if (language.value === "en" && exact[message]) return exact[message];
|
||||
if (message.startsWith("麦克风访问失败:")) {
|
||||
const detail = message.slice(8);
|
||||
if (language.value === "ru") return `Не удалось получить доступ к микрофону: ${detail}`;
|
||||
if (language.value === "ja") return `マイクへのアクセスに失敗しました: ${detail}`;
|
||||
return language.value === "de" ? `Mikrofonzugriff fehlgeschlagen: ${detail}` : `Microphone access failed: ${detail}`;
|
||||
}
|
||||
if (message.startsWith("切换失败:")) {
|
||||
const detail = message.slice(5);
|
||||
if (language.value === "ru") return `Не удалось переключить канал: ${detail}`;
|
||||
if (language.value === "ja") return `チャンネルの切り替えに失敗しました: ${detail}`;
|
||||
return language.value === "de" ? `Kanalwechsel fehlgeschlagen: ${detail}` : `Channel switch failed: ${detail}`;
|
||||
}
|
||||
if (language.value === "de") {
|
||||
const german: Record<string, string> = {
|
||||
"语音功能需要 HTTPS 安全连接": "Für Sprachfunktionen ist eine sichere HTTPS-Verbindung erforderlich",
|
||||
"当前浏览器不支持麦克风访问": "Dieser Browser unterstützt keinen Mikrofonzugriff",
|
||||
"当前浏览器不支持 Web Audio 音频处理": "Dieser Browser unterstützt keine Web-Audio-Verarbeitung",
|
||||
"连接服务器失败,请检查邀请链接或服务器状态": "Verbindung fehlgeschlagen. Prüfe den Einladungslink oder den Serverstatus",
|
||||
"请求来源不受信任,请从正确的网站入口重新打开": "Die Anfragequelle ist nicht vertrauenswürdig. Öffne die offizielle WebSpeak-Seite erneut",
|
||||
"WebSpeak 尚未完成配置,请联系管理员": "WebSpeak wurde noch nicht konfiguriert. Wende dich an den Administrator",
|
||||
"请求过于频繁,请稍后重试": "Zu viele Anfragen. Versuche es gleich erneut",
|
||||
"当前中继加速不可用,请关闭加速或联系管理员": "Das ausgewählte Relay ist nicht verfügbar. Deaktiviere den Relay-Modus oder wende dich an den Administrator",
|
||||
"邀请链接已失效或已被撤销": "Der Einladungslink ist ungültig, abgelaufen oder widerrufen",
|
||||
"TeamSpeak 连接已断开": "Die TeamSpeak-Verbindung wurde getrennt",
|
||||
"连接已断开": "Die Verbindung wurde getrennt",
|
||||
"TeamSpeak 服务器地址无效": "Die TeamSpeak-Serveradresse ist ungültig",
|
||||
"昵称长度不符合 TeamSpeak 服务器要求,至少 3 个字符,请修改后重试": "Die Länge des Spitznamens entspricht nicht den Anforderungen des TeamSpeak-Servers (mindestens 3 Zeichen). Ändere ihn und versuche es erneut",
|
||||
"请输入有效的昵称": "Gib einen gültigen Nicknamen ein",
|
||||
"找不到 TeamSpeak 服务器主机名,请检查地址": "Der TeamSpeak-Servername konnte nicht aufgelöst werden. Prüfe die Adresse",
|
||||
"无法到达 TeamSpeak 服务器,请检查网络或地址": "Der TeamSpeak-Server ist nicht erreichbar. Prüfe Netzwerk und Adresse",
|
||||
"TeamSpeak 服务器拒绝了连接,请检查端口和服务状态": "Der TeamSpeak-Server hat die Verbindung abgelehnt. Prüfe Port und Serverstatus",
|
||||
"TeamSpeak 连接被服务器或网络重置,请稍后重试": "Die TeamSpeak-Verbindung wurde vom Server oder Netzwerk zurückgesetzt. Versuche es später erneut",
|
||||
"连接 TeamSpeak 超时,请检查网络或服务器状态": "Die TeamSpeak-Verbindung hat das Zeitlimit überschritten. Prüfe Netzwerk und Serverstatus",
|
||||
"该服务器需要密码,请输入密码后重试": "Dieser Server benötigt ein Passwort. Gib es ein und versuche es erneut",
|
||||
"服务器密码错误,请重新输入": "Das Serverpasswort ist falsch. Gib es erneut ein",
|
||||
"TeamSpeak 协议协商失败": "Die Aushandlung des TeamSpeak-Protokolls ist fehlgeschlagen",
|
||||
"TeamSpeak 服务器拒绝了连接": "Der TeamSpeak-Server hat die Verbindung abgelehnt",
|
||||
"TeamSpeak 连接失败,请检查地址、网络或服务器状态": "Die TeamSpeak-Verbindung ist fehlgeschlagen. Prüfe Adresse, Netzwerk und Serverstatus",
|
||||
"服务器当前已满或拒绝了连接,请稍后重试": "Der Server ist voll oder hat die Verbindung abgelehnt. Versuche es später erneut",
|
||||
"服务器当前已满,请稍后重试": "Der Server ist derzeit voll. Versuche es später erneut",
|
||||
"该昵称已被服务器上的其他用户占用,请更换昵称": "Dieser Spitzname wird auf dem Server bereits verwendet. Wähle einen anderen",
|
||||
"该昵称已被占用,请更换昵称": "Dieser Spitzname wird bereits verwendet. Wähle einen anderen",
|
||||
"你的身份安全等级低于该服务器要求,请提升后重试": "Deine Sicherheitsstufe liegt unter der Anforderung dieses Servers. Erhöhe sie und versuche es erneut",
|
||||
"该身份建立的连接数已达上限,请关闭其他连接后重试": "Diese Identität hat ihr Verbindungslimit erreicht. Schließe die anderen Verbindungen und versuche es erneut",
|
||||
"客户端版本过旧,服务器拒绝连接,请升级后重试": "Deine Client-Version ist veraltet und der Server hat die Verbindung abgelehnt. Aktualisiere und versuche es erneut",
|
||||
"客户端版本过旧,服务器拒绝了该操作": "Deine Client-Version ist veraltet, daher hat der Server diese Aktion abgelehnt",
|
||||
"操作过于频繁,已被服务器洪水防护暂时拒绝,请稍后重试": "Zu viele Anfragen: Der Flood-Schutz des Servers hat dich vorübergehend abgewiesen. Versuche es gleich erneut",
|
||||
"操作过于频繁,请稍后重试": "Zu viele Anfragen. Versuche es gleich erneut",
|
||||
"你已被该服务器封禁,无法连接": "Du wurdest von diesem Server gebannt und kannst nicht verbinden",
|
||||
"你已被该服务器封禁": "Du wurdest von diesem Server gebannt",
|
||||
"你已被服务器移出": "Du wurdest vom Server entfernt",
|
||||
"TeamSpeak 服务器正在关闭,暂时无法连接": "Der TeamSpeak-Server wird heruntergefahren und ist derzeit nicht erreichbar",
|
||||
"TeamSpeak 服务器未能完成连接初始化,请检查地址、端口或稍后重试": "Der TeamSpeak-Server konnte die Verbindungsinitialisierung nicht abschließen. Prüfe Adresse und Port oder versuche es später erneut",
|
||||
"TeamSpeak 服务器拒绝了参数,通常是昵称长度或格式不合规": "Der TeamSpeak-Server hat die Parameter abgelehnt, meist wegen ungültiger Länge oder ungültigen Formats des Spitznamens",
|
||||
"此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试": "Diese TeamSpeak-Identität wird bereits in einem anderen Browser-Tab verwendet. Schließe die andere Verbindung oder deaktiviere „Identität merken“ und versuche es erneut",
|
||||
"语音会话票据缺失或已过期,请返回列表重新进入语音空间": "Der Sprachsitzungs-Token fehlt oder ist abgelaufen. Kehre zur Liste zurück und tritt dem Sprachraum erneut bei",
|
||||
"语音网关拒绝了本次连接:身份无效,请取消“保持身份”后重新进入": "Das Sprach-Gateway hat die Verbindung abgelehnt: Die Identität ist ungültig. Deaktiviere „Identität merken“ und tritt erneut bei",
|
||||
"语音网关拒绝了本次连接:身份无效或无法在此页面使用,请取消“保持身份”后重新进入": "Das Sprach-Gateway hat die Verbindung abgelehnt: Die Identität ist ungültig oder kann auf dieser Seite nicht verwendet werden. Deaktiviere „Identität merken“ und tritt erneut bei",
|
||||
"当前中继加速不可用,请关闭加速后重试或联系管理员": "Der beschleunigte Relay-Modus ist nicht verfügbar. Deaktiviere ihn und versuche es erneut oder wende dich an den Administrator",
|
||||
"与语音网关的网络连接异常中断(掉线或代理断开),并非 TeamSpeak 服务器拒绝连接,请检查网络后重新进入": "Die Verbindung zum Sprach-Gateway wurde unerwartet unterbrochen (Offline oder Proxy getrennt) – der TeamSpeak-Server hat die Verbindung nicht abgelehnt. Prüfe deine Netzwerkverbindung und tritt erneut bei",
|
||||
"语音网关会话意外结束,请重新进入语音空间": "Die Sprach-Gateway-Sitzung wurde unerwartet beendet. Tritt dem Sprachraum erneut bei",
|
||||
"语音网关未能创建 TeamSpeak 客户端(服务器可能已关闭或地址不可达),请确认服务器地址或稍后重试": "Das Sprach-Gateway konnte keinen TeamSpeak-Client erstellen (der Server ist möglicherweise aus oder nicht erreichbar). Prüfe die Serveradresse oder versuche es später erneut",
|
||||
"消息格式无效": "Ungültiges Nachrichtenformat",
|
||||
"请求标识无效": "Ungültige Anforderungs-ID",
|
||||
"不支持的操作": "Nicht unterstützte Operation",
|
||||
"操作参数无效": "Ungültige Operationsparameter",
|
||||
"频道标识无效": "Ungültige Kanal-ID",
|
||||
"频道密码无效": "Ungültiges Kanalpasswort",
|
||||
"成员标识无效": "Ungültige Mitglieds-ID",
|
||||
"文字消息无效": "Ungültige Textnachricht",
|
||||
"戳一戳消息无效": "Ungültige Poke-Nachricht",
|
||||
"离开状态无效": "Ungültiger Abwesenheitsstatus",
|
||||
"音频帧格式无效": "Ungültiges Audio-Frame-Format",
|
||||
"成员音量无效": "Ungültige Mitgliedslautstärke",
|
||||
"私语目标无效": "Ungültige Flüsterziele",
|
||||
"私语状态无效": "Ungültiger Flüsterstatus",
|
||||
"请先选择私语目标": "Wähle zuerst ein Flüsterziel",
|
||||
"TeamSpeak 会话尚未就绪": "Die TeamSpeak-Sitzung ist noch nicht bereit",
|
||||
"频道切换失败": "Kanalwechsel fehlgeschlagen",
|
||||
"该频道需要密码": "Dieser Kanal erfordert ein Passwort",
|
||||
"该频道已满": "Dieser Kanal ist voll",
|
||||
"你没有执行此操作的权限": "Du hast keine Berechtigung für diese Aktion",
|
||||
"不能移动自己的客户端": "Du kannst dich nicht selbst verschieben",
|
||||
"目标频道不可用": "Der Zielkanal ist nicht verfügbar",
|
||||
"成员已离线或当前不可见": "Das Mitglied ist offline oder nicht mehr sichtbar",
|
||||
"成员已离线": "Das Mitglied ist offline",
|
||||
"操作失败": "Operation fehlgeschlagen",
|
||||
};
|
||||
if (german[message]) return german[message];
|
||||
if (message.startsWith("麦克风访问失败:")) return `Mikrofonzugriff fehlgeschlagen: ${message.slice(8)}`;
|
||||
if (message.startsWith("麦克风声音未能发送:")) return `Mikrofon-Audio konnte nicht gesendet werden: ${message.slice(10)}`;
|
||||
if (message.startsWith("音频链路异常")) return message.replace("音频链路异常", "Audioverbindung fehlerhaft");
|
||||
}
|
||||
if (language.value === "ru") return exact[message] ?? "Не удалось выполнить операцию. Проверьте ввод, сеть и состояние сервера";
|
||||
if (language.value === "ja") return exact[message] ?? "操作に失敗しました。入力、ネットワーク、サーバーの状態を確認してください";
|
||||
return exact[message] ?? message;
|
||||
}
|
||||
|
||||
function localizedAudioNotice(code: string, message: string) {
|
||||
if (language.value === "zh") return message;
|
||||
const normalizedCode = visibleErrorCode(code || "AUDIO_NOTICE");
|
||||
const messages: Record<string, { en: string; de: string; ru: string; ja: string }> = {
|
||||
WEBRTC_FALLBACK: {
|
||||
en: `WebRTC realtime voice is unavailable (error code: ${normalizedCode}). Compatibility transport is active; latency and audio quality may be lower`,
|
||||
de: `Echtzeitstimme über WebRTC ist nicht verfügbar (Fehlercode: ${normalizedCode}). Der Kompatibilitätstransport ist aktiv; Latenz und Audioqualität können schlechter sein`,
|
||||
ru: `Голосовая связь WebRTC недоступна (код ошибки: ${normalizedCode}). Используется совместимый транспорт; задержка и качество звука могут быть ниже`,
|
||||
ja: `WebRTC のリアルタイム音声は利用できません(エラーコード: ${normalizedCode})。互換トランスポートを使用するため、遅延や音質が低下する場合があります`,
|
||||
},
|
||||
PLAYBACK_BLOCKED: {
|
||||
en: "The browser blocked automatic audio playback. Click the page or allow audio playback for this site",
|
||||
de: "Der Browser hat die automatische Audiowiedergabe blockiert. Klicke auf die Seite oder erlaube die Audiowiedergabe für diese Website",
|
||||
ru: "Браузер заблокировал автоматическое воспроизведение. Нажмите на страницу или разрешите воспроизведение для этого сайта",
|
||||
ja: "ブラウザが自動再生をブロックしました。ページをクリックするか、このサイトの再生を許可してください",
|
||||
},
|
||||
DEVICE_LIST_UNAVAILABLE: {
|
||||
en: "Audio devices could not be listed. The browser default devices will be used",
|
||||
de: "Audiogeräte konnten nicht aufgelistet werden. Die Standardgeräte des Browsers werden verwendet",
|
||||
ru: "Не удалось получить список аудиоустройств. Будут использованы устройства браузера по умолчанию",
|
||||
ja: "オーディオデバイスを一覧表示できません。ブラウザのデフォルトデバイスを使用します",
|
||||
},
|
||||
AUDIO_CONTEXT_SUSPENDED: {
|
||||
en: "Browser audio processing is paused. Click the page once to resume microphone and speaker audio",
|
||||
de: "Die Audioverarbeitung des Browsers ist pausiert. Klicke einmal auf die Seite, um Mikrofon und Lautsprecher fortzusetzen",
|
||||
ru: "Обработка звука браузером приостановлена. Нажмите на страницу, чтобы возобновить работу микрофона и динамиков",
|
||||
ja: "ブラウザの音声処理が一時停止しています。ページを一度クリックしてマイクとスピーカーを再開してください",
|
||||
},
|
||||
AUDIO_ENCODER_UNAVAILABLE: {
|
||||
en: `Microphone audio could not be encoded (error code: ${normalizedCode}). Other members may not hear you`,
|
||||
de: `Mikrofon-Audio konnte nicht kodiert werden (Fehlercode: ${normalizedCode}). Andere Mitglieder hören dich möglicherweise nicht`,
|
||||
ru: `Не удалось кодировать звук микрофона (код ошибки: ${normalizedCode}). Другие участники могут вас не слышать`,
|
||||
ja: `マイク音声をエンコードできませんでした(エラーコード: ${normalizedCode})。他のメンバーに音声が届かない可能性があります`,
|
||||
},
|
||||
};
|
||||
const locale = language.value === "de" ? "de" : language.value === "ru" ? "ru" : language.value === "ja" ? "ja" : "en";
|
||||
return messages[code]?.[locale] ?? localizedMessage(message);
|
||||
}
|
||||
|
||||
function visibleErrorCode(code: string): string {
|
||||
const normalized = String(code || "CONNECTION_FAILED")
|
||||
.trim()
|
||||
.toUpperCase()
|
||||
.replace(/[^A-Z0-9_-]+/g, "_")
|
||||
.replace(/^_+|_+$/g, "");
|
||||
return (normalized || "CONNECTION_FAILED").slice(0, 64);
|
||||
}
|
||||
|
||||
return { t, localizedMessage, localizedAudioNotice, visibleErrorCode };
|
||||
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
import { computed, reactive, ref, type Ref } from "vue";
|
||||
import type { ChannelMember } from "./useVoiceWebSocket.js";
|
||||
import type { TreeChannel } from "./useWebClientChannels.js";
|
||||
|
||||
export interface MemberMenuState {
|
||||
member: ChannelMember;
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
interface UseWebClientMembersOptions {
|
||||
channels: Readonly<Ref<TreeChannel[]>>;
|
||||
currentChannel: Readonly<Ref<TreeChannel | undefined>>;
|
||||
members: ChannelMember[];
|
||||
speakingIds: Set<number>;
|
||||
whisperTargetIds: Set<number>;
|
||||
moveClient: (clientId: number, targetChannelId: string) => Promise<void>;
|
||||
setWhisperTargets: (clientIds: number[]) => void;
|
||||
sendPoke: (clientId: number, message: string) => void;
|
||||
setAway: (away: boolean, message: string) => void;
|
||||
stopWhisperTalk: () => void;
|
||||
localizedMessage: (message: string) => string;
|
||||
showToast: (message: string) => void;
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
export function useWebClientMembers({
|
||||
channels,
|
||||
currentChannel,
|
||||
members,
|
||||
speakingIds,
|
||||
whisperTargetIds,
|
||||
moveClient,
|
||||
setWhisperTargets,
|
||||
sendPoke,
|
||||
setAway,
|
||||
stopWhisperTalk,
|
||||
localizedMessage,
|
||||
showToast,
|
||||
t,
|
||||
}: UseWebClientMembersOptions) {
|
||||
const away = ref(false);
|
||||
const awayMessage = ref("");
|
||||
const memberMenu = ref<MemberMenuState | null>(null);
|
||||
const memberMoveMenuOpen = ref(false);
|
||||
const draggedMember = ref<ChannelMember | null>(null);
|
||||
const dragOverChannelId = ref("");
|
||||
const memberPointerDrag = reactive({
|
||||
member: null as ChannelMember | null,
|
||||
pointerId: null as number | null,
|
||||
startX: 0,
|
||||
startY: 0,
|
||||
active: false,
|
||||
targetChannelId: "",
|
||||
});
|
||||
|
||||
const memberMoveMenuCurrentChannel = computed<TreeChannel | null>(() => {
|
||||
const member = memberMenu.value?.member;
|
||||
const selected = currentChannel.value;
|
||||
if (!member || !selected || selected.id === "__current__") return null;
|
||||
return selected;
|
||||
});
|
||||
const memberMoveMenuCurrentSameChannel = computed(() => {
|
||||
const member = memberMenu.value?.member;
|
||||
const currentId = memberMoveMenuCurrentChannel.value?.id;
|
||||
if (!member || !currentId) return false;
|
||||
return channels.value.find((item) => item.members.some((candidate) => candidate.id === member.id))?.id === currentId;
|
||||
});
|
||||
const memberMoveMenuOtherChannels = computed<TreeChannel[]>(() => {
|
||||
const member = memberMenu.value?.member;
|
||||
if (!member) return [];
|
||||
const sourceChannelId = channels.value.find((item) => item.members.some((candidate) => candidate.id === member.id))?.id ?? "";
|
||||
const currentChannelId = memberMoveMenuCurrentChannel.value?.id;
|
||||
return channels.value.filter((item) => item.id !== "__current__" && item.id !== sourceChannelId && item.id !== currentChannelId);
|
||||
});
|
||||
|
||||
function openMemberMenu(member: ChannelMember, event: Event): void {
|
||||
if (member.isSelf) return;
|
||||
memberMoveMenuOpen.value = false;
|
||||
const point = event instanceof MouseEvent ? event : undefined;
|
||||
memberMenu.value = {
|
||||
member,
|
||||
x: Math.min(point?.clientX ?? 20, Math.max(12, window.innerWidth - 210)),
|
||||
y: Math.min(point?.clientY ?? 20, Math.max(12, window.innerHeight - 170)),
|
||||
};
|
||||
}
|
||||
|
||||
function openMemberActions(member: ChannelMember): void {
|
||||
if (member.isSelf) return;
|
||||
memberMoveMenuOpen.value = false;
|
||||
memberMenu.value = { member, x: 0, y: 0 };
|
||||
}
|
||||
|
||||
function toggleMemberMoveMenu(): void {
|
||||
memberMoveMenuOpen.value = true;
|
||||
}
|
||||
|
||||
async function moveMemberDirect(member: ChannelMember, targetChannelId: string): Promise<void> {
|
||||
if (member.isSelf || !targetChannelId || targetChannelId === "__current__") return;
|
||||
const sourceChannel = channels.value.find((item) => item.members.some((candidate) => candidate.id === member.id));
|
||||
if (sourceChannel?.id === targetChannelId) {
|
||||
memberMenu.value = null;
|
||||
memberMoveMenuOpen.value = false;
|
||||
return;
|
||||
}
|
||||
memberMenu.value = null;
|
||||
memberMoveMenuOpen.value = false;
|
||||
try {
|
||||
// Member moves are server-admin operations; never request or forward a channel password.
|
||||
await moveClient(member.id, targetChannelId);
|
||||
showToast(t("moveMemberSuccess"));
|
||||
} catch (error: unknown) {
|
||||
showToast(localizedMessage(error instanceof Error ? error.message : "操作失败"));
|
||||
}
|
||||
}
|
||||
|
||||
function onMemberDragStart(member: ChannelMember, event: DragEvent): void {
|
||||
if (member.isSelf) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
draggedMember.value = member;
|
||||
dragOverChannelId.value = "";
|
||||
event.dataTransfer?.setData("text/plain", String(member.id));
|
||||
if (event.dataTransfer) event.dataTransfer.effectAllowed = "move";
|
||||
}
|
||||
|
||||
function onMemberDragEnd(): void {
|
||||
draggedMember.value = null;
|
||||
dragOverChannelId.value = "";
|
||||
}
|
||||
|
||||
function onMemberPointerDown(member: ChannelMember, event: PointerEvent): void {
|
||||
if (member.isSelf || event.button !== 0) return;
|
||||
const target = event.target instanceof Element ? event.target : null;
|
||||
if (target?.closest("input,button")) return;
|
||||
event.preventDefault();
|
||||
memberPointerDrag.member = member;
|
||||
memberPointerDrag.pointerId = event.pointerId;
|
||||
memberPointerDrag.startX = event.clientX;
|
||||
memberPointerDrag.startY = event.clientY;
|
||||
memberPointerDrag.active = false;
|
||||
memberPointerDrag.targetChannelId = "";
|
||||
const currentTarget = event.currentTarget as HTMLElement | null;
|
||||
currentTarget?.setPointerCapture?.(event.pointerId);
|
||||
}
|
||||
|
||||
function onMemberPointerMove(event: PointerEvent): void {
|
||||
if (!memberPointerDrag.member || memberPointerDrag.pointerId !== event.pointerId) return;
|
||||
const distance = Math.hypot(event.clientX - memberPointerDrag.startX, event.clientY - memberPointerDrag.startY);
|
||||
if (!memberPointerDrag.active && distance < 6) return;
|
||||
event.preventDefault();
|
||||
memberPointerDrag.active = true;
|
||||
draggedMember.value = memberPointerDrag.member;
|
||||
const target = document.elementFromPoint(event.clientX, event.clientY)?.closest<HTMLElement>("[data-member-channel-id]");
|
||||
const targetChannelId = target?.dataset.memberChannelId ?? "";
|
||||
const sourceChannel = channels.value.find((item) => item.members.some((candidate) => candidate.id === memberPointerDrag.member?.id));
|
||||
if (!sourceChannel || !targetChannelId || targetChannelId === sourceChannel.id) {
|
||||
memberPointerDrag.targetChannelId = "";
|
||||
dragOverChannelId.value = "";
|
||||
return;
|
||||
}
|
||||
memberPointerDrag.targetChannelId = targetChannelId;
|
||||
dragOverChannelId.value = targetChannelId;
|
||||
}
|
||||
|
||||
function onMemberPointerUp(event: PointerEvent): void {
|
||||
if (!memberPointerDrag.member || memberPointerDrag.pointerId !== event.pointerId) return;
|
||||
const member = memberPointerDrag.member;
|
||||
const targetChannelId = memberPointerDrag.targetChannelId;
|
||||
const currentTarget = event.currentTarget as HTMLElement | null;
|
||||
currentTarget?.releasePointerCapture?.(event.pointerId);
|
||||
memberPointerDrag.member = null;
|
||||
memberPointerDrag.pointerId = null;
|
||||
memberPointerDrag.active = false;
|
||||
memberPointerDrag.targetChannelId = "";
|
||||
draggedMember.value = null;
|
||||
dragOverChannelId.value = "";
|
||||
if (targetChannelId) void moveMemberDirect(member, targetChannelId);
|
||||
}
|
||||
|
||||
function onMemberPointerCancel(event: PointerEvent): void {
|
||||
if (!memberPointerDrag.member || memberPointerDrag.pointerId !== event.pointerId) return;
|
||||
const currentTarget = event.currentTarget as HTMLElement | null;
|
||||
currentTarget?.releasePointerCapture?.(event.pointerId);
|
||||
memberPointerDrag.member = null;
|
||||
memberPointerDrag.pointerId = null;
|
||||
memberPointerDrag.active = false;
|
||||
memberPointerDrag.targetChannelId = "";
|
||||
draggedMember.value = null;
|
||||
dragOverChannelId.value = "";
|
||||
}
|
||||
|
||||
function onChannelDragOver(channel: TreeChannel, event: DragEvent): void {
|
||||
const member = draggedMember.value;
|
||||
if (!member || channel.id === "__current__") return;
|
||||
const sourceChannel = channels.value.find((item) => item.members.some((candidate) => candidate.id === member.id));
|
||||
if (!sourceChannel || sourceChannel.id === channel.id) return;
|
||||
event.preventDefault();
|
||||
if (event.dataTransfer) event.dataTransfer.dropEffect = "move";
|
||||
dragOverChannelId.value = channel.id;
|
||||
}
|
||||
|
||||
function onChannelDragLeave(channel: TreeChannel, event: DragEvent): void {
|
||||
const currentTarget = event.currentTarget;
|
||||
const relatedTarget = event.relatedTarget;
|
||||
if (currentTarget instanceof HTMLElement && relatedTarget instanceof Node && currentTarget.contains(relatedTarget)) return;
|
||||
if (dragOverChannelId.value === channel.id) dragOverChannelId.value = "";
|
||||
}
|
||||
|
||||
function onChannelDrop(channel: TreeChannel, event: DragEvent): void {
|
||||
event.preventDefault();
|
||||
const member = draggedMember.value;
|
||||
onMemberDragEnd();
|
||||
if (!member || channel.id === "__current__") return;
|
||||
void moveMemberDirect(member, channel.id);
|
||||
}
|
||||
|
||||
function toggleWhisperTarget(member: ChannelMember): void {
|
||||
if (member.isSelf) return;
|
||||
const targets = new Set(whisperTargetIds);
|
||||
if (targets.has(member.id)) targets.delete(member.id);
|
||||
else if (targets.size < 8) targets.add(member.id);
|
||||
setWhisperTargets([...targets]);
|
||||
showToast(t(targets.has(member.id) ? "setWhisperTarget" : "removeWhisperTarget"));
|
||||
}
|
||||
|
||||
function clearWhisperTargets(): void {
|
||||
stopWhisperTalk();
|
||||
setWhisperTargets([]);
|
||||
}
|
||||
|
||||
function pokeMember(member: ChannelMember): void {
|
||||
sendPoke(member.id, window.prompt(t("pokeMessagePrompt"), "") ?? "");
|
||||
showToast(t("pokeSent"));
|
||||
}
|
||||
|
||||
function copyMemberName(member: ChannelMember): void {
|
||||
navigator.clipboard?.writeText(member.nickname).then(
|
||||
() => showToast(t("copiedNickname")),
|
||||
() => showToast(t("copyFailedToast")),
|
||||
);
|
||||
}
|
||||
|
||||
function toggleAway(): void {
|
||||
away.value = !away.value;
|
||||
awayMessage.value = away.value ? (window.prompt(t("awayPrompt"), awayMessage.value) ?? "") : "";
|
||||
setAway(away.value, awayMessage.value);
|
||||
}
|
||||
|
||||
function isSpeaking(member: ChannelMember): boolean {
|
||||
return speakingIds.has(member.id);
|
||||
}
|
||||
|
||||
function memberDisplayName(member: ChannelMember): string {
|
||||
return member.isSelf ? `${member.nickname}${t("selfSuffix")}` : member.nickname;
|
||||
}
|
||||
|
||||
return {
|
||||
away,
|
||||
memberMenu,
|
||||
memberMoveMenuOpen,
|
||||
draggedMember,
|
||||
dragOverChannelId,
|
||||
memberPointerDrag,
|
||||
memberMoveMenuCurrentChannel,
|
||||
memberMoveMenuCurrentSameChannel,
|
||||
memberMoveMenuOtherChannels,
|
||||
openMemberMenu,
|
||||
openMemberActions,
|
||||
toggleMemberMoveMenu,
|
||||
moveMemberDirect,
|
||||
onMemberDragStart,
|
||||
onMemberDragEnd,
|
||||
onMemberPointerDown,
|
||||
onMemberPointerMove,
|
||||
onMemberPointerUp,
|
||||
onMemberPointerCancel,
|
||||
onChannelDragOver,
|
||||
onChannelDragLeave,
|
||||
onChannelDrop,
|
||||
toggleWhisperTarget,
|
||||
clearWhisperTargets,
|
||||
pokeMember,
|
||||
copyMemberName,
|
||||
toggleAway,
|
||||
isSpeaking,
|
||||
memberDisplayName,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { computed, onUnmounted, ref, watch, type Ref } from "vue";
|
||||
import type { LatencyProbeResult } from "./useVoiceWebSocket.js";
|
||||
|
||||
const SAMPLE_INTERVAL_MS = 3_000;
|
||||
const SAMPLE_WINDOW_SIZE = 20;
|
||||
|
||||
export function useWebClientPerformance(
|
||||
connected: Readonly<Ref<boolean>>,
|
||||
measureLatency: () => Promise<LatencyProbeResult | null>,
|
||||
) {
|
||||
const panelOpen = ref(false);
|
||||
const running = ref(false);
|
||||
const samples = ref<LatencyProbeResult[]>([]);
|
||||
const probeResults = ref<Array<LatencyProbeResult | null>>([]);
|
||||
const attempts = ref(0);
|
||||
let timer: number | null = null;
|
||||
let generation = 0;
|
||||
|
||||
const median = (values: number[]) => {
|
||||
const sorted = [...values].sort((left, right) => left - right);
|
||||
return sorted.length ? sorted[Math.floor(sorted.length / 2)] : null;
|
||||
};
|
||||
|
||||
const stats = computed(() => {
|
||||
const gatewaySamples = samples.value.map((sample) => sample.browserRttMs);
|
||||
const teamSpeakSamples = samples.value
|
||||
.filter((sample) => sample.teamSpeakReachable && sample.teamSpeakLatencyMs != null)
|
||||
.map((sample) => sample.teamSpeakLatencyMs as number);
|
||||
|
||||
return {
|
||||
gatewayLatencyMs: median(gatewaySamples),
|
||||
gatewayLossPercent: attempts.value > 0 ? Math.round(((attempts.value - samples.value.length) / attempts.value) * 100) : null,
|
||||
teamSpeakLatencyMs: median(teamSpeakSamples),
|
||||
teamSpeakLossPercent: attempts.value > 0 ? Math.round(((attempts.value - teamSpeakSamples.length) / attempts.value) * 100) : null,
|
||||
ready: attempts.value > 0,
|
||||
};
|
||||
});
|
||||
|
||||
function resetSamples(): void {
|
||||
probeResults.value = [];
|
||||
samples.value = [];
|
||||
attempts.value = 0;
|
||||
}
|
||||
|
||||
function stop(): void {
|
||||
if (timer !== null) {
|
||||
clearInterval(timer);
|
||||
timer = null;
|
||||
}
|
||||
generation += 1;
|
||||
running.value = false;
|
||||
}
|
||||
|
||||
async function runProbe(expectedGeneration = generation): Promise<void> {
|
||||
if (running.value || !connected.value || !panelOpen.value) return;
|
||||
running.value = true;
|
||||
try {
|
||||
const sample = await measureLatency();
|
||||
if (expectedGeneration !== generation || !panelOpen.value) return;
|
||||
probeResults.value.push(sample);
|
||||
if (probeResults.value.length > SAMPLE_WINDOW_SIZE) probeResults.value.shift();
|
||||
attempts.value = probeResults.value.length;
|
||||
samples.value = probeResults.value.filter((result): result is LatencyProbeResult => result !== null);
|
||||
} finally {
|
||||
if (expectedGeneration === generation) running.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function start(): void {
|
||||
if (timer !== null || !connected.value) return;
|
||||
resetSamples();
|
||||
const activeGeneration = ++generation;
|
||||
void runProbe(activeGeneration);
|
||||
timer = window.setInterval(() => {
|
||||
void runProbe(activeGeneration);
|
||||
}, SAMPLE_INTERVAL_MS);
|
||||
}
|
||||
|
||||
function refresh(): void {
|
||||
void runProbe();
|
||||
}
|
||||
|
||||
function togglePanel(): void {
|
||||
panelOpen.value = !panelOpen.value;
|
||||
}
|
||||
|
||||
watch([connected, panelOpen], ([isConnected, isOpen]) => {
|
||||
if (isConnected && isOpen) start();
|
||||
else stop();
|
||||
}, { immediate: true });
|
||||
|
||||
onUnmounted(stop);
|
||||
|
||||
return {
|
||||
panelOpen,
|
||||
running,
|
||||
stats,
|
||||
togglePanel,
|
||||
refresh,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { computed, reactive, ref, type Ref } from "vue";
|
||||
import { splitTeamSpeakTarget } from "../services/teamspeak-target.js";
|
||||
import type { Language } from "../i18n/web-client.js";
|
||||
|
||||
interface RelayOption {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
type Translator = (key: string, variables?: Record<string, string | number>) => string;
|
||||
|
||||
interface UseWebClientPublicConfigOptions {
|
||||
serverHost: Ref<string>;
|
||||
serverPort: Ref<string>;
|
||||
accelerationRelayId: Ref<string>;
|
||||
language: Ref<Language>;
|
||||
t: Translator;
|
||||
}
|
||||
|
||||
export function useWebClientPublicConfig({
|
||||
serverHost,
|
||||
serverPort,
|
||||
accelerationRelayId,
|
||||
language,
|
||||
t,
|
||||
}: UseWebClientPublicConfigOptions) {
|
||||
const accessMode = ref<"fixed" | "open">("fixed");
|
||||
const initialized = ref(false);
|
||||
const siteName = ref("WebSpeak");
|
||||
const appVersion = ref("0.2.5");
|
||||
const visitorNumber = ref<number | null>(null);
|
||||
const visitorTotal = ref<number | null>(null);
|
||||
const accelerationRelays = ref<RelayOption[]>([]);
|
||||
const serverConfigLoading = ref(true);
|
||||
const welcomeTexts = reactive<Record<Language, string>>({ zh: "", en: "", de: "", ru: "", ja: "" });
|
||||
const accelerationAvailable = computed(() => accelerationRelays.value.length > 0);
|
||||
const localizedWelcomeText = computed(() => welcomeTexts[language.value] || t("joinDescription"));
|
||||
|
||||
async function loadPublicConfig(): Promise<void> {
|
||||
const query = new URLSearchParams(location.search);
|
||||
try {
|
||||
const response = await fetch("/api/public-config", { headers: { accept: "application/json" } });
|
||||
if (!response.ok) return;
|
||||
const config = await response.json() as {
|
||||
version?: unknown;
|
||||
initialized?: unknown;
|
||||
siteName?: unknown;
|
||||
welcomeText?: unknown;
|
||||
welcomeTextEn?: unknown;
|
||||
welcomeTexts?: unknown;
|
||||
accessMode?: unknown;
|
||||
target?: unknown;
|
||||
visitorNumber?: unknown;
|
||||
visitorTotal?: unknown;
|
||||
accelerationRelays?: unknown;
|
||||
};
|
||||
if (typeof config.version === "string" && config.version.trim()) appVersion.value = config.version.trim();
|
||||
visitorNumber.value = Number.isSafeInteger(config.visitorNumber) && Number(config.visitorNumber) > 0 ? Number(config.visitorNumber) : null;
|
||||
visitorTotal.value = Number.isSafeInteger(config.visitorTotal) && Number(config.visitorTotal) > 0 ? Number(config.visitorTotal) : null;
|
||||
initialized.value = config.initialized === true;
|
||||
if (typeof config.siteName === "string" && config.siteName.trim()) siteName.value = config.siteName.trim();
|
||||
if (typeof config.welcomeText === "string") welcomeTexts.zh = config.welcomeText;
|
||||
if (typeof config.welcomeTextEn === "string") welcomeTexts.en = config.welcomeTextEn;
|
||||
if (config.welcomeTexts && typeof config.welcomeTexts === "object" && !Array.isArray(config.welcomeTexts)) {
|
||||
const configuredTexts = config.welcomeTexts as Record<string, unknown>;
|
||||
for (const languageCode of ["zh", "en", "de", "ru", "ja"] as const) {
|
||||
const text = configuredTexts[languageCode];
|
||||
if (typeof text === "string") welcomeTexts[languageCode] = text;
|
||||
}
|
||||
}
|
||||
accessMode.value = config.accessMode === "open" ? "open" : "fixed";
|
||||
accelerationRelays.value = Array.isArray(config.accelerationRelays)
|
||||
? config.accelerationRelays.flatMap((value) => {
|
||||
if (!value || typeof value !== "object") return [];
|
||||
const relay = value as { id?: unknown; name?: unknown };
|
||||
return typeof relay.id === "string" && typeof relay.name === "string" && relay.id && relay.name
|
||||
? [{ id: relay.id, name: relay.name }]
|
||||
: [];
|
||||
})
|
||||
: [];
|
||||
if (!accelerationAvailable.value || !accelerationRelays.value.some((relay) => relay.id === accelerationRelayId.value)) accelerationRelayId.value = "";
|
||||
const hasInviteTarget = query.has("server") || query.has("target") || query.has("tsHost") || query.has("tsPort");
|
||||
if (!hasInviteTarget && typeof config.target === "string" && config.target.trim()) {
|
||||
const target = splitTeamSpeakTarget(config.target);
|
||||
serverHost.value = target.address;
|
||||
serverPort.value = target.port;
|
||||
}
|
||||
} catch {
|
||||
// Keep joining disabled until the gateway confirms its initialized policy.
|
||||
} finally {
|
||||
serverConfigLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
accessMode,
|
||||
initialized,
|
||||
siteName,
|
||||
appVersion,
|
||||
visitorNumber,
|
||||
visitorTotal,
|
||||
accelerationRelays,
|
||||
accelerationAvailable,
|
||||
serverConfigLoading,
|
||||
localizedWelcomeText,
|
||||
loadPublicConfig,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import { computed, nextTick, onMounted, onUnmounted, ref, watch, type Ref } from "vue";
|
||||
import type { ChannelMember, ScreenShareOutputSettings, ScreenShareStream } from "./useVoiceWebSocket.js";
|
||||
|
||||
export type ScreenShareResolutionPreset = "source" | "720p" | "1080p";
|
||||
|
||||
interface ScreenShareResolutionOption {
|
||||
value: ScreenShareResolutionPreset;
|
||||
width?: number;
|
||||
height?: number;
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface UseWebClientScreenShareOptions {
|
||||
streams: ScreenShareStream[];
|
||||
viewing: Ref<boolean>;
|
||||
viewingStreamId: Ref<string>;
|
||||
remoteStream: Ref<MediaStream | null>;
|
||||
remoteVolume: Ref<number>;
|
||||
error: Ref<string>;
|
||||
errorCode: Ref<string>;
|
||||
startScreenShare: (audio?: boolean, settings?: ScreenShareOutputSettings) => Promise<void>;
|
||||
joinScreenShare: (streamId: string) => void;
|
||||
leaveScreenShare: () => void;
|
||||
nickname: Ref<string>;
|
||||
avatarStyle: (name: string, isSelf?: boolean, avatar?: string) => Record<string, string>;
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
export function useWebClientScreenShare({
|
||||
streams,
|
||||
viewing,
|
||||
viewingStreamId,
|
||||
remoteStream,
|
||||
remoteVolume,
|
||||
error,
|
||||
errorCode,
|
||||
startScreenShare,
|
||||
joinScreenShare,
|
||||
leaveScreenShare,
|
||||
nickname,
|
||||
avatarStyle,
|
||||
t,
|
||||
}: UseWebClientScreenShareOptions) {
|
||||
const videoElement = ref<HTMLVideoElement | null>(null);
|
||||
const playerElement = ref<HTMLElement | null>(null);
|
||||
const fullscreen = ref(false);
|
||||
const resolutionOptions: ScreenShareResolutionOption[] = [
|
||||
{ value: "source", label: "screenShareResolutionSource" },
|
||||
{ value: "720p", width: 1280, height: 720, label: "screenShareResolution720p" },
|
||||
{ value: "1080p", width: 1920, height: 1080, label: "screenShareResolution1080p" },
|
||||
];
|
||||
const frameRateOptions = [5, 10, 15, 24, 30, 60];
|
||||
const storedResolution = localStorage.getItem("webspeak:screen-share-resolution") as ScreenShareResolutionPreset | null;
|
||||
const resolutionPreset = ref<ScreenShareResolutionPreset>(resolutionOptions.some((option) => option.value === storedResolution) ? storedResolution! : "1080p");
|
||||
const storedFrameRate = Number(localStorage.getItem("webspeak:screen-share-framerate"));
|
||||
const frameRate = ref(frameRateOptions.includes(storedFrameRate) ? storedFrameRate : 15);
|
||||
const settingsOpen = ref(false);
|
||||
const activeStream = computed<ScreenShareStream | null>(() => streams.find((stream) => stream.streamId === viewingStreamId.value) ?? null);
|
||||
const viewers = computed(() => activeStream.value?.viewers.slice(-5) ?? []);
|
||||
const viewerCount = computed(() => activeStream.value?.viewerCount ?? activeStream.value?.viewers.length ?? 0);
|
||||
const ownerName = computed(() => activeStream.value?.ownerNickname ?? t("screenShare"));
|
||||
const errorText = computed(() => errorCode.value === "SCREEN_SHARE_NATIVE_BRIDGE_REQUIRED" ? t("screenShareNativeUnavailable") : error.value);
|
||||
|
||||
function setVideoElement(element: unknown): void {
|
||||
videoElement.value = element instanceof HTMLVideoElement ? element : null;
|
||||
}
|
||||
|
||||
function streamForMember(member: ChannelMember): ScreenShareStream | null {
|
||||
return streams.find((stream) => {
|
||||
if (typeof stream.ownerClientId === "number" && stream.ownerClientId === member.id) return true;
|
||||
if (stream.source === "teamspeak" && stream.ownerPeerId === `ts-${member.id}`) return true;
|
||||
return stream.ownerNickname === member.nickname;
|
||||
}) ?? null;
|
||||
}
|
||||
|
||||
function toggleForMember(member: ChannelMember): void {
|
||||
const stream = streamForMember(member);
|
||||
if (!stream) return;
|
||||
if (viewingStreamId.value === stream.streamId) leaveScreenShare();
|
||||
else joinScreenShare(stream.streamId);
|
||||
}
|
||||
|
||||
function viewerStyle(viewer: { nickname: string; avatar?: string }) {
|
||||
return avatarStyle(viewer.nickname, viewer.nickname === nickname.value, viewer.avatar ?? "");
|
||||
}
|
||||
|
||||
function setVolume(event: Event): void {
|
||||
remoteVolume.value = Math.max(0, Math.min(1, Number((event.target as HTMLInputElement).value) / 100));
|
||||
}
|
||||
|
||||
function syncFullscreen(): void {
|
||||
fullscreen.value = document.fullscreenElement === playerElement.value;
|
||||
}
|
||||
|
||||
async function toggleFullscreen(): Promise<void> {
|
||||
const player = playerElement.value;
|
||||
if (!player) return;
|
||||
try {
|
||||
if (document.fullscreenElement === player) await document.exitFullscreen();
|
||||
else if (player.requestFullscreen) await player.requestFullscreen();
|
||||
} catch {
|
||||
fullscreen.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function startWithSettings(): Promise<void> {
|
||||
const preset = resolutionOptions.find((option) => option.value === resolutionPreset.value);
|
||||
const settings: ScreenShareOutputSettings = {
|
||||
...(preset?.width && preset.height ? { maxWidth: preset.width, maxHeight: preset.height } : {}),
|
||||
maxFrameRate: frameRate.value,
|
||||
};
|
||||
localStorage.setItem("webspeak:screen-share-resolution", resolutionPreset.value);
|
||||
localStorage.setItem("webspeak:screen-share-framerate", String(frameRate.value));
|
||||
settingsOpen.value = false;
|
||||
await startScreenShare(true, settings);
|
||||
}
|
||||
|
||||
watch([remoteStream, remoteVolume], ([stream, volume]) => {
|
||||
void nextTick(() => {
|
||||
const video = videoElement.value;
|
||||
if (!video) return;
|
||||
if (video.srcObject !== stream) video.srcObject = stream;
|
||||
video.volume = Math.max(0, Math.min(1, volume ?? 1));
|
||||
if (stream) void video.play().catch(() => undefined);
|
||||
});
|
||||
});
|
||||
watch(viewing, (isViewing) => {
|
||||
if (!isViewing && document.fullscreenElement === playerElement.value) void document.exitFullscreen().catch(() => undefined);
|
||||
});
|
||||
|
||||
onMounted(() => document.addEventListener("fullscreenchange", syncFullscreen));
|
||||
onUnmounted(() => document.removeEventListener("fullscreenchange", syncFullscreen));
|
||||
|
||||
return {
|
||||
videoElement,
|
||||
playerElement,
|
||||
fullscreen,
|
||||
resolutionOptions,
|
||||
frameRateOptions,
|
||||
resolutionPreset,
|
||||
frameRate,
|
||||
settingsOpen,
|
||||
activeStream,
|
||||
viewers,
|
||||
viewerCount,
|
||||
ownerName,
|
||||
errorText,
|
||||
setVideoElement,
|
||||
streamForMember,
|
||||
toggleForMember,
|
||||
viewerStyle,
|
||||
setVolume,
|
||||
syncFullscreen,
|
||||
toggleFullscreen,
|
||||
startWithSettings,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { computed, ref, type Ref } from "vue";
|
||||
import {
|
||||
listFavorites,
|
||||
listRecentServers,
|
||||
recordRecentServer,
|
||||
removeFavorite,
|
||||
saveFavorite,
|
||||
type FavoriteServer,
|
||||
type RecentServer,
|
||||
} from "../services/local-persistence.js";
|
||||
import { combineTeamSpeakTarget, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
|
||||
|
||||
type Translator = (key: string, variables?: Record<string, string | number>) => string;
|
||||
|
||||
interface UseWebClientServerHistoryOptions {
|
||||
serverHost: Ref<string>;
|
||||
serverPort: Ref<string>;
|
||||
nickname: Ref<string>;
|
||||
channel: Ref<string>;
|
||||
rememberIdentity: Ref<boolean>;
|
||||
identityMaterial: Ref<string>;
|
||||
t: Translator;
|
||||
showToast: (message: string) => void;
|
||||
}
|
||||
|
||||
export function useWebClientServerHistory({
|
||||
serverHost,
|
||||
serverPort,
|
||||
nickname,
|
||||
channel,
|
||||
rememberIdentity,
|
||||
identityMaterial,
|
||||
t,
|
||||
showToast,
|
||||
}: UseWebClientServerHistoryOptions) {
|
||||
const favoriteServers = ref<FavoriteServer[]>([]);
|
||||
const recentServers = ref<RecentServer[]>([]);
|
||||
const currentTarget = computed(() => combineTeamSpeakTarget(serverHost.value, serverPort.value));
|
||||
const isFavorite = computed(() => favoriteServers.value.some((favorite) => favorite.id === serverKey(currentTarget.value)));
|
||||
|
||||
async function loadSavedServers(): Promise<void> {
|
||||
const [favorites, recent] = await Promise.all([listFavorites(), listRecentServers()]);
|
||||
favoriteServers.value = favorites;
|
||||
recentServers.value = recent;
|
||||
}
|
||||
|
||||
function recordCurrentServer(): void {
|
||||
const address = currentTarget.value;
|
||||
if (!address) return;
|
||||
const recent: RecentServer = {
|
||||
id: serverKey(address),
|
||||
address,
|
||||
...(nickname.value.trim() ? { nickname: nickname.value.trim() } : {}),
|
||||
...(rememberIdentity.value && identityMaterial.value ? { identityId: "current" } : {}),
|
||||
lastConnectedAt: Date.now(),
|
||||
...(channel.value.trim() ? { lastChannelHint: { name: channel.value.trim() } } : {}),
|
||||
};
|
||||
void recordRecentServer(recent).then(() => listRecentServers().then((items) => { recentServers.value = items; }));
|
||||
}
|
||||
|
||||
function selectLocalServer(address: string, savedNickname?: string): void {
|
||||
const target = splitTeamSpeakTarget(address);
|
||||
serverHost.value = target.address;
|
||||
serverPort.value = target.port;
|
||||
if (savedNickname && !nickname.value.trim()) nickname.value = savedNickname;
|
||||
}
|
||||
|
||||
async function toggleFavorite(): Promise<void> {
|
||||
const address = currentTarget.value;
|
||||
if (!address) return;
|
||||
const id = serverKey(address);
|
||||
const existing = favoriteServers.value.find((favorite) => favorite.id === id);
|
||||
if (existing) {
|
||||
await removeFavorite(id);
|
||||
favoriteServers.value = favoriteServers.value.filter((favorite) => favorite.id !== id);
|
||||
showToast(t("removedFavoriteToast"));
|
||||
return;
|
||||
}
|
||||
const favorite: FavoriteServer = {
|
||||
id,
|
||||
label: address,
|
||||
address,
|
||||
...(nickname.value.trim() ? { nickname: nickname.value.trim() } : {}),
|
||||
...(rememberIdentity.value && identityMaterial.value ? { identityId: "current" } : {}),
|
||||
...(channel.value.trim() ? { lastChannelHint: { name: channel.value.trim() } } : {}),
|
||||
};
|
||||
await saveFavorite(favorite);
|
||||
favoriteServers.value = [...favoriteServers.value, favorite].sort((left, right) => left.label.localeCompare(right.label));
|
||||
showToast(t("savedFavoriteToast"));
|
||||
}
|
||||
|
||||
function clearServerHistory(): void {
|
||||
favoriteServers.value = [];
|
||||
recentServers.value = [];
|
||||
}
|
||||
|
||||
return {
|
||||
favoriteServers,
|
||||
recentServers,
|
||||
isFavorite,
|
||||
loadSavedServers,
|
||||
recordCurrentServer,
|
||||
selectLocalServer,
|
||||
toggleFavorite,
|
||||
clearServerHistory,
|
||||
};
|
||||
}
|
||||
|
||||
function serverKey(address: string): string {
|
||||
return address.trim().toLocaleLowerCase();
|
||||
}
|
||||
@@ -7,6 +7,25 @@ import AdminView from "./views/AdminView.vue";
|
||||
import DemoView from "./views/DemoView.vue";
|
||||
import "./services/theme.js";
|
||||
|
||||
const BASELINE_WIDTH = 1920;
|
||||
const BASELINE_HEIGHT = 1080;
|
||||
const MAX_UI_SCALE = 1.5;
|
||||
|
||||
function applyUiScale(): void {
|
||||
// Keep the current 1080p layout as the reference. Only enlarge the UI when
|
||||
// both viewport dimensions provide more space; smaller windows keep the
|
||||
// existing responsive rules instead of shrinking text until it becomes hard
|
||||
// to read.
|
||||
const scale = Math.min(
|
||||
MAX_UI_SCALE,
|
||||
Math.max(1, Math.min(window.innerWidth / BASELINE_WIDTH, window.innerHeight / BASELINE_HEIGHT)),
|
||||
);
|
||||
document.documentElement.style.setProperty("--ui-scale", scale.toFixed(4));
|
||||
}
|
||||
|
||||
applyUiScale();
|
||||
window.addEventListener("resize", applyUiScale, { passive: true });
|
||||
|
||||
const routes = [
|
||||
{ path: "/", name: "webclient", component: WebClient },
|
||||
{ path: "/join", name: "join", component: WebClient },
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
const DB_NAME = "webspeak-local";
|
||||
const DB_VERSION = 1;
|
||||
const DB_VERSION = 2;
|
||||
const CURRENT_IDENTITY_KEY = "current";
|
||||
const PREFERENCES_KEY = "singleton";
|
||||
|
||||
import type { InstalledSkin } from "./skin-pack.js";
|
||||
|
||||
export interface StoredIdentity {
|
||||
id: string;
|
||||
label?: string;
|
||||
@@ -33,9 +35,11 @@ export interface LocalPreferences {
|
||||
schemaVersion: 1;
|
||||
locale?: "auto" | "zh-CN" | "en";
|
||||
theme?: "system" | "light" | "dark";
|
||||
skinId?: string;
|
||||
microphoneMuted?: boolean;
|
||||
noiseSuppressionEnabled?: boolean;
|
||||
voxThreshold?: number;
|
||||
language?: "zh" | "en" | "de";
|
||||
language?: "zh" | "en" | "de" | "ru" | "ja";
|
||||
preferredInputDeviceId?: string;
|
||||
preferredOutputDeviceId?: string;
|
||||
inputGain?: number;
|
||||
@@ -64,6 +68,7 @@ function openDatabase(): Promise<IDBDatabase> {
|
||||
if (!database.objectStoreNames.contains("preferences")) database.createObjectStore("preferences", { keyPath: "id" });
|
||||
if (!database.objectStoreNames.contains("favorites")) database.createObjectStore("favorites", { keyPath: "id" });
|
||||
if (!database.objectStoreNames.contains("recent")) database.createObjectStore("recent", { keyPath: "id" });
|
||||
if (!database.objectStoreNames.contains("skins")) database.createObjectStore("skins", { keyPath: "id" });
|
||||
};
|
||||
request.onsuccess = () => {
|
||||
const database = request.result;
|
||||
@@ -163,6 +168,47 @@ export async function saveLocalPreferences(preferences: LocalPreferences): Promi
|
||||
}
|
||||
}
|
||||
|
||||
export async function listInstalledSkins(): Promise<InstalledSkin[]> {
|
||||
try {
|
||||
const skins = await request<InstalledSkin[]>("skins", "readonly", (store, resolve, reject) => {
|
||||
const get = store.getAll();
|
||||
get.onsuccess = () => resolve(get.result as InstalledSkin[]);
|
||||
get.onerror = () => reject(get.error);
|
||||
});
|
||||
return skins.sort((a, b) => a.name.localeCompare(b.name));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function getInstalledSkin(id: string): Promise<InstalledSkin | null> {
|
||||
try {
|
||||
return await request<InstalledSkin | null>("skins", "readonly", (store, resolve, reject) => {
|
||||
const get = store.get(id);
|
||||
get.onsuccess = () => resolve((get.result as InstalledSkin | undefined) ?? null);
|
||||
get.onerror = () => reject(get.error);
|
||||
});
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveInstalledSkin(skin: InstalledSkin): Promise<void> {
|
||||
await request("skins", "readwrite", (store, resolve, reject) => {
|
||||
const put = store.put(skin);
|
||||
put.onsuccess = () => resolve(undefined);
|
||||
put.onerror = () => reject(put.error);
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeInstalledSkin(id: string): Promise<void> {
|
||||
await request("skins", "readwrite", (store, resolve, reject) => {
|
||||
const remove = store.delete(id);
|
||||
remove.onsuccess = () => resolve(undefined);
|
||||
remove.onerror = () => reject(remove.error);
|
||||
});
|
||||
}
|
||||
|
||||
export async function listFavorites(): Promise<FavoriteServer[]> {
|
||||
try {
|
||||
return await request<FavoriteServer[]>("favorites", "readonly", (store, resolve, reject) => {
|
||||
@@ -242,7 +288,7 @@ async function removeRecentServer(id: string): Promise<void> {
|
||||
export async function clearLocalData(): Promise<void> {
|
||||
try {
|
||||
const database = await openDatabase();
|
||||
await Promise.all(["identities", "preferences", "favorites", "recent"].map((storeName) => new Promise<void>((resolve, reject) => {
|
||||
await Promise.all(["identities", "preferences", "favorites", "recent", "skins"].map((storeName) => new Promise<void>((resolve, reject) => {
|
||||
const transaction = database.transaction(storeName, "readwrite");
|
||||
transaction.objectStore(storeName).clear();
|
||||
transaction.oncomplete = () => resolve();
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
/** Reduce built-in theme specificity while a community skin is active.
|
||||
* The community skin is loaded after this stylesheet and should own appearance
|
||||
* without needing !important or private component selectors.
|
||||
*/
|
||||
export function scopeBuiltinThemeForCustomSkin(css: string, theme: "light" | "dark", skinId: string): string {
|
||||
const sourceRoot = `.ws-skin-root[data-ws-skin="builtin.${theme}"]`;
|
||||
const customRoot = `:where(.ws-skin-root[data-ws-skin="${skinId}"])`;
|
||||
return css.replaceAll(sourceRoot, customRoot);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
BUILTIN_SKIN_CATALOG,
|
||||
getPublicDefaultSkinId,
|
||||
isPublicSkinEnabled,
|
||||
listPublicSkins,
|
||||
} from "./skin-catalog.js";
|
||||
|
||||
test("skin catalog always includes the three protected built-ins and exposes only enabled custom skins", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = async () => new Response(JSON.stringify({
|
||||
defaultSkinId: "sample-skin",
|
||||
skins: [
|
||||
{ id: "sample-skin", name: "Sample", version: "1.0.0", author: "Test", license: "MIT", minAppVersion: "0.2.5", installedAt: 1, enabled: true },
|
||||
{ id: "disabled-skin", name: "Disabled", version: "1.0.0", author: "Test", license: "MIT", minAppVersion: "0.2.5", installedAt: 2, enabled: false },
|
||||
{ id: "community.illusia-voice", name: "Spoofed", version: "9.9.9", author: "Other", license: "MIT", minAppVersion: "0.0.1", installedAt: 3 },
|
||||
],
|
||||
}), { status: 200, headers: { "content-type": "application/json" } });
|
||||
|
||||
try {
|
||||
const skins = await listPublicSkins();
|
||||
assert.deepEqual(skins.map((skin) => skin.id), [
|
||||
"builtin.light",
|
||||
"builtin.dark",
|
||||
"community.illusia-voice",
|
||||
"sample-skin",
|
||||
]);
|
||||
assert.deepEqual(BUILTIN_SKIN_CATALOG.map((skin) => skin.id), skins.slice(0, 3).map((skin) => skin.id));
|
||||
assert.equal(getPublicDefaultSkinId(), "sample-skin");
|
||||
assert.equal(isPublicSkinEnabled("sample-skin"), true);
|
||||
assert.equal(isPublicSkinEnabled("disabled-skin"), false);
|
||||
assert.equal(isPublicSkinEnabled("community.illusia-voice"), true);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test("invalid or disabled instance defaults safely fall back to the protected day skin", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = async () => new Response(JSON.stringify({
|
||||
defaultSkinId: "disabled-skin",
|
||||
skins: [{ id: "disabled-skin", name: "Disabled", version: "1.0.0", author: "Test", license: "MIT", minAppVersion: "0.2.5", installedAt: 2, enabled: false }],
|
||||
}), { status: 200, headers: { "content-type": "application/json" } });
|
||||
|
||||
try {
|
||||
const skins = await listPublicSkins();
|
||||
assert.equal(skins.length, 3);
|
||||
assert.equal(getPublicDefaultSkinId(), "builtin.light");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,144 @@
|
||||
export interface SkinCatalogEntry {
|
||||
id: string;
|
||||
name: string;
|
||||
version: string;
|
||||
author: string;
|
||||
license: string;
|
||||
description?: string;
|
||||
minAppVersion: string;
|
||||
previewUrl?: string;
|
||||
installedAt: number;
|
||||
builtIn?: boolean;
|
||||
enabled?: boolean;
|
||||
previewKind?: "day" | "night" | "illusia";
|
||||
}
|
||||
|
||||
export const BUILTIN_ILLUSIA_SKIN_ID = "community.illusia-voice";
|
||||
|
||||
export const BUILTIN_SKIN_CATALOG: SkinCatalogEntry[] = [
|
||||
{
|
||||
id: "builtin.light",
|
||||
name: "Day mode",
|
||||
version: "1.0.0",
|
||||
author: "WebSpeak",
|
||||
license: "AGPL-3.0-only",
|
||||
description: "The default light appearance.",
|
||||
minAppVersion: "0.2.5",
|
||||
installedAt: 0,
|
||||
builtIn: true,
|
||||
previewKind: "day",
|
||||
},
|
||||
{
|
||||
id: "builtin.dark",
|
||||
name: "Night mode",
|
||||
version: "1.0.0",
|
||||
author: "WebSpeak",
|
||||
license: "AGPL-3.0-only",
|
||||
description: "The default dark appearance.",
|
||||
minAppVersion: "0.2.5",
|
||||
installedAt: 0,
|
||||
builtIn: true,
|
||||
previewKind: "night",
|
||||
},
|
||||
{
|
||||
id: BUILTIN_ILLUSIA_SKIN_ID,
|
||||
name: "ILLUSIA风",
|
||||
version: "1.0.27",
|
||||
author: "WebSpeak Project",
|
||||
license: "All rights reserved",
|
||||
description: "A bright original-character art skin for the home, voice room, and demo pages.",
|
||||
minAppVersion: "0.2.5",
|
||||
previewUrl: "/skins/illusia-voice-preview.webp",
|
||||
installedAt: 0,
|
||||
builtIn: true,
|
||||
previewKind: "illusia",
|
||||
},
|
||||
];
|
||||
|
||||
const BUILTIN_ILLUSIA_PACKAGE_URL = "/skins/illusia-voice.wskin";
|
||||
let publicDirectoryLoaded = false;
|
||||
let publicEnabledSkinIds = new Set<string>(BUILTIN_SKIN_CATALOG.map((skin) => skin.id));
|
||||
let publicDefaultSkinId = "builtin.light";
|
||||
|
||||
export function getPublicDefaultSkinId(): string {
|
||||
return isPublicSkinEnabled(publicDefaultSkinId) ? publicDefaultSkinId : "builtin.light";
|
||||
}
|
||||
|
||||
export function isPublicSkinEnabled(id: string): boolean {
|
||||
if (BUILTIN_SKIN_CATALOG.some((skin) => skin.id === id)) return true;
|
||||
return !publicDirectoryLoaded || publicEnabledSkinIds.has(id);
|
||||
}
|
||||
|
||||
export function getBundledSkinPackageUrl(id: string): string | null {
|
||||
return id === BUILTIN_ILLUSIA_SKIN_ID ? BUILTIN_ILLUSIA_PACKAGE_URL : null;
|
||||
}
|
||||
|
||||
export async function listPublicSkins(): Promise<SkinCatalogEntry[]> {
|
||||
publicDirectoryLoaded = false;
|
||||
publicEnabledSkinIds = new Set(BUILTIN_SKIN_CATALOG.map((skin) => skin.id));
|
||||
publicDefaultSkinId = "builtin.light";
|
||||
try {
|
||||
const response = await fetch("/api/skins", { headers: { accept: "application/json" }, cache: "no-cache" });
|
||||
if (!response.ok) return BUILTIN_SKIN_CATALOG;
|
||||
const payload: unknown = await response.json();
|
||||
if (!payload || typeof payload !== "object" || !Array.isArray((payload as { skins?: unknown }).skins)) return BUILTIN_SKIN_CATALOG;
|
||||
const directorySkins = (payload as { skins: unknown[] }).skins.flatMap((value) => {
|
||||
if (!value || typeof value !== "object") return [];
|
||||
const skin = value as Record<string, unknown>;
|
||||
if (typeof skin.id !== "string" || !/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(skin.id) || skin.id.startsWith("builtin.") || skin.id === BUILTIN_ILLUSIA_SKIN_ID) return [];
|
||||
if ([skin.name, skin.version, skin.author, skin.license, skin.minAppVersion].some((field) => typeof field !== "string")) return [];
|
||||
const previewUrl = typeof skin.previewUrl === "string" && skin.previewUrl === `/api/skins/${skin.id}/preview` ? skin.previewUrl : undefined;
|
||||
return [{
|
||||
id: skin.id,
|
||||
name: skin.name as string,
|
||||
version: skin.version as string,
|
||||
author: skin.author as string,
|
||||
license: skin.license as string,
|
||||
minAppVersion: skin.minAppVersion as string,
|
||||
...(typeof skin.description === "string" ? { description: skin.description } : {}),
|
||||
...(previewUrl ? { previewUrl } : {}),
|
||||
installedAt: Number.isFinite(skin.installedAt) ? Number(skin.installedAt) : 0,
|
||||
enabled: skin.enabled !== false,
|
||||
}];
|
||||
});
|
||||
publicDirectoryLoaded = true;
|
||||
publicEnabledSkinIds = new Set([
|
||||
...BUILTIN_SKIN_CATALOG.map((skin) => skin.id),
|
||||
...directorySkins.filter((skin) => skin.enabled).map((skin) => skin.id),
|
||||
]);
|
||||
const requestedDefault = (payload as { defaultSkinId?: unknown }).defaultSkinId;
|
||||
publicDefaultSkinId = typeof requestedDefault === "string" && publicEnabledSkinIds.has(requestedDefault) ? requestedDefault : "builtin.light";
|
||||
return [...BUILTIN_SKIN_CATALOG, ...directorySkins.filter((skin) => skin.enabled)];
|
||||
} catch {
|
||||
publicDirectoryLoaded = false;
|
||||
publicEnabledSkinIds = new Set(BUILTIN_SKIN_CATALOG.map((skin) => skin.id));
|
||||
publicDefaultSkinId = "builtin.light";
|
||||
return BUILTIN_SKIN_CATALOG;
|
||||
}
|
||||
}
|
||||
|
||||
export async function uploadSkinPackage(file: File, csrfToken: string, confirmReplace?: (id: string) => boolean): Promise<SkinCatalogEntry | null> {
|
||||
const { importSkinPack } = await import("./skin-pack.js");
|
||||
const skin = await importSkinPack(file);
|
||||
if (confirmReplace && !confirmReplace(skin.id)) return null;
|
||||
const response = await fetch(`/api/admin/skins/${encodeURIComponent(skin.id)}`, {
|
||||
method: "PUT",
|
||||
headers: { "content-type": "application/octet-stream", "x-csrf-token": csrfToken, accept: "application/json" },
|
||||
body: file,
|
||||
});
|
||||
const payload = await response.json().catch(() => null) as { skin?: SkinCatalogEntry; message?: string; code?: string } | null;
|
||||
if (!response.ok || !payload?.skin) throw new Error(payload?.message || payload?.code || `HTTP_${response.status}`);
|
||||
return payload.skin;
|
||||
}
|
||||
|
||||
export async function deleteSkinPackage(id: string, csrfToken: string): Promise<void> {
|
||||
const response = await fetch(`/api/admin/skins/${encodeURIComponent(id)}`, {
|
||||
method: "DELETE",
|
||||
headers: { "content-type": "application/json", "x-csrf-token": csrfToken, accept: "application/json" },
|
||||
body: "{}",
|
||||
});
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => null) as { code?: string } | null;
|
||||
throw new Error(payload?.code || `HTTP_${response.status}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import test from "node:test";
|
||||
import { strToU8, zipSync } from "fflate";
|
||||
import { importSkinPack, resolveSkinCssAssets, SkinPackError } from "./skin-pack.js";
|
||||
import { scopeBuiltinThemeForCustomSkin } from "./skin-cascade.js";
|
||||
|
||||
const manifest = {
|
||||
schemaVersion: 1,
|
||||
id: "ocean-night",
|
||||
name: "Ocean Night",
|
||||
version: "1.0.0",
|
||||
author: "WebSpeak test",
|
||||
license: "MIT",
|
||||
minAppVersion: "0.2.4",
|
||||
entry: "skin.css",
|
||||
};
|
||||
|
||||
test("skin CSS is scoped, local artwork and fonts work, and global names are isolated", async () => {
|
||||
const skin = await importSkinPack(makeSkin(`
|
||||
@font-face { font-family: "Wave Font"; src: url("assets/wave.woff2") format("woff2"); }
|
||||
@keyframes shimmer { from { opacity: .4; } to { opacity: 1; } }
|
||||
:root { --skin-accent: #00a99d; }
|
||||
[data-ws-part="voice.member"] { font-family: "Wave Font", sans-serif; animation: shimmer 1s ease-in-out; background-image: image-set("assets/backdrop.png" 1x); }
|
||||
`));
|
||||
|
||||
assert.match(skin.css, /\.ws-skin-root\[data-ws-skin="ocean-night"\] \{ --skin-accent: #00a99d; \}/);
|
||||
assert.match(skin.css, /@keyframes ws-ocean-night-shimmer/);
|
||||
assert.match(skin.css, /animation: ws-ocean-night-shimmer/);
|
||||
assert.match(skin.css, /font-family: "ws-ocean-night-Wave-Font"/);
|
||||
assert.match(skin.css, /url\("wskin-asset:assets%2Fwave\.woff2"\)/);
|
||||
assert.match(skin.css, /image-set\("wskin-asset:assets%2Fbackdrop\.png" 1x\)/);
|
||||
assert.ok(skin.warnings.some((warning) => warning.includes("localized text wrapping")));
|
||||
assert.equal(skin.contentData, undefined, "skin content is optional; WebSpeak supplies the base interface translations");
|
||||
|
||||
const resolved = resolveSkinCssAssets(skin.css, skin.assets);
|
||||
assert.match(resolved.css, /blob:/);
|
||||
resolved.objectUrls.forEach((url) => URL.revokeObjectURL(url));
|
||||
});
|
||||
|
||||
test("skin CSS permits visual decoration but prevents layout, text-flow, and control-geometry changes", async () => {
|
||||
const skin = await importSkinPack(makeSkin('@keyframes fade-wave { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="demo.wave"] { opacity: var(--skin-decoration-opacity); animation: fade-wave 1s; box-shadow: 0 0 14px #4ff; }'));
|
||||
assert.match(skin.css, /opacity: var\(--skin-decoration-opacity\)/);
|
||||
assert.match(skin.css, /box-shadow: 0 0 14px #4ff/);
|
||||
assert.match(skin.css, /from \{ opacity: 0; \}/);
|
||||
assert.match(skin.css, /animation: ws-ocean-night-fade-wave 1s/);
|
||||
|
||||
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { display: none; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
|
||||
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { position: fixed; inset: 0; z-index: 99999; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
|
||||
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.member"] { padding: 30px; transform: scale(1.2); }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
|
||||
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home.hero.title"] { font-size: 3rem; line-height: 1; white-space: nowrap; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
|
||||
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home.hero.title"] { text-transform: uppercase; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
|
||||
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { opacity: 0; }')), (error: unknown) => error instanceof Error && error.message.includes("explicitly optional visual parts"));
|
||||
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="demo.wave"] span { display: none; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
|
||||
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { display: var(--skin-hidden); }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
|
||||
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { all: unset; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
|
||||
await assert.rejects(importSkinPack(makeSkin('@keyframes hide-control { to { opacity: 0; } } [data-ws-part="voice.screen-player.exit"] { animation: hide-control 1s infinite; }')), (error: unknown) => error instanceof Error && error.message.includes("explicitly optional visual parts"));
|
||||
await assert.rejects(importSkinPack(makeSkin('@keyframes hide-control { to { opacity: 0; } } [data-ws-part="control"] { animation: var(--custom-animation); }')), (error: unknown) => error instanceof Error && error.message.includes("explicitly optional visual parts"));
|
||||
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home"] { --accent: red; }')), (error: unknown) => error instanceof Error && error.message.includes("--skin- prefix"));
|
||||
await assert.rejects(importSkinPack(makeSkin(".internal-class { color: red; }")), (error: unknown) => error instanceof Error && error.message.includes("must use :root"));
|
||||
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="demo.voice-card"].private-component { color: red; }')), (error: unknown) => error instanceof Error && error.message.includes("must use :root"));
|
||||
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home"] { background-image: image-set("https://example.invalid/remote.png" 1x); }')), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_EXTERNAL_RESOURCE");
|
||||
});
|
||||
|
||||
test("custom skins can override theme appearance without !important or private class selectors", () => {
|
||||
const css = '.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-card { color: white; }';
|
||||
assert.equal(
|
||||
scopeBuiltinThemeForCustomSkin(css, "dark", "community.illusia-voice"),
|
||||
':where(.ws-skin-root[data-ws-skin="community.illusia-voice"]) .join-page .join-card { color: white; }',
|
||||
);
|
||||
});
|
||||
|
||||
test("community skins use a scoped light fallback instead of inheriting the night skin", async () => {
|
||||
const lightCss = await readFile(new URL("../skins/builtin/light/skin.css", import.meta.url), "utf8");
|
||||
const scoped = scopeBuiltinThemeForCustomSkin(lightCss, "light", "community.illusia-voice");
|
||||
assert.match(scoped, /:where\(\.ws-skin-root\[data-ws-skin="community\.illusia-voice"\]\) \{\s*color-scheme: light;/);
|
||||
assert.match(scoped, /:where\(\.ws-skin-root\[data-ws-skin="community\.illusia-voice"\]\) \.settings-content/);
|
||||
});
|
||||
|
||||
test("all public skin parts are documented and the admin console is outside skin scope", async () => {
|
||||
const [webClient, demo, skinSwitcher, languageSwitcher, admin, documentation] = await Promise.all([
|
||||
readFile(new URL("../views/WebClient.vue", import.meta.url), "utf8"),
|
||||
readFile(new URL("../views/DemoView.vue", import.meta.url), "utf8"),
|
||||
readFile(new URL("../components/SkinSwitcher.vue", import.meta.url), "utf8"),
|
||||
readFile(new URL("../components/LanguageSwitcher.vue", import.meta.url), "utf8"),
|
||||
readFile(new URL("../views/AdminView.vue", import.meta.url), "utf8"),
|
||||
readFile(new URL("../../../docs/SKIN_DEVELOPMENT.md", import.meta.url), "utf8"),
|
||||
]);
|
||||
const publicParts = new Set([...`${webClient}\n${demo}\n${skinSwitcher}\n${languageSwitcher}`.matchAll(/data-ws-part="([^"]+)"/g)].map((match) => match[1]));
|
||||
for (const part of publicParts) assert.ok(documentation.includes(`\`${part}\``), `Undocumented skin part: ${part}`);
|
||||
assert.match(skinSwitcher, /data-ws-skin-id/);
|
||||
assert.match(skinSwitcher, /data-ws-state/);
|
||||
assert.match(languageSwitcher, /data-ws-language/);
|
||||
assert.doesNotMatch(admin, /ws-skin-root|data-ws-page=/);
|
||||
assert.doesNotMatch(demo, /:global\(:root\[data-theme="dark"\]\)/);
|
||||
assert.match(demo, /\.demo-page\[data-ws-skin="builtin\.dark"\]/);
|
||||
});
|
||||
|
||||
test("public skin and language selectors keep readable light surfaces in dark mode", async () => {
|
||||
const [skinSwitcher, languageSwitcher, darkSkin] = await Promise.all([
|
||||
readFile(new URL("../components/SkinSwitcher.vue", import.meta.url), "utf8"),
|
||||
readFile(new URL("../components/LanguageSwitcher.vue", import.meta.url), "utf8"),
|
||||
readFile(new URL("../skins/builtin/dark/skin.css", import.meta.url), "utf8"),
|
||||
]);
|
||||
|
||||
assert.match(skinSwitcher, /\.skin-trigger\s*\{[^}]*background:\s*rgba\(250,\s*254,\s*255/i);
|
||||
assert.match(skinSwitcher, /\.skin-dropdown\s*\{[^}]*background:\s*linear-gradient/i);
|
||||
assert.match(skinSwitcher, /\.skin-option\s*\{[^}]*color:\s*#123849/i);
|
||||
assert.match(languageSwitcher, /\.language-dropdown\s*\{[^}]*background:\s*#fff/i);
|
||||
assert.doesNotMatch(darkSkin, /\.language-switcher\s+\.language-(?:trigger|dropdown|option)/);
|
||||
});
|
||||
|
||||
test("skin content supports localized interface message overrides and includes the preview as an asset", async () => {
|
||||
const content = { defaultLocale: "en", locales: { en: { home: { title: "Welcome" }, messages: { speakingNow: "Live now" } } } };
|
||||
const skin = await importSkinPack(makeSkin('[data-ws-part="demo.voice-card"] { background: url(assets/preview.png); }', content));
|
||||
assert.equal(skin.contentData?.locales.en?.messages?.speakingNow, "Live now");
|
||||
assert.equal(skin.previewBlob?.type, "image/png");
|
||||
assert.ok(skin.assets["assets/preview.png"]);
|
||||
});
|
||||
|
||||
test("the ILLUSIA visual-only example imports without replacing WebSpeak's base translations", async () => {
|
||||
const bytes = await readFile(new URL("../../../docs/examples/illusia-voice.wskin", import.meta.url));
|
||||
const skin = await importSkinPack(new File([bytes], "illusia-voice.wskin", { type: "application/octet-stream" }));
|
||||
assert.equal(skin.id, "community.illusia-voice");
|
||||
assert.equal(skin.name, "ILLUSIA风");
|
||||
assert.equal(skin.version, "1.0.27");
|
||||
assert.equal(skin.contentData, undefined);
|
||||
assert.equal(skin.previewBlob?.type, "image/webp");
|
||||
assert.ok(skin.assets["assets/background-composite.webp"]);
|
||||
assert.ok(skin.assets["assets/bg-room-main.webp"]);
|
||||
assert.ok(skin.assets["assets/banner-character-main.webp"]);
|
||||
assert.ok(skin.assets["assets/foreground-headphone.webp"]);
|
||||
assert.ok(skin.assets["assets/chat-empty-chibi.webp"]);
|
||||
assert.ok(skin.assets["assets/visitor-avatar.webp"]);
|
||||
assert.ok(skin.assets["assets/button-mascot.webp"]);
|
||||
assert.ok(skin.assets["assets/footer-wave.png"]);
|
||||
assert.match(skin.css, /\.ws-skin-root\[data-ws-skin="community\.illusia-voice"\]/);
|
||||
assert.match(skin.css, /home\.visitors.*?nth-child\(2\)/s);
|
||||
assert.match(skin.css, /skin\.menu/);
|
||||
assert.match(skin.css, /skin\.menu[^{}]*\[role="listbox"\]/);
|
||||
assert.match(skin.css, /skin\.option/);
|
||||
assert.match(skin.css, /language\.trigger/);
|
||||
assert.match(skin.css, /language\.menu[^{}]*\[role="listbox"\]/);
|
||||
assert.match(skin.css, /language\.option/);
|
||||
assert.match(skin.css, /data-ws-skin-id="community\.illusia-voice"/);
|
||||
assert.match(skin.css, /data-ws-part="home\.join-card\.waveform"/);
|
||||
assert.match(skin.css, /data-ws-part="home\.join-card\.sonar"/);
|
||||
assert.match(skin.css, /data-ws-part="home\.join-card"\]\s*\{[^}]*background-image:\s*url\("wskin-asset:assets%2Fbanner-mascot-blob\.webp"\)/s);
|
||||
assert.doesNotMatch(skin.css, /data-ws-part="home\.join-card"\]\s*\{[^}]*radial-gradient/s);
|
||||
assert.match(skin.css, /data-ws-part="voice\.member-panel"\]\s*\{[^}]*background-position:\s*0 0, right top, right top, center/s);
|
||||
assert.match(skin.css, /data-ws-part="voice\.member-panel"\]\s*::before\s*\{[^}]*background-image:\s*url\("wskin-asset:assets%2Fforeground-headphone\.webp"\)[^}]*filter:\s*drop-shadow/s);
|
||||
assert.doesNotMatch(skin.css, /illusia-card-signal|illusia-card-glow/);
|
||||
assert.match(skin.css, /illusia-home-aura/);
|
||||
assert.match(skin.css, /voice\.activity[\s\S]*?wskin-asset:assets%2Fbanner-character-main\.webp/);
|
||||
assert.match(skin.css, /voice\.activity\.artwork[\s\S]*?wskin-asset:assets%2Fbanner-character-main\.webp/);
|
||||
assert.match(skin.css, /data-ws-part="voice\.activity"\]\s*\{[^}]*border-color:\s*rgba\(113, 211, 222, \.62\);[^}]*border-radius:\s*24px;[^}]*background-image:[\s\S]*?bg-room-main\.webp[^}]*backdrop-filter:\s*blur\(10px\)/);
|
||||
assert.match(skin.css, /voice\.activity\.artwork[^{}]*\{[^}]*background-position:\s*right 16px bottom 8px;[^}]*background-size:\s*auto 150px;[^}]*filter:\s*drop-shadow\(0 18px 22px/);
|
||||
assert.match(skin.css, /@media \(max-width: 1100px\)[\s\S]*?voice\.activity\.artwork[^{}]*\{[^}]*background-position:\s*right 12px bottom 6px;[^}]*background-size:\s*auto 118px/);
|
||||
assert.doesNotMatch(skin.css, /voice\.chat\.empty[^{}]*data-ws-state="messages-empty"\]\s*> :first-child/);
|
||||
assert.match(skin.css, /data-ws-part="voice\.channel-group"\]\s*\{[^}]*border-color:\s*rgba\(8, 126, 134, \.32\)/);
|
||||
assert.match(skin.css, /data-ws-part="voice\.channel-group"\]\[data-ws-state="current"\]\s*\{[^}]*border-color:\s*rgba\(8, 126, 134, \.48\)/);
|
||||
assert.match(skin.css, /voice\.chat\.empty[^{}]*data-ws-state="messages-empty"[\s\S]*?wskin-asset:assets%2Fchat-empty-chibi\.webp/);
|
||||
assert.match(skin.css, /voice\.chat\.empty[^{}]*\{[^}]*background-size:\s*22px 22px, 300px 250px, cover, min\(340px, 46vw\) auto/s);
|
||||
assert.match(skin.css, /voice\.chat\.empty[^{}]*data-ws-state="messages-empty"[^{}]*\{[^}]*background-position:\s*0 0, right center, center, center 8px;[^}]*background-size:\s*22px 22px, 300px 250px, cover, min\(340px, 46vw\) auto/s);
|
||||
assert.match(skin.css, /data-ws-state="messages-empty"\]::before\s*\{[^}]*color:\s*rgba\(71, 126, 148, \.9\);[^}]*radial-gradient\(circle, #527f91 0 1\.6px/s);
|
||||
assert.match(skin.css, /data-ws-state="messages-empty"\]::after\s*\{[^}]*color:\s*rgba\(71, 126, 148, \.9\)/s);
|
||||
assert.match(skin.css, /@media \(max-width: 1100px\)[\s\S]*?voice\.chat\.empty[^{}]*\{[^}]*background-position:\s*0 0, right 8px center, center, center 8px;[^}]*background-size:\s*22px 22px, 260px 220px, cover, min\(300px, 66vw\) auto/s);
|
||||
assert.match(skin.css, /@media \(max-width: 1100px\)[\s\S]*?voice\.chat\.empty[^{}]*data-ws-state="messages-empty"[^{}]*\{[^}]*background-position:\s*0 0, right center, center, center 8px;[^}]*background-size:\s*22px 22px, 260px 220px, cover, min\(300px, 66vw\) auto/s);
|
||||
assert.doesNotMatch(skin.css, /data-ws-state="messages-empty"[^{}]*\{[^}]*color: transparent/s);
|
||||
assert.doesNotMatch(skin.css, /(?:^|[;{\s])(?:position|inset|top|right|bottom|left|width|height|min-height|padding|z-index|transform)\s*:/);
|
||||
assert.doesNotMatch(skin.css, /\[data-ws-part="home\.join-card"\]\s*\{[^}]*animation:/);
|
||||
assert.doesNotMatch(skin.css, /\[data-ws-part="home\.join-card"\]\s*\{\s*animation: none;/);
|
||||
assert.match(skin.css, /home\.footer[\s\S]*?footer-wave\.png/);
|
||||
assert.match(skin.css, /\[data-ws-part="home"\] \[data-ws-part="home\.connect"\]/);
|
||||
assert.doesNotMatch(skin.css, /\[data-ws-page="home"\] \[data-ws-part="home\.connect"\]/);
|
||||
assert.match(skin.css, /home\.connect[\s\S]*?wskin-asset:assets%2Fbutton-mascot\.webp/);
|
||||
assert.match(skin.css, /data-ws-page="demo"[^{}]*\{[^}]*wskin-asset:assets%2Fforeground-headphone\.webp[^}]*background-position:\s*left bottom, center, center;[^}]*background-size:\s*min\(34vw, 430px\) auto, auto, cover/s);
|
||||
assert.match(skin.css, /voice\.screen-player[\s\S]*?background: linear-gradient\(135deg, rgba\(250, 255, 255, \.96\), rgba\(220, 245, 250, \.94\)\)/);
|
||||
assert.doesNotMatch(skin.css, /voice\.screen-player[^{}]*\{[^}]*background: rgba\(10, 34, 45, \.96\)/);
|
||||
});
|
||||
|
||||
test("the activity artwork layer floats above room content without intercepting controls", async () => {
|
||||
const css = await readFile(new URL("../styles/web-client.css", import.meta.url), "utf8");
|
||||
assert.match(css, /\.app-shell \.workspace-content\s*\{\s*position: relative;\s*isolation: isolate;/);
|
||||
assert.match(css, /\.voice-activity-artwork\s*\{\s*position: absolute;\s*z-index: 2;\s*inset: -26px 0 -48px;[^}]*pointer-events: none;/);
|
||||
assert.match(css, /\.voice-activity-artwork\s*\{[^}]*transform: perspective\(1100px\) rotateY\(-2\.5deg\) translateZ\(22px\)/);
|
||||
assert.match(css, /\.app-shell \.member-panel::before\s*\{\s*content: "";\s*position: absolute;\s*z-index: 1;\s*left: -28px;\s*bottom: 18px;\s*width: min\(430px, calc\(100vw - 24px\)\);\s*aspect-ratio: 3 \/ 2;[^}]*perspective\(1100px\) rotateY\(-8deg\)/);
|
||||
assert.match(css, /\.app-shell \.chat-empty\[data-ws-state="messages-empty"\]\s*\{[^}]*min-height: 210px;\s*padding: 126px 12px 10px;/);
|
||||
assert.match(css, /\.app-shell \.chat-panel \.section-heading,[\s\S]*?\.app-shell \.chat-panel \.message-composer\s*\{\s*position: relative;\s*z-index: 3;/);
|
||||
assert.match(css, /\.screen-share-player\s*\{[^}]*background: var\(--surface-1\)/);
|
||||
assert.match(css, /\.screen-share-player-exit\s*\{[^}]*z-index: 3;/);
|
||||
assert.match(css, /\.screen-share-player-stage\s*\{[^}]*var\(--accent\)[^}]*var\(--surface-2\)/);
|
||||
assert.match(css, /\.screen-share-player-video\s*\{[^}]*background: var\(--surface-2\)/);
|
||||
assert.match(css, /@media \(min-width: 741px\)\s*\{\s*\/\* Keep header menus above the independently stacked screen-share stage\. \*\/\s*\.app-shell \.workspace-header\s*\{\s*position: relative;\s*z-index: 40;/);
|
||||
});
|
||||
|
||||
test("channel empty state removes its bubble ornament and keeps the text-channel label", async () => {
|
||||
const [view, chat] = await Promise.all([
|
||||
readFile(new URL("../views/WebClient.vue", import.meta.url), "utf8"),
|
||||
readFile(new URL("../composables/useWebClientChat.ts", import.meta.url), "utf8"),
|
||||
]);
|
||||
assert.doesNotMatch(view, /data-ws-state="messages-empty"><div class="chat-empty-icon"/);
|
||||
assert.match(view, /class="section-kicker">\{\{ chatTabLabel \}\}/);
|
||||
assert.match(chat, /tab\.value === "channel" \? t\("textChannel"\)/);
|
||||
});
|
||||
|
||||
test("homepage motion and room content spacing preserve the ILLUSIA layout", async () => {
|
||||
const css = await readFile(new URL("../styles/web-client.css", import.meta.url), "utf8");
|
||||
assert.ok(css.includes('.join-page *:not([data-ws-part="home.join-card"])'));
|
||||
assert.ok(css.includes("animation: none !important"));
|
||||
assert.doesNotMatch(css, /\.join-page \*, \.join-page \*::before, \.join-page \*::after\s*\{\s*animation: none !important/);
|
||||
assert.ok(css.includes("padding: 0 clamp(12px, 1.4vw, 22px);"), "homepage header contents keep an inset from their container edge");
|
||||
assert.ok(css.includes(".chat-panel { margin-top: 34px; padding: 0 clamp(14px, 1.8vw, 24px) 20px;"), "chat children keep horizontal and bottom breathing room");
|
||||
assert.match(css, /\.app-shell \.voice-section \{\s*position: relative;\s*padding: clamp\(14px, 1\.8vw, 24px\);/);
|
||||
assert.match(css, /@media \(max-width: 740px\) \{\s*\.app-shell \.voice-section \{\s*padding: 14px 10px 16px;/);
|
||||
assert.match(css, /\.promise-list \{\s*display: grid;\s*width: 100%;\s*grid-template-columns: repeat\(3, minmax\(0, 1fr\)\);/);
|
||||
assert.match(css, /\.promise-item \{\s*min-width: 0;\s*min-height: 58px;[\s\S]*?padding: 9px 11px;/);
|
||||
assert.match(css, /@media \(max-width: 420px\) \{\s*\.promise-list \{\s*grid-template-columns: minmax\(0, 1fr\);/);
|
||||
assert.match(css, /\.join-card-waveform i \{[^}]*animation: screen-share-wave 1\.1s ease-in-out infinite alternate;/);
|
||||
assert.match(css, /@keyframes join-card-sonar-ring[\s\S]*?transform: scale\(\.6\); opacity: \.62;[\s\S]*?transform: scale\(1\); opacity: 0;/);
|
||||
});
|
||||
|
||||
function makeSkin(css: string, content?: unknown): File {
|
||||
const packageFiles: Record<string, Uint8Array> = {
|
||||
"manifest.json": strToU8(JSON.stringify({ ...manifest, ...(content ? { content: "content.json" } : {}), preview: "assets/preview.png" })),
|
||||
"skin.css": strToU8(css),
|
||||
"assets/backdrop.png": new Uint8Array([1, 2, 3, 4]),
|
||||
"assets/preview.png": new Uint8Array([5, 6, 7, 8]),
|
||||
"assets/wave.woff2": new Uint8Array([9, 10, 11, 12]),
|
||||
};
|
||||
if (content) packageFiles["content.json"] = strToU8(JSON.stringify(content));
|
||||
const bytes = zipSync(packageFiles);
|
||||
return new File([bytes.slice().buffer as ArrayBuffer], "skin.wskin", { type: "application/octet-stream" });
|
||||
}
|
||||
@@ -0,0 +1,718 @@
|
||||
import postcss, { type AtRule, type Declaration, type Node, type Rule } from "postcss";
|
||||
import selectorParser from "postcss-selector-parser";
|
||||
import valueParser from "postcss-value-parser";
|
||||
import { unzipSync } from "fflate";
|
||||
|
||||
const MAX_ARCHIVE_BYTES = 20 * 1024 * 1024;
|
||||
const MAX_EXPANDED_BYTES = 50 * 1024 * 1024;
|
||||
const MAX_FILE_COUNT = 128;
|
||||
const MAX_CSS_BYTES = 512 * 1024;
|
||||
const MAX_CONTENT_BYTES = 256 * 1024;
|
||||
const MAX_IMAGE_BYTES = 16 * 1024 * 1024;
|
||||
const MAX_FONT_BYTES = 4 * 1024 * 1024;
|
||||
const ALLOWED_AT_RULES = new Set(["media", "supports", "container", "layer", "font-face", "keyframes", "-webkit-keyframes"]);
|
||||
const LAYOUT_AFFECTING_PROPERTIES = new Set([
|
||||
"all", "display", "position", "top", "right", "bottom", "left", "inset", "inset-block", "inset-inline",
|
||||
"width", "height", "min-width", "min-height", "max-width", "max-height", "inline-size", "block-size",
|
||||
"min-inline-size", "min-block-size", "max-inline-size", "max-block-size", "aspect-ratio", "box-sizing",
|
||||
"gap", "row-gap", "column-gap", "grid", "flex", "order", "float", "clear", "overflow", "overflow-x",
|
||||
"overflow-y", "overflow-block", "overflow-inline", "overscroll-behavior", "z-index", "visibility",
|
||||
"pointer-events", "clip", "clip-path", "mask", "mask-image", "transform", "transform-origin", "transform-style", "translate", "scale", "rotate",
|
||||
"perspective", "perspective-origin", "contain", "content-visibility", "container", "container-name",
|
||||
"container-type", "contain-intrinsic-size", "resize", "columns", "column-count", "column-width", "scrollbar-width", "font",
|
||||
"font-size", "line-height", "letter-spacing", "word-spacing", "white-space", "word-break", "overflow-wrap", "word-wrap",
|
||||
"text-wrap", "text-overflow", "text-indent", "text-transform", "text-combine-upright", "text-autospace", "text-spacing-trim",
|
||||
"line-clamp", "tab-size", "hyphens", "line-break", "text-size-adjust", "initial-letter", "shape-outside", "baseline-shift",
|
||||
"box-orient", "box-direction", "box-lines", "ruby-position", "caption-side", "table-layout", "border-collapse", "border-spacing",
|
||||
"writing-mode", "direction", "unicode-bidi", "vertical-align", "appearance", "zoom", "scrollbar-gutter", "touch-action", "user-select", "cursor", "content",
|
||||
"position-anchor", "position-area", "position-try-fallbacks", "position-try-order", "anchor-name", "anchor-scope",
|
||||
]);
|
||||
const OPTIONAL_VISUAL_PARTS = new Set([
|
||||
"home.hero.eyebrow",
|
||||
"home.gateway-status",
|
||||
"home.features",
|
||||
"home.feature",
|
||||
"home.visitors",
|
||||
"home.join-card.waveform",
|
||||
"home.join-card.sonar",
|
||||
"voice.activity-heading",
|
||||
"voice.member.avatar",
|
||||
"voice.member.live-indicator",
|
||||
"voice.member-row.avatar",
|
||||
"voice.screen-player.viewer-avatar",
|
||||
"voice.screen-player.live",
|
||||
"demo.badge",
|
||||
"demo.wave",
|
||||
"demo.avatar",
|
||||
"demo.member-status",
|
||||
"demo.note",
|
||||
]);
|
||||
const ZIP_EOCD = 0x06054b50;
|
||||
const ZIP_CENTRAL_FILE = 0x02014b50;
|
||||
|
||||
export interface SkinManifest {
|
||||
schemaVersion: 1;
|
||||
id: string;
|
||||
name: string;
|
||||
version: string;
|
||||
author: string;
|
||||
license: string;
|
||||
description?: string;
|
||||
entry: string;
|
||||
content?: string;
|
||||
minAppVersion: string;
|
||||
preview?: string;
|
||||
}
|
||||
|
||||
export interface SkinFeatureCopy {
|
||||
title: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface SkinHomeCopy {
|
||||
brandName?: string;
|
||||
eyebrow?: string;
|
||||
title?: string;
|
||||
titleAccent?: string;
|
||||
description?: string;
|
||||
welcomeTitle?: string;
|
||||
welcomeDescription?: string;
|
||||
features?: SkinFeatureCopy[];
|
||||
}
|
||||
|
||||
export interface SkinContent {
|
||||
defaultLocale: string;
|
||||
locales: Record<string, { home?: SkinHomeCopy; messages?: Record<string, string> }>;
|
||||
}
|
||||
|
||||
export interface InstalledSkin extends SkinManifest {
|
||||
css: string;
|
||||
assets: Record<string, Blob>;
|
||||
contentData?: SkinContent;
|
||||
previewBlob?: Blob;
|
||||
warnings: string[];
|
||||
installedAt: number;
|
||||
}
|
||||
|
||||
export class SkinPackError extends Error {
|
||||
constructor(message: string, readonly code: string) {
|
||||
super(message);
|
||||
this.name = "SkinPackError";
|
||||
}
|
||||
}
|
||||
|
||||
interface ZipEntryMetadata {
|
||||
path: string;
|
||||
compressedSize: number;
|
||||
expandedSize: number;
|
||||
compression: number;
|
||||
isDirectory: boolean;
|
||||
flags: number;
|
||||
crc: number;
|
||||
localOffset: number;
|
||||
}
|
||||
|
||||
const decoder = new TextDecoder("utf-8", { fatal: true });
|
||||
|
||||
export async function importSkinPack(file: File): Promise<InstalledSkin> {
|
||||
if (!file.name.toLowerCase().endsWith(".wskin")) throw new SkinPackError("Choose a .wskin skin package.", "SKIN_FILE_TYPE");
|
||||
if (!file.size || file.size > MAX_ARCHIVE_BYTES) throw new SkinPackError("The skin package must be smaller than 20 MiB.", "SKIN_ARCHIVE_SIZE");
|
||||
|
||||
const archiveBytes = new Uint8Array(await file.arrayBuffer());
|
||||
const metadata = inspectZip(archiveBytes);
|
||||
let unpacked: Record<string, Uint8Array>;
|
||||
try {
|
||||
unpacked = unzipSync(archiveBytes);
|
||||
} catch {
|
||||
throw new SkinPackError("The skin package is damaged or uses an unsupported ZIP format.", "SKIN_ZIP_INVALID");
|
||||
}
|
||||
|
||||
const regularFiles = metadata.filter((entry) => !entry.isDirectory);
|
||||
const rootPrefix = findSingleRootFolder(regularFiles.map((entry) => entry.path));
|
||||
const files = new Map<string, Uint8Array>();
|
||||
for (const entry of regularFiles) {
|
||||
const path = rootPrefix ? entry.path.slice(rootPrefix.length) : entry.path;
|
||||
if (!path || path.startsWith("/") || path.split("/").some((part) => !part || part === "." || part === "..")) {
|
||||
throw new SkinPackError("The package contains an unsafe file path.", "SKIN_PATH_INVALID");
|
||||
}
|
||||
const bytes = unpacked[entry.path];
|
||||
if (!bytes || bytes.byteLength !== entry.expandedSize) throw new SkinPackError("A package file failed its size check.", "SKIN_ZIP_INVALID");
|
||||
files.set(path, bytes);
|
||||
}
|
||||
|
||||
const manifestBytes = files.get("manifest.json");
|
||||
if (!manifestBytes || manifestBytes.byteLength > 32 * 1024) throw new SkinPackError("The package must contain a small root-level manifest.json.", "SKIN_MANIFEST_MISSING");
|
||||
const manifest = parseManifest(manifestBytes);
|
||||
const cssBytes = files.get(manifest.entry);
|
||||
if (!cssBytes || cssBytes.byteLength > MAX_CSS_BYTES) throw new SkinPackError("The CSS entry is missing or exceeds 512 KiB.", "SKIN_CSS_SIZE");
|
||||
|
||||
const assets: Record<string, Blob> = Object.create(null) as Record<string, Blob>;
|
||||
for (const [path, bytes] of files) {
|
||||
if (["manifest.json", manifest.entry, manifest.content].includes(path)) continue;
|
||||
const mimeType = assetMimeType(path);
|
||||
if (!mimeType) throw new SkinPackError(`Unsupported package file: ${path}`, "SKIN_FILE_UNSUPPORTED");
|
||||
if (mimeType.startsWith("font/") && bytes.byteLength > MAX_FONT_BYTES) throw new SkinPackError("Fonts must be smaller than 4 MiB.", "SKIN_FONT_SIZE");
|
||||
if (mimeType.startsWith("image/") && bytes.byteLength > MAX_IMAGE_BYTES) throw new SkinPackError("Each image must be smaller than 16 MiB.", "SKIN_IMAGE_SIZE");
|
||||
assets[path] = new Blob([bytes], { type: mimeType });
|
||||
}
|
||||
|
||||
let contentData: SkinContent | undefined;
|
||||
if (manifest.content) {
|
||||
const contentBytes = files.get(manifest.content);
|
||||
if (!contentBytes || contentBytes.byteLength > MAX_CONTENT_BYTES) throw new SkinPackError("content.json is missing or exceeds 256 KiB.", "SKIN_CONTENT_SIZE");
|
||||
contentData = parseContent(contentBytes);
|
||||
}
|
||||
|
||||
let previewBlob: Blob | undefined;
|
||||
if (manifest.preview) {
|
||||
const previewBytes = files.get(manifest.preview);
|
||||
const previewMime = assetMimeType(manifest.preview);
|
||||
if (!previewBytes || !previewMime?.startsWith("image/") || previewBytes.byteLength > MAX_IMAGE_BYTES) {
|
||||
throw new SkinPackError("The preview must be a supported image inside the package.", "SKIN_PREVIEW_INVALID");
|
||||
}
|
||||
previewBlob = new Blob([previewBytes], { type: previewMime });
|
||||
}
|
||||
|
||||
const compiled = compileSkinCss(decoder.decode(cssBytes), manifest.id, assets);
|
||||
return { ...manifest, css: compiled.css, assets, contentData, previewBlob, warnings: compiled.warnings, installedAt: Date.now() };
|
||||
}
|
||||
|
||||
export function resolveSkinCssAssets(css: string, assets: Record<string, Blob>): { css: string; objectUrls: string[] } {
|
||||
const objectUrls: string[] = [];
|
||||
try {
|
||||
const root = postcss.parse(css, { from: undefined });
|
||||
root.walkDecls((declaration) => {
|
||||
declaration.value = rewriteAssetUrls(declaration.value, (assetPath) => {
|
||||
const blob = assets[assetPath];
|
||||
if (!blob) throw new SkinPackError(`Skin asset is missing: ${assetPath}`, "SKIN_ASSET_MISSING");
|
||||
const url = URL.createObjectURL(blob);
|
||||
objectUrls.push(url);
|
||||
return url;
|
||||
});
|
||||
});
|
||||
return { css: root.toString(), objectUrls };
|
||||
} catch (error) {
|
||||
objectUrls.forEach((url) => URL.revokeObjectURL(url));
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function inspectZip(bytes: Uint8Array): ZipEntryMetadata[] {
|
||||
if (bytes.byteLength < 22) throw new SkinPackError("The selected file is not a valid ZIP package.", "SKIN_ZIP_INVALID");
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
const minOffset = Math.max(0, bytes.byteLength - 22 - 0xffff);
|
||||
let eocd = -1;
|
||||
for (let offset = bytes.byteLength - 22; offset >= minOffset; offset -= 1) {
|
||||
if (view.getUint32(offset, true) === ZIP_EOCD) { eocd = offset; break; }
|
||||
}
|
||||
if (eocd < 0) throw new SkinPackError("The selected file is not a valid ZIP package.", "SKIN_ZIP_INVALID");
|
||||
const disk = view.getUint16(eocd + 4, true);
|
||||
const centralDisk = view.getUint16(eocd + 6, true);
|
||||
const entriesOnDisk = view.getUint16(eocd + 8, true);
|
||||
const entryCount = view.getUint16(eocd + 10, true);
|
||||
const centralSize = view.getUint32(eocd + 12, true);
|
||||
const centralOffset = view.getUint32(eocd + 16, true);
|
||||
const commentLength = view.getUint16(eocd + 20, true);
|
||||
if (disk !== 0 || centralDisk !== 0 || entriesOnDisk !== entryCount || !entryCount || entryCount === 0xffff || centralSize === 0xffffffff || centralOffset === 0xffffffff || eocd + 22 + commentLength !== bytes.byteLength) {
|
||||
throw new SkinPackError("Multi-disk and ZIP64 skin packages are not supported.", "SKIN_ZIP_FORMAT");
|
||||
}
|
||||
if (entryCount > MAX_FILE_COUNT || centralOffset + centralSize !== eocd) throw new SkinPackError("The package contains too many files or an invalid directory.", "SKIN_FILE_COUNT");
|
||||
|
||||
const entries: ZipEntryMetadata[] = [];
|
||||
const seenPaths = new Set<string>();
|
||||
let expandedTotal = 0;
|
||||
let compressedTotal = 0;
|
||||
let offset = centralOffset;
|
||||
for (let index = 0; index < entryCount; index += 1) {
|
||||
if (offset + 46 > eocd || view.getUint32(offset, true) !== ZIP_CENTRAL_FILE) throw new SkinPackError("The package has an invalid ZIP directory entry.", "SKIN_ZIP_INVALID");
|
||||
const flags = view.getUint16(offset + 8, true);
|
||||
const compression = view.getUint16(offset + 10, true);
|
||||
const compressedSize = view.getUint32(offset + 20, true);
|
||||
const expandedSize = view.getUint32(offset + 24, true);
|
||||
const nameLength = view.getUint16(offset + 28, true);
|
||||
const extraLength = view.getUint16(offset + 30, true);
|
||||
const commentSize = view.getUint16(offset + 32, true);
|
||||
const diskStart = view.getUint16(offset + 34, true);
|
||||
const externalAttributes = view.getUint32(offset + 38, true);
|
||||
const localOffset = view.getUint32(offset + 42, true);
|
||||
const recordEnd = offset + 46 + nameLength + extraLength + commentSize;
|
||||
if (recordEnd > eocd || diskStart !== 0 || flags & ~0x0800 || (compression !== 0 && compression !== 8) || compressedSize === 0xffffffff || expandedSize === 0xffffffff || localOffset === 0xffffffff) throw new SkinPackError("Encrypted, multi-disk, and unsupported ZIP entries are not allowed.", "SKIN_ZIP_FORMAT");
|
||||
const unixFileType = (externalAttributes >>> 16) & 0xf000;
|
||||
if (unixFileType !== 0 && unixFileType !== 0x8000 && unixFileType !== 0x4000) throw new SkinPackError("Only regular files and directories are allowed in a skin package.", "SKIN_FILE_TYPE");
|
||||
let rawName: string;
|
||||
try { rawName = decoder.decode(bytes.subarray(offset + 46, offset + 46 + nameLength)); }
|
||||
catch { throw new SkinPackError("A package path is not valid UTF-8.", "SKIN_PATH_INVALID"); }
|
||||
const path = validateArchivePath(rawName);
|
||||
const isDirectory = path.endsWith("/");
|
||||
if ((unixFileType === 0x4000) !== isDirectory && unixFileType !== 0) throw new SkinPackError("ZIP file type does not match its path.", "SKIN_FILE_TYPE");
|
||||
if (isDirectory && (compressedSize !== 0 || expandedSize !== 0)) throw new SkinPackError("ZIP directory entries cannot contain data.", "SKIN_ZIP_INVALID");
|
||||
if (compression === 0 && compressedSize !== expandedSize) throw new SkinPackError("A stored ZIP entry has inconsistent sizes.", "SKIN_ZIP_INVALID");
|
||||
if (seenPaths.has(path.toLowerCase())) throw new SkinPackError("The package contains duplicate or case-conflicting paths.", "SKIN_PATH_DUPLICATE");
|
||||
seenPaths.add(path.toLowerCase());
|
||||
expandedTotal += expandedSize;
|
||||
compressedTotal += compressedSize;
|
||||
if (expandedTotal > MAX_EXPANDED_BYTES) throw new SkinPackError("The expanded skin package must be smaller than 50 MiB.", "SKIN_EXPANDED_SIZE");
|
||||
if (expandedSize > 1024 * 1024 && expandedSize > Math.max(compressedSize, 1) * 250) throw new SkinPackError("The package has an abnormal compression ratio.", "SKIN_COMPRESSION_RATIO");
|
||||
entries.push({ path, compressedSize, expandedSize, compression, isDirectory, flags, crc: view.getUint32(offset + 16, true), localOffset });
|
||||
offset = recordEnd;
|
||||
}
|
||||
if (offset !== centralOffset + centralSize || compressedTotal > bytes.byteLength) throw new SkinPackError("The package directory is inconsistent.", "SKIN_ZIP_INVALID");
|
||||
validateLocalEntries(bytes, entries, centralOffset);
|
||||
return entries;
|
||||
}
|
||||
|
||||
function validateLocalEntries(bytes: Uint8Array, entries: ZipEntryMetadata[], centralOffset: number): void {
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
const spans: Array<{ start: number; end: number }> = [];
|
||||
for (const entry of entries) {
|
||||
const offset = entry.localOffset;
|
||||
if (offset + 30 > centralOffset || view.getUint32(offset, true) !== 0x04034b50) throw new SkinPackError("A ZIP local file header is invalid.", "SKIN_ZIP_INVALID");
|
||||
const flags = view.getUint16(offset + 6, true);
|
||||
const compression = view.getUint16(offset + 8, true);
|
||||
const crc = view.getUint32(offset + 14, true);
|
||||
const compressedSize = view.getUint32(offset + 18, true);
|
||||
const expandedSize = view.getUint32(offset + 22, true);
|
||||
const nameLength = view.getUint16(offset + 26, true);
|
||||
const extraLength = view.getUint16(offset + 28, true);
|
||||
const headerEnd = offset + 30 + nameLength + extraLength;
|
||||
if (headerEnd > centralOffset || flags !== entry.flags || compression !== entry.compression || crc !== entry.crc || compressedSize !== entry.compressedSize || expandedSize !== entry.expandedSize) {
|
||||
throw new SkinPackError("ZIP local and central headers disagree.", "SKIN_ZIP_INVALID");
|
||||
}
|
||||
let localPath: string;
|
||||
try { localPath = decoder.decode(bytes.subarray(offset + 30, offset + 30 + nameLength)); }
|
||||
catch { throw new SkinPackError("A package path is not valid UTF-8.", "SKIN_PATH_INVALID"); }
|
||||
if (localPath !== entry.path) throw new SkinPackError("ZIP local and central filenames disagree.", "SKIN_ZIP_INVALID");
|
||||
const end = headerEnd + entry.compressedSize;
|
||||
if (end > centralOffset) throw new SkinPackError("A ZIP entry overlaps the central directory.", "SKIN_ZIP_INVALID");
|
||||
spans.push({ start: offset, end });
|
||||
}
|
||||
spans.sort((left, right) => left.start - right.start);
|
||||
for (let index = 1; index < spans.length; index += 1) {
|
||||
if (spans[index].start < spans[index - 1].end) throw new SkinPackError("ZIP local file entries overlap.", "SKIN_ZIP_INVALID");
|
||||
}
|
||||
}
|
||||
|
||||
function validateArchivePath(rawPath: string): string {
|
||||
if (!rawPath || rawPath.includes("\\") || rawPath.startsWith("/") || /^[a-z]:/i.test(rawPath) || rawPath.includes("\0")) {
|
||||
throw new SkinPackError("The package contains an absolute or unsafe path.", "SKIN_PATH_INVALID");
|
||||
}
|
||||
const segments = rawPath.split("/");
|
||||
const directory = segments.at(-1) === "";
|
||||
const usableSegments = directory ? segments.slice(0, -1) : segments;
|
||||
if (!usableSegments.length || usableSegments.some((segment) => !segment || segment === "." || segment === ".." || segment.includes(":"))) {
|
||||
throw new SkinPackError("The package contains an unsafe path segment.", "SKIN_PATH_INVALID");
|
||||
}
|
||||
return usableSegments.join("/") + (directory ? "/" : "");
|
||||
}
|
||||
|
||||
function findSingleRootFolder(paths: string[]): string {
|
||||
if (paths.includes("manifest.json")) return "";
|
||||
const firstSegments = paths.map((path) => path.split("/")[0]);
|
||||
const candidate = firstSegments[0];
|
||||
if (!candidate || !paths.every((path) => path.startsWith(`${candidate}/`))) return "";
|
||||
return `${candidate}/`;
|
||||
}
|
||||
|
||||
function parseManifest(bytes: Uint8Array): SkinManifest {
|
||||
let value: unknown;
|
||||
try { value = JSON.parse(decoder.decode(bytes)); }
|
||||
catch { throw new SkinPackError("manifest.json must contain valid UTF-8 JSON.", "SKIN_MANIFEST_INVALID"); }
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) throw new SkinPackError("manifest.json must be an object.", "SKIN_MANIFEST_INVALID");
|
||||
const raw = value as Record<string, unknown>;
|
||||
const stringField = (key: string, max: number, required = true): string | undefined => {
|
||||
const field = raw[key];
|
||||
if (field == null && !required) return undefined;
|
||||
if (typeof field !== "string" || !field.trim() || field.length > max) throw new SkinPackError(`manifest.json has an invalid ${key} field.`, "SKIN_MANIFEST_INVALID");
|
||||
return field.trim();
|
||||
};
|
||||
if (raw.schemaVersion !== 1) throw new SkinPackError("This skin package version is not supported.", "SKIN_SCHEMA_VERSION");
|
||||
const id = stringField("id", 80)!;
|
||||
if (!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(id) || id.startsWith("builtin.")) throw new SkinPackError("Skin IDs must be unique lowercase IDs and cannot use the reserved builtin. prefix.", "SKIN_ID_INVALID");
|
||||
const entry = stringField("entry", 120)!;
|
||||
const content = stringField("content", 120, false);
|
||||
const preview = stringField("preview", 120, false);
|
||||
for (const path of [entry, content, preview].filter((item): item is string => Boolean(item))) {
|
||||
if (path.startsWith("/") || path.includes("\\") || path.split("/").some((part) => !part || part === "." || part === "..")) throw new SkinPackError(`manifest.json has an unsafe path: ${path}`, "SKIN_PATH_INVALID");
|
||||
}
|
||||
const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
|
||||
const version = stringField("version", 32)!;
|
||||
const minAppVersion = stringField("minAppVersion", 32)!;
|
||||
if (!semver.test(version) || !semver.test(minAppVersion)) throw new SkinPackError("Skin and minimum app versions must use semantic version format.", "SKIN_MANIFEST_INVALID");
|
||||
if (!entry.toLowerCase().endsWith(".css") || (content && !content.toLowerCase().endsWith(".json")) || (preview && !assetMimeType(preview)?.startsWith("image/"))) throw new SkinPackError("The entry must be CSS, content must be JSON, and preview must be a supported image.", "SKIN_MANIFEST_INVALID");
|
||||
const declaredFiles = ["manifest.json", entry, ...(content ? [content] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase());
|
||||
if (new Set(declaredFiles).size !== declaredFiles.length) throw new SkinPackError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID");
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
id,
|
||||
name: stringField("name", 80)!,
|
||||
version,
|
||||
author: stringField("author", 80)!,
|
||||
license: stringField("license", 80)!,
|
||||
description: stringField("description", 400, false),
|
||||
entry,
|
||||
content,
|
||||
minAppVersion,
|
||||
preview,
|
||||
};
|
||||
}
|
||||
|
||||
function parseContent(bytes: Uint8Array): SkinContent {
|
||||
let raw: unknown;
|
||||
try { raw = JSON.parse(decoder.decode(bytes)); }
|
||||
catch { throw new SkinPackError("content.json must contain valid UTF-8 JSON.", "SKIN_CONTENT_INVALID"); }
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new SkinPackError("content.json must be an object.", "SKIN_CONTENT_INVALID");
|
||||
const root = raw as Record<string, unknown>;
|
||||
if (typeof root.defaultLocale !== "string" || !/^[a-z]{2,3}(?:-[A-Z]{2})?$/.test(root.defaultLocale) || !root.locales || typeof root.locales !== "object" || Array.isArray(root.locales)) throw new SkinPackError("content.json needs a valid defaultLocale and locales.", "SKIN_CONTENT_INVALID");
|
||||
const localeEntries = Object.entries(root.locales as Record<string, unknown>);
|
||||
if (!localeEntries.length || localeEntries.length > 20) throw new SkinPackError("content.json must contain between 1 and 20 locales.", "SKIN_CONTENT_INVALID");
|
||||
const allowed = new Set<keyof SkinHomeCopy>(["brandName", "eyebrow", "title", "titleAccent", "description", "welcomeTitle", "welcomeDescription", "features"]);
|
||||
const locales: SkinContent["locales"] = {};
|
||||
for (const [locale, entry] of localeEntries) {
|
||||
if (!/^[a-z]{2,3}(?:-[A-Z]{2})?$/.test(locale) || !entry || typeof entry !== "object" || Array.isArray(entry)) throw new SkinPackError("content.json contains an invalid locale entry.", "SKIN_CONTENT_INVALID");
|
||||
const localeValue = entry as Record<string, unknown>;
|
||||
const localeCopy: SkinContent["locales"][string] = {};
|
||||
if (localeValue.home !== undefined) {
|
||||
if (!localeValue.home || typeof localeValue.home !== "object" || Array.isArray(localeValue.home)) throw new SkinPackError("A locale home section must be an object.", "SKIN_CONTENT_INVALID");
|
||||
const homeCopy: SkinHomeCopy = {};
|
||||
for (const [key, field] of Object.entries(localeValue.home as Record<string, unknown>)) {
|
||||
if (!allowed.has(key as keyof SkinHomeCopy)) throw new SkinPackError(`Unknown homepage content field: ${key}`, "SKIN_CONTENT_INVALID");
|
||||
if (key === "features") {
|
||||
if (!Array.isArray(field) || field.length > 8) throw new SkinPackError("Each locale may define up to 8 homepage features.", "SKIN_CONTENT_INVALID");
|
||||
homeCopy.features = field.map((item) => {
|
||||
if (!item || typeof item !== "object" || Array.isArray(item)) throw new SkinPackError("A homepage feature must be an object.", "SKIN_CONTENT_INVALID");
|
||||
const feature = item as Record<string, unknown>;
|
||||
if (typeof feature.title !== "string" || typeof feature.description !== "string" || feature.title.length > 80 || feature.description.length > 240) throw new SkinPackError("Homepage feature text is too long or invalid.", "SKIN_CONTENT_INVALID");
|
||||
return { title: feature.title, description: feature.description };
|
||||
});
|
||||
} else if (typeof field === "string" && field.length <= 500) {
|
||||
homeCopy[key as Exclude<keyof SkinHomeCopy, "features">] = field;
|
||||
} else {
|
||||
throw new SkinPackError(`Invalid or oversized homepage content field: ${key}`, "SKIN_CONTENT_INVALID");
|
||||
}
|
||||
}
|
||||
localeCopy.home = homeCopy;
|
||||
}
|
||||
if (localeValue.messages !== undefined) {
|
||||
if (!localeValue.messages || typeof localeValue.messages !== "object" || Array.isArray(localeValue.messages)) throw new SkinPackError("Locale messages must be an object.", "SKIN_CONTENT_INVALID");
|
||||
const messageEntries = Object.entries(localeValue.messages as Record<string, unknown>);
|
||||
if (messageEntries.length > 200) throw new SkinPackError("Each locale may override up to 200 interface strings.", "SKIN_CONTENT_INVALID");
|
||||
const messages: Record<string, string> = {};
|
||||
for (const [key, text] of messageEntries) {
|
||||
if (!/^[a-z][a-zA-Z0-9.]*$/.test(key) || typeof text !== "string" || text.length > 500) throw new SkinPackError("A locale message key or value is invalid or too long.", "SKIN_CONTENT_INVALID");
|
||||
messages[key] = text;
|
||||
}
|
||||
localeCopy.messages = messages;
|
||||
}
|
||||
if (!localeCopy.home && !localeCopy.messages) throw new SkinPackError("Each locale must define home content or messages.", "SKIN_CONTENT_INVALID");
|
||||
locales[locale] = localeCopy;
|
||||
}
|
||||
if (!locales[root.defaultLocale]) throw new SkinPackError("defaultLocale must have a matching content entry.", "SKIN_CONTENT_INVALID");
|
||||
return { defaultLocale: root.defaultLocale, locales };
|
||||
}
|
||||
|
||||
function compileSkinCss(source: string, id: string, assets: Record<string, Blob>): { css: string; warnings: string[] } {
|
||||
const size = new TextEncoder().encode(source).byteLength;
|
||||
if (!size || size > MAX_CSS_BYTES) throw new SkinPackError("The CSS entry must be between 1 byte and 512 KiB.", "SKIN_CSS_SIZE");
|
||||
let root: postcss.Root;
|
||||
try { root = postcss.parse(source, { from: undefined }); }
|
||||
catch (error) { throw new SkinPackError(`The CSS file could not be parsed: ${(error as Error).message}`, "SKIN_CSS_INVALID"); }
|
||||
|
||||
const scope = `.ws-skin-root[data-ws-skin="${id}"]`;
|
||||
const namespace = `ws-${id.replace(/[^a-z0-9_-]/gi, "-")}`;
|
||||
const scopeNodes = selectorParser().astSync(scope).first!.nodes.map((node) => node.clone());
|
||||
const warnings = new Set<string>();
|
||||
const keyframeNames = new Map<string, string>();
|
||||
const fontFamilyNames = new Map<string, string>();
|
||||
const hideableRules = new WeakSet<Rule>();
|
||||
let nodeCount = 0;
|
||||
root.walk((node) => {
|
||||
nodeCount += 1;
|
||||
if (nodeCount > 12000) throw new SkinPackError("The CSS file contains too many rules.", "SKIN_CSS_COMPLEXITY");
|
||||
});
|
||||
|
||||
root.walkAtRules((rule: AtRule) => {
|
||||
const name = rule.name.toLowerCase();
|
||||
if (!ALLOWED_AT_RULES.has(name)) throw rule.error(`The @${rule.name} rule is not allowed in a skin package.`);
|
||||
if (name.endsWith("keyframes")) {
|
||||
const keyframeName = rule.params.trim();
|
||||
if (!/^[-_a-z][-_a-z0-9]*$/i.test(keyframeName)) throw rule.error("Keyframe names must be simple CSS identifiers.");
|
||||
keyframeNames.set(keyframeName, `${namespace}-${keyframeName}`);
|
||||
rule.params = `${namespace}-${keyframeName}`;
|
||||
} else if (name === "layer") {
|
||||
const layers = rule.params.split(",").map((layer) => layer.trim());
|
||||
if (!layers.length || layers.some((layer) => !layer || !layer.split(".").every((part) => /^[-_a-z][-_a-z0-9]*$/i.test(part)))) {
|
||||
throw rule.error("Skin CSS must use named @layer values so layer names can be isolated.");
|
||||
}
|
||||
rule.params = layers.map((layer) => `${namespace}-${layer.split(".").join(`.${namespace}-`)}`).join(", ");
|
||||
} else if (name === "font-face") {
|
||||
if (/\blocal\s*\(/i.test(rule.toString())) throw rule.error("@font-face local() is not allowed; include a WOFF2 file in the package.");
|
||||
const family = rule.nodes?.find((node): node is Declaration => node.type === "decl" && node.prop.toLowerCase() === "font-family");
|
||||
if (!family) throw rule.error("Each @font-face rule must declare font-family.");
|
||||
const originalFamily = parseSingleFontFamily(family.value);
|
||||
const scopedFamily = `${namespace}-${originalFamily.replace(/[^a-z0-9_-]/gi, "-")}`;
|
||||
fontFamilyNames.set(originalFamily.toLowerCase(), scopedFamily);
|
||||
family.value = `"${scopedFamily}"`;
|
||||
}
|
||||
});
|
||||
|
||||
root.walkRules((rule: Rule) => {
|
||||
if (hasKeyframesAncestor(rule)) return;
|
||||
if (rule.parent?.type === "rule") throw rule.error("Nested style rules are not supported; use flat selectors.");
|
||||
if (!selectorUsesPublicHook(rule.selector)) throw rule.error("Skin selectors must use :root, [data-ws-page], or [data-ws-part] so they stay attached to WebSpeak's stable visual interface.");
|
||||
if (targetsOnlyOptionalVisualParts(rule.selector)) hideableRules.add(rule);
|
||||
try {
|
||||
rule.selector = selectorParser((selectors) => {
|
||||
selectors.each((selector) => {
|
||||
const text = selector.toString().trim();
|
||||
if (!text) throw new SkinPackError("Empty selectors are not allowed.", "SKIN_CSS_SELECTOR");
|
||||
if (/:global\s*\(|:host(?:-context)?\b/i.test(text)) throw new SkinPackError("Shadow and global escape selectors are not allowed.", "SKIN_CSS_SELECTOR");
|
||||
if (/^:root\b/.test(text)) {
|
||||
selector.replaceWith(selectorParser().astSync(text.replace(/^:root\b/, scope)).first!.clone());
|
||||
return;
|
||||
}
|
||||
selector.prepend(selectorParser.combinator({ value: " " }));
|
||||
for (let index = scopeNodes.length - 1; index >= 0; index -= 1) selector.prepend(scopeNodes[index].clone());
|
||||
});
|
||||
}).processSync(rule.selector);
|
||||
} catch (error) {
|
||||
if (error instanceof SkinPackError) throw error;
|
||||
throw rule.error(`A CSS selector is invalid: ${(error as Error).message}`);
|
||||
}
|
||||
});
|
||||
|
||||
const referencedKeyframes = new Set<string>();
|
||||
const nonOptionalKeyframes = new Set<string>();
|
||||
root.walkRules((rule: Rule) => {
|
||||
if (hasKeyframesAncestor(rule)) return;
|
||||
const optionalTarget = hideableRules.has(rule);
|
||||
rule.walkDecls((declaration: Declaration) => {
|
||||
const property = declaration.prop.toLowerCase();
|
||||
if (property !== "animation" && property !== "animation-name") return;
|
||||
const value = declaration.value;
|
||||
if (/\b(?:var|attr)\s*\(|\\/i.test(value)) {
|
||||
keyframeNames.forEach((_, name) => nonOptionalKeyframes.add(name));
|
||||
return;
|
||||
}
|
||||
for (const name of keyframeNames.keys()) {
|
||||
if (!referencesCssIdentifier(value, name)) continue;
|
||||
referencedKeyframes.add(name);
|
||||
if (!optionalTarget) nonOptionalKeyframes.add(name);
|
||||
}
|
||||
});
|
||||
});
|
||||
const optionalOnlyKeyframes = new Set([...referencedKeyframes]
|
||||
.filter((name) => !nonOptionalKeyframes.has(name))
|
||||
.map((name) => keyframeNames.get(name)!));
|
||||
|
||||
root.walkDecls((declaration: Declaration) => {
|
||||
const property = declaration.prop.toLowerCase();
|
||||
const value = declaration.value.trim();
|
||||
const owningRule = findOwningRule(declaration);
|
||||
const keyframesRule = owningRule ? findKeyframesRule(owningRule) : null;
|
||||
const canHideTarget = owningRule
|
||||
? hideableRules.has(owningRule) || Boolean(keyframesRule && optionalOnlyKeyframes.has(keyframesRule.params.trim()))
|
||||
: false;
|
||||
if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property)) {
|
||||
throw declaration.error("Custom skin variables must use the --skin- prefix so they cannot replace WebSpeak's structural tokens.");
|
||||
}
|
||||
if (isLayoutAffectingProperty(property)) {
|
||||
throw declaration.error("Skin CSS may change component artwork and appearance, but must not change layout, positioning, sizing, text flow, or interaction geometry.");
|
||||
}
|
||||
if (property === "font-family") warnings.add("Custom fonts can change localized text wrapping; verify every WebSpeak language before publishing.");
|
||||
if (["behavior", "-moz-binding"].includes(property) || /expression\s*\(|javascript\s*:|vbscript\s*:/i.test(value)) {
|
||||
throw declaration.error("Executable CSS values are not allowed.");
|
||||
}
|
||||
const compactValue = valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment").map((node) => node.value ?? "").join("").toLowerCase();
|
||||
if (["display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image"].includes(property) && /\b(?:var|attr)\s*\(/i.test(value)) {
|
||||
if (!canHideTarget) throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts.");
|
||||
}
|
||||
const removesVisual = property === "all"
|
||||
|| (property === "display" && compactValue === "none")
|
||||
|| (property === "visibility" && /^(?:hidden|collapse)$/.test(compactValue))
|
||||
|| (property === "opacity" && /^0(?:\.0+)?%?$/.test(compactValue))
|
||||
|| (property === "pointer-events" && compactValue === "none")
|
||||
|| (property === "clip-path" && /inset\(\s*50%/.test(compactValue))
|
||||
|| (property === "mask" && /(?:alpha\(0\)|luminance\(0\))/.test(compactValue));
|
||||
if (removesVisual && !canHideTarget) {
|
||||
throw declaration.error("Only explicitly optional visual parts may be hidden or reset; required controls and their containers must remain available.");
|
||||
}
|
||||
const visuallyRemoves = (property === "transform" && /scale(?:3d)?\(\s*0(?:\s*[,)]|\s*\))/i.test(value))
|
||||
|| (property === "clip-path" && /inset\(\s*50%/i.test(value))
|
||||
|| (property === "filter" && /(?:opacity|brightness)\(\s*0(?:%|\s*[,)]|\s*\))/i.test(value));
|
||||
if (visuallyRemoves && !canHideTarget) {
|
||||
throw declaration.error("Only explicitly optional visual parts may be visually removed.");
|
||||
}
|
||||
if (/\bz-index\s*:\s*(?:[1-9]\d{4,}|-\d{4,})\b/i.test(`${property}:${value}`) || (property === "position" && value === "fixed")) warnings.add("Fixed positioning or extreme stacking may cover important controls; check the preview on desktop and mobile.");
|
||||
const withScopedNames = rewriteScopedNames(value, property, keyframeNames, fontFamilyNames);
|
||||
declaration.value = rewriteAssetUrls(withScopedNames, (assetPath) => {
|
||||
const blob = assets[assetPath];
|
||||
if (!blob) throw declaration.error(`CSS references an asset not present in the package: ${assetPath}`);
|
||||
return `wskin-asset:${encodeURIComponent(assetPath)}`;
|
||||
});
|
||||
});
|
||||
|
||||
return { css: root.toString(), warnings: [...warnings] };
|
||||
}
|
||||
|
||||
function targetsOnlyOptionalVisualParts(selector: string): boolean {
|
||||
try {
|
||||
const parsed = selectorParser().astSync(selector);
|
||||
return parsed.nodes.length > 0 && parsed.nodes.every((item) => {
|
||||
if (item.nodes.length !== 1 || item.nodes[0].type !== "attribute") return false;
|
||||
const attribute = item.nodes[0];
|
||||
if (attribute.attribute.toLowerCase() !== "data-ws-part" || attribute.operator !== "=") return false;
|
||||
const part = (attribute.value ?? "").replace(/^['"]|['"]$/g, "");
|
||||
return OPTIONAL_VISUAL_PARTS.has(part);
|
||||
});
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function selectorUsesPublicHook(selector: string): boolean {
|
||||
try {
|
||||
const parsed = selectorParser().astSync(selector);
|
||||
return parsed.nodes.length > 0 && parsed.nodes.every((item) => {
|
||||
let scoped = false;
|
||||
let usesPrivateName = false;
|
||||
item.walk((node) => {
|
||||
if (node.type === "attribute" && ["data-ws-part", "data-ws-page"].includes(node.attribute.toLowerCase())) scoped = true;
|
||||
if (node.type === "pseudo" && node.value.toLowerCase() === ":root") scoped = true;
|
||||
if (node.type === "class" || node.type === "id") usesPrivateName = true;
|
||||
});
|
||||
return scoped && !usesPrivateName;
|
||||
});
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isLayoutAffectingProperty(property: string): boolean {
|
||||
const unprefixed = property.replace(/^-(?:webkit|moz|ms|o)-/, "");
|
||||
if (LAYOUT_AFFECTING_PROPERTIES.has(unprefixed)) return true;
|
||||
if (/^(?:margin|padding)(?:-|$)/.test(unprefixed)) return true;
|
||||
if (/^border(?:-|$)/.test(unprefixed) && !/^border-(?:color(?:-|$)|radius(?:-|$))/.test(unprefixed)) return true;
|
||||
if (/^(?:grid|flex|align-(?:content|items|self)|justify-(?:content|items|self)|place-(?:content|items|self)|offset|transform|overscroll|overflow|column)(?:-|$)/.test(unprefixed)) return true;
|
||||
return /^font-(?!family$|weight$|style$|synthesis$|palette$)/.test(unprefixed);
|
||||
}
|
||||
|
||||
function findOwningRule(node: Node): Rule | null {
|
||||
let parent = node.parent;
|
||||
while (parent && parent.type !== "root") {
|
||||
if (parent.type === "rule") return parent as Rule;
|
||||
parent = parent.parent;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function findKeyframesRule(rule: Rule): AtRule | null {
|
||||
let parent = rule.parent;
|
||||
while (parent && parent.type !== "root") {
|
||||
if (parent.type === "atrule" && /(?:^|-)?keyframes$/i.test(parent.name)) return parent as AtRule;
|
||||
parent = parent.parent;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function referencesCssIdentifier(value: string, identifier: string): boolean {
|
||||
const escaped = identifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
return new RegExp(`(^|[^-_a-z0-9])${escaped}(?=$|[^-_a-z0-9])`, "i").test(value);
|
||||
}
|
||||
|
||||
function rewriteAssetUrls(value: string, resolve: (path: string) => string): string {
|
||||
const parsed = valueParser(value);
|
||||
const resolvePackageAsset = (rawValue: string): string => {
|
||||
const raw = rawValue.trim();
|
||||
if (!raw || raw.startsWith("#")) throw new SkinPackError("CSS images and fonts must point to assets inside this skin package.", "SKIN_EXTERNAL_RESOURCE");
|
||||
const isInternalMarker = raw.startsWith("wskin-asset:");
|
||||
if (!isInternalMarker && /^(?:data:|blob:|https?:|\/\/|file:|javascript:)/i.test(raw)) throw new SkinPackError("Only relative paths to assets inside this skin package are allowed in url().", "SKIN_EXTERNAL_RESOURCE");
|
||||
let path: string;
|
||||
try { path = isInternalMarker ? decodeURIComponent(raw.slice("wskin-asset:".length)) : normalizeAssetPath(raw); }
|
||||
catch { throw new SkinPackError("A skin asset reference is invalid.", "SKIN_ASSET_PATH"); }
|
||||
return resolve(path);
|
||||
};
|
||||
const visit = (nodes: typeof parsed.nodes, inImageSet = false): void => {
|
||||
for (const node of nodes) {
|
||||
if (node.type === "function" && node.value.toLowerCase() === "url") {
|
||||
const raw = valueParser.stringify(node.nodes).trim().replace(/^(?:"([\s\S]*)"|'([\s\S]*)')$/, "$1$2").trim();
|
||||
node.nodes = [{ type: "string", quote: '"', value: resolvePackageAsset(raw), sourceIndex: 0, sourceEndIndex: 0, unclosed: undefined }];
|
||||
node.before = "";
|
||||
node.after = "";
|
||||
continue;
|
||||
}
|
||||
if (node.type === "function" && (node.value.toLowerCase() === "image-set" || node.value.toLowerCase() === "-webkit-image-set")) {
|
||||
for (const child of node.nodes) {
|
||||
if (child.type === "string") child.value = resolvePackageAsset(child.value);
|
||||
else if (child.type === "function") visit([child]);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (node.type === "function") visit(node.nodes, inImageSet);
|
||||
else if (inImageSet && node.type === "string") node.value = resolvePackageAsset(node.value);
|
||||
}
|
||||
};
|
||||
visit(parsed.nodes);
|
||||
return parsed.toString();
|
||||
}
|
||||
|
||||
function parseSingleFontFamily(value: string): string {
|
||||
const parsed = valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment");
|
||||
if (parsed.length !== 1 || (parsed[0].type !== "string" && parsed[0].type !== "word") || !parsed[0].value.trim()) {
|
||||
throw new SkinPackError("@font-face must declare exactly one font family.", "SKIN_FONT_FAMILY");
|
||||
}
|
||||
return parsed[0].value.trim();
|
||||
}
|
||||
|
||||
function rewriteScopedNames(value: string, property: string, keyframes: Map<string, string>, fontFamilies: Map<string, string>): string {
|
||||
const parsed = valueParser(value);
|
||||
if (["animation", "animation-name", "font", "font-family"].includes(property)) {
|
||||
parsed.walk((node) => {
|
||||
if (node.type !== "word" && node.type !== "string") return;
|
||||
const keyframe = keyframes.get(node.value);
|
||||
if (keyframe) node.value = keyframe;
|
||||
const family = fontFamilies.get(node.value.toLowerCase());
|
||||
if (family) node.value = family;
|
||||
});
|
||||
}
|
||||
return parsed.toString();
|
||||
}
|
||||
|
||||
function normalizeAssetPath(raw: string): string {
|
||||
let path = raw.split(/[?#]/, 1)[0];
|
||||
try { path = decodeURIComponent(path); } catch { throw new SkinPackError("An asset URL contains invalid encoding.", "SKIN_ASSET_PATH"); }
|
||||
if (path.startsWith("/") || path.includes("\\") || path.includes("\0") || /^[a-z]:/i.test(path)) throw new SkinPackError("An asset URL must be a relative package path.", "SKIN_ASSET_PATH");
|
||||
const segments: string[] = [];
|
||||
for (const segment of path.split("/")) {
|
||||
if (!segment || segment === ".") continue;
|
||||
if (segment === "..") {
|
||||
if (!segments.length) throw new SkinPackError("An asset URL cannot leave the skin package.", "SKIN_ASSET_PATH");
|
||||
segments.pop();
|
||||
} else {
|
||||
segments.push(segment);
|
||||
}
|
||||
}
|
||||
if (!segments.length) throw new SkinPackError("An asset URL must point to a package file.", "SKIN_ASSET_PATH");
|
||||
return segments.join("/");
|
||||
}
|
||||
|
||||
function hasKeyframesAncestor(rule: Rule): boolean {
|
||||
let parent = rule.parent;
|
||||
while (parent && parent.type !== "root") {
|
||||
if (parent.type === "atrule" && /keyframes$/i.test(parent.name)) return true;
|
||||
parent = parent.parent;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function assetMimeType(path: string): string | null {
|
||||
const extension = path.split(".").at(-1)?.toLowerCase();
|
||||
switch (extension) {
|
||||
case "png": return "image/png";
|
||||
case "jpg": case "jpeg": return "image/jpeg";
|
||||
case "webp": return "image/webp";
|
||||
case "avif": return "image/avif";
|
||||
case "gif": return "image/gif";
|
||||
case "woff2": return "font/woff2";
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import { getInstalledSkin, saveInstalledSkin } from "./local-persistence.js";
|
||||
import type { InstalledSkin } from "./skin-pack.js";
|
||||
import { applyTheme, getBuiltinSkinCss, getStoredTheme, isDarkTheme } from "./theme.js";
|
||||
import { scopeBuiltinThemeForCustomSkin } from "./skin-cascade.js";
|
||||
import { getBundledSkinPackageUrl, isPublicSkinEnabled } from "./skin-catalog.js";
|
||||
|
||||
export const ACTIVE_SKIN_KEY = "webspeak:active-skin";
|
||||
export const BUILTIN_LIGHT_SKIN = "builtin.light";
|
||||
export const BUILTIN_DARK_SKIN = "builtin.dark";
|
||||
const CUSTOM_STYLE_ID = "webspeak-active-custom-skin";
|
||||
const CUSTOM_BASE_STYLE_ID = "webspeak-active-custom-skin-base";
|
||||
|
||||
let activeAssetUrls: string[] = [];
|
||||
let criticalControlObserver: MutationObserver | null = null;
|
||||
|
||||
export function getStoredSkinId(): string | null {
|
||||
return typeof localStorage === "undefined" ? null : localStorage.getItem(ACTIVE_SKIN_KEY);
|
||||
}
|
||||
|
||||
export function storeSkinId(id: string): void {
|
||||
if (typeof localStorage !== "undefined") localStorage.setItem(ACTIVE_SKIN_KEY, id);
|
||||
}
|
||||
|
||||
export async function activateStoredSkin(): Promise<InstalledSkin | null> {
|
||||
const storedId = getStoredSkinId();
|
||||
const legacyTheme = getStoredTheme();
|
||||
const selectedId = storedId || (isDarkTheme(legacyTheme) ? BUILTIN_DARK_SKIN : BUILTIN_LIGHT_SKIN);
|
||||
storeSkinId(selectedId);
|
||||
return activateSkin(selectedId);
|
||||
}
|
||||
|
||||
export async function activateSkin(id: string, expectedVersion?: string, appVersion = "0.2.5"): Promise<InstalledSkin | null> {
|
||||
if (id === BUILTIN_LIGHT_SKIN || id === BUILTIN_DARK_SKIN) {
|
||||
clearCustomSkinStyle();
|
||||
applyTheme(id === BUILTIN_DARK_SKIN ? "dark" : "light");
|
||||
markCoreControls();
|
||||
storeSkinId(id);
|
||||
return null;
|
||||
}
|
||||
if (!isPublicSkinEnabled(id)) {
|
||||
if (typeof localStorage !== "undefined") localStorage.removeItem("webspeak:skin-choice");
|
||||
return fallBackToBuiltin();
|
||||
}
|
||||
|
||||
let skin = await getInstalledSkin(id);
|
||||
if (!skin || (expectedVersion && skin.version !== expectedVersion)) {
|
||||
try {
|
||||
const packageUrl = getBundledSkinPackageUrl(id) ?? `/api/skins/${encodeURIComponent(id)}/package`;
|
||||
const response = await fetch(packageUrl, { cache: "no-cache" });
|
||||
if (!response.ok) throw new Error("Skin package is no longer available.");
|
||||
const archive = await response.blob();
|
||||
const file = new File([archive], `${id}.wskin`, { type: "application/octet-stream" });
|
||||
const { importSkinPack } = await import("./skin-pack.js");
|
||||
const downloaded = await importSkinPack(file);
|
||||
if (downloaded.id !== id) throw new Error("Skin package ID does not match its catalog entry.");
|
||||
if (expectedVersion && downloaded.version !== expectedVersion) throw new Error("Skin package version does not match its catalog entry.");
|
||||
skin = downloaded;
|
||||
await saveInstalledSkin(downloaded).catch(() => undefined);
|
||||
} catch {
|
||||
if (!skin) return fallBackToBuiltin();
|
||||
}
|
||||
}
|
||||
|
||||
if (!isVersionCompatible(appVersion, skin.minAppVersion)) return fallBackToBuiltin();
|
||||
|
||||
try {
|
||||
const { resolveSkinCssAssets } = await import("./skin-pack.js");
|
||||
const compiled = resolveSkinCssAssets(skin.css, skin.assets);
|
||||
// A community skin is a complete appearance choice, not an overlay on the
|
||||
// previously selected day/night skin. Keep the document theme (used by the
|
||||
// independent admin appearance) but give unstyled public parts a light,
|
||||
// neutral fallback. A custom skin can opt into dark colors itself.
|
||||
applyTheme(getStoredTheme());
|
||||
let baseStyle = document.getElementById(CUSTOM_BASE_STYLE_ID) as HTMLStyleElement | null;
|
||||
if (!baseStyle) {
|
||||
baseStyle = document.createElement("style");
|
||||
baseStyle.id = CUSTOM_BASE_STYLE_ID;
|
||||
document.head.append(baseStyle);
|
||||
}
|
||||
baseStyle.dataset.skinPackage = skin.id;
|
||||
baseStyle.textContent = scopeBuiltinThemeForCustomSkin(getBuiltinSkinCss("light"), "light", skin.id);
|
||||
document.querySelectorAll<HTMLElement>(".ws-skin-root").forEach((clientRoot) => {
|
||||
clientRoot.dataset.wsSkin = skin!.id;
|
||||
});
|
||||
markCoreControls();
|
||||
|
||||
let style = document.getElementById(CUSTOM_STYLE_ID) as HTMLStyleElement | null;
|
||||
if (!style) {
|
||||
style = document.createElement("style");
|
||||
style.id = CUSTOM_STYLE_ID;
|
||||
document.head.append(style);
|
||||
}
|
||||
style.dataset.skinPackage = skin.id;
|
||||
style.textContent = compiled.css;
|
||||
const previousAssetUrls = activeAssetUrls;
|
||||
activeAssetUrls = compiled.objectUrls;
|
||||
previousAssetUrls.forEach((url) => URL.revokeObjectURL(url));
|
||||
storeSkinId(id);
|
||||
return skin;
|
||||
} catch {
|
||||
return fallBackToBuiltin();
|
||||
}
|
||||
}
|
||||
|
||||
function fallBackToBuiltin(): null {
|
||||
const fallback = isDarkTheme(getStoredTheme()) ? BUILTIN_DARK_SKIN : BUILTIN_LIGHT_SKIN;
|
||||
clearCustomSkinStyle();
|
||||
applyTheme(fallback === BUILTIN_DARK_SKIN ? "dark" : "light");
|
||||
storeSkinId(fallback);
|
||||
return null;
|
||||
}
|
||||
|
||||
export function clearCustomSkinStyle(): void {
|
||||
document.getElementById(CUSTOM_STYLE_ID)?.remove();
|
||||
document.getElementById(CUSTOM_BASE_STYLE_ID)?.remove();
|
||||
activeAssetUrls.forEach((url) => URL.revokeObjectURL(url));
|
||||
activeAssetUrls = [];
|
||||
}
|
||||
|
||||
function isVersionCompatible(current: string, minimum: string): boolean {
|
||||
const parse = (value: string) => /^(\d+)\.(\d+)\.(\d+)/.exec(value)?.slice(1).map(Number);
|
||||
const currentParts = parse(current);
|
||||
const minimumParts = parse(minimum);
|
||||
if (!currentParts || !minimumParts) return false;
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
if (currentParts[index] > minimumParts[index]) return true;
|
||||
if (currentParts[index] < minimumParts[index]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function markCoreControls(): void {
|
||||
const roots = [...document.querySelectorAll<HTMLElement>(".ws-skin-root")];
|
||||
const selector = "button, a[href], input, select, textarea, [role='button'], [role='menuitem'], [draggable='true']";
|
||||
const markElement = (element: HTMLElement) => {
|
||||
element.dataset.wsCritical = "true";
|
||||
element.dataset.wsPart ||= "control";
|
||||
const role = element.getAttribute("role");
|
||||
const type = element instanceof HTMLInputElement ? element.type : "";
|
||||
element.dataset.wsControlKind = role === "menuitem" ? "menuitem" : role === "button" ? "button" : element instanceof HTMLInputElement && type === "range" ? "range" : element instanceof HTMLInputElement && type === "checkbox" ? "checkbox" : element instanceof HTMLInputElement ? "input" : element instanceof HTMLTextAreaElement ? "textarea" : element instanceof HTMLSelectElement ? "select" : element instanceof HTMLAnchorElement ? "link" : element instanceof HTMLButtonElement ? "button" : "draggable";
|
||||
};
|
||||
const mark = (root: ParentNode) => {
|
||||
if (root instanceof HTMLElement && root.matches(selector)) markElement(root);
|
||||
root.querySelectorAll<HTMLElement>(selector).forEach(markElement);
|
||||
};
|
||||
roots.forEach(mark);
|
||||
if (!criticalControlObserver) {
|
||||
criticalControlObserver = new MutationObserver((records) => {
|
||||
for (const record of records) for (const node of record.addedNodes) {
|
||||
if (!(node instanceof HTMLElement)) continue;
|
||||
const clientRoot = node.matches(".ws-skin-root") ? node : node.closest<HTMLElement>(".ws-skin-root");
|
||||
if (!clientRoot) continue;
|
||||
mark(node);
|
||||
}
|
||||
});
|
||||
criticalControlObserver.observe(document.getElementById("app") ?? document.body, { childList: true, subtree: true });
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,53 @@
|
||||
export type ThemeMode = "system" | "light" | "dark";
|
||||
|
||||
import lightManifest from "../skins/builtin/light/manifest.json";
|
||||
import lightCss from "../skins/builtin/light/skin.css?inline";
|
||||
import darkManifest from "../skins/builtin/dark/manifest.json";
|
||||
import darkCss from "../skins/builtin/dark/skin.css?inline";
|
||||
|
||||
const THEME_KEY = "webspeak:theme";
|
||||
const SKIN_STYLE_ELEMENT_ID = "webspeak-active-built-in-skin";
|
||||
let activeThemeMode: ThemeMode = "system";
|
||||
|
||||
const builtinSkins = {
|
||||
light: { manifest: lightManifest, css: lightCss },
|
||||
dark: { manifest: darkManifest, css: darkCss },
|
||||
} as const;
|
||||
|
||||
export function getBuiltinSkinCss(theme: Exclude<ThemeMode, "system">): string {
|
||||
return theme === "dark" ? builtinSkins.dark.css : builtinSkins.light.css;
|
||||
}
|
||||
|
||||
export function getStoredTheme(): ThemeMode {
|
||||
const value = typeof localStorage === "undefined" ? "" : localStorage.getItem(THEME_KEY);
|
||||
return value === "light" || value === "dark" || value === "system" ? value : "system";
|
||||
}
|
||||
|
||||
export function applyTheme(theme: ThemeMode): void {
|
||||
export function applyTheme(theme: ThemeMode, options: { preserveCustomSkins?: boolean } = {}): void {
|
||||
if (typeof document === "undefined") return;
|
||||
document.documentElement.dataset.theme = theme;
|
||||
activeThemeMode = theme;
|
||||
const root = document.documentElement;
|
||||
const activeSkin = isDarkTheme(theme) ? builtinSkins.dark : builtinSkins.light;
|
||||
|
||||
// Keep data-theme for the admin console's independent appearance rules.
|
||||
// Built-in skin CSS is scoped to public roots and can never restyle /admin.
|
||||
root.dataset.theme = theme;
|
||||
document.querySelectorAll<HTMLElement>(".ws-skin-root").forEach((clientRoot) => {
|
||||
const currentSkin = clientRoot.dataset.wsSkin;
|
||||
const isCustomSkin = currentSkin !== builtinSkins.light.manifest.id && currentSkin !== builtinSkins.dark.manifest.id;
|
||||
if (options.preserveCustomSkins && currentSkin && isCustomSkin) return;
|
||||
clientRoot.dataset.wsSkin = activeSkin.manifest.id;
|
||||
});
|
||||
|
||||
let style = document.getElementById(SKIN_STYLE_ELEMENT_ID) as HTMLStyleElement | null;
|
||||
if (!style) {
|
||||
style = document.createElement("style");
|
||||
style.id = SKIN_STYLE_ELEMENT_ID;
|
||||
style.dataset.skinPackage = activeSkin.manifest.id;
|
||||
document.head.append(style);
|
||||
}
|
||||
style.dataset.skinPackage = activeSkin.manifest.id;
|
||||
style.textContent = activeSkin.css;
|
||||
}
|
||||
|
||||
export function saveTheme(theme: ThemeMode): void {
|
||||
@@ -30,3 +68,12 @@ export function nextTheme(theme: ThemeMode): ThemeMode {
|
||||
}
|
||||
|
||||
applyTheme(getStoredTheme());
|
||||
|
||||
if (typeof window !== "undefined" && typeof window.matchMedia === "function") {
|
||||
const systemColorScheme = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
const updateSystemSkin = () => {
|
||||
if (activeThemeMode === "system") applyTheme("system", { preserveCustomSkins: true });
|
||||
};
|
||||
if (systemColorScheme.addEventListener) systemColorScheme.addEventListener("change", updateSystemSkin);
|
||||
else systemColorScheme.addListener?.(updateSystemSkin);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "builtin.dark",
|
||||
"name": "WebSpeak Dark",
|
||||
"version": "1.0.0",
|
||||
"author": "WebSpeak",
|
||||
"license": "AGPL-3.0-only",
|
||||
"description": "The built-in dark appearance for public WebSpeak pages.",
|
||||
"entry": "skin.css",
|
||||
"minAppVersion": "0.2.5"
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
/* Built-in package: builtin.dark. Scoped to public WebSpeak pages only. */
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] {
|
||||
color-scheme: dark;
|
||||
--ws-page-bg: #101918;
|
||||
--ws-surface-1: #172321;
|
||||
--ws-surface-2: #202f2c;
|
||||
--ws-text: #e8f3f0;
|
||||
--ws-text-muted: #9bb0aa;
|
||||
--ws-accent: #69d2c7;
|
||||
--ws-success: #78e489;
|
||||
--ws-warning: #e2b36c;
|
||||
--ws-danger: #ee8a82;
|
||||
--ws-border: #30413d;
|
||||
--surface-0: var(--ws-page-bg);
|
||||
--surface-1: var(--ws-surface-1);
|
||||
--surface-2: var(--ws-surface-2);
|
||||
--text-primary: var(--ws-text);
|
||||
--text-muted: var(--ws-text-muted);
|
||||
--accent: var(--ws-accent);
|
||||
--success: var(--ws-success);
|
||||
--warning: var(--ws-warning);
|
||||
--danger: var(--ws-danger);
|
||||
--border: var(--ws-border);
|
||||
}
|
||||
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] {
|
||||
background: var(--surface-0);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page {
|
||||
color: var(--text-primary);
|
||||
background-color: var(--surface-0);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .app-shell,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .workspace {
|
||||
background: var(--surface-1);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .workspace-header,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .member-panel,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .voice-card,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-modal {
|
||||
background: var(--surface-1);
|
||||
border-color: var(--border);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .workspace-header {
|
||||
border-bottom-color: var(--border);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .workspace-content {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-card {
|
||||
background: color-mix(in srgb, var(--surface-1) 94%, transparent);
|
||||
border-color: var(--border);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .field-wrap,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .message-composer,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .member-search,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .mic-mode-switch,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .mode-note {
|
||||
background: var(--surface-2);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .field-wrap input,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .message-composer input,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .member-search input,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-select {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .room-hero {
|
||||
background: linear-gradient(110deg, color-mix(in srgb, var(--accent) 18%, var(--surface-1)), var(--surface-1) 75%);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .voice-card,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .member-panel,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-modal {
|
||||
box-shadow: 0 7px 18px color-mix(in srgb, var(--text-primary) 8%, transparent);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .section-heading h2,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .room-hero h1,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-card h2,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .member-panel-heading h2,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .message-meta strong,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .member-copy strong {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .section-kicker,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .card-kicker,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-label,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .header-note,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .section-counter,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .message-meta time,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .member-copy span,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .chat-empty,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-description,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .card-lead {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .chat-panel,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .chat-heading,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-header,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-footer,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-separator {
|
||||
border-color: var(--border);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .message-bubble {
|
||||
color: var(--text-primary);
|
||||
background: var(--surface-2);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-content,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-nav {
|
||||
background: var(--surface-1);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-nav {
|
||||
border-right-color: var(--border);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-section h3,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-header h2 {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .settings-select {
|
||||
color: var(--text-primary);
|
||||
background: var(--surface-2);
|
||||
border-color: var(--border);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .audio-level-track,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .meter i {
|
||||
background: var(--border);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .member-presence {
|
||||
border-color: var(--surface-1);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .member-row:hover,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .member-row:focus-within {
|
||||
background: color-mix(in srgb, var(--accent) 10%, var(--surface-1));
|
||||
box-shadow: 0 4px 12px color-mix(in srgb, var(--text-primary) 8%, transparent);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] :focus-visible {
|
||||
outline-color: color-mix(in srgb, var(--accent) 55%, transparent);
|
||||
}
|
||||
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .channel-password-modal {
|
||||
color: var(--text-primary);
|
||||
border-color: var(--border);
|
||||
background: var(--surface-1);
|
||||
box-shadow: 0 20px 60px color-mix(in srgb, var(--text-primary) 18%, transparent);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .channel-password-modal h2 { color: var(--text-primary); }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .channel-password-modal > p { color: var(--text-muted); }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .channel-password-icon {
|
||||
color: var(--accent);
|
||||
background: color-mix(in srgb, var(--accent) 13%, var(--surface-2));
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .acceleration-choice {
|
||||
color: #b8eee3;
|
||||
background: #183530;
|
||||
border-color: #2b645b;
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .acceleration-choice small { color: #91b9b0; }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .acceleration-choice select {
|
||||
color: #d9f8f1;
|
||||
background: #203f39;
|
||||
border-color: #3b766d;
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .member-context-menu,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .member-submenu-panel {
|
||||
color: var(--text-primary);
|
||||
background: var(--surface-1);
|
||||
border-color: var(--border);
|
||||
box-shadow: 0 18px 42px color-mix(in srgb, #000 38%, transparent);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .member-context-menu strong { color: var(--text-primary); }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .member-context-menu button { color: var(--text-muted); }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .member-context-menu button:hover {
|
||||
color: var(--accent);
|
||||
background: color-mix(in srgb, var(--accent) 14%, var(--surface-2));
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .member-submenu-panel button small,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .member-submenu-empty { color: var(--text-muted); }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .breadcrumbs { color: var(--text-muted); }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .breadcrumbs strong,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .voice-card > strong { color: var(--text-primary); }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .member-channel-heading { color: var(--text-muted); }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .member-channel-group.current .member-channel-heading {
|
||||
color: var(--accent);
|
||||
background: color-mix(in srgb, var(--accent) 14%, var(--surface-1));
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .member-channel-group.current .member-channel-heading small { color: var(--accent); }
|
||||
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .brand-lockup strong { color: var(--accent); }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .brand-lockup strong span { color: var(--text-primary); }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .brand-lockup small,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .header-note,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-description,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .promise-item small,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .card-lead,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .field-hint,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-meta,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-footer { color: var(--text-muted); }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .visitor-count {
|
||||
color: #b7fff0;
|
||||
border-color: rgba(105, 210, 199, .42);
|
||||
background: linear-gradient(110deg, #173b36, #1c2d2a);
|
||||
box-shadow: 0 10px 28px rgba(0, 0, 0, .24), inset 0 0 0 1px rgba(105, 210, 199, .08);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .visitor-count::before {
|
||||
background: linear-gradient(105deg, transparent, rgba(125, 255, 174, .18), transparent);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .visitor-count-orbit { border-color: rgba(105, 210, 199, .34); }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-copy h1,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-card h2,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .promise-item b,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .field-label { color: var(--text-primary); }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-copy h1 em,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .eyebrow,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .card-kicker,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .field-label span,
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-footer a { color: var(--accent); }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-card {
|
||||
background: color-mix(in srgb, var(--surface-1) 94%, transparent);
|
||||
border-color: var(--border);
|
||||
box-shadow: 0 20px 52px color-mix(in srgb, var(--text-primary) 14%, transparent);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .field-wrap { color: var(--text-muted); background: var(--surface-2); }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .field-wrap input { color: var(--text-primary); }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .qq-modal-card {
|
||||
color: var(--text-primary);
|
||||
border-color: var(--border);
|
||||
background: var(--surface-1);
|
||||
box-shadow: 0 20px 60px color-mix(in srgb, var(--text-primary) 18%, transparent);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .qq-modal-heading h2 { color: var(--text-primary); }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .qq-direct-join { color: var(--text-muted); }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .qq-modal-close {
|
||||
color: var(--text-muted);
|
||||
background: var(--surface-2);
|
||||
border-color: var(--border);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .qq-join-link {
|
||||
color: var(--accent);
|
||||
background: color-mix(in srgb, var(--accent) 12%, var(--surface-2));
|
||||
border-color: color-mix(in srgb, var(--accent) 30%, var(--border));
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .qq-join-link:hover {
|
||||
color: var(--surface-1);
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .field-wrap input::placeholder { color: var(--text-muted); }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-footer { border-top-color: var(--border); }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-copy h1 {
|
||||
color: #f3fffb;
|
||||
text-shadow: 0 1px 0 #07100f, 0 0 9px rgba(243, 255, 251, .16);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-copy h1 em {
|
||||
color: #7dffae;
|
||||
text-shadow: 0 0 10px rgba(125, 255, 174, .38), 0 0 22px rgba(105, 210, 199, .18);
|
||||
animation-name: join-accent-breathe-dark;
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-description {
|
||||
color: #c4d9d3;
|
||||
text-shadow: 0 0 8px rgba(196, 217, 211, .12);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .promise-item b {
|
||||
color: #f0fff9;
|
||||
text-shadow: 0 0 7px rgba(240, 255, 249, .14);
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .promise-item small { color: #a9c6be; }
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .promise-icon { box-shadow: 0 0 12px rgba(105, 210, 199, .14); }
|
||||
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"],
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] * {
|
||||
scrollbar-color: #438f88 transparent;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] *::-webkit-scrollbar-thumb {
|
||||
background: #438f88;
|
||||
border-color: transparent;
|
||||
}
|
||||
.ws-skin-root[data-ws-skin="builtin.dark"] *::-webkit-scrollbar-thumb:hover { background: #69c7bc; }
|
||||
|
||||
@keyframes join-accent-breathe-dark {
|
||||
0%, 100% { transform: translateY(0); text-shadow: 0 0 8px rgba(125, 255, 174, .28), 0 0 18px rgba(105, 210, 199, .14); }
|
||||
50% { transform: translateY(-2px); text-shadow: 0 0 13px rgba(125, 255, 174, .5), 0 0 26px rgba(105, 210, 199, .22); }
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "builtin.light",
|
||||
"name": "WebSpeak Light",
|
||||
"version": "1.0.0",
|
||||
"author": "WebSpeak",
|
||||
"license": "AGPL-3.0-only",
|
||||
"description": "The built-in light appearance for public WebSpeak pages.",
|
||||
"entry": "skin.css",
|
||||
"minAppVersion": "0.2.5"
|
||||
}
|
||||