mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-01 02:52:49 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
556084233d | ||
|
|
c38239ec35 | ||
|
|
21041346e3 | ||
|
|
7320aa3bb5 | ||
|
|
d9b8ea625a | ||
|
|
2323e22fef | ||
|
|
b5f8f01301 | ||
|
|
e964ff460e | ||
|
|
21d8d9c3bc | ||
|
|
169cf88306 | ||
|
|
059435f4cb | ||
|
|
4d4d4cdeb1 | ||
|
|
d42e7a033c | ||
|
|
0986c65551 | ||
|
|
694f864d36 | ||
|
|
512854ab9f | ||
|
|
b298496911 | ||
|
|
b6367e2645 | ||
|
|
b0fa4bf5d0 | ||
|
|
cb3dbe4ca4 | ||
|
|
96ba467d52 | ||
|
|
20fdcc7b1d | ||
|
|
feea39a81c | ||
|
|
69d1653f99 | ||
|
|
a18a5b4920 | ||
|
|
343dd84132 | ||
|
|
a037962cc1 | ||
|
|
680ce246fd | ||
|
|
baa09ad38c | ||
|
|
767bdea018 | ||
|
|
83a8fd0d5a | ||
|
|
e14ddc9465 | ||
|
|
7feb97d77d | ||
|
|
434360cda9 | ||
|
|
d0a2e9edc0 | ||
|
|
61f66ab319 | ||
|
|
e79ad66e1f | ||
|
|
522fa8f409 | ||
|
|
c7def28a8f | ||
|
|
d6c8ccb73f | ||
|
|
ab5851935c | ||
|
|
5c3d1b7e5d | ||
|
|
ecff06e9a1 | ||
|
|
9c3f09b55b | ||
|
|
b42c455e7f | ||
|
|
40ea30b9e2 | ||
|
|
a4cf5b5359 | ||
|
|
1d41d5a3e7 | ||
|
|
46b190a913 | ||
|
|
8abd2d6228 | ||
|
|
7ff6836a7e | ||
|
|
a6187c18af | ||
|
|
8ab2fbe8ea | ||
|
|
3e7674c94f | ||
|
|
30c0d09a33 | ||
|
|
d9904fa154 | ||
|
|
afbbd1e2d4 | ||
|
|
adca8cc1db |
No files matched your search
@@ -9,7 +9,7 @@ on:
|
||||
version:
|
||||
description: Release version without the v prefix
|
||||
required: true
|
||||
default: 0.1.1
|
||||
default: 0.1.3
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
@@ -34,7 +34,11 @@ jobs:
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
$releaseVersion = $env:RELEASE_REF -replace '^v', ''
|
||||
npm ci --no-audit --no-fund
|
||||
npm ci --ignore-scripts --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
npm run prepare:sdk
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
npm --prefix web ci --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
@@ -130,7 +134,9 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
release_version="${RELEASE_REF#v}"
|
||||
npm ci --no-audit --no-fund
|
||||
npm ci --ignore-scripts --no-audit --no-fund
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
|
||||
npm --prefix web ci --no-audit --no-fund
|
||||
current_version="$(node -p "require('./package.json').version")"
|
||||
if [ "$current_version" != "$release_version" ]; then
|
||||
|
||||
@@ -22,7 +22,9 @@ jobs:
|
||||
web/package-lock.json
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
npm ci --no-audit --no-fund
|
||||
npm ci --ignore-scripts --no-audit --no-fund
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
|
||||
npm --prefix web ci --no-audit --no-fund
|
||||
- name: Test and build
|
||||
run: |
|
||||
|
||||
@@ -1,7 +1,73 @@
|
||||
# Changelog
|
||||
|
||||
## [0.1.6] — 2026-09-04
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增保持身份并发连接提醒,避免同一浏览器复用身份造成连接卡住。
|
||||
- 新增桌面端伴奏共享功能。
|
||||
- 新增网站 favicon,并更新仓库 README 主视觉。
|
||||
|
||||
### English
|
||||
|
||||
- Added a warning for concurrent remembered-identity connections in the same browser.
|
||||
- Added desktop accompaniment sharing.
|
||||
- Added a site favicon and refreshed the repository README branding.
|
||||
|
||||
## [0.1.5] — 2026-09-04
|
||||
|
||||
### 中文
|
||||
|
||||
- 修复并优化主题切换按钮,首次点击即可切换,并使用太阳/月亮图标。
|
||||
- 修复浏览器身份保存与退出后的保持逻辑。
|
||||
|
||||
### English
|
||||
|
||||
- Fixed and refined the theme toggle so the first click switches themes, with sun/moon icons.
|
||||
- Fixed browser identity persistence across exit and return.
|
||||
|
||||
All notable changes to WebSpeak are documented here. Versions follow SemVer.
|
||||
|
||||
## [0.1.4] — 2026-09-03
|
||||
|
||||
### 中文
|
||||
|
||||
- 修复 WebRTC 语音收发与发言状态同步。
|
||||
- 修复频道文字消息在 WebSpeak 客户端之间无法互收。
|
||||
- 优化管理员页面、运行日志换行和移动端顶部布局。
|
||||
- 首页新增 Bilibili 入口,管理员登录页新增返回首页。
|
||||
|
||||
### English
|
||||
|
||||
- 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 the Bilibili profile link and the admin-login home link.
|
||||
|
||||
## [0.1.3] — 2026-09-03
|
||||
|
||||
### Added
|
||||
|
||||
- Optional WebRTC audio transport for deployments that need lower and more stable realtime voice latency.
|
||||
- A self-contained WebRTC media service controlled by one administrator switch; the gateway derives the media host from the current WebSpeak address and owns a fixed UDP range.
|
||||
- Migrated the TeamSpeak integration to the maintained `EchoSixHIYA/teamspeak-js` fork, including live directory snapshots and member/channel synchronization.
|
||||
|
||||
### Changed
|
||||
|
||||
- WebRTC audio uses negotiated Opus parameters and a bounded newest-frame mixer instead of allowing stale audio to accumulate.
|
||||
- The browser keeps the WebSocket path available for signaling, control, and compatibility fallback; Docker Compose publishes the built-in `40000–40099/UDP` media range alongside the web port.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Prevented duplicate playback when WebRTC and the WebSocket audio path overlap during negotiation or fallback.
|
||||
- Made WebRTC teardown and fallback explicit so a failed negotiation does not leave a server-side media session behind.
|
||||
- Corrected native Opus decoder usage and cleaned up negotiated payload handling for TeamSpeak-to-browser audio.
|
||||
|
||||
### Verification
|
||||
|
||||
- After allowing inbound `40000–40099/UDP` on the public WebSpeak host, two browser sessions were tested against the same TeamSpeak target with WebRTC enabled: audio frames flowed in both directions, packet drops remained at `0`, ingress frame gaps peaked at about `27 ms`, and egress gaps peaked at about `81–83 ms`.
|
||||
- The measured WebRTC path stayed below the previous WebSocket jitter peaks of about `268–376 ms` in the same browser test setup; these figures describe the observed test path, not a universal latency guarantee.
|
||||
|
||||
## [0.1.2] — 2026-09-02
|
||||
|
||||
### Added
|
||||
@@ -20,6 +86,8 @@ All notable changes to WebSpeak are documented here. Versions follow SemVer.
|
||||
|
||||
- Replaced the visually off-center settings glyph and normalized icon alignment for settings-related controls across the client.
|
||||
- Fixed narrow-screen exit and microphone controls so their text-collapse rules apply correctly.
|
||||
- Bounded browser and gateway voice buffering, reset stale browser playback queues, and exposed low-overhead in-memory audio counters for diagnosing jitter without per-frame log writes.
|
||||
- Moved microphone frame assembly to an `AudioWorklet` with a compatibility fallback to `ScriptProcessorNode`; both paths emit fixed 960-sample frames.
|
||||
|
||||
## [0.1.1] — 2026-09-02
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@ Browser (PCM capture) → WebSocket → Node.js server (PCM→Opus) → TeamSpea
|
||||
Browser (playback) ← WebSocket ← Node.js server (Opus relay) ← TeamSpeak server
|
||||
```
|
||||
|
||||
- Each browser user = one independent TS3 virtual client via `@honeybbq/teamspeak-client`
|
||||
- Frontend captures PCM via `ScriptProcessorNode`, sends as Int16 binary over WebSocket
|
||||
- Each browser user = one independent TS3 virtual client via `@echosixhiya/teamspeak-client`
|
||||
- Frontend captures PCM in an `AudioWorklet` when available (with a `ScriptProcessorNode` fallback), assembles fixed 960-sample frames, and sends Int16 binary over WebSocket
|
||||
- Server encodes PCM → Opus using `@discordjs/opus` (CJS, loaded via `createRequire`)
|
||||
- Server sends Opus to TS via `client.sendVoice(data, codec=4)`
|
||||
- Incoming TS voice → Opus frames → binary WebSocket → browser `AudioDecoder` → playback
|
||||
@@ -30,16 +30,19 @@ src/
|
||||
server/
|
||||
server.ts # Express + HTTPS + WS setup
|
||||
voice-bridge.ts # /ws/voice endpoint, PCM→Opus encoding, WebQuery API
|
||||
ts-client.ts # TS3Client wrapper around @honeybbq/teamspeak-client
|
||||
ts-client.ts # TS3Client wrapper around @echosixhiya/teamspeak-client
|
||||
```
|
||||
|
||||
## Key Technical Details
|
||||
|
||||
### Audio Pipeline
|
||||
1. Browser mic → `getUserMedia` (48kHz mono) → `ScriptProcessorNode` (1024 samples)
|
||||
1. Browser mic → `getUserMedia` (48kHz mono) → `AudioWorklet` frame assembler (960 samples); older browsers use `ScriptProcessorNode` (1024-sample chunks) before the same assembler
|
||||
2. Float32 → Int16 conversion → PTT/VOX gate → WebSocket binary send
|
||||
3. Server accumulates PCM → every 1920 bytes (960 samples, 20ms) → `OpusEncoder.encode()` → `tsClient.sendVoice(opus, 4)`
|
||||
3. Server encodes each 1920-byte (960-sample, 20ms) PCM frame → `OpusEncoder.encode()` → `tsClient.sendVoice(opus, 4)`
|
||||
4. Incoming: TS → `voiceData` event → 3-byte header `[codec][clientId BE]` → WS binary → browser `AudioDecoder` → playback
|
||||
5. Browser uplink is capped at 10 PCM frames (about 200ms); gateway egress applies a bounded WebSocket byte guard; browser playback resets stale decoder/source queues above 120ms.
|
||||
|
||||
Audio flow counters are kept in memory and exposed in admin session summaries. Do not add per-frame persistent logging to the voice path.
|
||||
|
||||
### CJS Interop
|
||||
`@discordjs/opus` is CommonJS, loaded via:
|
||||
|
||||
+6
-5
@@ -2,14 +2,15 @@ FROM node:22-bookworm-slim AS build
|
||||
|
||||
WORKDIR /app
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends python3 make g++ \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates git python3 make g++ \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
COPY web/package.json web/package-lock.json ./web/
|
||||
# The root postinstall hook patches the TeamSpeak SDK during npm ci.
|
||||
COPY scripts ./scripts
|
||||
RUN npm ci
|
||||
RUN npm ci --ignore-scripts --no-audit --no-fund
|
||||
COPY scripts/prepare-sdk.mjs ./scripts/prepare-sdk.mjs
|
||||
RUN npm run prepare:sdk
|
||||
RUN npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
|
||||
RUN npm --prefix web ci
|
||||
|
||||
COPY . .
|
||||
@@ -37,7 +38,7 @@ COPY --from=build --chown=node:node /app/web/dist ./web/dist
|
||||
|
||||
USER node
|
||||
VOLUME ["/data"]
|
||||
EXPOSE 3040
|
||||
EXPOSE 3040/tcp 40000-40099/udp
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
||||
CMD node -e "fetch('http://127.0.0.1:3040/health').then(r => { if (!r.ok) process.exit(1) }).catch(() => process.exit(1))"
|
||||
|
||||
|
||||
@@ -2,139 +2,89 @@
|
||||
|
||||
# WebSpeak
|
||||
|
||||
<p>
|
||||
<img src="./仓库图标.png" alt="WebSpeak" width="220">
|
||||
</p>
|
||||
|
||||
**让 TeamSpeak 真正进入浏览器。**
|
||||
|
||||
自托管的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音接入网关。无需安装桌面客户端,打开浏览器即可进入你的语音空间。
|
||||
自托管的 TeamSpeak 3 / TeamSpeak 6 网页客户端。打开网页即可加入语音、查看频道、发送消息,无需安装桌面客户端。
|
||||
|
||||
A self-hosted TeamSpeak 3 / TeamSpeak 6 web client and voice gateway. Join your voice space from a modern browser without installing a desktop client.
|
||||
**在线体验:[webspeak.example.invalid](https://webspeak.example.invalid)**
|
||||
|
||||
[](LICENSE)
|
||||
[](https://nodejs.org/)
|
||||
[](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/)
|
||||
|
||||
**在线 Demo:** [https://webspeak.example.invalid](https://webspeak.example.invalid)
|
||||
|
||||
**[中文](#中文)**<br />
|
||||
[更新日志](#更新日志) · [为什么是 WebSpeak](#为什么是-webspeak) · [核心能力](#核心能力) · [架构](#架构) · [快速开始](#快速开始) · [首次登录与默认目标](#首次登录与默认目标) · [访问模式与邀请](#访问模式与邀请) · [音频与设备](#音频与设备) · [数据与安全边界](#数据与安全边界) · [旧版本升级](#旧版本升级) · [健康检查](#健康检查开发与验证) · [项目结构](#项目结构) · [已知边界](#已知边界) · [社区](#社区)
|
||||
|
||||
**[English](#english)**<br />
|
||||
[Changelog](#changelog) · [Why WebSpeak](#why-webspeak) · [Core capabilities](#core-capabilities) · [Architecture](#architecture) · [Quick Start](#quick-start) · [First login](#first-login-and-default-target) · [Access modes](#access-modes-and-invites) · [Audio](#audio-and-devices) · [Security](#data-and-security-boundary) · [Upgrade](#upgrading-from-a-legacy-version) · [Health](#health-development-and-verification) · [Project layout](#project-layout) · [Known boundaries](#known-boundaries) · [License](#license) · [Community](#community)
|
||||
[中文](#中文) · [English](#english) · [更新日志](#更新日志--changelog) · [快速开始](#快速开始--quick-start) · [社区](#社区--community)
|
||||
|
||||
</div>
|
||||
|
||||
> WebSpeak 是一个面向浏览器的 TeamSpeak 客户端,让频道、成员、文字与语音协作在网页中自然完成。
|
||||
|
||||
> WebSpeak is a browser-based TeamSpeak client that brings channels, members, text chat, and voice collaboration into one web experience.
|
||||
|
||||
## 中文
|
||||
|
||||
### 更新日志
|
||||
WebSpeak 是一个面向 TeamSpeak 服务器的浏览器客户端。部署一次,用户通过网页即可加入语音空间,不需要安装 TeamSpeak 桌面客户端。
|
||||
|
||||
#### 2026-09-02 · v0.1.2
|
||||
### 功能
|
||||
|
||||
- 优化移动端浏览器体验:频道、成员、聊天和语音操作适配窄屏;移动端成员操作提供三个点菜单,桌面端继续使用右键菜单。
|
||||
- 将首页 GitHub 入口改为显眼按钮,并增加当前版本标识和更新日志入口;窄屏时自动收敛为图标,避免按钮文字互相挤占。
|
||||
- 修复设置齿轮图标和相关操作按钮的对齐问题,统一设置、退出、麦克风等控制的触控尺寸与视觉反馈。
|
||||
- 将上一个版本之后的移动端语音控制、闭麦替代按键说话、目标协议自动探测、Docker Compose 简化启动和在线 Demo 文档整理为本次版本内容。
|
||||
- 支持 TeamSpeak 3 和 TeamSpeak 6,自动识别协议。
|
||||
- 浏览频道、在线成员和实时成员状态。
|
||||
- 加入、切换频道,并显示成员所在频道。
|
||||
- 频道文字聊天、服务器消息、私聊和戳一戳。
|
||||
- 浏览器麦克风和扬声器选择、音量调节、输入电平和本地麦克风测试。
|
||||
- 一键闭麦/开麦、VOX 语音激活、发言状态提示。
|
||||
- 可选 WebRTC 低延迟语音,网络不支持时自动回退。
|
||||
- 固定服务器、开放服务器和一次性邀请链接三种访问方式。
|
||||
- 管理控制台:默认目标、邀请链接、在线会话、日志、诊断和数据库备份。
|
||||
- 中英文界面、主题切换、桌面端和移动端适配。
|
||||
- 移动端提供成员操作菜单,桌面端支持右键菜单。
|
||||
|
||||
#### 2026-09-02 · v0.1.1
|
||||
### 快速开始 · Quick Start
|
||||
|
||||
- 汇总并正式发布浏览器客户端、管理员控制台、受控邀请、Session 运维、审计记录、诊断报告和 SQLite 备份能力。
|
||||
- 修复晚进入 WebSpeak 的浏览器会话无法看到先进入成员的问题;连接建立后会完成目录同步,并合并分阶段成员事件。
|
||||
- 修复私聊消息到达后网页端断开连接的问题,完善成员右键菜单、悬停高亮和语音活动状态展示。
|
||||
- 完成中英文界面、默认 TeamSpeak 目标、旧版配置迁移和首次登录强制改密流程。
|
||||
- 移除依赖页面焦点的普通空格键按键说话模式;改为桌面端和移动端均可用的一键闭麦/开麦,静音状态会保存在当前浏览器中。
|
||||
- 闭麦会在上行音频发送前直接阻断声音,同时保留 VOX 语音激活、输入设备选择、音量与阈值调节能力。
|
||||
- 发布流程稳定生成 Windows/Linux 部署包并同步发布 Docker 镜像;Docker 构建会正确处理依赖安装脚本。
|
||||
- 简化 Docker Compose 部署:默认从当前代码构建,自动创建并持久化数据卷,支持通过 `WEBSPEAK_PORT` 修改宿主机端口。
|
||||
#### Docker Compose(推荐)
|
||||
|
||||
#### 2026-08-31 · v0.1.0
|
||||
|
||||
- 首个规范化版本,提供浏览器客户端、TeamSpeak 3 / 6 网关、浏览器音频控制、访问模式、管理员运维能力和 AGPL-3.0-only 许可证。
|
||||
|
||||
### 为什么是 WebSpeak
|
||||
|
||||
| 体验 | WebSpeak 的答案 |
|
||||
| --- | --- |
|
||||
| 加入方式 | 浏览器打开链接即可加入,不安装桌面客户端 |
|
||||
| 兼容性 | 支持 TeamSpeak 3 / TeamSpeak 6,并自动识别协议 |
|
||||
| 连接模型 | HTTPS / WSS 连接 WebSpeak,WebSpeak 连接目标 TeamSpeak |
|
||||
| 入口控制 | 固定目标、开放目标、一次性受控邀请三种路径 |
|
||||
| 语言与主题 | 访客端和管理控制台均支持中英文与主题切换 |
|
||||
|
||||
### 核心能力
|
||||
|
||||
| 领域 | 已提供 |
|
||||
| --- | --- |
|
||||
| 语音 | Opus / PCM 桥接、VOX 语音激活、一键闭麦/开麦、连接状态与重连提示 |
|
||||
| 设备 | 浏览器麦克风与扬声器选择、音量调节、实时输入电平、本地麦克风测试 |
|
||||
| 频道 | 频道树、频道切换、成员移动、频道文字聊天、服务器事件与状态展示 |
|
||||
| 成员 | 在线成员、发言绿色头像边框、Away 状态、私聊、Poke、昵称复制、成员音量 |
|
||||
| 管理 | 默认账号首次登录强制改密、默认 TeamSpeak 目标、站点信息、真实连接测试 |
|
||||
| 运维 | 活动 Session、邀请创建与撤销、审计事件、结构化日志、诊断报告、SQLite 备份 |
|
||||
| 浏览器体验 | 响应式布局、桌面与移动端语音控制、紧凑滚动布局、浏览器本地收藏与最近连接 |
|
||||
|
||||
### 架构
|
||||
|
||||
| 层级 | 职责 | 连接 |
|
||||
| --- | --- | --- |
|
||||
| 浏览器会话 | 昵称、设备、频道、成员、文字和语音交互 | HTTPS / WSS → WebSpeak |
|
||||
| WebSpeak 网关 | 会话管理、访问控制、语音桥接、目录同步、管理控制台 | TeamSpeak 客户端协议 |
|
||||
| TeamSpeak 3 / 6 | 提供频道、成员、文字和语音服务 | 目标地址与语音端口 |
|
||||
|
||||
### 快速开始
|
||||
|
||||
#### 方式 A:Docker Compose(推荐)
|
||||
|
||||
Docker Compose 会直接使用当前目录的 Dockerfile 构建 WebSpeak,自动创建数据卷并启动服务,不需要手动创建镜像或数据卷。
|
||||
要求:安装 Docker Engine 和 Docker Compose。
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose up -d --build
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
查看状态和日志:
|
||||
打开 `http://你的服务器地址:3040/`,首次进入管理后台 `/admin` 使用:
|
||||
|
||||
```text
|
||||
账号:admin
|
||||
密码:admin
|
||||
```
|
||||
|
||||
首次登录必须修改管理员密码。然后在管理控制台的“服务器”页面设置“默认 TeamSpeak 目标”,例如:
|
||||
|
||||
```text
|
||||
203.0.113.10#9987
|
||||
```
|
||||
|
||||
用户欢迎页没有邀请链接参数时,会自动使用管理员设置的默认目标。开放模式下,用户可以自行输入要连接的服务器地址和端口。
|
||||
|
||||
数据会保存在 Docker volume `webspeak-data` 中。升级时执行:
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
curl http://127.0.0.1:3040/health
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
启动完成后打开 [http://127.0.0.1:3040/](http://127.0.0.1:3040/)。首次进入管理后台 `/admin` 使用 `admin / admin`,并按提示修改密码。
|
||||
不要使用 `docker compose down -v`,否则会删除数据库和管理员配置。
|
||||
|
||||
默认数据保存在 Docker volume `webspeak-data` 中。升级代码后再次执行 `docker compose up -d --build` 即可;停止服务使用 `docker compose down`,不要添加 `-v`,否则会删除数据库、密钥和管理员配置。
|
||||
|
||||
WebSpeak 默认对外提供 `3040` 端口。如需修改宿主机端口,只需设置 `WEBSPEAK_PORT`,容器内部端口无需修改:
|
||||
如需更换网页端口:
|
||||
|
||||
```bash
|
||||
WEBSPEAK_PORT=3041 docker compose up -d --build
|
||||
WEBSPEAK_PORT=3041 docker compose up -d
|
||||
```
|
||||
|
||||
#### 方式 B:Dockerfile 手动运行(可选)
|
||||
#### 源码运行
|
||||
|
||||
```bash
|
||||
docker build -t webspeak:local .
|
||||
docker volume create webspeak-data
|
||||
docker run -d \
|
||||
--name webspeak \
|
||||
--restart unless-stopped \
|
||||
-p 3040:3040 \
|
||||
-v webspeak-data:/data \
|
||||
webspeak:local
|
||||
```
|
||||
|
||||
容器内部监听 `3040`,SQLite 数据库、安装级主密钥和日志保存在 `/data`。手动运行时也请保留 `webspeak-data:/data` 数据卷。
|
||||
|
||||
#### 方式 C:源码运行
|
||||
|
||||
环境要求:
|
||||
|
||||
- Node.js `22.5.0` 或更高版本。
|
||||
- `@discordjs/opus` 所需的原生编译工具;Linux 通常需要 `python3`、`make`、`g++`。
|
||||
- 一台可访问的 TeamSpeak 3 或 TeamSpeak 6 服务端。
|
||||
- 较新的 Chrome 或 Edge;生产环境建议使用 HTTPS。
|
||||
需要 Node.js `22.5.0` 或更高版本,以及 `@discordjs/opus` 所需的本地编译工具。
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
@@ -144,134 +94,89 @@ npm run build
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
随后打开:
|
||||
服务默认监听 `3040` 端口。
|
||||
|
||||
```text
|
||||
http://127.0.0.1:3040/
|
||||
```
|
||||
### WebRTC 低延迟语音
|
||||
|
||||
### 首次登录与默认目标
|
||||
WebRTC 是可选功能,由 WebSpeak 自带,不需要额外部署媒体服务器。
|
||||
|
||||
1. 打开 `/admin`。
|
||||
2. 使用默认账户 `admin / admin` 登录。
|
||||
3. 按页面要求设置一个至少 12 个字符的新管理员密码。
|
||||
4. 在“服务器”页面的“默认 TeamSpeak 目标”中填写服务器地址与语音端口。
|
||||
5. 执行连接测试并保存。
|
||||
1. 在管理后台打开“WebRTC 语音”。
|
||||
2. 在部署主机所在云平台安全组或上游防火墙放行入站 UDP `40000–40099`。
|
||||
3. 重新进入语音空间即可生效。
|
||||
|
||||
欢迎页没有邀请链接目标参数时,会使用管理员设置的默认 TeamSpeak 目标进行预填写。邀请链接参数优先;固定模式下访客只能进入管理员配置的目标,开放模式下访客可以输入经过安全校验的公网目标。
|
||||
|
||||
WebSpeak 的 HTTP 端口固定为 `3040`,TeamSpeak 默认语音端口为 `9987`。目标地址在界面中拆分为“地址”和“语音端口”两个字段;旧版 `地址:端口` 与 `地址#端口` 文本仍可兼容解析。
|
||||
|
||||
### 访问模式与邀请
|
||||
|
||||
| 模式 | 行为 | 适用场景 |
|
||||
| --- | --- | --- |
|
||||
| `fixed` | 访客不改变目标,服务端管理目标与服务器密码 | 私有社区、固定服务器 |
|
||||
| `open` | 访客可输入公网目标与本次会话密码 | 临时接入、多服务器入口 |
|
||||
| 受控邀请 | 管理员生成一次性、可过期、可限次、可撤销链接 | 活动、临时房间、定向分享 |
|
||||
|
||||
开放模式会在 DNS 解析后阻止 loopback、私网、链路本地、组播、广播和保留地址,并使用已验证的 IP 进行实际连接。服务器密码不会写入分享链接、浏览器本地存储或 WebSocket URL。
|
||||
|
||||
### 音频与设备
|
||||
|
||||
进入语音空间后,在设置中可以:
|
||||
|
||||
- 选择浏览器检测到的麦克风与扬声器;
|
||||
- 一键闭麦或开麦;
|
||||
- 调整输入、输出、通知音量与 VOX 阈值;
|
||||
- 查看麦克风权限、实时输入电平和音频上下文状态;
|
||||
- 使用最多 5 秒的本地麦克风测试,录音只在浏览器本地播放,不发送到 TeamSpeak。
|
||||
|
||||
设备标签由浏览器权限模型决定。首次选择设备前,浏览器可能要求授予麦克风权限;输出设备选择依赖浏览器支持,不支持时会明确回退到默认扬声器。
|
||||
|
||||
### 数据与安全边界
|
||||
|
||||
运行数据默认位于 `data/`,Docker 环境默认位于 `/data`:
|
||||
|
||||
```text
|
||||
data/
|
||||
├── webspeak.db SQLite 配置、管理员凭据、邀请与有限审计事件
|
||||
├── master.key 32 字节安装级主密钥
|
||||
└── logs/ 本地轮转日志
|
||||
```
|
||||
|
||||
- 管理员密码使用 Node.js `crypto.scrypt`、随机 salt 与 constant-time compare。
|
||||
- TeamSpeak 服务器密码使用 AES-256-GCM 加密保存,管理 API 不返回明文。
|
||||
- 管理 Session 使用服务端会话、HttpOnly / SameSite Strict Cookie、同源校验与 CSRF token。
|
||||
- 管理登录具有固定窗口限速与失败延迟。
|
||||
- 普通用户 identity 只在当前 Join Ticket / Session 中使用;启用“记住此设备”后,私钥只保存在浏览器 IndexedDB,不上传到网关,也不会进入日志、诊断或数据库。
|
||||
- WebSpeak 不提供身份文件导入/导出界面;清除浏览器本地数据会移除本机记住的身份与偏好。
|
||||
- 日志、诊断报告与 Overview 不返回服务器密码、管理员密码或身份私钥。
|
||||
- 请同时备份 `webspeak.db` 与 `master.key`;只有数据库而没有主密钥时,加密的服务器密码无法恢复。
|
||||
|
||||
### 旧版本升级
|
||||
|
||||
如果升级启动时项目根目录仍有旧 `config.json`,WebSpeak 只做一次性导入:
|
||||
|
||||
- `tsHost`
|
||||
- `tsPort`
|
||||
- `tsServerPassword`
|
||||
|
||||
导入后 `data/webspeak.db` 成为唯一实时配置源;旧文件不会被删除或改写。旧版的 `port`、`tsServerProtocol`、`maxClients` 和 `trustProxy` 不再作为运行配置。
|
||||
|
||||
### 健康检查、开发与验证
|
||||
|
||||
无需认证的健康检查:
|
||||
|
||||
```text
|
||||
GET /health
|
||||
GET /api/health
|
||||
```
|
||||
|
||||
开发命令:
|
||||
Docker Compose 已自动发布 `40000–40099/UDP`,但无法替你修改云安全组。Ubuntu 使用 UFW 时可执行:
|
||||
|
||||
```bash
|
||||
# 后端:固定监听 3040
|
||||
npm run dev
|
||||
|
||||
# 前端:Vite 监听 5173,并将 /api 与 /ws 代理到 3040
|
||||
npm run web:dev
|
||||
|
||||
# 前端生产构建
|
||||
npm --prefix web run build
|
||||
|
||||
# 后端类型检查与构建
|
||||
npm run build
|
||||
|
||||
# 自动化测试
|
||||
npm test
|
||||
|
||||
# 依赖审计
|
||||
npm audit
|
||||
sudo ufw allow 40000:40099/udp
|
||||
```
|
||||
|
||||
`/demo` 是不连接真实 TeamSpeak 的交互式演示页面,仅用于界面预览、录屏和前端回归,不能替代真实 TS3 / TS6 验证。
|
||||
网页和 WSS 使用 TCP `80/443`。TeamSpeak 的 `9987` 只需要让 WebSpeak 主机能够访问目标 TeamSpeak,不需要在 WebSpeak 主机对公网开放。WebRTC 不支持或端口未放行时,客户端会自动使用兼容模式。
|
||||
|
||||
### 项目结构
|
||||
### 管理员设置
|
||||
|
||||
```text
|
||||
src/
|
||||
├── admin/ 管理服务、登录、Session、邀请与运维接口
|
||||
├── persistence/ SQLite schema、repository 与迁移边界
|
||||
├── security/ 主密钥、秘密加密、密码与开放目标策略
|
||||
├── domain/ TeamSpeak 目标地址与端口解析
|
||||
└── server/ TeamSpeak 适配器、Session、票据与语音桥
|
||||
管理员可以在控制台中:
|
||||
|
||||
web/src/
|
||||
├── views/WebClient.vue 访客端、语音空间、聊天与音频设置
|
||||
├── views/AdminView.vue 管理登录、服务器、概览与运维控制台
|
||||
├── composables/ WebSocket 与语音状态
|
||||
└── services/ 主题、本地持久化与目标解析
|
||||
```
|
||||
- 修改默认 TeamSpeak 目标和服务器密码。
|
||||
- 选择固定目标或允许用户自定义目标。
|
||||
- 创建、撤销和设置有效期的邀请链接。
|
||||
- 查看在线会话、运行日志、诊断信息和审计记录。
|
||||
- 下载诊断报告和 SQLite 数据库备份。
|
||||
- 开启或关闭 WebRTC 低延迟语音。
|
||||
|
||||
### 已知边界
|
||||
### 浏览器要求
|
||||
|
||||
- 服务端固定限制最多 100 个活动连接。
|
||||
- 管理员模型目前是单管理员,不提供用户列表、角色或权限管理后台。
|
||||
- 浏览器麦克风权限、HTTPS 与浏览器对音频输出设备的支持会影响最终体验。
|
||||
- TeamSpeak 服务端自身的版本、协议兼容性和网络可达性不由 WebSpeak 代替管理。
|
||||
- 使用较新的 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`
|
||||
|
||||
@@ -279,119 +184,76 @@ QQ群:`869500475`
|
||||
|
||||

|
||||
|
||||
### 许可证
|
||||
|
||||
WebSpeak 使用 [GNU Affero General Public License v3.0](LICENSE) 发布。
|
||||
|
||||
## English
|
||||
|
||||
WebSpeak brings TeamSpeak voice spaces to the browser. It is a self-hosted gateway and web client for TeamSpeak 3 and TeamSpeak 6: open a link, choose a nickname, and join from a modern browser without installing a desktop client.
|
||||
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.
|
||||
|
||||
**Live demo:** [https://webspeak.example.invalid](https://webspeak.example.invalid)
|
||||
**Live demo: [webspeak.example.invalid](https://webspeak.example.invalid)**
|
||||
|
||||
### Changelog
|
||||
### Features
|
||||
|
||||
#### 2026-09-02 · v0.1.2
|
||||
|
||||
- Improved the mobile browser experience across channel, member, chat, and voice surfaces; mobile member actions now use a three-dot menu while desktop keeps the context menu.
|
||||
- Promoted the GitHub entry on the welcome page and added a current-version badge plus a changelog link; narrow layouts collapse text controls into icons to prevent crowding.
|
||||
- Fixed alignment for the settings gear and related controls, with consistent touch sizing and visual treatment for settings, exit, and microphone actions.
|
||||
- Consolidated the post-0.1.1 mobile voice controls, microphone mute replacement for focus-dependent PTT, automatic protocol detection, simplified Docker Compose startup, and live-demo documentation into this release.
|
||||
|
||||
#### 2026-09-02 · v0.1.1
|
||||
|
||||
- Consolidated and officially released the browser client, administrator console, managed invites, session operations, audit records, diagnostics, and SQLite backup support.
|
||||
- Fixed late WebSpeak browser sessions missing members who joined earlier by reconciling the directory after connect and merging staged member events.
|
||||
- Fixed browser sessions disconnecting after receiving a private message, and improved member context menus, hover highlighting, and speaking-state presentation.
|
||||
- Added the bilingual interface, default TeamSpeak target, legacy configuration migration, and mandatory first-login password rotation.
|
||||
- Removed the focus-dependent normal Space-key PTT mode and replaced it with a one-click microphone mute/unmute control on desktop and mobile; the mute state is persisted in the current browser.
|
||||
- Mute now suppresses upstream microphone audio before it is sent, while VOX activation, input-device selection, volume controls, and threshold tuning remain available.
|
||||
- Stabilized release publishing for Windows/Linux packages and the matching Docker image; Docker builds now handle the dependency patch script correctly.
|
||||
- Simplified Docker Compose deployment: it builds from the current checkout, creates and persists the data volume automatically, and supports changing the host port with `WEBSPEAK_PORT`.
|
||||
|
||||
#### 2026-08-31 · v0.1.0
|
||||
|
||||
- First normalized release with the browser client, TeamSpeak 3 / 6 gateway, browser audio controls, access modes, administrator operations, and AGPL-3.0-only licensing.
|
||||
|
||||
### Why WebSpeak
|
||||
|
||||
| Experience | WebSpeak's answer |
|
||||
| --- | --- |
|
||||
| Joining | Open a browser link and join without installing the desktop client |
|
||||
| Compatibility | Supports TeamSpeak 3 and TeamSpeak 6 with automatic protocol detection |
|
||||
| Connection model | The browser connects to WebSpeak over HTTPS / WSS, and WebSpeak connects to TeamSpeak |
|
||||
| Access control | Fixed targets, open targets, and one-time managed invites |
|
||||
| Language and theme | Chinese and English interfaces with theme switching for guests and administrators |
|
||||
|
||||
### Core capabilities
|
||||
|
||||
| Area | Included |
|
||||
| --- | --- |
|
||||
| Voice | Opus / PCM bridging, VOX activation, one-click microphone mute/unmute, connection state, reconnect feedback, and speaking indicators |
|
||||
| Devices | Browser microphone and speaker selection, volume controls, live input level, and a local microphone test |
|
||||
| Channels | Channel tree, channel switching, member movement, channel text chat, server events, and status display |
|
||||
| Members | Online members, green speaking borders, Away state, private messages, Poke, nickname copy, and per-member volume |
|
||||
| Administration | Mandatory first-login password rotation, default TeamSpeak target, site information, and real connection tests |
|
||||
| Operations | Active sessions, invite creation and revocation, audit events, structured logs, diagnostics, and SQLite backup |
|
||||
| Browser experience | Responsive layouts, desktop and mobile voice controls, compact scrolling regions, local favorites, and recent connections |
|
||||
|
||||
### Architecture
|
||||
|
||||
| Layer | Responsibility | Connection |
|
||||
| --- | --- | --- |
|
||||
| Browser session | Nickname, device, channel, member, text, and voice interactions | HTTPS / WSS → WebSpeak |
|
||||
| WebSpeak gateway | Session management, access control, voice bridging, directory synchronization, and admin console | TeamSpeak client protocol |
|
||||
| TeamSpeak 3 / 6 | Channel, member, text, and voice services | Configured host and voice port |
|
||||
- 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.
|
||||
|
||||
### Quick Start
|
||||
|
||||
#### Option A: Docker Compose (recommended)
|
||||
#### Docker Compose (recommended)
|
||||
|
||||
Docker Compose builds WebSpeak from the Dockerfile in the current checkout, creates the persistent data volume automatically, and starts the service without a separate image-pull or volume-creation step.
|
||||
Requirements: Docker Engine and Docker Compose.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose up -d --build
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Check the service and health endpoint:
|
||||
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:
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
curl http://127.0.0.1:3040/health
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Then open [http://127.0.0.1:3040/](http://127.0.0.1:3040/). On the first admin login, use `admin / admin` and follow the prompt to change the password.
|
||||
Do not run `docker compose down -v`, because it removes the database and administrator settings.
|
||||
|
||||
Runtime data is kept in the `webspeak-data` Docker volume. After updating the checkout, run `docker compose up -d --build` again. Stop the service with `docker compose down`; do not add `-v`, because that removes the database, master key, and administrator settings.
|
||||
|
||||
The default host port is `3040`. To use another host port, set `WEBSPEAK_PORT`; the container port stays unchanged:
|
||||
To change the web host port:
|
||||
|
||||
```bash
|
||||
WEBSPEAK_PORT=3041 docker compose up -d --build
|
||||
WEBSPEAK_PORT=3041 docker compose up -d
|
||||
```
|
||||
|
||||
#### Option B: Run the Dockerfile manually (optional)
|
||||
#### Run from source
|
||||
|
||||
```bash
|
||||
docker build -t webspeak:local .
|
||||
docker volume create webspeak-data
|
||||
docker run -d \
|
||||
--name webspeak \
|
||||
--restart unless-stopped \
|
||||
-p 3040:3040 \
|
||||
-v webspeak-data:/data \
|
||||
webspeak:local
|
||||
```
|
||||
|
||||
The container listens on `3040` internally. SQLite data, the installation master key, and logs are stored in `/data`; keep the `webspeak-data:/data` volume when running the image manually.
|
||||
|
||||
#### Option C: Run from source
|
||||
|
||||
Requirements:
|
||||
|
||||
- Node.js `22.5.0` or newer.
|
||||
- Native build tools required by `@discordjs/opus`; Linux installations typically need `python3`, `make`, and `g++`.
|
||||
- An accessible TeamSpeak 3 or TeamSpeak 6 server.
|
||||
- A recent Chrome or Edge release; HTTPS is recommended for production.
|
||||
Requires Node.js `22.5.0` or newer and native build tools for `@discordjs/opus`.
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
@@ -401,141 +263,96 @@ npm run build
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
Then open:
|
||||
The service listens on port `3040` by default.
|
||||
|
||||
```text
|
||||
http://127.0.0.1:3040/
|
||||
```
|
||||
### Low-latency WebRTC audio
|
||||
|
||||
Use `https://127.0.0.1:3040/` when direct certificates are enabled. On first run, WebSpeak creates its SQLite database and installation master key in the data directory.
|
||||
WebRTC is optional and bundled with WebSpeak. No separate media server is required.
|
||||
|
||||
### First login and default target
|
||||
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.
|
||||
|
||||
1. Open `/admin`.
|
||||
2. Sign in with the default account `admin / admin`.
|
||||
3. Follow the prompt to set a new administrator password of at least 12 characters.
|
||||
4. In **Servers**, configure the **Default TeamSpeak target** with a host and voice port.
|
||||
5. Run the connection test and save the settings.
|
||||
|
||||
When a welcome link has no target parameters, the welcome page pre-fills the administrator's default TeamSpeak target. Invite parameters take precedence. In fixed mode, guests stay on the administrator-configured target; in open mode, guests may enter a public target that passes the network policy.
|
||||
|
||||
WebSpeak's web port is fixed at `3040`, and TeamSpeak's default voice port is `9987`. The web fields use separate host and voice-port inputs; legacy `host:port` and `host#port` text remains accepted by the parser.
|
||||
|
||||
### Access modes and invites
|
||||
|
||||
| Mode | Behavior | Typical use |
|
||||
| --- | --- | --- |
|
||||
| `fixed` | Guests cannot change the target; the server and password are managed by the administrator | Private communities and a single permanent server |
|
||||
| `open` | Guests may enter a public target and a password for that session | Temporary access and multi-server entry points |
|
||||
| Managed invite | An administrator creates a one-time, expiring, usage-limited, revocable link | Events, temporary rooms, and targeted sharing |
|
||||
|
||||
In open mode, DNS resolution is followed by blocking loopback, private, link-local, multicast, broadcast, and reserved addresses. The verified IP is used for the actual connection. Server passwords never appear in share links, browser storage, or WebSocket URLs.
|
||||
|
||||
### Audio and devices
|
||||
|
||||
Inside a voice space, the settings panel lets users:
|
||||
|
||||
- Choose a microphone and speaker detected by the browser.
|
||||
- Mute or unmute the microphone with one click.
|
||||
- Adjust input, output, notification, and VOX-threshold volumes.
|
||||
- Inspect microphone permission, live input level, and audio-context state.
|
||||
- Run a local microphone test of up to five seconds; the recording is played in the browser and is not sent to TeamSpeak.
|
||||
|
||||
Device labels are controlled by the browser permission model. The first device selection may request microphone permission. Output-device selection depends on browser support; unsupported browsers clearly fall back to the default speaker.
|
||||
|
||||
### Data and Security Boundary
|
||||
|
||||
Runtime data is stored in `data/` by default and in `/data` in Docker:
|
||||
|
||||
```text
|
||||
data/
|
||||
├── webspeak.db SQLite settings, admin credentials, invites, and bounded audit events
|
||||
├── master.key 32-byte installation master key
|
||||
└── logs/ Locally rotated logs
|
||||
```
|
||||
|
||||
- Administrator passwords use Node.js `crypto.scrypt`, a random salt, and constant-time comparison.
|
||||
- TeamSpeak server passwords are encrypted with AES-256-GCM; admin APIs never return them in plaintext.
|
||||
- Admin sessions use server-side sessions, HttpOnly / SameSite Strict cookies, same-origin checks, and CSRF tokens.
|
||||
- Admin login applies bounded-window rate limiting and failure delays.
|
||||
- A user identity is used only by the current join ticket and session. When “remember this device” is enabled, the private key stays in browser IndexedDB and is not uploaded to the gateway or written to logs, diagnostics, or the database.
|
||||
- WebSpeak has no identity-file import/export controls; clearing browser data removes the remembered identity and local preferences.
|
||||
- Logs, diagnostic reports, and the overview do not return server passwords, admin passwords, or private identity keys.
|
||||
- Back up `webspeak.db` together with `master.key`; an encrypted TeamSpeak password cannot be recovered from the database alone.
|
||||
|
||||
### Upgrading from a legacy version
|
||||
|
||||
If an old `config.json` is still present in the project root at startup, WebSpeak imports these fields once:
|
||||
|
||||
- `tsHost`
|
||||
- `tsPort`
|
||||
- `tsServerPassword`
|
||||
|
||||
After the import, `data/webspeak.db` is the only live configuration source. The legacy file is not deleted or rewritten. Legacy `port`, `tsServerProtocol`, `maxClients`, and `trustProxy` values are no longer runtime controls.
|
||||
|
||||
### Health, development, and verification
|
||||
|
||||
Unauthenticated health endpoints:
|
||||
|
||||
```text
|
||||
GET /health
|
||||
GET /api/health
|
||||
```
|
||||
|
||||
Development commands:
|
||||
Docker Compose publishes `40000–40099/UDP` automatically, but it cannot change a cloud security group. With Ubuntu UFW:
|
||||
|
||||
```bash
|
||||
# Backend: fixed port 3040
|
||||
npm run dev
|
||||
|
||||
# Frontend: Vite on 5173, proxying /api and /ws to 3040
|
||||
npm run web:dev
|
||||
|
||||
# Frontend production build
|
||||
npm --prefix web run build
|
||||
|
||||
# Backend type check and build
|
||||
npm run build
|
||||
|
||||
# Automated tests
|
||||
npm test
|
||||
|
||||
# Dependency audit
|
||||
npm audit
|
||||
sudo ufw allow 40000:40099/udp
|
||||
```
|
||||
|
||||
`/demo` is an interactive simulated page that never connects to a real TeamSpeak server. It is useful for UI previews, recordings, and frontend regression checks, but does not replace real TS3 / TS6 verification.
|
||||
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.
|
||||
|
||||
### Project layout
|
||||
### Administrator settings
|
||||
|
||||
```text
|
||||
src/
|
||||
├── admin/ Admin service, login, sessions, invites, and operations APIs
|
||||
├── persistence/ SQLite schema, repositories, and migration boundaries
|
||||
├── security/ Master key, secret encryption, passwords, and target policy
|
||||
├── domain/ TeamSpeak target and port parsing
|
||||
└── server/ TeamSpeak adapter, sessions, tickets, and voice bridge
|
||||
The admin console can:
|
||||
|
||||
web/src/
|
||||
├── views/WebClient.vue Guest client, voice space, chat, and audio settings
|
||||
├── views/AdminView.vue Admin login, server, overview, and operations console
|
||||
├── composables/ WebSocket and voice state
|
||||
└── services/ Theme, local persistence, and target parsing
|
||||
```
|
||||
- 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.
|
||||
|
||||
### Known boundaries
|
||||
### Browser requirements
|
||||
|
||||
- The server has a fixed limit of 100 active connections.
|
||||
- The current administrator model is single-admin; there is no user, role, or permission-management panel.
|
||||
- Browser microphone permissions, HTTPS, and browser support for output-device selection affect the final experience.
|
||||
- WebSpeak does not replace TeamSpeak server version, protocol-compatibility, or network-reachability management.
|
||||
- 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.
|
||||
|
||||
### License
|
||||
### Changelog
|
||||
|
||||
WebSpeak is licensed under the [GNU Affero General Public License v3.0 only](LICENSE) (`AGPL-3.0-only`). If you run a modified version as a network service, provide the corresponding source under the terms of the license.
|
||||
See [`CHANGELOG.md`](CHANGELOG.md) for the complete release history.
|
||||
|
||||
#### 2026-09-04 · v0.1.6
|
||||
|
||||
- Added a warning for concurrent remembered-identity connections.
|
||||
- Added desktop accompaniment sharing.
|
||||
- Added a site favicon and refreshed the repository README branding.
|
||||
|
||||
#### 2026-09-04 · v0.1.5
|
||||
|
||||
- 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).
|
||||
+3
-4
@@ -1,12 +1,11 @@
|
||||
services:
|
||||
webspeak:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
image: webspeak:local
|
||||
image: ${WEBSPEAK_IMAGE:-ghcr.io/echosixhiya/webspeak:latest}
|
||||
pull_policy: missing
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "${WEBSPEAK_PORT:-3040}:3040"
|
||||
- "40000-40099:40000-40099/udp"
|
||||
volumes:
|
||||
- webspeak-data:/data
|
||||
|
||||
|
||||
Generated
+533
-10
@@ -1,19 +1,19 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.6",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.2",
|
||||
"hasInstallScript": true,
|
||||
"version": "0.1.6",
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@honeybbq/teamspeak-client": "^0.2.2",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#4e9edf7",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"werift": "0.24.4",
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -61,6 +61,17 @@
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@echosixhiya/teamspeak-client": {
|
||||
"version": "0.2.4",
|
||||
"resolved": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#4e9edf7198418d8a0a0eff97e05aa2b3369c2fe0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
|
||||
@@ -503,16 +514,26 @@
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@honeybbq/teamspeak-client": {
|
||||
"version": "0.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@honeybbq/teamspeak-client/-/teamspeak-client-0.2.2.tgz",
|
||||
"integrity": "sha512-JQ4yHEUwAxK2kHmIxelEf3grzMM8lVeuf7RzxK1g24U6XH8ZJO28S477FUtSTRe68PwUBkAlsa1Z/7BhLKh+AA==",
|
||||
"node_modules/@fidm/asn1": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@fidm/asn1/-/asn1-1.0.4.tgz",
|
||||
"integrity": "sha512-esd1jyNvRb2HVaQGq2Gg8Z0kbQPXzV9Tq5Z14KNIov6KfFD6PTaRIO8UpcsYiTNzOqJpmyzWgVTrUwFV3UF4TQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/@fidm/x509": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@fidm/x509/-/x509-1.2.1.tgz",
|
||||
"integrity": "sha512-nwc2iesjyc9hkuzcrMCBXQRn653XuAUKorfWM8PZyJawiy1QzLj4vahwzaI25+pfpwOLvMzbJ0uKpWLDNmo16w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1"
|
||||
"@fidm/asn1": "^1.0.4",
|
||||
"tweetnacl": "^1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19"
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/@isaacs/fs-minipass": {
|
||||
@@ -527,6 +548,12 @@
|
||||
"node": ">=18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@leichtgewicht/ip-codec": {
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@leichtgewicht/ip-codec/-/ip-codec-2.0.5.tgz",
|
||||
"integrity": "sha512-Vo+PSpZG2/fmgmiNzYK9qWRh8h/CHrwD0mo1h1DzL4yzHNSfWYujGTYsWGreD000gcgmZ7K4Ys6Tx9TxtsKdDw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@noble/curves": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.2.0.tgz",
|
||||
@@ -554,12 +581,212 @@
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/asn1-cms": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/asn1-cms/-/asn1-cms-2.9.4.tgz",
|
||||
"integrity": "sha512-cben7oxmQsUGZqotus7yt0srYdncOT6RNWcTQ77T2RFOXejYVYkXadrfePdRcrVpO9K95IRLKKglG2k38jKXuw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-schema": "^2.9.4",
|
||||
"@peculiar/asn1-x509": "^2.9.4",
|
||||
"@peculiar/asn1-x509-attr": "^2.9.4",
|
||||
"asn1js": "^3.0.10",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/asn1-csr": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/asn1-csr/-/asn1-csr-2.9.4.tgz",
|
||||
"integrity": "sha512-xd4YN4vpRjkDAQWVfZZkeu12IEND7DOpkqaHSIHxZl1uggUNa9Ju0QxY2jHvDAS9pP0zhRBytg8ifsnGo3V0jw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-schema": "^2.9.4",
|
||||
"@peculiar/asn1-x509": "^2.9.4",
|
||||
"asn1js": "^3.0.10",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/asn1-ecc": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/asn1-ecc/-/asn1-ecc-2.9.4.tgz",
|
||||
"integrity": "sha512-JJXefFshRAuVAjWQo/39bkg1ywc1VaiO44S8RRC+Ykvf/u2KDmYffoDb0ZBPCR5uJy4AGKQhl8mX+Q8ShcWaXQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-schema": "^2.9.4",
|
||||
"@peculiar/asn1-x509": "^2.9.4",
|
||||
"asn1js": "^3.0.10",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/asn1-pfx": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pfx/-/asn1-pfx-2.9.4.tgz",
|
||||
"integrity": "sha512-khuGzHTzNzk4GDlIBEILyIs6Lce0yn0ZBdoI9v93kmNncfZRhD+AQ5ODFqdhvoE8cMJF/JMTQ8yA+t1D14kqCw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-cms": "^2.9.4",
|
||||
"@peculiar/asn1-pkcs8": "^2.9.4",
|
||||
"@peculiar/asn1-rsa": "^2.9.4",
|
||||
"@peculiar/asn1-schema": "^2.9.4",
|
||||
"asn1js": "^3.0.10",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/asn1-pkcs8": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs8/-/asn1-pkcs8-2.9.4.tgz",
|
||||
"integrity": "sha512-duRdotlUx9eDZe6QrQpQKl61RbWykCHBCkKayP8V8XdEFwlKHZ8qGGDMyS6Pye7OX7nLFttTTpRkJeet78ckwQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-schema": "^2.9.4",
|
||||
"@peculiar/asn1-x509": "^2.9.4",
|
||||
"asn1js": "^3.0.10",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/asn1-pkcs9": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs9/-/asn1-pkcs9-2.9.4.tgz",
|
||||
"integrity": "sha512-kaL4cNxBpdQE2dKlyZBqz4ygCrwffO+8wfoxTEqM1Z8RadvCeELBRzcv0dzM8aY9azHMwODO5nxU65zXmhToOQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-cms": "^2.9.4",
|
||||
"@peculiar/asn1-pfx": "^2.9.4",
|
||||
"@peculiar/asn1-pkcs8": "^2.9.4",
|
||||
"@peculiar/asn1-schema": "^2.9.4",
|
||||
"@peculiar/asn1-x509": "^2.9.4",
|
||||
"@peculiar/asn1-x509-attr": "^2.9.4",
|
||||
"asn1js": "^3.0.10",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/asn1-rsa": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/asn1-rsa/-/asn1-rsa-2.9.4.tgz",
|
||||
"integrity": "sha512-pZ96eD1PptovcWQ/GSmuNFXd/7EQJNlKfDaNCyE2rx3W0v6QFelkzquVqRSRyyDXXCYD69ZXJDzZ8GhIiQzKoA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-schema": "^2.9.4",
|
||||
"@peculiar/asn1-x509": "^2.9.4",
|
||||
"asn1js": "^3.0.10",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/asn1-schema": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.9.4.tgz",
|
||||
"integrity": "sha512-GjzePcT9Iw8NzeOPf73iNS9xM+TBhd/FilAfP+RQGkTMQJTVWtytN3JHJACCjf/ABNau5S7mS3g+DcuxmRgYEg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/utils": "^2.0.2",
|
||||
"asn1js": "^3.0.10",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/asn1-x509": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/asn1-x509/-/asn1-x509-2.9.4.tgz",
|
||||
"integrity": "sha512-CxhBo/RdEbMMob7T31ZdQjGuoyRFLVwrDzTn25bihzBasRg9kRm/0IxIPvhgQtcK/9dNcO1XQL2fuPugwELL0Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-schema": "^2.9.4",
|
||||
"@peculiar/utils": "^2.0.2",
|
||||
"asn1js": "^3.0.10",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/asn1-x509-attr": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/asn1-x509-attr/-/asn1-x509-attr-2.9.4.tgz",
|
||||
"integrity": "sha512-ehQXbpQaQYycgu8OrvigwSPTFfVRcu0ECNYCWw+yzBp02Lw5paRqzzhUpfOgO2K38+WfFZuEz/0RPtam5g0OMg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-schema": "^2.9.4",
|
||||
"@peculiar/asn1-x509": "^2.9.4",
|
||||
"asn1js": "^3.0.10",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/utils": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/utils/-/utils-2.0.3.tgz",
|
||||
"integrity": "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.8.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/x509": {
|
||||
"version": "1.14.3",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/x509/-/x509-1.14.3.tgz",
|
||||
"integrity": "sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-cms": "^2.6.0",
|
||||
"@peculiar/asn1-csr": "^2.6.0",
|
||||
"@peculiar/asn1-ecc": "^2.6.0",
|
||||
"@peculiar/asn1-pkcs9": "^2.6.0",
|
||||
"@peculiar/asn1-rsa": "^2.6.0",
|
||||
"@peculiar/asn1-schema": "^2.6.0",
|
||||
"@peculiar/asn1-x509": "^2.6.0",
|
||||
"pvtsutils": "^1.3.6",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"tslib": "^2.8.1",
|
||||
"tsyringe": "^4.10.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@pinojs/redact": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
|
||||
"integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@shinyoshiaki/binary-data": {
|
||||
"version": "0.6.1",
|
||||
"resolved": "https://registry.npmjs.org/@shinyoshiaki/binary-data/-/binary-data-0.6.1.tgz",
|
||||
"integrity": "sha512-7HDb/fQAop2bCmvDIzU5+69i+UJaFgIVp99h1VzK1mpg1JwSODOkjbqD7ilTYnqlnadF8C4XjpwpepxDsGY6+w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"generate-function": "^2.3.1",
|
||||
"is-plain-object": "^2.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/body-parser": {
|
||||
"version": "1.19.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz",
|
||||
@@ -581,6 +808,21 @@
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/dom-mediacapture-transform": {
|
||||
"version": "0.1.12",
|
||||
"resolved": "https://registry.npmjs.org/@types/dom-mediacapture-transform/-/dom-mediacapture-transform-0.1.12.tgz",
|
||||
"integrity": "sha512-d7/QsLRwF864A5mgIM/YrfiglHoYn7zgCcAoJgW404r+2DwnNr7EBbLnCWpmOMgH8y0te73L1AV6H1bmauaWFw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/dom-webcodecs": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/dom-webcodecs": {
|
||||
"version": "0.1.13",
|
||||
"resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.13.tgz",
|
||||
"integrity": "sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/express": {
|
||||
"version": "5.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz",
|
||||
@@ -728,6 +970,20 @@
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/asn1js": {
|
||||
"version": "3.0.10",
|
||||
"resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.10.tgz",
|
||||
"integrity": "sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"pvtsutils": "^1.3.6",
|
||||
"pvutils": "^1.1.5",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/atomic-sleep": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz",
|
||||
@@ -743,6 +999,26 @@
|
||||
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/base64-js": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
|
||||
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/body-parser": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",
|
||||
@@ -790,6 +1066,30 @@
|
||||
"concat-map": "0.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/buffer": {
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
|
||||
"integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"base64-js": "^1.3.1",
|
||||
"ieee754": "^1.2.1"
|
||||
}
|
||||
},
|
||||
"node_modules/bytes": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
|
||||
@@ -939,6 +1239,18 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/dns-packet": {
|
||||
"version": "5.6.1",
|
||||
"resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-5.6.1.tgz",
|
||||
"integrity": "sha512-l4gcSouhcgIKRvyy99RNVOgxXiicE+2jZoNmaNmZ6JXiGajBOJAesk1OBlJuM5k2c+eudGdLxDqXuPCKIj6kpw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@leichtgewicht/ip-codec": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/dunder-proto": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||
@@ -1194,6 +1506,15 @@
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/generate-function": {
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz",
|
||||
"integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"is-property": "^1.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/get-intrinsic": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
|
||||
@@ -1343,6 +1664,26 @@
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/ieee754": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
|
||||
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/inflight": {
|
||||
"version": "1.0.6",
|
||||
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
|
||||
@@ -1378,12 +1719,39 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/is-plain-object": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz",
|
||||
"integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"isobject": "^3.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/is-promise": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
|
||||
"integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/is-property": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",
|
||||
"integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/isobject": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
|
||||
"integrity": "sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/make-dir": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",
|
||||
@@ -1426,6 +1794,24 @@
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/mediabunny": {
|
||||
"version": "1.55.5",
|
||||
"resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.55.5.tgz",
|
||||
"integrity": "sha512-m0v6y8FGXiK+HKOc3AZqU+kJPLYsSKaLitmQNQIIHZKIGlTwQ34OF+X6Ul0K8iV4b03oPse10apwuoqbvmKeAA==",
|
||||
"license": "MPL-2.0",
|
||||
"workspaces": [
|
||||
".",
|
||||
"packages/*"
|
||||
],
|
||||
"dependencies": {
|
||||
"@types/dom-mediacapture-transform": "^0.1.11",
|
||||
"@types/dom-webcodecs": "0.1.13"
|
||||
},
|
||||
"funding": {
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/Vanilagy"
|
||||
}
|
||||
},
|
||||
"node_modules/merge-descriptors": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
|
||||
@@ -1502,6 +1888,19 @@
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/multicast-dns": {
|
||||
"version": "7.2.5",
|
||||
"resolved": "https://registry.npmjs.org/multicast-dns/-/multicast-dns-7.2.5.tgz",
|
||||
"integrity": "sha512-2eznPJP8z2BFLX50tf0LuODrpINqP1RVIm/CObbTcBRITQgmC/TjcREF1NeTBzIcR5XO/ukWo+YHOjBbFwIupg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"dns-packet": "^5.2.2",
|
||||
"thunky": "^1.0.2"
|
||||
},
|
||||
"bin": {
|
||||
"multicast-dns": "cli.js"
|
||||
}
|
||||
},
|
||||
"node_modules/negotiator": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
|
||||
@@ -1713,6 +2112,24 @@
|
||||
"node": ">= 0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/pvtsutils": {
|
||||
"version": "1.3.6",
|
||||
"resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",
|
||||
"integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.8.1"
|
||||
}
|
||||
},
|
||||
"node_modules/pvutils": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz",
|
||||
"integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/qs": {
|
||||
"version": "6.15.2",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz",
|
||||
@@ -1781,6 +2198,12 @@
|
||||
"node": ">= 12.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/reflect-metadata": {
|
||||
"version": "0.2.2",
|
||||
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
|
||||
"integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/rimraf": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz",
|
||||
@@ -2091,6 +2514,12 @@
|
||||
"integrity": "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/thunky": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/thunky/-/thunky-1.1.0.tgz",
|
||||
"integrity": "sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/toidentifier": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
|
||||
@@ -2106,6 +2535,12 @@
|
||||
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/tsx": {
|
||||
"version": "4.22.3",
|
||||
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.22.3.tgz",
|
||||
@@ -2125,6 +2560,30 @@
|
||||
"fsevents": "~2.3.3"
|
||||
}
|
||||
},
|
||||
"node_modules/tsyringe": {
|
||||
"version": "4.10.0",
|
||||
"resolved": "https://registry.npmjs.org/tsyringe/-/tsyringe-4.10.0.tgz",
|
||||
"integrity": "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^1.9.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tsyringe/node_modules/tslib": {
|
||||
"version": "1.14.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz",
|
||||
"integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==",
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/tweetnacl": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",
|
||||
"integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==",
|
||||
"license": "Unlicense"
|
||||
},
|
||||
"node_modules/type-is": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",
|
||||
@@ -2207,6 +2666,70 @@
|
||||
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
|
||||
"license": "BSD-2-Clause"
|
||||
},
|
||||
"node_modules/werift": {
|
||||
"version": "0.24.4",
|
||||
"resolved": "https://registry.npmjs.org/werift/-/werift-0.24.4.tgz",
|
||||
"integrity": "sha512-NoROZ11L/ZqAB5ombCB4VBuVNdIZfwI493zlxlIX7BlwfWRy55eDJdtWMC2VX35yBXFaWwA8NtYbmJ8qWtVk9Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@fidm/x509": "^1.2.1",
|
||||
"@noble/curves": "^1.8.1",
|
||||
"@peculiar/x509": "^1.12.3",
|
||||
"@shinyoshiaki/binary-data": "^0.6.1",
|
||||
"buffer": "^6.0.3",
|
||||
"debug": "4.4.0",
|
||||
"mediabunny": "^1.45.2",
|
||||
"multicast-dns": "^7.2.5",
|
||||
"tweetnacl": "^1.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/werift/node_modules/@noble/curves": {
|
||||
"version": "1.9.7",
|
||||
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz",
|
||||
"integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/hashes": "1.8.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^14.21.3 || >=16"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/werift/node_modules/@noble/hashes": {
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
|
||||
"integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^14.21.3 || >=16"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/werift/node_modules/debug": {
|
||||
"version": "4.4.0",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz",
|
||||
"integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ms": "^2.1.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"supports-color": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/whatwg-url": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
|
||||
|
||||
+5
-4
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.6",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-only",
|
||||
"type": "module",
|
||||
@@ -13,15 +13,16 @@
|
||||
"build": "tsc",
|
||||
"test": "tsx --test \"test/**/*.test.ts\"",
|
||||
"start": "node dist/index.js",
|
||||
"postinstall": "node scripts/patch-teamspeak-sdk.mjs",
|
||||
"web:dev": "cd web && npx vite --host",
|
||||
"web:build": "cd web && npx vite build"
|
||||
"web:build": "cd web && npx vite build",
|
||||
"prepare:sdk": "node scripts/prepare-sdk.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@honeybbq/teamspeak-client": "^0.2.2",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#4e9edf7",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"werift": "0.24.4",
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,183 +0,0 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const packageRoot = path.join(root, "node_modules", "@honeybbq", "teamspeak-client");
|
||||
const marker = "webspeak-directory-snapshot-v2";
|
||||
const whisperMarker = "webspeak-team-whisper-v1";
|
||||
|
||||
const packageJson = JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8"));
|
||||
if (packageJson.version !== "0.2.2") {
|
||||
throw new Error(`Unsupported @honeybbq/teamspeak-client version: ${packageJson.version}`);
|
||||
}
|
||||
|
||||
const cjsPath = path.join(packageRoot, "dist", "index.cjs");
|
||||
const mjsPath = path.join(packageRoot, "dist", "index.mjs");
|
||||
const handlerCjsPath = path.join(packageRoot, "dist", "handler-CqCD93f0.cjs");
|
||||
const handlerMjsPath = path.join(packageRoot, "dist", "handler-C_JhqGTd.js");
|
||||
const [cjs, mjs, handlerCjs, handlerMjs] = await Promise.all([
|
||||
readFile(cjsPath, "utf8"),
|
||||
readFile(mjsPath, "utf8"),
|
||||
readFile(handlerCjsPath, "utf8"),
|
||||
readFile(handlerMjsPath, "utf8"),
|
||||
]);
|
||||
|
||||
const patchedCjs = patchWhisperClient(patchCjs(cjs), "cjs");
|
||||
const patchedMjs = patchWhisperClient(patchMjs(mjs), "mjs");
|
||||
const patchedHandlerCjs = patchWhisperHandler(handlerCjs, "cjs");
|
||||
const patchedHandlerMjs = patchWhisperHandler(handlerMjs, "mjs");
|
||||
await Promise.all([
|
||||
writeFile(cjsPath, patchedCjs, "utf8"),
|
||||
writeFile(mjsPath, patchedMjs, "utf8"),
|
||||
writeFile(handlerCjsPath, patchedHandlerCjs, "utf8"),
|
||||
writeFile(handlerMjsPath, patchedHandlerMjs, "utf8"),
|
||||
]);
|
||||
|
||||
function patchWhisperClient(source, format) {
|
||||
if (source.includes(whisperMarker)) return source;
|
||||
if (format === "cjs") {
|
||||
const needle = "sendVoice(e,t){this.handler.sendVoicePacket(e,t)}";
|
||||
if (!source.includes(needle)) throw new Error("Could not patch CJS SDK client whisper method");
|
||||
return source.replace(needle, `${needle}sendWhisper(e,t,n){this.handler.sendWhisperPacket(e,t,n)}`) + `/* ${whisperMarker} */`;
|
||||
}
|
||||
const needle = "\tsendVoice(e, t) {\n\t\tthis.handler.sendVoicePacket(e, t);\n\t}\n";
|
||||
if (!source.includes(needle)) throw new Error("Could not patch MJS SDK client whisper method");
|
||||
return source.replace(needle, `${needle}\tsendWhisper(e, t, n) {\n\t\tthis.handler.sendWhisperPacket(e, t, n);\n\t}\n`) + `/* ${whisperMarker} */`;
|
||||
}
|
||||
|
||||
function patchWhisperHandler(source, format) {
|
||||
if (source.includes(whisperMarker)) return source;
|
||||
if (format === "cjs") {
|
||||
const needle = "this.#b(u)}close(){";
|
||||
if (!source.includes(needle)) throw new Error("Could not patch CJS SDK whisper packet handler");
|
||||
const method = `/* ${whisperMarker} */sendWhisperPacket(e,t,n){if(t.length>32)throw new Error(\`too many whisper targets\`);let a=this.#c[r.VoiceWhisper],o=this.#l[r.VoiceWhisper];this.#c[r.VoiceWhisper]=a+1&65535,this.#c[r.VoiceWhisper]===0&&this.#l[r.VoiceWhisper]++;let s=5+2*t.length+e.length,l=new Uint8Array(s),u=new DataView(l.buffer);u.setUint16(0,a,!1),l[2]=n,l[3]=0,l[4]=t.length;for(let n=0;n<t.length;n++)u.setUint16(5+2*n,t[n],!1);l.set(e,5+2*t.length);let c0=c({typeFlagged:r.VoiceWhisper|i.Unencrypted,id:a,clientID:this.#r,generationID:o,data:l,receivedAt:0}),d=new Uint8Array(x+b+s);d.set(this.#e.fakeSignature,0),d.set(c0,x),d.set(l,x+b),this.#b(d)}`;
|
||||
return source.replace(needle, `this.#b(u)}${method}close(){`);
|
||||
}
|
||||
const needle = "this.#b(u);\n\t}\n\tclose() {";
|
||||
if (!source.includes(needle)) throw new Error("Could not patch MJS SDK whisper packet handler");
|
||||
const method = `\t/* ${whisperMarker} */\n\tsendWhisperPacket(e, t, n) {\n\t\tif (t.length > 32) throw new Error("too many whisper targets");\n\t\tlet a = this.#c[r.VoiceWhisper], o = this.#l[r.VoiceWhisper];\n\t\tthis.#c[r.VoiceWhisper] = a + 1 & 65535;\n\t\tif (this.#c[r.VoiceWhisper] === 0) this.#l[r.VoiceWhisper]++;\n\t\tconst s = 5 + 2 * t.length + e.length, l = new Uint8Array(s), u = new DataView(l.buffer);\n\t\tu.setUint16(0, a, false);\n\t\tl[2] = n;\n\t\tl[3] = 0;\n\t\tl[4] = t.length;\n\t\tfor (let n = 0; n < t.length; n++) u.setUint16(5 + 2 * n, t[n], false);\n\t\tl.set(e, 5 + 2 * t.length);\n\t\tconst c0 = c({ typeFlagged: r.VoiceWhisper | i.Unencrypted, id: a, clientID: this.#r, generationID: o, data: l, receivedAt: 0 });\n\t\tconst d = new Uint8Array(x + b + s);\n\t\td.set(this.#e.fakeSignature, 0);\n\t\td.set(c0, x);\n\t\td.set(l, x + b);\n\t\tthis.#b(d);\n\t}\n\tclose() {`;
|
||||
return source.replace(needle, `this.#b(u);\n\t}\n${method}`);
|
||||
}
|
||||
|
||||
function patchCjs(source) {
|
||||
if (source.includes(marker) || source.includes("webspeak-directory-snapshot")) return source;
|
||||
|
||||
const helper = `/* ${marker} */
|
||||
function webSpeakDirectoryBigInt(value){try{return BigInt(value??"0")}catch{return 0n}}
|
||||
function webSpeakDirectoryChannel(params,decode){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return null;return{id,parentID:webSpeakDirectoryBigInt(params.pid??params.cpid??"0"),name:decode(params.channel_name??""),description:decode(params.channel_topic??params.channel_description??"")}}
|
||||
function webSpeakDirectoryClient(params,decode){const id=parseInt(params.clid??"0",10);if(!Number.isInteger(id)||id<=0)return null;const groups=params.client_servergroups??"";return{id,nickname:decode(params.client_nickname??""),uid:params.client_unique_identifier??"",channelID:webSpeakDirectoryBigInt(params.cid),type:parseInt(params.client_type??"0",10),serverGroups:groups?groups.split(","):[],away:params.client_away==="1",awayMessage:decode(params.client_away_message??""),inputMuted:params.client_input_muted==="1",outputMuted:params.client_output_muted==="1",channelCommander:params.client_is_channel_commander==="1"}}
|
||||
function webSpeakDirectoryChannelNotification(name,params,decode,channels){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return false;switch(name){case"notifychannelcreated":{const channel=webSpeakDirectoryChannel(params,decode);if(!channel)return false;channels.set(id,channel);return true}case"notifychanneledited":{const current=channels.get(id);if(!current)return false;const next={...current};if(params.channel_name!==undefined)next.name=decode(params.channel_name);if(params.channel_topic!==undefined)next.description=decode(params.channel_topic);if(params.cpid!==undefined||params.pid!==undefined)next.parentID=webSpeakDirectoryBigInt(params.cpid??params.pid);channels.set(id,next);return true}case"notifychannelmoved":{const current=channels.get(id);if(!current)return false;channels.set(id,{...current,parentID:webSpeakDirectoryBigInt(params.cpid??params.pid)});return true}case"notifychanneldeleted":return channels.delete(id);default:return false}}
|
||||
`;
|
||||
source = source.replace("var K=class", `${helper}var K=class`);
|
||||
|
||||
// TS6 reports a client that moved out of our current view as
|
||||
// notifyclientleftview with a non-zero ctid. Preserve that client and apply
|
||||
// the target channel; ctid=0 is the actual server leave case.
|
||||
const replacements = [
|
||||
[
|
||||
"function L(e,t,n){let r=j(e.params.clid??``),i=M(e.params.reasonid??``),a=r===t;return r!==0&&n.delete(r),{kind:`clientLeave`,event:{id:r,reasonID:i,reasonMsg:e.params.reasonmsg??``,targetID:j(e.params.targetid??``)},isSelf:a}}",
|
||||
"function L(e,t,n){let r=j(e.params.clid??``),i=M(e.params.reasonid??``),a=r===t,o=A(e.params.ctid??``),s=o!==0n;if(r!==0)if(s){let e=n.get(r);e&&n.set(r,{...e,channelID:o})}else n.delete(r);return s?{kind:`clientMoved`,event:{id:r,targetChannelID:o,reasonID:i,invokerID:j(e.params.invokerid??``),invokerName:e.params.invokername??``,invokerUID:e.params.invokeruid??``}}:{kind:`clientLeave`,event:{id:r,reasonID:i,reasonMsg:e.params.reasonmsg??``,targetID:j(e.params.targetid??``)},isSelf:a}}",
|
||||
],
|
||||
[
|
||||
"var K=class{crypt;handler;logger;nickname;clid=0;#e;#t;#n;#r;#i=e.t.Disconnected;#a=new W;#o=new d;#s=new m;#c=new Map;#l=[];#u=[];#d=[];#f=[];#p=[];#m=[];#h=[];#g=[];#_=[];#v=[];#y=[];#b=[];#x;#S;constructor",
|
||||
"var K=class{crypt;handler;logger;nickname;clid=0;#e;#t;#n;#r;#i=e.t.Disconnected;#a=new W;#o=new d;#s=new m;#c=new Map;#q=new Map;#R=[];#L=!1;#l=[];#u=[];#d=[];#f=[];#p=[];#m=[];#h=[];#g=[];#_=[];#v=[];#y=[];#b=[];#x;#S;constructor",
|
||||
],
|
||||
[
|
||||
"case`voiceData`:this.#h.push(t);break;case`connected`:",
|
||||
"case`voiceData`:this.#h.push(t);break;case`directorySnapshot`:this.#R.push(t);break;case`connected`:",
|
||||
],
|
||||
[
|
||||
"this.#o.reset(),this.#s.reset(),this.#c.clear(),this.clid=0",
|
||||
"this.#o.reset(),this.#s.reset(),this.#q.clear(),this.#c.clear(),this.#L=!1,this.clid=0",
|
||||
],
|
||||
[
|
||||
"case`initserver`:w(this,t.params);break;case`error`:this.#A(t.params);break;default:{",
|
||||
"case`initserver`:w(this,t.params);break;case`channellist`:{let e=webSpeakDirectoryChannel(t.params,a.i);e&&this.#q.set(e.id,e),this.#Y();break}case`channelclientlist`:{let e=webSpeakDirectoryClient(t.params,a.i);e&&this.#c.set(e.id,e),this.#Y();break}case`error`:this.#A(t.params);break;default:{",
|
||||
],
|
||||
[
|
||||
"if(t.name.startsWith(`notify`)){let e=F(t,this.clid,this.#c,this.nickname);this.#j(e,t.params);return}",
|
||||
"if(t.name.startsWith(`notify`)){let e=webSpeakDirectoryChannelNotification(t.name,t.params,a.i,this.#q),n=F(t,this.clid,this.#c,this.nickname);this.#j(n,t.params),e&&this.#Y();return}",
|
||||
],
|
||||
[
|
||||
"case`clientEnter`:{let t=e.info;t.id!==0&&N(this.nickname,t.nickname)&&(this.clid=t.id,this.handler.setClientID(t.id),this.#o.signalWelcomeComplete()),this.#M(`clientEnter`,t);break}",
|
||||
"case`clientEnter`:{let t=e.info,r=webSpeakDirectoryBigInt(arguments[1]?.cid??arguments[1]?.ctid??\"0\");r!==0n&&(t={...t,channelID:r},this.#c.set(t.id,t));let n=this.#c.get(t.id);n&&t.channelID===0n&&n.channelID!==0n&&(t={...t,channelID:n.channelID},this.#c.set(t.id,t));let i=t.id!==0&&N(this.nickname,t.nickname);i&&(this.clid=t.id,this.handler.setClientID(t.id),this.#o.signalWelcomeComplete(),this.#Y()),this.#M(`clientEnter`,t),!i&&this.#i===2&&this.#Y();break}",
|
||||
],
|
||||
[
|
||||
"case`clientLeave`:if(this.#M(`clientLeave`,e.event),e.isSelf&&(e.event.reasonID===4||e.event.reasonID===5)){let t=e.event.reasonMsg;for(let e of this.#v)setImmediate(()=>e(t))}break;case`clientMoved`:this.#M(`clientMoved`,e.event);break;",
|
||||
"case`clientLeave`:if(this.#M(`clientLeave`,e.event),this.#i===2&&this.#Y(),e.isSelf&&(e.event.reasonID===4||e.event.reasonID===5)){let t=e.event.reasonMsg;for(let e of this.#v)setImmediate(()=>e(t))}break;case`clientMoved`:this.#M(`clientMoved`,e.event),this.#i===2&&this.#Y();break;",
|
||||
],
|
||||
[
|
||||
"#M(e,t){this.#S(t)}#N(e,t){",
|
||||
"#Y(){if(this.#L)return;this.#L=!0,setImmediate(()=>{this.#L=!1;const e={channels:Array.from(this.#q.values()).map(e=>({...e})),clients:Array.from(this.#c.values()).map(e=>({...e,serverGroups:[...(e.serverGroups??[])]}))};for(const t of this.#R)setImmediate(()=>t(e))})}#M(e,t){this.#S(t)}#N(e,t){",
|
||||
],
|
||||
];
|
||||
|
||||
for (const [before, after] of replacements) {
|
||||
if (!source.includes(before)) throw new Error(`Could not patch CJS SDK segment: ${before.slice(0, 80)}`);
|
||||
source = source.replace(before, after);
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
function patchMjs(source) {
|
||||
if (source.includes(marker) || source.includes("webspeak-directory-snapshot")) return source;
|
||||
|
||||
const helper = `/* ${marker} */
|
||||
function webSpeakDirectoryBigInt(value){try{return BigInt(value??"0")}catch{return 0n}}
|
||||
function webSpeakDirectoryChannel(params,decode){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return null;return{id,parentID:webSpeakDirectoryBigInt(params.pid??params.cpid??"0"),name:decode(params.channel_name??""),description:decode(params.channel_topic??params.channel_description??"")}}
|
||||
function webSpeakDirectoryClient(params,decode){const id=parseInt(params.clid??"0",10);if(!Number.isInteger(id)||id<=0)return null;const groups=params.client_servergroups??"";return{id,nickname:decode(params.client_nickname??""),uid:params.client_unique_identifier??"",channelID:webSpeakDirectoryBigInt(params.cid),type:parseInt(params.client_type??"0",10),serverGroups:groups?groups.split(","):[],away:params.client_away==="1",awayMessage:decode(params.client_away_message??""),inputMuted:params.client_input_muted==="1",outputMuted:params.client_output_muted==="1",channelCommander:params.client_is_channel_commander==="1"}}
|
||||
function webSpeakDirectoryChannelNotification(name,params,decode,channels){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return false;switch(name){case"notifychannelcreated":{const channel=webSpeakDirectoryChannel(params,decode);if(!channel)return false;channels.set(id,channel);return true}case"notifychanneledited":{const current=channels.get(id);if(!current)return false;const next={...current};if(params.channel_name!==undefined)next.name=decode(params.channel_name);if(params.channel_topic!==undefined)next.description=decode(params.channel_topic);if(params.cpid!==undefined||params.pid!==undefined)next.parentID=webSpeakDirectoryBigInt(params.cpid??params.pid);channels.set(id,next);return true}case"notifychannelmoved":{const current=channels.get(id);if(!current)return false;channels.set(id,{...current,parentID:webSpeakDirectoryBigInt(params.cpid??params.pid)});return true}case"notifychanneldeleted":return channels.delete(id);default:return false}}
|
||||
`;
|
||||
source = source.replace("var k = class", `${helper}var k = class`);
|
||||
|
||||
// Keep the readable ESM build behavior identical to the minified CJS build.
|
||||
const replacements = [
|
||||
[
|
||||
"function ie(e, t, n) {\n\tlet r = Y(e.params.clid ?? \"\"), i = X(e.params.reasonid ?? \"\"), a = r === t;\n\treturn r !== 0 && n.delete(r), {\n\t\tkind: \"clientLeave\",\n\t\tevent: {\n\t\t\tid: r,\n\t\t\treasonID: i,\n\t\t\treasonMsg: e.params.reasonmsg ?? \"\",\n\t\t\ttargetID: Y(e.params.targetid ?? \"\")\n\t\t},\n\t\tisSelf: a\n\t};\n}",
|
||||
"function ie(e, t, n) {\n\tlet r = Y(e.params.clid ?? \"\"), i = X(e.params.reasonid ?? \"\"), a = r === t, targetChannelID = J(e.params.ctid ?? \"\"), moved = targetChannelID !== 0n;\n\tif (r !== 0) {\n\t\tif (moved) {\n\t\t\tconst current = n.get(r);\n\t\t\tif (current) n.set(r, { ...current, channelID: targetChannelID });\n\t\t} else {\n\t\t\tn.delete(r);\n\t\t}\n\t}\n\treturn moved ? {\n\t\tkind: \"clientMoved\",\n\t\tevent: {\n\t\t\tid: r,\n\t\t\ttargetChannelID,\n\t\t\treasonID: i,\n\t\t\tinvokerID: Y(e.params.invokerid ?? \"\"),\n\t\t\tinvokerName: e.params.invokername ?? \"\",\n\t\t\tinvokerUID: e.params.invokeruid ?? \"\"\n\t\t}\n\t} : {\n\t\tkind: \"clientLeave\",\n\t\tevent: {\n\t\t\tid: r,\n\t\t\treasonID: i,\n\t\t\treasonMsg: e.params.reasonmsg ?? \"\",\n\t\t\ttargetID: Y(e.params.targetid ?? \"\")\n\t\t},\n\t\tisSelf: a\n\t};\n}",
|
||||
],
|
||||
[
|
||||
"\t#c = /* @__PURE__ */ new Map();\n\t#l = [];",
|
||||
"\t#c = /* @__PURE__ */ new Map();\n\t#q = /* @__PURE__ */ new Map();\n\t#R = [];\n\t#L = false;\n\t#l = [];",
|
||||
],
|
||||
[
|
||||
"\t\t\tcase \"voiceData\":\n\t\t\t\tthis.#h.push(t);\n\t\t\t\tbreak;\n\t\t\tcase \"connected\":",
|
||||
"\t\t\tcase \"voiceData\":\n\t\t\t\tthis.#h.push(t);\n\t\t\t\tbreak;\n\t\t\tcase \"directorySnapshot\":\n\t\t\t\tthis.#R.push(t);\n\t\t\t\tbreak;\n\t\t\tcase \"connected\":",
|
||||
],
|
||||
[
|
||||
"this.#o.reset(), this.#s.reset(), this.#c.clear(), this.clid = 0",
|
||||
"this.#o.reset(), this.#s.reset(), this.#q.clear(), this.#c.clear(), this.#L = false, this.clid = 0",
|
||||
],
|
||||
[
|
||||
"\t\t\t\tcase \"initserver\":\n\t\t\t\t\tH(this, t.params);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"error\":",
|
||||
"\t\t\t\tcase \"initserver\":\n\t\t\t\t\tH(this, t.params);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"channellist\": {\n\t\t\t\t\tconst e = webSpeakDirectoryChannel(t.params, S);\n\t\t\t\t\tif (e) this.#q.set(e.id, e);\n\t\t\t\t\tthis.#Y();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"channelclientlist\": {\n\t\t\t\t\tconst e = webSpeakDirectoryClient(t.params, S);\n\t\t\t\t\tif (e) this.#c.set(e.id, e);\n\t\t\t\t\tthis.#Y();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"error\":",
|
||||
],
|
||||
[
|
||||
"\t\t\tif (t.name.startsWith(\"notify\")) {\n\t\t\t\tlet e = ne(t, this.clid, this.#c, this.nickname);\n\t\t\t\tthis.#j(e, t.params);\n\t\t\t\treturn;\n\t\t\t}",
|
||||
"\t\t\tif (t.name.startsWith(\"notify\")) {\n\t\t\t\tconst directoryChanged = webSpeakDirectoryChannelNotification(t.name, t.params, S, this.#q);\n\t\t\t\tlet e = ne(t, this.clid, this.#c, this.nickname);\n\t\t\t\tthis.#j(e, t.params);\n\t\t\t\tif (directoryChanged) this.#Y();\n\t\t\t\treturn;\n\t\t\t}",
|
||||
],
|
||||
[
|
||||
"\t\t\tcase \"clientEnter\": {\n\t\t\t\tlet t = e.info;\n\t\t\t\tt.id !== 0 && Z(this.nickname, t.nickname) && (this.clid = t.id, this.handler.setClientID(t.id), this.#o.signalWelcomeComplete()), this.#M(\"clientEnter\", t);\n\t\t\t\tbreak;\n\t\t\t}",
|
||||
"\t\t\tcase \"clientEnter\": {\n\t\t\t\tlet t = e.info;\n\t\t\t\tconst rawChannelID = webSpeakDirectoryBigInt(arguments[1]?.cid ?? arguments[1]?.ctid ?? \"0\");\n\t\t\t\tif (rawChannelID !== 0n) {\n\t\t\t\t\tt = { ...t, channelID: rawChannelID };\n\t\t\t\t\tthis.#c.set(t.id, t);\n\t\t\t\t}\n\t\t\t\tconst cached = this.#c.get(t.id);\n\t\t\t\tif (cached && t.channelID === 0n && cached.channelID !== 0n) {\n\t\t\t\t\tt = { ...t, channelID: cached.channelID };\n\t\t\t\t\tthis.#c.set(t.id, t);\n\t\t\t\t}\n\t\t\t\tconst own = t.id !== 0 && Z(this.nickname, t.nickname);\n\t\t\t\tif (own) {\n\t\t\t\t\tthis.clid = t.id;\n\t\t\t\t\tthis.handler.setClientID(t.id);\n\t\t\t\t\tthis.#o.signalWelcomeComplete();\n\t\t\t\t\tthis.#Y();\n\t\t\t\t}\n\t\t\t\tthis.#M(\"clientEnter\", t);\n\t\t\t\tif (!own && this.#i === n.Connected) this.#Y();\n\t\t\t\tbreak;\n\t\t\t}",
|
||||
],
|
||||
[
|
||||
"\t\t\tcase \"clientLeave\":\n\t\t\t\tif (this.#M(\"clientLeave\", e.event), e.isSelf && (e.event.reasonID === 4 || e.event.reasonID === 5)) {",
|
||||
"\t\t\tcase \"clientLeave\":\n\t\t\t\tif (this.#M(\"clientLeave\", e.event), this.#i === n.Connected && this.#Y(), e.isSelf && (e.event.reasonID === 4 || e.event.reasonID === 5)) {",
|
||||
],
|
||||
[
|
||||
"\t\t\tcase \"clientMoved\":\n\t\t\t\tthis.#M(\"clientMoved\", e.event);\n\t\t\t\tbreak;",
|
||||
"\t\t\tcase \"clientMoved\":\n\t\t\t\tthis.#M(\"clientMoved\", e.event);\n\t\t\t\tif (this.#i === n.Connected) this.#Y();\n\t\t\t\tbreak;",
|
||||
],
|
||||
[
|
||||
"\t#M(e, t) {\n\t\tthis.#S(t);\n\t}\n\t#N(e, t) {",
|
||||
"\t#Y() {\n\t\tif (this.#L) return;\n\t\tthis.#L = true;\n\t\tsetImmediate(() => {\n\t\t\tthis.#L = false;\n\t\t\tconst e = {\n\t\t\t\tchannels: Array.from(this.#q.values()).map((item) => ({ ...item })),\n\t\t\t\tclients: Array.from(this.#c.values()).map((item) => ({ ...item, serverGroups: [...(item.serverGroups ?? [])] })),\n\t\t\t};\n\t\t\tfor (const handler of this.#R) setImmediate(() => handler(e));\n\t\t});\n\t}\n\t#M(e, t) {\n\t\tthis.#S(t);\n\t}\n\t#N(e, t) {",
|
||||
],
|
||||
];
|
||||
|
||||
for (const [before, after] of replacements) {
|
||||
if (!source.includes(before)) throw new Error(`Could not patch MJS SDK segment: ${before.slice(0, 80)}`);
|
||||
source = source.replace(before, after);
|
||||
}
|
||||
return source;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { cpSync, existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import process from "node:process";
|
||||
|
||||
const root = process.cwd();
|
||||
const sdkPackage = "@echosixhiya/teamspeak-client";
|
||||
const packageJson = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
||||
const dependency = packageJson.dependencies?.[sdkPackage];
|
||||
const match = typeof dependency === "string" ? /^git\+(.+?)#(.+)$/.exec(dependency) : null;
|
||||
|
||||
if (!match) {
|
||||
throw new Error(`${sdkPackage} must be pinned to a Git repository commit`);
|
||||
}
|
||||
|
||||
const [, repository, commit] = match;
|
||||
const temporaryRoot = mkdtempSync(join(tmpdir(), "webspeak-sdk-build-"));
|
||||
const destination = join(root, "node_modules", "@echosixhiya", "teamspeak-client", "dist");
|
||||
|
||||
try {
|
||||
execFileSync("git", ["clone", "--no-checkout", repository, temporaryRoot], { stdio: "inherit" });
|
||||
execFileSync("git", ["checkout", "--detach", commit], { cwd: temporaryRoot, stdio: "inherit" });
|
||||
const npmOptions = { cwd: temporaryRoot, stdio: "inherit" };
|
||||
const runNpm = (args) => {
|
||||
if (process.platform === "win32") {
|
||||
execFileSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", `npm.cmd ${args.join(" ")}`], npmOptions);
|
||||
} else {
|
||||
execFileSync("npm", args, npmOptions);
|
||||
}
|
||||
};
|
||||
runNpm(["install", "--ignore-scripts", "--no-audit", "--no-fund"]);
|
||||
runNpm(["run", "build"]);
|
||||
|
||||
const source = join(temporaryRoot, "dist");
|
||||
if (!existsSync(join(source, "index.mjs"))) {
|
||||
throw new Error(`SDK build did not produce ${join(source, "index.mjs")}`);
|
||||
}
|
||||
|
||||
mkdirSync(dirname(destination), { recursive: true });
|
||||
mkdirSync(destination, { recursive: true });
|
||||
for (const entry of readdirSync(source)) {
|
||||
cpSync(join(source, entry), join(destination, entry), { recursive: true, force: true });
|
||||
}
|
||||
console.log(`Prepared ${sdkPackage} from ${commit}`);
|
||||
} finally {
|
||||
rmSync(temporaryRoot, { recursive: true, force: true });
|
||||
}
|
||||
@@ -332,6 +332,9 @@ 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),
|
||||
webRtcEnabled: body.webRtcEnabled === true,
|
||||
webRtcUdpStart: readOptionalInteger(body, "webRtcUdpStart"),
|
||||
webRtcUdpEnd: readOptionalInteger(body, "webRtcUdpEnd"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -349,6 +352,14 @@ function readString(body: Record<string, unknown>, key: string, max: number): st
|
||||
return body[key];
|
||||
}
|
||||
|
||||
function readOptionalInteger(body: Record<string, unknown>, key: string): number | undefined {
|
||||
if (body[key] === undefined) return undefined;
|
||||
if (typeof body[key] !== "number" || !Number.isSafeInteger(body[key])) {
|
||||
throw new AdminInputError("INVALID_REQUEST", `${key} is invalid`);
|
||||
}
|
||||
return body[key];
|
||||
}
|
||||
|
||||
function readOptionalString(body: Record<string, unknown>, key: string, max: number): string {
|
||||
return typeof body[key] === "string" ? body[key].slice(0, max) : "";
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ import { type AccessMode, type ManagedInviteRecord, type SettingsUpdate, WebSpea
|
||||
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 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";
|
||||
|
||||
export interface AdminSettingsInput {
|
||||
target: string;
|
||||
@@ -15,6 +17,9 @@ export interface AdminSettingsInput {
|
||||
accessMode: AccessMode;
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
webRtcEnabled: boolean;
|
||||
webRtcUdpStart?: number;
|
||||
webRtcUdpEnd?: number;
|
||||
}
|
||||
|
||||
export interface ConnectionPolicy {
|
||||
@@ -108,11 +113,22 @@ export class AdminService {
|
||||
lastTestAt: settings.lastTestAt,
|
||||
lastTestLatencyMs: settings.lastTestLatencyMs,
|
||||
lastTestError: settings.lastTestError,
|
||||
webRtcEnabled: settings.webRtcEnabled,
|
||||
webRtcUdpStart: settings.webRtcUdpStart,
|
||||
webRtcUdpEnd: settings.webRtcUdpEnd,
|
||||
internalPort: 3040,
|
||||
updatedAt: settings.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
getWebRtcAudioOptions(): WebRtcAudioOptions {
|
||||
const settings = this.database.getSettings();
|
||||
return {
|
||||
enabled: settings.webRtcEnabled,
|
||||
udpPortRange: [settings.webRtcUdpStart, settings.webRtcUdpEnd],
|
||||
};
|
||||
}
|
||||
|
||||
updateSettings(input: AdminSettingsInput): void {
|
||||
const current = this.database.getSettings();
|
||||
const settings = this.normalizeSettings(input, current);
|
||||
@@ -252,6 +268,23 @@ export class AdminService {
|
||||
if (input.accessMode !== "fixed" && input.accessMode !== "open") {
|
||||
throw new AdminInputError("INVALID_ACCESS_MODE", "Access mode is invalid");
|
||||
}
|
||||
if (typeof input.webRtcEnabled !== "boolean") {
|
||||
throw new AdminInputError("INVALID_WEBRTC_ENABLED", "WebRTC enabled value is invalid");
|
||||
}
|
||||
const webRtcUdpStart = input.webRtcUdpStart ?? current.webRtcUdpStart ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[0];
|
||||
const webRtcUdpEnd = input.webRtcUdpEnd ?? current.webRtcUdpEnd ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[1];
|
||||
if (!Number.isInteger(webRtcUdpStart) || webRtcUdpStart < WEBRTC_UDP_PORT_MIN || webRtcUdpStart > WEBRTC_UDP_PORT_MAX) {
|
||||
throw new AdminInputError("INVALID_WEBRTC_PORT_RANGE", "WebRTC UDP start port must be between 1024 and 65535");
|
||||
}
|
||||
if (!Number.isInteger(webRtcUdpEnd) || webRtcUdpEnd < WEBRTC_UDP_PORT_MIN || webRtcUdpEnd > WEBRTC_UDP_PORT_MAX) {
|
||||
throw new AdminInputError("INVALID_WEBRTC_PORT_RANGE", "WebRTC UDP end port must be between 1024 and 65535");
|
||||
}
|
||||
if (webRtcUdpStart > webRtcUdpEnd) {
|
||||
throw new AdminInputError("INVALID_WEBRTC_PORT_RANGE", "WebRTC UDP start port must not exceed the end port");
|
||||
}
|
||||
if (current.webRtcEnabled && (webRtcUdpStart !== current.webRtcUdpStart || webRtcUdpEnd !== current.webRtcUdpEnd)) {
|
||||
throw new AdminInputError("WEBRTC_PORT_LOCKED", "Disable WebRTC and save before changing its UDP port range");
|
||||
}
|
||||
|
||||
let encryptedPassword = current.tsPasswordEncrypted;
|
||||
const action = input.passwordAction ?? (input.serverPassword === undefined ? "keep" : "replace");
|
||||
@@ -264,6 +297,9 @@ export class AdminService {
|
||||
tsHost: target.host,
|
||||
tsPort: target.port,
|
||||
tsPasswordEncrypted: encryptedPassword,
|
||||
webRtcEnabled: input.webRtcEnabled,
|
||||
webRtcUdpStart,
|
||||
webRtcUdpEnd,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -292,6 +328,9 @@ export class AdminService {
|
||||
tsHost: settings.tsHost,
|
||||
tsPort: settings.tsPort,
|
||||
tsPasswordEncrypted: settings.tsPasswordEncrypted,
|
||||
webRtcEnabled: settings.webRtcEnabled,
|
||||
webRtcUdpStart: settings.webRtcUdpStart,
|
||||
webRtcUdpEnd: settings.webRtcUdpEnd,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -307,6 +346,9 @@ export class AdminService {
|
||||
tsHost: legacy.tsHost,
|
||||
tsPort: legacy.tsPort,
|
||||
tsPasswordEncrypted: legacy.tsServerPassword ? encryptSecret(legacy.tsServerPassword, this.masterSecret) : null,
|
||||
webRtcEnabled: current.webRtcEnabled,
|
||||
webRtcUdpStart: current.webRtcUdpStart,
|
||||
webRtcUdpEnd: current.webRtcUdpEnd,
|
||||
}, "LEGACY_CONFIG_IMPORTED");
|
||||
this.database.setMeta("legacy_config_imported", "1");
|
||||
this.database.setMeta("legacy_import_notice_pending", "1");
|
||||
|
||||
@@ -48,6 +48,7 @@ async function main() {
|
||||
certDir: hasCert ? CERT_DIR : undefined,
|
||||
voiceBridgeOptions: {
|
||||
joinTickets,
|
||||
webRtc: () => adminService.getWebRtcAudioOptions(),
|
||||
},
|
||||
adminService,
|
||||
logger,
|
||||
|
||||
@@ -4,8 +4,9 @@ import { dirname } from "node:path";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
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 = 2;
|
||||
export const DATABASE_SCHEMA_VERSION = 3;
|
||||
export type AccessMode = "fixed" | "open";
|
||||
|
||||
export interface PersistedSettings {
|
||||
@@ -19,6 +20,9 @@ export interface PersistedSettings {
|
||||
lastTestAt: string | null;
|
||||
lastTestLatencyMs: number | null;
|
||||
lastTestError: string | null;
|
||||
webRtcEnabled: boolean;
|
||||
webRtcUdpStart: number;
|
||||
webRtcUdpEnd: number;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
@@ -29,6 +33,9 @@ export interface SettingsUpdate {
|
||||
tsHost: string;
|
||||
tsPort: number;
|
||||
tsPasswordEncrypted: string | null;
|
||||
webRtcEnabled: boolean;
|
||||
webRtcUdpStart?: number;
|
||||
webRtcUdpEnd?: number;
|
||||
}
|
||||
|
||||
export interface ManagedInviteRecord {
|
||||
@@ -70,6 +77,10 @@ interface SettingsRow extends Record<string, unknown> {
|
||||
last_test_at: string | null;
|
||||
last_test_latency_ms: number | null;
|
||||
last_test_error: string | null;
|
||||
webrtc_enabled: number;
|
||||
webrtc_public_host: string;
|
||||
webrtc_udp_start: number;
|
||||
webrtc_udp_end: number;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
@@ -140,6 +151,9 @@ export class WebSpeakDatabase {
|
||||
lastTestAt: row.last_test_at,
|
||||
lastTestLatencyMs: row.last_test_latency_ms,
|
||||
lastTestError: row.last_test_error,
|
||||
webRtcEnabled: row.webrtc_enabled === 1,
|
||||
webRtcUdpStart: row.webrtc_udp_start,
|
||||
webRtcUdpEnd: row.webrtc_udp_end,
|
||||
updatedAt: row.updated_at,
|
||||
};
|
||||
}
|
||||
@@ -349,6 +363,20 @@ export class WebSpeakDatabase {
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 2");
|
||||
});
|
||||
version = 2;
|
||||
}
|
||||
if (version === 2) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
-- WebRTC media ports are stored with the administrator settings so the
|
||||
-- same range is used by the gateway and shown in the admin console.
|
||||
ALTER TABLE settings ADD COLUMN webrtc_enabled INTEGER NOT NULL DEFAULT 0 CHECK (webrtc_enabled IN (0, 1));
|
||||
ALTER TABLE settings ADD COLUMN webrtc_public_host TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE settings ADD COLUMN webrtc_udp_start INTEGER NOT NULL DEFAULT 40000 CHECK (webrtc_udp_start BETWEEN 1 AND 65535);
|
||||
ALTER TABLE settings ADD COLUMN webrtc_udp_end INTEGER NOT NULL DEFAULT 40099 CHECK (webrtc_udp_end BETWEEN 1 AND 65535);
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 3");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -356,7 +384,8 @@ export class WebSpeakDatabase {
|
||||
this.database.prepare(
|
||||
`UPDATE settings SET
|
||||
site_name = ?, welcome_text = ?, access_mode = ?, ts_host = ?, ts_port = ?,
|
||||
ts_password_encrypted = ?, updated_at = ?
|
||||
ts_password_encrypted = ?, webrtc_enabled = ?, webrtc_udp_start = ?,
|
||||
webrtc_udp_end = ?, updated_at = ?
|
||||
WHERE id = 1`,
|
||||
).run(
|
||||
settings.siteName,
|
||||
@@ -365,6 +394,9 @@ export class WebSpeakDatabase {
|
||||
settings.tsHost,
|
||||
settings.tsPort,
|
||||
settings.tsPasswordEncrypted,
|
||||
settings.webRtcEnabled ? 1 : 0,
|
||||
settings.webRtcUdpStart ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[0],
|
||||
settings.webRtcUdpEnd ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[1],
|
||||
now,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ClientInfo } from "@honeybbq/teamspeak-client";
|
||||
import type { ClientInfo } from "@echosixhiya/teamspeak-client";
|
||||
import type { TSDirectorySnapshot } from "./ts-client.js";
|
||||
|
||||
type DirectoryDelta =
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Prevents one persisted TeamSpeak identity from being used by two live
|
||||
* browser sessions at the same target at the same time.
|
||||
*/
|
||||
export class IdentityLeaseStore {
|
||||
private readonly owners = new Map<string, string>();
|
||||
|
||||
acquire(key: string, owner: string): boolean {
|
||||
const currentOwner = this.owners.get(key);
|
||||
if (currentOwner && currentOwner !== owner) return false;
|
||||
this.owners.set(key, owner);
|
||||
return true;
|
||||
}
|
||||
|
||||
release(key: string, owner: string): void {
|
||||
if (this.owners.get(key) === owner) this.owners.delete(key);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import { createAdminRouter } from "../admin/admin-router.js";
|
||||
import type { AdminService } from "../admin/admin-service.js";
|
||||
import { AdminSessionStore } from "../admin/admin-session.js";
|
||||
import { resolveSafeOpenTarget } from "../security/open-target-policy.js";
|
||||
import { identityFromString } from "@honeybbq/teamspeak-client";
|
||||
import { identityFromString } from "@echosixhiya/teamspeak-client";
|
||||
import { JoinRateLimiter } from "./join-rate-limit.js";
|
||||
|
||||
export interface WebServerOptions {
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
generateIdentity,
|
||||
type ClientOptions,
|
||||
type Identity,
|
||||
} from "@honeybbq/teamspeak-client";
|
||||
} from "@echosixhiya/teamspeak-client";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { normalizeTeamSpeakError } from "../errors.js";
|
||||
import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
|
||||
+10
-28
@@ -9,10 +9,10 @@ import {
|
||||
generateIdentity,
|
||||
type Identity,
|
||||
type VoiceData,
|
||||
type ChannelInfo,
|
||||
type ClientInfo,
|
||||
type DirectoryClientInfo,
|
||||
type DirectorySnapshot,
|
||||
type TextMessage,
|
||||
} from "@honeybbq/teamspeak-client";
|
||||
} from "@echosixhiya/teamspeak-client";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js";
|
||||
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
@@ -32,18 +32,8 @@ export interface TSVoiceData {
|
||||
data: Buffer;
|
||||
}
|
||||
|
||||
export interface TSDirectorySnapshot {
|
||||
channels: ChannelInfo[];
|
||||
clients: TSDirectoryClient[];
|
||||
}
|
||||
|
||||
export interface TSDirectoryClient extends ClientInfo {
|
||||
away?: boolean;
|
||||
awayMessage?: string;
|
||||
inputMuted?: boolean;
|
||||
outputMuted?: boolean;
|
||||
channelCommander?: boolean;
|
||||
}
|
||||
export type TSDirectorySnapshot = DirectorySnapshot;
|
||||
export type TSDirectoryClient = DirectoryClientInfo;
|
||||
|
||||
export type TSChatScope = "channel" | "server" | "private";
|
||||
|
||||
@@ -172,12 +162,10 @@ export class TSClient extends EventEmitter {
|
||||
} as TSVoiceData);
|
||||
});
|
||||
|
||||
// The SDK patch exposes the directory that TeamSpeak sends during the
|
||||
// normal client welcome sequence. The connect path also reconciles this
|
||||
// event stream with a complete client-protocol snapshot.
|
||||
(client as unknown as {
|
||||
on(event: "directorySnapshot", handler: (snapshot: TSDirectorySnapshot) => void): unknown;
|
||||
}).on("directorySnapshot", (snapshot) => {
|
||||
// The SDK exposes the directory that TeamSpeak sends during the normal
|
||||
// client welcome sequence. The connect path also reconciles this event
|
||||
// stream with a complete client-protocol snapshot.
|
||||
client.on("directorySnapshot", (snapshot) => {
|
||||
this.emit("directorySnapshot", {
|
||||
channels: snapshot.channels.slice(),
|
||||
clients: snapshot.clients.slice(),
|
||||
@@ -222,13 +210,7 @@ export class TSClient extends EventEmitter {
|
||||
if (!this.client || !this.connected) return;
|
||||
const targets = [...new Set(clientIds)].filter((clientId) => Number.isInteger(clientId) && clientId > 0 && clientId <= 65535 && clientId !== this.getClientId());
|
||||
if (!targets.length) throw new Error("Whisper requires at least one valid target");
|
||||
const whisperClient = this.client as unknown as {
|
||||
sendWhisper?: (voiceData: Uint8Array, targetClientIds: number[], voiceCodec: number) => void;
|
||||
};
|
||||
if (typeof whisperClient.sendWhisper !== "function") {
|
||||
throw new Error("TeamSpeak SDK whisper support is unavailable");
|
||||
}
|
||||
whisperClient.sendWhisper(data, targets, codec);
|
||||
this.client.sendWhisper(data, targets, codec);
|
||||
}
|
||||
|
||||
async sendTextMessage(scope: TSChatScope, message: string, targetId = 0n): Promise<void> {
|
||||
|
||||
+356
-8
@@ -1,16 +1,18 @@
|
||||
import { WebSocketServer, WebSocket } from "ws";
|
||||
import type { IncomingMessage, Server } from "node:http";
|
||||
import { createRequire } from "node:module";
|
||||
import { identityFromString } from "@honeybbq/teamspeak-client";
|
||||
import { identityFromString } from "@echosixhiya/teamspeak-client";
|
||||
import { DirectorySynchronizer } from "./directory-sync.js";
|
||||
import { TSClient, type TSDirectorySnapshot, type TSVoiceData } from "./ts-client.js";
|
||||
import type { Logger as LoggerType } from "../logger.js";
|
||||
import { normalizeTeamSpeakError } from "../errors.js";
|
||||
import { formatTeamSpeakTarget, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { JoinTicketStore, type JoinTicketPayload } from "./join-ticket.js";
|
||||
import { IdentityLeaseStore } from "./identity-lease.js";
|
||||
import { SessionManager, type ManagedSession, type SessionTeardownReason } from "./session-manager.js";
|
||||
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";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { OpusEncoder } = require("@discordjs/opus") as {
|
||||
@@ -19,9 +21,17 @@ const { OpusEncoder } = require("@discordjs/opus") as {
|
||||
|
||||
const HEARTBEAT_INTERVAL_MS = 30_000;
|
||||
const AUDIO_FRAME_BYTES = 1_920;
|
||||
// A browser audio frame is 20 ms of mono 48 kHz PCM. Keep the server-side
|
||||
// WebSocket egress queue small enough that a slow browser cannot turn old
|
||||
// voice into seconds of latency. Opus frames are variable-sized, so this is
|
||||
// deliberately a conservative byte backpressure guard for roughly 10–20
|
||||
// small Opus frames; the browser also enforces a time-based playback limit
|
||||
// before scheduling decoded audio.
|
||||
const MAX_SERVER_AUDIO_BUFFERED_BYTES = 4_096;
|
||||
|
||||
export interface VoiceBridgeOptions {
|
||||
joinTickets: JoinTicketStore;
|
||||
webRtc?: WebRtcAudioOptions | (() => WebRtcAudioOptions);
|
||||
}
|
||||
|
||||
export interface AdminSessionSummary {
|
||||
@@ -34,6 +44,53 @@ export interface AdminSessionSummary {
|
||||
tsClientId: number | null;
|
||||
channelId: string | null;
|
||||
memberCount: number;
|
||||
audio: AudioFlowStats;
|
||||
}
|
||||
|
||||
export interface AudioFlowStats {
|
||||
ingressFrames: number;
|
||||
ingressDroppedFrames: number;
|
||||
ingressFirstAt: number | null;
|
||||
ingressLastAt: number | null;
|
||||
ingressMaxGapMs: number;
|
||||
tsSendFrames: number;
|
||||
tsSendErrors: number;
|
||||
tsSendFirstAt: number | null;
|
||||
tsSendLastAt: number | null;
|
||||
tsSendMaxGapMs: number;
|
||||
tsEncodeMaxMs: number;
|
||||
tsReceiveFrames: number;
|
||||
tsReceiveFirstAt: number | null;
|
||||
tsReceiveLastAt: number | null;
|
||||
tsReceiveMaxGapMs: number;
|
||||
egressFrames: number;
|
||||
egressDroppedFrames: number;
|
||||
egressFirstAt: number | null;
|
||||
egressLastAt: number | null;
|
||||
egressMaxGapMs: number;
|
||||
egressSentFirstAt: number | null;
|
||||
egressSentLastAt: number | null;
|
||||
egressSentMaxGapMs: number;
|
||||
egressPeakBufferedBytes: number;
|
||||
egressFramesByClient: Record<string, number>;
|
||||
webrtcIngressRtpFrames: number;
|
||||
webrtcIngressRtpFirstAt: number | null;
|
||||
webrtcIngressRtpLastAt: number | null;
|
||||
webrtcIngressRtpMaxGapMs: number;
|
||||
webrtcEgressRtpFrames: number;
|
||||
webrtcEgressRtpFirstAt: number | null;
|
||||
webrtcEgressRtpLastAt: number | null;
|
||||
webrtcEgressRtpMaxGapMs: number;
|
||||
webrtcQueuePeakFrames: number;
|
||||
webrtcQueueDroppedFrames: number;
|
||||
webrtcQueueUnderrunTicks: number;
|
||||
webrtcPacerLateTicks: number;
|
||||
webrtcQueueCurrentFrames: number;
|
||||
webrtcIngressQuietFrames: number;
|
||||
webrtcIngressDecodeErrors: number;
|
||||
webrtcDownlinkDecodedFrames: number;
|
||||
webrtcDownlinkDecodeErrors: number;
|
||||
webrtcDownlinkShortFrames: number;
|
||||
}
|
||||
|
||||
interface ChannelMember {
|
||||
@@ -62,6 +119,8 @@ interface WebClientEntry {
|
||||
nickname: string;
|
||||
rememberIdentity: boolean;
|
||||
target: TeamSpeakTarget;
|
||||
identityLeaseKey?: string;
|
||||
webrtcPublicHost?: string;
|
||||
channelTree: unknown[];
|
||||
members: Map<number, ChannelMember>;
|
||||
eventLog: ServerEvent[];
|
||||
@@ -70,11 +129,14 @@ interface WebClientEntry {
|
||||
whisperActive: boolean;
|
||||
isAlive: boolean;
|
||||
reconnectTimer: ReturnType<typeof setTimeout> | null;
|
||||
audio: AudioFlowStats;
|
||||
webrtc: WebRtcAudioSession | null;
|
||||
}
|
||||
|
||||
export class VoiceBridge {
|
||||
private readonly sessionManager = new SessionManager();
|
||||
private readonly entries = new Map<string, WebClientEntry>();
|
||||
private readonly identityLeases = new IdentityLeaseStore();
|
||||
private wss: WebSocketServer | null = null;
|
||||
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private logger: LoggerType;
|
||||
@@ -100,6 +162,7 @@ export class VoiceBridge {
|
||||
|
||||
const { target, serverPassword, nickname } = connection;
|
||||
const channelName = connection.channel;
|
||||
const webrtcPublicHost = resolveWebRtcPublicHost(req);
|
||||
let identity;
|
||||
try {
|
||||
identity = connection.identity ? identityFromString(connection.identity) : undefined;
|
||||
@@ -118,11 +181,22 @@ export class VoiceBridge {
|
||||
return;
|
||||
}
|
||||
|
||||
const identityLeaseKey = identity
|
||||
? `${teamSpeakTargetKey(target)}:${identity.toString()}`
|
||||
: "";
|
||||
if (identityLeaseKey && !this.identityLeases.acquire(identityLeaseKey, entryId)) {
|
||||
this.logger.warn({ entryId, nickname, target: formatTeamSpeakTarget(target) }, "TeamSpeak identity already in use");
|
||||
void this.sessionManager.teardown(entryId, "teamSpeak-connect-failed");
|
||||
ws.close(4005, "IDENTITY_IN_USE");
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.info({ entryId, nickname, channel: channelName, target: formatTeamSpeakTarget(target) }, "WebClient connecting");
|
||||
let tsClient: TSClient;
|
||||
try {
|
||||
tsClient = new TSClient({ target, nickname, serverPassword, defaultChannel: channelName, identity }, this.logger);
|
||||
} catch (error: unknown) {
|
||||
if (identityLeaseKey) this.identityLeases.release(identityLeaseKey, entryId);
|
||||
this.logger.error({ err: error, entryId }, "Could not create TeamSpeak client");
|
||||
void this.sessionManager.teardown(entryId, "teamSpeak-connect-failed");
|
||||
ws.close(4003, "TeamSpeak client unavailable");
|
||||
@@ -136,6 +210,8 @@ export class VoiceBridge {
|
||||
nickname,
|
||||
rememberIdentity: connection.rememberIdentity === true,
|
||||
target,
|
||||
...(identityLeaseKey ? { identityLeaseKey } : {}),
|
||||
...(webrtcPublicHost ? { webrtcPublicHost } : {}),
|
||||
channelTree: [],
|
||||
members: new Map(),
|
||||
eventLog: [],
|
||||
@@ -144,6 +220,8 @@ export class VoiceBridge {
|
||||
whisperActive: false,
|
||||
isAlive: true,
|
||||
reconnectTimer: null,
|
||||
audio: createAudioFlowStats(),
|
||||
webrtc: null,
|
||||
};
|
||||
this.entries.set(entryId, entry!);
|
||||
try {
|
||||
@@ -238,6 +316,7 @@ export class VoiceBridge {
|
||||
serverEventLog: entry!.eventLog,
|
||||
whisperTargetIds: [...entry!.whisperTargetIds],
|
||||
whisperActive: entry!.whisperActive,
|
||||
webrtcAvailable: this.getWebRtcOptions()?.enabled === true,
|
||||
...(entry!.rememberIdentity ? { identity: tsClient.getIdentityString() } : {}),
|
||||
});
|
||||
sendJson({ type: "channelList", channels: entry!.channelTree });
|
||||
@@ -370,6 +449,7 @@ export class VoiceBridge {
|
||||
tsClient.on("clientLeave", (info) => {
|
||||
const wasKnown = entry!.members.has(info.id);
|
||||
const leavingMember = entry!.members.get(info.id);
|
||||
entry!.webrtc?.setMemberVolume(info.id, 1);
|
||||
directory.applyClientLeave(info.id);
|
||||
refreshDirectory();
|
||||
if (tsReady && initialStateSent && wasKnown) {
|
||||
@@ -392,22 +472,62 @@ export class VoiceBridge {
|
||||
});
|
||||
|
||||
tsClient.on("voiceData", (data: TSVoiceData) => {
|
||||
const receivedAt = Date.now();
|
||||
if (entry!.audio.tsReceiveLastAt !== null) entry!.audio.tsReceiveMaxGapMs = Math.max(entry!.audio.tsReceiveMaxGapMs, receivedAt - entry!.audio.tsReceiveLastAt);
|
||||
entry!.audio.tsReceiveFirstAt ??= receivedAt;
|
||||
entry!.audio.tsReceiveLastAt = receivedAt;
|
||||
entry!.audio.tsReceiveFrames++;
|
||||
if (ws.readyState !== WebSocket.OPEN || data.clientId === selfId) return;
|
||||
const webRtc = entry!.webrtc;
|
||||
webRtc?.pushTeamSpeakVoice(data);
|
||||
const now = receivedAt;
|
||||
if (entry!.audio.egressLastAt !== null) entry!.audio.egressMaxGapMs = Math.max(entry!.audio.egressMaxGapMs, now - entry!.audio.egressLastAt);
|
||||
entry!.audio.egressFirstAt ??= now;
|
||||
entry!.audio.egressLastAt = now;
|
||||
const sourceKey = String(data.clientId);
|
||||
entry!.audio.egressFramesByClient[sourceKey] = (entry!.audio.egressFramesByClient[sourceKey] ?? 0) + 1;
|
||||
// A negotiated WebRTC session owns the browser's realtime audio
|
||||
// egress. Do not also send the same TeamSpeak packet over the
|
||||
// reliable WebSocket, otherwise the browser plays two copies and
|
||||
// the TCP path can still accumulate stale audio behind the peer.
|
||||
if (webRtc) {
|
||||
entry!.audio.egressFrames++;
|
||||
return;
|
||||
}
|
||||
const packet = Buffer.allocUnsafe(3 + data.data.length);
|
||||
packet[0] = data.codec;
|
||||
packet.writeUInt16BE(data.clientId, 1);
|
||||
data.data.copy(packet, 3);
|
||||
ws.send(packet);
|
||||
const bufferedBytes = ws.bufferedAmount;
|
||||
entry!.audio.egressPeakBufferedBytes = Math.max(entry!.audio.egressPeakBufferedBytes, bufferedBytes);
|
||||
if (bufferedBytes > MAX_SERVER_AUDIO_BUFFERED_BYTES) {
|
||||
entry!.audio.egressDroppedFrames++;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
ws.send(packet);
|
||||
entry!.audio.egressFrames++;
|
||||
const sentAt = Date.now();
|
||||
if (entry!.audio.egressSentLastAt !== null) entry!.audio.egressSentMaxGapMs = Math.max(entry!.audio.egressSentMaxGapMs, sentAt - entry!.audio.egressSentLastAt);
|
||||
entry!.audio.egressSentFirstAt ??= sentAt;
|
||||
entry!.audio.egressSentLastAt = sentAt;
|
||||
} catch {
|
||||
entry!.audio.egressDroppedFrames++;
|
||||
}
|
||||
});
|
||||
|
||||
tsClient.on("textMessage", (message) => {
|
||||
const scope = message.targetMode === 1 ? "private" : message.targetMode === 3 ? "server" : message.targetMode === 2 ? "channel" : "server";
|
||||
const targetId = message.targetId ?? 0n;
|
||||
// TeamSpeak channel notifications omit `target`; the SDK represents
|
||||
// that as 0. Bind the broadcast to this session's current channel so
|
||||
// it remains visible now but cannot leak into another channel after a
|
||||
// later channel switch.
|
||||
const effectiveTargetId = scope === "channel" && targetId === 0n ? tsClient.getChannelId() : targetId;
|
||||
sendJson({
|
||||
type: "chatMessage",
|
||||
scope,
|
||||
// Keep event handling total: malformed/legacy SDK events must not
|
||||
// throw from this callback and tear down the browser session.
|
||||
targetId: String(message.targetId ?? 0n),
|
||||
...(effectiveTargetId !== 0n ? { targetId: String(effectiveTargetId) } : {}),
|
||||
senderUid: message.invokerUid,
|
||||
timestamp: Date.now(),
|
||||
invokerName: message.invokerName,
|
||||
@@ -434,22 +554,61 @@ export class VoiceBridge {
|
||||
if (isBinary) {
|
||||
const frame = typeof data === "string" ? Buffer.from(data) : data;
|
||||
if (!tsReady || frame.length !== AUDIO_FRAME_BYTES) {
|
||||
entry!.audio.ingressDroppedFrames++;
|
||||
sendProtocolError(sendJson, "INVALID_AUDIO_FRAME", "音频帧格式无效");
|
||||
return;
|
||||
}
|
||||
const now = Date.now();
|
||||
if (entry!.audio.ingressLastAt !== null) entry!.audio.ingressMaxGapMs = Math.max(entry!.audio.ingressMaxGapMs, now - entry!.audio.ingressLastAt);
|
||||
entry!.audio.ingressFirstAt ??= now;
|
||||
entry!.audio.ingressLastAt = now;
|
||||
entry!.audio.ingressFrames++;
|
||||
const encodeStartedAt = Date.now();
|
||||
try {
|
||||
if (entry!.opusEncoder) {
|
||||
const encoded = entry!.opusEncoder.encode(frame);
|
||||
const encodedAt = Date.now();
|
||||
entry!.audio.tsEncodeMaxMs = Math.max(entry!.audio.tsEncodeMaxMs, encodedAt - encodeStartedAt);
|
||||
if (entry!.whisperActive && entry!.whisperTargetIds.size) tsClient.sendWhisper(encoded, [...entry!.whisperTargetIds], 4);
|
||||
else tsClient.sendVoice(encoded, 4);
|
||||
const sentAt = Date.now();
|
||||
if (entry!.audio.tsSendLastAt !== null) entry!.audio.tsSendMaxGapMs = Math.max(entry!.audio.tsSendMaxGapMs, sentAt - entry!.audio.tsSendLastAt);
|
||||
entry!.audio.tsSendFirstAt ??= sentAt;
|
||||
entry!.audio.tsSendLastAt = sentAt;
|
||||
entry!.audio.tsSendFrames++;
|
||||
}
|
||||
} catch {
|
||||
// A frame arriving during shutdown is safe to discard.
|
||||
entry!.audio.tsSendErrors++;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const command = parseClientCommand(typeof data === "string" ? data : data.toString("utf-8"));
|
||||
const rawMessage = typeof data === "string" ? data : data.toString("utf-8");
|
||||
const webRtcOffer = parseWebRtcOffer(rawMessage);
|
||||
if (webRtcOffer) {
|
||||
if (this.getWebRtcOptions()?.enabled !== true) {
|
||||
sendProtocolError(sendJson, "WEBRTC_DISABLED", "WebRTC 音频传输未启用");
|
||||
return;
|
||||
}
|
||||
if (!tsReady || session.state !== "connected") {
|
||||
sendProtocolError(sendJson, "SESSION_NOT_READY", "TeamSpeak 会话尚未就绪");
|
||||
return;
|
||||
}
|
||||
void this.handleWebRtcOffer(entry!, webRtcOffer, sendJson);
|
||||
return;
|
||||
}
|
||||
if (isWebRtcStopMessage(rawMessage)) {
|
||||
const webRtc = entry!.webrtc;
|
||||
entry!.webrtc = null;
|
||||
if (webRtc) {
|
||||
void webRtc.close()
|
||||
.then(() => Object.assign(entry!.audio, webRtc.getStats()))
|
||||
.catch(() => undefined);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const command = parseClientCommand(rawMessage);
|
||||
if ("error" in command) {
|
||||
sendProtocolError(sendJson, command.error.code, command.error.message);
|
||||
return;
|
||||
@@ -537,6 +696,7 @@ export class VoiceBridge {
|
||||
tsClientId,
|
||||
channelId,
|
||||
memberCount: entry.members.size,
|
||||
audio: snapshotAudioStats(entry),
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -558,6 +718,12 @@ export class VoiceBridge {
|
||||
entry.reconnectTimer = null;
|
||||
}
|
||||
entry.opusEncoder = null;
|
||||
const webRtc = entry.webrtc;
|
||||
entry.webrtc = null;
|
||||
if (webRtc) {
|
||||
try { await webRtc.close(); } catch { /* peer teardown is idempotent */ }
|
||||
Object.assign(entry.audio, webRtc.getStats());
|
||||
}
|
||||
entry.whisperTargetIds.clear();
|
||||
entry.whisperActive = false;
|
||||
entry.channelTree = [];
|
||||
@@ -569,7 +735,8 @@ export class VoiceBridge {
|
||||
if (reason === "heartbeat-timeout" || reason === "gateway-shutdown") entry.ws.terminate();
|
||||
else entry.ws.close(reason === "protocol-error" ? 1008 : 1000, reason);
|
||||
}
|
||||
this.logger.info({ entryId: entry.id, reason }, "Client session torn down");
|
||||
if (entry.identityLeaseKey) this.identityLeases.release(entry.identityLeaseKey, entry.id);
|
||||
this.logger.info({ entryId: entry.id, reason, audio: { ...entry.audio } }, "Client session torn down");
|
||||
}
|
||||
|
||||
private startHeartbeat(): void {
|
||||
@@ -593,6 +760,96 @@ export class VoiceBridge {
|
||||
const token = url.searchParams.get("ticket");
|
||||
return token ? this.options.joinTickets.consume(token) : null;
|
||||
}
|
||||
|
||||
private getWebRtcOptions(): WebRtcAudioOptions | undefined {
|
||||
const configured = this.options.webRtc;
|
||||
return typeof configured === "function" ? configured() : configured;
|
||||
}
|
||||
|
||||
private async handleWebRtcOffer(
|
||||
entry: WebClientEntry,
|
||||
offer: WebRtcSessionDescription,
|
||||
sendJson: (message: Record<string, unknown>) => void,
|
||||
): Promise<void> {
|
||||
if (entry.webrtc) {
|
||||
const previousWebRtc = entry.webrtc;
|
||||
try { await previousWebRtc.close(); } catch { /* replace a retried offer */ }
|
||||
Object.assign(entry.audio, previousWebRtc.getStats());
|
||||
entry.webrtc = null;
|
||||
}
|
||||
const config = this.getWebRtcOptions();
|
||||
if (!config?.enabled) return;
|
||||
const peer = new WebRtcAudioSession({
|
||||
connectionId: entry.id,
|
||||
...(entry.webrtcPublicHost ? { publicHost: entry.webrtcPublicHost } : {}),
|
||||
udpPortRange: config.udpPortRange,
|
||||
logger: this.logger,
|
||||
microphoneMuted: offer.muted === true,
|
||||
accompanimentActive: offer.accompanimentActive === true,
|
||||
onVoiceFrame: (data, codec) => {
|
||||
const now = Date.now();
|
||||
if (entry.audio.ingressLastAt !== null) entry.audio.ingressMaxGapMs = Math.max(entry.audio.ingressMaxGapMs, now - entry.audio.ingressLastAt);
|
||||
entry.audio.ingressFirstAt ??= now;
|
||||
entry.audio.ingressLastAt = now;
|
||||
entry.audio.ingressFrames++;
|
||||
try {
|
||||
if (entry.whisperActive && entry.whisperTargetIds.size) entry.tsClient.sendWhisper(data, [...entry.whisperTargetIds], codec);
|
||||
else entry.tsClient.sendVoice(data, codec);
|
||||
const sentAt = Date.now();
|
||||
if (entry.audio.tsSendLastAt !== null) entry.audio.tsSendMaxGapMs = Math.max(entry.audio.tsSendMaxGapMs, sentAt - entry.audio.tsSendLastAt);
|
||||
entry.audio.tsSendFirstAt ??= sentAt;
|
||||
entry.audio.tsSendLastAt = sentAt;
|
||||
entry.audio.tsSendFrames++;
|
||||
} catch {
|
||||
entry.audio.tsSendErrors++;
|
||||
// A packet arriving while the TeamSpeak session is being replaced
|
||||
// is discarded; the WebRTC peer remains independently closable.
|
||||
}
|
||||
},
|
||||
onVoiceActivity: (clientIds) => {
|
||||
if (entry.ws.readyState === WebSocket.OPEN) sendJson({ type: "voiceActivity", clientIds });
|
||||
},
|
||||
});
|
||||
entry.webrtc = peer;
|
||||
try {
|
||||
const answer = await peer.createAnswer({ type: offer.type, sdp: offer.sdp });
|
||||
if (entry.webrtc !== peer || entry.ws.readyState !== WebSocket.OPEN) return;
|
||||
sendJson({ type: "webrtcAnswer", payload: { sdp: answer } });
|
||||
this.logger.info({ entryId: entry.id }, "WebRTC audio negotiation completed");
|
||||
} catch (error: unknown) {
|
||||
if (entry.webrtc === peer) entry.webrtc = null;
|
||||
try { await peer.close(); } catch { /* best effort */ }
|
||||
this.logger.warn({ entryId: entry.id, err: error instanceof Error ? error.message : String(error) }, "WebRTC audio negotiation failed");
|
||||
if (entry.ws.readyState === WebSocket.OPEN) sendJson({ type: "webrtcError", code: "WEBRTC_NEGOTIATION_FAILED" });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function resolveWebRtcPublicHost(request: IncomingMessage): string | undefined {
|
||||
const origin = firstHeader(request.headers.origin);
|
||||
const forwardedHost = firstHeader(request.headers["x-forwarded-host"]);
|
||||
const directHost = firstHeader(request.headers.host);
|
||||
for (const candidate of [origin, forwardedHost, directHost]) {
|
||||
const host = normalizeWebRtcHost(candidate);
|
||||
if (host) return host;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function firstHeader(value: string | string[] | undefined): string | undefined {
|
||||
return Array.isArray(value) ? value[0] : value;
|
||||
}
|
||||
|
||||
function normalizeWebRtcHost(value: string | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
const trimmed = value.split(",", 1)[0]?.trim();
|
||||
if (!trimmed || trimmed.toLowerCase() === "null") return undefined;
|
||||
try {
|
||||
const parsed = new URL(trimmed.includes("://") ? trimmed : `https://${trimmed}`);
|
||||
return parsed.hostname || undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCommand(
|
||||
@@ -662,6 +919,13 @@ async function handleCommand(
|
||||
}
|
||||
entry.whisperActive = active;
|
||||
sendJson({ type: "whisperTargets", targetIds: [...entry.whisperTargetIds], active: entry.whisperActive });
|
||||
} else if (command.type === "setMicrophoneMuted") {
|
||||
entry.webrtc?.setMicrophoneMuted(command.payload.muted as boolean);
|
||||
} else if (command.type === "setAccompanimentActive") {
|
||||
entry.webrtc?.setAccompanimentActive(command.payload.active as boolean);
|
||||
} else if (command.type === "setMemberVolume") {
|
||||
const clientId = command.payload.clientId as number;
|
||||
entry.webrtc?.setMemberVolume(clientId, command.payload.volume as number);
|
||||
}
|
||||
if (command.requestId) sendJson({ type: "commandCompleted", requestId: command.requestId });
|
||||
} catch (error: unknown) {
|
||||
@@ -685,10 +949,94 @@ function sendProtocolError(sendJson: (message: Record<string, unknown>) => void,
|
||||
sendJson({ type: "error", error: { code, message, recoverable: false } });
|
||||
}
|
||||
|
||||
function parseWebRtcOffer(raw: string): WebRtcSessionDescription | null {
|
||||
let value: unknown;
|
||||
try { value = JSON.parse(raw); } catch { return null; }
|
||||
if (!isRecord(value) || value.type !== "webrtcOffer" || !isRecord(value.payload) || !isRecord(value.payload.sdp)) return null;
|
||||
const description = value.payload.sdp;
|
||||
if (description.type !== "offer" || typeof description.sdp !== "string" || description.sdp.length > 256 * 1024) return null;
|
||||
if (value.payload.muted !== undefined && typeof value.payload.muted !== "boolean") return null;
|
||||
if (value.payload.accompanimentActive !== undefined && typeof value.payload.accompanimentActive !== "boolean") return null;
|
||||
return {
|
||||
type: "offer",
|
||||
sdp: description.sdp,
|
||||
muted: value.payload.muted === true,
|
||||
accompanimentActive: value.payload.accompanimentActive === true,
|
||||
};
|
||||
}
|
||||
|
||||
function isWebRtcStopMessage(raw: string): boolean {
|
||||
try {
|
||||
const value: unknown = JSON.parse(raw);
|
||||
return isRecord(value) && value.type === "webrtcStop";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isChannelRecord(value: unknown): value is { id: string; name: string } {
|
||||
return Boolean(value) && typeof value === "object" && typeof (value as { id?: unknown }).id === "string" && typeof (value as { name?: unknown }).name === "string";
|
||||
}
|
||||
|
||||
function createAudioFlowStats(): AudioFlowStats {
|
||||
return {
|
||||
ingressFrames: 0,
|
||||
ingressDroppedFrames: 0,
|
||||
ingressFirstAt: null,
|
||||
ingressLastAt: null,
|
||||
ingressMaxGapMs: 0,
|
||||
tsSendFrames: 0,
|
||||
tsSendErrors: 0,
|
||||
tsSendFirstAt: null,
|
||||
tsSendLastAt: null,
|
||||
tsSendMaxGapMs: 0,
|
||||
tsEncodeMaxMs: 0,
|
||||
tsReceiveFrames: 0,
|
||||
tsReceiveFirstAt: null,
|
||||
tsReceiveLastAt: null,
|
||||
tsReceiveMaxGapMs: 0,
|
||||
egressFrames: 0,
|
||||
egressDroppedFrames: 0,
|
||||
egressFirstAt: null,
|
||||
egressLastAt: null,
|
||||
egressMaxGapMs: 0,
|
||||
egressSentFirstAt: null,
|
||||
egressSentLastAt: null,
|
||||
egressSentMaxGapMs: 0,
|
||||
egressPeakBufferedBytes: 0,
|
||||
egressFramesByClient: {},
|
||||
webrtcIngressRtpFrames: 0,
|
||||
webrtcIngressRtpFirstAt: null,
|
||||
webrtcIngressRtpLastAt: null,
|
||||
webrtcIngressRtpMaxGapMs: 0,
|
||||
webrtcEgressRtpFrames: 0,
|
||||
webrtcEgressRtpFirstAt: null,
|
||||
webrtcEgressRtpLastAt: null,
|
||||
webrtcEgressRtpMaxGapMs: 0,
|
||||
webrtcQueuePeakFrames: 0,
|
||||
webrtcQueueDroppedFrames: 0,
|
||||
webrtcQueueUnderrunTicks: 0,
|
||||
webrtcPacerLateTicks: 0,
|
||||
webrtcQueueCurrentFrames: 0,
|
||||
webrtcIngressQuietFrames: 0,
|
||||
webrtcIngressDecodeErrors: 0,
|
||||
webrtcDownlinkDecodedFrames: 0,
|
||||
webrtcDownlinkDecodeErrors: 0,
|
||||
webrtcDownlinkShortFrames: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function snapshotAudioStats(entry: WebClientEntry): AudioFlowStats {
|
||||
const stats = { ...entry.audio };
|
||||
const webRtcStats: WebRtcAudioStats | undefined = entry.webrtc?.getStats();
|
||||
if (webRtcStats) Object.assign(stats, webRtcStats);
|
||||
return stats;
|
||||
}
|
||||
|
||||
function mapChannelTree(snapshot: TSDirectorySnapshot): unknown[] {
|
||||
return snapshot.channels.map((channel) => ({
|
||||
id: String(channel.id),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export interface ClientCommand {
|
||||
type: "switchChannel" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway" | "setWhisperTargets" | "setWhisperActive";
|
||||
type: "switchChannel" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway" | "setWhisperTargets" | "setWhisperActive" | "setMicrophoneMuted" | "setAccompanimentActive" | "setMemberVolume";
|
||||
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"]);
|
||||
const supportedTypes = new Set(["switchChannel", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume"]);
|
||||
if (!supportedTypes.has(value.type)) {
|
||||
return { error: { code: "UNKNOWN_MESSAGE_TYPE", message: "不支持的消息类型" } };
|
||||
}
|
||||
@@ -56,6 +56,15 @@ export function parseClientCommand(raw: string): ClientCommandResult {
|
||||
if (value.type === "setWhisperActive" && typeof value.payload.active !== "boolean") {
|
||||
return { error: { code: "INVALID_WHISPER_STATE", message: "私语状态无效" } };
|
||||
}
|
||||
if (value.type === "setMicrophoneMuted" && typeof value.payload.muted !== "boolean") {
|
||||
return { error: { code: "INVALID_MICROPHONE_STATE", message: "麦克风状态无效" } };
|
||||
}
|
||||
if (value.type === "setAccompanimentActive" && typeof value.payload.active !== "boolean") {
|
||||
return { error: { code: "INVALID_ACCOMPANIMENT_STATE", message: "伴奏状态无效" } };
|
||||
}
|
||||
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: "成员音量无效" } };
|
||||
}
|
||||
return {
|
||||
type: value.type as ClientCommand["type"],
|
||||
...(typeof value.requestId === "string" ? { requestId: value.requestId } : {}),
|
||||
|
||||
@@ -0,0 +1,505 @@
|
||||
import { randomInt } from "node:crypto";
|
||||
import { createRequire } from "node:module";
|
||||
import {
|
||||
MediaStreamTrack,
|
||||
RtpHeader,
|
||||
RtpPacket,
|
||||
RTCPeerConnection,
|
||||
} from "werift";
|
||||
import type { Logger as LoggerType } from "../logger.js";
|
||||
import type { TSVoiceData } from "./ts-client.js";
|
||||
import { WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
|
||||
|
||||
export { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { OpusEncoder } = require("@discordjs/opus") as {
|
||||
OpusEncoder: new (sampleRate: number, channels: number) => {
|
||||
decode(data: Buffer): Buffer;
|
||||
encode(data: Buffer): Buffer;
|
||||
};
|
||||
};
|
||||
|
||||
const AUDIO_SAMPLE_RATE = 48_000;
|
||||
const AUDIO_FRAME_SAMPLES = 960;
|
||||
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
|
||||
const DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE = 111;
|
||||
const AUDIO_CLOCK_INTERVAL_MS = 20;
|
||||
const SPEAKER_ACTIVITY_INTERVAL_MS = 100;
|
||||
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;
|
||||
|
||||
// WebRTC is served by the WebSpeak process itself. The default range is also
|
||||
// published by the bundled Docker Compose file; advanced administrators can
|
||||
// change it in the admin console before enabling WebRTC.
|
||||
export interface WebRtcAudioOptions {
|
||||
enabled: boolean;
|
||||
udpPortRange?: [number, number];
|
||||
}
|
||||
|
||||
export interface WebRtcSessionDescription {
|
||||
type: "offer" | "answer";
|
||||
sdp: string;
|
||||
muted?: boolean;
|
||||
accompanimentActive?: boolean;
|
||||
}
|
||||
|
||||
export interface WebRtcAudioSessionOptions {
|
||||
connectionId: string;
|
||||
publicHost?: string;
|
||||
udpPortRange?: [number, number];
|
||||
logger: LoggerType;
|
||||
microphoneMuted?: boolean;
|
||||
accompanimentActive?: boolean;
|
||||
onVoiceFrame: (data: Buffer, codec: 4 | 5) => void;
|
||||
onVoiceActivity: (clientIds: number[]) => void;
|
||||
}
|
||||
|
||||
export interface WebRtcAudioStats {
|
||||
webrtcIngressRtpFrames: number;
|
||||
webrtcIngressRtpFirstAt: number | null;
|
||||
webrtcIngressRtpLastAt: number | null;
|
||||
webrtcIngressRtpMaxGapMs: number;
|
||||
webrtcEgressRtpFrames: number;
|
||||
webrtcEgressRtpFirstAt: number | null;
|
||||
webrtcEgressRtpLastAt: number | null;
|
||||
webrtcEgressRtpMaxGapMs: number;
|
||||
webrtcQueuePeakFrames: number;
|
||||
webrtcQueueDroppedFrames: number;
|
||||
webrtcQueueUnderrunTicks: number;
|
||||
webrtcPacerLateTicks: number;
|
||||
webrtcQueueCurrentFrames: number;
|
||||
webrtcIngressQuietFrames: number;
|
||||
webrtcIngressDecodeErrors: number;
|
||||
webrtcDownlinkDecodedFrames: number;
|
||||
webrtcDownlinkDecodeErrors: number;
|
||||
webrtcDownlinkShortFrames: number;
|
||||
}
|
||||
|
||||
interface PendingAudioFrame {
|
||||
pcm: Buffer;
|
||||
receivedAt: number;
|
||||
/** Preserve a native 20 ms Opus frame when no mix is required. */
|
||||
opus?: Buffer;
|
||||
}
|
||||
|
||||
interface SelectedAudioFrame extends PendingAudioFrame {
|
||||
clientId: number;
|
||||
volume: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* One low-latency WebRTC audio session for one browser connection.
|
||||
*
|
||||
* TeamSpeak provides one Opus payload per speaker. WebRTC has one negotiated
|
||||
* audio track in this first transport, so this class mixes one 20 ms frame
|
||||
* from each active speaker and packetizes the result as RTP. Each speaker has
|
||||
* a very small bounded queue so bursts from the TeamSpeak adapter can be
|
||||
* smoothed without turning into an ever-growing playback delay.
|
||||
*/
|
||||
export class WebRtcAudioSession {
|
||||
readonly peer: RTCPeerConnection;
|
||||
private readonly logger: LoggerType;
|
||||
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[]>();
|
||||
private readonly memberVolumes = new Map<number, number>();
|
||||
private readonly activeSpeakerIds = new Set<number>();
|
||||
private readonly opusPayloadTypes = new Set<number>();
|
||||
private audioTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private readonly activityTimer: ReturnType<typeof setInterval>;
|
||||
private encoder: { encode(data: Buffer): Buffer } | null;
|
||||
private sequenceNumber = randomInt(0, 65_536);
|
||||
private timestamp = randomInt(0, 0x1_0000_0000) >>> 0;
|
||||
private readonly ssrc = randomInt(1, 0x1_0000_0000) >>> 0;
|
||||
private outgoingPayloadType = DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE;
|
||||
private closed = false;
|
||||
private nextAudioDeadline = 0;
|
||||
private lastIngressRtpAt: number | null = null;
|
||||
private lastEgressRtpAt: number | null = null;
|
||||
private lastQueueEnqueuedAt: number | null = null;
|
||||
private accompanimentActive: boolean;
|
||||
private readonly stats: WebRtcAudioStats = {
|
||||
webrtcIngressRtpFrames: 0,
|
||||
webrtcIngressRtpFirstAt: null,
|
||||
webrtcIngressRtpLastAt: null,
|
||||
webrtcIngressRtpMaxGapMs: 0,
|
||||
webrtcEgressRtpFrames: 0,
|
||||
webrtcEgressRtpFirstAt: null,
|
||||
webrtcEgressRtpLastAt: null,
|
||||
webrtcEgressRtpMaxGapMs: 0,
|
||||
webrtcQueuePeakFrames: 0,
|
||||
webrtcQueueDroppedFrames: 0,
|
||||
webrtcQueueUnderrunTicks: 0,
|
||||
webrtcPacerLateTicks: 0,
|
||||
webrtcQueueCurrentFrames: 0,
|
||||
webrtcIngressQuietFrames: 0,
|
||||
webrtcIngressDecodeErrors: 0,
|
||||
webrtcDownlinkDecodedFrames: 0,
|
||||
webrtcDownlinkDecodeErrors: 0,
|
||||
webrtcDownlinkShortFrames: 0,
|
||||
};
|
||||
|
||||
constructor(options: WebRtcAudioSessionOptions) {
|
||||
this.logger = options.logger.child({ component: "webrtc-audio", connectionId: options.connectionId });
|
||||
this.onVoiceFrame = options.onVoiceFrame;
|
||||
this.onVoiceActivity = options.onVoiceActivity;
|
||||
this.accompanimentActive = options.accompanimentActive === true;
|
||||
this.outgoingTrack = new MediaStreamTrack({ kind: "audio" });
|
||||
|
||||
const iceAdditionalHostAddresses = options.publicHost ? [options.publicHost] : undefined;
|
||||
const udpPortRange = options.udpPortRange ?? WEBRTC_UDP_PORT_RANGE;
|
||||
this.peer = new RTCPeerConnection({
|
||||
iceServers: [],
|
||||
iceUseIpv4: true,
|
||||
iceUseIpv6: false,
|
||||
iceUseTcp: false,
|
||||
icePortRange: [...udpPortRange] as [number, number],
|
||||
...(iceAdditionalHostAddresses ? { iceAdditionalHostAddresses } : {}),
|
||||
});
|
||||
|
||||
const audio = this.peer.addTransceiver("audio", { direction: "sendrecv" });
|
||||
audio.onTrack.subscribe((track) => {
|
||||
track.onReceiveRtp.subscribe((rtp) => {
|
||||
if (this.closed) return;
|
||||
const receivedAt = performance.now();
|
||||
if (this.lastIngressRtpAt !== null) this.stats.webrtcIngressRtpMaxGapMs = Math.max(this.stats.webrtcIngressRtpMaxGapMs, Math.round(receivedAt - this.lastIngressRtpAt));
|
||||
this.lastIngressRtpAt = receivedAt;
|
||||
this.stats.webrtcIngressRtpFirstAt ??= Date.now();
|
||||
this.stats.webrtcIngressRtpLastAt = Date.now();
|
||||
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;
|
||||
}
|
||||
this.onVoiceFrame(payload, this.accompanimentActive ? 5 : 4);
|
||||
});
|
||||
void audio.sender.replaceTrack(this.outgoingTrack).catch((error: unknown) => {
|
||||
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not attach WebRTC output track");
|
||||
});
|
||||
});
|
||||
void audio.sender.replaceTrack(this.outgoingTrack).catch((error: unknown) => {
|
||||
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not prepare WebRTC output track");
|
||||
});
|
||||
|
||||
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) {
|
||||
this.outgoingTrack.stop();
|
||||
throw new Error("WebRTC Opus codec is unavailable");
|
||||
}
|
||||
|
||||
this.nextAudioDeadline = performance.now();
|
||||
this.scheduleAudioTick();
|
||||
this.activityTimer = setInterval(() => this.flushSpeakerActivity(), SPEAKER_ACTIVITY_INTERVAL_MS);
|
||||
this.activityTimer.unref?.();
|
||||
this.peer.onconnectionstatechange = () => {
|
||||
this.logger.info({ state: this.peer.connectionState }, "WebRTC connection state changed");
|
||||
};
|
||||
}
|
||||
|
||||
getStats(): WebRtcAudioStats {
|
||||
return { ...this.stats, webrtcQueueCurrentFrames: this.getQueueFrameCount() };
|
||||
}
|
||||
|
||||
async createAnswer(offer: WebRtcSessionDescription): Promise<WebRtcSessionDescription> {
|
||||
if (this.closed) throw new Error("WebRTC session is closed");
|
||||
this.setOpusPayloadTypes(offer.sdp);
|
||||
await this.peer.setRemoteDescription(offer);
|
||||
const transceiver = this.peer.getTransceivers().find((candidate) => candidate.kind === "audio");
|
||||
if (transceiver) await transceiver.sender.replaceTrack(this.outgoingTrack);
|
||||
const answer = await this.peer.createAnswer();
|
||||
await this.peer.setLocalDescription(answer);
|
||||
const description = this.peer.localDescription;
|
||||
if (!description) throw new Error("WebRTC answer was not created");
|
||||
if (description.type !== "answer" && description.type !== "offer") throw new Error("Unexpected WebRTC answer type");
|
||||
return { type: description.type, sdp: description.sdp };
|
||||
}
|
||||
|
||||
pushTeamSpeakVoice(data: TSVoiceData): void {
|
||||
if (this.closed || (data.codec !== 4 && data.codec !== 5)) return;
|
||||
let decoder = this.decoderByClient.get(data.clientId);
|
||||
if (!decoder) {
|
||||
try {
|
||||
// @discordjs/opus exposes decoding on OpusEncoder instances too;
|
||||
// there is no separate OpusDecoder constructor in that package.
|
||||
decoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
|
||||
this.decoderByClient.set(data.clientId, decoder);
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer decoder");
|
||||
return;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const pcm = decoder.decode(data.data);
|
||||
this.stats.webrtcDownlinkDecodedFrames++;
|
||||
if (pcm.length < 2) {
|
||||
this.stats.webrtcDownlinkShortFrames++;
|
||||
return;
|
||||
}
|
||||
// TeamSpeak may deliver 10/20/40/60 ms Opus frames. Keep a partial
|
||||
// decoded frame per speaker and split every decoded buffer into the
|
||||
// fixed 20 ms cadence used by the WebRTC mixer instead of discarding
|
||||
// anything after the first 20 ms.
|
||||
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);
|
||||
const canForwardOpus = !pendingPcm && pcm.length === AUDIO_FRAME_BYTES;
|
||||
let offset = 0;
|
||||
let enqueued = false;
|
||||
let queue = this.pendingFrames.get(data.clientId);
|
||||
while (offset + AUDIO_FRAME_BYTES <= combined.length) {
|
||||
if (!queue) {
|
||||
queue = [];
|
||||
this.pendingFrames.set(data.clientId, queue);
|
||||
}
|
||||
if (queue.length >= MAX_MIXER_QUEUE_FRAMES) {
|
||||
queue.shift();
|
||||
this.stats.webrtcQueueDroppedFrames++;
|
||||
}
|
||||
queue.push({
|
||||
pcm: Buffer.from(combined.subarray(offset, offset + AUDIO_FRAME_BYTES)),
|
||||
receivedAt: performance.now(),
|
||||
...(canForwardOpus && offset === 0 ? { opus: Buffer.from(data.data) } : {}),
|
||||
});
|
||||
enqueued = true;
|
||||
offset += AUDIO_FRAME_BYTES;
|
||||
}
|
||||
if (offset < combined.length) this.partialPcmByClient.set(data.clientId, Buffer.from(combined.subarray(offset)));
|
||||
else this.partialPcmByClient.delete(data.clientId);
|
||||
if (enqueued) {
|
||||
this.lastQueueEnqueuedAt = performance.now();
|
||||
this.stats.webrtcQueuePeakFrames = Math.max(this.stats.webrtcQueuePeakFrames, this.getQueueFrameCount());
|
||||
}
|
||||
} catch {
|
||||
this.stats.webrtcDownlinkDecodeErrors++;
|
||||
// A malformed or codec-transition packet is discarded without touching
|
||||
// the peer connection. The next valid Opus frame can recover the stream.
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
if (this.audioTimer) clearTimeout(this.audioTimer);
|
||||
this.audioTimer = null;
|
||||
clearInterval(this.activityTimer);
|
||||
this.pendingFrames.clear();
|
||||
this.memberVolumes.clear();
|
||||
this.partialPcmByClient.clear();
|
||||
this.activeSpeakerIds.clear();
|
||||
this.ingressDecoder = null;
|
||||
this.decoderByClient.clear();
|
||||
this.encoder = null;
|
||||
this.outgoingTrack.stop();
|
||||
await this.peer.close();
|
||||
}
|
||||
|
||||
private scheduleAudioTick(): void {
|
||||
if (this.closed) return;
|
||||
const delay = Math.max(0, this.nextAudioDeadline - performance.now());
|
||||
this.audioTimer = setTimeout(() => this.flushAudio(), delay);
|
||||
this.audioTimer.unref?.();
|
||||
}
|
||||
|
||||
private flushAudio(): void {
|
||||
if (this.closed) return;
|
||||
const now = performance.now();
|
||||
if (now > this.nextAudioDeadline + MAX_MIXER_PACER_LAG_MS) {
|
||||
this.stats.webrtcPacerLateTicks++;
|
||||
this.nextAudioDeadline = now;
|
||||
this.trimQueuesAfterLateTick();
|
||||
}
|
||||
this.nextAudioDeadline += AUDIO_CLOCK_INTERVAL_MS;
|
||||
this.audioTimer = null;
|
||||
this.mixAndSendAudio();
|
||||
this.scheduleAudioTick();
|
||||
}
|
||||
|
||||
private mixAndSendAudio(): void {
|
||||
if (!this.encoder) {
|
||||
return;
|
||||
}
|
||||
if (!this.pendingFrames.size) {
|
||||
if (this.lastQueueEnqueuedAt !== null && performance.now() - this.lastQueueEnqueuedAt <= MIXER_UNDERRUN_WINDOW_MS) {
|
||||
this.stats.webrtcQueueUnderrunTicks++;
|
||||
}
|
||||
}
|
||||
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES);
|
||||
const selectedFrames: SelectedAudioFrame[] = [];
|
||||
for (const [clientId, queue] of this.pendingFrames) {
|
||||
const frame = queue.shift();
|
||||
if (queue.length === 0) this.pendingFrames.delete(clientId);
|
||||
if (!frame) continue;
|
||||
const volume = this.memberVolumes.get(clientId) ?? 1;
|
||||
selectedFrames.push({ ...frame, clientId, volume });
|
||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
|
||||
mixed[index] += Math.round(frame.pcm.readInt16LE(index * 2) * volume);
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedFrames.length === 1 && selectedFrames[0]?.opus && selectedFrames[0].volume === 1) {
|
||||
this.sendRtpAudio(selectedFrames[0].opus);
|
||||
return;
|
||||
}
|
||||
|
||||
const pcm = Buffer.allocUnsafe(AUDIO_FRAME_BYTES);
|
||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
|
||||
// Keep a fixed gain for the mixed path. Per-sample soft limiting changes
|
||||
// the waveform's apparent loudness as the source level changes, which
|
||||
// is especially noticeable on music. Only clip actual overflow caused
|
||||
// by simultaneous speakers; never normalize by the active speaker count.
|
||||
const sample = Math.max(-32_768, Math.min(32_767, mixed[index]!));
|
||||
pcm.writeInt16LE(sample, index * 2);
|
||||
}
|
||||
try {
|
||||
const encoded = this.encoder.encode(pcm);
|
||||
this.sendRtpAudio(encoded);
|
||||
} catch {
|
||||
// A peer closing concurrently may reject a packet; teardown owns the
|
||||
// session lifecycle and no per-frame error needs to reach the logs.
|
||||
}
|
||||
}
|
||||
|
||||
private sendRtpAudio(encoded: Buffer): void {
|
||||
const packet = new RtpPacket(new RtpHeader({
|
||||
payloadType: this.outgoingPayloadType,
|
||||
sequenceNumber: this.sequenceNumber,
|
||||
timestamp: this.timestamp,
|
||||
ssrc: this.ssrc,
|
||||
marker: true,
|
||||
}), encoded);
|
||||
this.sequenceNumber = (this.sequenceNumber + 1) & 0xffff;
|
||||
this.timestamp = (this.timestamp + AUDIO_FRAME_SAMPLES) >>> 0;
|
||||
this.outgoingTrack.writeRtp(packet);
|
||||
const sentAt = performance.now();
|
||||
if (this.lastEgressRtpAt !== null) this.stats.webrtcEgressRtpMaxGapMs = Math.max(this.stats.webrtcEgressRtpMaxGapMs, Math.round(sentAt - this.lastEgressRtpAt));
|
||||
this.lastEgressRtpAt = sentAt;
|
||||
this.stats.webrtcEgressRtpFirstAt ??= Date.now();
|
||||
this.stats.webrtcEgressRtpLastAt = Date.now();
|
||||
this.stats.webrtcEgressRtpFrames++;
|
||||
}
|
||||
|
||||
private flushSpeakerActivity(): void {
|
||||
if (this.closed || !this.activeSpeakerIds.size) return;
|
||||
const ids = [...this.activeSpeakerIds];
|
||||
this.activeSpeakerIds.clear();
|
||||
this.onVoiceActivity(ids);
|
||||
}
|
||||
|
||||
setMicrophoneMuted(muted: boolean): void {
|
||||
// The browser sends a mixed microphone/accompaniment track. The mute gain
|
||||
// is applied before RTP encoding, so a server-side mute flag must not drop
|
||||
// the whole packet and silence a still-playing accompaniment.
|
||||
void muted;
|
||||
}
|
||||
|
||||
setAccompanimentActive(active: boolean): void {
|
||||
this.accompanimentActive = active;
|
||||
}
|
||||
|
||||
setMemberVolume(clientId: number, volume: number): void {
|
||||
if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535 || !Number.isFinite(volume)) return;
|
||||
const normalized = Math.max(0, Math.min(4, volume));
|
||||
if (normalized === 1) this.memberVolumes.delete(clientId);
|
||||
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;
|
||||
for (let index = 0; index + 1 < pcm.length; index += 2) {
|
||||
const sample = pcm.readInt16LE(index);
|
||||
sum += sample * sample;
|
||||
samples++;
|
||||
}
|
||||
return samples ? Math.sqrt(sum / samples) : 0;
|
||||
}
|
||||
|
||||
private trimQueuesAfterLateTick(): void {
|
||||
const now = performance.now();
|
||||
for (const [clientId, queue] of this.pendingFrames) {
|
||||
while (queue.length > 1) {
|
||||
queue.shift();
|
||||
this.stats.webrtcQueueDroppedFrames++;
|
||||
}
|
||||
if (queue[0] && now - queue[0].receivedAt > MAX_MIXER_FRAME_AGE_MS) {
|
||||
queue.shift();
|
||||
this.stats.webrtcQueueDroppedFrames++;
|
||||
}
|
||||
if (queue.length === 0) this.pendingFrames.delete(clientId);
|
||||
}
|
||||
}
|
||||
|
||||
private getQueueFrameCount(): number {
|
||||
let count = 0;
|
||||
for (const queue of this.pendingFrames.values()) count += queue.length;
|
||||
return count;
|
||||
}
|
||||
|
||||
private setOpusPayloadTypes(sdp: string): void {
|
||||
this.opusPayloadTypes.clear();
|
||||
for (const match of sdp.matchAll(/^a=rtpmap:(\d+)\s+opus\/48000(?:\/\d+)?/gim)) {
|
||||
const payloadType = Number(match[1]);
|
||||
if (!Number.isInteger(payloadType) || payloadType < 0 || payloadType > 127) continue;
|
||||
this.opusPayloadTypes.add(payloadType);
|
||||
this.outgoingPayloadType = payloadType;
|
||||
}
|
||||
if (!this.opusPayloadTypes.size) this.opusPayloadTypes.add(DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/** Default WebRTC media port range used by WebSpeak and its Docker image. */
|
||||
export const DEFAULT_WEBRTC_UDP_PORT_RANGE: [number, number] = [40000, 40099];
|
||||
|
||||
// Kept as a public alias for callers that used the original fixed-range name.
|
||||
export const WEBRTC_UDP_PORT_RANGE = DEFAULT_WEBRTC_UDP_PORT_RANGE;
|
||||
export const WEBRTC_UDP_PORT_MIN = 1024;
|
||||
export const WEBRTC_UDP_PORT_MAX = 65535;
|
||||
+25
-1
@@ -111,11 +111,35 @@ test("admin API requires the default password to be changed before administratio
|
||||
accessMode: "open",
|
||||
siteName: "Changed",
|
||||
welcomeText: "Open access",
|
||||
webRtcEnabled: true,
|
||||
webRtcUdpStart: 41000,
|
||||
webRtcUdpEnd: 41099,
|
||||
},
|
||||
});
|
||||
assert.equal(saved.body.ok, true);
|
||||
assert.equal(saved.body.settings.accessMode, "open");
|
||||
assert.equal(saved.body.settings.hasPassword, false);
|
||||
assert.equal(saved.body.settings.webRtcEnabled, true);
|
||||
assert.equal(saved.body.settings.webRtcUdpStart, 41000);
|
||||
assert.equal(saved.body.settings.webRtcUdpEnd, 41099);
|
||||
|
||||
const lockedPorts = await request(origin, "/api/admin/server", {
|
||||
method: "PUT",
|
||||
cookie,
|
||||
csrf: login.body.csrfToken,
|
||||
body: {
|
||||
target: "voice.example.com:9988",
|
||||
passwordAction: "keep",
|
||||
accessMode: "open",
|
||||
siteName: "Changed",
|
||||
welcomeText: "Open access",
|
||||
webRtcEnabled: true,
|
||||
webRtcUdpStart: 42000,
|
||||
webRtcUdpEnd: 42099,
|
||||
},
|
||||
});
|
||||
assert.equal(lockedPorts.response.status, 400);
|
||||
assert.equal(lockedPorts.body.code, "WEBRTC_PORT_LOCKED");
|
||||
|
||||
const invite = await request(origin, "/api/admin/invites", {
|
||||
method: "POST",
|
||||
@@ -137,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, 2);
|
||||
assert.equal(diagnostics.body.database.schemaVersion, 3);
|
||||
assert.equal("target" in diagnostics.body.teamSpeak, true);
|
||||
assert.equal("protocol" in diagnostics.body.teamSpeak, false);
|
||||
|
||||
|
||||
@@ -54,6 +54,9 @@ test("legacy config imports once, seeds the default admin, and allows password r
|
||||
accessMode: "open",
|
||||
siteName: "Open WebSpeak",
|
||||
welcomeText: "Public gateway",
|
||||
webRtcEnabled: true,
|
||||
webRtcUdpStart: 41000,
|
||||
webRtcUdpEnd: 41099,
|
||||
});
|
||||
const publicConfig = service.getPublicConfig();
|
||||
assert.equal(publicConfig.target, "public.example.com:9987");
|
||||
@@ -61,6 +64,19 @@ test("legacy config imports once, seeds the default admin, and allows password r
|
||||
assert.equal("serverPassword" in service.getAdminSettings(), false);
|
||||
assert.equal(service.getAdminSettings().hasPassword, true);
|
||||
assert.equal(service.getConnectionPolicy().serverPassword, "replacement-secret");
|
||||
assert.equal(service.getAdminSettings().webRtcEnabled, true);
|
||||
assert.equal(service.getAdminSettings().webRtcUdpStart, 41000);
|
||||
assert.equal(service.getAdminSettings().webRtcUdpEnd, 41099);
|
||||
assert.deepEqual(service.getWebRtcAudioOptions(), { enabled: true, udpPortRange: [41000, 41099] });
|
||||
assert.throws(() => service.updateSettings({
|
||||
target: "public.example.com:9987",
|
||||
accessMode: "open",
|
||||
siteName: "Open WebSpeak",
|
||||
welcomeText: "Public gateway",
|
||||
webRtcEnabled: true,
|
||||
webRtcUdpStart: 42000,
|
||||
webRtcUdpEnd: 42099,
|
||||
}), /Disable WebRTC/);
|
||||
database.close();
|
||||
});
|
||||
|
||||
@@ -106,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, 2);
|
||||
assert.equal(reopened.schemaVersion, 3);
|
||||
assert.equal(reopened.listManagedInvites().length, 3);
|
||||
reopened.close();
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { ChannelInfo, ClientInfo } from "@honeybbq/teamspeak-client";
|
||||
import type { ChannelInfo, ClientInfo } from "@echosixhiya/teamspeak-client";
|
||||
import { DirectorySynchronizer } from "../src/server/directory-sync.js";
|
||||
|
||||
const root: ChannelInfo = { id: 1n, parentID: 0n, name: "Lobby", description: "", };
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { IdentityLeaseStore } from "../src/server/identity-lease.js";
|
||||
|
||||
test("an identity lease rejects a second live owner and ignores a release from another owner", () => {
|
||||
const store = new IdentityLeaseStore();
|
||||
assert.equal(store.acquire("target:identity", "first"), true);
|
||||
assert.equal(store.acquire("target:identity", "second"), false);
|
||||
store.release("target:identity", "second");
|
||||
assert.equal(store.acquire("target:identity", "second"), false);
|
||||
store.release("target:identity", "first");
|
||||
assert.equal(store.acquire("target:identity", "second"), true);
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { generateIdentity } from "@honeybbq/teamspeak-client";
|
||||
import { generateIdentity } from "@echosixhiya/teamspeak-client";
|
||||
import { JoinTicketStore } from "../src/server/join-ticket.js";
|
||||
|
||||
test("join tickets are opaque, one-time, and expire", () => {
|
||||
|
||||
@@ -23,6 +23,9 @@ test("SQLite persistence initializes schema and stores the single admin/settings
|
||||
tsHost: "voice.example.com",
|
||||
tsPort: 9988,
|
||||
tsPasswordEncrypted: "v1:ciphertext",
|
||||
webRtcEnabled: true,
|
||||
webRtcUdpStart: 41000,
|
||||
webRtcUdpEnd: 41099,
|
||||
});
|
||||
assert.equal(database.hasAdmin(), true);
|
||||
assert.equal(database.getAdminCredential()?.hash, credential.hash);
|
||||
@@ -37,6 +40,9 @@ test("SQLite persistence initializes schema and stores the single admin/settings
|
||||
lastTestAt: null,
|
||||
lastTestLatencyMs: null,
|
||||
lastTestError: null,
|
||||
webRtcEnabled: true,
|
||||
webRtcUdpStart: 41000,
|
||||
webRtcUdpEnd: 41099,
|
||||
updatedAt: database.getSettings().updatedAt,
|
||||
});
|
||||
assert.equal(database.recentAudit()[0]?.event, "ADMIN_INITIALIZED");
|
||||
@@ -48,7 +54,7 @@ test("SQLite persistence initializes schema and stores the single admin/settings
|
||||
reopened.close();
|
||||
});
|
||||
|
||||
test("SQLite schema v1 upgrades to v2 with a migration copy", () => {
|
||||
test("SQLite schema v1 upgrades to v3 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);
|
||||
@@ -68,7 +74,10 @@ test("SQLite schema v1 upgrades to v2 with a migration copy", () => {
|
||||
legacy.close();
|
||||
|
||||
const upgraded = new WebSpeakDatabase(dbPath);
|
||||
assert.equal(upgraded.schemaVersion, 2);
|
||||
assert.equal(upgraded.schemaVersion, 3);
|
||||
assert.equal(upgraded.getSettings().webRtcEnabled, false);
|
||||
assert.equal(upgraded.getSettings().webRtcUdpStart, 40000);
|
||||
assert.equal(upgraded.getSettings().webRtcUdpEnd, 40099);
|
||||
assert.equal(upgraded.listManagedInvites().length, 0);
|
||||
assert.equal(existsSync(`${dbPath}.schema-1.bak`), true);
|
||||
upgraded.close();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { generateIdentity } from "@honeybbq/teamspeak-client";
|
||||
import { generateIdentity } from "@echosixhiya/teamspeak-client";
|
||||
import { parseTeamSpeakTarget } from "../src/domain/teamspeak-target.js";
|
||||
import { TSClient, toTSChatMessage } from "../src/server/ts-client.js";
|
||||
import { silentLogger } from "./helpers/logger.js";
|
||||
|
||||
@@ -73,3 +73,36 @@ test("voice protocol validates whisper targets and its independent push state",
|
||||
error: { code: "INVALID_WHISPER_STATE", message: "私语状态无效" },
|
||||
});
|
||||
});
|
||||
|
||||
test("voice protocol accepts and validates the microphone mute state", () => {
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setMicrophoneMuted", payload: { muted: true } })), {
|
||||
type: "setMicrophoneMuted",
|
||||
payload: { muted: true },
|
||||
});
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setMicrophoneMuted", payload: { muted: "yes" } })), {
|
||||
error: { code: "INVALID_MICROPHONE_STATE", message: "麦克风状态无效" },
|
||||
});
|
||||
});
|
||||
|
||||
test("voice protocol accepts and validates the accompaniment state", () => {
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setAccompanimentActive", payload: { active: true } })), {
|
||||
type: "setAccompanimentActive",
|
||||
payload: { active: true },
|
||||
});
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setAccompanimentActive", payload: { active: "yes" } })), {
|
||||
error: { code: "INVALID_ACCOMPANIMENT_STATE", message: "伴奏状态无效" },
|
||||
});
|
||||
});
|
||||
|
||||
test("voice protocol accepts and validates per-member volume", () => {
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setMemberVolume", payload: { clientId: 7, volume: 1.5 } })), {
|
||||
type: "setMemberVolume",
|
||||
payload: { clientId: 7, volume: 1.5 },
|
||||
});
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setMemberVolume", payload: { clientId: 7, volume: 4.1 } })), {
|
||||
error: { code: "INVALID_MEMBER_VOLUME", message: "成员音量无效" },
|
||||
});
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setMemberVolume", payload: { clientId: 7, volume: Number.NaN } })), {
|
||||
error: { code: "INVALID_MEMBER_VOLUME", message: "成员音量无效" },
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#006a64" />
|
||||
<meta name="description" content="WebSpeak — TeamSpeak browser voice workspace" />
|
||||
<link rel="icon" type="image/jpeg" href="/网站图标.jpg" />
|
||||
<title>WebSpeak · TeamSpeak Web Client</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
const FRAME_SAMPLES = 960;
|
||||
|
||||
class WebSpeakMicCaptureProcessor extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
super();
|
||||
this.frame = new Float32Array(FRAME_SAMPLES);
|
||||
this.offset = 0;
|
||||
}
|
||||
|
||||
process(inputs, outputs) {
|
||||
const input = inputs[0]?.[0];
|
||||
const output = outputs[0]?.[0];
|
||||
if (output) output.fill(0);
|
||||
if (!input) return true;
|
||||
|
||||
let inputOffset = 0;
|
||||
while (inputOffset < input.length) {
|
||||
const count = Math.min(input.length - inputOffset, FRAME_SAMPLES - this.offset);
|
||||
this.frame.set(input.subarray(inputOffset, inputOffset + count), this.offset);
|
||||
this.offset += count;
|
||||
inputOffset += count;
|
||||
if (this.offset !== FRAME_SAMPLES) continue;
|
||||
|
||||
let sum = 0;
|
||||
for (let index = 0; index < this.frame.length; index++) sum += this.frame[index] * this.frame[index];
|
||||
const frame = this.frame;
|
||||
this.frame = new Float32Array(FRAME_SAMPLES);
|
||||
this.offset = 0;
|
||||
this.port.postMessage({ samples: frame, rms: Math.sqrt(sum / FRAME_SAMPLES) }, [frame.buffer]);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor("webspeak-mic-capture", WebSpeakMicCaptureProcessor);
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 55 KiB |
@@ -31,7 +31,12 @@
|
||||
</template>
|
||||
<path v-else-if="name === 'mic'" d="M12 14a3 3 0 0 0 3-3V6a3 3 0 0 0-6 0v5a3 3 0 0 0 3 3Zm-7-3a7 7 0 0 0 14 0m-7 7v3m-3 0h6" />
|
||||
<path v-else-if="name === 'mic-off'" d="m4 4 16 16M10 6v5a2 2 0 0 0 3.2 1.6M14 6V5a2 2 0 0 0-3.7-1M5 11a7 7 0 0 0 10.6 6m3.4-6a7 7 0 0 0-.5-2.5M12 18v3m-3 0h6" />
|
||||
<path v-else-if="name === 'headset'" d="M4 14v-2a8 8 0 0 1 16 0v2M4 14h3v5H5a1 1 0 0 1-1-1zm16 0h-3v5h2a1 1 0 0 0 1-1z" />
|
||||
<template v-else-if="name === 'music'">
|
||||
<path d="M9 18V5l10-2v13" />
|
||||
<circle cx="6" cy="18" r="3" />
|
||||
<circle cx="16" cy="16" r="3" />
|
||||
</template>
|
||||
<path v-else-if="name === 'headset'" d="M4 14v-2a8 8 0 0 1 16 0v2M4 14h3v5H5a1 1 0 0 1-1-1zm16 0h-3v5h2a1 1 0 0 1-1-1z" />
|
||||
<path v-else-if="name === 'volume'" d="M4 10v4h3l4 3V7l-4 3zm10.5-2.5a6 6 0 0 1 0 9m2-11a9 9 0 0 1 0 13" />
|
||||
<path v-else-if="name === 'volume-off'" d="m4 4 16 16M4 10v4h3l4 3V7l-4 3z" />
|
||||
<template v-else-if="name === 'search'">
|
||||
@@ -68,6 +73,11 @@
|
||||
<path v-else-if="name === 'door'" d="M10 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5m5 14 5-5-5-5m5 5H9" />
|
||||
<path v-else-if="name === 'waveform'" d="M3 12h2l2-6 3 12 3-9 2 6h6" />
|
||||
<path v-else-if="name === 'shield'" d="M12 21s8-3.5 8-10V5l-8-3-8 3v6c0 6.5 8 10 8 10Z" />
|
||||
<template v-else-if="name === 'sun'">
|
||||
<circle cx="12" cy="12" r="4" />
|
||||
<path d="M12 2v2m0 16v2M4.93 4.93l1.42 1.42m11.3 11.3 1.42 1.42M2 12h2m16 0h2M4.93 19.07l1.42-1.42m11.3-11.3 1.42-1.42" />
|
||||
</template>
|
||||
<path v-else-if="name === 'moon'" d="M20.4 15.2A8.5 8.5 0 0 1 8.8 3.6 8.5 8.5 0 1 0 20.4 15.2Z" />
|
||||
<path v-else-if="name === 'monitor'" d="M4 4h16v12H4zM8 20h8M12 16v4" />
|
||||
<path v-else-if="name === '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" />
|
||||
<path v-else-if="name === 'check'" d="m5 12 4 4L19 6" />
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { reactive, ref } from "vue";
|
||||
import { loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js";
|
||||
|
||||
const micCaptureWorkletUrl = "/mic-capture-worklet.js";
|
||||
|
||||
export interface VoiceState {
|
||||
connected: boolean;
|
||||
connecting: boolean;
|
||||
@@ -42,6 +44,10 @@ type SinkAudioContext = AudioContext & {
|
||||
setSinkId?: (sinkId: string) => Promise<void>;
|
||||
};
|
||||
|
||||
type SinkAudioElement = HTMLAudioElement & {
|
||||
setSinkId?: (sinkId: string) => Promise<void>;
|
||||
};
|
||||
|
||||
export interface ChannelInfo {
|
||||
id: string;
|
||||
parentID: string;
|
||||
@@ -80,19 +86,42 @@ 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 webrtcPeer: RTCPeerConnection | null = null;
|
||||
let webrtcOutputElement: SinkAudioElement | null = null;
|
||||
let webrtcPlaybackStream: MediaStream | null = null;
|
||||
let webrtcPlaybackRetryCleanup: (() => void) | null = null;
|
||||
let webrtcNegotiationPromise: Promise<void> | null = null;
|
||||
let webrtcFallbackStarted = false;
|
||||
const webrtcActive = ref(false);
|
||||
const identityMaterial = ref("");
|
||||
const storedVolumesByUid = reactive<Record<string, number>>({});
|
||||
let microphoneStartPromise: Promise<void> | null = null;
|
||||
|
||||
// Audio capture. The ScriptProcessor path remains the most compatible option
|
||||
// for the current browser support matrix, but the graph now has an explicit
|
||||
// input gain and a silent output to avoid monitoring the microphone locally.
|
||||
// WebRTC carries audio when the gateway advertises it. The bounded PCM
|
||||
// WebSocket path remains the compatibility fallback for older browsers and
|
||||
// for deployments where the gateway's built-in UDP media range is unavailable.
|
||||
let audioCtx: SinkAudioContext | null = null;
|
||||
let micStream: MediaStream | null = null;
|
||||
let scriptNode: ScriptProcessorNode | null = null;
|
||||
let workletNode: AudioWorkletNode | null = null;
|
||||
let workletContext: AudioContext | null = null;
|
||||
let workletModulePromise: Promise<void> | null = null;
|
||||
let micSource: MediaStreamAudioSourceNode | null = null;
|
||||
let micGain: GainNode | null = null;
|
||||
let silentGain: GainNode | null = null;
|
||||
const accompanimentActive = ref(false);
|
||||
const accompanimentSupported = ref(typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getDisplayMedia));
|
||||
const accompanimentErrorCode = ref<"" | "unsupported" | "needsWebRtc" | "noAudio" | "permission">("");
|
||||
let accompanimentStream: MediaStream | null = null;
|
||||
let webrtcMixDestination: MediaStreamAudioDestinationNode | null = null;
|
||||
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;
|
||||
let webrtcMicMonitorTimer: ReturnType<typeof setInterval> | null = null;
|
||||
const inputDevices = reactive<AudioInputDevice[]>([]);
|
||||
const outputDevices = reactive<AudioOutputDevice[]>([]);
|
||||
const selectedInputDeviceId = ref(typeof localStorage !== "undefined" ? localStorage.getItem("webspeak:input-device") ?? "" : "");
|
||||
@@ -113,7 +142,7 @@ export function useVoiceWebSocket() {
|
||||
let voxAttack = 0;
|
||||
let voxRelease = 0;
|
||||
const VOX_HOLD = 15;
|
||||
const VOX_ATTACK_FRAMES = 2;
|
||||
const VOX_ATTACK_FRAMES = 1;
|
||||
let convBuf = new Int16Array(1024);
|
||||
let accumBuf = new Int16Array(2048);
|
||||
let accumLen = 0;
|
||||
@@ -121,7 +150,10 @@ export function useVoiceWebSocket() {
|
||||
// Playback is kept per client so frames from multiple speakers cannot
|
||||
// interleave into one decoder or one scheduling queue.
|
||||
const remoteDecoders = new Map<number, AudioDecoder>();
|
||||
const remoteDecoderGenerations = new Map<number, number>();
|
||||
let nextRemoteDecoderGeneration = 0;
|
||||
const remotePlayTimes = new Map<number, number>();
|
||||
const remotePlaybackSources = new Map<number, Set<AudioBufferSourceNode>>();
|
||||
const remoteGains = new Map<number, GainNode>();
|
||||
const remoteDecodeTimestamps = new Map<number, number>();
|
||||
const volumes = reactive<Record<number, number>>({});
|
||||
@@ -130,8 +162,15 @@ export function useVoiceWebSocket() {
|
||||
const whisperActive = ref(false);
|
||||
const speakingTimers = new Map<number, ReturnType<typeof setTimeout>>();
|
||||
const SPEAKING_HOLD_MS = 360;
|
||||
const MAX_AUDIO_BUFFERED_BYTES = 192_000;
|
||||
let droppedAudioFrames = 0;
|
||||
const AUDIO_FRAME_SAMPLES = 960;
|
||||
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
|
||||
const MAX_AUDIO_BUFFERED_FRAMES = 10;
|
||||
const MAX_AUDIO_BUFFERED_BYTES = AUDIO_FRAME_BYTES * MAX_AUDIO_BUFFERED_FRAMES;
|
||||
// Keep the WebSocket playback buffer below the 100 ms latency target. A
|
||||
// 20 ms frame plus three queued decoder frames leaves only a short cushion
|
||||
// for jitter; stale audio is discarded instead of being played late.
|
||||
const MAX_REMOTE_PLAY_AHEAD_SECONDS = 0.08;
|
||||
const MAX_REMOTE_DECODE_QUEUE_FRAMES = 3;
|
||||
|
||||
async function saveAudioPreferences(): Promise<void> {
|
||||
await saveLocalPreferences({
|
||||
@@ -200,7 +239,8 @@ export function useVoiceWebSocket() {
|
||||
audioCtx.addEventListener("statechange", () => {
|
||||
if (audioCtx) audioContextState.value = audioCtx.state;
|
||||
});
|
||||
outputDeviceSupported.value = typeof audioCtx.setSinkId === "function";
|
||||
outputDeviceSupported.value = typeof audioCtx.setSinkId === "function"
|
||||
|| typeof (HTMLMediaElement.prototype as SinkAudioElement).setSinkId === "function";
|
||||
if (selectedOutputDeviceId.value && outputDeviceSupported.value) {
|
||||
void setAudioSink(audioCtx, selectedOutputDeviceId.value).catch(() => undefined);
|
||||
}
|
||||
@@ -213,13 +253,46 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
async function setAudioSink(ctx: SinkAudioContext, deviceId: string): Promise<void> {
|
||||
if (!ctx.setSinkId) {
|
||||
const mediaSinkSupported = typeof (HTMLMediaElement.prototype as SinkAudioElement).setSinkId === "function";
|
||||
if (!ctx.setSinkId && !mediaSinkSupported) {
|
||||
outputDeviceSupported.value = false;
|
||||
if (deviceId) throw new Error("当前浏览器不支持扬声器设备选择,将使用默认输出设备");
|
||||
return;
|
||||
}
|
||||
outputDeviceSupported.value = true;
|
||||
await ctx.setSinkId(deviceId || "default");
|
||||
if (ctx.setSinkId) await ctx.setSinkId(deviceId || "default");
|
||||
if (webrtcOutputElement?.setSinkId) await webrtcOutputElement.setSinkId(deviceId || "default");
|
||||
}
|
||||
|
||||
function installWebRtcPlaybackRetry(): void {
|
||||
if (webrtcPlaybackRetryCleanup) return;
|
||||
const retry = () => { void syncWebRtcPlayback(); };
|
||||
const events: (keyof WindowEventMap)[] = ["pointerdown", "touchstart", "keydown"];
|
||||
for (const event of events) window.addEventListener(event, retry, { passive: true });
|
||||
document.addEventListener("visibilitychange", retry, { passive: true });
|
||||
webrtcPlaybackRetryCleanup = () => {
|
||||
for (const event of events) window.removeEventListener(event, retry);
|
||||
document.removeEventListener("visibilitychange", retry);
|
||||
webrtcPlaybackRetryCleanup = null;
|
||||
};
|
||||
}
|
||||
|
||||
async function syncWebRtcPlayback(): Promise<void> {
|
||||
const output = webrtcOutputElement;
|
||||
if (!output || !webrtcPlaybackStream) return;
|
||||
// Keep WebRTC on the browser's native MediaStream playback path. The
|
||||
// capture AudioContext is intentionally not used as a second output
|
||||
// route: a running-but-silent graph could leave the UI reporting a live
|
||||
// speaker while the actual remote audio element remained muted.
|
||||
output.muted = false;
|
||||
try {
|
||||
await output.play();
|
||||
webrtcPlaybackRetryCleanup?.();
|
||||
} catch {
|
||||
// Mobile and privacy-focused browsers can require a gesture even for a
|
||||
// MediaStream. Keep retrying after the next real interaction.
|
||||
installWebRtcPlaybackRetry();
|
||||
}
|
||||
}
|
||||
|
||||
function checkSupport(): string | null {
|
||||
@@ -295,18 +368,16 @@ export function useVoiceWebSocket() {
|
||||
micSource = ctx.createMediaStreamSource(micStream);
|
||||
micGain = ctx.createGain();
|
||||
micGain.gain.value = inputVolume.value;
|
||||
scriptNode = ctx.createScriptProcessor(1024, 1, 1);
|
||||
silentGain = ctx.createGain();
|
||||
silentGain.gain.value = 0;
|
||||
|
||||
scriptNode.onaudioprocess = (event) => {
|
||||
const input = event.inputBuffer.getChannelData(0);
|
||||
let sum = 0;
|
||||
for (let i = 0; i < input.length; i++) sum += input[i] * input[i];
|
||||
micLevel.value = Math.min(1, Math.sqrt(sum / Math.max(1, input.length)) * 6);
|
||||
const handleCaptureChunk = (input: Float32Array, rms?: number): void => {
|
||||
if (!input.length) return;
|
||||
micLevel.value = Math.min(1, (rms ?? Math.sqrt(input.reduce((sum, sample) => sum + sample * sample, 0) / input.length)) * 6);
|
||||
const socket = ws.value;
|
||||
const shouldSend = !microphoneMuted.value
|
||||
&& !microphoneTestActive.value
|
||||
&& !webrtcActive.value
|
||||
&& socket?.readyState === WebSocket.OPEN
|
||||
&& voxGate(input);
|
||||
if (!shouldSend) {
|
||||
@@ -321,16 +392,15 @@ export function useVoiceWebSocket() {
|
||||
accumLen = 0;
|
||||
return;
|
||||
}
|
||||
if (socket.bufferedAmount > MAX_AUDIO_BUFFERED_BYTES) {
|
||||
const bufferedBytes = socket.bufferedAmount;
|
||||
if (bufferedBytes > MAX_AUDIO_BUFFERED_BYTES) {
|
||||
accumLen = 0;
|
||||
droppedAudioFrames++;
|
||||
return;
|
||||
}
|
||||
markSpeaking(state.tsClientId);
|
||||
|
||||
if (convBuf.length < input.length) convBuf = new Int16Array(input.length);
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
const sample = Math.max(-1, Math.min(1, input[i]));
|
||||
const sample = Math.max(-1, Math.min(1, input[i]!));
|
||||
convBuf[i] = sample < 0 ? sample * 0x8000 : sample * 0x7fff;
|
||||
}
|
||||
|
||||
@@ -340,17 +410,48 @@ export function useVoiceWebSocket() {
|
||||
accumLen = need;
|
||||
|
||||
let offset = 0;
|
||||
while (offset + 960 <= accumLen && socket.readyState === WebSocket.OPEN && socket.bufferedAmount <= MAX_AUDIO_BUFFERED_BYTES) {
|
||||
socket.send(accumBuf.slice(offset, offset + 960).buffer);
|
||||
offset += 960;
|
||||
while (offset + AUDIO_FRAME_SAMPLES <= accumLen && socket.readyState === WebSocket.OPEN && socket.bufferedAmount <= MAX_AUDIO_BUFFERED_BYTES) {
|
||||
socket.send(accumBuf.slice(offset, offset + AUDIO_FRAME_SAMPLES).buffer);
|
||||
offset += AUDIO_FRAME_SAMPLES;
|
||||
}
|
||||
if (offset > 0) markSpeaking(state.tsClientId);
|
||||
accumLen -= offset;
|
||||
if (offset > 0) accumBuf.set(accumBuf.subarray(offset, offset + accumLen), 0);
|
||||
};
|
||||
|
||||
if (typeof AudioWorkletNode !== "undefined" && ctx.audioWorklet) {
|
||||
try {
|
||||
if (workletContext !== ctx || !workletModulePromise) {
|
||||
workletContext = ctx;
|
||||
workletModulePromise = ctx.audioWorklet.addModule(micCaptureWorkletUrl);
|
||||
}
|
||||
await workletModulePromise;
|
||||
workletNode = new AudioWorkletNode(ctx, "webspeak-mic-capture", {
|
||||
numberOfInputs: 1,
|
||||
numberOfOutputs: 1,
|
||||
outputChannelCount: [1],
|
||||
});
|
||||
workletNode.port.onmessage = (event: MessageEvent<{ samples?: Float32Array; rms?: number }>) => {
|
||||
const samples = event.data?.samples;
|
||||
if (samples instanceof Float32Array) handleCaptureChunk(samples, event.data.rms);
|
||||
};
|
||||
} catch {
|
||||
workletNode?.disconnect();
|
||||
workletNode = null;
|
||||
workletContext = null;
|
||||
workletModulePromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (!workletNode) {
|
||||
scriptNode = ctx.createScriptProcessor(1024, 1, 1);
|
||||
scriptNode.onaudioprocess = (event) => handleCaptureChunk(event.inputBuffer.getChannelData(0));
|
||||
}
|
||||
|
||||
micSource.connect(micGain);
|
||||
micGain.connect(scriptNode);
|
||||
scriptNode.connect(silentGain);
|
||||
const captureNode = workletNode ?? scriptNode!;
|
||||
micGain.connect(captureNode);
|
||||
captureNode.connect(silentGain);
|
||||
silentGain.connect(ctx.destination);
|
||||
await refreshAudioDevices();
|
||||
}
|
||||
@@ -383,24 +484,348 @@ export function useVoiceWebSocket() {
|
||||
return false;
|
||||
}
|
||||
|
||||
function stopMicrophone(closeContext = true): void {
|
||||
function stopWebRtcMix(): void {
|
||||
webrtcMixAccompanimentSource?.disconnect();
|
||||
webrtcMixAccompanimentGain?.disconnect();
|
||||
webrtcMixMicSource?.disconnect();
|
||||
webrtcMixMicGain?.disconnect();
|
||||
webrtcMixDestination?.disconnect();
|
||||
webrtcMixAccompanimentSource = null;
|
||||
webrtcMixAccompanimentGain = null;
|
||||
webrtcMixMicSource = null;
|
||||
webrtcMixMicGain = null;
|
||||
webrtcMixDestination = null;
|
||||
}
|
||||
|
||||
function releaseAccompanimentStream(): void {
|
||||
accompanimentStream?.getTracks().forEach((track) => track.stop());
|
||||
accompanimentStream = null;
|
||||
accompanimentActive.value = false;
|
||||
}
|
||||
|
||||
function createWebRtcMixStream(): MediaStream {
|
||||
if (!micStream) throw new Error("没有可用的麦克风音轨");
|
||||
const ctx = getAudioCtx();
|
||||
stopWebRtcMix();
|
||||
const destination = ctx.createMediaStreamDestination();
|
||||
destination.channelCount = 1;
|
||||
destination.channelCountMode = "explicit";
|
||||
const microphoneSource = ctx.createMediaStreamSource(micStream);
|
||||
const microphoneGain = ctx.createGain();
|
||||
microphoneGain.gain.value = microphoneMuted.value ? 0 : inputVolume.value;
|
||||
microphoneSource.connect(microphoneGain);
|
||||
microphoneGain.connect(destination);
|
||||
|
||||
webrtcMixDestination = destination;
|
||||
webrtcMixMicSource = microphoneSource;
|
||||
webrtcMixMicGain = microphoneGain;
|
||||
|
||||
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);
|
||||
webrtcMixAccompanimentSource = accompanimentSource;
|
||||
webrtcMixAccompanimentGain = accompanimentGain;
|
||||
}
|
||||
return destination.stream;
|
||||
}
|
||||
|
||||
async function replaceWebRtcAudioTrack(): Promise<void> {
|
||||
if (!webrtcPeer || !micStream) return;
|
||||
const sender = webrtcPeer.getSenders().find((candidate) => candidate.track?.kind === "audio");
|
||||
if (!sender) throw new Error("WebRTC 音频轨道尚未就绪");
|
||||
const mixedStream = createWebRtcMixStream();
|
||||
const mixedTrack = mixedStream.getAudioTracks()[0];
|
||||
if (!mixedTrack) throw new Error("混合音频轨道创建失败");
|
||||
await sender.replaceTrack(mixedTrack);
|
||||
}
|
||||
|
||||
async function startAccompaniment(): Promise<void> {
|
||||
accompanimentErrorCode.value = "";
|
||||
if (!accompanimentSupported.value) {
|
||||
accompanimentErrorCode.value = "unsupported";
|
||||
throw new Error("伴奏共享不可用");
|
||||
}
|
||||
if (!webrtcActive.value || !webrtcPeer || !micStream) {
|
||||
accompanimentErrorCode.value = "needsWebRtc";
|
||||
throw new Error("伴奏功能需要启用 WebRTC");
|
||||
}
|
||||
|
||||
const audioConstraints = {} as MediaTrackConstraints & { restrictOwnAudio?: boolean };
|
||||
const supportedConstraints = navigator.mediaDevices.getSupportedConstraints?.() as Record<string, boolean> | undefined;
|
||||
if (supportedConstraints?.restrictOwnAudio) audioConstraints.restrictOwnAudio = true;
|
||||
const options = {
|
||||
video: { displaySurface: "browser" },
|
||||
audio: audioConstraints,
|
||||
selfBrowserSurface: "exclude",
|
||||
systemAudio: "include",
|
||||
windowAudio: "window",
|
||||
} as unknown as DisplayMediaStreamOptions;
|
||||
|
||||
let nextStream: MediaStream;
|
||||
try {
|
||||
nextStream = await navigator.mediaDevices.getDisplayMedia(options);
|
||||
} catch (error) {
|
||||
if (error instanceof DOMException && error.name === "AbortError") return;
|
||||
accompanimentErrorCode.value = "permission";
|
||||
throw error;
|
||||
}
|
||||
const audioTrack = nextStream.getAudioTracks()[0];
|
||||
nextStream.getVideoTracks().forEach((track) => track.stop());
|
||||
if (!audioTrack) {
|
||||
nextStream.getTracks().forEach((track) => track.stop());
|
||||
accompanimentErrorCode.value = "noAudio";
|
||||
throw new Error("所选来源没有可共享音频");
|
||||
}
|
||||
|
||||
accompanimentStream?.getTracks().forEach((track) => track.stop());
|
||||
accompanimentStream = nextStream;
|
||||
accompanimentActive.value = true;
|
||||
sendCmd("setAccompanimentActive", { active: true });
|
||||
audioTrack.addEventListener("ended", () => { void stopAccompaniment(); }, { once: true });
|
||||
try {
|
||||
await replaceWebRtcAudioTrack();
|
||||
} catch (error) {
|
||||
releaseAccompanimentStream();
|
||||
sendCmd("setAccompanimentActive", { active: false });
|
||||
stopWebRtcMix();
|
||||
accompanimentErrorCode.value = "permission";
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function stopAccompaniment(): Promise<void> {
|
||||
accompanimentErrorCode.value = "";
|
||||
releaseAccompanimentStream();
|
||||
if (webrtcActive.value) sendCmd("setAccompanimentActive", { active: false });
|
||||
if (webrtcActive.value && webrtcPeer && micStream) await replaceWebRtcAudioTrack();
|
||||
else stopWebRtcMix();
|
||||
}
|
||||
|
||||
async function startWebRtcTransport(sequence: number, socket: WebSocket): Promise<void> {
|
||||
if (typeof RTCPeerConnection === "undefined") throw new Error("当前浏览器不支持 WebRTC");
|
||||
await ensureMicrophone();
|
||||
if (sequence !== connectionSequence || socket.readyState !== WebSocket.OPEN || !micStream) return;
|
||||
const microphoneTrack = micStream.getAudioTracks()[0];
|
||||
if (!microphoneTrack) throw new Error("没有可用的麦克风音轨");
|
||||
|
||||
stopCaptureGraph();
|
||||
const peer = new RTCPeerConnection({ iceServers: [] });
|
||||
webrtcPeer = peer;
|
||||
webrtcFallbackStarted = false;
|
||||
microphoneTrack.enabled = !microphoneMuted.value;
|
||||
const mixedStream = createWebRtcMixStream();
|
||||
const mixedTrack = mixedStream.getAudioTracks()[0];
|
||||
if (!mixedTrack) throw new Error("混合音频轨道创建失败");
|
||||
peer.addTrack(mixedTrack, mixedStream);
|
||||
peer.ontrack = (event) => {
|
||||
const stream = event.streams[0] ?? new MediaStream([event.track]);
|
||||
// Use the browser's native WebRTC media output. Routing the remote
|
||||
// track through AudioContext made playback depend on autoplay policy:
|
||||
// the control channel could report speaking while a suspended context
|
||||
// silently discarded the actual audio. A hidden autoplaying media
|
||||
// element keeps WebRTC's decoder and jitter buffer on the native path.
|
||||
stopWebRtcPlayback();
|
||||
const output = document.createElement("audio") as SinkAudioElement;
|
||||
output.autoplay = true;
|
||||
output.muted = false;
|
||||
output.setAttribute("playsinline", "");
|
||||
output.volume = outputVolume.value;
|
||||
output.setAttribute("aria-hidden", "true");
|
||||
output.tabIndex = -1;
|
||||
output.style.position = "fixed";
|
||||
output.style.width = "1px";
|
||||
output.style.height = "1px";
|
||||
output.style.opacity = "0";
|
||||
output.style.pointerEvents = "none";
|
||||
output.srcObject = stream;
|
||||
document.body.append(output);
|
||||
webrtcOutputElement = output;
|
||||
webrtcPlaybackStream = stream;
|
||||
if (selectedOutputDeviceId.value && output.setSinkId) {
|
||||
void output.setSinkId(selectedOutputDeviceId.value).catch(() => undefined);
|
||||
}
|
||||
void syncWebRtcPlayback();
|
||||
};
|
||||
startWebRtcMicMonitor(getAudioCtx(), micStream, microphoneTrack);
|
||||
peer.onconnectionstatechange = () => {
|
||||
if (peer.connectionState === "failed") void fallbackFromWebRtc(sequence, socket);
|
||||
};
|
||||
|
||||
const negotiation = (async () => {
|
||||
webrtcActive.value = true;
|
||||
const offer = await peer.createOffer();
|
||||
await peer.setLocalDescription(offer);
|
||||
await waitForIceGathering(peer);
|
||||
if (sequence !== connectionSequence || webrtcPeer !== peer || socket.readyState !== WebSocket.OPEN) return;
|
||||
const description = peer.localDescription;
|
||||
if (!description) throw new Error("WebRTC offer was not created");
|
||||
socket.send(JSON.stringify({ type: "webrtcOffer", payload: {
|
||||
sdp: { type: description.type, sdp: description.sdp },
|
||||
muted: microphoneMuted.value,
|
||||
accompanimentActive: accompanimentActive.value,
|
||||
} }));
|
||||
window.setTimeout(() => {
|
||||
if (webrtcPeer === peer && !peer.remoteDescription) void fallbackFromWebRtc(sequence, socket);
|
||||
}, 8_000);
|
||||
})();
|
||||
webrtcNegotiationPromise = negotiation;
|
||||
try {
|
||||
await negotiation;
|
||||
} catch (error) {
|
||||
if (webrtcPeer === peer) await fallbackFromWebRtc(sequence, socket);
|
||||
throw error;
|
||||
} finally {
|
||||
if (webrtcNegotiationPromise === negotiation) webrtcNegotiationPromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForIceGathering(peer: RTCPeerConnection): Promise<void> {
|
||||
if (peer.iceGatheringState === "complete") return;
|
||||
await new Promise<void>((resolve) => {
|
||||
let settled = false;
|
||||
const finish = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
window.clearTimeout(timer);
|
||||
peer.removeEventListener("icegatheringstatechange", onStateChange);
|
||||
resolve();
|
||||
};
|
||||
const onStateChange = () => {
|
||||
if (peer.iceGatheringState === "complete") finish();
|
||||
};
|
||||
const timer = window.setTimeout(finish, 5_000);
|
||||
peer.addEventListener("icegatheringstatechange", onStateChange);
|
||||
});
|
||||
}
|
||||
|
||||
async function applyWebRtcAnswer(description: unknown): Promise<void> {
|
||||
if (!webrtcPeer || !isSessionDescription(description, "answer")) return;
|
||||
try {
|
||||
await webrtcPeer.setRemoteDescription(description);
|
||||
webrtcActive.value = true;
|
||||
syncWebRtcMemberVolumes();
|
||||
} catch {
|
||||
if (lastConnection && ws.value) await fallbackFromWebRtc(connectionSequence, ws.value);
|
||||
}
|
||||
}
|
||||
|
||||
async function fallbackFromWebRtc(sequence: number, socket: WebSocket): Promise<void> {
|
||||
if (sequence !== connectionSequence || webrtcFallbackStarted) return;
|
||||
webrtcFallbackStarted = true;
|
||||
webrtcActive.value = false;
|
||||
if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: "webrtcStop" }));
|
||||
stopWebRtcTransport();
|
||||
if (socket.readyState === WebSocket.OPEN && state.connected) {
|
||||
try { await startMicrophone(); } catch (error: unknown) {
|
||||
state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function stopWebRtcTransport(): void {
|
||||
const peer = webrtcPeer;
|
||||
webrtcPeer = null;
|
||||
webrtcActive.value = false;
|
||||
webrtcNegotiationPromise = null;
|
||||
releaseAccompanimentStream();
|
||||
stopWebRtcMix();
|
||||
stopWebRtcMicMonitor();
|
||||
stopWebRtcPlayback();
|
||||
if (peer) void peer.close();
|
||||
}
|
||||
|
||||
function stopWebRtcPlayback(): void {
|
||||
webrtcPlaybackRetryCleanup?.();
|
||||
webrtcPlaybackStream = null;
|
||||
webrtcOutputElement?.pause();
|
||||
if (webrtcOutputElement) {
|
||||
webrtcOutputElement.srcObject = null;
|
||||
webrtcOutputElement.remove();
|
||||
}
|
||||
webrtcOutputElement = null;
|
||||
}
|
||||
|
||||
function startWebRtcMicMonitor(ctx: AudioContext, stream: MediaStream, track: MediaStreamTrack): void {
|
||||
stopWebRtcMicMonitor(false);
|
||||
try {
|
||||
const source = ctx.createMediaStreamSource(stream);
|
||||
const analyser = ctx.createAnalyser();
|
||||
analyser.fftSize = 512;
|
||||
const silent = ctx.createGain();
|
||||
silent.gain.value = 0;
|
||||
source.connect(analyser);
|
||||
analyser.connect(silent);
|
||||
silent.connect(ctx.destination);
|
||||
const samples = new Float32Array(analyser.fftSize);
|
||||
webrtcMicMonitorSource = source;
|
||||
webrtcMicMonitorAnalyser = analyser;
|
||||
webrtcMicMonitorGain = silent;
|
||||
webrtcMicMonitorTimer = setInterval(() => {
|
||||
if (!webrtcMicMonitorAnalyser) return;
|
||||
webrtcMicMonitorAnalyser.getFloatTimeDomainData(samples);
|
||||
let sum = 0;
|
||||
for (const sample of samples) sum += sample * sample;
|
||||
const rms = Math.sqrt(sum / samples.length);
|
||||
micLevel.value = Math.min(1, rms * 6);
|
||||
if (!microphoneMuted.value && track.enabled && rms >= voxThreshold.value) markSpeaking(state.tsClientId);
|
||||
else if (state.tsClientId) clearSpeaking(state.tsClientId);
|
||||
}, 50);
|
||||
} catch {
|
||||
stopWebRtcMicMonitor(false);
|
||||
}
|
||||
}
|
||||
|
||||
function stopWebRtcMicMonitor(resetLevel = true): void {
|
||||
if (webrtcMicMonitorTimer) clearInterval(webrtcMicMonitorTimer);
|
||||
webrtcMicMonitorTimer = null;
|
||||
webrtcMicMonitorSource?.disconnect();
|
||||
webrtcMicMonitorAnalyser?.disconnect();
|
||||
webrtcMicMonitorGain?.disconnect();
|
||||
webrtcMicMonitorSource = null;
|
||||
webrtcMicMonitorAnalyser = null;
|
||||
webrtcMicMonitorGain = null;
|
||||
if (resetLevel) micLevel.value = 0;
|
||||
}
|
||||
|
||||
function isSessionDescription(value: unknown, type: "answer"): value is RTCSessionDescriptionInit {
|
||||
return Boolean(value) && typeof value === "object"
|
||||
&& (value as { type?: unknown }).type === type
|
||||
&& typeof (value as { sdp?: unknown }).sdp === "string";
|
||||
}
|
||||
|
||||
function stopCaptureGraph(): void {
|
||||
accumLen = 0;
|
||||
voxAttack = 0;
|
||||
voxRelease = 0;
|
||||
micLevel.value = 0;
|
||||
scriptNode?.disconnect();
|
||||
workletNode?.port.close();
|
||||
workletNode?.disconnect();
|
||||
micGain?.disconnect();
|
||||
micSource?.disconnect();
|
||||
silentGain?.disconnect();
|
||||
scriptNode = null;
|
||||
workletNode = null;
|
||||
micGain = null;
|
||||
micSource = null;
|
||||
silentGain = null;
|
||||
}
|
||||
|
||||
function stopMicrophone(closeContext = true): void {
|
||||
stopCaptureGraph();
|
||||
releaseAccompanimentStream();
|
||||
stopWebRtcMix();
|
||||
micStream?.getTracks().forEach((track) => track.stop());
|
||||
micStream = null;
|
||||
if (closeContext) {
|
||||
audioCtx?.close();
|
||||
audioCtx = null;
|
||||
workletContext = null;
|
||||
workletModulePromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -411,11 +836,17 @@ export function useVoiceWebSocket() {
|
||||
|
||||
async function setInputDevice(deviceId: string): Promise<void> {
|
||||
const previousDeviceId = selectedInputDeviceId.value;
|
||||
const shouldRestartWebRtc = webrtcActive.value && Boolean(ws.value);
|
||||
selectedInputDeviceId.value = deviceId;
|
||||
localStorage.setItem("webspeak:input-device", deviceId);
|
||||
void saveAudioPreferences();
|
||||
try {
|
||||
if (shouldRestartWebRtc) stopWebRtcTransport();
|
||||
if (micStream) await startMicrophone();
|
||||
if (shouldRestartWebRtc && ws.value) {
|
||||
stopWebRtcTransport();
|
||||
await startWebRtcTransport(connectionSequence, ws.value);
|
||||
}
|
||||
await refreshAudioDevices();
|
||||
} catch (error) {
|
||||
selectedInputDeviceId.value = previousDeviceId;
|
||||
@@ -511,14 +942,30 @@ export function useVoiceWebSocket() {
|
||||
function playAudioFrame(clientId: number, opusData: Uint8Array): void {
|
||||
if (opusData.length < 3) return;
|
||||
let decoder = remoteDecoders.get(clientId);
|
||||
const ctx = getAudioCtx();
|
||||
const now = ctx.currentTime;
|
||||
const scheduledUntil = remotePlayTimes.get(clientId) ?? now;
|
||||
const decodeQueueSize = decoder?.decodeQueueSize ?? 0;
|
||||
if (
|
||||
decoder &&
|
||||
(scheduledUntil > now + MAX_REMOTE_PLAY_AHEAD_SECONDS || decodeQueueSize >= MAX_REMOTE_DECODE_QUEUE_FRAMES)
|
||||
) {
|
||||
resetRemotePlayback(clientId);
|
||||
decoder = undefined;
|
||||
}
|
||||
|
||||
if (!decoder) {
|
||||
const ctx = getAudioCtx();
|
||||
const gainNode = ctx.createGain();
|
||||
gainNode.gain.value = (volumes[clientId] ?? 1) * outputVolume.value;
|
||||
gainNode.connect(ctx.destination);
|
||||
remoteGains.set(clientId, gainNode);
|
||||
decoder = new AudioDecoder({
|
||||
const generation = ++nextRemoteDecoderGeneration;
|
||||
const nextDecoder = new AudioDecoder({
|
||||
output: (chunk: AudioData) => {
|
||||
if (remoteDecoderGenerations.get(clientId) !== generation) {
|
||||
chunk.close();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { sampleRate, numberOfChannels, numberOfFrames } = chunk;
|
||||
const buffer = ctx.createBuffer(numberOfChannels, numberOfFrames, sampleRate);
|
||||
@@ -530,8 +977,27 @@ export function useVoiceWebSocket() {
|
||||
const source = ctx.createBufferSource();
|
||||
source.buffer = buffer;
|
||||
source.connect(gainNode);
|
||||
let sources = remotePlaybackSources.get(clientId);
|
||||
if (!sources) {
|
||||
sources = new Set<AudioBufferSourceNode>();
|
||||
remotePlaybackSources.set(clientId, sources);
|
||||
}
|
||||
sources.add(source);
|
||||
source.addEventListener("ended", () => {
|
||||
source.disconnect();
|
||||
sources?.delete(source);
|
||||
if (sources?.size === 0) remotePlaybackSources.delete(clientId);
|
||||
}, { once: true });
|
||||
let playTime = remotePlayTimes.get(clientId) ?? ctx.currentTime;
|
||||
if (playTime < ctx.currentTime) playTime = ctx.currentTime;
|
||||
if (playTime + numberOfFrames / sampleRate > ctx.currentTime + MAX_REMOTE_PLAY_AHEAD_SECONDS) {
|
||||
source.disconnect();
|
||||
sources.delete(source);
|
||||
if (sources.size === 0) remotePlaybackSources.delete(clientId);
|
||||
chunk.close();
|
||||
resetRemotePlayback(clientId);
|
||||
return;
|
||||
}
|
||||
source.start(playTime);
|
||||
remotePlayTimes.set(clientId, playTime + numberOfFrames / sampleRate);
|
||||
} catch {
|
||||
@@ -540,10 +1006,15 @@ export function useVoiceWebSocket() {
|
||||
chunk.close();
|
||||
},
|
||||
error: () => {
|
||||
remoteDecoders.delete(clientId);
|
||||
if (remoteDecoderGenerations.get(clientId) === generation) {
|
||||
remoteDecoderGenerations.delete(clientId);
|
||||
remoteDecoders.delete(clientId);
|
||||
}
|
||||
},
|
||||
});
|
||||
decoder.configure({ codec: "opus", sampleRate: 48000, numberOfChannels: 1 });
|
||||
nextDecoder.configure({ codec: "opus", sampleRate: 48000, numberOfChannels: 1 });
|
||||
decoder = nextDecoder;
|
||||
remoteDecoderGenerations.set(clientId, generation);
|
||||
remoteDecoders.set(clientId, decoder);
|
||||
}
|
||||
|
||||
@@ -556,6 +1027,29 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
}
|
||||
|
||||
function clearRemotePlayback(clientId: number): void {
|
||||
const decoder = remoteDecoders.get(clientId);
|
||||
if (decoder) {
|
||||
try { decoder.close(); } catch { /* already closed */ }
|
||||
}
|
||||
remoteDecoders.delete(clientId);
|
||||
remoteDecoderGenerations.delete(clientId);
|
||||
remotePlayTimes.delete(clientId);
|
||||
remoteDecodeTimestamps.delete(clientId);
|
||||
const sources = remotePlaybackSources.get(clientId);
|
||||
if (sources) {
|
||||
for (const source of sources) {
|
||||
try { source.stop(); } catch { /* already ended */ }
|
||||
source.disconnect();
|
||||
}
|
||||
remotePlaybackSources.delete(clientId);
|
||||
}
|
||||
}
|
||||
|
||||
function resetRemotePlayback(clientId: number): void {
|
||||
clearRemotePlayback(clientId);
|
||||
}
|
||||
|
||||
function connect(target: string, channel: string, nickname: string, serverPassword = "", identity = "", rememberIdentity = false, inviteToken = ""): void {
|
||||
disconnect(true);
|
||||
lastConnection = { target, channel, nickname, serverPassword, ...(identity ? { identity } : {}), rememberIdentity };
|
||||
@@ -600,9 +1094,6 @@ export function useVoiceWebSocket() {
|
||||
socket.close(1000);
|
||||
return;
|
||||
}
|
||||
ensureMicrophone().catch((error: unknown) => {
|
||||
state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`;
|
||||
});
|
||||
};
|
||||
socket.onmessage = (event) => {
|
||||
if (typeof event.data === "string") {
|
||||
@@ -620,14 +1111,18 @@ export function useVoiceWebSocket() {
|
||||
state.connected = false;
|
||||
state.connecting = false;
|
||||
state.reconnecting = false;
|
||||
if (event.code !== 1000 && !state.error && !state.reconnectFailed) state.error = closeReason(event.code);
|
||||
// Prefer the close code over the generic WebSocket error event. The
|
||||
// gateway uses a dedicated code when a remembered identity is already
|
||||
// active in another browser page.
|
||||
if (event.code !== 1000 && !state.reconnectFailed) state.error = closeReason(event.code);
|
||||
stopWebRtcTransport();
|
||||
stopMicrophone();
|
||||
whisperTargetIds.clear();
|
||||
whisperActive.value = false;
|
||||
};
|
||||
socket.onerror = () => {
|
||||
if (sequence !== connectionSequence) return;
|
||||
state.error = "连接服务器失败,请检查邀请链接或服务器状态";
|
||||
// The following close event contains the actionable close code. Do not
|
||||
// overwrite it with a generic browser WebSocket error first.
|
||||
};
|
||||
}
|
||||
|
||||
@@ -643,15 +1138,18 @@ export function useVoiceWebSocket() {
|
||||
if (code === 4002) return "TeamSpeak 服务器地址无效";
|
||||
if (code === 4003) return "TeamSpeak 服务器连接失败";
|
||||
if (code === 4004) return "服务器当前已满,请稍后重试";
|
||||
if (code === 4005) return "此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试";
|
||||
return "连接已断开";
|
||||
}
|
||||
|
||||
function disconnect(preserveConnection = false): void {
|
||||
connectionSequence++;
|
||||
const keepRememberedIdentity = lastConnection?.rememberIdentity === true;
|
||||
if (!preserveConnection) lastConnection = null;
|
||||
stopMicrophone();
|
||||
const socket = ws.value;
|
||||
ws.value = null;
|
||||
stopWebRtcTransport();
|
||||
if (socket && socket.readyState < WebSocket.CLOSING) socket.close(1000);
|
||||
state.connected = false;
|
||||
state.connecting = false;
|
||||
@@ -660,12 +1158,12 @@ export function useVoiceWebSocket() {
|
||||
state.reconnectFailed = false;
|
||||
state.tsClientId = 0;
|
||||
state.errorCode = "";
|
||||
identityMaterial.value = "";
|
||||
if (!keepRememberedIdentity) identityMaterial.value = "";
|
||||
members.length = 0;
|
||||
channels.length = 0;
|
||||
chatMessages.length = 0;
|
||||
for (const decoder of remoteDecoders.values()) decoder.close();
|
||||
remoteDecoders.clear();
|
||||
for (const clientId of new Set([...remoteDecoders.keys(), ...remotePlaybackSources.keys()])) clearRemotePlayback(clientId);
|
||||
remoteDecoderGenerations.clear();
|
||||
remotePlayTimes.clear();
|
||||
remoteDecodeTimestamps.clear();
|
||||
for (const gain of remoteGains.values()) gain.disconnect();
|
||||
@@ -703,7 +1201,18 @@ export function useVoiceWebSocket() {
|
||||
if (lastConnection) lastConnection.identity = msg.identity;
|
||||
}
|
||||
if (wasReconnecting) {
|
||||
ensureMicrophone().catch((error: unknown) => {
|
||||
const start = msg.webrtcAvailable === true && typeof RTCPeerConnection !== "undefined"
|
||||
? (ws.value ? startWebRtcTransport(connectionSequence, ws.value) : Promise.resolve())
|
||||
: ensureMicrophone();
|
||||
start.catch((error: unknown) => {
|
||||
state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`;
|
||||
});
|
||||
} else if (msg.webrtcAvailable === true && typeof RTCPeerConnection !== "undefined" && ws.value) {
|
||||
void startWebRtcTransport(connectionSequence, ws.value).catch((error: unknown) => {
|
||||
state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`;
|
||||
});
|
||||
} else {
|
||||
void ensureMicrophone().catch((error: unknown) => {
|
||||
state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`;
|
||||
});
|
||||
}
|
||||
@@ -715,8 +1224,10 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
break;
|
||||
case "memberLeave": {
|
||||
clearSpeaking(Number(msg.id));
|
||||
const index = members.findIndex((member) => member.id === msg.id);
|
||||
const clientId = Number(msg.id);
|
||||
clearSpeaking(clientId);
|
||||
clearRemotePlayback(clientId);
|
||||
const index = members.findIndex((member) => member.id === clientId);
|
||||
if (index >= 0) members.splice(index, 1);
|
||||
break;
|
||||
}
|
||||
@@ -730,10 +1241,14 @@ export function useVoiceWebSocket() {
|
||||
case "chatMessage":
|
||||
if (Number(msg.invokerId) === state.tsClientId) break;
|
||||
const incomingScope = msg.scope === "private" || msg.scope === "server" || msg.scope === "channel" ? msg.scope : "system";
|
||||
const rawTargetId = typeof msg.targetId === "string" || typeof msg.targetId === "number" ? String(msg.targetId) : undefined;
|
||||
// Older gateways and TeamSpeak channel notifications may use 0 as
|
||||
// the broadcast sentinel. It must not be compared with a channel id.
|
||||
const incomingTargetId = rawTargetId && rawTargetId !== "0" ? rawTargetId : undefined;
|
||||
chatMessages.push({
|
||||
id: `remote-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
||||
scope: incomingScope,
|
||||
targetId: typeof msg.targetId === "string" ? msg.targetId : undefined,
|
||||
...(incomingTargetId ? { targetId: incomingTargetId } : {}),
|
||||
...(incomingScope === "private" ? { conversationId: String(Number(msg.invokerId) || 0) } : {}),
|
||||
senderId: Number(msg.invokerId) || undefined,
|
||||
senderUid: typeof msg.senderUid === "string" ? msg.senderUid : undefined,
|
||||
@@ -763,6 +1278,7 @@ export function useVoiceWebSocket() {
|
||||
state.reconnecting = Boolean(msg.recoverable !== false);
|
||||
state.reconnectFailed = false;
|
||||
if (!state.reconnecting) state.error = "TeamSpeak 连接已断开";
|
||||
stopWebRtcTransport();
|
||||
stopMicrophone();
|
||||
whisperTargetIds.clear();
|
||||
whisperActive.value = false;
|
||||
@@ -773,6 +1289,7 @@ export function useVoiceWebSocket() {
|
||||
state.reconnecting = true;
|
||||
state.reconnectFailed = false;
|
||||
state.reconnectAttempt = Number(msg.attempt) || state.reconnectAttempt + 1;
|
||||
stopWebRtcTransport();
|
||||
stopMicrophone();
|
||||
whisperTargetIds.clear();
|
||||
whisperActive.value = false;
|
||||
@@ -793,6 +1310,19 @@ export function useVoiceWebSocket() {
|
||||
case "whisperTargets":
|
||||
applyWhisperState(msg.targetIds, msg.active);
|
||||
break;
|
||||
case "webrtcAnswer":
|
||||
void applyWebRtcAnswer(msg.payload?.sdp);
|
||||
break;
|
||||
case "webrtcError":
|
||||
if (ws.value) void fallbackFromWebRtc(connectionSequence, ws.value);
|
||||
break;
|
||||
case "voiceActivity":
|
||||
if (Array.isArray(msg.clientIds)) {
|
||||
for (const clientId of msg.clientIds) {
|
||||
if (typeof clientId === "number" && Number.isInteger(clientId) && clientId > 0) markSpeaking(clientId);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "error":
|
||||
state.errorCode = String(msg.error?.code || "");
|
||||
state.error = protocolErrorMessage(state.errorCode, String(msg.error?.message || msg.message || "操作失败"));
|
||||
@@ -801,6 +1331,10 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
function handleAudioFrame(data: Uint8Array): void {
|
||||
// WebRTC carries the realtime downlink after negotiation. Ignore any
|
||||
// in-flight fallback WebSocket packets so a transport switch cannot
|
||||
// produce duplicate or delayed playback.
|
||||
if (webrtcActive.value) return;
|
||||
if (data.length < 4) return;
|
||||
const clientId = (data[1] << 8) | data[2];
|
||||
if (clientId === state.tsClientId) return;
|
||||
@@ -890,6 +1424,10 @@ export function useVoiceWebSocket() {
|
||||
voxAttack = 0;
|
||||
voxRelease = 0;
|
||||
accumLen = 0;
|
||||
if (webrtcActive.value) micStream?.getAudioTracks().forEach((track) => { track.enabled = !muted; });
|
||||
if (webrtcMixMicGain) webrtcMixMicGain.gain.value = muted ? 0 : inputVolume.value;
|
||||
if (webrtcActive.value) sendCmd("setMicrophoneMuted", { muted });
|
||||
if (muted && state.tsClientId) clearSpeaking(state.tsClientId);
|
||||
void saveAudioPreferences();
|
||||
}
|
||||
|
||||
@@ -912,6 +1450,7 @@ export function useVoiceWebSocket() {
|
||||
INVALID_POKE_MESSAGE: "戳一戳消息无效",
|
||||
INVALID_AWAY_STATUS: "离开状态无效",
|
||||
INVALID_AUDIO_FRAME: "音频帧格式无效",
|
||||
INVALID_MEMBER_VOLUME: "成员音量无效",
|
||||
INVALID_WHISPER_TARGETS: "私语目标无效",
|
||||
INVALID_WHISPER_STATE: "私语状态无效",
|
||||
NO_WHISPER_TARGETS: "请先选择私语目标",
|
||||
@@ -936,17 +1475,29 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
const gain = remoteGains.get(clientId);
|
||||
if (gain) gain.gain.value = normalized * outputVolume.value;
|
||||
if (webrtcPeer || webrtcActive.value) sendCmd("setMemberVolume", { clientId, volume: normalized });
|
||||
}
|
||||
|
||||
function syncWebRtcMemberVolumes(): void {
|
||||
if (!webrtcActive.value || ws.value?.readyState !== WebSocket.OPEN) return;
|
||||
for (const [rawClientId, volume] of Object.entries(volumes)) {
|
||||
const clientId = Number(rawClientId);
|
||||
if (!Number.isInteger(clientId) || clientId <= 0) continue;
|
||||
sendCmd("setMemberVolume", { clientId, volume });
|
||||
}
|
||||
}
|
||||
|
||||
function setInputVolume(volume: number): void {
|
||||
inputVolume.value = Math.max(0, Math.min(1, volume));
|
||||
if (micGain) micGain.gain.value = inputVolume.value;
|
||||
if (webrtcMixMicGain) webrtcMixMicGain.gain.value = microphoneMuted.value ? 0 : inputVolume.value;
|
||||
void saveAudioPreferences();
|
||||
}
|
||||
|
||||
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;
|
||||
void saveAudioPreferences();
|
||||
}
|
||||
|
||||
@@ -988,6 +1539,9 @@ export function useVoiceWebSocket() {
|
||||
whisperTargetIds,
|
||||
whisperActive,
|
||||
volumes,
|
||||
accompanimentActive,
|
||||
accompanimentSupported,
|
||||
accompanimentErrorCode,
|
||||
setVolume,
|
||||
setInputVolume,
|
||||
setOutputVolume,
|
||||
@@ -1012,6 +1566,8 @@ export function useVoiceWebSocket() {
|
||||
setWhisperTargets,
|
||||
setWhisperActive,
|
||||
setMicrophoneMuted,
|
||||
startAccompaniment,
|
||||
stopAccompaniment,
|
||||
checkSupport,
|
||||
clearError,
|
||||
};
|
||||
|
||||
@@ -118,6 +118,18 @@ export async function saveStoredIdentity(privateMaterial: string, label = "此
|
||||
}
|
||||
}
|
||||
|
||||
export async function removeStoredIdentity(): Promise<void> {
|
||||
try {
|
||||
await request("identities", "readwrite", (store, resolve, reject) => {
|
||||
const remove = store.delete(CURRENT_IDENTITY_KEY);
|
||||
remove.onsuccess = () => resolve(undefined);
|
||||
remove.onerror = () => reject(remove.error);
|
||||
});
|
||||
} catch {
|
||||
// Identity removal is best effort when browser storage is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadLocalPreferences(): Promise<LocalPreferences> {
|
||||
const defaults: LocalPreferences = { schemaVersion: 1, volumesByUid: {} };
|
||||
try {
|
||||
|
||||
@@ -17,8 +17,16 @@ export function saveTheme(theme: ThemeMode): void {
|
||||
applyTheme(theme);
|
||||
}
|
||||
|
||||
export function isDarkTheme(theme: ThemeMode): boolean {
|
||||
if (theme === "dark") return true;
|
||||
if (theme === "light") return false;
|
||||
return typeof window !== "undefined" && typeof window.matchMedia === "function"
|
||||
? window.matchMedia("(prefers-color-scheme: dark)").matches
|
||||
: false;
|
||||
}
|
||||
|
||||
export function nextTheme(theme: ThemeMode): ThemeMode {
|
||||
return theme === "system" ? "light" : theme === "light" ? "dark" : "system";
|
||||
return isDarkTheme(theme) ? "light" : "dark";
|
||||
}
|
||||
|
||||
applyTheme(getStoredTheme());
|
||||
+131
-9
@@ -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>
|
||||
<button class="language-link" type="button" @click="toggleLanguage">{{ tr('languageSwitch') }}</button>
|
||||
<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>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
</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" :title="themeLabel" @click="cycleTheme">{{ themeLabel }}</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><button type="button" @click="toggleLanguage">{{ tr('languageSwitch') }}</button></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">
|
||||
@@ -36,6 +36,7 @@
|
||||
<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 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>
|
||||
</section>
|
||||
@@ -56,6 +57,7 @@
|
||||
<div class="metric-grid"><article><span><Icon name="activity" :size="20" /></span><small>{{ tr('gateway') }}</small><strong>{{ overview.gateway.version || '—' }}</strong><em>{{ formatUptime(overview.gateway.uptimeSeconds) }}</em></article><article><span><Icon name="server" :size="20" /></span><small>{{ tr('teamSpeakTarget') }}</small><strong>{{ overview.teamSpeak.target || '—' }}</strong><em>{{ targetStatusText }}</em></article><article><span><Icon name="users" :size="20" /></span><small>{{ tr('activeSessions') }}</small><strong>{{ overview.sessions.active }} / {{ overview.sessions.limit }}</strong><em>{{ tr('peakSessions', { count: overview.sessions.peak }) }}</em></article></div>
|
||||
<div class="overview-columns"><article class="overview-card target-health-card"><header><div><h3>{{ tr('targetHealth') }}</h3><p>{{ tr('targetHealthLead') }}</p></div><RouterLink to="/admin/server">{{ tr('manage') }}</RouterLink></header><dl><div><dt>{{ tr('status') }}</dt><dd><i :class="overview.teamSpeak.status"></i>{{ targetStatusText }}</dd></div><div><dt>{{ tr('lastTest') }}</dt><dd>{{ formatDate(overview.teamSpeak.lastTestAt) }}</dd></div><div><dt>{{ tr('latency') }}</dt><dd>{{ overview.teamSpeak.latencyMs == null ? '—' : `${overview.teamSpeak.latencyMs} ms` }}</dd></div></dl></article><article class="overview-card recent-events-card"><header><div><h3>{{ tr('recentEvents') }}</h3><p>{{ tr('recentEventsLead') }}</p></div></header><ul class="event-list"><li v-for="event in overview.recentEvents" :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="!overview.recentEvents.length" class="empty-event">{{ tr('noRecentEvents') }}</li></ul></article></div>
|
||||
</section>
|
||||
<div v-if="webrtcPortNoticeOpen" class="modal-backdrop" @click.self="webrtcPortNoticeOpen = false"><section class="modal-card" role="dialog" aria-modal="true" :aria-label="tr('webrtcPortNoticeTitle')"><div class="modal-icon"><Icon name="info" :size="21" /></div><h2>{{ tr('webrtcPortNoticeTitle') }}</h2><p>{{ tr('webrtcPortNotice', { range: webrtcPortRangeText }) }}</p><button class="primary-button wide" type="button" @click="webrtcPortNoticeOpen = false">{{ tr('gotIt') }}</button></section></div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
@@ -66,7 +68,7 @@ import { computed, onMounted, reactive, ref, watch } from "vue";
|
||||
import { RouterLink, useRoute, useRouter } from "vue-router";
|
||||
import Icon from "../components/Icon.vue";
|
||||
import { combineTeamSpeakTarget, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
|
||||
import { applyTheme, getStoredTheme, nextTheme, saveTheme, type ThemeMode } from "../services/theme.js";
|
||||
import { applyTheme, getStoredTheme, isDarkTheme, nextTheme, saveTheme, type ThemeMode } from "../services/theme.js";
|
||||
|
||||
type Language = "zh" | "en";
|
||||
type Screen = "login" | "change-password" | "admin";
|
||||
@@ -77,7 +79,8 @@ const route = useRoute();
|
||||
const router = useRouter();
|
||||
const language = ref<Language>((localStorage.getItem("webspeak:language") as Language) || "zh");
|
||||
const themeMode = ref<ThemeMode>(getStoredTheme());
|
||||
const themeLabel = computed(() => themeMode.value === "dark" ? tr("themeDark") : themeMode.value === "light" ? tr("themeLight") : tr("themeSystem"));
|
||||
const themeIcon = computed(() => isDarkTheme(themeMode.value) ? "sun" : "moon");
|
||||
const themeLabel = computed(() => isDarkTheme(themeMode.value) ? tr("switchToLightTheme") : tr("switchToDarkTheme"));
|
||||
applyTheme(themeMode.value);
|
||||
const loading = ref(true);
|
||||
const screen = ref<Screen>("login");
|
||||
@@ -91,7 +94,7 @@ 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: "", 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: "", 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" }
|
||||
@@ -100,6 +103,7 @@ 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 copy = {
|
||||
@@ -119,10 +123,13 @@ const copy = {
|
||||
themeSystem: "跟随系统",
|
||||
themeLight: "浅色主题",
|
||||
themeDark: "深色主题",
|
||||
switchToLightTheme: "切换到浅色主题",
|
||||
switchToDarkTheme: "切换到深色主题",
|
||||
welcomeAdmin: "欢迎回来",
|
||||
loginLead: "输入管理员账号和密码以管理此 WebSpeak 实例。",
|
||||
adminPassword: "管理员密码",
|
||||
login: "登录",
|
||||
backHome: "返回首页",
|
||||
overview: "概览",
|
||||
server: "服务器",
|
||||
operations: "运维",
|
||||
@@ -150,6 +157,19 @@ const copy = {
|
||||
connectionReady: "连接成功",
|
||||
connectionFailed: "连接失败",
|
||||
accessAndIdentity: "访问与站点信息",
|
||||
advancedSettings: "高级参数",
|
||||
advancedSettingsLead: "仅在需要时调整网关的高级传输参数。",
|
||||
webrtcSettings: "WebRTC 语音",
|
||||
webrtcLead: "由当前 WebSpeak 网关直接提供低延迟语音传输,无需配置其他服务器。",
|
||||
webrtcEnabled: "启用 WebRTC",
|
||||
webrtcEnabledLead: "浏览器和网络支持时使用实时语音通道,否则自动回退到兼容模式。",
|
||||
webrtcPortRange: "WebRTC UDP 端口范围",
|
||||
webrtcPortRangeLead: "请在 WebSpeak 所在主机的防火墙和安全组放行整个范围。",
|
||||
webrtcPortStart: "起始端口",
|
||||
webrtcPortEnd: "结束端口",
|
||||
webrtcApplyHint: "端口范围仅可在 WebRTC 关闭时修改;开启后会锁定,保存后对新连接生效。",
|
||||
webrtcPortNoticeTitle: "请先放行 WebRTC 端口",
|
||||
webrtcPortNotice: "需要开启端口,范围是 {{range}}(UDP)。请先在主机防火墙、安全组和 Docker 端口映射中放行该范围。",
|
||||
accessMode: "访客访问模式",
|
||||
fixedMode: "仅限此 TeamSpeak 服务器",
|
||||
fixedModeLead: "访客只需填写昵称,目标和密码由 WebSpeak 管理。",
|
||||
@@ -260,10 +280,13 @@ const copy = {
|
||||
themeSystem: "System theme",
|
||||
themeLight: "Light theme",
|
||||
themeDark: "Dark theme",
|
||||
switchToLightTheme: "Switch to light theme",
|
||||
switchToDarkTheme: "Switch to dark theme",
|
||||
welcomeAdmin: "Welcome back",
|
||||
loginLead: "Enter the admin account and password to manage this WebSpeak instance.",
|
||||
adminPassword: "Admin password",
|
||||
login: "Sign in",
|
||||
backHome: "Back to home",
|
||||
overview: "Overview",
|
||||
server: "Server",
|
||||
operations: "Operations",
|
||||
@@ -291,6 +314,19 @@ const copy = {
|
||||
connectionReady: "Connection ready",
|
||||
connectionFailed: "Connection failed",
|
||||
accessAndIdentity: "Access and site identity",
|
||||
advancedSettings: "Advanced settings",
|
||||
advancedSettingsLead: "Adjust gateway transport options only when needed.",
|
||||
webrtcSettings: "WebRTC audio",
|
||||
webrtcLead: "Low-latency voice is provided by this WebSpeak gateway; no extra server is required.",
|
||||
webrtcEnabled: "Enable WebRTC",
|
||||
webrtcEnabledLead: "Use realtime audio when supported; browsers and networks fall back automatically.",
|
||||
webrtcPortRange: "WebRTC UDP port range",
|
||||
webrtcPortRangeLead: "Allow the complete range through the host firewall and security group.",
|
||||
webrtcPortStart: "Start port",
|
||||
webrtcPortEnd: "End port",
|
||||
webrtcApplyHint: "The range can only be edited while WebRTC is off. It is locked while enabled and applies to new connections after saving.",
|
||||
webrtcPortNoticeTitle: "Allow WebRTC ports first",
|
||||
webrtcPortNotice: "Ports must be opened: {{range}} (UDP). Allow this range in the host firewall, security group, and Docker port mapping first.",
|
||||
accessMode: "Guest access mode",
|
||||
fixedMode: "Only this TeamSpeak server",
|
||||
fixedModeLead: "Guests enter only a nickname; WebSpeak manages the target and password.",
|
||||
@@ -392,6 +428,7 @@ const passwordStrength = computed(() => Math.min(100, Math.max(8, newPassword.va
|
||||
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 targetStatusText = computed(() => overview.teamSpeak.status === "reachable" ? tr('reachable') : overview.teamSpeak.status === "unreachable" ? tr('unreachable') : tr('notTested'));
|
||||
const webrtcPortRangeText = computed(() => `${serverForm.webRtcUdpStart}–${serverForm.webRtcUdpEnd}`);
|
||||
|
||||
onMounted(loadAdminView);
|
||||
watch(() => [serverForm.address, serverForm.port, serverForm.serverPassword, serverForm.passwordAction], () => { if (!testing.value && screen.value === "admin") testResult.value = null; });
|
||||
@@ -402,7 +439,7 @@ async function login() { submitting.value = true; errorMessage.value = ""; try {
|
||||
async function changePassword() { errorMessage.value = ""; if (newPassword.value.length < 12) { errorMessage.value = tr('setupPasswordShort'); return; } if (newPassword.value !== confirmNewPassword.value) { errorMessage.value = tr('setupPasswordsMismatch'); return; } submitting.value = true; try { await sendJson("/api/admin/change-password", "POST", { newPassword: newPassword.value }); newPassword.value = ""; confirmNewPassword.value = ""; screen.value = "admin"; await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
|
||||
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" }); }
|
||||
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 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; } }
|
||||
@@ -410,9 +447,10 @@ async function revokeInvite(invite: ManagedInvite) { if (!window.confirm(tr('con
|
||||
async function copyInviteLink() { if (!createdInvite.value) return; try { await navigator.clipboard.writeText(createdInvite.value.link); showOperationNotice(tr('copiedLink')); } catch { errorMessage.value = tr('operationFailed'); } }
|
||||
function showOperationNotice(message: string) { errorMessage.value = message; window.setTimeout(() => { if (errorMessage.value === message) errorMessage.value = ""; }, 2200); }
|
||||
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" }); await loadOverview(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
|
||||
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 }; }
|
||||
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 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); }
|
||||
@@ -424,7 +462,7 @@ function sessionStateLabel(state: string) { const names: Record<string, { zh: st
|
||||
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'); 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 且起始端口不能大于结束端口。" : "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'); }
|
||||
|
||||
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); }
|
||||
@@ -434,6 +472,7 @@ async function parseResponse(response: Response) { const value = await response.
|
||||
|
||||
<style scoped>
|
||||
.intro-copy h1{font-size:clamp(38px,4.2vw,56px)!important;line-height:1.05!important;letter-spacing:-.055em!important}
|
||||
.admin-topbar .theme-toggle{display:inline-flex;align-items:center;gap:6px}
|
||||
:global(*){box-sizing:border-box}:global(body){margin:0;font-family:Inter,"Segoe UI","PingFang SC",sans-serif;color:#20302c;background:#f4f8f6}.admin-root{min-height:100dvh}.auth-layout{display:grid;min-height:100dvh;grid-template-columns:minmax(360px,.82fr) minmax(520px,1.18fr)}.auth-intro{display:flex;flex-direction:column;padding:48px clamp(38px,6vw,92px);color:#e8fffa;background:radial-gradient(circle at 20% 0,rgba(90,211,191,.28),transparent 32rem),#063f3b}.admin-brand{display:flex;align-items:center;gap:12px}.admin-brand>span{display:grid;place-items:center;width:42px;height:42px;color:#fff;background:#07877d;border-radius:12px;box-shadow:0 8px 22px rgba(0,0,0,.15)}.admin-brand strong,.admin-brand small{display:block}.admin-brand strong{font-size:20px;letter-spacing:-.04em}.admin-brand small{margin-top:3px;color:#9bc9c2;font-size:11px}.intro-copy{margin:auto 0 48px}.intro-copy i{color:#75e3d2;font-size:12px;font-style:normal;font-weight:800;letter-spacing:.12em}.intro-copy h1{max-width:540px;margin:16px 0;font-size:clamp(40px,5vw,66px);line-height:1.03;letter-spacing:-.065em}.intro-copy p{max-width:530px;color:#a9d0ca;font-size:16px;line-height:1.75}.step-list{display:grid;gap:10px}.step-list button{display:flex;align-items:center;gap:13px;width:100%;padding:13px;color:#89bbb4;text-align:left;background:transparent;border:1px solid transparent;border-radius:12px}.step-list button.active{color:#fff;background:rgba(255,255,255,.08);border-color:rgba(255,255,255,.1)}.step-list button.done{color:#8ee4d7}.step-list button>span{display:grid;place-items:center;width:28px;height:28px;flex:none;border:1px solid currentColor;border-radius:50%;font-size:12px;font-weight:800}.step-list strong,.step-list small{display:block}.step-list strong{font-size:13px}.step-list small{margin-top:3px;font-size:10px;opacity:.75}.auth-panel{position:relative;display:grid;place-items:center;padding:80px 40px;background:radial-gradient(circle at 80% 10%,rgba(99,205,188,.15),transparent 25rem),#f5f9f7}.panel-tools{position:absolute;top:28px;right:34px}.panel-tools button,.language-link,.admin-topbar button{color:#08766e;background:#e4f3ef;border:1px solid #cae7e0;border-radius:8px;padding:8px 12px;font-size:11px;font-weight:700;cursor:pointer}.setup-card,.login-card{width:min(560px,100%);padding:36px;background:#fff;border:1px solid #dfeae6;border-radius:20px;box-shadow:0 20px 55px rgba(27,69,61,.09)}.setup-card header small{color:#07877d;font-size:11px;font-weight:800;letter-spacing:.08em}.setup-card header h2,.login-card h1{margin:10px 0 7px;font-size:29px;letter-spacing:-.045em}.setup-card header p,.login-card header p{margin:0;color:#71817c;font-size:13px;line-height:1.6}.form-stack,.login-card form{display:grid;gap:17px;margin-top:27px}label>span,fieldset legend{display:block;margin-bottom:7px;color:#40514c;font-size:12px;font-weight:700}label em{color:#91a09c;font-size:10px;font-style:normal;font-weight:500}label small{display:block;margin-top:6px;color:#899792;font-size:10px;line-height:1.5}input,textarea{width:100%;padding:11px 12px;color:#22332f;background:#fbfdfc;border:1px solid #dbe7e3;border-radius:9px;font:inherit;font-size:13px;outline:none}input{height:43px}input:focus,textarea:focus{border-color:#54bdb2;box-shadow:0 0 0 3px rgba(84,189,178,.13)}textarea{resize:vertical}.strength{height:4px;overflow:hidden;background:#e7eeeb;border-radius:4px}.strength i{display:block;height:100%;background:linear-gradient(90deg,#e7a452,#50c5a2);transition:.2s}fieldset{display:grid;gap:9px;margin:0;padding:0;border:0}.choice{display:flex;align-items:flex-start;gap:10px;padding:13px;border:1px solid #dfe9e6;border-radius:10px;cursor:pointer}.choice:has(input:checked){border-color:#62bfb5;background:#eff8f6}.choice input{width:16px;height:16px;flex:none;margin:2px 0}.choice strong,.choice small{display:block}.choice strong{font-size:12px}.choice small{margin-top:4px;color:#7b8985;font-size:10px;line-height:1.45}.setup-card footer{display:flex;align-items:center;justify-content:space-between;margin-top:28px;padding-top:20px;border-top:1px solid #edf1ef}.primary-button,.secondary-button,.text-button{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:42px;padding:0 18px;border:0;border-radius:9px;font-size:12px;font-weight:800;cursor:pointer}.primary-button{color:#fff;background:#087d74}.primary-button:hover{background:#056b63}.primary-button:disabled,.secondary-button:disabled{opacity:.55;cursor:not-allowed}.secondary-button{color:#08776e;background:#eaf6f3;border:1px solid #cfe9e3}.text-button{color:#687a74;background:transparent}.wide{width:100%}.spinner{display:inline-block;width:22px;height:22px;border:2px solid #cde6df;border-top-color:#087d74;border-radius:50%;animation:spin .7s linear infinite}.spinner.small{width:15px;height:15px;border-color:rgba(255,255,255,.35);border-top-color:currentColor}@keyframes spin{to{transform:rotate(360deg)}}.alert{padding:12px 14px;border-radius:9px;font-size:12px;linLine truncated
|
||||
@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}}
|
||||
@@ -450,6 +489,7 @@ async function parseResponse(response: Response) { const value = await response.
|
||||
@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}
|
||||
.webrtc-card .card-help{margin:5px 0 0;color:#7e8c88;font-size:10px;line-height:1.5}.toggle-choice{margin:0}.webrtc-card>.field-help{margin-top:-8px}
|
||||
@media(max-width:520px){.target-fields{grid-template-columns:1fr}}
|
||||
|
||||
/* Keep administration inside the browser viewport. Long data sets scroll in
|
||||
@@ -552,4 +592,86 @@ async function parseResponse(response: Response) { const value = await response.
|
||||
.operations-page .lower-operations{grid-auto-rows:190px}
|
||||
.operations-page .lower-operations{flex:1 1 0}
|
||||
}
|
||||
.advanced-card{grid-column:1 / -1}
|
||||
.advanced-card .card-help{margin:5px 0 0;color:#7e8c88;font-size:10px;line-height:1.5}
|
||||
.advanced-card .toggle-choice{margin:0}
|
||||
.webrtc-port-fields{display:grid;gap:10px;padding:14px;background:#f6f9f8;border:1px solid #e4efeb;border-radius:10px}
|
||||
.port-fields-heading strong,.port-fields-heading small{display:block}
|
||||
.port-fields-heading strong{font-size:11px}
|
||||
.port-fields-heading small{margin-top:4px;color:#899792;font-size:10px;line-height:1.45}
|
||||
.port-inputs{display:grid;grid-template-columns:1fr 1fr;gap:10px}
|
||||
.port-inputs label>span{font-size:10px}
|
||||
.port-inputs input:disabled{color:#70817b;background:#e9f1ee;border-color:#d7e5e1;cursor:not-allowed;opacity:1}
|
||||
.modal-backdrop{position:fixed;z-index:20;inset:0;display:grid;place-items:center;padding:22px;background:rgba(5,41,38,.38);backdrop-filter:blur(3px)}
|
||||
.modal-card{width:min(410px,100%);padding:26px;background:#fff;border:1px solid #d9e9e4;border-radius:16px;box-shadow:0 20px 60px rgba(14,62,55,.2)}
|
||||
.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}
|
||||
@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.
|
||||
Let each card keep its natural height so a few extra pixels do not create
|
||||
three nested scrollbars. The section itself is the only fallback scroll
|
||||
surface when a small viewport cannot show the complete form. */
|
||||
.server-page{overflow-x:hidden;overflow-y:auto}
|
||||
.server-page .settings-grid{flex:0 0 auto;min-height:auto;align-items:start;overflow:visible;grid-auto-rows:auto}
|
||||
.server-page .settings-card{height:auto;min-height:0;overflow:visible;padding:16px;gap:12px}
|
||||
.server-page .settings-card input{height:40px}
|
||||
.server-page .settings-card .choice{padding:10px;gap:8px}
|
||||
.server-page .settings-card .choice small{margin-top:3px}
|
||||
.server-page .webrtc-port-fields{padding:12px;gap:8px}
|
||||
.server-page .readonly-card{margin-top:12px;padding:14px 16px}
|
||||
.server-page .readonly-card dl{gap:8px;margin-top:10px}
|
||||
|
||||
@media(max-width:850px){
|
||||
.server-page .settings-grid{overflow:visible;grid-auto-rows:auto}
|
||||
.server-page .settings-card{overflow:visible}
|
||||
}
|
||||
|
||||
/* Mobile admin pages should read like one continuous form. Keep the desktop
|
||||
viewport shell untouched, but let the document grow vertically on narrow
|
||||
screens instead of trapping content inside cards and nested panes. */
|
||||
@media(max-width:850px){
|
||||
:global(html),:global(body),:global(#app){height:auto;min-height:100%;max-height:none;overflow:auto}
|
||||
.admin-root{height:auto;min-height:100dvh;overflow:visible}
|
||||
.admin-shell{height:auto;min-height:100dvh;overflow:visible}
|
||||
.admin-main{height:auto;min-height:0;overflow:visible}
|
||||
.page-content{display:block;height:auto;min-height:0;overflow:visible}
|
||||
.login-page{height:auto;min-height:100dvh;overflow:visible}
|
||||
.login-card{max-height:none;overflow:visible}
|
||||
|
||||
.overview-page{height:auto;min-height:0;overflow:visible}
|
||||
.overview-page .overview-columns{grid-template-rows:auto;overflow:visible}
|
||||
.overview-page .target-health-card,.overview-page .recent-events-card{height:auto;min-height:0;overflow:visible}
|
||||
.overview-page .recent-events-card .event-list{max-height:none;overflow:visible}
|
||||
|
||||
.server-page{height:auto;min-height:0;overflow:visible}
|
||||
.server-page .settings-grid{height:auto;overflow:visible}
|
||||
|
||||
.operations-page{height:auto;min-height:0;overflow:visible}
|
||||
.operations-page .operations-primary,.operations-page .lower-operations{height:auto;min-height:0;overflow:visible;grid-auto-rows:auto;flex:none}
|
||||
.operations-page .operation-card{height:auto;min-height:0;overflow:visible}
|
||||
.operations-primary .table-wrap{max-height:none;overflow-x:auto;overflow-y:visible}
|
||||
.operations-primary .invite-list{max-height:none;overflow:visible}
|
||||
.logs-card .log-list,.audit-card .event-list{max-height:none;overflow:visible;flex:none}
|
||||
.logs-card .log-list{width:100%;min-width:0}
|
||||
.logs-card .log-row{min-width:0;max-width:100%;overflow:hidden}
|
||||
.logs-card .log-row>div{width:0;max-width:100%;flex:1 1 auto;min-width:0;overflow:hidden}
|
||||
.logs-card .log-row strong,.logs-card .log-row small{overflow-wrap:anywhere;white-space:normal;word-break:break-word}
|
||||
}
|
||||
|
||||
/* Long log messages should wrap on every screen size instead of widening the
|
||||
log card or introducing page-level horizontal scrolling. */
|
||||
.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}
|
||||
|
||||
.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}
|
||||
</style>
|
||||
+138
-17
@@ -10,7 +10,7 @@
|
||||
<small>{{ t('browserWorkspace') }}</small>
|
||||
</div>
|
||||
</div>
|
||||
<div class="header-tools"><div class="header-note"><span class="tiny-dot"></span> {{ t('secureGateway') }}</div><a class="github-button" href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak" target="_blank" rel="noreferrer" :title="t('githubRepository')" :aria-label="t('githubRepository')"><Icon name="github" :size="18" /><span>{{ t('githubRepository') }}</span></a><span class="version-badge" :title="`${t('currentVersion')}: v${appVersion}`" :aria-label="`${t('currentVersion')}: v${appVersion}`">v{{ appVersion }}</span><a class="changelog-button" href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/CHANGELOG.md" target="_blank" rel="noreferrer" :title="t('viewChangelog')" :aria-label="t('viewChangelog')"><Icon name="clock" :size="16" /><span>{{ t('viewChangelog') }}</span></a><a class="guide-button" href="/admin" :title="t('adminConsole')" :aria-label="t('adminConsole')"><Icon name="settings" :size="15" /><span>{{ t('adminConsole') }}</span></a><button type="button" class="header-action theme-toggle" :title="themeLabel" :aria-label="themeLabel" @click="cycleTheme"><Icon name="monitor" :size="17" /></button><button class="language-switch" :aria-label="t('langSwitch')" @click="toggleLanguage">{{ t('langSwitch') }}</button></div>
|
||||
<div class="header-tools"><div class="header-note"><span class="tiny-dot"></span> {{ t('secureGateway') }}</div><a class="github-button" href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak" target="_blank" rel="noreferrer" :title="t('githubRepository')" :aria-label="t('githubRepository')"><Icon name="github" :size="18" /><span>{{ t('githubRepository') }}</span></a><a class="bilibili-button" href="https://space.bilibili.com/25414873" target="_blank" rel="noreferrer" :title="t('bilibiliProfile')" :aria-label="t('bilibiliProfile')"><span class="bilibili-glyph">B</span><span class="bilibili-label">{{ t('bilibiliProfile') }}</span></a><span class="version-badge" :title="`${t('currentVersion')}: v${appVersion}`" :aria-label="`${t('currentVersion')}: v${appVersion}`">v{{ appVersion }}</span><a class="changelog-button" href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/CHANGELOG.md" target="_blank" rel="noreferrer" :title="t('viewChangelog')" :aria-label="t('viewChangelog')"><Icon name="clock" :size="16" /><span>{{ t('viewChangelog') }}</span></a><a class="guide-button" href="/admin" :title="t('adminConsole')" :aria-label="t('adminConsole')"><Icon name="settings" :size="15" /><span>{{ t('adminConsole') }}</span></a><button type="button" class="header-action theme-toggle" :title="themeLabel" :aria-label="themeLabel" @click="cycleTheme"><Icon :name="themeIcon" :size="17" /></button><button class="language-switch" :aria-label="t('langSwitch')" @click="toggleLanguage">{{ t('langSwitch') }}</button></div>
|
||||
</header>
|
||||
|
||||
<main class="join-content">
|
||||
@@ -64,9 +64,9 @@
|
||||
<input id="channel" v-model="channel" :placeholder="t('emptyDefault')" @keyup.enter="doConnect" />
|
||||
</div>
|
||||
|
||||
<details class="identity-options"><summary>{{ t('identityOptions') }}</summary><label class="remember-identity"><input v-model="rememberIdentity" type="checkbox" /><span><strong>{{ t('rememberIdentity') }}</strong><small>{{ t('rememberIdentityHint') }}</small></span></label></details>
|
||||
<details class="identity-options"><summary>{{ t('identityOptions') }}</summary><label class="remember-identity"><input v-model="rememberIdentity" type="checkbox" /><span><strong>{{ t('rememberIdentity') }}</strong><small>{{ t('rememberIdentityHint') }}</small></span></label></details><p v-if="rememberIdentity" class="identity-warning">{{ t('rememberIdentityConcurrentWarning') }}</p>
|
||||
|
||||
<button class="primary-button connect-button" :disabled="!canJoin || serverConfigLoading || voiceState.connecting" type="submit">
|
||||
<button class="primary-button connect-button" :disabled="!canJoin || serverConfigLoading || !identityReady || voiceState.connecting" type="submit">
|
||||
<span v-if="voiceState.connecting" class="button-spinner"></span>
|
||||
<span>{{ voiceState.connecting ? t('connecting') : t('enterVoice') }}</span>
|
||||
<Icon v-if="!voiceState.connecting" name="chevron-right" :size="17" />
|
||||
@@ -95,9 +95,9 @@
|
||||
</select>
|
||||
</label>
|
||||
<button class="header-action" :title="t('copyInvite')" @click="doShare"><Icon name="share" :size="18" /></button>
|
||||
<button class="header-action microphone-header-toggle" :class="{ muted: microphoneMuted }" :title="microphoneMuted ? t('unmuteMic') : t('muteMic')" :aria-label="microphoneMuted ? t('microphoneMuted') : t('microphoneActive')" :aria-pressed="!microphoneMuted" @click="toggleMicrophone"><Icon :name="microphoneMuted ? 'mic-off' : 'mic'" :size="18" /></button>
|
||||
<button class="header-action" :title="t('audioSettings')" :aria-label="t('audioSettings')" @click="settingsOpen = true"><Icon name="settings" :size="18" /></button>
|
||||
<button type="button" class="header-action theme-toggle" :title="themeLabel" :aria-label="themeLabel" @click="cycleTheme"><Icon name="monitor" :size="17" /></button>
|
||||
<button v-if="isMobileViewport" class="header-action microphone-header-toggle" :class="{ muted: microphoneMuted }" :title="microphoneMuted ? t('unmuteMic') : t('muteMic')" :aria-label="microphoneMuted ? t('microphoneMuted') : t('microphoneActive')" :aria-pressed="!microphoneMuted" @click="toggleMicrophone"><Icon :name="microphoneMuted ? 'mic-off' : 'mic'" :size="18" /></button>
|
||||
<button v-if="isMobileViewport" class="header-action" :title="t('audioSettings')" :aria-label="t('audioSettings')" @click="settingsOpen = true"><Icon name="settings" :size="18" /></button>
|
||||
<button type="button" class="header-action theme-toggle" :title="themeLabel" :aria-label="themeLabel" @click="cycleTheme"><Icon :name="themeIcon" :size="17" /></button>
|
||||
<button class="language-switch workspace-language" :aria-label="t('langSwitch')" @click="toggleLanguage">{{ t('langSwitch') }}</button>
|
||||
<button class="disconnect-button" @click="doDisconnect"><Icon name="door" :size="17" /><span>{{ t('exit') }}</span></button>
|
||||
</div>
|
||||
@@ -198,7 +198,14 @@
|
||||
</section>
|
||||
</div>
|
||||
<div v-if="!filteredMemberChannels.length" class="member-empty">{{ t('noMatchingMembers') }}</div>
|
||||
<div class="member-panel-tip"><Icon name="volume" :size="16" /><span>{{ t('volumeTip') }}</span></div>
|
||||
<div v-if="!isMobileViewport" class="desktop-audio-dock" role="toolbar" :aria-label="t('desktopAudioControls')">
|
||||
<div class="desktop-audio-dock-copy"><strong>{{ t('desktopAudioControls') }}</strong><span>{{ accompanimentActive ? t('accompanimentActive') : t('volumeTip') }}</span></div>
|
||||
<div class="desktop-audio-dock-actions">
|
||||
<button type="button" class="dock-audio-button microphone-header-toggle" :class="{ muted: microphoneMuted }" :title="microphoneMuted ? t('unmuteMic') : t('muteMic')" :aria-label="microphoneMuted ? t('microphoneMuted') : t('microphoneActive')" :aria-pressed="!microphoneMuted" @click="toggleMicrophone"><Icon :name="microphoneMuted ? 'mic-off' : 'mic'" :size="18" /></button>
|
||||
<button type="button" class="dock-audio-button" :title="t('audioSettings')" :aria-label="t('audioSettings')" @click="settingsOpen = true"><Icon name="settings" :size="18" /></button>
|
||||
<button type="button" class="dock-audio-button accompaniment-toggle" :class="{ active: accompanimentActive }" :title="accompanimentActive ? t('stopAccompaniment') : t('startAccompaniment')" :aria-label="accompanimentActive ? t('stopAccompaniment') : t('startAccompaniment')" :aria-pressed="accompanimentActive" @click="toggleAccompaniment"><Icon name="music" :size="18" /></button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<section v-if="mobileSection === 'more'" class="mobile-more-panel">
|
||||
@@ -206,7 +213,7 @@
|
||||
<h2>{{ t('mobileMore') }}</h2>
|
||||
<button type="button" :class="{ muted: microphoneMuted }" @click="toggleMicrophone"><Icon :name="microphoneMuted ? 'mic-off' : 'mic'" :size="18" /> {{ microphoneMuted ? t('unmuteMic') : t('muteMic') }}</button>
|
||||
<button type="button" @click="settingsOpen = true"><Icon name="settings" :size="18" /> {{ t('audioSettings') }}</button>
|
||||
<button type="button" @click="cycleTheme"><Icon name="monitor" :size="18" /> {{ themeLabel }}</button>
|
||||
<button type="button" @click="cycleTheme"><Icon :name="themeIcon" :size="18" /> {{ themeLabel }}</button>
|
||||
<button type="button" @click="toggleLanguage"><Icon name="globe" :size="18" /> {{ t('langSwitch') }}</button>
|
||||
<button type="button" class="danger" @click="doDisconnect"><Icon name="door" :size="18" /> {{ t('exit') }}</button>
|
||||
</section>
|
||||
@@ -247,8 +254,8 @@
|
||||
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
|
||||
import Icon from "../components/Icon.vue";
|
||||
import { useVoiceWebSocket, type ChannelInfo, type ChannelMember } from "../composables/useVoiceWebSocket.js";
|
||||
import { clearLocalData as clearStoredLocalData, isLocalPersistenceAvailable, listFavorites, listRecentServers, loadLocalPreferences, loadStoredIdentity, recordRecentServer, removeFavorite, saveFavorite, saveLocalPreferences, saveStoredIdentity, type FavoriteServer, type RecentServer } from "../services/local-persistence.js";
|
||||
import { applyTheme, getStoredTheme, nextTheme, saveTheme, type ThemeMode } from "../services/theme.js";
|
||||
import { clearLocalData as clearStoredLocalData, isLocalPersistenceAvailable, listFavorites, listRecentServers, loadLocalPreferences, loadStoredIdentity, recordRecentServer, removeFavorite, removeStoredIdentity, saveFavorite, saveLocalPreferences, saveStoredIdentity, type FavoriteServer, type RecentServer } from "../services/local-persistence.js";
|
||||
import { applyTheme, getStoredTheme, isDarkTheme, nextTheme, saveTheme, type ThemeMode } from "../services/theme.js";
|
||||
import { combineTeamSpeakTarget, DEFAULT_TEAM_SPEAK_PORT, isValidTeamSpeakPort, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
|
||||
|
||||
interface TreeChannel extends ChannelInfo {
|
||||
@@ -307,6 +314,10 @@ const {
|
||||
setWhisperTargets,
|
||||
setWhisperActive,
|
||||
setMicrophoneMuted,
|
||||
accompanimentActive,
|
||||
accompanimentErrorCode,
|
||||
startAccompaniment,
|
||||
stopAccompaniment,
|
||||
checkSupport,
|
||||
clearError,
|
||||
} = useVoiceWebSocket();
|
||||
@@ -338,6 +349,7 @@ const audioSettingsError = ref("");
|
||||
const toast = ref("");
|
||||
const chatListEl = ref<HTMLElement | null>(null);
|
||||
const localPersistenceAvailable = isLocalPersistenceAvailable();
|
||||
const identityReady = ref(!localPersistenceAvailable);
|
||||
const chatTab = ref<"channel" | "server" | "private" | "events">("channel");
|
||||
const privateClientId = ref(0);
|
||||
const away = ref(false);
|
||||
@@ -351,13 +363,16 @@ let toastTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
type Language = "zh" | "en";
|
||||
const language = ref<Language>(getInitialLanguage());
|
||||
const themeMode = ref<ThemeMode>(getStoredTheme());
|
||||
const themeLabel = computed(() => themeMode.value === "dark" ? t("themeDark") : themeMode.value === "light" ? t("themeLight") : t("themeSystem"));
|
||||
const themeIcon = computed(() => isDarkTheme(themeMode.value) ? "sun" : "moon");
|
||||
const themeLabel = computed(() => isDarkTheme(themeMode.value) ? t("switchToLightTheme") : t("switchToDarkTheme"));
|
||||
applyTheme(themeMode.value);
|
||||
const translations: Record<Language, Record<string, string>> = {
|
||||
zh: {
|
||||
themeSystem: "跟随系统",
|
||||
themeLight: "浅色主题",
|
||||
themeDark: "深色主题",
|
||||
switchToLightTheme: "切换到浅色主题",
|
||||
switchToDarkTheme: "切换到深色主题",
|
||||
browserWorkspace: "浏览器语音工作台",
|
||||
secureGateway: "安全语音网关",
|
||||
adminConsole: "管理控制台",
|
||||
@@ -393,6 +408,7 @@ const translations: Record<Language, Record<string, string>> = {
|
||||
emptyDefault: "留空进入默认频道",
|
||||
rememberIdentity: "记住此设备的 TeamSpeak 身份",
|
||||
rememberIdentityHint: "仅保存在本设备,用于下次连接时保持身份。",
|
||||
rememberIdentityConcurrentWarning: "同一浏览器只能同时使用一条保持身份的连接;要开启第二条,请取消勾选或使用另一个浏览器。",
|
||||
identityOptions: "设备身份选项",
|
||||
localPersistenceUnavailable: "当前浏览器无法使用持久化存储,本次将使用临时身份。",
|
||||
favoriteServers: "常用服务器",
|
||||
@@ -408,6 +424,7 @@ const translations: Record<Language, Record<string, string>> = {
|
||||
enterVoice: "进入语音空间",
|
||||
connectionAuthorized: "连接信息仅用于本次语音会话",
|
||||
githubRepository: "GitHub 仓库",
|
||||
bilibiliProfile: "Bilibili 个人空间",
|
||||
browserSupport: "Chrome / Edge 94+",
|
||||
teamSpeakClient: "TeamSpeak 浏览器客户端",
|
||||
home: "首页",
|
||||
@@ -420,6 +437,16 @@ const translations: Record<Language, Record<string, string>> = {
|
||||
serverOptions: "更多服务器选项",
|
||||
online: "在线",
|
||||
audioSettings: "音频设置",
|
||||
desktopAudioControls: "音频控制",
|
||||
startAccompaniment: "共享伴奏",
|
||||
stopAccompaniment: "停止伴奏",
|
||||
accompanimentStarted: "伴奏共享已开始",
|
||||
accompanimentStopped: "伴奏共享已停止",
|
||||
accompanimentActive: "伴奏共享中",
|
||||
accompanimentNeedsWebRtc: "伴奏功能需要启用 WebRTC",
|
||||
accompanimentNoAudio: "所选来源没有可共享音频,请重新选择并勾选共享音频",
|
||||
accompanimentPermissionDenied: "无法获取伴奏音频,请允许屏幕共享并勾选共享音频",
|
||||
accompanimentUnsupported: "当前浏览器不支持伴奏共享",
|
||||
serverPassword: "服务器密码",
|
||||
optionalPassword: "没有密码可留空",
|
||||
switchChannel: "切换频道",
|
||||
@@ -575,6 +602,8 @@ const translations: Record<Language, Record<string, string>> = {
|
||||
themeSystem: "System theme",
|
||||
themeLight: "Light theme",
|
||||
themeDark: "Dark theme",
|
||||
switchToLightTheme: "Switch to light theme",
|
||||
switchToDarkTheme: "Switch to dark theme",
|
||||
browserWorkspace: "Browser voice workspace",
|
||||
secureGateway: "Secure voice gateway",
|
||||
adminConsole: "Admin console",
|
||||
@@ -610,6 +639,7 @@ const translations: Record<Language, Record<string, string>> = {
|
||||
emptyDefault: "Leave empty to use the default channel",
|
||||
rememberIdentity: "Remember this TeamSpeak identity on this device",
|
||||
rememberIdentityHint: "Stored only on this device and reused on the next connection.",
|
||||
rememberIdentityConcurrentWarning: "Only one connection can use this identity in the same browser. Clear this option for a second connection or use another browser.",
|
||||
identityOptions: "Device identity options",
|
||||
localPersistenceUnavailable: "Persistent browser storage is unavailable; this session will use an ephemeral identity.",
|
||||
favoriteServers: "Favorites",
|
||||
@@ -625,6 +655,7 @@ const translations: Record<Language, Record<string, string>> = {
|
||||
enterVoice: "Enter voice space",
|
||||
connectionAuthorized: "Connection details are used only for this voice session",
|
||||
githubRepository: "GitHub repository",
|
||||
bilibiliProfile: "Bilibili profile",
|
||||
browserSupport: "Chrome / Edge 94+",
|
||||
teamSpeakClient: "TeamSpeak browser client",
|
||||
home: "Home",
|
||||
@@ -637,6 +668,16 @@ const translations: Record<Language, Record<string, string>> = {
|
||||
serverOptions: "More server options",
|
||||
online: "Online",
|
||||
audioSettings: "Audio settings",
|
||||
desktopAudioControls: "Audio controls",
|
||||
startAccompaniment: "Share accompaniment",
|
||||
stopAccompaniment: "Stop accompaniment",
|
||||
accompanimentStarted: "Accompaniment sharing started",
|
||||
accompanimentStopped: "Accompaniment sharing stopped",
|
||||
accompanimentActive: "Accompaniment sharing",
|
||||
accompanimentNeedsWebRtc: "Accompaniment requires WebRTC",
|
||||
accompanimentNoAudio: "The selected source has no shareable audio. Select it again and enable audio sharing",
|
||||
accompanimentPermissionDenied: "Could not access accompaniment audio. Allow screen sharing and enable audio sharing",
|
||||
accompanimentUnsupported: "This browser does not support accompaniment sharing",
|
||||
serverPassword: "Server password",
|
||||
optionalPassword: "Leave blank if not required",
|
||||
switchChannel: "Switch channel",
|
||||
@@ -822,6 +863,7 @@ function localizedMessage(message: string) {
|
||||
"连接服务器失败,请检查邀请链接或服务器状态": "Could not connect. Check the invite link or server status",
|
||||
"TeamSpeak 连接已断开": "The TeamSpeak connection was closed",
|
||||
"连接已断开": "The connection was closed",
|
||||
"此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试": "This TeamSpeak identity is already used by another browser page. Close that connection or clear ‘Remember identity’ and try again",
|
||||
"TeamSpeak 服务器地址无效": "The TeamSpeak server address is invalid",
|
||||
"TeamSpeak 服务器连接失败": "Could not connect to the TeamSpeak server",
|
||||
"服务器当前已满,请稍后重试": "The server is full. Try again shortly",
|
||||
@@ -937,7 +979,7 @@ const visibleChatMessages = computed(() => {
|
||||
if (chatTab.value === "private") return chatMessages.filter((message) => message.scope === "private" && message.conversationId === String(privateClientId.value));
|
||||
if (chatTab.value !== "channel") return [];
|
||||
const channelId = currentChannel.value?.id;
|
||||
return chatMessages.filter((message) => message.scope === "channel" && (!message.targetId || !channelId || message.targetId === channelId));
|
||||
return chatMessages.filter((message) => message.scope === "channel" && (!message.targetId || message.targetId === "0" || !channelId || message.targetId === channelId));
|
||||
});
|
||||
|
||||
const chatTabLabel = computed(() => chatTab.value === "channel" ? t("textChannel") : chatTab.value === "server" ? t("serverChat") : chatTab.value === "private" ? t("privateMessage") : t("eventLog"));
|
||||
@@ -982,7 +1024,10 @@ watch(settingsOpen, (open) => {
|
||||
});
|
||||
watch(rememberIdentity, (remember) => {
|
||||
localStorage.setItem("webspeak:remember-identity", remember ? "1" : "0");
|
||||
if (!remember) identityMaterial.value = "";
|
||||
if (!remember) {
|
||||
identityMaterial.value = "";
|
||||
void removeStoredIdentity();
|
||||
}
|
||||
});
|
||||
watch([rememberIdentity, identityMaterial], ([remember, material]) => {
|
||||
if (remember && material) void saveStoredIdentity(material);
|
||||
@@ -1027,10 +1072,12 @@ onMounted(() => {
|
||||
}
|
||||
});
|
||||
void loadStoredIdentity().then((stored) => {
|
||||
if (stored) {
|
||||
if (stored && localStorage.getItem("webspeak:remember-identity") === "1") {
|
||||
identityMaterial.value = stored.privateMaterial;
|
||||
rememberIdentity.value = true;
|
||||
}
|
||||
}).finally(() => {
|
||||
identityReady.value = true;
|
||||
});
|
||||
void listFavorites().then((items) => { favoriteServers.value = items; });
|
||||
void listRecentServers().then((items) => { recentServers.value = items; });
|
||||
@@ -1040,6 +1087,7 @@ onMounted(() => {
|
||||
viewportChangeHandler = () => {
|
||||
isMobileViewport.value = viewportMediaQuery?.matches ?? false;
|
||||
if (!isMobileViewport.value) memberMenu.value = null;
|
||||
else if (accompanimentActive.value) void stopAccompaniment();
|
||||
};
|
||||
viewportChangeHandler();
|
||||
viewportMediaQuery.addEventListener?.("change", viewportChangeHandler);
|
||||
@@ -1348,6 +1396,27 @@ function toggleMicrophone(): void {
|
||||
showToast(microphoneMuted.value ? t("microphoneMuted") : t("microphoneActive"));
|
||||
}
|
||||
|
||||
async function toggleAccompaniment(): Promise<void> {
|
||||
try {
|
||||
if (accompanimentActive.value) {
|
||||
await stopAccompaniment();
|
||||
showToast(t("accompanimentStopped"));
|
||||
return;
|
||||
}
|
||||
await startAccompaniment();
|
||||
if (accompanimentActive.value) showToast(t("accompanimentStarted"));
|
||||
} catch {
|
||||
const messageKey = accompanimentErrorCode.value === "needsWebRtc"
|
||||
? "accompanimentNeedsWebRtc"
|
||||
: accompanimentErrorCode.value === "noAudio"
|
||||
? "accompanimentNoAudio"
|
||||
: accompanimentErrorCode.value === "unsupported"
|
||||
? "accompanimentUnsupported"
|
||||
: "accompanimentPermissionDenied";
|
||||
showToast(t(messageKey));
|
||||
}
|
||||
}
|
||||
|
||||
function onWhisperPttDown(event: PointerEvent): void {
|
||||
if (!whisperTargetIds.size) return;
|
||||
const target = event.currentTarget as HTMLElement | null;
|
||||
@@ -1527,6 +1596,7 @@ function stopWhisperTalk(): void {
|
||||
.remember-identity strong, .remember-identity small { display: block; }
|
||||
.remember-identity strong { font-size: 11px; font-weight: 700; }
|
||||
.remember-identity small { margin-top: 3px; color: #8b9994; font-size: 10px; line-height: 1.4; }
|
||||
.identity-warning { margin: 8px 0 0; color: #9a6a32; font-size: 10px; line-height: 1.45; }
|
||||
.local-servers { display: grid; gap: 8px; margin: 1px 0 5px; }
|
||||
.local-server-group { display: flex; flex-wrap: wrap; align-items: center; gap: 5px; }
|
||||
.local-server-group > span { width: 100%; color: #87958f; font-size: 10px; font-weight: 700; }
|
||||
@@ -1623,8 +1693,9 @@ function stopWhisperTalk(): void {
|
||||
.app-shell { grid-template-rows: minmax(0, 1fr) 220px; }
|
||||
}
|
||||
|
||||
/* Keep connected controls in the header; the old bottom dock consumed the
|
||||
chat viewport and made the settings action appear detached from its icon. */
|
||||
/* Desktop audio controls live in the member rail so the workspace header
|
||||
stays focused on navigation. Mobile keeps its existing controls below the
|
||||
voice cards and in the More panel. */
|
||||
.header-tools { align-items: center; }
|
||||
.header-action, .round-icon { line-height: 0; }
|
||||
.guide-button { display: inline-flex; align-items: center; gap: 6px; min-height: 30px; padding: 0 10px; color: #006a64; background: #edf7f4; border: 1px solid #d7ebe6; border-radius: 8px; font-size: 12px; font-weight: 700; text-decoration: none; cursor: pointer; }
|
||||
@@ -1632,6 +1703,15 @@ function stopWhisperTalk(): void {
|
||||
.workspace-actions { align-items: center; flex-wrap: nowrap; }
|
||||
.workspace-actions .header-action { flex: 0 0 34px; padding: 0; line-height: 0; }
|
||||
.workspace-actions .header-action .ui-icon { margin: 0; }
|
||||
.desktop-audio-dock { display: flex; align-items: center; gap: 9px; flex: 0 0 auto; min-width: 0; margin-top: 12px; padding: 9px; color: var(--text-muted); background: color-mix(in srgb, var(--accent) 8%, var(--surface-1)); border: 1px solid var(--border); border-radius: 12px; box-shadow: 0 8px 20px color-mix(in srgb, var(--text-primary) 10%, transparent); }
|
||||
.desktop-audio-dock-copy { display: flex; min-width: 0; flex: 1; flex-direction: column; gap: 3px; }
|
||||
.desktop-audio-dock-copy strong { overflow: hidden; color: var(--text-primary); font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.desktop-audio-dock-copy span { overflow: hidden; font-size: 10px; line-height: 1.35; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.desktop-audio-dock-actions { display: flex; align-items: center; gap: 4px; flex: 0 0 auto; }
|
||||
.dock-audio-button { display: grid; place-items: center; width: 34px; height: 34px; padding: 0; color: var(--text-muted); background: transparent; border: 1px solid transparent; border-radius: 9px; cursor: pointer; transition: color .16s, background .16s, border-color .16s, transform .16s; }
|
||||
.dock-audio-button:hover, .dock-audio-button:focus-visible { color: var(--accent); background: color-mix(in srgb, var(--accent) 14%, var(--surface-1)); border-color: color-mix(in srgb, var(--accent) 32%, var(--border)); transform: translateY(-1px); }
|
||||
.dock-audio-button.microphone-header-toggle.muted { color: var(--danger); background: color-mix(in srgb, var(--danger) 12%, var(--surface-1)); }
|
||||
.dock-audio-button.accompaniment-toggle.active { color: var(--accent); background: color-mix(in srgb, var(--accent) 18%, var(--surface-1)); border-color: color-mix(in srgb, var(--accent) 40%, var(--border)); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 12%, transparent); }
|
||||
.settings-mode-switch { width: fit-content; margin: 0 0 7px; }
|
||||
.settings-hint { margin: -1px 0 19px; color: #8b9994; font-size: 11px; }
|
||||
|
||||
@@ -1856,7 +1936,7 @@ function stopWhisperTalk(): void {
|
||||
.member-presence { width: 10px; height: 10px; }
|
||||
.member-copy strong { font-size: 14px; }
|
||||
.member-copy span { margin-top: 3px; font-size: 12px; }
|
||||
.member-flags, .member-volume, .member-panel-tip { display: none; }
|
||||
.desktop-audio-dock, .member-flags, .member-volume, .member-panel-tip { display: none; }
|
||||
.member-action-button { display: grid; place-items: center; width: 38px; height: 38px; flex: 0 0 38px; color: var(--text-muted); background: transparent; border-radius: 10px; cursor: pointer; }
|
||||
.member-action-button:hover, .member-action-button:active { color: var(--accent); background: color-mix(in srgb, var(--accent) 14%, var(--surface-1)); }
|
||||
|
||||
@@ -1931,4 +2011,45 @@ function stopWhisperTalk(): void {
|
||||
.join-content { gap: 18px; }
|
||||
.join-card { padding-inline: 15px; }
|
||||
}
|
||||
|
||||
/* Keep every welcome-page action inside the viewport on narrow phones. */
|
||||
@media (max-width: 420px) {
|
||||
.join-page .join-header { width: calc(100% - 20px); gap: 6px; }
|
||||
.join-page .brand-lockup { min-width: 0; flex: 1 1 auto; gap: 7px; }
|
||||
.join-page .brand-mark { width: 32px; height: 32px; border-radius: 9px; }
|
||||
.join-page .brand-lockup strong { overflow: hidden; font-size: 15px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.join-page .brand-lockup small { display: none; }
|
||||
.join-page .header-tools { min-width: 0; flex: 0 0 auto; gap: 2px; }
|
||||
.join-page .header-tools .theme-toggle { display: none; }
|
||||
.join-page .github-button, .join-page .bilibili-button, .join-page .changelog-button, .join-page .guide-button { width: 28px; min-width: 28px; min-height: 28px; height: 28px; padding: 0; }
|
||||
.join-page .github-button, .join-page .bilibili-button, .join-page .changelog-button, .join-page .guide-button { justify-content: center; }
|
||||
.join-page .github-button .ui-icon { width: 16px; height: 16px; }
|
||||
.join-page .bilibili-glyph { width: 18px; height: 18px; }
|
||||
.join-page .version-badge { min-width: 28px; min-height: 28px; padding-inline: 4px; font-size: 9px; }
|
||||
.join-page .language-switch { min-width: 40px; min-height: 28px; padding-inline: 4px; font-size: 10px; }
|
||||
}
|
||||
|
||||
@media (max-width: 360px) {
|
||||
.join-page .brand-lockup > div { display: none; }
|
||||
.join-page .brand-lockup { flex: 0 0 32px; }
|
||||
}
|
||||
|
||||
.bilibili-button { display: inline-flex; align-items: center; gap: 7px; min-height: 30px; padding: 0 10px; color: #e56b91; background: #fff0f5; border: 1px solid #f6d2df; border-radius: 8px; font-size: 11px; font-weight: 800; text-decoration: none; transition: .18s; }
|
||||
.bilibili-button:hover { color: #fff; background: #e56b91; border-color: #e56b91; box-shadow: 0 7px 16px rgba(229,107,145,.2); transform: translateY(-1px); }
|
||||
.bilibili-glyph { display: grid; place-items: center; width: 18px; height: 18px; color: #fff; background: #e56b91; border-radius: 5px; font-size: 11px; line-height: 1; }
|
||||
.bilibili-button:hover .bilibili-glyph { color: #e56b91; background: #fff; }
|
||||
|
||||
@media (max-width: 740px) {
|
||||
.bilibili-button { width: 32px; min-width: 32px; min-height: 32px; justify-content: center; padding: 0; }
|
||||
.bilibili-button .bilibili-label { display: none; }
|
||||
}
|
||||
|
||||
@media (max-width: 390px) {
|
||||
.join-page .bilibili-button { width: 32px; min-width: 32px; min-height: 32px; height: 32px; }
|
||||
}
|
||||
|
||||
/* Override the shared Bilibili sizing above for the tighter welcome header. */
|
||||
@media (max-width: 420px) {
|
||||
.join-page .bilibili-button { width: 28px; min-width: 28px; min-height: 28px; height: 28px; padding: 0; }
|
||||
}
|
||||
</style>
|
||||
Reference in new issue
Block a user