Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea4d5b2a70 | ||
|
|
a439100ad6 | ||
|
|
620d24f796 | ||
|
|
fc3bbd0c59 | ||
|
|
3b5ce9b446 | ||
|
|
37de6067d0 | ||
|
|
45410fcc7d | ||
|
|
166cb543a1 | ||
|
|
a295ff4b27 | ||
|
|
dcc52c4530 | ||
|
|
dc3ad6a598 | ||
|
|
ef59e51e32 | ||
|
|
9bbc22de25 | ||
|
|
335d93a8b8 | ||
|
|
52ff0560d1 | ||
|
|
a5e5dd6592 | ||
|
|
62e41dbc51 | ||
|
|
d8b2fd9e1b | ||
|
|
8ca3249832 | ||
|
|
92574fddb1 | ||
|
|
596114e6a3 | ||
|
|
2868f7a478 | ||
|
|
63ef6b673d | ||
|
|
5a56e1706f | ||
|
|
986814441d | ||
|
|
0ab6fb6f3f | ||
|
|
a966be4db6 |
No files matched your search
@@ -1,5 +1,43 @@
|
||||
# Changelog
|
||||
|
||||
## [0.1.7] — 2026-09-06
|
||||
|
||||
### 中文
|
||||
|
||||
- 增加 Deutsch 界面支持和 Telegram 群组入口。
|
||||
- 增加桌面端整体音量滑块,默认收起并在悬停时展开。
|
||||
- 修复伴奏音量忽大忽小的问题。
|
||||
- 增加可展开的网络性能面板,显示浏览器、WebSpeak 与 TeamSpeak 之间的延迟和丢包率。
|
||||
- 管理员连接测试改用服务端多次主机 Ping 并显示丢包率,不再创建临时 TeamSpeak 客户端。
|
||||
- 统一中文、English、Deutsch 的旗帜代码语言菜单。
|
||||
- 修复 TeamSpeak 使用 TCP 探测导致的误报丢包,并修正语言菜单异常留白。
|
||||
- 移除 WebRTC 桥接中的 RMS 静音帧过滤,安静帧仅用于发言状态指示,不再丢弃。
|
||||
- 修复 Docker 运行环境缺少 ICMP Ping 工具导致管理员测试误报 100% 丢包。
|
||||
|
||||
### English
|
||||
|
||||
- Added German UI support and a Telegram community link.
|
||||
- Added a compact desktop master-volume slider that expands on hover.
|
||||
- Fixed accompaniment volume fluctuations.
|
||||
- Added an expandable network performance panel with latency and packet loss across the browser, WebSpeak, and TeamSpeak path.
|
||||
- Updated the administrator connection test to use repeated host pings, report packet loss, and avoid creating temporary TeamSpeak clients.
|
||||
- Unified the Chinese, English, and German flag/code language menu.
|
||||
- Fixed false packet-loss reports caused by probing the TeamSpeak UDP service with TCP, and corrected excess space in the language menu.
|
||||
- Removed RMS-based silence filtering from the WebRTC bridge; quiet frames are now retained for the codec timeline.
|
||||
- Fixed Docker admin diagnostics falsely reporting 100% packet loss when the runtime lacked the ICMP ping tool.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Deutsche Benutzeroberfläche und Telegram-Community-Link hinzugefügt.
|
||||
- Kompakten Gesamtlautstärkeregler für den Desktop ergänzt, der sich beim Überfahren öffnet.
|
||||
- Schwankende Lautstärke bei der Begleittonfreigabe behoben.
|
||||
- Aufklappbares Netzwerkleistungsfeld mit Latenz und Paketverlust zwischen Browser, WebSpeak und TeamSpeak ergänzt.
|
||||
- Verbindungstest in der Administration auf wiederholte Host-Pings mit Paketverlustanzeige umgestellt, ohne temporäre TeamSpeak-Clients zu erzeugen.
|
||||
- Einheitliches Sprachmenü mit Flaggen und Sprachcodes für Chinesisch, Englisch und Deutsch ergänzt.
|
||||
- Falsche Paketverlustmeldungen durch TCP-Prüfung des UDP-Dienstes behoben und übermäßigen Leerraum im Sprachmenü korrigiert.
|
||||
- RMS-basierte Stillefilterung aus der WebRTC-Brücke entfernt; leise Frames bleiben nun im Codec-Zeitverlauf erhalten.
|
||||
- Falsche 100-%-Paketverlustmeldungen behoben, wenn dem Docker-Laufzeitimage das ICMP-Ping-Tool fehlte.
|
||||
|
||||
## [0.1.6] — 2026-09-04
|
||||
|
||||
### 中文
|
||||
|
||||
@@ -23,7 +23,7 @@ FROM node:22-bookworm-slim AS runtime
|
||||
|
||||
WORKDIR /app
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates libstdc++6 \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates libstdc++6 iputils-ping \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& mkdir -p /data \
|
||||
&& chown node:node /data
|
||||
|
||||
@@ -1,358 +1,558 @@
|
||||
<div align="center">
|
||||
<a id="readme-top"></a>
|
||||
|
||||
<img src="./仓库图标.png" alt="WebSpeak 项目图标" width="190" />
|
||||
|
||||
<h1>WebSpeak</h1>
|
||||
|
||||
<p><strong>让 TeamSpeak 自然地进入浏览器。</strong></p>
|
||||
<p>A self-hosted browser voice client for TeamSpeak 3 and TeamSpeak 6.</p>
|
||||
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/workflows/docker-publish.yml)
|
||||
[](./LICENSE)
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/stargazers)
|
||||
<br />
|
||||
[](https://www.teamspeak.com/)
|
||||
[](https://nodejs.org/)
|
||||
[](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>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<details>
|
||||
<summary><kbd>目录 / Table of contents</kbd></summary>
|
||||
|
||||
- [项目简介 · Overview](#overview)
|
||||
- [在线 Demo · Live Demo](#demo)
|
||||
- [社区 · Community](#community)
|
||||
- [简体中文](#简体中文)
|
||||
- [界面截图](#zh-screenshots)
|
||||
- [特性](#zh-features)
|
||||
- [更新日志](#zh-changelog)
|
||||
- [部署方案](#zh-deployment)
|
||||
- [要求和注意事项](#zh-requirements)
|
||||
- [许可证](#zh-license)
|
||||
- [English](#english)
|
||||
- [Screenshots](#en-screenshots)
|
||||
- [Features](#en-features)
|
||||
- [Changelog](#en-changelog)
|
||||
- [Deployment](#en-deployment)
|
||||
- [Requirements and notes](#en-requirements)
|
||||
- [License](#en-license)
|
||||
- [Deutsch](#deutsch)
|
||||
- [Screenshots](#de-screenshots)
|
||||
- [Funktionen](#de-features)
|
||||
- [Ä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. |
|
||||
|
||||
<a id="demo"></a>
|
||||
|
||||
## 在线 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>
|
||||
|
||||
## 社区 · Community
|
||||
|
||||
<div align="center">
|
||||
|
||||
# WebSpeak
|
||||
<a href="http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475">
|
||||
<img src="./web/public/qq-group-qr.jpg" alt="WebSpeak QQ 群二维码" width="290" />
|
||||
</a>
|
||||
|
||||
<p>
|
||||
<img src="./仓库图标.png" alt="WebSpeak" width="220">
|
||||
</p>
|
||||
**群号 / Group ID:`869500475`**
|
||||
|
||||
**让 TeamSpeak 真正进入浏览器。**
|
||||
[通过群聊链接直接加入 / 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)
|
||||
|
||||
自托管的 TeamSpeak 3 / TeamSpeak 6 网页客户端。打开网页即可加入语音、查看频道、发送消息,无需安装桌面客户端。
|
||||
|
||||
**在线体验:[webspeak.example.invalid](https://webspeak.example.invalid)**
|
||||
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak)
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6)
|
||||
[](LICENSE)
|
||||
[](https://www.teamspeak.com/)
|
||||
|
||||
[中文](#中文) · [English](#english) · [更新日志](#更新日志--changelog) · [快速开始](#快速开始--quick-start) · [社区](#社区--community)
|
||||
中文:在群内获取部署帮助、版本通知和使用交流。<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)
|
||||
|
||||
</div>
|
||||
|
||||
## 中文
|
||||
---
|
||||
|
||||
WebSpeak 是一个面向 TeamSpeak 服务器的浏览器客户端。部署一次,用户通过网页即可加入语音空间,不需要安装 TeamSpeak 桌面客户端。
|
||||
<a id="简体中文"></a>
|
||||
|
||||
### 功能
|
||||
## 简体中文
|
||||
|
||||
- 支持 TeamSpeak 3 和 TeamSpeak 6,自动识别协议。
|
||||
- 浏览频道、在线成员和实时成员状态。
|
||||
- 加入、切换频道,并显示成员所在频道。
|
||||
- 频道文字聊天、服务器消息、私聊和戳一戳。
|
||||
- 浏览器麦克风和扬声器选择、音量调节、输入电平和本地麦克风测试。
|
||||
- 一键闭麦/开麦、VOX 语音激活、发言状态提示。
|
||||
- 可选 WebRTC 低延迟语音,网络不支持时自动回退。
|
||||
- 固定服务器、开放服务器和一次性邀请链接三种访问方式。
|
||||
- 管理控制台:默认目标、邀请链接、在线会话、日志、诊断和数据库备份。
|
||||
- 中英文界面、主题切换、桌面端和移动端适配。
|
||||
- 移动端提供成员操作菜单,桌面端支持右键菜单。
|
||||
WebSpeak 面向希望通过网页提供 TeamSpeak 语音服务的个人、社区和服务器管理员。它提供完整的访客页面、语音工作区和管理控制台,并可使用 Docker、预编译包或源码部署。
|
||||
|
||||
### 快速开始 · Quick Start
|
||||
<a id="zh-screenshots"></a>
|
||||
|
||||
### 🖼️ 界面截图
|
||||
|
||||
以下截图来自上海测试节点,展示中文界面下的欢迎页、语音工作区、音量控制和成员操作菜单。
|
||||
|
||||
#### 欢迎页
|
||||
|
||||
<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-changelog"></a>
|
||||
|
||||
### 🧾 更新日志
|
||||
|
||||
| 版本 | 日期 | 摘要 |
|
||||
| --- | --- | --- |
|
||||
| [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(推荐)
|
||||
|
||||
要求:安装 Docker Engine 和 Docker Compose。
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
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` 使用:
|
||||
|
||||
```text
|
||||
账号:admin
|
||||
密码:admin
|
||||
```
|
||||
|
||||
首次登录必须修改管理员密码。然后在管理控制台的“服务器”页面设置“默认 TeamSpeak 目标”,例如:
|
||||
|
||||
```text
|
||||
203.0.113.10#9987
|
||||
```
|
||||
|
||||
用户欢迎页没有邀请链接参数时,会自动使用管理员设置的默认目标。开放模式下,用户可以自行输入要连接的服务器地址和端口。
|
||||
|
||||
数据会保存在 Docker volume `webspeak-data` 中。升级时执行:
|
||||
默认网页端口为 `3040/TCP`,数据保存在 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`,否则会删除数据库和管理员配置。
|
||||
不要执行 `docker compose down -v`,否则会删除数据库、管理员设置和其他持久化数据。
|
||||
|
||||
如需更换网页端口:
|
||||
如需修改宿主机网页端口,在仓库目录创建 `.env`:
|
||||
|
||||
```bash
|
||||
WEBSPEAK_PORT=3041 docker compose up -d
|
||||
```dotenv
|
||||
WEBSPEAK_PORT=3041
|
||||
```
|
||||
|
||||
#### 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`。
|
||||
|
||||
#### 源码运行
|
||||
|
||||
需要 Node.js `22.5.0` 或更高版本,以及 `@discordjs/opus` 所需的本地编译工具。
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
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
|
||||
node dist/index.js
|
||||
npm start
|
||||
```
|
||||
|
||||
服务默认监听 `3040` 端口。
|
||||
源码构建 `@discordjs/opus` 时需要 Python、Make 和 C/C++ 编译工具。开发模式可分别使用 `npm run dev` 与 `npm run web:dev`。
|
||||
|
||||
### WebRTC 低延迟语音
|
||||
#### 首次配置(所有方案)
|
||||
|
||||
WebRTC 是可选功能,由 WebSpeak 自带,不需要额外部署媒体服务器。
|
||||
1. 打开 `http://<你的主机>:3040/admin`。
|
||||
2. 使用默认账号 `admin`、默认密码 `admin` 登录,并按提示立即设置至少 12 位的新密码。
|
||||
3. 在“服务器”页填写默认 TeamSpeak 目标和访问方式;目标可写为 `voice.example.com#9987`。
|
||||
4. 公网使用时为站点配置 HTTPS。若启用 WebRTC,还需放行管理后台显示的 UDP 端口范围。
|
||||
|
||||
1. 在管理后台打开“WebRTC 语音”。
|
||||
2. 在部署主机所在云平台安全组或上游防火墙放行入站 UDP `40000–40099`。
|
||||
3. 重新进入语音空间即可生效。
|
||||
<a id="zh-requirements"></a>
|
||||
|
||||
Docker Compose 已自动发布 `40000–40099/UDP`,但无法替你修改云安全组。Ubuntu 使用 UFW 时可执行:
|
||||
### ⚠️ 要求和注意事项
|
||||
|
||||
```bash
|
||||
sudo ufw allow 40000:40099/udp
|
||||
```
|
||||
| 项目 | 要求或注意事项 |
|
||||
| --- | --- |
|
||||
| 浏览器 | 建议使用最新版 Chrome、Edge 或其他支持 WebRTC 的现代浏览器。麦克风和屏幕音频通常要求 HTTPS 安全上下文。 |
|
||||
| TeamSpeak 网络 | WebSpeak 主机必须能够访问目标 TeamSpeak 服务器。目标默认语音端口为 `9987`,也可在网页中填写其他端口。 |
|
||||
| Web 服务网络 | 服务默认监听 `3040/TCP`。公网部署建议通过 HTTPS 反向代理提供网页和 WebSocket。 |
|
||||
| WebRTC | 默认使用 `40000–40099/UDP`。Docker Compose 已发布该范围,但云安全组和主机防火墙仍需放行;自定义范围时也要同步修改 Docker 端口映射。启用 WebRTC 后需先关闭它才能修改端口范围。 |
|
||||
| 身份保持 | 同一浏览器身份同时只能保持一条活动连接。需要并行连接时,请取消第二条连接的“保持身份”,或使用另一个浏览器/浏览器配置文件。 |
|
||||
| 伴奏 | 仅桌面端提供,并要求启用 WebRTC。选择窗口或标签页时必须同时勾选共享音频;浏览器无法直接任意读取本地应用音频。 |
|
||||
| 数据 | Docker 数据位于 `webspeak-data` volume;发布包和源码运行的数据位于程序目录的 `data/`。升级或迁移前建议从管理后台导出数据库备份。 |
|
||||
| 会话上限 | 单实例最多允许 100 个活动网页会话。 |
|
||||
| 项目关系 | WebSpeak 是社区项目,不是 TeamSpeak 官方产品;TeamSpeak 名称及商标归其权利人所有。 |
|
||||
|
||||
网页和 WSS 使用 TCP `80/443`。TeamSpeak 的 `9987` 只需要让 WebSpeak 主机能够访问目标 TeamSpeak,不需要在 WebSpeak 主机对公网开放。WebRTC 不支持或端口未放行时,客户端会自动使用兼容模式。
|
||||
<a id="zh-license"></a>
|
||||
|
||||
### 管理员设置
|
||||
### 📜 许可证
|
||||
|
||||
管理员可以在控制台中:
|
||||
WebSpeak 使用 [GNU Affero General Public License v3.0 only](./LICENSE) 发布。你可以使用、研究、修改和再分发本项目;如果修改后的版本通过网络向用户提供服务,需要按照 AGPL-3.0 向这些用户提供对应源代码。
|
||||
|
||||
- 修改默认 TeamSpeak 目标和服务器密码。
|
||||
- 选择固定目标或允许用户自定义目标。
|
||||
- 创建、撤销和设置有效期的邀请链接。
|
||||
- 查看在线会话、运行日志、诊断信息和审计记录。
|
||||
- 下载诊断报告和 SQLite 数据库备份。
|
||||
- 开启或关闭 WebRTC 低延迟语音。
|
||||
<div align="right"><a href="#readme-top">返回顶部 ↑</a></div>
|
||||
|
||||
### 浏览器要求
|
||||
---
|
||||
|
||||
- 使用较新的 Chrome、Edge 或其他支持 WebRTC 的现代浏览器。
|
||||
- 使用麦克风需要浏览器权限;公网部署建议使用 HTTPS。
|
||||
- 目标 TeamSpeak 服务器必须能被 WebSpeak 主机访问。
|
||||
|
||||
### 更新日志 · Changelog
|
||||
|
||||
完整记录见 [`CHANGELOG.md`](CHANGELOG.md)。
|
||||
|
||||
#### 2026-09-04 · v0.1.6
|
||||
|
||||
- 新增保持身份并发连接提醒。
|
||||
- 新增桌面端伴奏共享功能。
|
||||
- 新增网站 favicon,并更新仓库 README 主视觉。
|
||||
|
||||
#### 2026-09-04 · v0.1.5
|
||||
|
||||
- 修复并优化主题切换按钮,首次点击即可切换,并使用太阳/月亮图标。
|
||||
- 修复浏览器身份保存与退出后的保持逻辑。
|
||||
|
||||
#### 2026-09-03 · v0.1.4
|
||||
|
||||
- 修复 WebRTC 语音收发与发言状态同步。
|
||||
- 修复频道文字消息在 WebSpeak 客户端之间无法互收。
|
||||
- 优化管理员页面、运行日志换行和移动端顶部布局;新增 Bilibili 入口及登录页返回首页。
|
||||
|
||||
#### 2026-09-03 · v0.1.3
|
||||
|
||||
- 增加可选 WebRTC 低延迟语音。
|
||||
- 支持在管理员页面直接启用 WebRTC,无需额外媒体服务器。
|
||||
- 更新 TeamSpeak 集成,改善频道、成员和实时状态同步。
|
||||
- 优化语音缓冲和连接回退,减少网络抖动造成的延迟堆积。
|
||||
- 公网部署放行 UDP `40000–40099` 后,双浏览器语音测试稳定运行,实测间隔峰值约 `27–83ms`。
|
||||
|
||||
#### 2026-09-02 · v0.1.2
|
||||
|
||||
- 大幅优化移动端界面和成员操作。
|
||||
- 首页增加 GitHub、当前版本和更新日志入口。
|
||||
- 修复设置按钮错位,优化窄屏布局和滚动体验。
|
||||
- 增加 AudioWorklet、设备选择和更稳定的语音缓冲处理。
|
||||
|
||||
#### 2026-09-02 · v0.1.1
|
||||
|
||||
- 正式提供浏览器客户端、管理控制台、邀请链接和运维功能。
|
||||
- 修复成员同步、私聊断开和频道显示问题。
|
||||
- 增加中英文切换、默认目标、首次登录改密和一键闭麦。
|
||||
- 发布 Windows、Linux 和 Docker 部署方式。
|
||||
|
||||
#### 2026-08-31 · v0.1.0
|
||||
|
||||
- 首个规范化版本。
|
||||
|
||||
### 社区 · Community
|
||||
|
||||
QQ群:`869500475`
|
||||
|
||||
加入 QQ 群获取使用帮助、版本更新和交流支持:
|
||||
|
||||

|
||||
|
||||
### 许可证
|
||||
|
||||
WebSpeak 使用 [GNU Affero General Public License v3.0](LICENSE) 发布。
|
||||
<a id="english"></a>
|
||||
|
||||
## English
|
||||
|
||||
WebSpeak is a self-hosted browser client for TeamSpeak 3 and TeamSpeak 6. Deploy it once and let users join voice channels from a browser without installing the desktop TeamSpeak client.
|
||||
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.
|
||||
|
||||
**Live demo: [webspeak.example.invalid](https://webspeak.example.invalid)**
|
||||
<a id="en-screenshots"></a>
|
||||
|
||||
### Features
|
||||
### 🖼️ Screenshots
|
||||
|
||||
- TeamSpeak 3 and TeamSpeak 6 support with automatic protocol detection.
|
||||
- Live channel tree, online members, member locations, and status updates.
|
||||
- Channel switching and member presence grouped under the correct channel.
|
||||
- Channel text chat, server messages, private messages, and poke actions.
|
||||
- Browser microphone and speaker selection, volume control, input level, and local microphone test.
|
||||
- One-click microphone mute/unmute, VOX activation, and speaking indicators.
|
||||
- Optional low-latency WebRTC audio with automatic compatibility fallback.
|
||||
- Fixed targets, open targets, and expiring one-time invite links.
|
||||
- Admin console for targets, invites, sessions, logs, diagnostics, and database backups.
|
||||
- Chinese and English UI, theme switching, and responsive desktop/mobile layouts.
|
||||
- Mobile member action menus and desktop context menus.
|
||||
These screenshots come from the Shanghai test node and show the welcome page, voice workspace, audio controls, and member actions in English.
|
||||
|
||||
### Quick Start
|
||||
#### 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-changelog"></a>
|
||||
|
||||
### 🧾 Changelog
|
||||
|
||||
| Version | Date | Summary |
|
||||
| --- | --- | --- |
|
||||
| [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)
|
||||
|
||||
Requirements: Docker Engine and Docker Compose.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
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-server:3040/`. On the first admin login at `/admin`, use:
|
||||
|
||||
```text
|
||||
Username: admin
|
||||
Password: admin
|
||||
```
|
||||
|
||||
You must change the administrator password after the first login. Then configure the **Default TeamSpeak target** in the **Servers** page, for example:
|
||||
|
||||
```text
|
||||
203.0.113.10#9987
|
||||
```
|
||||
|
||||
If a welcome link does not contain an invite target, the default target is pre-filled automatically. In open mode, users may enter their own TeamSpeak address and port.
|
||||
|
||||
Data is stored in the `webspeak-data` Docker volume. To upgrade:
|
||||
The web service uses `3040/TCP` by default. 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`, because it removes the database and administrator settings.
|
||||
Do not run `docker compose down -v`; it removes the database, administrator settings, and other persistent data.
|
||||
|
||||
To change the web host port:
|
||||
To change the host-side web port, create `.env` in the repository directory:
|
||||
|
||||
```bash
|
||||
WEBSPEAK_PORT=3041 docker compose up -d
|
||||
```dotenv
|
||||
WEBSPEAK_PORT=3041
|
||||
```
|
||||
|
||||
#### 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
|
||||
|
||||
Requires Node.js `22.5.0` or newer and native build tools for `@discordjs/opus`.
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
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
|
||||
node dist/index.js
|
||||
npm start
|
||||
```
|
||||
|
||||
The service listens on port `3040` by default.
|
||||
Building `@discordjs/opus` requires Python, Make, and a C/C++ toolchain. For development, run `npm run dev` and `npm run web:dev` separately.
|
||||
|
||||
### Low-latency WebRTC audio
|
||||
#### First-time setup (all methods)
|
||||
|
||||
WebRTC is optional and bundled with WebSpeak. No separate media server is required.
|
||||
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.
|
||||
|
||||
1. Enable **WebRTC audio** in the admin console.
|
||||
2. Allow inbound UDP `40000–40099` in the cloud security group or upstream firewall for the WebSpeak host.
|
||||
3. Re-enter the voice space to apply the setting.
|
||||
<a id="en-requirements"></a>
|
||||
|
||||
Docker Compose publishes `40000–40099/UDP` automatically, but it cannot change a cloud security group. With Ubuntu UFW:
|
||||
### ⚠️ 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 listens on `3040/TCP` by default. Public deployments should expose the page and WebSocket through an HTTPS reverse proxy. |
|
||||
| WebRTC | The default range is `40000–40099/UDP`. Docker Compose publishes it, but the cloud security group and host firewall must also allow it. A custom range must also be reflected in Docker port mappings. 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-changelog"></a>
|
||||
|
||||
### 🧾 Änderungsprotokoll
|
||||
|
||||
| Version | Datum | Zusammenfassung |
|
||||
| --- | --- | --- |
|
||||
| [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
|
||||
sudo ufw allow 40000:40099/udp
|
||||
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
|
||||
```
|
||||
|
||||
The web page and WSS signaling use TCP `80/443`. TeamSpeak port `9987` only needs to be reachable from WebSpeak to the target TeamSpeak server; it does not need to be exposed publicly on the WebSpeak host. If WebRTC is unavailable, the client automatically uses the compatibility mode.
|
||||
WebSpeak ist standardmäßig unter `3040/TCP` erreichbar. Die persistenten Daten liegen im Docker-Volume `webspeak-data`. Für WebRTC muss zusätzlich der im Adminbereich angezeigte UDP-Portbereich freigegeben werden.
|
||||
|
||||
### Administrator settings
|
||||
#### Release-Pakete
|
||||
|
||||
The admin console can:
|
||||
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`.
|
||||
|
||||
- Set the default TeamSpeak target and server password.
|
||||
- Choose a fixed target or allow users to enter their own target.
|
||||
- Create, revoke, expire, and limit invite links.
|
||||
- View online sessions, runtime logs, diagnostics, and audit records.
|
||||
- Download diagnostic reports and SQLite backups.
|
||||
- Enable or disable low-latency WebRTC audio.
|
||||
#### Erste Konfiguration
|
||||
|
||||
### Browser requirements
|
||||
Ö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 recent Chrome, Edge, or another modern browser with WebRTC support.
|
||||
- Microphone permission is required for voice input; HTTPS is recommended for public deployments.
|
||||
- The target TeamSpeak server must be reachable from the WebSpeak host.
|
||||
<a id="de-requirements"></a>
|
||||
|
||||
### Changelog
|
||||
### ⚠️ Voraussetzungen und Hinweise
|
||||
|
||||
See [`CHANGELOG.md`](CHANGELOG.md) for the complete release history.
|
||||
| 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, Sicherheitsgruppe und Docker-Portzuordnung müssen den gesamten Bereich erlauben. |
|
||||
| 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. |
|
||||
|
||||
#### 2026-09-04 · v0.1.6
|
||||
<a id="de-license"></a>
|
||||
|
||||
- Added a warning for concurrent remembered-identity connections.
|
||||
- Added desktop accompaniment sharing.
|
||||
- Added a site favicon and refreshed the repository README branding.
|
||||
### 📜 Lizenz
|
||||
|
||||
#### 2026-09-04 · v0.1.5
|
||||
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.
|
||||
|
||||
- Fixed and refined the theme toggle so the first click switches themes, with sun/moon icons.
|
||||
- Fixed browser identity persistence across exit and return.
|
||||
|
||||
#### 2026-09-03 · v0.1.4
|
||||
|
||||
- Fixed WebRTC voice transport and speaking-state synchronization.
|
||||
- Fixed channel text messages between WebSpeak clients.
|
||||
- Refined admin pages, log wrapping, and narrow-screen header layout; added Bilibili and admin-login home links.
|
||||
|
||||
#### 2026-09-03 · v0.1.3
|
||||
|
||||
- Added optional low-latency WebRTC audio.
|
||||
- Added an admin switch for WebRTC without requiring a separate media server.
|
||||
- Updated TeamSpeak integration for better channel, member, and realtime status synchronization.
|
||||
- Improved audio buffering and connection fallback to reduce delay growth during network jitter.
|
||||
- After allowing inbound UDP `40000–40099`, a two-browser voice test ran reliably with observed peak gaps of about `27–83 ms`.
|
||||
|
||||
#### 2026-09-02 · v0.1.2
|
||||
|
||||
- Major mobile UI and member-action improvements.
|
||||
- Added GitHub, current-version, and changelog entries to the welcome page.
|
||||
- Fixed settings-button alignment and improved narrow-screen layout and scrolling.
|
||||
- Added AudioWorklet, device selection, and more stable voice buffering.
|
||||
|
||||
#### 2026-09-02 · v0.1.1
|
||||
|
||||
- Official browser client, admin console, invite links, and operations tools.
|
||||
- Fixed member synchronization, private-message disconnects, and channel display issues.
|
||||
- Added Chinese/English switching, default targets, first-login password rotation, and one-click mute.
|
||||
- Added Windows, Linux, and Docker deployment options.
|
||||
|
||||
#### 2026-08-31 · v0.1.0
|
||||
|
||||
- First normalized release.
|
||||
|
||||
### Community
|
||||
|
||||
QQ group: `869500475`
|
||||
|
||||
Join the group for support, release updates, and discussion:
|
||||
|
||||

|
||||
|
||||
### License
|
||||
|
||||
WebSpeak is released under the [GNU Affero General Public License v3.0](LICENSE).
|
||||
<div align="right"><a href="#readme-top">Nach oben ↑</a></div>
|
||||
|
After Width: | Height: | Size: 67 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 68 KiB |
|
After Width: | Height: | Size: 62 KiB |
|
After Width: | Height: | Size: 63 KiB |
|
After Width: | Height: | Size: 106 KiB |
|
After Width: | Height: | Size: 63 KiB |
|
After Width: | Height: | Size: 58 KiB |
|
After Width: | Height: | Size: 56 KiB |
|
After Width: | Height: | Size: 97 KiB |
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 56 KiB |
@@ -1,16 +1,16 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.6",
|
||||
"version": "0.1.7",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.6",
|
||||
"version": "0.1.7",
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#4e9edf7",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#8d91c30",
|
||||
"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#4e9edf7198418d8a0a0eff97e05aa2b3369c2fe0",
|
||||
"resolved": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#8d91c300438b45c2f5e96638daabbc68277f378b",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.6",
|
||||
"version": "0.1.7",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-only",
|
||||
"type": "module",
|
||||
@@ -19,7 +19,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#4e9edf7",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#8d91c30",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"werift": "0.24.4",
|
||||
|
||||
@@ -7,6 +7,18 @@ import { AdminLoginRateLimiter, waitFor } from "./login-rate-limit.js";
|
||||
import { TeamSpeakProbeError } from "../server/teamspeak-probe.js";
|
||||
import type { AdminSessionSummary } from "../server/voice-bridge.js";
|
||||
|
||||
export interface AdminConnectionRecord {
|
||||
id: string;
|
||||
nickname: string;
|
||||
target: string;
|
||||
startedAt: string;
|
||||
connectedAt: string | null;
|
||||
disconnectedAt: string | null;
|
||||
durationSeconds: number | null;
|
||||
status: "active" | "connecting" | "disconnected" | "failed";
|
||||
reason: string | null;
|
||||
}
|
||||
|
||||
export interface AdminRouterOptions {
|
||||
service: AdminService;
|
||||
sessions: AdminSessionStore;
|
||||
@@ -155,7 +167,12 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
});
|
||||
|
||||
router.get("/logs", (request, response) => {
|
||||
response.json({ available: Boolean(options.logFile && existsSync(options.logFile)), entries: readRecentLogs(options.logFile, readLimit(request.query.limit, 100)) });
|
||||
const limit = readLimit(request.query.limit, 100);
|
||||
response.json({
|
||||
available: Boolean(options.logFile && existsSync(options.logFile)),
|
||||
entries: readRecentLogs(options.logFile, limit),
|
||||
sessions: readConnectionHistory(options.logFile, limit),
|
||||
});
|
||||
});
|
||||
|
||||
router.get("/diagnostics", (_request, response) => {
|
||||
@@ -332,6 +349,7 @@ function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
|
||||
accessMode: body.accessMode === "open" ? "open" : body.accessMode === "fixed" ? "fixed" : body.accessMode as never,
|
||||
siteName: readString(body, "siteName", 80),
|
||||
welcomeText: readOptionalString(body, "welcomeText", 500),
|
||||
welcomeTextEn: typeof body.welcomeTextEn === "string" ? body.welcomeTextEn.slice(0, 500) : undefined,
|
||||
webRtcEnabled: body.webRtcEnabled === true,
|
||||
webRtcUdpStart: readOptionalInteger(body, "webRtcUdpStart"),
|
||||
webRtcUdpEnd: readOptionalInteger(body, "webRtcUdpEnd"),
|
||||
@@ -407,6 +425,113 @@ function readRecentLogs(logFile: string | undefined, limit: number): AdminLogEnt
|
||||
}
|
||||
}
|
||||
|
||||
interface StructuredLogEntry {
|
||||
timestamp: string | null;
|
||||
message: string;
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function readConnectionHistory(logFile: string | undefined, limit: number): AdminConnectionRecord[] {
|
||||
if (!logFile) return [];
|
||||
const records = new Map<string, {
|
||||
id: string;
|
||||
nickname: string;
|
||||
target: string;
|
||||
startedAt: string | null;
|
||||
connectedAt: string | null;
|
||||
disconnectedAt: string | null;
|
||||
durationSeconds: number | null;
|
||||
status: AdminConnectionRecord["status"];
|
||||
reason: string | null;
|
||||
}>();
|
||||
for (const log of readStructuredLogs(logFile)) {
|
||||
const entryId = typeof log.raw.entryId === "string" ? log.raw.entryId : "";
|
||||
if (!entryId || !log.timestamp) continue;
|
||||
const current = records.get(entryId) ?? {
|
||||
id: entryId,
|
||||
nickname: "",
|
||||
target: "",
|
||||
startedAt: null,
|
||||
connectedAt: null,
|
||||
disconnectedAt: null,
|
||||
durationSeconds: null,
|
||||
status: "connecting" as const,
|
||||
reason: null,
|
||||
};
|
||||
const nickname = typeof log.raw.nickname === "string" ? log.raw.nickname : "";
|
||||
const target = typeof log.raw.target === "string" ? log.raw.target : "";
|
||||
if (nickname) current.nickname = nickname;
|
||||
if (target) current.target = target;
|
||||
if (log.message === "WebClient connecting") {
|
||||
current.startedAt ??= log.timestamp;
|
||||
current.status = "connecting";
|
||||
} else if (log.message === "Web client connected to TeamSpeak") {
|
||||
current.startedAt ??= log.timestamp;
|
||||
current.connectedAt = log.timestamp;
|
||||
current.status = "active";
|
||||
} else if (log.message === "Client session torn down") {
|
||||
current.startedAt ??= log.timestamp;
|
||||
current.disconnectedAt = log.timestamp;
|
||||
current.durationSeconds = current.connectedAt && typeof log.raw.durationSeconds === "number"
|
||||
? Math.max(0, Math.floor(log.raw.durationSeconds))
|
||||
: current.connectedAt
|
||||
? Math.max(0, Math.floor((Date.parse(log.timestamp) - Date.parse(current.connectedAt)) / 1000))
|
||||
: null;
|
||||
current.reason = typeof log.raw.reason === "string" ? log.raw.reason : null;
|
||||
current.status = current.connectedAt ? "disconnected" : "failed";
|
||||
}
|
||||
records.set(entryId, current);
|
||||
}
|
||||
const now = Date.now();
|
||||
return [...records.values()]
|
||||
.filter((record): record is typeof record & { startedAt: string } => Boolean(record.startedAt))
|
||||
.map((record) => {
|
||||
const start = record.connectedAt ?? record.startedAt;
|
||||
const end = record.disconnectedAt ? Date.parse(record.disconnectedAt) : now;
|
||||
return {
|
||||
id: record.id,
|
||||
nickname: record.nickname || "—",
|
||||
target: record.target || "—",
|
||||
startedAt: record.startedAt,
|
||||
connectedAt: record.connectedAt,
|
||||
disconnectedAt: record.disconnectedAt,
|
||||
durationSeconds: record.durationSeconds ?? (record.status === "active" || record.status === "connecting"
|
||||
? Math.max(0, Math.floor((end - Date.parse(start)) / 1000))
|
||||
: null),
|
||||
status: record.status,
|
||||
reason: record.reason,
|
||||
};
|
||||
})
|
||||
.sort((left, right) => Date.parse(right.disconnectedAt ?? right.startedAt) - Date.parse(left.disconnectedAt ?? left.startedAt))
|
||||
.slice(0, limit);
|
||||
}
|
||||
|
||||
function readStructuredLogs(logFile: string): StructuredLogEntry[] {
|
||||
const paths = [logFile, `${logFile}.1`, `${logFile}.2`, `${logFile}.3`].filter((value, index, all) => value && all.indexOf(value) === index);
|
||||
const entries: StructuredLogEntry[] = [];
|
||||
for (const path of paths) {
|
||||
if (!existsSync(path)) continue;
|
||||
try {
|
||||
for (const line of readFileSync(path, "utf8").split(/\r?\n/).filter(Boolean)) {
|
||||
try {
|
||||
const raw = JSON.parse(line) as Record<string, unknown>;
|
||||
entries.push({
|
||||
timestamp: typeof raw.time === "string" ? raw.time : null,
|
||||
message: typeof raw.msg === "string" ? raw.msg : "",
|
||||
raw,
|
||||
});
|
||||
} catch {
|
||||
// Non-JSON lines are still shown by the normal log viewer, but cannot
|
||||
// be associated with a user session safely.
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// A rotated file can disappear between existsSync and readFileSync.
|
||||
}
|
||||
}
|
||||
return entries.sort((left, right) => Date.parse(left.timestamp ?? "") - Date.parse(right.timestamp ?? ""));
|
||||
}
|
||||
|
||||
interface AdminOverview {
|
||||
gateway: { uptimeSeconds: number };
|
||||
teamSpeak: {
|
||||
|
||||
@@ -6,7 +6,8 @@ import { formatTeamSpeakTarget, parseTeamSpeakTarget, type TeamSpeakTarget } fro
|
||||
import { type AccessMode, type ManagedInviteRecord, type SettingsUpdate, WebSpeakDatabase } from "../persistence/database.js";
|
||||
import { hashAdminPassword, validateAdminPassword, verifyAdminPassword } from "../security/admin-password.js";
|
||||
import { decryptSecret, encryptSecret } from "../security/secret-crypto.js";
|
||||
import { probeTeamSpeak, TeamSpeakProbeError, type TeamSpeakProbeResult } from "../server/teamspeak-probe.js";
|
||||
import { probeTeamSpeak, TeamSpeakProbeError } from "../server/teamspeak-probe.js";
|
||||
import { pingTeamSpeakHost } from "../server/network-probe.js";
|
||||
import type { WebRtcAudioOptions } from "../server/webrtc-audio.js";
|
||||
import { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_MAX, WEBRTC_UDP_PORT_MIN } from "../server/webrtc-config.js";
|
||||
|
||||
@@ -17,6 +18,7 @@ export interface AdminSettingsInput {
|
||||
accessMode: AccessMode;
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
welcomeTextEn?: string;
|
||||
webRtcEnabled: boolean;
|
||||
webRtcUdpStart?: number;
|
||||
webRtcUdpEnd?: number;
|
||||
@@ -97,6 +99,7 @@ export class AdminService {
|
||||
initialized: this.isInitialized(),
|
||||
siteName: settings.siteName,
|
||||
welcomeText: settings.welcomeText,
|
||||
welcomeTextEn: settings.welcomeTextEn,
|
||||
accessMode: settings.accessMode,
|
||||
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
|
||||
};
|
||||
@@ -110,6 +113,7 @@ export class AdminService {
|
||||
accessMode: settings.accessMode,
|
||||
siteName: settings.siteName,
|
||||
welcomeText: settings.welcomeText,
|
||||
welcomeTextEn: settings.welcomeTextEn,
|
||||
lastTestAt: settings.lastTestAt,
|
||||
lastTestLatencyMs: settings.lastTestLatencyMs,
|
||||
lastTestError: settings.lastTestError,
|
||||
@@ -152,7 +156,7 @@ export class AdminService {
|
||||
};
|
||||
}
|
||||
|
||||
async testConnection(targetText: string, password: string, persistResult: boolean): Promise<Omit<TeamSpeakProbeResult, "protocol">> {
|
||||
async testConnection(targetText: string, password: string, persistResult: boolean): Promise<{ ok: boolean; latencyMs: number; serverName: string | null; requiresPassword: boolean; packetLossPercent?: number; attempts?: number; successfulAttempts?: number; errorCode?: string }> {
|
||||
let target: TeamSpeakTarget;
|
||||
try {
|
||||
target = parseTeamSpeakTarget(targetText);
|
||||
@@ -160,6 +164,32 @@ export class AdminService {
|
||||
throw new AdminInputError("INVALID_TARGET", "TeamSpeak target is invalid");
|
||||
}
|
||||
try {
|
||||
// The admin connection test must not create a temporary TeamSpeak
|
||||
// client: that client becomes visible in the target channel. Use the
|
||||
// WebSpeak host's ICMP route measurement instead. The injected probe is
|
||||
// retained for unit tests and explicit protocol-probe callers.
|
||||
if (this.probe === probeTeamSpeak) {
|
||||
const result = await pingTeamSpeakHost(target.host, { attempts: 4 });
|
||||
const publicResult = {
|
||||
ok: result.ok,
|
||||
latencyMs: result.latencyMs ?? 0,
|
||||
serverName: null,
|
||||
requiresPassword: false,
|
||||
packetLossPercent: result.packetLossPercent,
|
||||
attempts: result.attempts,
|
||||
successfulAttempts: result.successfulAttempts,
|
||||
...(result.errorCode ? { errorCode: result.errorCode } : {}),
|
||||
};
|
||||
if (persistResult) {
|
||||
this.database.recordConnectionTest({ protocol: null, latencyMs: result.latencyMs, error: result.ok ? null : (result.errorCode ?? "UNREACHABLE") });
|
||||
this.database.addAudit(result.ok ? "CONNECTION_TEST_SUCCEEDED" : "CONNECTION_TEST_FAILED", {
|
||||
latencyMs: result.latencyMs,
|
||||
packetLossPercent: result.packetLossPercent,
|
||||
...(result.errorCode ? { code: result.errorCode } : {}),
|
||||
});
|
||||
}
|
||||
return publicResult;
|
||||
}
|
||||
const result = await this.probe(target, password, this.logger);
|
||||
if (persistResult) {
|
||||
this.database.recordConnectionTest({ protocol: result.protocol, latencyMs: result.latencyMs, error: null });
|
||||
@@ -263,8 +293,10 @@ export class AdminService {
|
||||
}
|
||||
const siteName = input.siteName.trim();
|
||||
const welcomeText = input.welcomeText.trim();
|
||||
const welcomeTextEn = typeof input.welcomeTextEn === "string" ? input.welcomeTextEn.trim() : current.welcomeTextEn;
|
||||
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 (input.accessMode !== "fixed" && input.accessMode !== "open") {
|
||||
throw new AdminInputError("INVALID_ACCESS_MODE", "Access mode is invalid");
|
||||
}
|
||||
@@ -293,6 +325,7 @@ export class AdminService {
|
||||
return {
|
||||
siteName,
|
||||
welcomeText,
|
||||
welcomeTextEn,
|
||||
accessMode: input.accessMode,
|
||||
tsHost: target.host,
|
||||
tsPort: target.port,
|
||||
@@ -324,6 +357,7 @@ export class AdminService {
|
||||
return {
|
||||
siteName: settings.siteName,
|
||||
welcomeText: settings.welcomeText,
|
||||
welcomeTextEn: settings.welcomeTextEn,
|
||||
accessMode: settings.accessMode,
|
||||
tsHost: settings.tsHost,
|
||||
tsPort: settings.tsPort,
|
||||
@@ -342,6 +376,7 @@ export class AdminService {
|
||||
this.database.updateSettings({
|
||||
siteName: current.siteName,
|
||||
welcomeText: current.welcomeText,
|
||||
welcomeTextEn: current.welcomeTextEn,
|
||||
accessMode: current.accessMode,
|
||||
tsHost: legacy.tsHost,
|
||||
tsPort: legacy.tsPort,
|
||||
|
||||
@@ -6,12 +6,13 @@ 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 = 3;
|
||||
export const DATABASE_SCHEMA_VERSION = 4;
|
||||
export type AccessMode = "fixed" | "open";
|
||||
|
||||
export interface PersistedSettings {
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
welcomeTextEn: string;
|
||||
accessMode: AccessMode;
|
||||
tsHost: string;
|
||||
tsPort: number;
|
||||
@@ -29,6 +30,7 @@ export interface PersistedSettings {
|
||||
export interface SettingsUpdate {
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
welcomeTextEn?: string;
|
||||
accessMode: AccessMode;
|
||||
tsHost: string;
|
||||
tsPort: number;
|
||||
@@ -69,6 +71,7 @@ interface ManagedInviteRow extends Record<string, unknown> {
|
||||
interface SettingsRow extends Record<string, unknown> {
|
||||
site_name: string;
|
||||
welcome_text: string;
|
||||
welcome_text_en: string;
|
||||
access_mode: string;
|
||||
ts_host: string;
|
||||
ts_port: number;
|
||||
@@ -143,6 +146,7 @@ export class WebSpeakDatabase {
|
||||
return {
|
||||
siteName: row.site_name,
|
||||
welcomeText: row.welcome_text,
|
||||
welcomeTextEn: row.welcome_text_en,
|
||||
accessMode: row.access_mode === "open" ? "open" : "fixed",
|
||||
tsHost: row.ts_host,
|
||||
tsPort: row.ts_port,
|
||||
@@ -377,19 +381,29 @@ export class WebSpeakDatabase {
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 3");
|
||||
});
|
||||
version = 3;
|
||||
}
|
||||
if (version === 3) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
ALTER TABLE settings ADD COLUMN welcome_text_en TEXT NOT NULL DEFAULT '';
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 4");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private writeSettings(settings: SettingsUpdate, now: string): void {
|
||||
this.database.prepare(
|
||||
`UPDATE settings SET
|
||||
site_name = ?, welcome_text = ?, access_mode = ?, ts_host = ?, ts_port = ?,
|
||||
site_name = ?, welcome_text = ?, welcome_text_en = ?, access_mode = ?, ts_host = ?, ts_port = ?,
|
||||
ts_password_encrypted = ?, webrtc_enabled = ?, webrtc_udp_start = ?,
|
||||
webrtc_udp_end = ?, updated_at = ?
|
||||
WHERE id = 1`,
|
||||
).run(
|
||||
settings.siteName,
|
||||
settings.welcomeText,
|
||||
settings.welcomeTextEn ?? "",
|
||||
settings.accessMode,
|
||||
settings.tsHost,
|
||||
settings.tsPort,
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
export type TeamSpeakPingErrorCode =
|
||||
| "HOST_NOT_FOUND"
|
||||
| "UNREACHABLE"
|
||||
| "TIMEOUT"
|
||||
| "PING_UNAVAILABLE"
|
||||
| "INVALID_PASSWORD"
|
||||
| "PROTOCOL_NEGOTIATION_FAILED"
|
||||
| "SERVER_REJECTED"
|
||||
| "INTERNAL_ERROR";
|
||||
|
||||
export interface TeamSpeakPingAttempt {
|
||||
ok: boolean;
|
||||
latencyMs: number | null;
|
||||
errorCode?: TeamSpeakPingErrorCode;
|
||||
}
|
||||
|
||||
export interface TeamSpeakPingResult {
|
||||
ok: boolean;
|
||||
latencyMs: number | null;
|
||||
packetLossPercent: number;
|
||||
attempts: number;
|
||||
successfulAttempts: number;
|
||||
samples: number[];
|
||||
errorCode?: TeamSpeakPingErrorCode;
|
||||
}
|
||||
|
||||
export type TeamSpeakCommandExecutor = (command: string, timeoutMs?: number) => Promise<unknown>;
|
||||
|
||||
export type HostPingExecutor = (host: string, timeoutMs: number) => Promise<number>;
|
||||
|
||||
/**
|
||||
* Measure an already connected TeamSpeak session using the protocol's own
|
||||
* command channel. TeamSpeak voice/query traffic is UDP; a TCP connect to
|
||||
* port 9987 is therefore not a valid reachability test and reports false
|
||||
* packet loss even while voice works normally.
|
||||
*/
|
||||
export async function pingTeamSpeakSession(
|
||||
execute: TeamSpeakCommandExecutor,
|
||||
timeoutMs = 1_500,
|
||||
): Promise<TeamSpeakPingAttempt> {
|
||||
const startedAt = Date.now();
|
||||
try {
|
||||
// `version` is read-only and is handled by both TS3 and TS6.
|
||||
await execute("version", timeoutMs);
|
||||
return { ok: true, latencyMs: Math.max(0, Date.now() - startedAt) };
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
ok: false,
|
||||
latencyMs: null,
|
||||
errorCode: classifyProbeError(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function collectTeamSpeakPings(
|
||||
probe: () => Promise<TeamSpeakPingAttempt>,
|
||||
options: { attempts?: number } = {},
|
||||
): Promise<TeamSpeakPingResult> {
|
||||
const attempts = Math.max(1, Math.min(8, Math.floor(options.attempts ?? 4)));
|
||||
const results: TeamSpeakPingAttempt[] = [];
|
||||
// Keep attempts sequential. This measures the real protocol path without
|
||||
// opening several temporary TeamSpeak sessions at the same time.
|
||||
for (let index = 0; index < attempts; index += 1) {
|
||||
results.push(await probe());
|
||||
}
|
||||
return summarizeTeamSpeakPings(results, attempts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ping the TeamSpeak host from the WebSpeak machine without creating a
|
||||
* TeamSpeak client. This is intentionally a host/network diagnostic: the
|
||||
* TeamSpeak voice port is UDP, so a TCP socket probe is not meaningful and a
|
||||
* client-protocol probe would create an extra visible member.
|
||||
*/
|
||||
export async function pingTeamSpeakHost(
|
||||
host: string,
|
||||
options: { attempts?: number; timeoutMs?: number; execute?: HostPingExecutor } = {},
|
||||
): Promise<TeamSpeakPingResult> {
|
||||
const timeoutMs = Math.max(250, Math.min(5_000, Math.floor(options.timeoutMs ?? 1_000)));
|
||||
const execute = options.execute ?? pingHostOnce;
|
||||
return collectTeamSpeakPings(async () => {
|
||||
try {
|
||||
return { ok: true, latencyMs: await execute(host, timeoutMs) };
|
||||
} catch (error: unknown) {
|
||||
return { ok: false, latencyMs: null, errorCode: classifyProbeError(error) };
|
||||
}
|
||||
}, { attempts: options.attempts ?? 4 });
|
||||
}
|
||||
|
||||
export function summarizeTeamSpeakPings(results: TeamSpeakPingAttempt[], attempts = results.length): TeamSpeakPingResult {
|
||||
const normalizedAttempts = Math.max(1, attempts);
|
||||
const samples = results
|
||||
.filter((result): result is TeamSpeakPingAttempt & { latencyMs: number } => result.ok && result.latencyMs !== null)
|
||||
.map((result) => result.latencyMs)
|
||||
.sort((left, right) => left - right);
|
||||
const errorCode = results.find((result) => result.errorCode)?.errorCode;
|
||||
|
||||
return {
|
||||
ok: samples.length > 0,
|
||||
latencyMs: samples.length ? samples[Math.floor(samples.length / 2)] : null,
|
||||
packetLossPercent: Math.round(((normalizedAttempts - samples.length) / normalizedAttempts) * 100),
|
||||
attempts: normalizedAttempts,
|
||||
successfulAttempts: samples.length,
|
||||
samples,
|
||||
...(errorCode ? { errorCode } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function classifyProbeError(error: unknown): TeamSpeakPingErrorCode {
|
||||
const text = error instanceof Error ? error.message : String(error);
|
||||
const lower = text.toLocaleLowerCase();
|
||||
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";
|
||||
return "UNREACHABLE";
|
||||
}
|
||||
|
||||
function pingHostOnce(host: string, timeoutMs: number): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const windows = process.platform === "win32";
|
||||
const command = windows ? "ping.exe" : "ping";
|
||||
const args = windows
|
||||
? ["-n", "1", "-w", String(timeoutMs), host]
|
||||
: ["-c", "1", "-W", String(Math.max(1, Math.ceil(timeoutMs / 1_000))), host];
|
||||
const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"] });
|
||||
let output = "";
|
||||
let settled = false;
|
||||
const finish = (callback: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
callback();
|
||||
};
|
||||
const timer = setTimeout(() => finish(() => {
|
||||
child.kill();
|
||||
reject(new Error("ping timeout"));
|
||||
}), timeoutMs + 250);
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stderr.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk: string) => { output += chunk; });
|
||||
child.stderr.on("data", (chunk: string) => { output += chunk; });
|
||||
child.once("error", (error) => finish(() => reject(error)));
|
||||
child.once("close", (code) => finish(() => {
|
||||
const match = output.match(/(?:time|时间)\s*[=<]\s*([\d.,]+)\s*(?:ms|毫秒)?/i);
|
||||
if (code === 0 && match) {
|
||||
const latencyMs = Number.parseFloat(match[1].replace(",", "."));
|
||||
if (Number.isFinite(latencyMs)) {
|
||||
resolve(Math.max(0, latencyMs));
|
||||
return;
|
||||
}
|
||||
}
|
||||
reject(new Error(output.trim() || `ping exited with code ${code ?? "unknown"}`));
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep a small compatibility helper for callers that only need one protocol
|
||||
* attempt. It deliberately has no host/port argument because the connected
|
||||
* TeamSpeak session owns the actual resolved endpoint.
|
||||
*/
|
||||
export function pingTeamSpeakPort(
|
||||
execute: TeamSpeakCommandExecutor,
|
||||
timeoutMs = 1_500,
|
||||
): Promise<TeamSpeakPingAttempt> {
|
||||
return pingTeamSpeakSession(execute, timeoutMs);
|
||||
}
|
||||
|
||||
/*
|
||||
* This function used to open a raw TCP socket to the TeamSpeak voice port.
|
||||
* That transport is not TeamSpeak's client protocol and must not be used for
|
||||
* reachability measurements. Keep the aggregation logic above independent of
|
||||
* the connection setup so admin tests can supply a real protocol probe.
|
||||
*/
|
||||
export async function pingTeamSpeak(
|
||||
probe: () => Promise<TeamSpeakPingAttempt>,
|
||||
options: { attempts?: number } = {},
|
||||
): Promise<TeamSpeakPingResult> {
|
||||
return collectTeamSpeakPings(probe, options);
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import type { Logger } from "../logger.js";
|
||||
import { normalizeTeamSpeakError, type WebSpeakErrorCode } from "../errors.js";
|
||||
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js";
|
||||
import { TSClient } from "./ts-client.js";
|
||||
import type { TeamSpeakProtocol } from "./teamspeak-adapter.js";
|
||||
|
||||
export type ProbeErrorCode =
|
||||
| "HOST_NOT_FOUND"
|
||||
@@ -30,8 +31,10 @@ export class TeamSpeakProbeError extends Error {
|
||||
interface ProbeAdapter {
|
||||
connect(): Promise<void>;
|
||||
disconnect(): Promise<void>;
|
||||
readonly protocol: TeamSpeakProtocol | null;
|
||||
readonly client: {
|
||||
readonly protocol?: TeamSpeakProtocol | null;
|
||||
getProtocol?(): TeamSpeakProtocol | null;
|
||||
execCommandWithResponse?(command: string, timeoutMs?: number): Promise<Record<string, string>[]>;
|
||||
readonly client?: {
|
||||
execCommandWithResponse(command: string, timeoutMs?: number): Promise<Record<string, string>[]>;
|
||||
};
|
||||
}
|
||||
@@ -47,7 +50,15 @@ export async function probeTeamSpeak(
|
||||
password: string,
|
||||
logger: Logger,
|
||||
factory: ProbeAdapterFactory = ({ target: probeTarget, password: probePassword, logger: probeLogger }) =>
|
||||
new TeamSpeakAdapter({ target: probeTarget, nickname: "WebSpeak Probe", serverPassword: probePassword }, probeLogger),
|
||||
(() => {
|
||||
const client = new TSClient({ target: probeTarget, nickname: "WebSpeak Probe", serverPassword: probePassword }, probeLogger);
|
||||
return {
|
||||
connect: () => client.connect(),
|
||||
disconnect: () => client.disconnect(),
|
||||
getProtocol: () => client.getProtocol(),
|
||||
execCommandWithResponse: (command: string, timeoutMs?: number) => client.execCommandWithResponse(command, timeoutMs),
|
||||
};
|
||||
})(),
|
||||
): Promise<TeamSpeakProbeResult> {
|
||||
const startedAt = Date.now();
|
||||
const adapter = factory({ target, password, logger: logger.child({ component: "teamspeak-probe" }) });
|
||||
@@ -55,7 +66,9 @@ export async function probeTeamSpeak(
|
||||
await adapter.connect();
|
||||
let serverName: string | null = null;
|
||||
try {
|
||||
const rows = await adapter.client.execCommandWithResponse("serverinfo", 3000);
|
||||
const execute = adapter.execCommandWithResponse?.bind(adapter) ?? adapter.client?.execCommandWithResponse.bind(adapter.client);
|
||||
if (!execute) throw new Error("Probe adapter does not support commands");
|
||||
const rows = await execute("serverinfo", 3000);
|
||||
const first = rows[0] ?? {};
|
||||
serverName = first.virtualserver_name ?? first.server_name ?? first.name ?? null;
|
||||
} catch {
|
||||
@@ -63,7 +76,7 @@ export async function probeTeamSpeak(
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
protocol: adapter.protocol,
|
||||
protocol: adapter.protocol ?? adapter.getProtocol?.() ?? null,
|
||||
latencyMs: Math.max(0, Date.now() - startedAt),
|
||||
serverName,
|
||||
requiresPassword: Boolean(password),
|
||||
|
||||
@@ -247,6 +247,11 @@ export class TSClient extends EventEmitter {
|
||||
return this.adapter?.protocol ?? null;
|
||||
}
|
||||
|
||||
async execCommandWithResponse(command: string, timeoutMs = 3000): Promise<Record<string, string>[]> {
|
||||
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
|
||||
return this.client.execCommandWithResponse(command, timeoutMs);
|
||||
}
|
||||
|
||||
getIdentityString(): string {
|
||||
return this.identity.toString();
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import { SessionManager, type ManagedSession, type SessionTeardownReason } from
|
||||
import { parseClientCommand, type ClientCommand } from "./voice-protocol.js";
|
||||
import { isRecoverable, reconnectDelayMs, reconnectWindowOpen } from "./reconnect-policy.js";
|
||||
import { WebRtcAudioSession, type WebRtcAudioOptions, type WebRtcAudioStats, type WebRtcSessionDescription } from "./webrtc-audio.js";
|
||||
import { pingTeamSpeakSession } from "./network-probe.js";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { OpusEncoder } = require("@discordjs/opus") as {
|
||||
@@ -131,6 +132,7 @@ interface WebClientEntry {
|
||||
reconnectTimer: ReturnType<typeof setTimeout> | null;
|
||||
audio: AudioFlowStats;
|
||||
webrtc: WebRtcAudioSession | null;
|
||||
lastLatencyProbeAt: number;
|
||||
}
|
||||
|
||||
export class VoiceBridge {
|
||||
@@ -222,6 +224,7 @@ export class VoiceBridge {
|
||||
reconnectTimer: null,
|
||||
audio: createAudioFlowStats(),
|
||||
webrtc: null,
|
||||
lastLatencyProbeAt: 0,
|
||||
};
|
||||
this.entries.set(entryId, entry!);
|
||||
try {
|
||||
@@ -307,6 +310,7 @@ export class VoiceBridge {
|
||||
reconnectStartedAt = 0;
|
||||
if (!wasReconnecting) {
|
||||
entry!.eventLog.push({ id: `event-${Date.now().toString(36)}-connected`, kind: "connection", message: "已连接到服务器", timestamp: Date.now() });
|
||||
this.logger.info({ entryId: entry!.id, nickname: entry!.nickname, target: formatTeamSpeakTarget(entry!.target) }, "Web client connected to TeamSpeak");
|
||||
}
|
||||
session.transition("connected");
|
||||
sendJson({
|
||||
@@ -736,7 +740,14 @@ export class VoiceBridge {
|
||||
else entry.ws.close(reason === "protocol-error" ? 1008 : 1000, reason);
|
||||
}
|
||||
if (entry.identityLeaseKey) this.identityLeases.release(entry.identityLeaseKey, entry.id);
|
||||
this.logger.info({ entryId: entry.id, reason, audio: { ...entry.audio } }, "Client session torn down");
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
nickname: entry.nickname,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
reason,
|
||||
durationSeconds: Math.max(0, Math.floor((Date.now() - entry.session.createdAt) / 1000)),
|
||||
audio: { ...entry.audio },
|
||||
}, "Client session torn down");
|
||||
}
|
||||
|
||||
private startHeartbeat(): void {
|
||||
@@ -857,6 +868,24 @@ async function handleCommand(
|
||||
command: ClientCommand,
|
||||
sendJson: (message: Record<string, unknown>) => void,
|
||||
): Promise<void> {
|
||||
if (command.type === "latencyProbe") {
|
||||
const sequence = command.payload.sequence as string;
|
||||
const now = Date.now();
|
||||
if (now - entry.lastLatencyProbeAt < 150) return;
|
||||
entry.lastLatencyProbeAt = now;
|
||||
const result = await pingTeamSpeakSession(
|
||||
(request, timeoutMs) => entry.tsClient.execCommandWithResponse(request, timeoutMs),
|
||||
);
|
||||
sendJson({
|
||||
type: "latencyPong",
|
||||
sequence,
|
||||
teamSpeakLatencyMs: result.latencyMs,
|
||||
teamSpeakReachable: result.ok,
|
||||
teamSpeakErrorCode: result.errorCode ?? null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (command.type === "switchChannel") {
|
||||
const rawId = command.payload.channelId as string;
|
||||
const channelPassword = typeof command.payload.password === "string" ? command.payload.password : "";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export interface ClientCommand {
|
||||
type: "switchChannel" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway" | "setWhisperTargets" | "setWhisperActive" | "setMicrophoneMuted" | "setAccompanimentActive" | "setMemberVolume";
|
||||
type: "switchChannel" | "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"]);
|
||||
const supportedTypes = new Set(["switchChannel", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume", "latencyProbe"]);
|
||||
if (!supportedTypes.has(value.type)) {
|
||||
return { error: { code: "UNKNOWN_MESSAGE_TYPE", message: "不支持的消息类型" } };
|
||||
}
|
||||
@@ -65,6 +65,9 @@ export function parseClientCommand(raw: string): ClientCommandResult {
|
||||
if (value.type === "setMemberVolume" && (typeof value.payload.clientId !== "number" || !Number.isInteger(value.payload.clientId) || value.payload.clientId <= 0 || value.payload.clientId > 65535 || typeof value.payload.volume !== "number" || !Number.isFinite(value.payload.volume) || value.payload.volume < 0 || value.payload.volume > 4)) {
|
||||
return { error: { code: "INVALID_MEMBER_VOLUME", message: "成员音量无效" } };
|
||||
}
|
||||
if (value.type === "latencyProbe" && (typeof value.payload.sequence !== "string" || value.payload.sequence.length > 64)) {
|
||||
return { error: { code: "INVALID_LATENCY_PROBE", message: "延迟探测标识无效" } };
|
||||
}
|
||||
return {
|
||||
type: value.type as ClientCommand["type"],
|
||||
...(typeof value.requestId === "string" ? { requestId: value.requestId } : {}),
|
||||
|
||||
@@ -30,13 +30,10 @@ const MAX_MIXER_QUEUE_FRAMES = 4;
|
||||
const MAX_MIXER_PACER_LAG_MS = AUDIO_CLOCK_INTERVAL_MS * 2;
|
||||
const MAX_MIXER_FRAME_AGE_MS = MAX_MIXER_QUEUE_FRAMES * AUDIO_CLOCK_INTERVAL_MS;
|
||||
const MIXER_UNDERRUN_WINDOW_MS = 200;
|
||||
// TeamSpeak and browsers can emit valid Opus comfort-noise/silence packets
|
||||
// while a client is muted. Do not turn those packets into a false "speaking"
|
||||
// indicator or forward them to TeamSpeak as if they were voice.
|
||||
const MIN_SPEAKER_RMS = 160;
|
||||
// Keep this below the speaking threshold so quiet but valid accompaniment is
|
||||
// forwarded while comfort-noise packets remain filtered.
|
||||
const MIN_FORWARD_RMS = 24;
|
||||
// This threshold is used only for the speaking indicator. It must never decide
|
||||
// whether a media packet is forwarded or queued: quiet/comfort-noise Opus
|
||||
// packets are still valid media and dropping them can break decoder continuity.
|
||||
const SPEAKER_ACTIVITY_RMS = 160;
|
||||
|
||||
// WebRTC is served by the WebSpeak process itself. The default range is also
|
||||
// published by the bundled Docker Compose file; advanced administrators can
|
||||
@@ -112,7 +109,6 @@ export class WebRtcAudioSession {
|
||||
private readonly onVoiceFrame: (data: Buffer, codec: 4 | 5) => void;
|
||||
private readonly onVoiceActivity: (clientIds: number[]) => void;
|
||||
private readonly outgoingTrack: MediaStreamTrack;
|
||||
private ingressDecoder: { decode(data: Buffer): Buffer } | null = null;
|
||||
private readonly decoderByClient = new Map<number, { decode(data: Buffer): Buffer }>();
|
||||
private readonly partialPcmByClient = new Map<number, Buffer>();
|
||||
private readonly pendingFrames = new Map<number, PendingAudioFrame[]>();
|
||||
@@ -183,17 +179,10 @@ export class WebRtcAudioSession {
|
||||
this.stats.webrtcIngressRtpFrames++;
|
||||
if (!this.opusPayloadTypes.has(rtp.header.payloadType)) return;
|
||||
const payload = Buffer.from(rtp.payload);
|
||||
// The track is a browser-side mix of microphone and accompaniment.
|
||||
// Decode it once to reject malformed RTP. A normal microphone still
|
||||
// uses the low-level comfort-noise gate, while accompaniment must not
|
||||
// be treated as speech: quiet music frames are valid audio and are
|
||||
// forwarded with TeamSpeak's music codec marker.
|
||||
const rms = this.getIngressRms(payload);
|
||||
if (rms === null) return;
|
||||
if (!this.accompanimentActive && rms < MIN_FORWARD_RMS) {
|
||||
this.stats.webrtcIngressQuietFrames++;
|
||||
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
|
||||
// can cause downstream gaps, clicks, or decoder recovery artifacts.
|
||||
this.onVoiceFrame(payload, this.accompanimentActive ? 5 : 4);
|
||||
});
|
||||
void audio.sender.replaceTrack(this.outgoingTrack).catch((error: unknown) => {
|
||||
@@ -206,16 +195,11 @@ export class WebRtcAudioSession {
|
||||
|
||||
try {
|
||||
this.encoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
|
||||
// Use a separate stateful decoder for browser ingress. RTP payloads do
|
||||
// not identify whether a packet contains microphone energy or DTX/CN
|
||||
// audio, so the gateway must decode it before forwarding to TS.
|
||||
this.ingressDecoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
|
||||
} catch (error: unknown) {
|
||||
this.encoder = null;
|
||||
this.ingressDecoder = null;
|
||||
this.logger.error({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer encoder");
|
||||
}
|
||||
if (!this.encoder || !this.ingressDecoder) {
|
||||
if (!this.encoder) {
|
||||
this.outgoingTrack.stop();
|
||||
throw new Error("WebRTC Opus codec is unavailable");
|
||||
}
|
||||
@@ -275,12 +259,10 @@ export class WebRtcAudioSession {
|
||||
const pendingPcm = this.partialPcmByClient.get(data.clientId);
|
||||
const combined = pendingPcm ? Buffer.concat([pendingPcm, pcm]) : pcm;
|
||||
const rms = this.calculateRms(pcm);
|
||||
// A muted TeamSpeak client can still produce comfort-noise packets.
|
||||
// Do not let those packets turn a single accompaniment stream into a
|
||||
// synthetic multi-source mix. Music packets use codec 5 and must be
|
||||
// retained even when their instantaneous RMS is low.
|
||||
if (data.codec !== 5 && rms < MIN_SPEAKER_RMS) return;
|
||||
if (rms >= MIN_SPEAKER_RMS) this.activeSpeakerIds.add(data.clientId);
|
||||
// RMS is used only for the UI speaking indicator. Every decoded frame,
|
||||
// including quiet/comfort-noise frames, continues into the queue so the
|
||||
// receiver keeps an uninterrupted codec timeline.
|
||||
if (rms >= SPEAKER_ACTIVITY_RMS) this.activeSpeakerIds.add(data.clientId);
|
||||
const canForwardOpus = !pendingPcm && pcm.length === AUDIO_FRAME_BYTES;
|
||||
let offset = 0;
|
||||
let enqueued = false;
|
||||
@@ -325,7 +307,6 @@ export class WebRtcAudioSession {
|
||||
this.memberVolumes.clear();
|
||||
this.partialPcmByClient.clear();
|
||||
this.activeSpeakerIds.clear();
|
||||
this.ingressDecoder = null;
|
||||
this.decoderByClient.clear();
|
||||
this.encoder = null;
|
||||
this.outgoingTrack.stop();
|
||||
@@ -442,24 +423,6 @@ export class WebRtcAudioSession {
|
||||
else this.memberVolumes.set(clientId, normalized);
|
||||
}
|
||||
|
||||
private getIngressRms(data: Buffer): number | null {
|
||||
const decoder = this.ingressDecoder;
|
||||
if (!decoder) return null;
|
||||
try {
|
||||
const pcm = decoder.decode(data);
|
||||
if (pcm.length < 2) {
|
||||
this.stats.webrtcIngressDecodeErrors++;
|
||||
return null;
|
||||
}
|
||||
return this.calculateRms(pcm);
|
||||
} catch {
|
||||
// Malformed/transition packets are discarded without interrupting the
|
||||
// rest of the peer. The next valid Opus packet can recover the decoder.
|
||||
this.stats.webrtcIngressDecodeErrors++;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private calculateRms(pcm: Buffer): number {
|
||||
let sum = 0;
|
||||
let samples = 0;
|
||||
|
||||
@@ -161,7 +161,7 @@ test("admin API requires the default password to be changed before administratio
|
||||
const sessions = await request(origin, "/api/admin/sessions", { cookie });
|
||||
assert.deepEqual(sessions.body.sessions, []);
|
||||
const diagnostics = await request(origin, "/api/admin/diagnostics", { cookie });
|
||||
assert.equal(diagnostics.body.database.schemaVersion, 3);
|
||||
assert.equal(diagnostics.body.database.schemaVersion, 4);
|
||||
assert.equal("target" in diagnostics.body.teamSpeak, true);
|
||||
assert.equal("protocol" in diagnostics.body.teamSpeak, false);
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { mkdtempSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readConnectionHistory } from "../src/admin/admin-router.js";
|
||||
|
||||
test("admin log history groups a user's connection lifecycle", () => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-admin-log-history-"));
|
||||
const logFile = path.join(directory, "webspeak.log");
|
||||
const connectedAt = new Date(Date.now() - 8_000).toISOString();
|
||||
const disconnectedAt = new Date(Date.now() - 2_000).toISOString();
|
||||
const lines = [
|
||||
{ time: new Date(Date.now() - 9_000).toISOString(), msg: "WebClient connecting", entryId: "entry-a", nickname: "Alice", target: "voice.example.com:9987" },
|
||||
{ time: connectedAt, msg: "Web client connected to TeamSpeak", entryId: "entry-a", nickname: "Alice", target: "voice.example.com:9987" },
|
||||
{ time: disconnectedAt, msg: "Client session torn down", entryId: "entry-a", nickname: "Alice", target: "voice.example.com:9987", reason: "websocket-close", durationSeconds: 6 },
|
||||
{ time: new Date(Date.now() - 1_000).toISOString(), msg: "WebClient connecting", entryId: "entry-b", nickname: "Bob", target: "voice.example.com:9987" },
|
||||
{ time: new Date(Date.now() - 500).toISOString(), msg: "Web client connected to TeamSpeak", entryId: "entry-b", nickname: "Bob", target: "voice.example.com:9987" },
|
||||
{ time: new Date(Date.now() - 250).toISOString(), msg: "WebClient connecting", entryId: "entry-c", nickname: "Carol", target: "voice.example.com:9987" },
|
||||
{ time: new Date(Date.now() - 100).toISOString(), msg: "Client session torn down", entryId: "entry-c", nickname: "Carol", target: "voice.example.com:9987", reason: "teamSpeak-connect-failed", durationSeconds: 0 },
|
||||
].map((entry) => JSON.stringify(entry));
|
||||
writeFileSync(logFile, `${lines.join("\n")}\n`);
|
||||
|
||||
const history = readConnectionHistory(logFile, 10);
|
||||
assert.equal(history.length, 3);
|
||||
const alice = history.find((entry) => entry.id === "entry-a");
|
||||
const bob = history.find((entry) => entry.id === "entry-b");
|
||||
const carol = history.find((entry) => entry.id === "entry-c");
|
||||
assert.equal(alice?.status, "disconnected");
|
||||
assert.equal(alice?.durationSeconds, 6);
|
||||
assert.equal(alice?.disconnectedAt, disconnectedAt);
|
||||
assert.equal(bob?.status, "active");
|
||||
assert.equal(bob?.disconnectedAt, null);
|
||||
assert.ok((bob?.durationSeconds ?? 0) >= 0);
|
||||
assert.equal(carol?.status, "failed");
|
||||
assert.equal(carol?.durationSeconds, null);
|
||||
});
|
||||
@@ -122,7 +122,7 @@ test("managed invites are opaque, bounded, revocable, and included in database b
|
||||
assert.ok(backup.length > 100);
|
||||
database.close();
|
||||
const reopened = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
|
||||
assert.equal(reopened.schemaVersion, 3);
|
||||
assert.equal(reopened.schemaVersion, 4);
|
||||
assert.equal(reopened.listManagedInvites().length, 3);
|
||||
reopened.close();
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { collectTeamSpeakPings, pingTeamSpeakHost, pingTeamSpeakSession, summarizeTeamSpeakPings } from "../src/server/network-probe.js";
|
||||
|
||||
test("TeamSpeak latency probe uses the protocol command channel", async () => {
|
||||
let command = "";
|
||||
const result = await pingTeamSpeakSession(async (value) => {
|
||||
command = value;
|
||||
return [];
|
||||
});
|
||||
assert.equal(command, "version");
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.errorCode, undefined);
|
||||
assert.equal(typeof result.latencyMs, "number");
|
||||
});
|
||||
|
||||
test("TeamSpeak protocol probe classifies a timeout and aggregates packet loss", async () => {
|
||||
const timeout = await pingTeamSpeakSession(async () => {
|
||||
throw new Error("packet ack timeout");
|
||||
});
|
||||
assert.deepEqual(timeout, { ok: false, latencyMs: null, errorCode: "TIMEOUT" });
|
||||
|
||||
let calls = 0;
|
||||
const result = await collectTeamSpeakPings(async () => {
|
||||
calls += 1;
|
||||
return calls === 2
|
||||
? { ok: false, latencyMs: null, errorCode: "TIMEOUT" }
|
||||
: { ok: true, latencyMs: calls };
|
||||
}, { attempts: 4 });
|
||||
assert.equal(calls, 4);
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.packetLossPercent, 25);
|
||||
assert.equal(result.successfulAttempts, 3);
|
||||
assert.deepEqual(result.samples, [1, 3, 4]);
|
||||
});
|
||||
|
||||
test("TeamSpeak ping summary reports complete loss without fake latency", () => {
|
||||
const result = summarizeTeamSpeakPings([
|
||||
{ ok: false, latencyMs: null, errorCode: "UNREACHABLE" },
|
||||
{ ok: false, latencyMs: null, errorCode: "UNREACHABLE" },
|
||||
]);
|
||||
assert.deepEqual(result, {
|
||||
ok: false,
|
||||
latencyMs: null,
|
||||
packetLossPercent: 100,
|
||||
attempts: 2,
|
||||
successfulAttempts: 0,
|
||||
samples: [],
|
||||
errorCode: "UNREACHABLE",
|
||||
});
|
||||
});
|
||||
|
||||
test("admin host ping measures the route without opening a TeamSpeak client", async () => {
|
||||
const calls: Array<[string, number]> = [];
|
||||
let attempt = 0;
|
||||
const result = await pingTeamSpeakHost("203.0.113.10", {
|
||||
attempts: 4,
|
||||
timeoutMs: 900,
|
||||
execute: async (host, timeoutMs) => {
|
||||
calls.push([host, timeoutMs]);
|
||||
attempt += 1;
|
||||
if (attempt === 3) throw new Error("ping timeout");
|
||||
return attempt * 2;
|
||||
},
|
||||
});
|
||||
assert.deepEqual(calls, [
|
||||
["203.0.113.10", 900],
|
||||
["203.0.113.10", 900],
|
||||
["203.0.113.10", 900],
|
||||
["203.0.113.10", 900],
|
||||
]);
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.packetLossPercent, 25);
|
||||
assert.equal(result.latencyMs, 4);
|
||||
});
|
||||
|
||||
test("admin host ping reports a missing runtime ping tool separately from packet loss", async () => {
|
||||
const result = await pingTeamSpeakHost("203.0.113.20", {
|
||||
attempts: 1,
|
||||
execute: async () => { throw new Error("spawn ping ENOENT"); },
|
||||
});
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.errorCode, "PING_UNAVAILABLE");
|
||||
});
|
||||
@@ -19,6 +19,7 @@ test("SQLite persistence initializes schema and stores the single admin/settings
|
||||
database.initializeAdmin(credential, {
|
||||
siteName: "Private Voice",
|
||||
welcomeText: "Welcome",
|
||||
welcomeTextEn: "",
|
||||
accessMode: "open",
|
||||
tsHost: "voice.example.com",
|
||||
tsPort: 9988,
|
||||
@@ -32,6 +33,7 @@ test("SQLite persistence initializes schema and stores the single admin/settings
|
||||
assert.deepEqual(database.getSettings(), {
|
||||
siteName: "Private Voice",
|
||||
welcomeText: "Welcome",
|
||||
welcomeTextEn: "",
|
||||
accessMode: "open",
|
||||
tsHost: "voice.example.com",
|
||||
tsPort: 9988,
|
||||
@@ -54,7 +56,7 @@ test("SQLite persistence initializes schema and stores the single admin/settings
|
||||
reopened.close();
|
||||
});
|
||||
|
||||
test("SQLite schema v1 upgrades to v3 with a migration copy", () => {
|
||||
test("SQLite schema v1 upgrades to v4 with a migration copy", () => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-db-migration-"));
|
||||
const dbPath = path.join(directory, "webspeak.db");
|
||||
const legacy = new DatabaseSync(dbPath);
|
||||
@@ -74,10 +76,11 @@ test("SQLite schema v1 upgrades to v3 with a migration copy", () => {
|
||||
legacy.close();
|
||||
|
||||
const upgraded = new WebSpeakDatabase(dbPath);
|
||||
assert.equal(upgraded.schemaVersion, 3);
|
||||
assert.equal(upgraded.schemaVersion, 4);
|
||||
assert.equal(upgraded.getSettings().webRtcEnabled, false);
|
||||
assert.equal(upgraded.getSettings().webRtcUdpStart, 40000);
|
||||
assert.equal(upgraded.getSettings().webRtcUdpEnd, 40099);
|
||||
assert.equal(upgraded.getSettings().welcomeTextEn, "");
|
||||
assert.equal(upgraded.listManagedInvites().length, 0);
|
||||
assert.equal(existsSync(`${dbPath}.schema-1.bak`), true);
|
||||
upgraded.close();
|
||||
|
||||
|
After Width: | Height: | Size: 114 KiB |
@@ -80,6 +80,16 @@
|
||||
<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 === '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" />
|
||||
<ellipse cx="12" cy="14.8" rx="4.1" ry="5.55" fill="#fff" stroke="none" />
|
||||
<circle cx="9.45" cy="9.55" r="1.35" fill="#fff" stroke="none" />
|
||||
<circle cx="14.55" cy="9.55" r="1.35" fill="#fff" stroke="none" />
|
||||
<circle cx="9.45" cy="9.55" r=".52" fill="#202a2a" stroke="none" />
|
||||
<circle cx="14.55" cy="9.55" r=".52" fill="#202a2a" stroke="none" />
|
||||
<path d="m10 11.15 2-1.05 2 1.05-2 1.45z" fill="#f2a53d" stroke="none" />
|
||||
<path d="m5.8 18.55-2.1 2.1 3.75-.45m10.75-1.65 2.1 2.1-3.75-.45" fill="#f2a53d" stroke="#f2a53d" stroke-width="1.5" />
|
||||
</template>
|
||||
<path v-else-if="name === 'check'" d="m5 12 4 4L19 6" />
|
||||
<circle v-else cx="12" cy="12" r="8" />
|
||||
</svg>
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
<template>
|
||||
<div ref="root" class="language-switcher" :class="{ open }" @keydown.esc="close">
|
||||
<button
|
||||
type="button"
|
||||
class="language-trigger"
|
||||
:aria-label="menuLabel"
|
||||
aria-haspopup="listbox"
|
||||
:aria-expanded="open"
|
||||
:aria-controls="menuId"
|
||||
@click.stop="toggle"
|
||||
>
|
||||
<span class="language-current-flag" aria-hidden="true">{{ currentLanguage.flag }}</span>
|
||||
<span class="language-current-code">{{ currentLanguage.code }}</span>
|
||||
<Icon name="chevron-down" :size="13" />
|
||||
</button>
|
||||
|
||||
<div v-if="open" :id="menuId" class="language-dropdown" role="listbox" :aria-label="menuLabel" @click.stop>
|
||||
<button
|
||||
v-for="option in options"
|
||||
:key="option.value"
|
||||
type="button"
|
||||
class="language-option"
|
||||
:class="{ selected: modelValue === option.value }"
|
||||
role="option"
|
||||
:aria-selected="modelValue === option.value"
|
||||
@pointerdown.stop.prevent="select(option.value)"
|
||||
@keydown.enter.prevent="select(option.value)"
|
||||
@keydown.space.prevent="select(option.value)"
|
||||
>
|
||||
<span class="language-option-flag" aria-hidden="true">{{ option.flag }}</span>
|
||||
<span class="language-option-copy">
|
||||
<strong>{{ option.label }}</strong>
|
||||
<small>{{ option.code }}</small>
|
||||
</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";
|
||||
|
||||
type Language = "zh" | "en" | "de";
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue: Language;
|
||||
menuLabel?: string;
|
||||
}>(), {
|
||||
menuLabel: "Language",
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [value: Language];
|
||||
change: [value: Language];
|
||||
}>();
|
||||
|
||||
const options: Array<{ value: Language; code: string; label: string; flag: string }> = [
|
||||
{ value: "zh", code: "ZH", label: "中文", flag: "🇨🇳" },
|
||||
{ value: "en", code: "EN", label: "English", flag: "🇬🇧" },
|
||||
{ value: "de", code: "DE", label: "Deutsch", flag: "🇩🇪" },
|
||||
];
|
||||
|
||||
const root = ref<HTMLElement | null>(null);
|
||||
const open = ref(false);
|
||||
const menuId = `language-menu-${Math.random().toString(36).slice(2, 9)}`;
|
||||
const currentLanguage = computed(() => options.find((option) => option.value === props.modelValue) ?? options[0]);
|
||||
|
||||
function toggle() {
|
||||
open.value = !open.value;
|
||||
}
|
||||
|
||||
function close() {
|
||||
open.value = false;
|
||||
}
|
||||
|
||||
function select(value: Language) {
|
||||
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>
|
||||
.language-switcher {
|
||||
position: relative;
|
||||
z-index: 20;
|
||||
flex: 0 0 auto;
|
||||
color: #006a64;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.language-trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 70px;
|
||||
min-height: 32px;
|
||||
padding: 0 9px;
|
||||
color: #006a64;
|
||||
background: #e2f2ef;
|
||||
border: 1px solid #c8e6e1;
|
||||
border-radius: 8px;
|
||||
font: inherit;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
cursor: pointer;
|
||||
transition: color .16s, background .16s, border-color .16s, box-shadow .16s;
|
||||
}
|
||||
|
||||
.language-trigger:hover,
|
||||
.language-switcher.open .language-trigger {
|
||||
color: #fff;
|
||||
background: #006a64;
|
||||
border-color: #006a64;
|
||||
box-shadow: 0 7px 16px rgba(0, 106, 100, .16);
|
||||
}
|
||||
|
||||
.language-trigger .ui-icon {
|
||||
margin-left: auto;
|
||||
transition: transform .16s;
|
||||
}
|
||||
|
||||
.language-switcher.open .language-trigger .ui-icon {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
|
||||
.language-current-flag,
|
||||
.language-option-flag {
|
||||
font-family: "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.language-current-flag {
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.language-current-code {
|
||||
letter-spacing: .02em;
|
||||
}
|
||||
|
||||
.language-dropdown {
|
||||
position: absolute;
|
||||
top: calc(100% + 8px);
|
||||
right: 0;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
grid-auto-rows: minmax(38px, max-content);
|
||||
align-items: start;
|
||||
align-content: start;
|
||||
gap: 3px;
|
||||
width: min(360px, calc(100vw - 16px));
|
||||
height: auto;
|
||||
max-height: none;
|
||||
padding: 7px;
|
||||
overflow: visible;
|
||||
background: #fff;
|
||||
border: 1px solid #dce9e5;
|
||||
border-radius: 13px;
|
||||
box-shadow: 0 16px 36px rgba(23, 60, 54, .18), 0 3px 8px rgba(23, 60, 54, .06);
|
||||
animation: language-menu-in .14s ease-out;
|
||||
}
|
||||
|
||||
.language-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
align-self: start;
|
||||
min-width: 0;
|
||||
gap: 8px;
|
||||
min-height: 38px;
|
||||
padding: 6px 8px;
|
||||
color: #344540;
|
||||
background: transparent;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 8px;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
transition: color .14s, background .14s, border-color .14s;
|
||||
}
|
||||
|
||||
.language-option:hover,
|
||||
.language-option:focus-visible,
|
||||
.language-option.selected {
|
||||
color: #006a64;
|
||||
background: #edf8f5;
|
||||
border-color: #d4eee8;
|
||||
}
|
||||
|
||||
.language-option-flag {
|
||||
flex: 0 0 auto;
|
||||
font-size: 17px;
|
||||
}
|
||||
|
||||
.language-option-copy {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.language-option strong,
|
||||
.language-option small {
|
||||
overflow: visible;
|
||||
text-overflow: clip;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.language-option strong {
|
||||
flex: 0 0 auto;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.language-option small {
|
||||
flex: 0 0 auto;
|
||||
color: #91a19c;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.language-option > .ui-icon {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
@keyframes language-menu-in {
|
||||
from { opacity: 0; transform: translateY(-4px) scale(.98); }
|
||||
to { opacity: 1; transform: translateY(0) scale(1); }
|
||||
}
|
||||
|
||||
:global(html[data-theme="dark"]) .language-trigger,
|
||||
:global(:root[data-theme="dark"]) .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 {
|
||||
color: #10201d;
|
||||
background: #69d2c7;
|
||||
border-color: #69d2c7;
|
||||
}
|
||||
|
||||
:global(html[data-theme="dark"]) .language-dropdown,
|
||||
:global(:root[data-theme="dark"]) .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 {
|
||||
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 {
|
||||
color: #69d2c7;
|
||||
background: #203531;
|
||||
border-color: #38564f;
|
||||
}
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.language-trigger {
|
||||
min-width: 62px;
|
||||
min-height: 30px;
|
||||
padding-inline: 7px;
|
||||
}
|
||||
|
||||
.language-dropdown {
|
||||
width: min(360px, calc(100vw - 16px));
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -12,6 +12,7 @@ export interface VoiceState {
|
||||
tsClientId: number;
|
||||
error: string;
|
||||
errorCode: string;
|
||||
channelSwitchedChannelId: string;
|
||||
}
|
||||
|
||||
export interface ChannelMember {
|
||||
@@ -76,9 +77,16 @@ export interface ServerEvent {
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface LatencyProbeResult {
|
||||
browserRttMs: number;
|
||||
teamSpeakLatencyMs: number | null;
|
||||
teamSpeakReachable: boolean;
|
||||
teamSpeakErrorCode?: string;
|
||||
}
|
||||
|
||||
export function useVoiceWebSocket() {
|
||||
const ws = ref<WebSocket | null>(null);
|
||||
const state = reactive<VoiceState>({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "", errorCode: "" });
|
||||
const state = reactive<VoiceState>({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "", errorCode: "", channelSwitchedChannelId: "" });
|
||||
const members = reactive<ChannelMember[]>([]);
|
||||
const channels = reactive<ChannelInfo[]>([]);
|
||||
const chatMessages = reactive<ChatMessage[]>([]);
|
||||
@@ -86,6 +94,8 @@ export function useVoiceWebSocket() {
|
||||
const pokeNotifications = reactive<{ id: string; invokerId: number; invokerUid: string; invokerName: string; message: string; timestamp: number }[]>([]);
|
||||
let connectionSequence = 0;
|
||||
let lastConnection: { target: string; channel: string; nickname: string; serverPassword: string; identity?: string; rememberIdentity: boolean } | null = null;
|
||||
let latencyProbeSequence = 0;
|
||||
const pendingLatencyProbes = new Map<string, { startedAt: number; resolve: (result: LatencyProbeResult | null) => void; timer: ReturnType<typeof setTimeout> }>();
|
||||
let webrtcPeer: RTCPeerConnection | null = null;
|
||||
let webrtcOutputElement: SinkAudioElement | null = null;
|
||||
let webrtcPlaybackStream: MediaStream | null = null;
|
||||
@@ -117,7 +127,6 @@ export function useVoiceWebSocket() {
|
||||
let webrtcMixMicSource: MediaStreamAudioSourceNode | null = null;
|
||||
let webrtcMixMicGain: GainNode | null = null;
|
||||
let webrtcMixAccompanimentSource: MediaStreamAudioSourceNode | null = null;
|
||||
let webrtcMixAccompanimentGain: GainNode | null = null;
|
||||
let webrtcMicMonitorSource: MediaStreamAudioSourceNode | null = null;
|
||||
let webrtcMicMonitorAnalyser: AnalyserNode | null = null;
|
||||
let webrtcMicMonitorGain: GainNode | null = null;
|
||||
@@ -137,6 +146,7 @@ export function useVoiceWebSocket() {
|
||||
const microphoneMuted = ref(false);
|
||||
const inputVolume = ref(1);
|
||||
const outputVolume = ref(1);
|
||||
const outputMuted = ref(false);
|
||||
const notificationVolume = ref(0.5);
|
||||
const voxThreshold = ref(0.008);
|
||||
let voxAttack = 0;
|
||||
@@ -232,6 +242,16 @@ export function useVoiceWebSocket() {
|
||||
speakingIds.clear();
|
||||
}
|
||||
|
||||
function effectiveOutputVolume(): number {
|
||||
return outputMuted.value ? 0 : outputVolume.value;
|
||||
}
|
||||
|
||||
function applyOutputVolume(): void {
|
||||
const level = effectiveOutputVolume();
|
||||
for (const [clientId, gain] of remoteGains) gain.gain.value = (volumes[clientId] ?? 1) * level;
|
||||
if (webrtcOutputElement) webrtcOutputElement.volume = level;
|
||||
}
|
||||
|
||||
function getAudioCtx(): SinkAudioContext {
|
||||
if (!audioCtx) {
|
||||
audioCtx = new AudioContext({ sampleRate: 48000 }) as SinkAudioContext;
|
||||
@@ -486,12 +506,10 @@ export function useVoiceWebSocket() {
|
||||
|
||||
function stopWebRtcMix(): void {
|
||||
webrtcMixAccompanimentSource?.disconnect();
|
||||
webrtcMixAccompanimentGain?.disconnect();
|
||||
webrtcMixMicSource?.disconnect();
|
||||
webrtcMixMicGain?.disconnect();
|
||||
webrtcMixDestination?.disconnect();
|
||||
webrtcMixAccompanimentSource = null;
|
||||
webrtcMixAccompanimentGain = null;
|
||||
webrtcMixMicSource = null;
|
||||
webrtcMixMicGain = null;
|
||||
webrtcMixDestination = null;
|
||||
@@ -523,12 +541,11 @@ export function useVoiceWebSocket() {
|
||||
const accompanimentTrack = accompanimentStream?.getAudioTracks()[0];
|
||||
if (accompanimentTrack) {
|
||||
const accompanimentSource = ctx.createMediaStreamSource(accompanimentStream!);
|
||||
const accompanimentGain = ctx.createGain();
|
||||
accompanimentGain.gain.value = 0.78;
|
||||
accompanimentSource.connect(accompanimentGain);
|
||||
accompanimentGain.connect(destination);
|
||||
// Keep the captured application audio at its source level. Do not add
|
||||
// a fixed attenuation/gain node: it makes music sound quieter than the
|
||||
// source and encourages later "compensation" steps to pump its volume.
|
||||
accompanimentSource.connect(destination);
|
||||
webrtcMixAccompanimentSource = accompanimentSource;
|
||||
webrtcMixAccompanimentGain = accompanimentGain;
|
||||
}
|
||||
return destination.stream;
|
||||
}
|
||||
@@ -554,7 +571,16 @@ export function useVoiceWebSocket() {
|
||||
throw new Error("伴奏功能需要启用 WebRTC");
|
||||
}
|
||||
|
||||
const audioConstraints = {} as MediaTrackConstraints & { restrictOwnAudio?: boolean };
|
||||
const captureProcessingConstraints: MediaTrackConstraints = {
|
||||
// Display/application audio must not pass through browser voice
|
||||
// processing. Those processors are designed for speech and can change
|
||||
// music level from frame to frame (AGC), suppress quiet passages, or
|
||||
// cancel sustained tones.
|
||||
autoGainControl: false,
|
||||
echoCancellation: false,
|
||||
noiseSuppression: false,
|
||||
};
|
||||
const audioConstraints = { ...captureProcessingConstraints } as MediaTrackConstraints & { restrictOwnAudio?: boolean };
|
||||
const supportedConstraints = navigator.mediaDevices.getSupportedConstraints?.() as Record<string, boolean> | undefined;
|
||||
if (supportedConstraints?.restrictOwnAudio) audioConstraints.restrictOwnAudio = true;
|
||||
const options = {
|
||||
@@ -581,6 +607,18 @@ export function useVoiceWebSocket() {
|
||||
throw new Error("所选来源没有可共享音频");
|
||||
}
|
||||
|
||||
try {
|
||||
// Do not pass the Chromium-only restrictOwnAudio hint to
|
||||
// applyConstraints: rejecting an unknown key could otherwise cause the
|
||||
// browser to discard all three standard processing-off constraints.
|
||||
await audioTrack.applyConstraints(captureProcessingConstraints);
|
||||
} catch {
|
||||
// Some browsers expose display audio but reject one or more optional
|
||||
// processing constraints. The capture can still proceed without
|
||||
// introducing a WebSpeak-side gain stage.
|
||||
}
|
||||
if ("contentHint" in audioTrack) audioTrack.contentHint = "music";
|
||||
|
||||
accompanimentStream?.getTracks().forEach((track) => track.stop());
|
||||
accompanimentStream = nextStream;
|
||||
accompanimentActive.value = true;
|
||||
@@ -633,7 +671,7 @@ export function useVoiceWebSocket() {
|
||||
output.autoplay = true;
|
||||
output.muted = false;
|
||||
output.setAttribute("playsinline", "");
|
||||
output.volume = outputVolume.value;
|
||||
output.volume = effectiveOutputVolume();
|
||||
output.setAttribute("aria-hidden", "true");
|
||||
output.tabIndex = -1;
|
||||
output.style.position = "fixed";
|
||||
@@ -911,7 +949,7 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
function playNotification(kind: "connected" | "disconnected" | "poke" | "private" | "reconnectFailed"): void {
|
||||
if (notificationVolume.value <= 0 || typeof window === "undefined") return;
|
||||
if (notificationVolume.value <= 0 || outputMuted.value || effectiveOutputVolume() <= 0 || typeof window === "undefined") return;
|
||||
try {
|
||||
const ctx = getAudioCtx();
|
||||
if (ctx.state === "suspended") return;
|
||||
@@ -928,7 +966,7 @@ export function useVoiceWebSocket() {
|
||||
oscillator.frequency.setValueAtTime(frequencies[kind][0], now);
|
||||
oscillator.frequency.setValueAtTime(frequencies[kind][1], now + 0.08);
|
||||
gain.gain.setValueAtTime(0.0001, now);
|
||||
gain.gain.exponentialRampToValueAtTime(Math.max(0.0001, notificationVolume.value * 0.12), now + 0.01);
|
||||
gain.gain.exponentialRampToValueAtTime(Math.max(0.0001, notificationVolume.value * effectiveOutputVolume() * 0.12), now + 0.01);
|
||||
gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.18);
|
||||
oscillator.connect(gain);
|
||||
gain.connect(ctx.destination);
|
||||
@@ -956,7 +994,7 @@ export function useVoiceWebSocket() {
|
||||
|
||||
if (!decoder) {
|
||||
const gainNode = ctx.createGain();
|
||||
gainNode.gain.value = (volumes[clientId] ?? 1) * outputVolume.value;
|
||||
gainNode.gain.value = (volumes[clientId] ?? 1) * effectiveOutputVolume();
|
||||
gainNode.connect(ctx.destination);
|
||||
remoteGains.set(clientId, gainNode);
|
||||
const generation = ++nextRemoteDecoderGeneration;
|
||||
@@ -1108,6 +1146,7 @@ export function useVoiceWebSocket() {
|
||||
};
|
||||
socket.onclose = (event) => {
|
||||
if (sequence !== connectionSequence) return;
|
||||
clearLatencyProbes();
|
||||
state.connected = false;
|
||||
state.connecting = false;
|
||||
state.reconnecting = false;
|
||||
@@ -1144,6 +1183,7 @@ export function useVoiceWebSocket() {
|
||||
|
||||
function disconnect(preserveConnection = false): void {
|
||||
connectionSequence++;
|
||||
clearLatencyProbes();
|
||||
const keepRememberedIdentity = lastConnection?.rememberIdentity === true;
|
||||
if (!preserveConnection) lastConnection = null;
|
||||
stopMicrophone();
|
||||
@@ -1158,6 +1198,7 @@ export function useVoiceWebSocket() {
|
||||
state.reconnectFailed = false;
|
||||
state.tsClientId = 0;
|
||||
state.errorCode = "";
|
||||
state.channelSwitchedChannelId = "";
|
||||
if (!keepRememberedIdentity) identityMaterial.value = "";
|
||||
members.length = 0;
|
||||
channels.length = 0;
|
||||
@@ -1174,6 +1215,14 @@ export function useVoiceWebSocket() {
|
||||
for (const key of Object.keys(volumes)) delete volumes[Number(key)];
|
||||
}
|
||||
|
||||
function clearLatencyProbes(): void {
|
||||
for (const [sequence, pending] of pendingLatencyProbes) {
|
||||
clearTimeout(pending.timer);
|
||||
pendingLatencyProbes.delete(sequence);
|
||||
pending.resolve(null);
|
||||
}
|
||||
}
|
||||
|
||||
function handleMessage(msg: any): void {
|
||||
switch (msg.type) {
|
||||
case "connected":
|
||||
@@ -1185,6 +1234,7 @@ export function useVoiceWebSocket() {
|
||||
state.reconnectFailed = false;
|
||||
state.error = "";
|
||||
state.errorCode = "";
|
||||
state.channelSwitchedChannelId = "";
|
||||
state.tsClientId = Number(msg.tsClientId) || 0;
|
||||
applyWhisperState(msg.whisperTargetIds, msg.whisperActive);
|
||||
if (Array.isArray(msg.members)) {
|
||||
@@ -1271,7 +1321,24 @@ export function useVoiceWebSocket() {
|
||||
});
|
||||
break;
|
||||
case "channelSwitched":
|
||||
state.channelSwitchedChannelId = typeof msg.channelId === "string" || typeof msg.channelId === "number" ? String(msg.channelId) : "";
|
||||
state.error = "";
|
||||
state.errorCode = "";
|
||||
break;
|
||||
case "latencyPong": {
|
||||
const sequence = typeof msg.sequence === "string" ? msg.sequence : "";
|
||||
const pending = pendingLatencyProbes.get(sequence);
|
||||
if (!pending) break;
|
||||
pendingLatencyProbes.delete(sequence);
|
||||
clearTimeout(pending.timer);
|
||||
pending.resolve({
|
||||
browserRttMs: Math.max(0, Math.round(performance.now() - pending.startedAt)),
|
||||
teamSpeakLatencyMs: typeof msg.teamSpeakLatencyMs === "number" ? msg.teamSpeakLatencyMs : null,
|
||||
teamSpeakReachable: msg.teamSpeakReachable === true,
|
||||
...(typeof msg.teamSpeakErrorCode === "string" ? { teamSpeakErrorCode: msg.teamSpeakErrorCode } : {}),
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "disconnected":
|
||||
state.connected = false;
|
||||
state.connecting = false;
|
||||
@@ -1349,9 +1416,24 @@ export function useVoiceWebSocket() {
|
||||
function switchChannel(channelId: string, password = ""): void {
|
||||
state.error = "";
|
||||
state.errorCode = "";
|
||||
state.channelSwitchedChannelId = "";
|
||||
sendCmd("switchChannel", { channelId, ...(password ? { password } : {}) });
|
||||
}
|
||||
|
||||
function measureLatency(timeoutMs = 2_200): Promise<LatencyProbeResult | null> {
|
||||
const socket = ws.value;
|
||||
if (!socket || socket.readyState !== WebSocket.OPEN) return Promise.resolve(null);
|
||||
const sequence = `latency-${Date.now().toString(36)}-${(latencyProbeSequence++).toString(36)}`;
|
||||
return new Promise((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
pendingLatencyProbes.delete(sequence);
|
||||
resolve(null);
|
||||
}, timeoutMs);
|
||||
pendingLatencyProbes.set(sequence, { startedAt: performance.now(), resolve, timer });
|
||||
sendCmd("latencyProbe", { sequence });
|
||||
});
|
||||
}
|
||||
|
||||
function sendTextMessage(message: string, targetId = ""): void {
|
||||
const trimmed = message.trim();
|
||||
if (!trimmed || trimmed.length > 500) return;
|
||||
@@ -1474,7 +1556,7 @@ export function useVoiceWebSocket() {
|
||||
void saveAudioPreferences();
|
||||
}
|
||||
const gain = remoteGains.get(clientId);
|
||||
if (gain) gain.gain.value = normalized * outputVolume.value;
|
||||
if (gain) gain.gain.value = normalized * effectiveOutputVolume();
|
||||
if (webrtcPeer || webrtcActive.value) sendCmd("setMemberVolume", { clientId, volume: normalized });
|
||||
}
|
||||
|
||||
@@ -1496,11 +1578,15 @@ export function useVoiceWebSocket() {
|
||||
|
||||
function setOutputVolume(volume: number): void {
|
||||
outputVolume.value = Math.max(0, Math.min(1, volume));
|
||||
for (const [clientId, gain] of remoteGains) gain.gain.value = (volumes[clientId] ?? 1) * outputVolume.value;
|
||||
if (webrtcOutputElement) webrtcOutputElement.volume = outputVolume.value;
|
||||
applyOutputVolume();
|
||||
void saveAudioPreferences();
|
||||
}
|
||||
|
||||
function toggleOutputMute(): void {
|
||||
outputMuted.value = !outputMuted.value;
|
||||
applyOutputVolume();
|
||||
}
|
||||
|
||||
function setVoxThreshold(threshold: number): void {
|
||||
voxThreshold.value = clamp(threshold, 0.001, 0.08);
|
||||
void saveAudioPreferences();
|
||||
@@ -1522,6 +1608,7 @@ export function useVoiceWebSocket() {
|
||||
microphoneMuted,
|
||||
inputVolume,
|
||||
outputVolume,
|
||||
outputMuted,
|
||||
notificationVolume,
|
||||
voxThreshold,
|
||||
inputDevices,
|
||||
@@ -1545,6 +1632,7 @@ export function useVoiceWebSocket() {
|
||||
setVolume,
|
||||
setInputVolume,
|
||||
setOutputVolume,
|
||||
toggleOutputMute,
|
||||
setVoxThreshold,
|
||||
setNotificationVolume,
|
||||
prepareInputDevices,
|
||||
@@ -1570,5 +1658,6 @@ export function useVoiceWebSocket() {
|
||||
stopAccompaniment,
|
||||
checkSupport,
|
||||
clearError,
|
||||
measureLatency,
|
||||
};
|
||||
}
|
||||
@@ -35,7 +35,7 @@ export interface LocalPreferences {
|
||||
theme?: "system" | "light" | "dark";
|
||||
microphoneMuted?: boolean;
|
||||
voxThreshold?: number;
|
||||
language?: "zh" | "en";
|
||||
language?: "zh" | "en" | "de";
|
||||
preferredInputDeviceId?: string;
|
||||
preferredOutputDeviceId?: string;
|
||||
inputGain?: number;
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<div class="admin-brand centered"><span><Icon name="waveform" :size="24" /></span><div><strong>WebSpeak</strong><small>{{ tr('adminConsole') }}</small></div></div>
|
||||
<header><h1>{{ tr('changePasswordTitle') }}</h1><p>{{ tr('changePasswordLead') }}</p></header>
|
||||
<form @submit.prevent="changePassword"><div v-if="errorMessage" class="alert error">{{ errorMessage }}</div><label><span>{{ tr('newPassword') }}</span><input v-model="newPassword" type="password" autocomplete="new-password" maxlength="1024" autofocus :placeholder="tr('passwordPlaceholder')" /></label><label><span>{{ tr('confirmPassword') }}</span><input v-model="confirmNewPassword" type="password" autocomplete="new-password" maxlength="1024" /></label><div class="strength"><i :style="{ width: `${passwordStrength}%` }"></i></div><button class="primary-button wide" :disabled="submitting" type="submit"><span v-if="submitting" class="spinner small"></span>{{ tr('savePassword') }}</button></form>
|
||||
<p class="security-note">{{ tr('defaultCredentialNotice') }}</p><button class="language-link" type="button" @click="toggleLanguage">{{ tr('languageSwitch') }}</button>
|
||||
<p class="security-note">{{ tr('defaultCredentialNotice') }}</p><LanguageSwitcher v-model="language" class="language-link" :menu-label="tr('languageMenu')" @change="persistLanguage" />
|
||||
</section>
|
||||
</main>
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
<div class="admin-brand centered"><span><Icon name="waveform" :size="24" /></span><div><strong>WebSpeak</strong><small>{{ tr('adminConsole') }}</small></div></div>
|
||||
<header><h1>{{ tr('welcomeAdmin') }}</h1><p>{{ tr('loginLead') }}</p></header>
|
||||
<form @submit.prevent="login"><div v-if="errorMessage" class="alert error">{{ errorMessage }}</div><label><span>{{ tr('adminUsername') }}</span><input v-model.trim="loginUsername" autocomplete="username" autofocus /></label><label><span>{{ tr('adminPassword') }}</span><input v-model="loginPassword" type="password" autocomplete="current-password" /></label><button class="primary-button wide" :disabled="submitting" type="submit"><span v-if="submitting" class="spinner small"></span>{{ tr('login') }}</button></form>
|
||||
<div class="login-actions"><RouterLink to="/" class="home-link"><Icon name="home" :size="15" />{{ tr('backHome') }}</RouterLink><button class="language-link" type="button" @click="toggleLanguage">{{ tr('languageSwitch') }}</button></div>
|
||||
<div class="login-actions"><RouterLink to="/" class="home-link"><Icon name="home" :size="15" />{{ tr('backHome') }}</RouterLink><LanguageSwitcher v-model="language" class="language-link" :menu-label="tr('languageMenu')" @change="persistLanguage" /></div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
@@ -28,14 +28,14 @@
|
||||
</aside>
|
||||
|
||||
<main class="admin-main">
|
||||
<header class="admin-topbar"><div><small>{{ tr('adminConsole') }}</small><h1>{{ currentPageTitle }}</h1></div><div><span class="running-dot"></span>{{ tr('gatewayRunning') }}<button type="button" class="theme-toggle" :title="themeLabel" :aria-label="themeLabel" @click="cycleTheme"><Icon :name="themeIcon" :size="17" /><span>{{ themeLabel }}</span></button><button type="button" @click="toggleLanguage">{{ tr('languageSwitch') }}</button></div></header>
|
||||
<header class="admin-topbar"><div><small>{{ tr('adminConsole') }}</small><h1>{{ currentPageTitle }}</h1></div><div><span class="running-dot"></span>{{ tr('gatewayRunning') }}<button type="button" class="theme-toggle" :title="themeLabel" :aria-label="themeLabel" @click="cycleTheme"><Icon :name="themeIcon" :size="17" /><span>{{ themeLabel }}</span></button><LanguageSwitcher v-model="language" :menu-label="tr('languageMenu')" @change="persistLanguage" /></div></header>
|
||||
|
||||
<div v-if="errorMessage" class="alert error page-alert">{{ errorMessage }}</div>
|
||||
<section v-if="route.path === '/admin/server'" class="page-content server-page">
|
||||
<div class="page-heading"><div><h2>{{ tr('serverSettings') }}</h2><p>{{ tr('serverSettingsLead') }}</p></div><button class="primary-button" :disabled="submitting" @click="saveServerSettings">{{ submitting ? tr('saving') : tr('saveChanges') }}</button></div>
|
||||
<div class="settings-grid">
|
||||
<article class="settings-card"><h3>{{ tr('teamSpeakTarget') }}</h3><div class="target-fields"><label><span>{{ tr('serverAddress') }}</span><input v-model.trim="serverForm.address" :placeholder="tr('serverPlaceholder')" /></label><label><span>{{ tr('serverPort') }}</span><input v-model.trim="serverForm.port" inputmode="numeric" type="text" maxlength="5" :placeholder="tr('serverPortPlaceholder')" /></label></div><div class="password-row"><label><span>{{ tr('serverPassword') }}</span><input v-model="serverForm.serverPassword" type="password" autocomplete="off" :disabled="serverForm.passwordAction !== 'replace'" :placeholder="serverForm.hasPassword ? tr('passwordConfigured') : tr('optionalPassword')" /></label><div class="password-actions"><button type="button" :class="{ active: serverForm.passwordAction === 'replace' }" @click="serverForm.passwordAction = 'replace'">{{ tr('change') }}</button><button v-if="serverForm.hasPassword" type="button" :class="{ danger: serverForm.passwordAction === 'remove' }" @click="serverForm.passwordAction = 'remove'">{{ tr('remove') }}</button></div></div><button class="secondary-button" type="button" :disabled="testing" @click="testServerConnection"><span v-if="testing" class="spinner small"></span><Icon v-else name="activity" :size="17" />{{ testing ? tr('testing') : tr('testConnection') }}</button><div v-if="testResult" :class="['test-result', testResult.ok ? 'success' : 'error']"><Icon :name="testResult.ok ? 'check' : 'close'" :size="18" /><div><strong>{{ testResult.ok ? tr('connectionReady') : tr('connectionFailed') }}</strong><small>{{ testResultText }}</small></div></div></article>
|
||||
<article class="settings-card"><h3>{{ tr('accessAndIdentity') }}</h3><fieldset><legend>{{ tr('accessMode') }}</legend><label class="choice"><input v-model="serverForm.accessMode" type="radio" value="fixed" /><span><strong>{{ tr('fixedMode') }}</strong><small>{{ tr('fixedModeLead') }}</small></span></label><label class="choice"><input v-model="serverForm.accessMode" type="radio" value="open" /><span><strong>{{ tr('openMode') }}</strong><small>{{ tr('openModeLead') }}</small></span></label></fieldset><label><span>{{ tr('siteName') }}</span><input v-model.trim="serverForm.siteName" maxlength="80" /></label><label><span>{{ tr('welcomeText') }}</span><textarea v-model="serverForm.welcomeText" maxlength="500" rows="4"></textarea></label></article>
|
||||
<article class="settings-card"><h3>{{ tr('accessAndIdentity') }}</h3><fieldset><legend>{{ tr('accessMode') }}</legend><label class="choice"><input v-model="serverForm.accessMode" type="radio" value="fixed" /><span><strong>{{ tr('fixedMode') }}</strong><small>{{ tr('fixedModeLead') }}</small></span></label><label class="choice"><input v-model="serverForm.accessMode" type="radio" value="open" /><span><strong>{{ tr('openMode') }}</strong><small>{{ tr('openModeLead') }}</small></span></label></fieldset><label><span>{{ tr('siteName') }}</span><input v-model.trim="serverForm.siteName" maxlength="80" /></label><label><span>{{ tr('welcomeTextZh') }}</span><textarea v-model="serverForm.welcomeText" maxlength="500" rows="3"></textarea></label><label><span>{{ tr('welcomeTextEn') }}</span><textarea v-model="serverForm.welcomeTextEn" maxlength="500" rows="3"></textarea></label></article>
|
||||
<article class="settings-card advanced-card"><div><h3>{{ tr('advancedSettings') }}</h3><p class="card-help">{{ tr('advancedSettingsLead') }}</p></div><label class="choice toggle-choice"><input v-model="serverForm.webRtcEnabled" type="checkbox" @change="handleWebRtcToggle" /><span><strong>{{ tr('webrtcEnabled') }}</strong><small>{{ tr('webrtcEnabledLead') }}</small></span></label><div class="webrtc-port-fields"><div class="port-fields-heading"><strong>{{ tr('webrtcPortRange') }}</strong><small>{{ tr('webrtcPortRangeLead') }}</small></div><div class="port-inputs"><label><span>{{ tr('webrtcPortStart') }}</span><input v-model.number="serverForm.webRtcUdpStart" type="number" inputmode="numeric" min="1024" max="65535" :disabled="serverForm.webRtcEnabled" /></label><label><span>{{ tr('webrtcPortEnd') }}</span><input v-model.number="serverForm.webRtcUdpEnd" type="number" inputmode="numeric" min="1024" max="65535" :disabled="serverForm.webRtcEnabled" /></label></div></div><small class="field-help">{{ tr('webrtcApplyHint') }}</small></article>
|
||||
</div>
|
||||
<article class="readonly-card"><h3>{{ tr('runtimeFacts') }}</h3><dl><div><dt>{{ tr('lastTest') }}</dt><dd>{{ formatDate(serverForm.lastTestAt) }}</dd></div><div><dt>{{ tr('latency') }}</dt><dd>{{ serverForm.lastTestLatencyMs == null ? '—' : `${serverForm.lastTestLatencyMs} ms` }}</dd></div><div><dt>{{ tr('internalPort') }}</dt><dd>3040</dd></div></dl></article>
|
||||
@@ -48,7 +48,11 @@
|
||||
<article class="operation-card operation-wide"><header><div><h3>{{ tr('sessions') }}</h3><p>{{ tr('sessionsLead') }}</p></div><strong>{{ operations.sessions.length }}</strong></header><div v-if="operations.sessions.length" class="table-wrap"><table><thead><tr><th>{{ tr('nickname') }}</th><th>{{ tr('sessionState') }}</th><th>{{ tr('age') }}</th><th>{{ tr('memberCount') }}</th><th></th></tr></thead><tbody><tr v-for="session in operations.sessions" :key="session.id"><td><strong>{{ session.nickname }}</strong><small>{{ session.target }}</small></td><td><span class="state-pill">{{ sessionStateLabel(session.state) }}</span></td><td>{{ formatAge(session.ageSeconds) }}</td><td>{{ session.memberCount }}</td><td><button class="danger-button" type="button" :disabled="terminatingSession === session.id" @click="terminateSession(session)">{{ terminatingSession === session.id ? tr('terminating') : tr('endSession') }}</button></td></tr></tbody></table></div><div v-else class="operation-empty"><Icon name="users" :size="22" /><span>{{ tr('sessionEmpty') }}</span></div></article>
|
||||
<article class="operation-card"><header><div><h3>{{ tr('invites') }}</h3><p>{{ tr('invitesLead') }}</p></div></header><form class="invite-form" @submit.prevent="createInvite"><label><span>{{ tr('inviteChannel') }}</span><input v-model.trim="inviteForm.channel" maxlength="100" :placeholder="tr('inviteChannelPlaceholder')" /></label><div class="invite-form-grid"><label><span>{{ tr('expiresIn') }}</span><input v-model.number="inviteForm.expiresInHours" type="number" min="1" max="720" /></label><label><span>{{ tr('maxUses') }}</span><input v-model.number="inviteForm.maxUses" type="number" min="0" max="10000" /></label></div><small class="field-help">{{ tr('unlimitedUses') }}</small><button class="primary-button" type="submit" :disabled="submitting"><span v-if="submitting" class="spinner small"></span>{{ tr('createInvite') }}</button></form><div v-if="createdInvite" class="generated-invite"><strong>{{ tr('inviteCreated') }}</strong><div class="generated-link"><input :value="createdInvite.link" readonly /><button class="secondary-button" type="button" @click="copyInviteLink">{{ tr('copyLink') }}</button></div><small>{{ tr('inviteSecurity') }}</small></div><div v-if="operations.invites.length" class="invite-list"><div v-for="invite in operations.invites" :key="invite.id" class="invite-row"><div><strong>{{ invite.channel || tr('defaultChannel') }}</strong><small>{{ invite.target }} · {{ formatDate(invite.expiresAt) }}</small></div><div class="invite-row-meta"><span :class="['state-pill', invite.status]">{{ inviteStatusLabel(invite.status) }}</span><span>{{ invite.useCount }}/{{ invite.maxUses || '∞' }}</span><button v-if="invite.status === 'active'" class="text-danger" type="button" @click="revokeInvite(invite)">{{ tr('revoke') }}</button></div></div></div></article>
|
||||
</div>
|
||||
<div class="operations-grid lower-operations"><article class="operation-card diagnostics-card"><header><div><h3>{{ tr('diagnostics') }}</h3><p>{{ tr('diagnosticsLead') }}</p></div><a class="text-link" href="/api/admin/diagnostics/report">{{ tr('downloadReport') }}</a></header><dl class="diagnostic-list"><div><dt>{{ tr('version') }}</dt><dd>{{ operations.diagnostics.version || '—' }}</dd></div><div><dt>{{ tr('runtime') }}</dt><dd>{{ operations.diagnostics.node || '—' }}</dd></div><div><dt>{{ tr('platform') }}</dt><dd>{{ operations.diagnostics.platform || '—' }} / {{ operations.diagnostics.arch || '—' }}</dd></div><div><dt>{{ tr('databaseSchema') }}</dt><dd>v{{ operations.diagnostics.schemaVersion || '—' }}</dd></div><div><dt>{{ tr('createdSessions') }}</dt><dd>{{ operations.diagnostics.createdSessions }}</dd></div></dl><button class="secondary-button" type="button" @click="downloadBackup">{{ tr('exportBackup') }}</button></article><article class="operation-card logs-card"><header><div><h3>{{ tr('logViewer') }}</h3><p>{{ tr('logViewerLead') }}</p></div><span v-if="!operations.logs.available" class="muted-label">{{ tr('logsUnavailable') }}</span></header><div v-if="operations.logs.entries.length" class="log-list"><div v-for="(entry, index) in operations.logs.entries" :key="`${entry.timestamp}-${index}`" class="log-row"><span :class="['log-level', entry.level.toLowerCase()]">{{ entry.level }}</span><div><strong>{{ entry.message || '—' }}</strong><small>{{ formatDate(entry.timestamp) }}<template v-if="Object.keys(entry.context).length"> · {{ formatContext(entry.context) }}</template></small></div></div></div><div v-else class="operation-empty"><Icon name="activity" :size="22" /><span>{{ tr('noLogs') }}</span></div></article><article class="operation-card audit-card"><header><div><h3>{{ tr('audit') }}</h3><p>{{ tr('auditLead') }}</p></div></header><ul class="event-list"><li v-for="event in operations.audit" :key="`${event.event}-${event.createdAt}`"><span><Icon name="check" :size="14" /></span><div><strong>{{ eventName(event.event) }}</strong><small>{{ formatDate(event.createdAt) }}</small></div></li><li v-if="!operations.audit.length" class="empty-event">{{ tr('auditEmpty') }}</li></ul></article></div>
|
||||
<div class="operations-grid lower-operations">
|
||||
<article class="operation-card diagnostics-card"><header><div><h3>{{ tr('diagnostics') }}</h3><p>{{ tr('diagnosticsLead') }}</p></div><a class="text-link" href="/api/admin/diagnostics/report">{{ tr('downloadReport') }}</a></header><dl class="diagnostic-list"><div><dt>{{ tr('version') }}</dt><dd>{{ operations.diagnostics.version || '—' }}</dd></div><div><dt>{{ tr('runtime') }}</dt><dd>{{ operations.diagnostics.node || '—' }}</dd></div><div><dt>{{ tr('platform') }}</dt><dd>{{ operations.diagnostics.platform || '—' }} / {{ operations.diagnostics.arch || '—' }}</dd></div><div><dt>{{ tr('databaseSchema') }}</dt><dd>v{{ operations.diagnostics.schemaVersion || '—' }}</dd></div><div><dt>{{ tr('createdSessions') }}</dt><dd>{{ operations.diagnostics.createdSessions }}</dd></div></dl><button class="secondary-button" type="button" @click="downloadBackup">{{ tr('exportBackup') }}</button></article>
|
||||
<article class="operation-card logs-card"><header><div><h3>{{ tr('logViewer') }}</h3><p>{{ tr('logViewerLead') }}</p></div><span v-if="!operations.logs.available" class="muted-label">{{ tr('logsUnavailable') }}</span></header><div v-if="operations.logs.sessions.length" class="connection-list"><div class="connection-history-heading"><strong>{{ tr('connectionHistory') }}</strong><small>{{ tr('connectionHistoryLead') }}</small></div><div v-for="record in operations.logs.sessions" :key="record.id" class="connection-row"><div class="connection-person"><strong>{{ record.nickname }}</strong><small>{{ record.target }}</small></div><div class="connection-detail"><span :class="['connection-status', record.status]">{{ connectionStatusLabel(record.status) }}</span><small>{{ record.connectedAt ? tr('connectedAt') : tr('connectionAttemptedAt') }}:{{ formatDate(record.connectedAt || record.startedAt) }}</small><small>{{ tr('duration') }}:{{ formatAge(record.durationSeconds) }}</small><small v-if="record.disconnectedAt">{{ tr('disconnectedAt') }}:{{ formatDate(record.disconnectedAt) }}</small></div></div></div><div v-if="operations.logs.entries.length" class="log-list"><div v-for="(entry, index) in operations.logs.entries" :key="`${entry.timestamp}-${index}`" class="log-row"><span :class="['log-level', entry.level.toLowerCase()]">{{ entry.level }}</span><div><strong>{{ entry.message || '—' }}</strong><small>{{ formatDate(entry.timestamp) }}<template v-if="Object.keys(entry.context).length"> · {{ formatContext(entry.context) }}</template></small></div></div></div><div v-if="!operations.logs.sessions.length && !operations.logs.entries.length" class="operation-empty"><Icon name="activity" :size="22" /><span>{{ tr('noLogs') }}</span></div></article>
|
||||
<article class="operation-card audit-card"><header><div><h3>{{ tr('audit') }}</h3><p>{{ tr('auditLead') }}</p></div></header><ul class="event-list"><li v-for="event in operations.audit" :key="`${event.event}-${event.createdAt}`"><span><Icon name="check" :size="14" /></span><div><strong>{{ eventName(event.event) }}</strong><small>{{ formatDate(event.createdAt) }}</small></div></li><li v-if="!operations.audit.length" class="empty-event">{{ tr('auditEmpty') }}</li></ul></article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-else class="page-content overview-page">
|
||||
@@ -67,17 +71,19 @@
|
||||
import { computed, onMounted, reactive, ref, watch } from "vue";
|
||||
import { RouterLink, useRoute, useRouter } from "vue-router";
|
||||
import Icon from "../components/Icon.vue";
|
||||
import LanguageSwitcher from "../components/LanguageSwitcher.vue";
|
||||
import { combineTeamSpeakTarget, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
|
||||
import { applyTheme, getStoredTheme, isDarkTheme, nextTheme, saveTheme, type ThemeMode } from "../services/theme.js";
|
||||
|
||||
type Language = "zh" | "en";
|
||||
type Language = "zh" | "en" | "de";
|
||||
type Screen = "login" | "change-password" | "admin";
|
||||
type AccessMode = "fixed" | "open";
|
||||
interface ProbeState { ok: boolean; latencyMs?: number; serverName?: string | null; code?: string }
|
||||
interface ProbeState { ok: boolean; latencyMs?: number; serverName?: string | null; packetLossPercent?: number; attempts?: number; successfulAttempts?: number; code?: string; errorCode?: string }
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const language = ref<Language>((localStorage.getItem("webspeak:language") as Language) || "zh");
|
||||
const storedLanguage = localStorage.getItem("webspeak:language");
|
||||
const language = ref<Language>(storedLanguage === "en" || storedLanguage === "de" ? storedLanguage : "zh");
|
||||
const themeMode = ref<ThemeMode>(getStoredTheme());
|
||||
const themeIcon = computed(() => isDarkTheme(themeMode.value) ? "sun" : "moon");
|
||||
const themeLabel = computed(() => isDarkTheme(themeMode.value) ? tr("switchToLightTheme") : tr("switchToDarkTheme"));
|
||||
@@ -94,17 +100,18 @@ const newPassword = ref("");
|
||||
const confirmNewPassword = ref("");
|
||||
const testResult = ref<ProbeState | null>(null);
|
||||
|
||||
const serverForm = reactive({ address: "", port: "9987", serverPassword: "", passwordAction: "keep" as "keep" | "replace" | "remove", hasPassword: false, accessMode: "fixed" as AccessMode, siteName: "WebSpeak", welcomeText: "", webRtcEnabled: false, webRtcUdpStart: 40000, webRtcUdpEnd: 40099, lastTestAt: null as string | null, lastTestLatencyMs: null as number | null });
|
||||
const serverForm = reactive({ address: "", port: "9987", serverPassword: "", passwordAction: "keep" as "keep" | "replace" | "remove", hasPassword: false, accessMode: "fixed" as AccessMode, siteName: "WebSpeak", welcomeText: "", welcomeTextEn: "", webRtcEnabled: false, webRtcUdpStart: 40000, webRtcUdpEnd: 40099, lastTestAt: null as string | null, lastTestLatencyMs: null as number | null });
|
||||
const overview = reactive({ gateway: { version: "", uptimeSeconds: 0 }, teamSpeak: { target: "", status: "unknown", lastTestAt: null as string | null, latencyMs: null as number | null }, sessions: { active: 0, peak: 0, limit: 100 }, recentEvents: [] as Array<{ event: string; createdAt: string }>, legacyConfigImported: false });
|
||||
interface AdminSession { id: string; nickname: string; target: string; state: string; createdAt: string; ageSeconds: number; tsClientId: number | null; channelId: string | null; memberCount: number }
|
||||
interface ManagedInvite { id: string; target: string; channel: string; expiresAt: string; maxUses: number; useCount: number; createdAt: string; revokedAt: string | null; status: "active" | "expired" | "exhausted" | "revoked" }
|
||||
interface AdminLog { timestamp: string | null; level: string; message: string; context: Record<string, string | number | boolean> }
|
||||
interface AdminConnectionRecord { id: string; nickname: string; target: string; startedAt: string; connectedAt: string | null; disconnectedAt: string | null; durationSeconds: number; status: "active" | "connecting" | "disconnected" | "failed"; reason: string | null }
|
||||
const operationsLoading = ref(false);
|
||||
const terminatingSession = ref("");
|
||||
const inviteForm = reactive({ channel: "", expiresInHours: 24, maxUses: 0 });
|
||||
const createdInvite = ref<{ token: string; link: string } | null>(null);
|
||||
const webrtcPortNoticeOpen = ref(false);
|
||||
const operations = reactive({ sessions: [] as AdminSession[], invites: [] as ManagedInvite[], diagnostics: { version: "", node: "", platform: "", arch: "", schemaVersion: 0, createdSessions: 0 }, logs: { available: false, entries: [] as AdminLog[] }, audit: [] as Array<{ event: string; createdAt: string }> });
|
||||
const operations = reactive({ sessions: [] as AdminSession[], invites: [] as ManagedInvite[], diagnostics: { version: "", node: "", platform: "", arch: "", schemaVersion: 0, createdSessions: 0 }, logs: { available: false, entries: [] as AdminLog[], sessions: [] as AdminConnectionRecord[] }, audit: [] as Array<{ event: string; createdAt: string }> });
|
||||
|
||||
const copy = {
|
||||
zh: {
|
||||
@@ -119,6 +126,7 @@ const copy = {
|
||||
passwordPlaceholder: "至少 12 个字符",
|
||||
passwordHint: "建议使用长且唯一的密码。",
|
||||
confirmPassword: "确认管理员密码",
|
||||
languageMenu: "语言",
|
||||
languageSwitch: "English",
|
||||
themeSystem: "跟随系统",
|
||||
themeLight: "浅色主题",
|
||||
@@ -154,8 +162,9 @@ const copy = {
|
||||
remove: "移除",
|
||||
testConnection: "测试连接",
|
||||
testing: "正在测试…",
|
||||
connectionReady: "连接成功",
|
||||
connectionFailed: "连接失败",
|
||||
connectionReady: "连接成功",
|
||||
connectionFailed: "连接失败",
|
||||
packetLoss: "丢包率",
|
||||
accessAndIdentity: "访问与站点信息",
|
||||
advancedSettings: "高级参数",
|
||||
advancedSettingsLead: "仅在需要时调整网关的高级传输参数。",
|
||||
@@ -176,7 +185,9 @@ const copy = {
|
||||
openMode: "允许访客输入其他服务器",
|
||||
openModeLead: "访客可输入公网 TeamSpeak 地址;内网和保留地址会被阻止。",
|
||||
siteName: "站点显示名称",
|
||||
welcomeText: "欢迎文本",
|
||||
welcomeText: "公告",
|
||||
welcomeTextZh: "中文公告",
|
||||
welcomeTextEn: "英文公告",
|
||||
runtimeFacts: "运行时信息",
|
||||
lastTest: "最近测试",
|
||||
latency: "延迟",
|
||||
@@ -254,7 +265,16 @@ const copy = {
|
||||
downloadReport: "下载诊断报告",
|
||||
exportBackup: "导出数据库备份",
|
||||
logViewer: "运行日志",
|
||||
logViewerLead: "最近的网关日志,不包含聊天内容。",
|
||||
logViewerLead: "最近的网关日志及用户连接记录,不包含聊天内容。",
|
||||
connectionHistory: "用户连接记录",
|
||||
connectionHistoryLead: "按用户合并连接、断开与持续时间。",
|
||||
connectionActive: "连接中",
|
||||
connectionConnecting: "准备连接",
|
||||
connectionDisconnected: "已断开",
|
||||
connectedAt: "接入",
|
||||
connectionAttemptedAt: "尝试",
|
||||
disconnectedAt: "断开",
|
||||
duration: "时长",
|
||||
logsUnavailable: "未配置日志文件",
|
||||
noLogs: "暂无可查看日志。",
|
||||
operationFailed: "运维操作失败,请稍后重试。",
|
||||
@@ -276,6 +296,7 @@ const copy = {
|
||||
passwordPlaceholder: "At least 12 characters",
|
||||
passwordHint: "Use a long, unique password.",
|
||||
confirmPassword: "Confirm admin password",
|
||||
languageMenu: "Language",
|
||||
languageSwitch: "中文",
|
||||
themeSystem: "System theme",
|
||||
themeLight: "Light theme",
|
||||
@@ -311,8 +332,9 @@ const copy = {
|
||||
remove: "Remove",
|
||||
testConnection: "Test connection",
|
||||
testing: "Testing…",
|
||||
connectionReady: "Connection ready",
|
||||
connectionFailed: "Connection failed",
|
||||
connectionReady: "Connection ready",
|
||||
connectionFailed: "Connection failed",
|
||||
packetLoss: "Packet loss",
|
||||
accessAndIdentity: "Access and site identity",
|
||||
advancedSettings: "Advanced settings",
|
||||
advancedSettingsLead: "Adjust gateway transport options only when needed.",
|
||||
@@ -333,7 +355,9 @@ const copy = {
|
||||
openMode: "Allow other TeamSpeak servers",
|
||||
openModeLead: "Guests may enter public TeamSpeak addresses; private and reserved networks are blocked.",
|
||||
siteName: "Site display name",
|
||||
welcomeText: "Welcome text",
|
||||
welcomeText: "Announcement",
|
||||
welcomeTextZh: "Chinese announcement",
|
||||
welcomeTextEn: "English announcement",
|
||||
runtimeFacts: "Runtime facts",
|
||||
lastTest: "Last test",
|
||||
latency: "Latency",
|
||||
@@ -411,7 +435,16 @@ const copy = {
|
||||
downloadReport: "Download diagnostic report",
|
||||
exportBackup: "Export database backup",
|
||||
logViewer: "Runtime logs",
|
||||
logViewerLead: "Recent gateway logs; chat content is not recorded.",
|
||||
logViewerLead: "Recent gateway logs and user connection records; chat content is not recorded.",
|
||||
connectionHistory: "User connection records",
|
||||
connectionHistoryLead: "Connections, disconnects, and durations grouped by user.",
|
||||
connectionActive: "Connected",
|
||||
connectionConnecting: "Connecting",
|
||||
connectionDisconnected: "Disconnected",
|
||||
connectedAt: "Connected",
|
||||
connectionAttemptedAt: "Attempted",
|
||||
disconnectedAt: "Disconnected",
|
||||
duration: "Duration",
|
||||
logsUnavailable: "Log file unavailable",
|
||||
noLogs: "No logs are available.",
|
||||
operationFailed: "The operation failed. Try again later.",
|
||||
@@ -423,10 +456,137 @@ const copy = {
|
||||
},
|
||||
} as const;
|
||||
|
||||
function tr(key: keyof typeof copy.zh, vars: Record<string, string | number> = {}): string { let value: string = language.value === "zh" ? copy.zh[key] : copy.en[key] ?? copy.zh[key]; for (const [name, replacement] of Object.entries(vars)) value = value.replaceAll(`{{${name}}}`, String(replacement)); return value; }
|
||||
const germanCopy = {
|
||||
...copy.en,
|
||||
loading: "Administrationskonsole wird geladen…",
|
||||
adminConsole: "Administrationskonsole",
|
||||
changePasswordTitle: "Standardpasswort ändern",
|
||||
changePasswordLead: "Das Standardpasswort ist nur für die erste Anmeldung gedacht. Lege ein neues Passwort mit mindestens 12 Zeichen fest.",
|
||||
savePassword: "Neues Passwort speichern",
|
||||
defaultCredentialNotice: "Standardkonto: admin. Standardpasswort: admin. Das alte Passwort wird nach dem Speichern sofort ungültig.",
|
||||
adminUsername: "Administratorname",
|
||||
newPassword: "Neues Administratorpasswort",
|
||||
passwordPlaceholder: "Mindestens 12 Zeichen",
|
||||
passwordHint: "Verwende ein langes, eindeutiges Passwort.",
|
||||
confirmPassword: "Administratorpasswort bestätigen",
|
||||
languageMenu: "Sprache",
|
||||
languageSwitch: "中文",
|
||||
welcomeAdmin: "Willkommen zurück",
|
||||
loginLead: "Melde dich an, um diese WebSpeak-Instanz zu verwalten.",
|
||||
adminPassword: "Administratorpasswort",
|
||||
login: "Anmelden",
|
||||
backHome: "Zur Startseite",
|
||||
overview: "Übersicht",
|
||||
server: "Server",
|
||||
operations: "Betrieb",
|
||||
openGuest: "Gastseite öffnen",
|
||||
logout: "Abmelden",
|
||||
gatewayRunning: "Gateway läuft",
|
||||
serverSettings: "Servereinstellungen",
|
||||
serverSettingsLead: "Standard-TeamSpeak-Ziel, Zugriffsregeln und Inhalte der Gastseite verwalten.",
|
||||
saving: "Wird gespeichert…",
|
||||
saveChanges: "Änderungen speichern",
|
||||
teamSpeakTarget: "Standard-TeamSpeak-Ziel",
|
||||
serverAddress: "TeamSpeak-Serveradresse",
|
||||
serverPlaceholder: "z. B. ts.example.com oder 127.0.0.1",
|
||||
serverPort: "Sprachport",
|
||||
serverHint: "Serveradresse und Sprachport getrennt eingeben. IPv6-Adressen benötigen keine Klammern.",
|
||||
serverPassword: "Serverpasswort",
|
||||
optional: "Optional",
|
||||
optionalPassword: "Leer lassen, wenn kein Passwort verwendet wird",
|
||||
passwordConfigured: "Passwort konfiguriert (leer lassen, um es beizubehalten)",
|
||||
change: "Ändern",
|
||||
remove: "Entfernen",
|
||||
testConnection: "Verbindung testen",
|
||||
testing: "Wird getestet…",
|
||||
connectionReady: "Verbindung hergestellt",
|
||||
connectionFailed: "Verbindung fehlgeschlagen",
|
||||
packetLoss: "Paketverlust",
|
||||
accessAndIdentity: "Zugriff und Website-Informationen",
|
||||
advancedSettings: "Erweiterte Einstellungen",
|
||||
advancedSettingsLead: "Erweiterte Gateway-Transportparameter nur bei Bedarf ändern.",
|
||||
webrtcSettings: "WebRTC-Audio",
|
||||
webrtcEnabled: "WebRTC aktivieren",
|
||||
webrtcPortRange: "WebRTC-UDP-Portbereich",
|
||||
webrtcPortStart: "Startport",
|
||||
webrtcPortEnd: "Endport",
|
||||
accessMode: "Gastzugriff",
|
||||
fixedMode: "Nur dieser TeamSpeak-Server",
|
||||
openMode: "Andere TeamSpeak-Server erlauben",
|
||||
siteName: "Anzeigename der Website",
|
||||
welcomeText: "Ankündigung",
|
||||
welcomeTextZh: "Chinesische Ankündigung",
|
||||
welcomeTextEn: "Englische Ankündigung",
|
||||
runtimeFacts: "Laufzeitinformationen",
|
||||
lastTest: "Letzter Test",
|
||||
latency: "Latenz",
|
||||
internalPort: "Interner Port",
|
||||
unknown: "Unbekannt",
|
||||
gotIt: "Verstanden",
|
||||
systemStatus: "SYSTEMSTATUS",
|
||||
everythingRunning: "WebSpeak läuft",
|
||||
overviewLead: "Der Verwaltungsdienst ist verfügbar. Die Erreichbarkeit von TeamSpeak entspricht dem letzten Verbindungstest.",
|
||||
running: "Läuft",
|
||||
gateway: "Gateway",
|
||||
activeSessions: "Aktive Sitzungen",
|
||||
targetHealth: "Zielstatus",
|
||||
status: "Status",
|
||||
recentEvents: "Letzte Ereignisse",
|
||||
noRecentEvents: "Keine aktuellen Ereignisse",
|
||||
reachable: "Erreichbar",
|
||||
unreachable: "Nicht erreichbar",
|
||||
notTested: "Nicht getestet",
|
||||
invalidPassword: "Das Administratorpasswort ist falsch.",
|
||||
rateLimited: "Zu viele Versuche. Bitte später erneut versuchen.",
|
||||
requestFailed: "Anfrage fehlgeschlagen. Prüfe die Eingaben und versuche es erneut.",
|
||||
refresh: "Aktualisieren",
|
||||
sessions: "Aktive Sitzungen",
|
||||
sessionEmpty: "Keine aktiven Sitzungen.",
|
||||
nickname: "Name",
|
||||
sessionState: "Status",
|
||||
age: "Dauer",
|
||||
memberCount: "Mitglieder",
|
||||
endSession: "Trennen",
|
||||
terminating: "Wird getrennt…",
|
||||
sessionTerminated: "Sitzung getrennt.",
|
||||
invites: "Verwaltete Einladungen",
|
||||
inviteChannel: "Zielkanal",
|
||||
expiresIn: "Gültig für (Stunden)",
|
||||
maxUses: "Maximale Nutzungen",
|
||||
createInvite: "Einladungslink erstellen",
|
||||
inviteCreated: "Einladungslink erstellt",
|
||||
copyLink: "Link kopieren",
|
||||
copiedLink: "Einladungslink kopiert.",
|
||||
revoke: "Widerrufen",
|
||||
inviteRevoked: "Einladungslink widerrufen.",
|
||||
active: "Aktiv",
|
||||
expired: "Abgelaufen",
|
||||
exhausted: "Aufgebraucht",
|
||||
revoked: "Widerrufen",
|
||||
diagnostics: "Diagnose",
|
||||
downloadReport: "Diagnosebericht herunterladen",
|
||||
exportBackup: "Datenbanksicherung exportieren",
|
||||
logViewer: "Laufzeitprotokoll",
|
||||
connectionHistory: "Verbindungsaufzeichnungen",
|
||||
connectionActive: "Verbunden",
|
||||
connectionConnecting: "Verbindung wird hergestellt",
|
||||
connectionDisconnected: "Getrennt",
|
||||
connectedAt: "Verbunden",
|
||||
connectionAttemptedAt: "Versuch",
|
||||
disconnectedAt: "Getrennt",
|
||||
duration: "Dauer",
|
||||
logsUnavailable: "Protokolldatei nicht verfügbar",
|
||||
noLogs: "Keine Protokolle verfügbar.",
|
||||
operationFailed: "Vorgang fehlgeschlagen. Bitte später erneut versuchen.",
|
||||
version: "Version",
|
||||
audit: "Prüfprotokoll",
|
||||
auditEmpty: "Keine Prüfereignisse.",
|
||||
} as const;
|
||||
|
||||
function tr(key: keyof typeof copy.zh, vars: Record<string, string | number> = {}): string { let value: string = language.value === "zh" ? copy.zh[key] : language.value === "de" ? germanCopy[key] ?? copy.en[key] ?? copy.zh[key] : copy.en[key] ?? copy.zh[key]; for (const [name, replacement] of Object.entries(vars)) value = value.replaceAll(`{{${name}}}`, String(replacement)); return value; }
|
||||
const passwordStrength = computed(() => Math.min(100, Math.max(8, newPassword.value.length * 5 + (/[\s\W]/.test(newPassword.value) ? 15 : 0))));
|
||||
const currentPageTitle = computed(() => route.path === "/admin/server" ? tr('server') : route.path === "/admin/operations" ? tr('operations') : tr('overview'));
|
||||
const testResultText = computed(() => { if (!testResult.value) return ""; if (!testResult.value.ok) return errorText(testResult.value.code); return [testResult.value.serverName, testResult.value.latencyMs == null ? null : `${testResult.value.latencyMs} ms`].filter(Boolean).join(" · "); });
|
||||
const testResultText = computed(() => { if (!testResult.value) return ""; const result = testResult.value; const toolUnavailable = result.errorCode === "PING_UNAVAILABLE"; const loss = toolUnavailable || result.packetLossPercent == null ? null : `${tr('packetLoss')} ${result.packetLossPercent}%`; if (!result.ok) return [errorText(result.code ?? result.errorCode), loss].filter(Boolean).join(" · "); return [result.serverName, result.latencyMs == null ? null : `${result.latencyMs} ms`, loss].filter(Boolean).join(" · "); });
|
||||
const targetStatusText = computed(() => overview.teamSpeak.status === "reachable" ? tr('reachable') : overview.teamSpeak.status === "unreachable" ? tr('unreachable') : tr('notTested'));
|
||||
const webrtcPortRangeText = computed(() => `${serverForm.webRtcUdpStart}–${serverForm.webRtcUdpEnd}`);
|
||||
|
||||
@@ -440,7 +600,7 @@ async function changePassword() { errorMessage.value = ""; if (newPassword.value
|
||||
async function logout() { try { await sendJson("/api/admin/logout", "POST", {}); } finally { csrfToken.value = ""; screen.value = "login"; await router.replace("/admin/login"); } }
|
||||
async function loadOverview() { Object.assign(overview, await getJson("/api/admin/overview")); }
|
||||
async function loadServerSettings() { const value = await getJson("/api/admin/server"); const target = splitTeamSpeakTarget(value.target); Object.assign(serverForm, value, { address: target.address, port: target.port, serverPassword: "", passwordAction: "keep", webRtcEnabled: value.webRtcEnabled === true, webRtcUdpStart: Number(value.webRtcUdpStart || 40000), webRtcUdpEnd: Number(value.webRtcUdpEnd || 40099) }); }
|
||||
async function loadOperations() { operationsLoading.value = true; try { const [sessions, invites, diagnostics, logs, audit] = await Promise.all([getJson("/api/admin/sessions"), getJson("/api/admin/invites"), getJson("/api/admin/diagnostics"), getJson("/api/admin/logs?limit=100"), getJson("/api/admin/audit?limit=50")]); operations.sessions = Array.isArray(sessions.sessions) ? sessions.sessions : []; operations.invites = Array.isArray(invites.invites) ? invites.invites : []; operations.diagnostics = { version: String(diagnostics.gateway?.version || ""), node: String(diagnostics.gateway?.node || ""), platform: String(diagnostics.gateway?.platform || ""), arch: String(diagnostics.gateway?.arch || ""), schemaVersion: Number(diagnostics.database?.schemaVersion || 0), createdSessions: Number(diagnostics.sessions?.created || 0) }; operations.logs = { available: Boolean(logs.available), entries: Array.isArray(logs.entries) ? logs.entries : [] }; operations.audit = Array.isArray(audit.events) ? audit.events : []; } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { operationsLoading.value = false; } }
|
||||
async function loadOperations() { operationsLoading.value = true; try { const [sessions, invites, diagnostics, logs, audit] = await Promise.all([getJson("/api/admin/sessions"), getJson("/api/admin/invites"), getJson("/api/admin/diagnostics"), getJson("/api/admin/logs?limit=100"), getJson("/api/admin/audit?limit=50")]); operations.sessions = Array.isArray(sessions.sessions) ? sessions.sessions : []; operations.invites = Array.isArray(invites.invites) ? invites.invites : []; operations.diagnostics = { version: String(diagnostics.gateway?.version || ""), node: String(diagnostics.gateway?.node || ""), platform: String(diagnostics.gateway?.platform || ""), arch: String(diagnostics.gateway?.arch || ""), schemaVersion: Number(diagnostics.database?.schemaVersion || 0), createdSessions: Number(diagnostics.sessions?.created || 0) }; operations.logs = { available: Boolean(logs.available), entries: Array.isArray(logs.entries) ? logs.entries : [], sessions: Array.isArray(logs.sessions) ? logs.sessions : [] }; operations.audit = Array.isArray(audit.events) ? audit.events : []; } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { operationsLoading.value = false; } }
|
||||
async function terminateSession(session: AdminSession) { if (!window.confirm(tr('confirmTerminate', { nickname: session.nickname }))) return; terminatingSession.value = session.id; errorMessage.value = ""; try { await sendJson(`/api/admin/sessions/${encodeURIComponent(session.id)}/terminate`, "POST", {}); await Promise.all([loadOperations(), loadOverview()]); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { terminatingSession.value = ""; } }
|
||||
async function createInvite() { submitting.value = true; errorMessage.value = ""; createdInvite.value = null; try { const result = await sendJson("/api/admin/invites", "POST", { channel: inviteForm.channel, expiresInHours: inviteForm.expiresInHours, maxUses: inviteForm.maxUses }); if (typeof result.token !== "string") throw new Error("INVITE_CREATE_FAILED"); createdInvite.value = { token: result.token, link: `${location.origin}/?invite=${encodeURIComponent(result.token)}` }; inviteForm.channel = ""; await loadOperations(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
|
||||
async function revokeInvite(invite: ManagedInvite) { if (!window.confirm(tr('confirmRevoke'))) return; try { await sendJson(`/api/admin/invites/${encodeURIComponent(invite.id)}/revoke`, "POST", {}); await loadOperations(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } }
|
||||
@@ -449,20 +609,21 @@ function showOperationNotice(message: string) { errorMessage.value = message; wi
|
||||
async function downloadBackup() { try { const response = await fetch("/api/admin/backup", { headers: { accept: "application/octet-stream" } }); if (!response.ok) throw new Error("BACKUP_FAILED"); const blob = await response.blob(); const url = URL.createObjectURL(blob); const anchor = document.createElement("a"); anchor.href = url; anchor.download = `webspeak-backup-${new Date().toISOString().slice(0, 10)}.db`; anchor.click(); URL.revokeObjectURL(url); await loadOperations(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } }
|
||||
async function saveServerSettings() { submitting.value = true; errorMessage.value = ""; try { const result = await sendJson("/api/admin/server", "PUT", serverPayload()); const target = splitTeamSpeakTarget(result.settings?.target); Object.assign(serverForm, result.settings, { address: target.address, port: target.port, serverPassword: "", passwordAction: "keep", webRtcEnabled: result.settings.webRtcEnabled === true, webRtcUdpStart: Number(result.settings.webRtcUdpStart || 40000), webRtcUdpEnd: Number(result.settings.webRtcUdpEnd || 40099) }); await loadOverview(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
|
||||
function handleWebRtcToggle() { if (serverForm.webRtcEnabled) webrtcPortNoticeOpen.value = true; }
|
||||
async function testServerConnection() { await runTest("/api/admin/server/test", { target: combineTeamSpeakTarget(serverForm.address, serverForm.port), serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined, passwordAction: serverForm.passwordAction }); if (testResult.value?.ok) { await loadOverview(); serverForm.lastTestAt = new Date().toISOString(); serverForm.lastTestLatencyMs = testResult.value.latencyMs ?? null; } }
|
||||
function serverPayload() { return { target: combineTeamSpeakTarget(serverForm.address, serverForm.port), serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined, passwordAction: serverForm.passwordAction, accessMode: serverForm.accessMode, siteName: serverForm.siteName, welcomeText: serverForm.welcomeText, webRtcEnabled: serverForm.webRtcEnabled, webRtcUdpStart: serverForm.webRtcUdpStart, webRtcUdpEnd: serverForm.webRtcUdpEnd }; }
|
||||
async function testServerConnection() { await runTest("/api/admin/server/test", { target: combineTeamSpeakTarget(serverForm.address, serverForm.port), serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined, passwordAction: serverForm.passwordAction }); if (testResult.value) { await loadOverview(); serverForm.lastTestAt = new Date().toISOString(); serverForm.lastTestLatencyMs = testResult.value.ok ? (testResult.value.latencyMs ?? null) : null; } }
|
||||
function serverPayload() { return { target: combineTeamSpeakTarget(serverForm.address, serverForm.port), serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined, passwordAction: serverForm.passwordAction, accessMode: serverForm.accessMode, siteName: serverForm.siteName, welcomeText: serverForm.welcomeText, welcomeTextEn: serverForm.welcomeTextEn, webRtcEnabled: serverForm.webRtcEnabled, webRtcUdpStart: serverForm.webRtcUdpStart, webRtcUdpEnd: serverForm.webRtcUdpEnd }; }
|
||||
async function runTest(url: string, body: Record<string, unknown>) { testing.value = true; errorMessage.value = ""; testResult.value = null; try { testResult.value = await sendJson(url, "POST", body, url.includes("/server/test")); } catch (error) { testResult.value = { ok: false, code: (error as ApiError).code }; } finally { testing.value = false; } }
|
||||
async function dismissLegacyNotice() { await sendJson("/api/admin/legacy-import/dismiss", "POST", {}); overview.legacyConfigImported = false; }
|
||||
function toggleLanguage() { language.value = language.value === "zh" ? "en" : "zh"; localStorage.setItem("webspeak:language", language.value); }
|
||||
function persistLanguage() { localStorage.setItem("webspeak:language", language.value); }
|
||||
function cycleTheme() { themeMode.value = nextTheme(themeMode.value); saveTheme(themeMode.value); }
|
||||
function formatDate(value: string | null) { return value ? new Intl.DateTimeFormat(language.value === "zh" ? "zh-CN" : "en-US", { dateStyle: "medium", timeStyle: "short" }).format(new Date(value)) : "—"; }
|
||||
function formatUptime(seconds: number) { const hours = Math.floor(seconds / 3600); const minutes = Math.floor((seconds % 3600) / 60); return language.value === "zh" ? `已运行 ${hours} 小时 ${minutes} 分钟` : `Up ${hours}h ${minutes}m`; }
|
||||
function formatAge(seconds: number) { if (seconds < 60) return language.value === "zh" ? `${seconds} 秒` : `${seconds}s`; const minutes = Math.floor(seconds / 60); if (minutes < 60) return language.value === "zh" ? `${minutes} 分钟` : `${minutes}m`; const hours = Math.floor(minutes / 60); return language.value === "zh" ? `${hours} 小时 ${minutes % 60} 分钟` : `${hours}h ${minutes % 60}m`; }
|
||||
function sessionStateLabel(state: string) { const names: Record<string, { zh: string; en: string }> = { connecting: { zh: "连接中", en: "Connecting" }, authenticating: { zh: "认证中", en: "Authenticating" }, syncing: { zh: "同步中", en: "Syncing" }, connected: { zh: "已连接", en: "Connected" }, interrupted: { zh: "已中断", en: "Interrupted" }, reconnecting: { zh: "重连中", en: "Reconnecting" }, disconnecting: { zh: "断开中", en: "Disconnecting" }, failed: { zh: "失败", en: "Failed" }, idle: { zh: "空闲", en: "Idle" } }; return names[state]?.[language.value] ?? state; }
|
||||
function formatDate(value: string | null) { return value ? new Intl.DateTimeFormat(language.value === "zh" ? "zh-CN" : language.value === "de" ? "de-DE" : "en-US", { dateStyle: "medium", timeStyle: "short" }).format(new Date(value)) : "—"; }
|
||||
function formatUptime(seconds: number) { const hours = Math.floor(seconds / 3600); const minutes = Math.floor((seconds % 3600) / 60); return language.value === "zh" ? `已运行 ${hours} 小时 ${minutes} 分钟` : language.value === "de" ? `${hours} Std. ${minutes} Min. aktiv` : `Up ${hours}h ${minutes}m`; }
|
||||
function formatAge(seconds: number | null) { if (seconds == null) return "—"; if (seconds < 60) return language.value === "zh" ? `${seconds} 秒` : language.value === "de" ? `${seconds} Sek.` : `${seconds}s`; const minutes = Math.floor(seconds / 60); if (minutes < 60) return language.value === "zh" ? `${minutes} 分钟` : language.value === "de" ? `${minutes} Min.` : `${minutes}m`; const hours = Math.floor(minutes / 60); return language.value === "zh" ? `${hours} 小时 ${minutes % 60} 分钟` : language.value === "de" ? `${hours} Std. ${minutes % 60} Min.` : `${hours}h ${minutes % 60}m`; }
|
||||
function connectionStatusLabel(status: AdminConnectionRecord["status"]) { const names: Record<AdminConnectionRecord["status"], keyof typeof copy.zh> = { active: "connectionActive", connecting: "connectionConnecting", disconnected: "connectionDisconnected", failed: "connectionFailed" }; return tr(names[status]); }
|
||||
function sessionStateLabel(state: string) { const names: Record<string, { zh: string; en: string; de: string }> = { connecting: { zh: "连接中", en: "Connecting", de: "Verbindung wird hergestellt" }, authenticating: { zh: "认证中", en: "Authenticating", de: "Authentifizierung" }, syncing: { zh: "同步中", en: "Syncing", de: "Synchronisierung" }, connected: { zh: "已连接", en: "Connected", de: "Verbunden" }, interrupted: { zh: "已中断", en: "Interrupted", de: "Unterbrochen" }, reconnecting: { zh: "重连中", en: "Reconnecting", de: "Wiederverbindung" }, disconnecting: { zh: "断开中", en: "Disconnecting", de: "Wird getrennt" }, failed: { zh: "失败", en: "Failed", de: "Fehlgeschlagen" }, idle: { zh: "空闲", en: "Idle", de: "Inaktiv" } }; return names[state]?.[language.value] ?? state; }
|
||||
function inviteStatusLabel(status: ManagedInvite["status"]) { const names: Record<ManagedInvite["status"], keyof typeof copy.zh> = { active: "active", expired: "expired", exhausted: "exhausted", revoked: "revoked" }; return tr(names[status]); }
|
||||
function formatContext(context: Record<string, string | number | boolean>) { return Object.entries(context).map(([key, value]) => `${key}=${value}`).join(" · "); }
|
||||
function eventName(event: string) { if (event === "ADMIN_LOGIN_FAILED") return language.value === "zh" ? "管理员登录失败" : "Administrator login failed"; if (event === "CONNECTION_TEST_SUCCEEDED") return language.value === "zh" ? "连接测试成功" : "Connection test succeeded"; if (event === "CONNECTION_TEST_FAILED") return language.value === "zh" ? "连接测试失败" : "Connection test failed"; const names: Record<string, keyof typeof copy.zh> = { ADMIN_LOGIN_SUCCEEDED: "loginEvent", ADMIN_LOGOUT: "logoutEvent", SETTINGS_CHANGED: "settingsEvent", ADMIN_INITIALIZED: "initializedEvent", LEGACY_CONFIG_IMPORTED: "importedEvent", CONNECTION_TEST: "testEvent" }; return names[event] ? tr(names[event]) : language.value === "zh" ? "系统事件" : event.replaceAll("_", " "); }
|
||||
function errorText(code?: string) { if (code === "INVALID_PASSWORD") return tr('invalidPassword'); if (code === "INVALID_ADMIN_PASSWORD") return tr('setupPasswordShort'); if (code === "PASSWORD_CHANGE_REQUIRED") return tr('changePasswordLead'); if (code === "RATE_LIMITED") return tr('rateLimited'); if (code === "INVALID_WEBRTC_PORT_RANGE") return language.value === "zh" ? "WebRTC UDP 端口范围无效,请填写 1024–65535 且起始端口不能大于结束端口。" : "The WebRTC UDP port range is invalid. Use 1024–65535 with the start no greater than the end."; if (code === "WEBRTC_PORT_LOCKED") return language.value === "zh" ? "WebRTC 已开启,请先关闭并保存后再修改端口范围。" : "WebRTC is enabled. Turn it off and save before changing the port range."; const probe: Record<string, { zh: string; en: string }> = { INVALID_TARGET: { zh: "TeamSpeak 服务器地址格式无效。", en: "The TeamSpeak server address is invalid." }, HOST_NOT_FOUND: { zh: "找不到服务器主机名。", en: "The server hostname could not be resolved." }, UNREACHABLE: { zh: "无法连接 TeamSpeak 服务器。", en: "The TeamSpeak server is unreachable." }, TIMEOUT: { zh: "连接 TeamSpeak 超时。", en: "The TeamSpeak connection timed out." }, PROTOCOL_NEGOTIATION_FAILED: { zh: "无法识别 TeamSpeak 协议。", en: "TeamSpeak protocol negotiation failed." }, SERVER_REJECTED: { zh: "TeamSpeak 服务器拒绝了连接。", en: "The TeamSpeak server rejected the connection." }, TARGET_NOT_ALLOWED: { zh: "此地址不允许在开放模式中使用。", en: "This target is not allowed in open mode." } }; return probe[code || ""]?.[language.value] ?? tr('requestFailed'); }
|
||||
function errorText(code?: string) { if (code === "INVALID_PASSWORD") return tr('invalidPassword'); if (code === "INVALID_ADMIN_PASSWORD") return tr('setupPasswordShort'); if (code === "PASSWORD_CHANGE_REQUIRED") return tr('changePasswordLead'); if (code === "RATE_LIMITED") return tr('rateLimited'); if (code === "INVALID_WEBRTC_PORT_RANGE") return language.value === "zh" ? "WebRTC UDP 端口范围无效,请填写 1024–65535 且起始端口不能大于结束端口。" : language.value === "de" ? "Der WebRTC-UDP-Portbereich ist ungültig. Verwende 1024–65535; der Startport darf nicht größer als der Endport sein." : "The WebRTC UDP port range is invalid. Use 1024–65535 with the start no greater than the end."; if (code === "WEBRTC_PORT_LOCKED") return language.value === "zh" ? "WebRTC 已开启,请先关闭并保存后再修改端口范围。" : language.value === "de" ? "WebRTC ist aktiviert. Deaktiviere es und speichere zuerst, bevor du den Portbereich änderst." : "WebRTC is enabled. Turn it off and save before changing the port range."; const probe: Record<string, { zh: string; en: string; de: string }> = { INVALID_TARGET: { zh: "TeamSpeak 服务器地址格式无效。", en: "The TeamSpeak server address is invalid.", de: "Die TeamSpeak-Serveradresse ist ungültig." }, PING_UNAVAILABLE: { zh: "当前运行环境没有可用的 ICMP Ping 工具。", en: "The runtime does not provide an ICMP ping tool.", de: "In der Laufzeitumgebung ist kein ICMP-Ping-Tool verfügbar." }, HOST_NOT_FOUND: { zh: "找不到服务器主机名。", en: "The server hostname could not be resolved.", de: "Der Servername konnte nicht aufgelöst werden." }, UNREACHABLE: { zh: "无法连接 TeamSpeak 服务器。", en: "The TeamSpeak server is unreachable.", de: "Der TeamSpeak-Server ist nicht erreichbar." }, TIMEOUT: { zh: "连接 TeamSpeak 超时。", en: "The TeamSpeak connection timed out.", de: "Die Verbindung zu TeamSpeak ist abgelaufen." }, PROTOCOL_NEGOTIATION_FAILED: { zh: "无法识别 TeamSpeak 协议。", en: "TeamSpeak protocol negotiation failed.", de: "Die Aushandlung des TeamSpeak-Protokolls ist fehlgeschlagen." }, SERVER_REJECTED: { zh: "TeamSpeak 服务器拒绝了连接。", en: "The TeamSpeak server rejected the connection.", de: "Der TeamSpeak-Server hat die Verbindung abgelehnt." }, TARGET_NOT_ALLOWED: { zh: "此地址不允许在开放模式中使用。", en: "This target is not allowed in open mode.", de: "Dieses Ziel ist im offenen Modus nicht erlaubt." } }; return probe[code || ""]?.[language.value] ?? tr('requestFailed'); }
|
||||
|
||||
interface ApiError extends Error { code?: string }
|
||||
async function getJson(url: string): Promise<any> { const response = await fetch(url, { headers: { accept: "application/json" } }); return parseResponse(response); }
|
||||
@@ -477,15 +638,17 @@ async function parseResponse(response: Response) { const value = await response.
|
||||
@media(max-width:850px){.auth-layout{display:block}.auth-intro{min-height:auto;padding:28px 24px}.intro-copy{margin:55px 0 35px}.step-list{display:none}.auth-panel{padding:35px 18px 60px}.panel-tools{top:18px;right:18px}.admin-shell{display:block}.admin-sidebar{position:static;width:100%;height:auto;flex-direction:row;align-items:center;padding:12px 16px}.admin-sidebar .admin-brand{padding:0}.admin-sidebar .admin-brand small{display:none}.admin-sidebar nav{display:flex;margin-left:auto}.admin-sidebar nav a{font-size:0}.admin-sidebar nav a .ui-icon{width:20px;height:20px}.sidebar-bottom{display:flex;margin:0 0 0 8px;padding:0;border:0}.sidebar-bottom a{display:none}.sidebar-bottom button{font-size:0}.settings-grid,.overview-columns{grid-template-columns:1fr}.readonly-card dl{grid-template-columns:1fr 1fr}.admin-topbar{padding:0 18px}.page-content{width:min(100% - 28px,700px);padding-top:24px}.metric-grid{grid-template-columns:1fr}.hero-status{align-items:flex-start;gap:20px}.hero-status p{max-width:75%}}
|
||||
@media(max-width:520px){.setup-card,.login-card{padding:25px 20px;border-radius:15px}.setup-card header h2{font-size:24px}.admin-topbar>div:last-child{font-size:0}.page-heading{gap:15px}.page-heading .primary-button{padding-inline:12px}.settings-card,.readonly-card,.overview-card{padding:18px}.readonly-card dl,.overview-card dl{grid-template-columns:1fr}.password-row{grid-template-columns:1fr}.password-actions{padding:0}.hero-status{padding:23px}.status-badge{display:none}}
|
||||
.security-note{margin:18px 0 0;color:#879590;font-size:11px;line-height:1.5}
|
||||
:global(:root[data-theme="dark"]) .admin-root, :global(:root[data-theme="dark"]) .login-page, :global(:root[data-theme="dark"]) .auth-panel { color: #e8f3f0; background: #101918; }
|
||||
:global(:root[data-theme="dark"]) .admin-topbar, :global(:root[data-theme="dark"]) .setup-card, :global(:root[data-theme="dark"]) .login-card, :global(:root[data-theme="dark"]) .settings-card, :global(:root[data-theme="dark"]) .readonly-card, :global(:root[data-theme="dark"]) .overview-card, :global(:root[data-theme="dark"]) input, :global(:root[data-theme="dark"]) textarea { color: #e8f3f0; background: #172321; border-color: #30413d; }
|
||||
:global(:root[data-theme="dark"]) .admin-topbar, :global(:root[data-theme="dark"]) .settings-card, :global(:root[data-theme="dark"]) .readonly-card, :global(:root[data-theme="dark"]) .overview-card { border-color: #30413d; }
|
||||
:global(:root[data-theme="dark"]) .admin-topbar h1, :global(:root[data-theme="dark"]) .page-heading h2, :global(:root[data-theme="dark"]) .settings-card h3, :global(:root[data-theme="dark"]) .readonly-card h3, :global(:root[data-theme="dark"]) .overview-card h3, :global(:root[data-theme="dark"]) .login-card h1 { color: #e8f3f0; }
|
||||
:global(:root[data-theme="dark"]) .page-heading p, :global(:root[data-theme="dark"]) .admin-topbar small, :global(:root[data-theme="dark"]) label > span, :global(:root[data-theme="dark"]) .page-heading p { color: #9bb0aa; }
|
||||
:global(:root[data-theme="dark"]) .metric-grid article, :global(:root[data-theme="dark"]) .readonly-card dl div, :global(:root[data-theme="dark"]) .overview-card dl div, :global(:root[data-theme="dark"]) .event-list li { background: #202f2c; border-color: #30413d; }
|
||||
@media (prefers-color-scheme: dark) { :global(:root[data-theme="system"]) .admin-root, :global(:root[data-theme="system"]) .login-page, :global(:root[data-theme="system"]) .auth-panel { color: #e8f3f0; background: #101918; } :global(:root[data-theme="system"]) .admin-topbar, :global(:root[data-theme="system"]) .setup-card, :global(:root[data-theme="system"]) .login-card, :global(:root[data-theme="system"]) .settings-card, :global(:root[data-theme="system"]) .readonly-card, :global(:root[data-theme="system"]) .overview-card { background: #172321; border-color: #30413d; } }
|
||||
:global(html[data-theme="dark"] .admin-root), :global(html[data-theme="dark"] .login-page), :global(html[data-theme="dark"] .auth-panel) { color: #e8f3f0; background: #101918; }
|
||||
:global(html[data-theme="dark"] .admin-topbar), :global(html[data-theme="dark"] .setup-card), :global(html[data-theme="dark"] .login-card), :global(html[data-theme="dark"] .settings-card), :global(html[data-theme="dark"] .readonly-card), :global(html[data-theme="dark"] .overview-card), :global(html[data-theme="dark"] input), :global(html[data-theme="dark"] textarea) { color: #e8f3f0; background: #172321; border-color: #30413d; }
|
||||
:global(html[data-theme="dark"] .admin-topbar), :global(html[data-theme="dark"] .settings-card), :global(html[data-theme="dark"] .readonly-card), :global(html[data-theme="dark"] .overview-card) { border-color: #30413d; }
|
||||
:global(html[data-theme="dark"] .admin-topbar h1), :global(html[data-theme="dark"] .page-heading h2), :global(html[data-theme="dark"] .settings-card h3), :global(html[data-theme="dark"] .readonly-card h3), :global(html[data-theme="dark"] .overview-card h3), :global(html[data-theme="dark"] .login-card h1) { color: #e8f3f0; }
|
||||
:global(html[data-theme="dark"] .page-heading p), :global(html[data-theme="dark"] .admin-topbar small), :global(html[data-theme="dark"] label > span) { color: #9bb0aa; }
|
||||
:global(html[data-theme="dark"] .metric-grid article), :global(html[data-theme="dark"] .readonly-card dl div), :global(html[data-theme="dark"] .overview-card dl div), :global(html[data-theme="dark"] .event-list li) { background: #202f2c; border-color: #30413d; }
|
||||
:global(html[data-theme="dark"] .admin-topbar button), :global(html[data-theme="dark"] .admin-topbar .language-select), :global(html[data-theme="dark"] .language-link), :global(html[data-theme="dark"] .home-link) { color: #a9d9d1; background: #203531; border-color: #38564f; }
|
||||
@media (prefers-color-scheme: dark) { :global(html[data-theme="system"] .admin-root), :global(html[data-theme="system"] .login-page), :global(html[data-theme="system"] .auth-panel) { color: #e8f3f0; background: #101918; } :global(html[data-theme="system"] .admin-topbar), :global(html[data-theme="system"] .setup-card), :global(html[data-theme="system"] .login-card), :global(html[data-theme="system"] .settings-card), :global(html[data-theme="system"] .readonly-card), :global(html[data-theme="system"] .overview-card) { background: #172321; border-color: #30413d; } }
|
||||
.operations-grid{display:grid;grid-template-columns:minmax(0,1.12fr) minmax(340px,.88fr);gap:18px}.system-notice{display:flex;align-items:center;gap:8px;margin-bottom:18px}.operation-card{min-width:0;padding:22px;background:#fff;border:1px solid #dfe8e5;border-radius:14px}.operation-card header{display:flex;align-items:flex-start;justify-content:space-between;gap:15px}.operation-card h3{margin:0;font-size:15px}.operation-card header p{margin:5px 0 0;color:#7e8c88;font-size:10px;line-height:1.5}.operation-card header>strong{color:#087d74;font-size:22px}.table-wrap{margin:18px -22px -22px;overflow:auto;border-top:1px solid #edf1ef}.table-wrap table{width:100%;min-width:600px;border-collapse:collapse;text-align:left}.table-wrap th,.table-wrap td{padding:12px 14px;border-bottom:1px solid #edf1ef;font-size:11px;white-space:nowrap}.table-wrap th{color:#83928d;font-size:10px;font-weight:700}.table-wrap td strong,.table-wrap td small{display:block}.table-wrap td small{margin-top:3px;color:#8a9994;font-size:9px}.state-pill{display:inline-flex;padding:4px 7px;color:#236c63;background:#e5f5f1;border-radius:99px;font-size:10px;font-weight:700}.state-pill.expired,.state-pill.exhausted,.state-pill.revoked{color:#8b6259;background:#f8ece9}.danger-button,.text-danger{color:#a34f48;background:#fff0ee;border:1px solid #f1d2cd;border-radius:7px;font-size:10px;font-weight:700;cursor:pointer}.danger-button{padding:7px 9px}.text-danger{padding:4px 7px;border:0}.danger-button:disabled{opacity:.55;cursor:wait}.operation-empty{display:grid;place-items:center;gap:8px;min-height:130px;color:#8b9994;text-align:center;font-size:11px}.operation-empty .ui-icon{color:#72afa7}.invite-form{display:grid;gap:14px;margin-top:18px}.invite-form-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px}.field-help{margin-top:-8px;color:#899792;font-size:10px}.generated-invite{display:grid;gap:8px;margin-top:17px;padding:12px;color:#29685f;background:#eaf7f3;border-radius:9px}.generated-invite strong{font-size:11px}.generated-invite small{color:#648780;font-size:9px;line-height:1.45}.generated-link{display:flex;gap:6px}.generated-link input{height:36px;min-width:0;padding:8px;font-size:10px}.generated-link .secondary-button{min-height:36px;padding-inline:9px;white-space:nowrap;font-size:10px}.invite-list{display:grid;gap:9px;margin-top:18px;padding-top:15px;border-top:1px solid #edf1ef}.invite-row{display:flex;align-items:center;justify-content:space-between;gap:9px;padding:10px;background:#f6f9f8;border-radius:9px}.invite-row>div:first-child{min-width:0}.invite-row strong,.invite-row small{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.invite-row strong{font-size:11px}.invite-row small{max-width:260px;margin-top:4px;color:#86958f;font-size:9px}.invite-row-meta{display:flex;align-items:center;gap:7px;flex:none;color:#70827b;font-size:9px}.lower-operations{margin-top:18px}.text-link{color:#087d74;font-size:10px;font-weight:700;text-decoration:none;white-space:nowrap}.diagnostic-list{display:grid;grid-template-columns:1fr 1fr;gap:9px;margin:18px 0}.diagnostic-list div{padding:10px;background:#f6f9f8;border-radius:8px}.diagnostic-list dt{color:#8a9893;font-size:9px}.diagnostic-list dd{margin:4px 0 0;overflow:hidden;font-size:11px;font-weight:700;text-overflow:ellipsis;white-space:nowrap}.logs-card{display:flex;min-height:250px;flex-direction:column}.audit-card{min-height:250px}.muted-label{color:#9aa6a2;font-size:9px}.log-list{display:grid;gap:7px;max-height:280px;margin-top:16px;overflow:auto}.log-row{display:flex;align-items:flex-start;gap:8px;padding:8px;background:#f6f9f8;border-radius:7px}.log-row>div{min-width:0}.log-row strong,.log-row small{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.log-row strong{font-size:10px}.log-row small{margin-top:4px;color:#899792;font-size:8px}.log-level{flex:none;padding:3px 5px;border-radius:4px;color:#356c62;background:#e3f3ef;font-size:8px;font-weight:800}.log-level.warn{color:#8b6a3e;background:#fbf1dc}.log-level.error,.log-level.fatal{color:#a34f48;background:#fff0ee}
|
||||
:global(:root[data-theme="dark"]) .operation-card,:global(:root[data-theme="dark"]) .invite-row,:global(:root[data-theme="dark"]) .diagnostic-list div,:global(:root[data-theme="dark"]) .log-row{color:#e8f3f0;background:#202f2c;border-color:#30413d}:global(:root[data-theme="dark"]) .table-wrap{border-color:#30413d}:global(:root[data-theme="dark"]) .table-wrap th,:global(:root[data-theme="dark"]) .table-wrap td,:global(:root[data-theme="dark"]) .invite-list{border-color:#30413d}:global(:root[data-theme="dark"]) .operation-card header p,:global(:root[data-theme="dark"]) .table-wrap th,:global(:root[data-theme="dark"]) .table-wrap td small,:global(:root[data-theme="dark"]) .invite-row small{color:#9bb0aa}
|
||||
:global(html[data-theme="dark"] .connection-row),:global(html[data-theme="dark"] .connection-history-heading){color:#e8f3f0;background:#202f2c;border-color:#30413d}
|
||||
:global(html[data-theme="dark"] .operation-card),:global(html[data-theme="dark"] .invite-row),:global(html[data-theme="dark"] .diagnostic-list div),:global(html[data-theme="dark"] .log-row){color:#e8f3f0;background:#202f2c;border-color:#30413d}:global(html[data-theme="dark"] .table-wrap){border-color:#30413d}:global(html[data-theme="dark"] .table-wrap th),:global(html[data-theme="dark"] .table-wrap td),:global(html[data-theme="dark"] .invite-list){border-color:#30413d}:global(html[data-theme="dark"] .operation-card header p),:global(html[data-theme="dark"] .table-wrap th),:global(html[data-theme="dark"] .table-wrap td small),:global(html[data-theme="dark"] .invite-row small){color:#9bb0aa}
|
||||
@media(max-width:850px){.operations-grid{grid-template-columns:1fr}.operation-wide{overflow:hidden}}
|
||||
@media(max-width:520px){.operation-card{padding:18px}.table-wrap{margin-left:-18px;margin-right:-18px;margin-bottom:-18px}.invite-form-grid,.diagnostic-list{grid-template-columns:1fr}.generated-link{display:grid}.invite-row{align-items:flex-start;flex-direction:column}.invite-row-meta{width:100%;justify-content:flex-end}.lower-operations{margin-top:14px}}
|
||||
.target-fields{display:grid;grid-template-columns:minmax(0,1fr) 132px;gap:12px}
|
||||
@@ -607,11 +770,11 @@ async function parseResponse(response: Response) { const value = await response.
|
||||
.modal-icon{display:grid;place-items:center;width:38px;height:38px;color:#087d74;background:#e3f5f0;border-radius:11px}
|
||||
.modal-card h2{margin:16px 0 8px;font-size:20px}
|
||||
.modal-card p{margin:0 0 20px;color:#71817c;font-size:12px;line-height:1.7}
|
||||
:global(:root[data-theme="dark"]) .webrtc-port-fields{background:#202f2c;border-color:#30413d}
|
||||
:global(:root[data-theme="dark"]) .port-fields-heading small{color:#9bb0aa}
|
||||
:global(:root[data-theme="dark"]) .port-inputs input:disabled{color:#9bb0aa;background:#263a35;border-color:#3a514b}
|
||||
:global(:root[data-theme="dark"]) .modal-card{color:#e8f3f0;background:#172321;border-color:#30413d}
|
||||
:global(:root[data-theme="dark"]) .modal-card p{color:#9bb0aa}
|
||||
:global(html[data-theme="dark"] .webrtc-port-fields){background:#202f2c;border-color:#30413d}
|
||||
:global(html[data-theme="dark"] .port-fields-heading small){color:#9bb0aa}
|
||||
:global(html[data-theme="dark"] .port-inputs input:disabled){color:#9bb0aa;background:#263a35;border-color:#3a514b}
|
||||
:global(html[data-theme="dark"] .modal-card){color:#e8f3f0;background:#172321;border-color:#30413d}
|
||||
:global(html[data-theme="dark"] .modal-card p){color:#9bb0aa}
|
||||
@media(max-width:520px){.advanced-card{grid-column:auto}.port-inputs{grid-template-columns:1fr}}
|
||||
|
||||
/* Server settings are a short form, not a set of independent data feeds.
|
||||
@@ -670,8 +833,32 @@ async function parseResponse(response: Response) { const value = await response.
|
||||
.logs-card .log-row{min-width:0}
|
||||
.logs-card .log-row strong,.logs-card .log-row small{overflow-wrap:anywhere;white-space:normal;word-break:break-word}
|
||||
|
||||
.connection-list{display:grid;gap:7px;max-height:180px;margin-top:12px;overflow-y:auto}
|
||||
.connection-history-heading{display:grid;gap:3px;padding:0 0 6px;border-bottom:1px solid #edf1ef}
|
||||
.connection-history-heading strong{font-size:10px}
|
||||
.connection-history-heading small{color:#899792;font-size:8px}
|
||||
.connection-row{display:flex;align-items:flex-start;justify-content:space-between;gap:10px;padding:8px;background:#f6f9f8;border-radius:7px}
|
||||
.connection-person,.connection-detail{min-width:0}
|
||||
.connection-person{flex:1 1 auto}
|
||||
.connection-person strong,.connection-person small,.connection-detail small{display:block;overflow-wrap:anywhere;word-break:break-word}
|
||||
.connection-person strong{font-size:10px}
|
||||
.connection-person small{margin-top:3px;color:#899792;font-size:8px}
|
||||
.connection-detail{display:grid;flex:0 1 58%;justify-items:end;gap:2px;text-align:right}
|
||||
.connection-detail small{color:#899792;font-size:8px}
|
||||
.connection-status{display:inline-flex;padding:3px 6px;border-radius:999px;color:#236c63;background:#e3f3ef;font-size:8px;font-weight:800}
|
||||
.connection-status.disconnected{color:#687a74;background:#e9efed}
|
||||
.connection-status.failed{color:#a34f48;background:#fff0ee}
|
||||
.connection-status.connecting{color:#8b6a3e;background:#fbf1dc}
|
||||
|
||||
@media(max-width:520px){
|
||||
.connection-row{display:grid;gap:7px}
|
||||
.connection-detail{justify-items:start;text-align:left}
|
||||
}
|
||||
|
||||
.login-actions{display:flex;align-items:center;justify-content:center;gap:12px;margin-top:20px;flex-wrap:wrap}
|
||||
.login-actions .language-link{margin-top:0}
|
||||
.home-link{display:inline-flex;align-items:center;gap:6px;padding:8px 12px;color:#08766e;background:#e4f3ef;border:1px solid #cae7e0;border-radius:8px;font-size:11px;font-weight:700;text-decoration:none}
|
||||
.home-link:hover{background:#d8eee9}
|
||||
.language-link{margin-top:20px!important;padding:0!important;background:transparent!important;border:0!important;border-radius:0!important}
|
||||
.login-actions .language-link{margin-top:0!important}
|
||||
</style>
|
||||
@@ -2,7 +2,7 @@
|
||||
<div class="demo-page">
|
||||
<header class="demo-header">
|
||||
<div class="demo-brand"><span><Icon name="waveform" :size="21" /></span><div><strong>WebSpeak</strong><small>{{ copy.browserClient }}</small></div></div>
|
||||
<div class="demo-tools"><span class="demo-badge">{{ copy.demoBadge }}</span><button type="button" @click="toggleLanguage">{{ copy.languageSwitch }}</button><a href="/">{{ copy.back }}</a></div>
|
||||
<div class="demo-tools"><span class="demo-badge">{{ copy.demoBadge }}</span><LanguageSwitcher v-model="language" :menu-label="copy.languageMenu" @change="persistLanguage" /><a href="/">{{ copy.back }}</a></div>
|
||||
</header>
|
||||
|
||||
<div v-if="reconnecting" class="demo-reconnect" role="status"><Icon name="refresh" :size="17" /><span>{{ copy.reconnecting }}</span><button type="button" @click="reconnecting = false">{{ copy.restore }}</button></div>
|
||||
@@ -34,12 +34,14 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from "vue";
|
||||
import Icon from "../components/Icon.vue";
|
||||
import LanguageSwitcher from "../components/LanguageSwitcher.vue";
|
||||
|
||||
type Language = "zh" | "en";
|
||||
type Language = "zh" | "en" | "de";
|
||||
interface DemoMessage { id: number; author: string; time: string; text: string; zhText?: string; enText?: string; mine: boolean }
|
||||
type Tab = "channel" | "server";
|
||||
const language = ref<Language>(localStorage.getItem("webspeak:language") === "en" ? "en" : "zh");
|
||||
const copy = computed(() => language.value === "zh" ? zh : en);
|
||||
const storedLanguage = localStorage.getItem("webspeak:language");
|
||||
const language = ref<Language>(storedLanguage === "en" || storedLanguage === "de" ? storedLanguage : "zh");
|
||||
const copy = computed(() => language.value === "zh" ? zh : language.value === "de" ? de : en);
|
||||
const selectedChannelId = ref("quiet");
|
||||
const activeTab = ref<Tab>("channel");
|
||||
const speakingId = ref("illusia");
|
||||
@@ -56,13 +58,14 @@ const messages = ref<DemoMessage[]>([
|
||||
{ id: 1, author: "illusia", time: "10:24", text: "", zhText: "大家好,欢迎来到 WebSpeak。", enText: "Hello everyone, welcome to WebSpeak.", mine: true },
|
||||
{ id: 2, author: "msicbot", time: "10:25", text: "", zhText: "语音和文字频道都已同步。", enText: "Voice and text channels are in sync.", mine: false },
|
||||
]);
|
||||
const zh = { browserClient: "浏览器语音工作台", demoBadge: "演示 — 模拟数据", languageSwitch: "English", back: "返回主页", reconnecting: "连接中断,正在恢复…", restore: "恢复连接", channels: "频道", channel: "频道", simulated: "演示状态", heroLead: "这里展示 WebSpeak 的频道、语音和聊天交互。", online: "人在线", voiceActivity: "语音活动", speakingNow: "正在语音中", speaking: "正在说话…", connected: "已连接", textChannel: "文字频道", chat: "聊天", server: "服务器", emptyChat: "暂无消息", placeholder: "发送一条消息…", voice: "语音", simulationControls: "模拟控制", stopSpeaking: "停止说话", simulateSpeaking: "模拟发言", poke: "戳一戳", simulateReconnect: "模拟重连", demoNote: "此页面不会连接真实 TeamSpeak 服务器。", you: "你", ready: "已就绪", pokedYou: "戳了你一下" };
|
||||
const en = { browserClient: "Browser voice workspace", demoBadge: "Demo — simulated data", languageSwitch: "中文", back: "Back home", reconnecting: "Connection interrupted, recovering…", restore: "Restore", channels: "Channels", channel: "Channel", simulated: "Simulation", heroLead: "A preview of WebSpeak channels, voice, and chat interactions.", online: "online", voiceActivity: "VOICE ACTIVITY", speakingNow: "Speaking now", speaking: "Speaking…", connected: "Connected", textChannel: "TEXT CHANNEL", chat: "chat", server: "Server", emptyChat: "No messages yet", placeholder: "Send a message…", voice: "Voice", simulationControls: "Simulation controls", stopSpeaking: "Stop speaking", simulateSpeaking: "Simulate speaking", poke: "Poke", simulateReconnect: "Simulate reconnect", demoNote: "This page never connects to a real TeamSpeak server.", you: "You", ready: "Ready", pokedYou: "poked you" };
|
||||
const zh = { languageMenu: "语言", browserClient: "浏览器语音工作台", demoBadge: "演示 — 模拟数据", languageSwitch: "English", back: "返回主页", reconnecting: "连接中断,正在恢复…", restore: "恢复连接", channels: "频道", channel: "频道", simulated: "演示状态", heroLead: "这里展示 WebSpeak 的频道、语音和聊天交互。", online: "人在线", voiceActivity: "语音活动", speakingNow: "正在语音中", speaking: "正在说话…", connected: "已连接", textChannel: "文字频道", chat: "聊天", server: "服务器", emptyChat: "暂无消息", placeholder: "发送一条消息…", voice: "语音", simulationControls: "模拟控制", stopSpeaking: "停止说话", simulateSpeaking: "模拟发言", poke: "戳一戳", simulateReconnect: "模拟重连", demoNote: "此页面不会连接真实 TeamSpeak 服务器。", you: "你", ready: "已就绪", pokedYou: "戳了你一下" };
|
||||
const en = { languageMenu: "Language", browserClient: "Browser voice workspace", demoBadge: "Demo — simulated data", languageSwitch: "中文", back: "Back home", reconnecting: "Connection interrupted, recovering…", restore: "Restore", channels: "Channels", channel: "Channel", simulated: "Simulation", heroLead: "A preview of WebSpeak channels, voice, and chat interactions.", online: "online", voiceActivity: "VOICE ACTIVITY", speakingNow: "Speaking now", speaking: "Speaking…", connected: "Connected", textChannel: "TEXT CHANNEL", chat: "chat", server: "Server", emptyChat: "No messages yet", placeholder: "Send a message…", voice: "Voice", simulationControls: "Simulation controls", stopSpeaking: "Stop speaking", simulateSpeaking: "Simulate speaking", poke: "Poke", simulateReconnect: "Simulate reconnect", demoNote: "This page never connects to a real TeamSpeak server.", you: "You", ready: "Ready", pokedYou: "poked you" };
|
||||
const de = { languageMenu: "Sprache", browserClient: "Sprachbereich im Browser", demoBadge: "Demo — simulierte Daten", languageSwitch: "中文", back: "Zur Startseite", reconnecting: "Verbindung unterbrochen, Wiederherstellung…", restore: "Wiederherstellen", channels: "Kanäle", channel: "Kanal", simulated: "Simulation", heroLead: "Eine Vorschau auf Kanäle, Sprache und Chat von WebSpeak.", online: "online", voiceActivity: "SPRACHAKTIVITÄT", speakingNow: "Spricht gerade", speaking: "Spricht…", connected: "Verbunden", textChannel: "TEXTKANAL", chat: "Chat", server: "Server", emptyChat: "Noch keine Nachrichten", placeholder: "Nachricht senden…", voice: "Sprache", simulationControls: "Simulation steuern", stopSpeaking: "Sprechen stoppen", simulateSpeaking: "Sprechen simulieren", poke: "Anstupsen", simulateReconnect: "Verbindung simulieren", demoNote: "Diese Seite verbindet sich nie mit einem echten TeamSpeak-Server.", you: "Du", ready: "Bereit", pokedYou: "hat dich angestupst" };
|
||||
const tabs = computed(() => [{ id: "channel" as const, label: copy.value.channel }, { id: "server" as const, label: copy.value.server }]);
|
||||
const selectedChannel = computed(() => channels.find((channel) => channel.id === selectedChannelId.value) ?? channels[0]);
|
||||
const visibleMessages = computed(() => activeTab.value === "channel" ? messages.value : []);
|
||||
|
||||
function toggleLanguage() { language.value = language.value === "zh" ? "en" : "zh"; localStorage.setItem("webspeak:language", language.value); }
|
||||
function persistLanguage() { localStorage.setItem("webspeak:language", language.value); }
|
||||
function selectChannel(id: string) { selectedChannelId.value = id; activeTab.value = "channel"; }
|
||||
function toggleSpeaking() { speakingId.value = speakingId.value ? "" : selectedChannel.value.members[0]?.id ?? ""; }
|
||||
function messageText(message: DemoMessage): string { return language.value === "zh" ? message.zhText ?? message.text : message.enText ?? message.text; }
|
||||
@@ -90,5 +93,5 @@ function avatarStyle(name: string) { let hash = 0; for (const char of name) hash
|
||||
:global(:root[data-theme="dark"]) .demo-message p, :global(:root[data-theme="dark"]) .demo-composer, :global(:root[data-theme="dark"]) .demo-actions-panel > button { background: #202f2c; color: #d7e7e3; }
|
||||
:global(:root[data-theme="dark"]) .demo-chat-head, :global(:root[data-theme="dark"]) .demo-user { border-color: #30413d; }
|
||||
@media (prefers-color-scheme: dark) { :global(:root[data-theme="system"]) .demo-channel-panel, :global(:root[data-theme="system"]) .demo-actions-panel, :global(:root[data-theme="system"]) .demo-main, :global(:root[data-theme="system"]) .demo-voice-card { background: #172321; border-color: #30413d; } }
|
||||
:global(button:focus-visible), :global(a:focus-visible), :global(input:focus-visible) { outline: 3px solid #69d2c7; outline-offset: 2px; }
|
||||
:global(button:focus-visible), :global(a:focus-visible), :global(input:focus-visible), :global(select:focus-visible) { outline: 3px solid #69d2c7; outline-offset: 2px; }
|
||||
</style>
|
||||