Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
69f8d66ca9 | ||
|
|
7789758024 | ||
|
|
c211deeb98 | ||
|
|
aad7833509 | ||
|
|
39413cf840 | ||
|
|
50d9d58ad0 | ||
|
|
0a552f7ee8 | ||
|
|
568b8fd8be | ||
|
|
d919df1273 | ||
|
|
921e83dfb3 | ||
|
|
77fef3bed9 | ||
|
|
2c49ee2599 | ||
|
|
81a860c3df | ||
|
|
d327c6f179 | ||
|
|
7baeff00ba | ||
|
|
777c779d79 | ||
|
|
051cb402e5 | ||
|
|
1791d5946d | ||
|
|
39eba1b121 | ||
|
|
a195681e78 | ||
|
|
172347aaa7 | ||
|
|
8e28bca634 | ||
|
|
4ef7ec5ee3 | ||
|
|
f18fa63001 | ||
|
|
6ed8abfb15 | ||
|
|
8b6c998c43 | ||
|
|
d2caaa8f3c | ||
|
|
83b2430d18 | ||
|
|
a416e36bd1 | ||
|
|
a2f91e606f | ||
|
|
9dfded0fb7 | ||
|
|
15e22d3099 | ||
|
|
db08fbda6b | ||
|
|
c16d1d4cfb | ||
|
|
5855d0ba67 | ||
|
|
f11fe26bfe | ||
|
|
1a46ab83a3 | ||
|
|
878e94a93a | ||
|
|
2047e30984 | ||
|
|
3dfd25dab7 | ||
|
|
c8417edd7d | ||
|
|
49481145ef | ||
|
|
3b5c0dfc7d | ||
|
|
525f512f4a | ||
|
|
0785f82386 | ||
|
|
797fc135a9 | ||
|
|
f0712fa3fc | ||
|
|
e2f0a43762 | ||
|
|
8960189bc7 | ||
|
|
f4cbd61cff | ||
|
|
541a216c4d | ||
|
|
aeaeb15965 | ||
|
|
9e2b9bf564 | ||
|
|
0a4fff6f6f | ||
|
|
e0d5916a86 | ||
|
|
e8dc71329b | ||
|
|
30682cd659 | ||
|
|
e09a19b7b4 | ||
|
|
2b7e908d31 | ||
|
|
0ea85752fd | ||
|
|
97b7127ca3 | ||
|
|
db38feba52 | ||
|
|
1bab4df64e | ||
|
|
193130c50f | ||
|
|
c7794a12e7 | ||
|
|
408d8bcda4 | ||
|
|
5a3eebecbd | ||
|
|
713716dacc | ||
|
|
3a7a162f97 | ||
|
|
2f8614d53a | ||
|
|
bdac15afac | ||
|
|
7f49e2f2d7 | ||
|
|
24f1b9a4b8 | ||
|
|
79b91fca44 | ||
|
|
6a821b760e | ||
|
|
6539479d10 | ||
|
|
8ed3e788be | ||
|
|
de8f6a11c9 | ||
|
|
21d53a30c9 | ||
|
|
22656b2e7d | ||
|
|
3a18bcebbc | ||
|
|
7b35c63a74 | ||
|
|
6b9038da6c | ||
|
|
1dd04bf7ca | ||
|
|
15af861389 | ||
|
|
7ea63c525e | ||
|
|
3d0b8a5c97 | ||
|
|
fb39d82c01 | ||
|
|
ae530963bf | ||
|
|
f8554fc991 | ||
|
|
a3dad55c76 | ||
|
|
0b29742bce | ||
|
|
c2c38fa011 | ||
|
|
578217ba41 | ||
|
|
d75bdccfd9 | ||
|
|
412f560677 | ||
|
|
fdccf86458 | ||
|
|
d43a33aa15 | ||
|
|
056b57bcd1 | ||
|
|
688eb3174e | ||
|
|
c38f67bc3b | ||
|
|
67c7a27af6 | ||
|
|
6d1d2a1f92 | ||
|
|
faff7a2237 | ||
|
|
dc63f4b45b | ||
|
|
380fb67090 | ||
|
|
b71632cc29 | ||
|
|
38f7c94a65 | ||
|
|
d91a145657 | ||
|
|
a2e33ff176 | ||
|
|
010b8ef072 | ||
|
|
883703dd0c | ||
|
|
bcf212738b | ||
|
|
fae21ec086 | ||
|
|
22dcf93925 | ||
|
|
4df59b80d0 |
No files matched your search
@@ -0,0 +1,32 @@
|
||||
---
|
||||
name: webspeak-skin-development
|
||||
description: Create, refine, package, and verify WebSpeak visual skins while preserving the product's translated content, fixed component geometry, and interactions.
|
||||
---
|
||||
|
||||
# WebSpeak skin development
|
||||
|
||||
Use this skill when editing or authoring a WebSpeak `.wskin` package, the ILLUSIA built-in skin, or skin-facing UI hooks. A skin changes artwork and visual treatment; WebSpeak owns page structure, text, and behavior. The administrator console is deliberately outside the skin scope.
|
||||
|
||||
## Before editing
|
||||
|
||||
- Read [`docs/SKIN_DEVELOPMENT.md`](../../../docs/SKIN_DEVELOPMENT.md) for the current package validator and public hooks.
|
||||
- Use [`docs/examples/illusia-voice/`](../../../docs/examples/illusia-voice/) and [`docs/examples/ILLUSIA-VOICE.md`](../../../docs/examples/ILLUSIA-VOICE.md) as the reference implementation. Do not restore the removed Aurora Voice sample.
|
||||
- Inspect the actual component markup for `data-ws-page`, `data-ws-part`, and `data-ws-state` hooks. Treat Vue classes and incidental DOM structure as private.
|
||||
|
||||
## Preserve the interface
|
||||
|
||||
- Keep WebSpeak's translations and semantic content as the baseline. Add `content.json` only when a text override is an explicit part of the request; never use it to implement visual artwork.
|
||||
- Skin only with supported visual CSS and package-local images/fonts. The upload validator rejects layout, positioning, sizing, spacing, clipping, text-flow, and interaction-geometry changes. Do not work around it with selectors, pseudo-elements, or animation.
|
||||
- Never hide or obstruct critical controls, make a card or player move/resize, change a floating menu into a modal, or make artwork intercept pointer input. Keep `/admin/**` unskinned.
|
||||
- Use the host's reserved artwork hooks for layered character art and the headphone scene. Prefer transparent assets and `background-size: contain` where the reference requires the full character or chibi to remain visible; arrange the artwork around the fixed hook rather than changing its geometry.
|
||||
- Build visual depth with separate background, surface, and foreground artwork already exposed by the hooks. Avoid duplicate static decorations when an animated replacement exists. For motion, keep waveforms/sonar smooth and restrained, honor reduced-motion preferences, and retain readable focus, error, mute, and speaking states.
|
||||
- Keep skin-specific CSS variables under `--skin-*`. Use only package-local assets and confirm their redistribution rights.
|
||||
|
||||
## Verify and package
|
||||
|
||||
1. Compare the implementation with its visual reference at desktop and narrow widths. Check the homepage, voice workspace, empty chat, member list, screen-share player, selectors, and `/demo`; verify no crop, overflow, text collision, or control overlap.
|
||||
2. Check all five interface languages, day/night modes, keyboard focus, and reduced-motion behavior. Confirm the admin console is unchanged.
|
||||
3. Run `npm test` and `npm --prefix web run build`. Fix validator or build failures rather than weakening the layout guardrails.
|
||||
4. Package the contents of the skin directory so `manifest.json` is at the archive root, then import it through `/admin/skins` and retest the installed `.wskin` in a visitor session.
|
||||
|
||||
The three shipped skins—default day, default night, and ILLUSIA—are protected built-ins. Do not change their IDs or introduce upload/update flows that can disable, replace, or remove them.
|
||||
@@ -3,6 +3,10 @@
|
||||
.claude
|
||||
node_modules
|
||||
web/node_modules
|
||||
mobile/node_modules
|
||||
web/android
|
||||
.local-opus-hook.cjs
|
||||
界面参考
|
||||
dist
|
||||
web/dist
|
||||
data
|
||||
@@ -13,4 +17,6 @@ scripts/acceleration-poc
|
||||
*.tar.xz
|
||||
claude.pem
|
||||
config.json
|
||||
.env
|
||||
.env.*
|
||||
*.log
|
||||
@@ -9,20 +9,31 @@ on:
|
||||
version:
|
||||
description: Release version without the v prefix
|
||||
required: true
|
||||
default: 0.1.3
|
||||
default: 0.2.6
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
windows-x64:
|
||||
runs-on: windows-latest
|
||||
verify:
|
||||
uses: ./.github/workflows/ci.yml
|
||||
|
||||
windows:
|
||||
needs: verify
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: x64
|
||||
runner: windows-latest
|
||||
runs-on: ${{ matrix.runner }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22.22.2
|
||||
architecture: x64
|
||||
cache: npm
|
||||
cache-dependency-path: |
|
||||
package-lock.json
|
||||
@@ -47,20 +58,21 @@ jobs:
|
||||
npm version --no-git-tag-version $releaseVersion
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
}
|
||||
npm --prefix web run build
|
||||
npm run web:build
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
npm run build
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
npm prune --omit=dev --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
- name: Package and smoke-test Windows x64
|
||||
- name: Package and smoke-test Windows ${{ matrix.arch }}
|
||||
shell: pwsh
|
||||
env:
|
||||
RELEASE_REF: ${{ inputs.version || github.ref_name }}
|
||||
PACKAGE_ARCH: ${{ matrix.arch }}
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
$releaseVersion = $env:RELEASE_REF -replace '^v', ''
|
||||
$packageName = "webspeak-webclient-v$releaseVersion-windows-x64"
|
||||
$packageName = "webspeak-webclient-v$releaseVersion-windows-$env:PACKAGE_ARCH"
|
||||
$packageRoot = Join-Path $env:RUNNER_TEMP $packageName
|
||||
$runtimeRoot = Split-Path -Parent (Get-Command node).Source
|
||||
New-Item -ItemType Directory -Path $packageRoot | Out-Null
|
||||
@@ -88,7 +100,7 @@ jobs:
|
||||
Copy-Item -Recurse -LiteralPath $packageRoot -Destination $smokeRoot
|
||||
@{
|
||||
port = 3040
|
||||
tsHost = "203.0.113.10"
|
||||
tsHost = "127.0.0.1"
|
||||
tsPort = 9987
|
||||
tsServerPassword = ""
|
||||
tsServerProtocol = "ts6"
|
||||
@@ -112,18 +124,28 @@ jobs:
|
||||
Compress-Archive -LiteralPath $packageRoot -DestinationPath (Join-Path $env:GITHUB_WORKSPACE ($packageName + ".zip")) -CompressionLevel Optimal
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-x64
|
||||
path: webspeak-webclient-v*-windows-x64.zip
|
||||
name: windows-${{ matrix.arch }}
|
||||
path: webspeak-webclient-v*-windows-${{ matrix.arch }}.zip
|
||||
if-no-files-found: error
|
||||
compression-level: 0
|
||||
|
||||
linux-x64:
|
||||
runs-on: ubuntu-latest
|
||||
linux:
|
||||
needs: verify
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: x64
|
||||
runner: ubuntu-latest
|
||||
- arch: arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
runs-on: ${{ matrix.runner }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22.22.2
|
||||
architecture: ${{ matrix.arch == 'arm64' && 'arm64' || 'x64' }}
|
||||
cache: npm
|
||||
cache-dependency-path: |
|
||||
package-lock.json
|
||||
@@ -142,16 +164,17 @@ jobs:
|
||||
if [ "$current_version" != "$release_version" ]; then
|
||||
npm version --no-git-tag-version "$release_version"
|
||||
fi
|
||||
npm --prefix web run build
|
||||
npm run web:build
|
||||
npm run build
|
||||
npm prune --omit=dev --no-audit --no-fund
|
||||
- name: Package and smoke-test Linux x64
|
||||
- name: Package and smoke-test Linux ${{ matrix.arch }}
|
||||
env:
|
||||
RELEASE_REF: ${{ inputs.version || github.ref_name }}
|
||||
PACKAGE_ARCH: ${{ matrix.arch }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
release_version="${RELEASE_REF#v}"
|
||||
package_name="webspeak-webclient-v${release_version}-linux-x64"
|
||||
package_name="webspeak-webclient-v${release_version}-linux-${PACKAGE_ARCH}"
|
||||
package_root="$RUNNER_TEMP/$package_name"
|
||||
runtime_root="$(dirname "$(dirname "$(command -v node)")")"
|
||||
mkdir -p "$package_root/web" "$package_root/runtime"
|
||||
@@ -175,7 +198,7 @@ jobs:
|
||||
cat > "$smoke_root/config.json" <<'CONFIG'
|
||||
{
|
||||
"port": 3040,
|
||||
"tsHost": "203.0.113.10",
|
||||
"tsHost": "127.0.0.1",
|
||||
"tsPort": 9987,
|
||||
"tsServerPassword": "",
|
||||
"tsServerProtocol": "ts6",
|
||||
@@ -200,28 +223,117 @@ jobs:
|
||||
tar -czf "$GITHUB_WORKSPACE/${package_name}.tar.gz" -C "$RUNNER_TEMP" "$package_name"
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: linux-x64
|
||||
path: webspeak-webclient-v*-linux-x64.tar.gz
|
||||
name: linux-${{ matrix.arch }}
|
||||
path: webspeak-webclient-v*-linux-${{ matrix.arch }}.tar.gz
|
||||
if-no-files-found: error
|
||||
compression-level: 0
|
||||
|
||||
android:
|
||||
needs: verify
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22.22.2
|
||||
cache: npm
|
||||
cache-dependency-path: |
|
||||
package-lock.json
|
||||
web/package-lock.json
|
||||
mobile/package-lock.json
|
||||
- uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "21"
|
||||
- uses: android-actions/setup-android@v4
|
||||
with:
|
||||
packages: platform-tools
|
||||
- name: Build Android APKs
|
||||
env:
|
||||
RELEASE_REF: ${{ inputs.version || github.ref_name }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
release_version="${RELEASE_REF#v}"
|
||||
version_code="$(node -e 'const [major, minor, patch] = process.argv[1].split(".").map(Number); process.stdout.write(String(major * 10000 + minor * 100 + patch))' "$release_version")"
|
||||
sdkmanager "platform-tools" "platforms;android-36" "build-tools;36.0.0"
|
||||
npm ci --ignore-scripts --no-audit --no-fund
|
||||
current_version="$(node -p "require('./package.json').version")"
|
||||
if [ "$current_version" != "$release_version" ]; then
|
||||
npm version --no-git-tag-version "$release_version"
|
||||
fi
|
||||
npm run prepare:sdk
|
||||
npm --prefix web ci --no-audit --no-fund
|
||||
npm --prefix mobile ci --no-audit --no-fund
|
||||
npm run android:sync
|
||||
cd web/android
|
||||
chmod +x gradlew
|
||||
./gradlew --no-daemon assembleDebug -PappVersion="$release_version" -PappVersionCode="$version_code"
|
||||
cd "$GITHUB_WORKSPACE"
|
||||
mkdir -p release-apks
|
||||
for apk in web/android/app/build/outputs/apk/debug/app-*-debug.apk; do
|
||||
abi="${apk##*/app-}"
|
||||
abi="${abi%-debug.apk}"
|
||||
cp "$apk" "release-apks/webspeak-android-v${release_version}-${abi}-debug.apk"
|
||||
done
|
||||
test "$(find release-apks -maxdepth 1 -name '*.apk' | wc -l)" -eq 3
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: android-apks
|
||||
path: release-apks/*.apk
|
||||
if-no-files-found: error
|
||||
compression-level: 0
|
||||
|
||||
publish-release:
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
needs: [windows-x64, linux-x64]
|
||||
needs: [windows, linux, android]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Download deployment packages
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
pattern: '*-x64'
|
||||
pattern: '*'
|
||||
path: release-assets
|
||||
merge-multiple: true
|
||||
- name: Create checksums
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd release-assets
|
||||
sha256sum * > SHA256SUMS.txt
|
||||
- name: Publish GitHub release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ github.ref_name }}
|
||||
name: WebSpeak ${{ github.ref_name }}
|
||||
generate_release_notes: true
|
||||
body_path: docs/releases/${{ github.ref_name }}.md
|
||||
files: release-assets/*
|
||||
- name: Remove superseded preview release and tag
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const tag = 'v0.2.6-preview';
|
||||
try {
|
||||
const release = await github.rest.repos.getReleaseByTag({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
tag,
|
||||
});
|
||||
await github.rest.repos.deleteRelease({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
release_id: release.data.id,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error.status !== 404) throw error;
|
||||
}
|
||||
try {
|
||||
await github.rest.git.deleteRef({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
ref: `tags/${tag}`,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error.status !== 404 && error.status !== 422) throw error;
|
||||
}
|
||||
@@ -2,8 +2,10 @@ name: Continuous integration
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
branches: [dev, master]
|
||||
pull_request:
|
||||
workflow_call:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -26,10 +28,8 @@ jobs:
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
|
||||
npm --prefix web ci --no-audit --no-fund
|
||||
- name: Build application
|
||||
run: |
|
||||
npm run build
|
||||
npm --prefix web run build
|
||||
- name: Test and build application
|
||||
run: npm run verify
|
||||
|
||||
docker-smoke:
|
||||
needs: verify
|
||||
|
||||
@@ -14,10 +14,15 @@ env:
|
||||
IMAGE_NAME: ghcr.io/echosixhiya/webspeak
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
uses: ./.github/workflows/ci.yml
|
||||
|
||||
publish:
|
||||
needs: verify
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: docker/setup-qemu-action@v3
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
- name: Log in to GHCR
|
||||
uses: docker/login-action@v3
|
||||
@@ -39,6 +44,7 @@ jobs:
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
platforms: linux/amd64,linux/arm64
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
|
||||
@@ -1,9 +1,31 @@
|
||||
node_modules/
|
||||
dist/
|
||||
web/dist/
|
||||
mobile/node_modules/
|
||||
web/android/.gradle/
|
||||
web/android/build/
|
||||
web/android/app/build/
|
||||
web/android/local.properties
|
||||
web/android/app/src/main/assets/public/
|
||||
web/android/app/src/main/assets/capacitor.config.json
|
||||
data/
|
||||
config.json
|
||||
*.log
|
||||
.env
|
||||
webspeak-update.tar.gz
|
||||
# Local deployment/download artifacts (see docs/LOCAL_ARTIFACTS.zh-CN.md).
|
||||
/release-artifacts/
|
||||
/webspeak-deploy*.tar.gz
|
||||
/webspeak-update*.tar.gz
|
||||
/teamspeak6-server-linux-amd64.tar.xz
|
||||
/.local-opus-hook.cjs
|
||||
/界面参考/stitch_teamspeak_web_interface.zip
|
||||
claude.pem
|
||||
|
||||
# Private credentials and deployment notes stay local.
|
||||
.env.*
|
||||
!.env.example
|
||||
*.pem
|
||||
*.key
|
||||
/.claude/
|
||||
/LOCAL-RELEASE-RUNBOOK.md
|
||||
/DEPLOYMENT-*.md
|
||||
@@ -1,5 +1,180 @@
|
||||
# Changelog
|
||||
|
||||
## [0.2.6] — 2026-10-08(相对 0.2.5 正式版)
|
||||
|
||||
### 中文
|
||||
|
||||
- 修复 [#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10) 中 Docker/Compose 短主机名解析和 HTTPS 健康检查问题;实现 [#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9) 的 TeamSpeak 身份导入、转换与导出;加固 [#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6) 静音状态同步及 [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7) TS6 屏幕共享清理流程。
|
||||
- 实现 [#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12) 所需的公网媒体地址、IPv6 候选和语音 STUN 管理配置;修复 [PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13) 所报告的连接后漏掉既有 TS6 原生屏幕共享的问题。媒体直连仍要求 UDP 路径可达,需按部署环境配置并验证。
|
||||
- 改善语音与 WebRTC 会话稳定性:隔离连接切换后的音频、目录和统计事件,改进 Opus 协商及连续编码状态,并修复静音麦克风时伴奏被一并静音的问题。
|
||||
- 优化移动端语音控制、屏幕常亮和窄屏布局;改进管理后台状态生命周期与语音工作区组件结构。
|
||||
- 发布包提供 Windows x64 与 Linux x64/ARM64;Docker 镜像支持 amd64/arm64;增加 Android 客户端 APK,包含 arm64-v8a、armeabi-v7a、x86_64 三种构建。Android APK 使用 debug 签名,供侧载测试,不代表已完成真机 TeamSpeak 语音验收。
|
||||
|
||||
### English
|
||||
|
||||
- Fixed Docker/Compose short-hostname resolution and HTTPS health checks in [#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10); implemented TeamSpeak identity import, conversion, and export for [#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9); hardened mute-state synchronization for [#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6) and TS6 screen-share cleanup for [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7).
|
||||
- Added the public media address, IPv6-candidate, and voice-STUN controls requested by [#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12), and fixed the missed-existing-TS6-share case described in [PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13). Direct media still requires a reachable UDP path and deployment-specific configuration and testing.
|
||||
- Improved voice and WebRTC session stability by isolating audio, directory, and statistics events across reconnects, tightening Opus negotiation and encoder continuity, and keeping accompaniment audible while the microphone is muted.
|
||||
- Refined mobile voice controls, screen wake behavior, and narrow layouts; improved administration state lifecycles and voice-workspace component boundaries.
|
||||
- Added Windows x64 and Linux x64/ARM64 packages; Docker images support amd64/arm64. Android APKs are available for arm64-v8a, armeabi-v7a, and x86_64. They use debug signing for sideload testing; real-device TeamSpeak voice has not been validated.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Docker-/Compose-Auflösung kurzer Hostnamen und HTTPS-Gesundheitsprüfungen aus [#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10) behoben; Import, Konvertierung und Export von TeamSpeak-Identitäten für [#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9) ergänzt; Stummschaltungssynchronisierung aus [#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6) und TS6-Bildschirmfreigabe-Bereinigung aus [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7) gehärtet.
|
||||
- Die in [#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12) gewünschten Einstellungen für öffentliche Medienadresse, IPv6-Kandidaten und Sprach-STUN ergänzt; den Fall verpasst synchronisierter, bereits aktiver TS6-Freigaben aus [PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13) behoben. Direkte Medien benötigen weiterhin einen erreichbaren UDP-Pfad und deployment-spezifische Konfiguration und Tests.
|
||||
- Sprach- und WebRTC-Sitzungen stabilisiert, Opus-Aushandlung verbessert und Begleitton bei stummgeschaltetem Mikrofon erhalten. Mobile Sprachsteuerung, Bildschirm-Wachhalten und schmale Layouts wurden überarbeitet.
|
||||
- Windows-x64- und Linux-x64/ARM64-Pakete sowie Docker-Images für amd64/arm64 ergänzt. Android-APKs gibt es für arm64-v8a, armeabi-v7a und x86_64; sie sind für Seiteneinladungstests debug-signiert. Reale TeamSpeak-Sprachtests auf Geräten sind nicht bestätigt.
|
||||
|
||||
### Русский
|
||||
|
||||
- Исправлены разрешение коротких имён Docker/Compose и HTTPS-проверки работоспособности из [#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10); добавлен импорт, преобразование и экспорт идентификаторов TeamSpeak для [#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9); усилена синхронизация микрофона из [#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6) и очистка трансляции экрана TS6 из [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7).
|
||||
- Добавлены настройки публичного адреса медиа, IPv6-кандидатов и голосового STUN по запросу [#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12); исправлен пропуск уже запущенной трансляции TS6 после подключения из [PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13). Для прямого медиа по-прежнему нужен доступный UDP-маршрут и настройка конкретного развёртывания.
|
||||
- Повышена устойчивость голосовых сессий и WebRTC: события аудио, каталога и статистики изолированы при переподключении, улучшены согласование Opus и непрерывность кодирования; музыка сопровождения остаётся слышна при выключенном микрофоне. Улучшены мобильные элементы управления и узкие экраны.
|
||||
- Доступны пакеты Windows x64 и Linux x64/ARM64, Docker-образы — для amd64/arm64. Android APK собраны для arm64-v8a, armeabi-v7a и x86_64 и подписаны отладочным ключом для установки вручную; голос TeamSpeak на реальных устройствах не проверен.
|
||||
|
||||
### 日本語
|
||||
|
||||
- [#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10) の Docker/Compose 短縮ホスト名解決と HTTPS ヘルスチェックを修正。[#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9) の TeamSpeak ID インポート・変換・エクスポートを実装し、[#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6) のミュート同期と [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7) の TS6 画面共有終了処理を強化しました。
|
||||
- [#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12) の要望に沿って公開メディアアドレス、IPv6 候補、音声 STUN の設定を追加し、[PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13) が報告した接続前から存在する TS6 画面共有の見落としを修正しました。直接メディア通信には到達可能な UDP 経路と環境ごとの設定・検証が必要です。
|
||||
- 音声/WebRTC セッションの安定性を改善し、再接続後に古い音声・ディレクトリ・統計イベントが混ざらないようにしました。Opus のネゴシエーションと連続エンコードを改善し、マイクをミュートしても伴奏が聞こえるよう修正しました。モバイル操作と狭い画面のレイアウトも改善しました。
|
||||
- Windows x64 と Linux x64/ARM64 のサーバーパッケージ、amd64/arm64 の Docker イメージに対応。Android APK は arm64-v8a、armeabi-v7a、x86_64 を用意しました。APK はサイドロードテスト向けのデバッグ署名で、実機 TeamSpeak 音声は未検証です。
|
||||
|
||||
## [0.2.5] — 2026-09-27(相对 0.2.4)
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增 `.wskin` 视觉皮肤系统:用户可在首页、语音工作区和 `/demo` 选择外观;皮肤可更换背景、美术素材与组件视觉,但页面结构、排版空间、控件位置和交互仍由 WebSpeak 固定提供,管理后台不受皮肤影响。
|
||||
- 管理员可在皮肤库启用/停用自定义皮肤并指定实例默认皮肤;访客手动选择会保留,未手动选择的访客采用实例默认。默认日间、默认夜间和 ILLUSIA 风是受保护内置皮肤,不能删除、停用或替换。
|
||||
- 将完成度不足的 Aurora Voice 示例移除,以 ILLUSIA 风作为完整皮肤开发样例;细化首页装饰、语音区跨层级立绘、耳机场景、聊天空状态和屏幕播放器表现,并修复深色模式控件可读性、组件溢出和皮肤加载闪烁。
|
||||
- 新增官方仓库皮肤开发 Agent Skill,配套更新开发规范与多语言功能说明;访客总数在统计暂不可用时也不会低于当前访客序号。
|
||||
- 缩小 ILLUSIA 语音活动立绘并固定在容器右下角,避免遮挡成员名单和屏幕共享播放器。
|
||||
|
||||
### English
|
||||
|
||||
- Added the `.wskin` visual skin system. Visitors can choose appearances on the home page, voice workspace, and `/demo`; skins may customize artwork and component visuals while WebSpeak retains page structure, layout, control placement, and behavior. The administration console remains unskinned.
|
||||
- Administrators can enable/disable custom skins and set an instance default. Deliberate visitor choices are preserved; visitors without an explicit choice receive the instance default. Default Day, Default Night, and ILLUSIA are protected built-ins that cannot be removed, disabled, or replaced.
|
||||
- Removed the unfinished Aurora Voice sample and made ILLUSIA the complete reference skin. Refined homepage artwork, layered voice-room character art and headphone scene, the empty-chat backdrop, and the screen-share player; fixed dark-mode control contrast, overflow, and skin-load flashes.
|
||||
- Added the repository's official skin-development Agent Skill and synchronized the guide and localized feature notes. The displayed visitor total also remains at least as high as the current visitor ordinal when the counter is unavailable.
|
||||
- Reduced and anchored the ILLUSIA voice-activity artwork to the lower-right corner so it no longer obscures member cards or the screen-share player.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Das visuelle `.wskin`-System wurde ergänzt. Besucher können das Design auf der Startseite, im Sprachbereich und unter `/demo` wählen. Skins dürfen Grafiken und die visuelle Darstellung anpassen; Seitenstruktur, Layout, Positionen der Bedienelemente und Verhalten bleiben von WebSpeak vorgegeben. Die Administrationskonsole bleibt ungestaltet.
|
||||
- Administratoren können eigene Skins aktivieren/deaktivieren und ein Standarddesign für die Instanz festlegen. Eine bewusst getroffene Besucherauswahl bleibt erhalten; ohne eigene Auswahl gilt der Instanzstandard. Tagesmodus, Nachtmodus und ILLUSIA sind geschützte integrierte Skins und können weder gelöscht noch deaktiviert oder ersetzt werden.
|
||||
- Das unfertige Aurora-Voice-Beispiel wurde entfernt; ILLUSIA ist nun das vollständige Referenzdesign. Startseitenkunst, Ebenenillustration und Kopfhörerszene im Sprachbereich, leerer Chat-Hintergrund und Bildschirmfreigabe-Player wurden verfeinert. Außerdem wurden dunkle Bedienelemente, Überläufe und Skin-Ladeblitze korrigiert.
|
||||
- Der offizielle Skin-Entwicklungs-Agent-Skill des Repositorys wurde ergänzt; Anleitung und lokalisierte Funktionsübersichten wurden aktualisiert. Die Besucher-Gesamtzahl fällt bei nicht verfügbarem Zähler nicht unter die aktuelle Besuchernummer.
|
||||
- Die ILLUSIA-Illustration bei Sprachaktivität wurde verkleinert und unten rechts verankert, damit sie weder Mitgliederkarten noch den Bildschirmfreigabe-Player verdeckt.
|
||||
|
||||
### Русский
|
||||
|
||||
- Добавлена визуальная система скинов `.wskin`: посетители могут выбирать оформление на главной странице, в голосовом пространстве и в `/demo`. Скины меняют иллюстрации и внешний вид компонентов, а структуру, компоновку, расположение элементов управления и поведение задаёт WebSpeak. Панель администратора не оформляется скинами.
|
||||
- Администраторы могут включать и отключать пользовательские скины и задавать оформление по умолчанию для экземпляра. Явный выбор посетителя сохраняется; без него используется настройка экземпляра. Дневная тема, ночная тема и ILLUSIA — защищённые встроенные скины, которые нельзя удалить, отключить или заменить.
|
||||
- Удалён незавершённый пример Aurora Voice; полной эталонной темой стала ILLUSIA. Улучшены иллюстрации главной страницы, многослойный персонаж и сцена с наушниками в голосовой комнате, фон пустого чата и проигрыватель трансляции экрана. Исправлены контраст элементов в тёмном режиме, переполнение и вспышки при загрузке скина.
|
||||
- В официальный репозиторий добавлен Agent Skill для разработки скинов, обновлены руководство и локализованные описания функций. При недоступности счётчика общее число посетителей не опускается ниже текущего номера посетителя.
|
||||
- Иллюстрация ILLUSIA при голосовой активности уменьшена и закреплена внизу справа, чтобы не перекрывать список участников и проигрыватель трансляции экрана.
|
||||
|
||||
### 日本語
|
||||
|
||||
- `.wskin` ビジュアルスキン機能を追加しました。ホーム、音声ワークスペース、`/demo` で外観を選択できます。背景や素材、コンポーネントの見た目を変更できますが、ページ構造、レイアウト、操作部品の位置と動作は WebSpeak が管理します。管理コンソールには適用されません。
|
||||
- 管理者はカスタムスキンの有効/無効と、インスタンスのデフォルトスキンを設定できます。訪問者が明示的に選んだスキンは維持され、未選択の場合はインスタンスのデフォルトを使用します。昼、夜、ILLUSIA の3種類は保護された内蔵スキンで、削除・無効化・置換できません。
|
||||
- 未完成の Aurora Voice サンプルを削除し、ILLUSIA を完成版のリファレンスにしました。ホームのアート、音声画面の重ね合わせ立ち絵とヘッドホン背景、空のチャット背景、画面共有プレーヤーを調整し、ダークモードの視認性、はみ出し、読み込み時のちらつきを修正しました。
|
||||
- 公式リポジトリにスキン開発 Agent Skill を追加し、ガイドと各言語の機能説明を更新しました。カウンターを取得できない場合も、訪問者総数が現在の訪問者番号を下回らないようにしました。
|
||||
- 音声アクティビティの ILLUSIA 立ち絵を縮小して右下に固定し、メンバー一覧や画面共有プレーヤーを隠さないようにしました。
|
||||
|
||||
## [0.2.4] — 2026-09-22
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增跨端 P2P 屏幕共享:浏览器用户可以与 TeamSpeak 6 原生客户端互相发现、发起和观看屏幕共享;浏览器之间以及浏览器与原生客户端之间的媒体流优先通过 WebRTC/ICE 直连,WebSpeak 仅负责会话鉴权、共享状态和 SDP/ICE 信令转发,不承载屏幕媒体流量。
|
||||
- 默认使用 TeamSpeak 官方 STUN 服务发现直连候选,并支持管理员显式配置外部 TURN;即使使用 TURN,媒体也经过外部服务而不是 WebSpeak 网关。
|
||||
- 新增屏幕共享直播状态、观众人数、播放器音量、全屏和退出控制,并提供发送端/接收端 WebRTC 实时统计。
|
||||
- 提供浏览器屏幕采集分辨率和帧率设置,最高支持 1080p、60 FPS;设置改为独立弹窗,避免成员卡片被撑高。
|
||||
- 新增首页访客编号,并优化屏幕共享成员卡片和观看交互。
|
||||
- 修正输出限制的应用方式:保持所选桌面或窗口的原始采集尺寸,由发送端编码器按设置缩放和限帧;首页同时显示当前访客序号和累计访客数。
|
||||
- 修复 TeamSpeak 握手期间服务器拒绝错误被误报为连接超时的问题;昵称长度不符合要求时会显示明确的修改提示。
|
||||
|
||||
### English
|
||||
|
||||
- Added cross-platform P2P screen sharing: browser users can discover, start, and watch screen shares with native TeamSpeak 6 clients. Media between browsers, and between a browser and a native client, prefers a direct WebRTC/ICE path; WebSpeak handles session authorization, share state, and SDP/ICE signaling only and does not carry screen media.
|
||||
- Added TeamSpeak's public STUN services for direct-candidate discovery by default, with optional administrator-configured external TURN. Even with TURN, media uses the external service rather than the WebSpeak gateway.
|
||||
- Added live screen-share status, viewer counts, player volume, fullscreen, and exit controls, plus live sender/receiver WebRTC statistics.
|
||||
- Added browser capture-resolution and frame-rate controls up to 1080p and 60 FPS; moved the controls into a standalone modal so member cards no longer stretch.
|
||||
- Added homepage visitor numbering and refined screen-share member-card and viewing interactions.
|
||||
- Fixed output-limit handling so the selected desktop or window keeps its native capture size while the sender encoder applies the requested scale and frame-rate cap; the homepage now also shows the total visitor count.
|
||||
- Fixed handshake refusals being reported as connection timeouts; invalid nickname lengths now show a clear prompt to change the nickname.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Plattformübergreifendes P2P-Bildschirmteilen ergänzt: Browsernutzer können Bildschirmfreigaben mit nativen TeamSpeak-6-Clients erkennen, starten und ansehen. Die Medienübertragung zwischen Browsern sowie zwischen Browser und nativem Client nutzt möglichst direkte WebRTC-/ICE-Verbindungen; WebSpeak übernimmt nur Sitzungsberechtigung, Freigabestatus und SDP-/ICE-Signalisierung und transportiert keine Bildschirmmedien.
|
||||
- Öffentliche TeamSpeak-STUN-Dienste werden standardmäßig zur Ermittlung direkter Kandidaten verwendet; ein externes TURN kann ausdrücklich durch den Administrator konfiguriert werden. Auch mit TURN läuft die Medienübertragung über den externen Dienst und nicht über das WebSpeak-Gateway.
|
||||
- Live-Status, Zuschauerzahl, Lautstärke, Vollbild- und Beenden-Steuerung für Bildschirmfreigaben sowie laufende WebRTC-Statistiken für Sender und Empfänger ergänzt.
|
||||
- Aufnahmeauflösung und Bildrate im Browser bis 1080p und 60 FPS konfigurierbar; die Einstellungen wurden in ein eigenes Modal verschoben, damit Mitgliederkarten nicht mehr in die Höhe wachsen.
|
||||
- Besucherzählung auf der Startseite ergänzt und die Interaktion von Bildschirmfreigabe-Karten und Player verbessert.
|
||||
- Die Ausgabelimits werden nun am Sender-Encoder angewendet, während die native Aufnahmegröße des ausgewählten Desktops oder Fensters erhalten bleibt; auf der Startseite wird zusätzlich die Gesamtzahl der Besucher angezeigt.
|
||||
- Behoben, dass Ablehnungen während des TeamSpeak-Handshakes als Zeitüberschreitung angezeigt wurden; bei ungültiger Nicknamenslänge erscheint nun ein klarer Änderungshinweis.
|
||||
|
||||
### Русский
|
||||
|
||||
- Добавлена кроссплатформенная P2P-трансляция экрана: пользователи браузера могут обнаруживать, запускать и смотреть трансляции вместе с нативными клиентами TeamSpeak 6. Медиа между браузерами, а также между браузером и нативным клиентом по возможности передаётся напрямую через WebRTC/ICE; WebSpeak отвечает только за авторизацию сессии, состояние трансляции и SDP/ICE-сигналы и не переносит медиаданные экрана.
|
||||
- По умолчанию добавлено обнаружение прямых кандидатов через публичные STUN-сервисы TeamSpeak; администратор может явно настроить внешний TURN. Даже при использовании TURN медиа идёт через внешний сервис, а не через шлюз WebSpeak.
|
||||
- Добавлены статус трансляции, число зрителей, громкость проигрывателя, полноэкранный режим и выход, а также текущая статистика WebRTC для отправителя и получателя.
|
||||
- Добавлены настройки разрешения и частоты кадров захвата в браузере до 1080p и 60 FPS; настройки вынесены в отдельное окно, чтобы карточки участников не растягивались.
|
||||
- Добавлен номер посетителя на главной странице и улучшено управление карточками и просмотром трансляций.
|
||||
- Исправлено применение ограничений вывода: выбранный рабочий стол или окно сохраняет исходный размер захвата, а запрошенное масштабирование и ограничение частоты кадров применяются кодировщиком отправителя; на главной странице также показывается общее число посетителей.
|
||||
- Исправлено ошибочное отображение отказов TeamSpeak во время рукопожатия как тайм-аута; при недопустимой длине имени показывается понятная просьба изменить его.
|
||||
|
||||
### 日本語
|
||||
|
||||
- クロスプラットフォーム P2P 画面共有を追加しました。ブラウザユーザーは TeamSpeak 6 ネイティブクライアントと互いに画面共有を検出・開始・視聴できます。ブラウザ間、およびブラウザとネイティブクライアント間のメディアは可能な限り WebRTC/ICE で直接送信され、WebSpeak はセッション認証、共有状態、SDP/ICE シグナリングだけを担当し、画面メディアは運びません。
|
||||
- 初期設定で TeamSpeak 公開 STUN サービスによる直接候補の検出に対応し、管理者が外部 TURN を明示的に設定できるようにしました。TURN 使用時もメディアは外部サービスを経由し、WebSpeak ゲートウェイは経由しません。
|
||||
- 配信状態、視聴者数、プレーヤー音量、全画面、終了操作と、送信側・受信側の WebRTC 統計を追加しました。
|
||||
- ブラウザの画面取得設定で最大 1080p / 60 FPS を選択できます。設定を独立したモーダルに移し、メンバーカードが縦に伸びないようにしました。
|
||||
- ホームページの訪問者番号を追加し、画面共有カードと視聴操作を改善しました。
|
||||
- 出力制限を送信側エンコーダーで適用するよう修正し、選択したデスクトップやウィンドウの元の取得サイズを維持します。ホームページには訪問者番号に加えて累計訪問者数も表示します。
|
||||
- TeamSpeak の接続ハンドシェイク中の拒否がタイムアウトとして表示される問題を修正しました。ニックネームの長さが不適切な場合は、変更を促すメッセージを表示します。
|
||||
|
||||
## [0.2.3] — 2026-09-19
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增频道成员调度入口:保留拖放移动,并在右键菜单提供“调度到”二级菜单和“我所在的频道”快捷项。
|
||||
- 支持按 TeamSpeak 权限直接移动成员;具备权限时无需重复输入频道密码,无权限时不提供该操作。
|
||||
- 支持成员头像显示、麦克风静音状态同步和保存身份恢复,并增强指针拖动兼容性。
|
||||
- 更新中文、English、Deutsch、Русский、日本語五种语言的功能截图和文档页面。
|
||||
- 修复高分辨率桌面端管理员设置页面底部内容被裁切的问题,并收紧中继卡片的宽度约束。
|
||||
|
||||
### English
|
||||
|
||||
- Added member-management entry points: drag-and-drop remains available, while the context menu now provides a “Move to” submenu with a “My channel” shortcut.
|
||||
- Added permission-aware direct member moves: authorized users can move clients without redundant channel-password prompts, while the action is unavailable without the required TeamSpeak permission.
|
||||
- Added client-avatar display, microphone mute-state synchronization, and remembered-identity recovery, with improved pointer-drag compatibility.
|
||||
- Refreshed feature screenshots and documentation pages for all five supported languages.
|
||||
- Fixed clipped lower content in the high-resolution desktop admin settings page and tightened relay-card width constraints.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Neue Einstiege für die Mitgliederverwaltung: Ziehen und Ablegen bleibt verfügbar, zusätzlich bietet das Kontextmenü ein Untermenü „Verschieben nach“ mit dem Eintrag „Mein Kanal“.
|
||||
- Direkte, berechtigungsabhängige Mitgliederverschiebung ergänzt: Benutzer mit den erforderlichen TeamSpeak-Rechten benötigen keine erneute Kanalpasswortabfrage; ohne diese Rechte steht die Aktion nicht zur Verfügung.
|
||||
- Anzeige von Client-Avataren, Synchronisierung des Mikrofon-Stummschaltstatus und Wiederherstellung gespeicherter Identitäten ergänzt; Zeigerbedienung verbessert.
|
||||
- Funktionsscreenshots und Dokumentationsseiten für alle fünf unterstützten Sprachen aktualisiert.
|
||||
- Das Abschneiden unterer Inhalte in den Admin-Einstellungen bei hoher Desktop-Auflösung behoben und die Breitenbegrenzung der Relay-Karten verbessert.
|
||||
|
||||
### Русский
|
||||
|
||||
- Добавлены способы управления участниками: перетаскивание сохранено, а в контекстном меню появился пункт «Переместить в» с быстрым вариантом «Мой канал».
|
||||
- Добавлено прямое перемещение с учётом прав TeamSpeak: пользователям с нужными правами не нужно повторно вводить пароль канала, а без этих прав действие недоступно.
|
||||
- Добавлены отображение аватаров клиентов, синхронизация состояния микрофона и восстановление сохранённой идентичности; улучшено перетаскивание указателем.
|
||||
- Обновлены функциональные скриншоты и страницы документации для всех пяти поддерживаемых языков.
|
||||
- Исправлено обрезание нижнего содержимого настроек администратора на десктопах с высоким разрешением и ограничена ширина карточек ретрансляторов.
|
||||
|
||||
### 日本語
|
||||
|
||||
- メンバー操作を追加しました。ドラッグ&ドロップに加えて、コンテキストメニューに「移動先」サブメニューと「自分のチャンネル」ショートカットを用意しました。
|
||||
- TeamSpeak 権限に応じた直接移動を追加しました。必要な権限があればチャンネルパスワードを再入力せずに移動でき、権限がなければ操作は表示されません。
|
||||
- クライアントアバターの表示、マイクミュート状態の同期、保存した ID の復元に対応し、ポインター操作も改善しました。
|
||||
- 対応する 5 言語すべての機能スクリーンショットとドキュメントページを更新しました。
|
||||
- 高解像度デスクトップで管理設定の下部が切れる問題を修正し、中継カードの幅制約を改善しました。
|
||||
|
||||
## [0.2.2] — 2026-09-17
|
||||
|
||||
### 中文
|
||||
|
||||
@@ -1,90 +1,210 @@
|
||||
# WebSpeak — TeamSpeak Browser Gateway
|
||||
# WebSpeak TeamSpeak Browser Gateway
|
||||
|
||||
Server-side bridge that lets users join TeamSpeak voice channels from a browser. No TS client install needed.
|
||||
WebSpeak connects browser users to TeamSpeak 3 and TeamSpeak 6 through a self-hosted Node.js gateway. Each connected browser session owns an independent TeamSpeak client. The repository also contains a standalone UDP acceleration relay and an Android preview with an embedded local gateway.
|
||||
|
||||
## Architecture
|
||||
## Application boundaries
|
||||
|
||||
```
|
||||
Browser (PCM capture) → WebSocket → Node.js server (PCM→Opus) → TeamSpeak server
|
||||
Browser (playback) ← WebSocket ← Node.js server (Opus relay) ← TeamSpeak server
|
||||
| Location | Responsibility |
|
||||
| --- | --- |
|
||||
| `src/index.ts` | Gateway startup, SQLite, master secret, admin service and shutdown; also supports relay mode |
|
||||
| `src/server/server.ts` | HTTP or HTTPS, public configuration, skins, join tickets, admin routes and static frontend |
|
||||
| `src/server/voice-bridge.ts` | `/ws/voice`, admission, connection/reconnection orchestration and voice transport assembly |
|
||||
| `src/server/voice-commands.ts`, `directory-view.ts`, `audio-stats.ts` | Command execution, public directory projection and diagnostic snapshots |
|
||||
| `src/server/member-avatars.ts` | Generation-bound optional avatar downloads, bounded sequential batches, cached images and timer cleanup |
|
||||
| `src/server/session-events.ts` | Session-owned SDK subscriptions, directory projection, self/channel state, chat mapping and avatar coordination |
|
||||
| `src/server/screen-share-coordinator.ts` | Server/channel-scoped sharing membership and browser/native signaling |
|
||||
| `src/shared/` | Browser-safe wire types and runtime parsers shared by both endpoints |
|
||||
| `src/shared/admin-inputs.ts`, `admin-responses.ts` | Shared admin request types and runtime-checked response projections |
|
||||
| `src/server/ts-client.ts` and `teamspeak-adapter.ts` | SDK integration, TS3/TS6 negotiation, identity, chat, voice and client events |
|
||||
| `src/server/session-manager.ts` and `directory-sync.ts` | Connection state, teardown, admission limits and directory reconciliation |
|
||||
| `src/server/webrtc-audio.ts` and `opus-codec.ts` | WebRTC audio mixing and platform-specific Opus codecs |
|
||||
| `src/server/session-audio.ts` | Per-session PCM encoding, exclusive WebRTC/WebSocket routing, whisper dispatch, bounded egress and audio counters |
|
||||
| `src/admin/`, `src/security/`, `src/persistence/` | Administration, access policies, credentials and persistent settings |
|
||||
| `src/relay.ts` and `src/server/acceleration-relay.ts` | Standalone relay and gateway-side relay transport |
|
||||
| `web/src/views/` and `web/src/composables/` | Vue pages, connection state, audio controls, chat and screen sharing |
|
||||
| `web/src/voice/screen-share.ts` | Per-session screen capture, peer negotiation, cleanup and diagnostics |
|
||||
| `web/src/voice/remote-playback.ts` | Per-speaker compatibility decoding, bounded scheduling, volume and resource cleanup |
|
||||
| `web/src/voice/microphone-test.ts` | Cancellable recording tests, recorder deadline and playback URL ownership |
|
||||
| `web/src/voice/microphone-capture.ts` | Prepared microphone processing graphs, per-context worklet loading, optional RNNoise and independent PCM activation/cleanup |
|
||||
| `web/src/voice/audio-sink.ts` | Serialized device routing per audio endpoint, with stale-operation guards |
|
||||
| `web/src/voice/accompaniment.ts` | Generation-bound display-audio capture, immediate pending-capture cancellation, ended listeners and committed activity |
|
||||
| `web/src/voice/webrtc-input.ts` | Stable WebRTC sender output, microphone gain and transactional accompaniment-source attachment |
|
||||
| `web/src/voice/microphone-meter.ts` | Optional per-peer level sampling, owned analysis nodes and timer, partial-failure cleanup and stale-tick rejection |
|
||||
| `web/src/voice/webrtc-transport.ts`, `webrtc-playback.ts` | Per-attempt peer negotiation, input/meter ownership, compatibility fallback and independently owned playback elements and retries |
|
||||
| `web/src/voice/connection.ts`, `commands.ts` | Cancellable ticket acquisition, socket and connection generations, plus per-command acknowledgement deadlines and cleanup |
|
||||
| `web/src/voice/session-state.ts` | Reactive directory, chat history, events and notifications; complete versus omitted directory data, session resets and private-conversation identity scopes |
|
||||
| `web/src/composables/useWebClientChat.ts`, `useWebClientChannels.ts` | Destination-owned drafts and pending sends, identity-bound private history, and iterative channel-tree projection |
|
||||
| `web/src/composables/useWebClientIdentity.ts`, `web/src/components/web-client/IdentityImportDialog.vue` | Page-owned identity reads, parsing, restoration and exports; a presentation dialog with explicit input and action events |
|
||||
| `web/src/voice/audio-diagnostics.ts`, `web/src/composables/useWebClientPerformance.ts` | Session-owned diagnostic probes and compatibility counters, browser statistics, comparable sample scopes and cancellable UI polling |
|
||||
| `web/src/platform/` | Browser mounting and cancellable Android gateway readiness handshake |
|
||||
| `web/src/services/`, `web/src/i18n/`, `web/src/skins/` | Browser persistence, identity import, skin packages and translations |
|
||||
| `web/src/composables/usePublicSkin.ts`, `web/src/services/skin-operation.ts` | Shared public-page skin initialization and selection, page ownership, cancellation and bounded loading |
|
||||
| `web/src/services/admin-api.ts`, `admin-requests.ts` | Admin HTTP validation and cancellation, session-bound CSRF and per-feature request ownership, including skin uploads and backup downloads |
|
||||
| `web/src/composables/useAdminServerSettings.ts`, `useAdminOperations.ts`, `useAdminSkins.ts` | Admin form merging, probes, operational actions and skin state; the page owns authentication, routing and overview |
|
||||
| `web/src/components/admin/` | Server settings, operations and skin presentation; the parent page retains the feature controller instances across subroute changes |
|
||||
| `web/src/composables/useAdminI18n.ts`, `web/src/i18n/admin.ts` | Admin formatting and error/status mappings; all five languages explicitly implement the same translation keys |
|
||||
| `src/mobile/`, `mobile/`, `web/android/` | Android loopback gateway, asset packaging and Capacitor container |
|
||||
|
||||
## Connection and control protocol
|
||||
|
||||
1. The browser requests `/api/join-ticket`. The gateway validates the request against its access policy and issues a short-lived, single-use ticket.
|
||||
2. The browser presents the ticket to `/ws/voice`. The bridge admits a session, acquires any required identity lease and creates its TeamSpeak client.
|
||||
3. WebSocket text messages carry JSON commands, events, WebRTC negotiation and screen-sharing signaling. The server uses the WebSocket `isBinary` flag to distinguish audio from control messages.
|
||||
4. Register TeamSpeak event listeners before connecting: directory and membership events may arrive during the handshake.
|
||||
|
||||
Channel and member data come from SDK directory snapshots and client-protocol commands, followed by realtime notifications. WebQuery and its API key are not required. `DirectorySynchronizer` reconciles snapshots with membership events.
|
||||
|
||||
`SessionEventCoordinator` subscribes before SDK connection and closes before waiting for peer shutdown. Remove only its own listeners and guard captured callbacks as well as registered ones. Directory events are accepted during authentication, synchronization and the live connection, but not reconnect backoff. SDK adapter listeners must reject events from a replaced client before mutating state or forwarding them. A kick remains terminal if the disconnect notification already started recovery.
|
||||
|
||||
Avatar downloads belong to the connected directory generation. Reset them on SDK interruption and close them before awaiting session teardown. Old success or failure results cannot refill caches, publish images, start another download, or unlock newer work. `isAlive` is only the WebSocket heartbeat acknowledgement flag; it is not a lifecycle predicate. Keep avatar failure optional, the 50-member batch limit and 250 ms continuation delay.
|
||||
|
||||
The SDK avatar method captures its client and connection generation across metadata, transfer initialization and download. Recheck both after each await, including reconnects that reuse the same SDK object; never continue an old transfer through a replacement `this.client`. A retired SDK client's disconnect event must not clear the current connection.
|
||||
|
||||
Session teardown must remain safe when requested more than once or when sockets and codec resources are already closed. Reconnection is governed by `reconnect-policy.ts`; preserve terminal error handling, bounded retries and the previous-channel fallback.
|
||||
|
||||
Invalidate session audio before awaiting peer closure. Each codec and track must be released independently so one disposal failure cannot abandon the remaining resources. WebRTC close callers share one completion promise, including a peer-close rejection. Preserve WebSocketServer's close listener: it owns removal from the server's client set and allows shutdown to finish.
|
||||
|
||||
Late socket messages and media permission/negotiation results must not mutate a replacement session. Screen-sharing ownership is scoped to both the TeamSpeak target and channel; another member moving channels must not stop the current user's share. Preserve these invariants when extracting the remaining audio responsibilities.
|
||||
|
||||
WebRTC offers, answers, playback callbacks and accompaniment capture belong to the session and peer that started them. Invalidate pending negotiation on stop, reconnect or teardown before awaiting resource closure. A stale peer must not publish errors, counters or audio into its successor. Negotiation and track setup failures must restore compatibility capture without misreporting a microphone failure.
|
||||
|
||||
The WebRTC transport owns its peer, input mixer, meter, ICE wait and answer deadline. The capture layer retains ownership of the original microphone and PCM graph; releasing input during microphone preparation must not invalidate the preparing transport. Failed stop signaling cannot prevent local cleanup or compatibility fallback. A fallback permission failure must still belong to the connection and transport generation that initiated it.
|
||||
|
||||
Each remote WebRTC audio element owns its in-flight play attempt and retry listeners. Coalesce overlapping gestures, guard captured callbacks against replacement and release partial element setup. Pause, listener removal, source clearing or peer closure failures must not interrupt release of other resources.
|
||||
|
||||
Ticket acquisition has a 15-second browser deadline covering preference readiness, fetch and response-body reading. Disconnect and replacement abort the owning request immediately; stale success, rejection and deadline callbacks cannot open a socket or update a newer connection. This is separate from the gateway's TeamSpeak handshake policy. Browser cancellation does not undo a server-side invite consumption or ticket issuance. Preserve the gateway close code over generic WebSocket errors, detach retired handlers, and tolerate socket-close failures.
|
||||
|
||||
Every acknowledged command owns its original socket, connection generation and deadline. Success, server rejection, synchronous send failure, timeout and disconnect all use one idempotent completion path; release the registration and timer immediately. Fire-and-forget commands keep the existing shared wire contract.
|
||||
|
||||
Chat sends require a connected TeamSpeak session and append local history only after acknowledgement. A queued acknowledgement cannot append after session resource release. Recovery rejections retain the command request ID. Optional channelId and clientUid command fields let the gateway verify the actual channel and recipient before invoking the SDK; legacy payloads remain accepted without those additional guards. Confirmation is not a read receipt, and a timeout does not prove non-delivery.
|
||||
|
||||
Directory, chat, events and poke lists retain their reactive array identities. Complete channel snapshots replace the member directory, while omitted members remain unknown rather than empty. Channel projections share canonical members. Departure and UID replacement release the old member's playback, speaking state, temporary volume and whisper selection; persisted UID-based preferences remain. A recovered TeamSpeak connection replaces its directory even when the connected message omits members.
|
||||
|
||||
Explicit disconnect, target replacement and ordinary socket closure reset message state and advance the page's session epoch. Same-socket recovery may preserve chat history, but cannot send until connected; recovered directories and events replace old snapshots and clear old pokes. Failed recovery may retain its history for the failure panel until retry or exit.
|
||||
|
||||
Private history uses UID scopes when available and member-lifetime scopes for legacy clients without UIDs. Unknown senders must not become later members merely because a numeric ID matches. Preserve the recipient name in outgoing history. Drafts, pending submissions and errors belong to a destination within a session; switching tabs cannot duplicate an in-flight send. Confirmation clears only the unchanged submitted draft, including when its tab is inactive. Reset or disposal retires late feedback.
|
||||
|
||||
Channel projection uses iterative parent and sibling traversal, emits each ID at most once, keeps the first duplicate, promotes missing-parent channels to roots and starts isolated cycles at their first source entry. Do not reintroduce recursive traversal or silently discard the entire directory on a malformed topology.
|
||||
|
||||
Audio diagnostic probes retain their cancellation entry and deadline until both gateway and browser statistics finish. Bind the result to the original socket, connection generation and peer; disconnect settles pending consumers immediately, and a late browser getStats result cannot mix with a replacement peer. A probe send failure returns no sample.
|
||||
|
||||
Diagnostic samples also include the WebRTC transport generation, so a probe cannot survive a failed attempt that starts and ends without a peer. A browser-local scope ID changes with the source and session resets; compatibility counters reset at session teardown and snapshots stay independent. The scope ID is internal metadata, not part of the gateway protocol. Keep the exported diagnostic types available from the voice composable for existing callers.
|
||||
|
||||
The performance panel only subtracts counters from matching scopes, transports and downlink sources (PCM, RTP or gateway frames). Null or rejected probes clear stale activity and restart the baseline. Check the polling generation before starting work as well as after awaiting results; unmount retires callbacks and manual refresh. Preserve the 2-second polling interval. For loss estimates, packetsSent already includes all sent packets, while packetsReceived requires adding lost packets to form the denominator; keep percentages bounded and treat RTCP/local snapshots as estimates.
|
||||
|
||||
Accompaniment changes keep the WebRTC sender output alive. Prepare and connect the new source before replacing the old one; a failure preserves the current microphone and accompaniment. The input mixer owns its nodes and output track, never the externally owned capture streams. Release partial allocations and continue cleanup if an individual node fails. Application audio bypasses microphone gain/denoising and retains its source level.
|
||||
|
||||
The accompaniment controller owns both active and pending captures. Stop, disconnect and replacement immediately release candidates already returned by the browser, even while optional constraints are pending. Late permissions are stopped on arrival; ended or stale candidates cannot be published. Register ended listeners during preparation and publish activity only after attachment succeeds. Optional content hints and processing constraints may fail without losing capture; distinguish audio attachment errors from permission errors in all five languages.
|
||||
|
||||
Microphone metering is optional and must not interrupt voice. Its nodes and timer belong to one meter instance; a queued old tick cannot read the next session's analyser or publish a level. Allocation, connection and read failures release all meter resources and clear level/speaking presentation, while preserving the capture stream and peer. Keep the 512-sample analyser and 50 ms cadence unless audio validation justifies changing them.
|
||||
|
||||
## Audio and screen sharing
|
||||
|
||||
The compatibility voice path captures 48 kHz mono PCM using an AudioWorklet, with a ScriptProcessor fallback. The browser assembles 960-sample, 20 ms frames and sends 1,920-byte Int16 payloads over WebSocket. The gateway encodes them as Opus for TeamSpeak. Incoming Opus uses a three-byte header containing codec and client ID, then browser WebCodecs decoding and playback.
|
||||
|
||||
When enabled by the administrator, WebRTC provides a separate voice transport between the browser and gateway. The gateway uses `werift` and mixes incoming TeamSpeak speakers for WebRTC playback. Negotiation failures can fall back to the compatibility path. Keep microphone mute, per-member volume and playback behavior consistent across both transports.
|
||||
|
||||
Screen sharing has its own peer connections. The gateway coordinates stream membership and SDP/ICE signaling between browsers and supported TeamSpeak 6 clients. Screen media travels directly or through an externally configured TURN server; the WebSpeak gateway does not carry screen media.
|
||||
|
||||
Preserve bounded audio buffering and stale-playback recovery. Audio counters stay in memory and are exposed in session diagnostics. Do not add per-frame persistent logging to the voice path.
|
||||
|
||||
Remote playback owns each speaker's decoder, gain and source nodes as one resource set. Member departure, decoder failure and session teardown release that set; queued callbacks must not touch its replacement. Preserve the 80 ms playback window and three-frame decoder queue threshold unless audio validation justifies changing them.
|
||||
|
||||
Microphone recording tests own their recorder, timeout and object URL, while the capture layer owns the microphone stream. A normal stop may publish its final recording; replacement and session teardown discard late results and revoke the old URL. Stopping a test while connected must preserve room capture. Test cancellation and stale permission failures must not change a newer test's state.
|
||||
|
||||
Device and noise-suppression changes share one configuration operation. Persist only the last successful settings; stale failures cannot roll back a newer choice. Acquiring a replacement microphone must preserve the current WebRTC peer and compatibility PCM capture until the replacement is ready. Capture callbacks are invalidated when their graph stops, separately from permission-request generations. Closing settings also releases standalone device-preview capture when no recording was started.
|
||||
|
||||
Prepare microphone nodes and streams before replacing the live graph. A failed allocation or delayed worklet load must leave the old capture usable. Aborting preparation releases its candidate resources immediately; only activation enables PCM callbacks. Worklet module caches belong to their AudioContext. Device removal uses the normal input/output configuration transactions, including WebRTC restart and rollback on failed default-device selection. A committed graph becomes the fallback preference before subsequent device enumeration completes.
|
||||
|
||||
Serialize `setSinkId` on each audio context or media element, since an in-flight browser sink change cannot be cancelled. Bind subsequent work to the original endpoint and current operation; session teardown invalidates queued changes and device enumeration results. If one output endpoint rejects after another changed, attempt to restore the last committed output.
|
||||
|
||||
`src/server/opus-codec.ts` loads the native `@discordjs/opus` implementation for server deployments and `opusscript` for the Android bundle. Dispose codec and media resources at the end of their owning session.
|
||||
|
||||
## Configuration and persistence
|
||||
|
||||
Identity file reads belong to the current selection, text revision and dialog lifetime. New files (including invalid selections), manual edits, closing, entering the room, clearing local data and page disposal retire old results. Parsing owns its submitted draft; only a current result may replace the identity or notify. Preserve the 128 KiB limit, UTF-8/UTF-16 BOM decoding and existing busy-close behavior. The dialog disables submission while a selected file is being read and disables edits while parsing.
|
||||
|
||||
Startup identity restoration must not overwrite a newer import or remember preference. Exports belong to the identity and page that started them; coalesce pending clicks, discard late serialization and release download anchors, URLs and timers independently. Keep codec parsing in the existing identity service and persistence in the page/storage layer.
|
||||
|
||||
Admin requests belong to the login session and feature that started them. Invalidate pending work on authentication changes and page disposal; cancel feature work on management subroute exit. A late 401 must not expire a newer session, and late login or backup results must not navigate or download after disposal. Aborted work is not a user-facing failure. Failed logout preserves the authenticated draft; successful logout or session expiry resets private page state.
|
||||
|
||||
Settings responses merge against the submitted snapshot instead of replacing newer edits. Password and action, and relay token and action, are atomic draft groups. Clear acknowledged secret inputs, retain edits made during the request, merge relay nodes by ID, and do not restore obsolete probe metadata. Serialize skin mutations and prevent duplicate invite actions; cancelling browser work does not undo a server mutation already executed.
|
||||
|
||||
| Source | Purpose |
|
||||
| --- | --- |
|
||||
| SQLite `webspeak.db` | Admin credentials, target and access settings, relay nodes, invitations, audit records and visitor metadata |
|
||||
| `master.key` beside the database | Encryption key for persisted secrets; retain it with database backups |
|
||||
| `/admin` | Normal configuration and operational controls |
|
||||
| Legacy `config.json` | One-time import of `tsHost`, `tsPort` and `tsServerPassword`; later changes do not replace database settings |
|
||||
| `WEBSPEAK_DATA_DIR` | Persistent data directory; defaults to project `data/`, while Docker uses `/data` |
|
||||
| `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` | Screen-sharing ICE configuration read at startup |
|
||||
| Relay environment variables | Standalone relay mode; public gateway relay choices come from saved admin settings |
|
||||
| Browser IndexedDB and localStorage | Local identities, preferences, server history and skin state |
|
||||
|
||||
The current SQLite schema version is defined in `src/persistence/database.ts`. Keep schema migrations separate from structural refactors. Legacy fields such as `voiceToken`, `tsApiKey`, `tsQueryPort`, `port` and `maxClients` do not configure the current gateway.
|
||||
|
||||
The gateway HTTP port is `3040`. Its admission ceiling is `100` sessions, defined in `src/constants.ts`; this is an application limit, not a TeamSpeak license allowance or a measured performance guarantee. Target server capacity and permissions still apply.
|
||||
|
||||
The server uses HTTPS when `certs/cert.pem` and `certs/key.pem` are supplied; otherwise it starts HTTP. It does not generate certificates. Use an appropriate secure browser origin for microphone and screen capture, typically HTTPS in public deployments. Feature support depends on the browser and selected transport; do not infer a universal minimum browser version from WebCodecs alone.
|
||||
|
||||
## Development and verification
|
||||
|
||||
Server deployments require Node.js 22.5 or newer. CI uses Node.js 22.22.2. Root and frontend dependencies are installed separately. The pinned Git SDK and native Opus module require the preparation steps used by CI:
|
||||
|
||||
```sh
|
||||
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
|
||||
npm run verify
|
||||
```
|
||||
|
||||
- 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
|
||||
- Channel/member list fetched via TS6 WebQuery HTTP API (port 10080, requires API key)
|
||||
- WebSocket text frames = JSON commands, binary frames = PCM audio / Opus relay
|
||||
`npm run verify` runs unit tests, the backend build and `npm run web:build`. The latter delegates to the frontend build, including `vue-tsc --noEmit`. Use `npm run dev` and `npm run web:dev` for development, or `npm start` after building both applications.
|
||||
|
||||
## Project Structure
|
||||
Headless Vue tests use Vite middleware mode with both HMR and the WebSocket listener disabled (`hmr: false`, `ws: false`). Disabling HMR alone still reserves Vite's default socket port and causes parallel test processes to conflict.
|
||||
|
||||
```
|
||||
web/ # Vue 3 + Vite frontend (SPA)
|
||||
src/composables/useVoiceWebSocket.ts # Mic capture, VOX/PTT, playback, WS client
|
||||
src/views/WebClient.vue # Connect form + channel/member tree
|
||||
src/
|
||||
index.ts # Entry point, config loading, server startup
|
||||
config.ts # AppConfig interface + load/save
|
||||
logger.ts # Pino wrapper
|
||||
server/
|
||||
server.ts # Express + HTTPS + WS setup
|
||||
voice-bridge.ts # /ws/voice endpoint, PCM→Opus encoding, WebQuery API
|
||||
ts-client.ts # TS3Client wrapper around @echosixhiya/teamspeak-client
|
||||
```
|
||||
CI verifies pushes to `dev` and `master`, pull requests and manual runs. Docker publication on `master` or release tags, and release packaging on tags or manual runs, call the same verification workflow before publishing or packaging. Verification includes the application checks and a Docker HTTP health smoke test; that smoke test does not prove voice or screen-sharing functionality.
|
||||
|
||||
## Key Technical Details
|
||||
Tests requiring a real TeamSpeak server, browser media devices or Android hardware must document their environment and outcome separately. Never substitute a mock codec or an HTTP health response for a successful audio test.
|
||||
|
||||
### Audio Pipeline
|
||||
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 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.
|
||||
## Android preview
|
||||
|
||||
Audio flow counters are kept in memory and exposed in admin session summaries. Do not add per-frame persistent logging to the voice path.
|
||||
The Android app starts an embedded Node.js gateway on `127.0.0.1:3040` and opens it in the WebView. This preview disables gateway WebRTC voice and the admin console, while reusing the compatibility voice path. Its dependencies and runtime differ from server deployments.
|
||||
|
||||
### CJS Interop
|
||||
`@discordjs/opus` is CommonJS, loaded via:
|
||||
```ts
|
||||
import { createRequire } from "node:module";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { OpusEncoder } = require("@discordjs/opus");
|
||||
```
|
||||
See `mobile/README.md` for build steps and recorded limitations. The embedded Node.js version, SDK compatibility, real-device connections, background audio and native screen sharing require their own validation. Do not present these capabilities as production-ready based on desktop tests.
|
||||
|
||||
### WebSocket Message Routing
|
||||
- Text frames → JSON commands (`listChannels`, `switchChannel`)
|
||||
- Binary frames → PCM audio (browser→server) or Opus frames (server→browser)
|
||||
- JSON detection: `typeof data === "string"` first, then fallback `data[0] === 0x7b` with try/catch
|
||||
Platform startup owns its message listener, polling interval and deadline, including slow listener registration. Release them on success, failure, timeout and page exit. The retry button repeats the readiness handshake; it does not restart the embedded Node.js runtime.
|
||||
|
||||
### Event Handlers
|
||||
Must be registered BEFORE `tsClient.connect()` because `clientEnter`/`clientLeave` fire during handshake.
|
||||
## Repository maintenance
|
||||
|
||||
### Channel List
|
||||
Uses TS6 WebQuery HTTP API (`http://tsHost:tsQueryPort/1/channellist`) with `x-api-key` header. Falls back empty if `tsApiKey` not configured. Regular TS3 voice clients lack permission for `listChannels`/`listClients`.
|
||||
Routes load their page modules on demand. Document-level page styles must be gated by `html[data-ws-route]` because loaded CSS remains after navigation. The admin stylesheet is independent of public skins. Component extraction must retain `data-ws-part` hooks and account for Vue scoped styles across component boundaries.
|
||||
|
||||
### Config (config.json)
|
||||
```json
|
||||
{
|
||||
"port": 3040, "tsHost": "127.0.0.1", "tsPort": 9987,
|
||||
"tsQueryPort": 10080, "tsServerProtocol": "ts6",
|
||||
"tsApiKey": "", "voiceToken": "change-me", "maxClients": 10
|
||||
}
|
||||
```
|
||||
The identity dialog retains page-owned CSS with narrowly targeted `:deep` selectors so the existing declaration order and specificity remain intact. Shared button rules target its dedicated classes across the component boundary. Its close button is positioned within the modal. Public skin-contract tests include Vue files recursively under `components/web-client`; keep new public parts documented.
|
||||
|
||||
## Build & Deploy
|
||||
```bash
|
||||
npm install && cd web && npm install && npx vite build && cd .. && npx tsc
|
||||
node dist/index.js
|
||||
```
|
||||
The public join form uses explicit named field models and emits page actions. The chat panel receives a presentation subset of the single page-owned chat controller; keep its list ref bound to the rendered scroller so tab changes and new messages retain automatic scrolling. Form grid columns must allow shrinking, and narrow identity/relay controls must wrap without clipping translated text.
|
||||
|
||||
## Git
|
||||
- Remote: `https://github.com/EchoSixHIYA/web-client-for-TeamSpeak`
|
||||
- `webspeak-update.tar.gz` is in .gitignore (deployment artifact)
|
||||
- No secrets in source; config.json is gitignored
|
||||
The member panel and actions menu also share one page-owned member controller. The panel exposes an audio-dock slot; menu placement uses measured viewport bounds, converts through the page CSS zoom, and releases its resize observer/listener on unmount. Only desktop may open the move submenu on hover: mobile bottom-anchored menus change position when expanded and must open on click to avoid moving a member accidentally. Constrain short-window menus and allow scrolling.
|
||||
|
||||
## Known Limitations
|
||||
- Browser must be Chrome/Edge 94+ (WebCodecs AudioDecoder)
|
||||
- HTTPS required (self-signed cert OK, generated in `certs/`)
|
||||
- Max 32 concurrent users (TS3 license limit)
|
||||
- `tsApiKey` required for channel list; voice works without it
|
||||
Voice member cards receive the current channel projection, speaking/avatar helpers and a narrow sharing interface. Keep the sharing refs stable; member menus and stop-sharing actions return to the page through events. Empty, self, speaking, starting, sharing and viewing states must retain their skin hooks and mobile behavior.
|
||||
|
||||
Voice diagnostics and screen-sharing presentation also reuse page-owned controllers. Bind the player and video with explicit element callbacks. Rebind an existing stream when its video element changes, clear the previous element, and never stop the media owner's tracks during presentation cleanup. Fullscreen requires a non-null owned player; removing it exits only its own fullscreen. Known screen owner IDs take precedence over nickname fallback, including duplicate nicknames. Sharing settings use the common dialog focus handling.
|
||||
|
||||
The audio dock and whisper strip share the page-owned audio controller. Push-to-talk belongs to one primary pointer or one Space/Enter press; unrelated releases and key repeats must not change it. Failed pointer capture must not enable whispering. Clear ownership before releasing capture, and stop on blur, hidden controls/pages and disposal. The whisper component owns and releases its window/document listeners; keep media state in the voice layer.
|
||||
|
||||
Audio settings and password dialogs retain one page-owned media/connection state. Dialog focus supports initial focus, Tab cycling, Escape and return to the opener, with a connect-button fallback after pending connections disable that opener. Settings error feedback belongs to the current opening and latest request; closing synchronously stops recording tests, and scope disposal retires pending feedback and stops tests too. A non-password channel error must release the password dialog's pending state and preserve its draft for retry; reject duplicate submissions while pending.
|
||||
|
||||
Admin presentation components receive stable feature controllers; do not instantiate duplicate controllers in children. The welcome-language model remains page-owned and the skin file input belongs to its presentation component. Feature CSS crosses these boundaries with `:deep`, while shell and language-control selectors retain their existing scope. On narrow screens the brand and logout occupy the first row and all four navigation links share a separate row with at least 44 px high targets.
|
||||
|
||||
Keep each repair batch tied to its current plan item. Combine related fixes before running the full verification command; use focused checks during diagnosis and repeat the full suite only when subsequent changes or failures warrant it.
|
||||
|
||||
Keep template/CSS formatting separate from behavior changes. Preserve inline whitespace text nodes when wrapping Vue tags; compare compiled render output when needed. CSS formatting must retain selector meaning, values and declaration/rule order. Layout assertions should tolerate formatting whitespace while still checking the intended rules and values.
|
||||
|
||||
Public skin activation is last-choice-owned across both public pages. Retire previous runtime work before preparing a replacement, and reject results after page disposal, a newer choice or local-data reset. Check ownership before modifying document styles, selected content, asset URLs or stored preferences. An already aborted caller must not cancel a newer page's activation. Release compiled candidate URLs on failed installation.
|
||||
|
||||
Skin initialization has an 8-second total deadline covering preference reads, directory fetch and body, package loading and activation. Network stages also have bounded standalone operations. A timeout reveals a usable built-in palette and retires late work; retain the explicit skin choice for a later retry. Normal initialization still respects the enabled instance default unless the visitor made a deliberate choice. Home and demo use the same controller; do not restore duplicate unguarded refresh paths.
|
||||
|
||||
Skin cache writes and preference persistence accept the owning AbortSignal, including while waiting for IndexedDB to open and during its write transaction. Report storage success at transaction completion. Merge preferences within one transaction so concurrent unrelated settings are preserved. Cancellation of optional persistence must never block page use.
|
||||
|
||||
Validate admin responses before applying them to page state. Network and protocol failures must preserve unsaved input; a failed logout must not be presented as a successful logout. Keep secret keep/replace/remove actions intact and do not persist credentials in UI error messages or diagnostic logs.
|
||||
|
||||
The repository remote is `https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak`. Preserve existing local work when implementing the plan in `docs/CODE_REFACTOR_PLAN.zh-CN.md`. Keep private configuration, runtime data and local deployment archives out of source commits. Preserve documented skin hooks and browser persistence formats during component refactors.
|
||||
@@ -14,7 +14,7 @@ RUN npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
|
||||
RUN npm --prefix web ci
|
||||
|
||||
COPY . .
|
||||
RUN npm --prefix web run build \
|
||||
RUN npm run web:build \
|
||||
&& npm run build \
|
||||
&& npm prune --omit=dev \
|
||||
&& rm -rf web/node_modules
|
||||
@@ -35,11 +35,12 @@ COPY --from=build --chown=node:node /app/package.json /app/package-lock.json ./
|
||||
COPY --from=build --chown=node:node /app/node_modules ./node_modules
|
||||
COPY --from=build --chown=node:node /app/dist ./dist
|
||||
COPY --from=build --chown=node:node /app/web/dist ./web/dist
|
||||
COPY --from=build --chown=node:node /app/scripts/docker-healthcheck.mjs ./scripts/docker-healthcheck.mjs
|
||||
|
||||
USER node
|
||||
VOLUME ["/data"]
|
||||
EXPOSE 3040/tcp 39087/udp 40000-40099/udp
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
||||
CMD ["sh", "-c", "if [ \"$WEBSPEAK_MODE\" = \"relay\" ]; then node -e \"process.exit(0)\"; else node -e \"fetch('http://127.0.0.1:3040/health').then(r => { if (!r.ok) process.exit(1) }).catch(() => process.exit(1))\"; fi"]
|
||||
CMD ["node", "scripts/docker-healthcheck.mjs"]
|
||||
|
||||
CMD ["node", "dist/index.js"]
|
||||
@@ -1,7 +1,7 @@
|
||||
<div align="center">
|
||||
<a id="readme-top"></a>
|
||||
|
||||
<img src="./仓库图标.png" alt="WebSpeak 项目图标" width="180" />
|
||||
<img src="./image.png" alt="WebSpeak 项目横幅" width="100%" />
|
||||
|
||||
<h1>WebSpeak</h1>
|
||||
|
||||
@@ -36,15 +36,15 @@
|
||||
| **WHY** | 无需安装桌面客户端,用户打开网页即可加入频道;部署者仍然掌控目标服务器、访问策略和数据。 | Users can join a voice channel from a browser without installing a desktop client, while the operator keeps control of servers, access, and data. |
|
||||
| **HOW** | 部署后在管理员控制台配置 TeamSpeak 目标和访问方式,浏览器负责交互与音频,WebSpeak 负责网关连接。 | Configure the TeamSpeak target and access policy in the administration console. The browser handles interaction and audio; WebSpeak provides the gateway connection. |
|
||||
|
||||
## 文档语言 · Documentation
|
||||
|
||||
详细的特性、截图、高级功能、部署方案、要求和更新日志已按语言拆分:
|
||||
## 文档 · Documentation
|
||||
|
||||
- [简体中文](./docs/README.zh-CN.md)
|
||||
- [English](./docs/README.en.md)
|
||||
- [Deutsch](./docs/README.de.md)
|
||||
- [Русский](./docs/README.ru.md)
|
||||
- [日本語](./docs/README.ja.md)
|
||||
- [皮肤开发规范](./docs/SKIN_DEVELOPMENT.md)
|
||||
- [WebSpeak 皮肤开发 Agent Skill](./.agents/skills/webspeak-skin-development/SKILL.md)
|
||||
|
||||
## 社区 · Community
|
||||
|
||||
@@ -70,7 +70,13 @@
|
||||
A multi-platform music bot for TeamSpeak 3/6 with Netease Cloud Music, QQ Music, and Bilibili playback, plus a web console.<br />
|
||||
Ein plattformübergreifender Musikbot für TeamSpeak 3/6 mit Netease Cloud Music, QQ Music und Bilibili sowie Webkonsole.
|
||||
|
||||
## 许可证 · License · Lizenz
|
||||
## Contributors · 贡献者
|
||||
|
||||
感谢提交 PR 的贡献者:
|
||||
|
||||
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2):浏览器端报错翻译与提示改造。
|
||||
|
||||
## 许可证 · License · Lizenz · Лицензия · ライセンス
|
||||
|
||||
WebSpeak 使用 [GNU Affero General Public License v3.0 only](./LICENSE) 发布。你可以使用、研究、修改和再分发本项目;如果修改后的版本通过网络向用户提供服务,需要按照 AGPL-3.0 向这些用户提供对应源代码。
|
||||
|
||||
@@ -78,4 +84,14 @@ WebSpeak is released under the [GNU Affero General Public License v3.0 only](./L
|
||||
|
||||
WebSpeak wird unter der [GNU Affero General Public License v3.0 only](./LICENSE) veröffentlicht. Bei Bereitstellung einer veränderten Version über ein Netzwerk muss der entsprechende Quellcode unter AGPL-3.0 angeboten werden.
|
||||
|
||||
WebSpeak распространяется по лицензии [GNU Affero General Public License v3.0 only](./LICENSE). Если изменённая версия предоставляется пользователям через сеть, соответствующий исходный код должен быть доступен этим пользователям на условиях AGPL-3.0.
|
||||
|
||||
WebSpeak は [GNU Affero General Public License v3.0 only](./LICENSE) の下で公開されています。変更版をネットワーク経由でユーザーに提供する場合は、対応するソースコードを AGPL-3.0 に従ってユーザーに提供する必要があります。
|
||||
|
||||
## Star History
|
||||
|
||||
<a href="https://star-history.com/#EchoSixHIYA/WebSpeak-client-for-TeamSpeak&Date">
|
||||
<img src="https://api.star-history.com/svg?repos=EchoSixHIYA/WebSpeak-client-for-TeamSpeak&type=Date" alt="WebSpeak Star History" width="100%" />
|
||||
</a>
|
||||
|
||||
<div align="right"><a href="#readme-top">返回顶部 · Back to top ↑</a></div>
|
||||
@@ -0,0 +1,801 @@
|
||||
# WebSpeak 代码待修改清单与修改方向
|
||||
|
||||
本文聚焦 `webspeak-webclient`,记录代码结构、修复方向与实施结果。2026 年 10 月 3 日按用户地址 `<TS3_TEST_HOST>:9987` 成功连接 TeamSpeak 3.13.8 / Linux,完成真实目录、私聊、状态及 PCM/WebRTC 媒体链路检查,并修复麦克风静音时伴奏被 TeamSpeak 丢弃、WebRTC 下行编码器状态不连续导致音量衰减的问题。上海 TS6 节点恢复后,已补验消息、媒体及共享信令,并修复状态恢复与共享清理问题。Android 已按用户要求移出本轮修复计划。用户随后明确跳过剩余设备、原生交互和旧版本验收;按调整后的范围,本轮施工已完成。跳过项保留未验收状态,不认定为已通过。
|
||||
|
||||
按用户要求,每批仅处理当前节点相关问题,合并相关修复后统一验证,不扩展到无关模块。管理页主要交互与布局已检查,原生确认框阻塞的操作验收单独保留。加入、聊天、频道成员、成员菜单、音频设置及密码弹窗已拆分;音频工具栏、私语控制条、语音诊断、共享设置与播放器已提取,语音活动成员卡片也已提取。06-L 的保序格式整理及两份页面样式确认冗余项已完成。真实消息与 TeamSpeak 媒体按已取得的证据记录范围;Android 既有结果仅作历史记录,不作为当前完成门槛。媒体、连接、命令、诊断、消息、身份及公共皮肤状态已有独立模块,继续复用。当前完成状态和跳过项放在前部,历史修复及验证记录保留在后部。
|
||||
|
||||
## 范围与依据
|
||||
|
||||
- 最新环境更新:用户确认上海节点恢复后,`<TS6_TEST_HOST>:9987` 实测为 TeamSpeak `6.0.0-beta13.1` / Linux,已补充下述 TS6 消息、媒体及静音恢复验收。此前旧 IP 超时仅作为历史记录,不再阻止该节点测试;`<TS3_TEST_HOST>:9987` 的 TS3 结果仍保留。
|
||||
- 记录日期:2026 年 10 月 3 日。
|
||||
- 当前代码基线:`dev` 分支,`50d71891034736d32a1accea94d13be91c8a3003`;应用版本 `0.2.5-preview`。本次收尾仅更新本文,不修改实现。
|
||||
- 最后一批代码修复覆盖 02-C TS6 共享清理参数及命令确认,新增 7 项回归。合并修改后一次 `npm run verify` 通过 434 项测试及前后端构建。该提交远端 CI 的 verify 与 docker-smoke 均成功,含 Docker 构建及健康检查([运行 37103379056](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/37103379056))。文档收尾不重复运行全量验证。
|
||||
- `6aa19c4` 的 CI、Docker 构建和健康检查已确认成功(运行 36896144974)。此前 `662dad3` 的手动发布工作流完整验证、Windows/Linux 打包启动及 Docker 健康检查通过(运行 36857782727);这些结果保留各自验证范围。
|
||||
- 既有皮肤修复记录记载新增 23 项测试,以及 `npm run verify` 通过 385 项测试和前后端构建;其中 5 项先复现旧结果覆盖及失效归属问题。这些是此前批次的验证结果,不是本轮重新执行的结果。
|
||||
- Android 从 `662dad3` 源码归档重新安装三套依赖并重建 SDK,在短路径完成 android:sync 和 assembleDebug,134 个 Gradle 任务执行,三个 ABI 包内容及 SHA-256 已检查。首次深层目录因原生工具路径限制失败,短路径重建通过;没有把构建成功写成设备或媒体验收。
|
||||
- 各平台构建环境、执行范围、Actions 归档摘要与本机 APK 校验和见 `docs/LOCAL_ARTIFACTS.zh-CN.md`。`662dad3` 的 x86_64 新包已在只读 Android 15 模拟器安装并冷启动,内嵌网关返回正确健康状态和版本;Android 布局复验仍待可交互环境。
|
||||
- 下文“代码可确认”指控制流或配置可直接支持的判断;具体故障发生条件仍需回归用例验证。“待验收”表示证据尚缺,不等于已发生故障。P1/P2/P3 表示建议实施顺序,不代表安全漏洞等级。
|
||||
- 后文身份、消息、媒体、皮肤等“实施记录”属于此前批次;其中“本批”指各记录对应的历史批次。当前待办以本页前部状态表为准。
|
||||
|
||||
## 当前代码结构
|
||||
|
||||
| 部分 | 主要位置 | 当前职责及整理判断 |
|
||||
| --- | --- | --- |
|
||||
| 启动与 HTTP | `src/index.ts`、`src/server/server.ts` | 网关启动、公共配置、加入凭证、管理路由与静态页面 |
|
||||
| 实时会话 | `src/server/voice-bridge.ts`、`session-manager.ts` | 接入、独立 TeamSpeak 客户端、连接恢复、会话终止及模块组装;桥接入口 782 行 |
|
||||
| 服务端会话子模块 | `session-audio.ts`、`session-events.ts`、`member-avatars.ts` | 音频转发、SDK 监听与目录编排、头像批次和生命周期均已提取 |
|
||||
| SDK 与媒体 | `ts-client.ts`、`teamspeak-adapter.ts`、`webrtc-audio.ts`、`opus-codec.ts` | SDK 连接及事件适配、WebRTC 混音、平台编解码 |
|
||||
| 共享契约 | `src/shared/` | 命令、服务端消息、WebRTC、屏幕共享、皮肤和管理请求与响应;后续复用现有模型 |
|
||||
| 管理与持久化 | `src/admin/`、`src/security/`、`src/persistence/` | 登录、配置、邀请、审计、访问策略与 SQLite |
|
||||
| 前端语音入口 | `web/src/composables/useVoiceWebSocket.ts` | 1,468 行;保留媒体组装、连接状态及业务动作,委托媒体、连接、命令、诊断和消息投影 |
|
||||
| 浏览器媒体模块 | `web/src/voice/` | 已有屏幕共享、远端播放、麦克风采集、录音测试、输出设备切换、伴奏、输入混音及电平监测;WebRTC 传输 194 行、播放 114 行 |
|
||||
| 浏览器连接与命令 | `web/src/voice/connection.ts`、`commands.ts` | 连接模块 132 行,拥有请求取消、期限、socket 与代次;命令模块 59 行,拥有确认等待及统一收尾 |
|
||||
| 浏览器诊断 | `web/src/voice/audio-diagnostics.ts`、`web/src/composables/useWebClientPerformance.ts` | 采样模块 168 行,拥有等待、来源范围与兼容计数;面板 composable 管理轮询和可比样本的展示 |
|
||||
| 会话消息状态 | `web/src/voice/session-state.ts` | 172 行;拥有成员与频道、聊天历史、事件、通知、会话范围和私聊身份映射 |
|
||||
| 页面与业务状态 | `web/src/views/`、`web/src/composables/` | 格式展开后主页面 1,337 行,管理页 580 行;聊天 composable 管理按会话和对象隔离的草稿、发送等待及反馈 |
|
||||
| 管理展示组件 | `web/src/components/admin/` | 格式展开后服务器设置 415 行、运维 326 行、皮肤 187 行;状态仍由父页创建,主要表单与路由交互已验收 |
|
||||
| 身份导入与导出 | `useWebClientIdentity.ts`、`components/web-client/IdentityImportDialog.vue` | 159 行状态模块与 151 行展示组件;异步操作、启动恢复与导出资源独立归属 |
|
||||
| 前端基础服务 | `web/src/services/`、`web/src/i18n/`、`web/src/skins/` | 请求、浏览器存储、身份导入、主题、皮肤及多语言;皮肤运行时的提交受取消和期限保护 |
|
||||
| 公共皮肤状态 | `usePublicSkin.ts`、`skin-operation.ts` | 104 行共享页面控制器与 38 行等待控制;管理初始化、选择、失效、回退和 8 秒期限 |
|
||||
| Android | `web/src/platform/`、`src/mobile/`、`mobile/`、`web/android/` | 本机网关就绪握手、移动打包和原生容器;运行时与设备验收独立 |
|
||||
| 独立中继 | `src/relay.ts`、`src/server/acceleration-relay.ts` | 中继进程及网关接入,本轮不扩展其功能 |
|
||||
|
||||
主链路为:浏览器申请一次性加入凭证,经 `/ws/voice` 建立网关会话,网关创建独立 TeamSpeak 客户端。WebSocket 承载控制消息和兼容音频;启用 WebRTC 时语音走另一条媒体通道。屏幕共享使用独立连接,由网关协调参与者及信令。
|
||||
|
||||
文件行数包含空行,仅用于定位职责集中处;“文件变短”不是验收标准。
|
||||
|
||||
## 完成状态与本轮跳过项
|
||||
|
||||
沿用原清单编号:06-H、06-I、06-J 已有身份与皮肤修复;06-K 管理导航已修复;06-C 展示拆分及主要交互已完成;06-L 格式及确认冗余项清理已完成。2026 年 10 月 3 日,用户明确要求“跳过这些内容”,以下剩余验收从本轮完成条件移除,不再等待环境或版本答复。按调整后的范围,本轮无剩余施工项;下表只保留未验收边界,已完成事项另列。
|
||||
|
||||
| 编号 | 本轮状态 | 保留的未验收边界 |
|
||||
| --- | --- | --- |
|
||||
| 06-C 客户端验收 | 按用户要求跳过 | 真实触屏拖动、原生离开/戳人输入框的操作及取消流程 |
|
||||
| 06-C 管理页 | 按用户要求跳过 | 原生确认框的移除、断开会话及取消流程;此前工具超时记录保留 |
|
||||
| 03 | 按用户要求跳过 | 真实旧客户端/旧网关版本矩阵;现有 TS3/TS6 消息和旧格式请求结果不代表旧应用整体通过 |
|
||||
| 02-C | 按用户要求跳过剩余验收 | 真实麦克风、扬声器、屏幕采集、完整音质、浏览器自动回退及官方 TS6 客户端视频共享;已完成的实服和合成端点结果保留其实际范围 |
|
||||
|
||||
当前范围调整:07-A 全部 Android 运行时、真机和媒体事项,以及 09-A 的 Android 布局复验,按用户要求暂不纳入本轮修复和完成条件。已有 Android 构建及启动记录保留,不认定为这些剩余能力已通过。09-A 在本轮保留的 Windows/Linux/Docker 干净构建与启动要求已完成。
|
||||
|
||||
以下实施过程、原修改方向和历史记录中的“待验收”“仍待完成”“继续”等描述,保留当时的验证边界;涉及上述跳过项时,不构成本轮新的待办。以后只有用户重新纳入范围才继续这些验收。
|
||||
|
||||
### 旧 IP 连接记录(2026-10-02,已由域名端点替代)
|
||||
|
||||
- 用户给出的 HTTP 形式链接按 TeamSpeak 地址 `<TS6_TEST_HOST>:9987` 使用;连接走 SDK 的 UDP 客户端协议,没有把 HTTP 探测当作 TeamSpeak 连通证据。
|
||||
- 使用当前源码的 `TSClient`、锁文件 SDK 和临时测试身份,不读取或修改真实配置、密码或持久身份。第一次连接返回 `timeout / TeamSpeak connection timed out`,随后正常断开。
|
||||
- 第二次在相同实际连接外增加只计数的 UDP 诊断:发起 15 次发送、510 字节,从该服务器收到 0 个数据报、0 字节,未收到 socket error 事件;同样超时并清理连接。这是进程级发送/接收记录,不是网卡抓包证据。
|
||||
- 两次均未取得已认证会话、服务器版本或目录,未发送聊天、戳人或音频。当前只能确认本机未获得协议响应,不能区分服务端状态、网络路径或协议响应原因;待确认公网 UDP 端口及接入条件后继续该节点。
|
||||
|
||||
### 域名实服与静音伴奏修复(2026-10-03)
|
||||
|
||||
- 通过当前 `TSClient` 和锁定 SDK 连接 `<TS3_TEST_HOST>:9987`,服务器返回 `3.13.8`、build `1779874471`、Linux;初次连接约 7.2 秒,自身目录项存在,正常断开。此前 IP 超时不再作为当前接入阻塞。
|
||||
- 两个临时 WebSocket 客户端经本机实际 `VoiceBridge` 连接远端服务,使用真实原生 Opus,无 SDK/编码器替身。临时身份不写入用户配置;私聊、戳人及私语音频仅发给测试会话。目录互见、带 UID 与省略 UID 的私聊、离开/返回、戳人和非法 PCM 拒绝通过;所见 JSON 消息全部通过共享解析器。
|
||||
- WebRTC 使用本机 werift 合成端点,经真实 ICE/DTLS/SRTP 与网关通信,再通过真实 TeamSpeak 服务到另一测试端。修复后上行 50/50 帧到达;反向 50 帧被网关接收并转发到 WebRTC,输出能解码出测试音频。没有使用浏览器麦克风、扬声器或屏幕采集。
|
||||
- 故障先在实服复现:麦克风静音后开启伴奏,网关发送 30 帧,对端收到 0 帧;仅取消静音后,同一伴奏收到 30 帧。原因是 `client_input_muted=1` 会使服务器丢弃该客户端的全部音频,而网关原本只更新混音器伴奏标志。
|
||||
- SDK 适配层现在分别记录逻辑麦克风静音和伴奏状态,串行提交组合后的 TeamSpeak 输入标志,成功后才更新状态;失败不污染后续更新,旧连接的排队/迟到结果失效。播放伴奏时允许整体输入,浏览器仍将麦克风静音;停止伴奏、WebRTC 停止及协商失败恢复输入状态,初始静音加伴奏也走相同处理。
|
||||
- 修复后静音伴奏和初始静音加伴奏均收到 30/30 帧(codec 5);停止伴奏后再次发送的帧均被抑制,关闭 WebRTC 后其他会话看到输入静音恢复。活动 WebRTC 停止后 PCM 恢复,本次观察收到 48/50 帧。测试会话已全部关闭,本机网关活动计数归零。
|
||||
- 质量边界:WebRTC 下行采样中,50 帧远端输入只有 30 个输出帧达到所设 RMS 门槛;该段网关记录 0 队列丢弃、0 解码错误,不能据此判断连续音质通过,也不能直接把帧数差归为网络丢包。下行解码连续性与混音仍需定位。合成无效 SDP 的尝试得到 answer,没有形成预期失败,因此未记为协商失败回退通过。
|
||||
- 416 项本地统一验证及实服结果覆盖本节点;TS6、旧应用版本、浏览器设备、多人/跨频道共享和原生输入框仍按待办推进,Android 不重新纳入。
|
||||
|
||||
### WebRTC 下行编码连续性修复(2026-10-03)
|
||||
|
||||
- 将前次实服音量异常缩小到实际 `WebRtcAudioSession` 混音器,用手动推进音频时钟排除网络和调度影响;源编码、网关解码和输出解码均使用原生 Opus。旧路径中,50 个语音帧与静音交替时,50 个输出全部低于 RMS 100;同样输入强制重编码后 50 个全部超过门槛。这证明存在独立于网络的代码故障。
|
||||
- 原因是单人且音量为 1 时直接转发源 Opus,静音、音量变化或多人混音则使用网关编码器;同一 RTP 流交替携带不同编码器历史,接收端无法维持连续解码状态。现在全部下行音频通过同一个会话编码器,删除原始 Opus 直通分支;队列、节拍、成员音量和上行路径保持原规则。
|
||||
- 新增 3 项回归覆盖静音间隔、交替说话者和音量变化,每项 50 个活动输出均达到预期电平,解码错误及队列丢弃为 0。本批一次统一验证通过 419 项测试及前后端构建。代价是单人默认音量也需要重编码,增加编码工作和一次有损转换;尚未完成容量压测。
|
||||
- 实服复查使用 `<TS3_TEST_HOST>:9987`、两个临时身份与本机 werift 端点。下行 50 个发送帧中网关收到 46 帧、向混音器提交 46 帧,队列丢弃和上下行解码错误均为 0;解码输出有测试音频。RMS 超门槛输出计数为 70,包含编码尾音,不能解释为 70/50 帧交付或完整音质通过。
|
||||
- 本次整套实服脚本未通过:后续静音伴奏收到 27/30 帧,严格数量断言失败;该段网关入口和 TeamSpeak 发送累计均为 80 帧且发送错误为 0。尚未定位这 3 帧差值发生于哪一段,不能直接归因于网络,也不修改断言掩盖结果。此前 30/30 的结果保留为此前批次记录。所有临时连接已清理,网关活动会话归零。
|
||||
- 当前代码故障及确定性回归已闭环;实服帧差、浏览器设备和完整媒体矩阵继续归 02-C。未扩展到其他模块,也未恢复 Android 待办。
|
||||
|
||||
### 音频分段复查与协商失败回退(2026-10-03)
|
||||
|
||||
- 针对前次伴奏 27/30 的帧差,临时测试进程记录 UDP 发送回调、接收数据报、解密后的音频包序号、SDK 事件和 WebSocket 输出,不修改生产诊断或 SDK。三轮静音伴奏各发送 50 帧,各段计数均为 50,序号分别为 0–49、50–99、100–149,无发送错误或网关输出丢弃;每次停止伴奏后再发送 10 帧均被静音抑制。此次未复现原帧差,不能倒推原故障原因或声称永不丢帧;不继续无差别重复探测。
|
||||
- 继续验收回退时确认:旧网关会对无音频的 `invalid sdp` 返回空 answer,也会协商只包含 PCMU 的真实音频 offer,但收发实现只处理 Opus。PCMU 被排在首位时,werift 发送器还会按首个协商编码标记实际 Opus 数据。这些会形成协商成功但媒体不可用的会话。
|
||||
- 现在将该音频 peer 的能力限定为 Opus,并从实际协商出的音频 transceiver 读取 payload type;未协商到 Opus 时进入现有失败清理和 `WEBRTC_NEGOTIATION_FAILED` 分支。删除扫描整个 SDP 和猜测默认 payload type 的路径;不修改共享信令格式、屏幕共享或其他模块。
|
||||
- 新增 4 项回归:无效 SDP、仅 PCMU、仅 Opus 109、PCMU 优先且 Opus 109。前两项受控失败,后两项 answer 只包含 Opus 109。统一 423 项测试及前后端构建通过。
|
||||
- 实服通过真实 `VoiceBridge` 验证两种失败均返回错误并清除 WebRTC 路由,无需先发送 `webrtcStop` 即可恢复 PCM。无效 SDP 后 50 帧收到 49 帧、RMS 1264;仅 PCMU 且初始静音加伴奏时,失败后 TeamSpeak 输入静音恢复,取消静音后 PCM 收到 50/50 帧、RMS 1259。这证明网关回退可用,不替代浏览器自动采集回退或完整音质验收。
|
||||
- 修改后另用 PCMU 优先、Opus payload type 109 的真实 ICE/DTLS/SRTP 合成端点连接实服:50 个静音伴奏帧从 RTP 入口到对端 WebSocket 全部到达,音频包序号连续;停止伴奏后静音恢复。上述临时会话均关闭,网关活动会话归零。
|
||||
- 已请求明确旧客户端/旧网关版本矩阵及 TS6、设备测试环境;未指定前保留验收缺口,Android 仍排除。此前原生确认框工具阻塞不重复重试。
|
||||
|
||||
### 实服双人混音与成员音量验收(2026-10-03)
|
||||
|
||||
- 当前 `6616d0b` 源码、原生 Opus、三个临时 TeamSpeak 身份连接 `<TS3_TEST_HOST>:9987`。两位发送者通过 WebSocket PCM 同时生成 500 Hz 和 850 Hz 音频,仅私语到第三个测试身份;接收端通过真实 werift ICE/DTLS/SRTP 解码网关混音。未向其他用户发送测试音频,未使用真实麦克风或扬声器。
|
||||
- 默认音量、第一位静音、第一位四分之一音量三组,每组两位各发送 100 帧。网关每组接收并提交混音 200 帧,队列丢弃和解码错误均为 0。持续使用同一个输出解码器,按 850 Hz 分量超过 500 的输出帧选取样本,比较两种频率的幅度中位数。
|
||||
- 默认音量的 500/850 Hz 幅度分别为 1211/1235;第一位静音后为 74/1187;第一位四分之一音量后为 370/1268。两种声音同时存在,单成员静音及衰减不抑制另一位。该频谱抽样只证明本场景的混音与音量控制,不作为精确增益、听感、所有网络条件或容量结论。
|
||||
- 第一次脚本在首组通过后请求统计过快,触发现有 750 毫秒限频并等待超时;只将临时脚本采样间隔调至 1100 毫秒后完成全部场景,没有修改生产限频或放宽断言。全部临时会话已关闭,网关活动会话归零。
|
||||
- 输出中超过频率门槛的帧数大于源帧数,不能用于计算交付率。额外用实际混音器和原生编解码器验证停止输入后的尾音:首个静音 tick 的 RMS 为 726,第二个为 6,第八个起为 0;没有观察到本地持续长尾音。实服节拍中的间隔与编码过渡仍需结合真实设备试听,不能仅以频谱计数宣称完整音质通过。
|
||||
|
||||
### Edge 原生确认框复核及剩余环境缺口(2026-10-03)
|
||||
|
||||
- 本轮浏览器清单出现可连接的 Edge 扩展后,使用独立临时数据库、临时皮肤和模拟会话重新检查管理确认流程。实际管理页登录、皮肤列表展示成功;点击移除时工具输入命令超时,但 `getJsDialog()` 确认弹窗类型为 `confirm`。
|
||||
- 对该弹窗执行 `dismiss()` 后,工具在焦点模拟命令超时,后续读取弹窗和关闭测试标签也超时。不能确认“取消”完整生效,更未执行确认移除或断开会话。只读检查临时后端显示测试皮肤仍存在、模拟会话仍活动,审计仅有初始化、改测试密码和登录记录,没有业务删除记录。
|
||||
- 临时服务进程已终止并确认退出;工具未确认测试标签关闭,不标记为已关闭。没有接触真实管理配置或用户会话,也没有为了工具限制重写原生确认逻辑。内置浏览器与 Edge 均已留下阻塞证据,后续只在工具状态有明确变化或有人工结果时补验。
|
||||
- 现有可自动执行的 TS3 媒体节点已有上述结果;剩余真实麦克风/扬声器及屏幕采集、触屏和原生弹窗流程需要可交互环境。旧应用版本矩阵与 TS6 端点仍等待明确。不能用再跑单元测试或合成音频替代这些验收,也不新增无关修复或容量目标。
|
||||
|
||||
### 上海 TS6 节点恢复与防刷期间静音恢复修复(2026-10-03)
|
||||
|
||||
- 用户确认节点更新后,以当前 SDK 和临时身份连接 `<TS6_TEST_HOST>:9987`,约 290 毫秒取得连接及版本:`6.0.0-beta13.1`、build `1790080330`、Linux,协议识别为 `ts6`;3 个频道、自身目录项存在,探测后正常断开。未修改部署、真实配置或持久身份。
|
||||
- 首轮快速并行验收触发 `FLOOD_PROTECTION`,同时首个 RTC 上行数量断言未通过,不能据此归因于媒体实现。随后将临时脚本的控制命令间隔调为 1 秒、接入后等待 1.5 秒并串行验收;没有更改服务器防刷设置或音频帧节拍。
|
||||
- 消息与 PCM 场景通过:目录互见、带 UID 与省略 UID 的双向私聊、离开/返回、测试身份间戳人、非法 PCM 拒绝;双向 PCM 和停止 WebRTC 后 PCM 均收到 50/50 帧,RMS 分别为 1268、1269、1259。全部实际 JSON 消息通过共享解析器。
|
||||
- WebRTC 使用本机 werift 合成端点和真实 ICE/DTLS/SRTP。上行 50/50 帧到达;反向网关收到并提交 50 帧,队列丢弃和解码错误为 0;输出可解码。麦克风静音阻止音频、静音伴奏及取消静音伴奏各收到 30/30 帧(codec 5);停止伴奏恢复静音,活动 WebRTC 停止后 PCM 收到 50/50 帧。输出 RMS 计数包含编码过渡,不作为交付率。
|
||||
- 第二次以初始静音加伴奏启动后,停止 WebRTC 未恢复对端可见静音。缩小为连续两次启停后稳定复现:第二次 `setAccompanimentActive(false)` 被服务端拒绝,明确返回 `client is flooding (id=524)`,对端仍显示 `inputMuted=false`。单次启停能正常恢复,故不是 TS6 完全不支持该状态。
|
||||
- 输入状态队列现在只跳过已经成功确认且有效静音值不变的上报,同时仍记录逻辑麦克风/伴奏变化;连接重建和失败确认使缓存失效。仅对防刷错误增加最多两次重试,分别等待 1 秒、2 秒;每次重试检查原连接及代次,成功确认后才提交状态,权限等其他错误不重试。持续拒绝仍向调用方返回失败,不无限重试或承诺服务器总能接受。
|
||||
- 新增 4 项回归覆盖相同有效静音值下的逻辑状态、恢复静音时防刷重试、重试上限及后续队列、连接替换后禁止旧重试。统一 427 项测试及前后端构建通过。修改后实服按相同两次启停复查,每次伴奏收到 30/30 帧,停止后对端均显示 `inputMuted=true`,传输返回 WebSocket;全部临时连接清理,活动会话归零。
|
||||
- 本轮解决了 TS6 测试端点缺失和实际发现的输入状态恢复问题。仍未完成 TS6 原生客户端共享、真实浏览器采集/设备试听、触屏及原生弹窗、指定旧应用版本矩阵;不把本轮合成端点结果扩大为这些项目通过。
|
||||
|
||||
### TS6 共享清理参数与服务端确认修复(2026-10-03)
|
||||
|
||||
- 使用上海 `<TS6_TEST_HOST>:9987`、实际 VoiceBridge 网关、独立 SDK 测试身份与两个本机 werift peer,验证网页侧发布经 TS6 通知另一端,加入请求、offer/answer 和 ICE/DTLS/SRTP 建立成功;共享音频收到 30/30 帧,解码 RMS 1270。video transceiver 参与协商,但没有发送视频帧,也未运行官方 TS6 客户端或浏览器屏幕采集。
|
||||
- 原代码在网页移除 TS6 观看者时遗漏 `removeclientfromstream` 的 `reason` 参数,服务器明确返回 `id=1542 / missing required parameter`;本地却立即减少观看者。停止共享又被防刷拒绝(`id=524`),未取得服务端停止通知。根因还包括适配层使用不等待回执的发送方法,使上层无法获知真实拒绝。
|
||||
- 两处移除命令补充 `reason=1`;共享命令等待服务端确认。网页移除原生观看者仅在确认或服务端离开通知后减少计数,拒绝时保留成员并返回现有错误消息;通知早于确认时不重复发送离开事件。仅对 `stopstream` 和 `removeclientfromstream` 的明确防刷拒绝重试,最多两次,等待 4 秒、8 秒;每次检查连接及代次。offer/ICE 和其他错误不重试,停止发布最终失败记入日志。
|
||||
- 新增 7 项回归覆盖等待确认、拒绝传播、清理重试间隔及上限、非清理信令不重放、连接替换失效、移除参数、失败保留成员及通知与确认去重(部分用例覆盖多项)。统一 434 项测试、后端编译、前端类型检查和构建通过,未逐项重跑全量验证。
|
||||
- 修改后通过原先失败的网关路径复查,共享音频仍收到 30/30 帧,TS6 发回观看者离开通知。停止共享连续两次收到防刷拒绝,服务器附带等待值约 6098/7063 毫秒;有限重试后收到实际停止通知。临时脚本将清理结果等待上限由 10 秒调整为 20 秒,以覆盖 12 秒重试等待;没有放宽音频数量或用本地状态代替服务端通知。全部会话断开,网关活动计数归零。
|
||||
- 反向检查由独立 SDK 身份先发布,再接入网页网关:发现已存在共享、加入请求到达来源、offer/answer、共享音频 30/30 帧(RMS 1270)、网页离开得到 TS6 通知、来源停止传播到网页均通过;JSON 全部通过共享解析器。首次临时脚本昵称过长,被服务器明确拒绝;仅缩短测试昵称后继续,未修改昵称业务规则。该结果仍是 SDK 与合成 peer 互通,未替代官方客户端的视频验收。
|
||||
- 跨频道实服检查:频道 2 要求密码,改用实际可进入的频道 3,未改变服务端权限。观看者换频道后退出、列表不可见、跨频道加入返回 `SCREEN_SHARE_TARGET_MISMATCH`,返回原频道后可重新加入;共享者换频道后两端收到网页停止事件。TS6 的停止命令确认成功,但两侧均未收到原生停止广播,原先仅等待广播的脚本因此超时,不能把脚本整体记为通过。
|
||||
- 为核对上述结果,另作一次单发布者查询:换频道前 `requeststreaminfo` 返回完整共享 ID/属性;换频道清理获成功回执后,同一查询只返回含 `return_code` 的空 `notifystreaminfo`,原共享已不可查询。临时断言原本预期报错而非空通知,因此断言失败;保留原始记录,并对已采集的前后结果检查“之前有 ID、之后无共享字段、会话归零”,通过。该节点没有新增代码故障,也未为通知差异修改生产行为;官方客户端视频和真实设备仍待验收。
|
||||
|
||||
## 待修改事项的具体方向
|
||||
|
||||
### 04-D 前端媒体与连接编排
|
||||
|
||||
[useVoiceWebSocket.ts](../web/src/composables/useVoiceWebSocket.ts) 保留为页面调用入口。媒体、连接、命令、诊断和消息投影已交由各自模块管理,页面拆分继续复用现有响应式数据。
|
||||
|
||||
| 现有边界 | 应拥有的状态与资源 | 重点约束 |
|
||||
| --- | --- | --- |
|
||||
| 伴奏采集,已提取 | 授权操作、候选与当前采集流、结束监听、错误状态 | 生命周期绑定当前会话和混音目标;取消立即释放已取得的流 |
|
||||
| WebRTC 输入混音,已提取 | 输出流、麦克风源和音量节点、可选伴奏源 | 不停止外部模块拥有的原始麦克风;准备失败保留可用输出 |
|
||||
| 电平监测,已提取 | 输入源、分析器、静音输出节点和周期计时器 | 旧回调失效;失败只停止监测,不影响语音发送 |
|
||||
| WebRTC 传输与播放,已提取 | PeerConnection、offer/answer、ICE 等待、播放元素和协商计时器 | 旧 peer 无法写回;失败恢复兼容 PCM;关闭完整释放 |
|
||||
| 连接控制,已提取 | WebSocket、加入凭证请求、取消器与连接代次;通过回调更新页面状态 | 旧 socket 消息不写回;取消、超时和失败语义明确 |
|
||||
| 命令等待,已提取 | 请求标识、待确认登记、期限和结束函数 | 结束幂等;发送失败和断开立即释放 |
|
||||
| 诊断采样,已提取 | 统计等待、兼容计数、浏览器统计和样本范围 | 只组合当前来源数据;失败与会话释放清除等待;范围不进入网关协议 |
|
||||
| 状态投影,已提取 | 成员与频道事件、聊天历史、事件、通知、私聊身份范围 | 保留数组引用;区分完整与未知目录;退出及替换重置会话数据 |
|
||||
|
||||
上表边界已有实现,不再作为待提取清单。`useVoiceWebSocket.ts` 仍有设备协调、音量与页面动作,但本轮没有仅凭行数新增重构任务。若后续修改反复涉及同一组状态,再按具体职责提取一个边界。保留 `releaseSessionResources` 作为会话统一释放入口,模块只释放自身拥有的资源,避免多个模块共同修改大型状态对象。
|
||||
|
||||
现有规则继续有效:采集层拥有麦克风流;录音测试只拥有录音器、期限和试听 URL;设备替换在候选处理链就绪后提交;输出设备切换按端点串行执行。模块拆分不能撤销这些已实现的行为。
|
||||
|
||||
### 06-C 页面组件
|
||||
|
||||
当前依据:[WebClient.vue](../web/src/views/WebClient.vue#L1) 格式展开后有 1,337 行,加入表单、聊天面板、频道成员、成员菜单、身份导入、音频设置及密码弹窗已独立;成员卡片也已提取,父页保留页面编排及区域组合。[AdminView.vue](../web/src/views/AdminView.vue#L41) 拆分后为 251 行,本批仅展开格式后为 580 行,三个管理模板已迁移到独立组件。管理页剩余浏览器验收缺口见前表,客户端继续明确展示边界;不以文件长度推定运行故障。
|
||||
|
||||
以下名称为建议,实施时按实际接口确定。按稳定区域迁移,相关展示区域合并后统一验收,避免同时重写模板和业务状态。
|
||||
|
||||
| 区域 | 建议组件及职责 | 状态保留位置与接口 | 重点验收 |
|
||||
| --- | --- | --- | --- |
|
||||
| 加入页,已提取 | `JoinForm` 展示目标、昵称、频道、身份选项与连接状态 | 连接与历史仍由现有 composable 管理;表单用明确字段模型,提交、取消和导入用事件 | 固定与开放模式、收藏与历史、连接等待及取消、密码交互 |
|
||||
| 频道与成员,已提取 | `ChannelMemberPanel` 与 `MemberActionsMenu` 展示层级、成员状态和操作入口 | 复用父页单一 `useWebClientMembers`;面板保留音频工具栏插槽,菜单拥有定位观察器;动作仍交回现有控制层 | 搜索、频道切换、桌面指针拖动、调度及菜单边界已检查;真实触屏拖动及原生输入框仍待验收 |
|
||||
| 聊天,已提取 | `ChatPanel` 展示标签、历史、草稿和发送反馈 | 草稿与待确认状态继续由单一 `useWebClientChat` 实例管理;保留外部打开私聊的入口 | 切标签保留草稿、发送失败与重试、目标离线、滚动和移动端切页 |
|
||||
| 设置与密码弹窗,已提取 | `AudioSettingsDialog`、`ChannelPasswordDialog`、`ServerPasswordDialog` 展示设置及连接反馈;身份导入此前已提取 | 复用父页单一媒体与连接状态;设置错误受打开代次和请求顺序保护;共享焦点工具管理循环、Esc 和返回 | 焦点、Esc、设置持久化、密码等待与重试已检查;真实设备切换与录音待媒体验收 |
|
||||
| 音频工具栏与私语,已提取 | `AudioDock` 展示桌面快捷操作;`WhisperControls` 展示目标与按住讲话入口 | 使用父页单一音频控制器;私语按钮只拥有当前输入,隐藏、失焦和卸载时停止;监听随组件释放 | 静音、音量、设置入口、伴奏不可用提示、指针/键盘命令及布局已检查,真实媒体另行验收 |
|
||||
| 诊断与共享展示,已提取 | `VoicePerformancePanel`、`ScreenShareSettingsDialog`、`ScreenSharePlayer` | 父页创建诊断与共享控制器;视频和播放器通过明确函数引用交回控制器,组件不创建采集或 PeerConnection | 兼容传输诊断、设置字段/焦点、合成视频元素替换与全屏已检查;真实 WebRTC/TeamSpeak 互通仍待验证 |
|
||||
| 语音成员卡片,已提取 | `VoiceMemberCards` 展示成员状态、头像和共享操作入口 | 复用父页频道投影、成员动作与共享控制器,停止共享及菜单用事件返回;活动区域仍由父页组合 | 在线、发言、自身、空成员、共享等待/停止、观看切换、移动菜单和抽样布局已检查 |
|
||||
| 管理功能页,已提交 | `AdminServerSettings`、`AdminOperations`、`AdminSkins` 已提取,先验收这三个边界 | 父页创建三个管理 composable,通过稳定 `model` 对象传入;登录、CSRF、路由与总览仍在页面;欢迎词语言用具名模型传递,WebRTC 提示用事件返回 | 保存期间继续编辑、请求失败保留草稿、欢迎词语言、退出失败、路由切换、皮肤文件选择及操作互斥 |
|
||||
|
||||
接口只传该区域需要的状态和动作,避免把整页上下文塞进一个对象,也避免父子各自实例化同一个业务 composable。管理组件当前使用 `ReturnType<typeof useAdmin...>` 描述功能控制器,并在 setup 中解构,因此依赖父页维持同一控制器实例;若后续支持替换实例,需要同步调整读取方式。可以用 `Pick` 或专用接口缩小暴露范围,但不为形式重写已明确的状态归属。展示辅助函数如头像、时间格式在确有多处复用时集中,不额外引入全局状态层。
|
||||
|
||||
样式需要随组件边界一并核对。[客户端样式入口](../web/src/views/WebClient.vue#L1337)和[管理页样式入口](../web/src/views/AdminView.vue#L580)均使用 `scoped`,格式展开并清理重复声明后 CSS 分别为 7,659 与 3,737 行。身份弹窗已有针对组件的 `:deep` 规则;管理页当前改动将大量功能区选择器改为 `:deep`,并保留部分外壳和语言控件选择器的原作用范围。不要把这项源码变化直接等同于视觉一致:需对比子组件内部、共享按钮与语言菜单的字体、间距、尺寸、折行,以及样式声明顺序和优先级。必要时改为组件自有样式或更窄的区域选择器,保留明暗主题、`data-ws-part` 和路由隔离,管理页保持独立于公开皮肤。
|
||||
|
||||
测试也需跟随边界调整:[皮肤节点检查](../web/src/services/skin-pack.test.ts#L80)在当前工作区已递归读取 `components/web-client` 和 `components/admin` 下的 Vue 文件,保留公开节点契约及管理页隔离检查。[管理页状态测试](../web/test/admin-view.test.mjs#L79)已改为读取父页功能模型,仍用 `render: () => null` 替换模板,不能单独证明子组件的字段与事件接线正确。后续验收必须覆盖真实渲染的表单、按钮和路由交互;这属于测试覆盖边界,不能推定测试已发现业务故障。
|
||||
|
||||
管理组件验收至少包括:服务器保存时继续编辑、失败保留草稿、不同语言欢迎词往返、WebRTC 开关触发父页提示;邀请创建和撤销、刷新与路由取消;皮肤默认选择、启停、文件导入反馈;认证失效清理和失败退出保留状态。检查桌面与 390 × 844 窄屏、明暗主题、五语长文案,以及公开页进入管理页再返回的样式隔离。既有记录完成了三个桌面页面的静态外观对比;本批补充主要表单交互和窄屏导航检查,具体结果见下节。
|
||||
|
||||
每个区域验收包括桌面与窄屏、五语长文案、明暗主题和自定义皮肤;对比布局、滚动、弹层遮挡及键盘操作。编译通过和源码正则匹配不能替代实际渲染检查。
|
||||
|
||||
### 语音成员卡片的上批结果
|
||||
|
||||
- `VoiceMemberCards.vue` 接收当前频道成员、发言判断与头像辅助函数,以及共享状态和动作的必要子集。共享状态引用保持稳定;停止与成员菜单事件回到父页,不复制频道、成员或媒体状态。
|
||||
- 保留现有皮肤节点和样式声明顺序。20 个可见元素对比中,字体、颜色及内边距一致;观测到的元素尺寸和居中边距差异小于 1 像素,不能宣称像素完全相同。
|
||||
- 模拟网关的发言消息正确更新 Alice 卡片;观看入口发出 `screenShareJoin`,目标为该成员的 `preview-share`。网关无真实共享,因此返回共享不存在的预期错误;此检查只证明目标与反馈接线。移动端卡片菜单仍对应 Alice,共享设置入口仍打开原弹窗。
|
||||
- 独立受控展示页检查开始等待时出现停止按钮、停止后恢复开始入口、共享成功状态显示标记、观看/取消观看切换以及空成员提示。没有用该页面宣称实际媒体链路成功。临时页面与进程在收尾时移除。
|
||||
- zh/浅色、en/深色、de/ILLUSIA、ru/浅色、ja/深色五组配对分别检查 1280×720、390×844、320×568,共 15 组;成员卡片、共享按钮和直播标记均未横向越界,应用浏览器日志无错误或警告。
|
||||
- 本批一次统一验证通过 409 项测试及前后端构建。06-C 主要结构拆分已完成,触屏与原生输入框验收缺口仍在状态表;下一结构节点为 06-L 的保序格式整理。
|
||||
### 此前诊断与屏幕共享展示的结果
|
||||
|
||||
- 三个展示组件使用父页单一控制器,诊断采样继续在原模块运行;共享设置沿用原输出参数和存储行为,补上 Tab 循环、Esc 关闭和返回入口焦点。播放器通过 `setVideoElement` 与 `setPlayerElement` 绑定真实 DOM,不把组件实例当成播放器。
|
||||
- 原视频绑定仅监听流和音量,元素替换而流不变时会漏绑。现在同时监听视频元素,在渲染后绑定当前流与音量;旧元素立即清空 `srcObject`,卸载不停止其他模块拥有的媒体轨道。
|
||||
- 原全屏判断在两个元素都为空时会为真。现在要求当前播放器存在;播放器移除或作用域释放仅退出自身拥有的全屏,失败时从真实文档状态重新同步。
|
||||
- 有明确成员 ID 或 TeamSpeak peer ID 的共享流以该身份为准,不再因昵称相同匹配到另一成员;缺少身份的旧数据仍保留昵称兼容。
|
||||
- 新增 6 项测试验证上述绑定、清理、全屏归属、同昵称匹配及 720p/30 FPS 输出参数。最终统一验证为 409 项测试及前后端构建通过。原有 4 条播放器皮肤样式断言保留颜色和层级要求,只兼容 `:deep` 写法。
|
||||
- 实际应用中,诊断面板 37 个可见元素和共享设置 21 个可见元素的尺寸、字体、颜色、间距与拆分前一致。共享设置选择 720p/30 FPS 后关闭再打开仍保留;Tab 首尾循环、Esc 与返回入口焦点通过。诊断浏览器结果覆盖兼容传输分支,WebRTC peer 数据的真实链路仍归媒体验收。
|
||||
- 共享设置与诊断分别在 zh/浅色、en/深色、de/ILLUSIA、ru/浅色、ja/深色五组配对下检查 1280×720、390×844、320×568,共 30 组;等待实际语言及皮肤生效后记录,弹层均在窗口内。
|
||||
- 独立本地预览用画布生成 640×360 媒体:新播放器可继续播放现有流,旧视频已解绑、轨道仍存活;全屏状态可进入,退出播放器后全屏清除。这只是浏览器展示生命周期证据,不代表真实共享采集、信令或跨端媒体已验收。临时预览文件和进程在收尾时移除。
|
||||
### 此前音频工具栏与私语控制的结果
|
||||
|
||||
- `AudioDock.vue` 通过稳定对象接收所需语音引用与动作,设置及输出静音用事件返回;`WhisperControls.vue` 复用同一控制器,清空目标仍交回成员模块。原有皮肤节点和样式声明顺序保留。
|
||||
- 私语只接受主指针左键,记录捕获指针并忽略其他指针的松开;捕获失败不进入讲话状态。新增空格/回车按住支持,忽略重复按键与无关松开。停止先清除归属,再释放捕获,避免丢失捕获事件重复停止。
|
||||
- 控件失焦、窗口失焦、页面隐藏、移动页切走和组件卸载均停止当前按住操作;组件释放监听,音频控制器作用域释放也停止私语。5 项新增测试验证输入归属与清理。
|
||||
- 浏览器确认右键不启动、左键启动、移出后松开停止;空格/回车各产生一组真实 WebSocket 开始/停止命令,模拟网关收到 `[true, false, true, false]`。窄屏隐藏与按钮失焦时状态停止,清空目标移除控制条。浏览器错误与警告记录为空。
|
||||
- 工具栏拆分前后 22 个可见元素的尺寸、字体、颜色和间距一致。麦克风及输出静音、输入与输出音量、设置入口/关闭、伴奏缺少 WebRTC 的反馈已检查;当前没有真实麦克风授权,不作为音频效果证据。
|
||||
- 布局使用 zh/浅色、en/深色、de/ILLUSIA、ru/浅色、ja/深色五组配对,每组检查 1280×720、390×844、320×568,共 15 组;另核对每组桌面输入/输出音量面板,共 10 个面板。等待语言及皮肤实际生效后记录边界,控件均未横向越界,音量面板均位于窗口内。
|
||||
- 本批统一验证 403 项测试与前后端构建通过;属性接口简化后前端类型检查及构建再次通过。真实语音、伴奏和触屏设备结果仍归原媒体验收节点。
|
||||
### 此前音频设置与密码弹窗的结果
|
||||
|
||||
- 三个展示组件复用父页现有状态,设置仅接收所需语音引用与控制动作,两个密码弹窗使用字段模型及提交/取消事件。共享焦点工具处理初始焦点、Tab 循环、Esc 和关闭后返回;服务器连接等待会使原按钮失焦,因此增加返回连接按钮的回退。
|
||||
- 设置准备、设备选择和录音测试的错误只允许当前打开代次及最新请求发布;关闭同步停止录音测试,作用域释放也停止并使迟到反馈失效。5 项测试先在旧实现全部失败,再验证修复;没有改写底层媒体事务。
|
||||
- 频道密码提交遇普通错误原先可能持续禁用输入。现在显示本次错误、解除等待、保留密码供重试,并阻止等待期间重复提交。3 项测试覆盖重复提交、普通错误重试和成功关闭。
|
||||
- 设置提取前后对比 88 个可见元素,发现权限拒绝颜色未跨组件边界生效并修正;最终拒绝颜色与基线一致。通知音量、VOX 阈值关闭再打开仍保留;权限拒绝提示、Tab 首尾循环、Esc 及返回焦点通过。当前浏览器无麦克风授权,不能将这些检查当作真实录音或设备切换验收。
|
||||
- 两个密码流程检查必填提示、错误密码、正确密码及取消。频道提交受控等待期间输入与按钮禁用;普通权限错误后恢复输入,撤除模拟故障后不重填密码即可成功重试。频道取消恢复原选择,服务器取消返回连接按钮。
|
||||
- 三个弹窗分别检查 zh/浅色、en/深色、de/ILLUSIA、ru/浅色、ja/深色五组配对,每组使用 1280×720、390×844、320×568,合计 45 组边界检查通过。这是抽样配对,不是五语言与三皮肤的完整交叉组合。最终浏览器错误与警告记录为空。
|
||||
- 最终统一 `npm run verify`:398 项测试全部通过,后端编译、前端类型检查和生产构建通过。真实媒体、触屏及原生输入框等缺口仍按原节点跟踪。
|
||||
|
||||
### 此前频道成员与菜单的结果
|
||||
|
||||
- `ChannelMemberPanel.vue` 接收频道投影、明确字段模型及成员控制器的展示子集;音频工具栏通过插槽保留在父页。`MemberActionsMenu.vue` 共用同一控制器,私聊和音量通过事件交回父页,不复制成员状态。
|
||||
- 组件提取前后 90 个成员面板可见元素的尺寸、字体、间距及颜色一致。按成员名/频道名搜索、空结果、键盘清空搜索、嵌套频道切换、菜单调度、私语目标增删、私聊入口、成员音量回传和桌面指针拖动已检查。模拟客户端按实际移动事件广播目录变化。
|
||||
- 移动端误调度:鼠标进入“调度到”会先展开子菜单,底部菜单随之上移,点击可能命中目标频道。现仅桌面允许悬停展开,移动端通过点击展开;复查展开后目录不变,明确点击目标后才移动成员。
|
||||
- 菜单越界:1280×568 窗口曾测得主菜单底部 580、子菜单底部 615;320×568 时最后一个目标底部 505,而导航从 494 开始。菜单现在按实际尺寸限制位置,子菜单空间不足时向左/上调整,超高菜单允许滚动,保留 CSS 缩放换算。组件拥有尺寸观察器及 resize 监听,卸载时释放。
|
||||
- 最终 390 项测试及前后端构建通过;其中 5 项定位回归覆盖短窗口、底部子菜单、右侧翻转、过大内容和缩放后的尺寸。五语×浅色/深色/ILLUSIA×1280×568、390×844、320×568 共 45 组 DOM 边界检查通过。实际点击确认短屏滚动选项和重定位子菜单均能调度,浏览器无警告/错误日志。
|
||||
- 验收限制:IAB 不支持 `Input.dispatchTouchEvent`,真实触屏拖动未完成;“离开/戳一戳”依赖原生输入框,本批未执行其完整流程。一次批量浏览器检查超时后按已完成组合恢复并补验,未据此改动业务代码。模拟服务不能证明生产调度权限或真实媒体。
|
||||
|
||||
### 加入表单与聊天面板的此前结果
|
||||
|
||||
- `JoinForm.vue` 通过七个具名模型回传字段,连接、取消、收藏、历史选择及身份操作通过事件回到父页。固定模式提交、开放模式目标/端口/昵称/频道/密码/中继回传、收藏与最近连接回填、身份弹窗入口和取消连接均已检查。取消后释放迟到的凭证响应,页面仍停留加入页。
|
||||
- `ChatPanel.vue` 接收父页单一聊天控制器的展示子集,保留草稿与确认状态归属;DOM 滚动引用仍接回该控制器。频道/服务器草稿切换、失败保留、成功回执清空、事件日志、外部打开私聊及私聊草稿恢复均已检查。两条长消息后实际滚动位置为 351,内容 867、可视高度 516,底部剩余距离为 0。
|
||||
- 拆分前后桌面空聊天面板 29 个元素的尺寸、字体、间距及颜色一致。加入页保留原结构、字段标识与皮肤节点;样式声明顺序不变,仅调整跨组件选择器和下述布局问题。
|
||||
- 窄屏问题:开放模式与展开身份选项时,长文案撑宽隐式网格列;俄语 320 像素视口实测表单宽 250、内容列约 369 像素。改为 `minmax(0, 1fr)` 列,窄屏身份按钮允许换行,中继说明与选择框纵向排列,并允许字段标签折行。修复后表单、聊天各 45 组五语×三皮肤×三宽度的控件边界检查通过。皮肤为内置浅色、深色及随项目提供的 ILLUSIA;未覆盖任意第三方皮肤包。
|
||||
- 浏览器无警告/错误日志。本批主要覆盖模拟服务的正常展示和操作;真实目标离线、真实媒体及生产消息兼容不归为本批完成项。其余客户端展示边界仍见 06-C 待办。
|
||||
|
||||
### 管理组件的此前验收结果
|
||||
|
||||
三个展示组件继续使用父页创建的控制器,未复制业务状态。欢迎词语言通过具名模型传递,WebRTC 提示通过事件返回父页,皮肤文件输入由展示组件持有。现有管理状态测试改为访问功能模型;皮肤契约检查包含递归的管理组件目录。
|
||||
|
||||
- 服务器设置:受控迟到保存不覆盖后续编辑,失败保留草稿;路由往返保留名称与欢迎词语言;WebRTC 开关触发提示并锁定端口;连接测试反馈、中继增删接线正常。连接测试使用模拟结果,未访问真实 TeamSpeak。
|
||||
- 运维与认证:邀请创建与撤销、数值字段及路由草稿已检查;退出失败保留草稿,成功退出移除管理内容,再进入读取已保存配置;当前 401 返回登录页并清理管理内容。
|
||||
- 皮肤:默认项保存、失败回滚、等待时操作互斥、启停、错误包反馈、合法包导入与文件输入重置已检查。包内容由实际前端解析器检查,预览服务端使用内存皮肤目录,不把该结果表述为生产注册表端到端验证。
|
||||
- 布局:系统深色下四路由 × 五语 × 四宽度,共 80 组导航、工具栏和页面横向边界检查通过;另有浅色 320 像素四路由检查。键盘从服务器链接按 Tab 可聚焦运维链接。
|
||||
- 剩余验收:点击移除测试皮肤后,浏览器工具在原生确认框处超时;新标签可继续其余检查。没有据此修改 `window.confirm` 或业务逻辑。移除、断开会话及下载类操作的完整浏览器流程仍未确认。
|
||||
|
||||
本批统一验证为 385 项测试及前后端构建通过。未因纯展示提取新增镜像实现测试;真实模板接线以以上浏览器结果补充已有状态和接口测试。
|
||||
|
||||
### 06-K 管理页窄屏导航修复
|
||||
|
||||
依据:[管理页侧栏模板](../web/src/views/AdminView.vue#L23)和[窄屏样式](../web/src/styles/admin.css#L318)。修改前品牌、四个链接和退出按钮在窄屏继续同排。浏览器已复现:390 像素视口的布局可用宽度为 375 像素,退出按钮右边缘约为 455 像素,入口被裁切。
|
||||
|
||||
已实施:不超过 850 像素时品牌与退出按钮占第一行,导航独占第二行,以四列等宽网格约束宽度,点击区域至少 44 像素高。保留桌面侧栏、可访问名称与当前页面标识,不使用隐藏横向溢出来掩盖不可见入口。
|
||||
|
||||
320、390、768、1280 像素及五语的边界检查通过,四个入口和退出按钮均在可见区;浅色窄屏与键盘导航通过。此处改变属于预期修复,与组件提取的外观保持检查分别记录。
|
||||
|
||||
### 06-L 模板和样式的可读性
|
||||
|
||||
原静态统计发现页面模板和 CSS 存在数千至上万字符的单行,增加审阅与定位成本,不等于存在运行故障。本批已展开主页面、管理页及所属展示组件的 20 个模板,以及两份页面样式;CSS 现为 7,854 与 3,852 行,行数增长来自排版。
|
||||
|
||||
模板使用固定版本 Prettier 3.6.2 整理,仅取其模板输出,脚本保持逐字一致。逐个比较 Vue 编译出的渲染函数语法树,20 个全部等价;比对发现成员菜单及共享错误提示中图标后的空格被换行消除,已保留原空白文本。CSS 使用现有 PostCSS 解析器展开声明,核对选择器、属性值、声明及规则顺序、条件和注释均不变。
|
||||
|
||||
两条既有布局断言调整为接受声明间换行,仍检查原选择器和值。首轮测试因单行断言失败,修正后统一验证 409 项测试及前后端构建全部通过。编译及解析等价是本批格式验证依据,未额外重复上批浏览器矩阵。临时核对脚本与报告留在本地 `.git`,未加入产品代码或依赖。
|
||||
|
||||
后续维护继续按组件边界核对后置覆盖和 `:deep` 作用范围。不同值的覆盖及非相邻断点具有顺序意义,不能仅为减少行数搬移;主题功能改写不属于本节点。两份样式的确认冗余项及对应浏览器比较现已完成,记录如下。
|
||||
|
||||
#### 管理样式冗余清理
|
||||
|
||||
删除 58 条被后续同条件、同选择器、同属性、同值及同重要性声明覆盖的早期声明,删除因此产生的空规则,并合并一组相邻的 520px 断点。桌面运维邀请表单及诊断区域的整段重复规则保留最后一份。日志折行注释移至保留规则旁。不同值的覆盖及非相邻断点仍保留,不能仅凭名称相同就移动合并。
|
||||
|
||||
静态核对保留的 1,776 条声明及其顺序不变;全量统一验证一次通过 409 项测试及前后端构建。实际管理页在 320、560、850、1280px 下,对四个路由及明暗主题共 32 组逐元素比较尺寸与 25 项计算样式,结果一致;展开全部服务器设置后,在 320、520、560、850、851、1100、1101、1280px 下另比较 8 组,结果一致且无横向溢出。浏览器日志无警告或错误,临时预览已关闭。该管理批次没有修改客户端 CSS;后续客户端清理结果见下一节。
|
||||
|
||||
#### 客户端样式冗余清理与 06-L 收尾
|
||||
|
||||
删除 116 条相同条件、选择器、属性、值及重要性的早期重复声明,主要涉及重复的工作区头部整段样式、移动端尺寸与滚动、菜单和页脚。删除空规则并合并两组相邻 740px 断点。保留 4,075 条声明的值、条件、选择器及相对顺序,没有更改脚本、模板、皮肤包或测试。统一运行一次全量验证,409 项测试及前后端构建通过。
|
||||
|
||||
浏览器比较 zh/浅色、en/深色、de/ILLUSIA 三组配对,在 320、740、741、980、1201、1280px 下检查首页与连接视图,共 36 组;另在 320、740px 下比较频道、聊天、语音、更多四分区及成员菜单、音频设置弹窗,共 12 组。针对受影响选择器检查尺寸及 37 项计算样式,最终比较一致且无横向溢出,浏览器日志无警告或错误。
|
||||
|
||||
首轮快速采样抓到 QQ 按钮 180ms 尺寸过渡,以及 741px 的响应式控件更新中间态。为排除实际回归,另构建原样式到本地隔离目录,对首页 18 组及临界宽度的三组皮肤补做稳定状态比较;统一移动分区后均一致。该补核没有修改业务逻辑,也没有重复运行全量测试。所有预览进程和标签已关闭,基线及临时记录仅留在本地 .git。
|
||||
|
||||
06-L 的格式及已确认冗余清理完成。不同值的后置覆盖、跨区域样式与非相邻断点继续保留其作用顺序,不将结构更短作为额外目标。剩余验收项以状态表为准。
|
||||
|
||||
### 03 与 02-C 契约和真实媒体
|
||||
|
||||
不另建平行协议类型。用真实连接中的脱敏样本补充现有解析用例,重点核对大整数频道标识、可选字段、未知消息、非法列表项和旧客户端兼容。行为变更单独记录兼容范围。
|
||||
|
||||
协议验收记录至少区分“当前客户端与当前网关”“当前客户端与受支持旧网关”“受支持旧客户端与当前网关”。重点核对 `commandCompleted`、可选的 `channelId` 与 `clientUid`;旧端没有某项能力时明确最低兼容版本或降级行为,不能直接把确认超时判定为消息未送达。只有真实样本暴露不一致时,才形成相应解析或兼容代码修改。
|
||||
|
||||
真实媒体验收至少覆盖 TeamSpeak 3 与 6、WebRTC 与兼容传输、协商失败回退、双向语音、静音与音量、伴奏启停、多人同时发言、频道切换及断线重连。屏幕共享另外验证频道隔离和停止后的资源释放。记录可重现的环境与结果;先由实际失败形成修复项,不预先宣称存在某类网络故障。
|
||||
|
||||
### 09-A 服务端发布与暂缓的 Android 事项
|
||||
|
||||
[mobile/README.md](../mobile/README.md) 保留 Android 已有构建、启动和运行时差异记录。用户明确 Android 暂不纳入修复计划,因此本轮不再推进 07-A、Android 布局或设备验收,也不以这些事项阻塞当前目标。
|
||||
|
||||
若以后恢复 Android 范围,再验收真实 SDK 连接、双向语音、输入输出切换、重连、资源释放及布局;既有构建和首页启动结果不替代这些检查。后台音频、前台服务和原生屏幕共享也保持独立能力范围。
|
||||
|
||||
本轮发布检查范围为 Windows、Linux 和 Docker,现有 CI 与打包工作流已提供干净构建和启动证据。参照 [本地产物说明](LOCAL_ARTIFACTS.zh-CN.md),保留未知用途文件及历史产物,构建输入仅来自声明的源码与依赖。`.local-opus-hook.cjs` 是原样复制缓冲区的实验替身,不作为正式音频验收依据;容器健康检查只证明其检查的 HTTP 启动路径。
|
||||
|
||||
平台记录保留提交号、构建主机与运行时版本、安装与构建命令、产物名称及校验和、启动与媒体结果。Android 的后台音频、前台服务和原生屏幕共享仍是单独的能力范围,不混入本轮代码整理的完成条件。
|
||||
|
||||
## 已完成事项与后续约束
|
||||
|
||||
以下实现已存在,不重复作为待开发任务。各批验证范围保留在文末。
|
||||
|
||||
| 原事项或范围 | 当前状态 |
|
||||
| --- | --- |
|
||||
| 09-A 干净构建 | 本轮 Windows/Linux/Docker 的构建和 HTTP 启动要求已通过;Android 构建与启动结果保留为历史证据,其剩余布局与真机验收暂不纳入本轮 |
|
||||
| 06-L 客户端样式冗余 | 删除 116 条重复声明并合并两组相邻断点;409 项测试和前后端构建、48 组浏览器比较通过 |
|
||||
| 06-L 管理样式冗余 | 删除 58 条重复声明及一组相邻重复断点;409 项测试和前后端构建、40 组浏览器前后对比通过 |
|
||||
| 06-L 保序格式整理 | 20 个模板编译结果等价、脚本原样保留;两份 CSS 规则树等价;409 项测试及前后端构建通过,后续两批规则清理也已完成 |
|
||||
| 06-C 语音成员卡片 | 展示提取完成,409 项测试及 15 组布局抽样通过;状态、共享入口与菜单接线已验证,媒体实测另行保留 |
|
||||
| 06-C 诊断与共享展示 | 三个组件已提取;修复视频重新绑定、全屏空值判断及同昵称归属,409 项测试与 30 组布局抽样通过,真实跨端共享验收保留 |
|
||||
| 06-C 工具栏与私语 | 两个展示组件已提取,修复指针归属并支持键盘按住;隐藏、失焦及释放停止,403 项测试及浏览器接线/布局检查通过 |
|
||||
| 06-C 设置与密码弹窗 | 三个展示组件已提取;修复迟到设置错误及频道密码普通错误后卡等待,新增 8 项回归;398 项测试与 45 组抽样布局检查通过,真实媒体验收另行保留 |
|
||||
| 06-K 管理页导航 | 窄屏改为品牌与退出、四项导航两行布局;五语四路由四宽度共 80 组边界检查通过 |
|
||||
| 06-C 频道成员与菜单 | 两个展示组件已提取;修复移动端误调度及短窗口菜单越界,390 项测试与 45 组边界检查通过;触屏及原生输入框验收仍保留 |
|
||||
| 06-C 加入与聊天 | 两个展示组件已提取;修复开放表单长文案撑宽,表单与聊天共 90 组语言/皮肤/宽度边界检查通过 |
|
||||
| 06-C 管理展示组件 | 三个组件已提取,父页保持状态归属;主要交互和两项实际下载通过,十类管理审计名称已补齐;原生确认验收缺口按用户要求跳过,见前部状态表 |
|
||||
| 06-I、06-J 皮肤生命周期 | 最新选择、页面取消、目录乱序、8 秒等待期限、资源及存储归属已修复;23 项新增测试与本机浏览器检查通过 |
|
||||
| 06-H 身份异步操作及 06-C 身份弹窗 | 24 项时序与资源测试通过,状态与模板分离,关闭按钮定位修正;正常文件读取、错误反馈、焦点和响应式布局已有浏览器验证 |
|
||||
| 04-K、04-L、04-D 消息状态 | 成员快照与增量统一投影,退出清理通知,恢复保留规则及会话范围已有实现;保留响应式数组引用 |
|
||||
| 06-E、06-F 聊天与私聊 | 发送等待确认,失败保留草稿;私聊按身份归属,网关可核对频道与 UID;上一批有状态与浏览器验证记录 |
|
||||
| 06-G 频道层级 | 迭代遍历处理环、重复 ID 和孤儿节点;正常顺序及深层目录已有回归记录 |
|
||||
| 04-E 至 04-J 浏览器媒体、连接与诊断 | 伴奏切换及取消、电平监测、命令等待、凭证取消和诊断来源隔离已有实现;此前验证结果保留于对应章节 |
|
||||
| 05-A 服务端会话音频 | `SessionAudioTransport` 已接入 PCM、WebRTC 和 TeamSpeak 下行,统一路由、背压与统计 |
|
||||
| 05-B、05-C WebRTC 关闭 | 已逐项容错释放资源,重复关闭共享完成 Promise,包括失败结果 |
|
||||
| 02-B 测试入口遗漏 | WebRTC、诊断、身份、皮肤和存储回归均进入统一命令;当前 42 个列出的测试文件均存在 |
|
||||
| 05-D SDK 事件与目录 | `SessionEventCoordinator` 已提取;旧 SDK 来源、关闭等待、重连等待及踢出到达顺序已有实现和回归记录 |
|
||||
| 成员头像 | 下载控制器与 SDK 异步阶段均绑定连接代次;批次、缓存、监听及迟到结果有生命周期限制 |
|
||||
| 前端基础整理 | 共享消息契约、管理请求与三个状态模块、五语管理文案、头部组件及路由延迟加载已实现 |
|
||||
| 浏览器媒体基础 | 远端播放、录音测试、麦克风处理链、设备切换事务及 Android 启动握手已独立实现 |
|
||||
|
||||
原清单记录以下批次的 CI 与 Docker 检查成功:[音频与关闭批次 972ee79](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36819043190)、[头像控制器批次 e9b8c2b](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36819750447)、[SDK 下载边界 cc9714b](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36820095236)。这些链接保留为历史依据,本轮未重新核对,也不替代当前提交的独立验证。
|
||||
|
||||
后续结构调整保留以下约定:
|
||||
|
||||
- 兼容音频为 48 kHz 单声道、20 ms、1,920 字节 PCM;TeamSpeak 下行保留 3 字节头。缓冲、背压和混音参数调整需另有音频依据。
|
||||
- WebSocket 背压阈值保留 4,096 字节;WebRTC 每位说话者最多 4 帧混音队列及 20 ms 调度节拍保持不变。浏览器远端播放保留现有 80 ms 窗口及解码队列限制。
|
||||
- 控制消息错误码、浏览器存储格式、身份占用、一次性凭证、会话上限及共享频道隔离保持兼容。
|
||||
- 服务端各层只解绑所属监听,不删除 WebSocketServer 管理连接集合所需的关闭监听;语音路径不增加逐帧持久化日志。
|
||||
- 保存失败保留草稿;秘密字段保留、替换、删除语义不变。依赖主版本、数据库 schema 和音质参数不与结构整理混在同一批修改。
|
||||
|
||||
## 原实施顺序与验收方式(历史依据)
|
||||
|
||||
以下保留原施工顺序和当时的验收要求。各节点实现及验证结果见前文;用户明确跳过的剩余验收以本页前部范围调整为准,不再作为本轮完成门槛。
|
||||
|
||||
| 顺序 | 内容 | 验收方式 |
|
||||
| --- | --- | --- |
|
||||
| 既有完成 | 06-I、06-J:皮肤激活与启动等待 | 历史记录包含 23 项新增测试与浏览器验证,本轮不重复实施 |
|
||||
| 本批实现 | 06-C、06-K:管理组件及窄屏导航 | 主要交互与 80 组边界检查通过;原生确认及下载类操作保留浏览器验收缺口 |
|
||||
| 随后 | 06-C:其余客户端组件 | 一次拆一个稳定区域;保留业务状态实例,检查主题、皮肤、五语、键盘与窄屏 |
|
||||
| 已完成整理 | 06-L:模板格式、两份页面样式的确认冗余项 | 保留非冗余覆盖顺序;后续业务修改继续维护现有边界 |
|
||||
| 联调阶段 | 03:契约兼容核对 | 收集脱敏真实消息;分别记录新旧客户端与网关组合的确认和目标校验行为 |
|
||||
| 联调阶段 | 02-C:真实 TeamSpeak | 使用用户指定服务器,先解决接入无回包条件,再记录协议与媒体实际结果 |
|
||||
| 已完成 | 09-A:Windows/Linux/Docker 干净构建与启动 | 已有产物和启动记录;Android 范围按用户要求暂缓 |
|
||||
|
||||
本节点统一执行一次 `npm run verify`,385 项测试及前后端构建通过。后续把同节点的相关修复合并后验证;新增测试文件纳入显式入口,后续改动或失败有必要时才重复完整检查。浏览器布局、真实媒体及平台验收单独记录,不能由类型检查或单元测试代替。真实环境记录至少包含提交、服务端与客户端版本、设备、传输方式、操作步骤、预期、实际结果及未通过原因。不要把纯结构调整与依赖主版本升级、数据库迁移或音质参数调整合并实施。
|
||||
|
||||
## 历史记录说明
|
||||
|
||||
以下保留此前批次的实施过程、只读整理及验证结果,用于追溯。各节中的“本批”“当前”及文件行号对应当时记录,不应覆盖前部待办表和本轮基线;历史测试、浏览器和 CI 结果均不表示本轮重新执行。
|
||||
|
||||
## 皮肤生命周期修复结果
|
||||
|
||||
### 06-I 皮肤异步激活归属
|
||||
|
||||
施工前,[skin-runtime.ts](../web/src/services/skin-runtime.ts#L36) 在本地读取、下载和包解析后直接修改样式及存储。五项用例先复现:慢自定义皮肤覆盖新的内置选择、旧下载失败回退覆盖新皮肤、清理后旧读取重新生效、页面取消后仍提交,以及旧目录重新启用已被新目录禁用的皮肤。
|
||||
|
||||
已实施:运行时按最新激活拥有提交权,目录请求有独立的同类归属;请求替换和外部取消立即结束等待,不能取消的底层操作也不能迟到提交。已失效调用不能取消下一页面的激活。失败安装释放候选对象 URL,正常替换后才释放旧资源。
|
||||
|
||||
主页与演示页共用 [usePublicSkin.ts](../web/src/composables/usePublicSkin.ts),所有初始化、手动选择、恢复回退和本地数据清理均由所属页面管理。卸载使旧操作失效;皮肤内容、选择标识及偏好只接受当前结果。去除两页重复的无归属版本刷新路径,正常加载仍核对目录版本与实例默认值。
|
||||
|
||||
缓存写入和偏好保存传递所属取消信号。本地数据库打开后再次检查信号,写事务期间可以取消;存储操作在事务完成时才报告成功。偏好读取和合并改在同一事务内完成,避免皮肤写入覆盖并发修改的其他设置。没有调整存储 schema 或已有键名。
|
||||
|
||||
### 06-J 皮肤启动期限与回退
|
||||
|
||||
已实施:[skin-operation.ts](../web/src/services/skin-operation.ts) 提供统一等待与取消,页面初始化默认总期限为 8 秒,覆盖偏好读取、目录、响应体、皮肤包及激活。目录与激活独立调用同样有期限。超时先使旧链失效,再显示可用内置主题,避免整页继续隐藏;显式皮肤偏好保留供下次重试。
|
||||
|
||||
正常网络下保留实例默认皮肤、已禁用皮肤过滤和缓存版本更新。页面不再重复发起同一版本的无归属刷新;后来的选择不能被启动响应覆盖。清理本地数据时先取消旧操作,再清理存储和重置外观,目录刷新失败不阻止页面使用。
|
||||
|
||||
验证:[skin-lifecycle.test.mjs](../web/test/skin-lifecycle.test.mjs) 的 17 项用例覆盖旧结果、目录乱序、本地读取与响应体挂起、页面退出、初始默认值、重置和候选 URL 清理;[local-persistence.test.ts](../web/src/services/local-persistence.test.ts) 的 6 项用例覆盖延迟打开、事务取消、提交确认和偏好合并。共 23 项新增用例均通过。
|
||||
|
||||
浏览器通过真实 HTTP 接口人为保持目录和皮肤包响应未完成,检查页面恢复和请求中止;取消旧下载后刷新仍为新的内置选择。正常加载 ILLUSIA 皮肤并进入演示页,内容和外观恢复成功,未发现浏览器错误日志。网络和数据库边界测试不替代真实媒体与设备验收。
|
||||
|
||||
## 身份导入与组件拆分实施
|
||||
|
||||
### 06-H 身份文件读取的异步归属
|
||||
|
||||
原入口为 `28eda60` 中的 `WebClient.vue` 文件读取、弹窗开关与卸载函数。当前实现见 [useWebClientIdentity.ts](../web/src/composables/useWebClientIdentity.ts) 与 [IdentityImportDialog.vue](../web/src/components/web-client/IdentityImportDialog.vue)。
|
||||
|
||||
修改前,`readIdentityFile` 等待 `file.arrayBuffer()` 后直接写入导入文本或错误,没有读取序号、弹窗代次或页面失效检查。文件读取也不设置 `identityImportBusy`;该标志用于点击导入后的解析阶段,不能阻止读取中的关闭操作。以下时序已通过可控制返回顺序的用例复现:
|
||||
|
||||
- 先选文件 A,再选文件 B;若 A 最后返回,会覆盖 B 的文本,A 的迟到失败也可能覆盖当前错误状态。
|
||||
- 读取期间关闭并重新打开弹窗;旧读取可能把上一次的内容写进新弹窗。
|
||||
- 读取期间手动编辑文本;旧读取完成后可能覆盖刚输入的内容。
|
||||
|
||||
已实施:状态模块统一持有操作代次,新的选择、文本修改、关闭、进入房间、清除本地数据或页面卸载使旧结果失效。文件仍在读取时不能提交旧文本;解析只提交所属草稿,失败保留输入。展示组件只接收文本、状态与文案并发出操作事件,文件输入和焦点归组件管理。
|
||||
|
||||
保留 128 KiB 文件限制、UTF-8 与带 BOM 的 UTF-16 解码、身份格式校验和五语提示。解析期间维持不允许关闭的行为,同时禁用编辑与文件选择。导出等待绑定当前身份与页面,重复点击合并,迟到结果不下载;锚点、对象 URL 和计时器分别释放。启动身份读取同样检查修订,不能覆盖新导入、已取消的记忆偏好或清理后的状态。
|
||||
|
||||
验证:[identity-dialog.test.mjs](../web/test/identity-dialog.test.mjs) 的 24 项测试覆盖上述时序、格式读取、正常提交、解析失败、导出与 URL 清理、启动恢复;其中 10 项先失败后通过。既有格式测试继续保留。浏览器实际选择 UTF-16 测试文件并验证错误反馈、保留文本、关闭和重开;桌面及窄屏对比发现原关闭按钮位于屏幕右上角,现定位于弹窗内。没有把该批验证扩展解释为真实 TeamSpeak 或 Android 验收。
|
||||
|
||||
## 上一批状态与聊天修复
|
||||
|
||||
以下问题描述与带行号的原入口引用对应上一批施工前基线 `a97fa54`;本节“本批”均指该历史批次。成员与消息的当前实现见 [session-state.ts](../web/src/voice/session-state.ts),聊天交互见 [useWebClientChat.ts](../web/src/composables/useWebClientChat.ts)。
|
||||
|
||||
### 04-K 统一成员目录更新
|
||||
|
||||
依据:[前端消息分支](../web/src/composables/useVoiceWebSocket.ts#L1072)、[服务端成员更新](../src/server/session-events.ts#L121)、[私聊名称](../web/src/composables/useWebClientChat.ts#L50)及[私语目标](../web/src/composables/useWebClientChannels.ts#L133)。
|
||||
|
||||
修改前,服务端收到成员更新后发布 `channelList`;浏览器只替换 `channels`,不更新扁平 `members`,导致频道树与私聊、私语名称不同步。进入事件丢失部分状态,离开事件也未立即移除频道副本。
|
||||
|
||||
已实施:消息模块拥有响应式数组,频道引用同一份成员数据;完整快照替换目录,旧网关省略成员时保留未知部分。进入更新全部已提供字段;离开同时清理各投影、播放、发言、临时音量和私语目标。UID 改变不继承旧成员音量,按 UID 保存的用户偏好仍保留。头像继续核对 UID。
|
||||
|
||||
验收:改名、静音、离开、再次进入、头像迟到、重复进入,以及省略成员字段的兼容消息;各处名称与状态一致,旧会话事件不能写入新会话。
|
||||
|
||||
### 06-E 明确聊天发送结果并保留失败草稿
|
||||
|
||||
依据:[命令发送](../web/src/voice/commands.ts#L19)、[聊天发送入口](../web/src/composables/useVoiceWebSocket.ts#L1266)、[提交草稿](../web/src/composables/useWebClientChat.ts#L99)及[发送按钮](../web/src/views/WebClient.vue#L255)。
|
||||
|
||||
修改前,普通命令在 socket 未打开时直接返回,聊天入口仍追加消息并清空草稿。重连期间界面允许提交,服务端拒绝也没有与本地消息关联的确认。
|
||||
|
||||
已实施:三个聊天动作返回 Promise,等待现有 `commandCompleted` 后才追加成功消息。未连接时拒绝发送;网关在恢复期间拒绝命令时保留 `requestId`。草稿、等待和错误按聊天对象隔离;切换标签再返回不能重复提交在途消息,确认只清理已提交且未被修改的草稿。退出或卸载使旧反馈失效。五语提示区分等待、对象失效、频道变化和发送未确认;超时可能已送达,提示核对后再重试,不声称对方已读。
|
||||
|
||||
频道消息新增可选 `channelId`,网关在调用 SDK 前核对实际频道,避免频道切换失败后把显示在目标频道的消息发到旧频道。旧客户端省略该字段时保留原行为。
|
||||
|
||||
验收:socket 关闭、TeamSpeak 重连、成员离线、服务端拒绝、超时、重复点击和等待期间继续输入;失败不伪装为成功,成功仅出现一次,本人回显不重复。保留现有 500 字符限制和五语提示。
|
||||
|
||||
### 06-F 将私聊目标绑定到所属会话
|
||||
|
||||
依据:[私聊状态与发送](../web/src/composables/useWebClientChat.ts#L45)、[连接动作](../web/src/composables/useWebClientConnection.ts#L90)及[页面组装](../web/src/views/WebClient.vue#L862)。
|
||||
|
||||
修改前,私聊选择与草稿未随退出重置,历史只按数字 ID 分组。编号复用可使旧私聊自动对应新成员;本批已用跨服务器和同服务器替换场景复现。
|
||||
|
||||
已实施:退出或目标替换清理选择和全部草稿;同一连接内按私聊身份保存草稿。历史带浏览器本地 `conversationKey` 和对方名称快照;有 UID 时按 UID 识别,旧网关无 UID 时按成员生命周期分配范围,离开或重连重新分配。未知发送者与后来出现的同编号成员不合并。离线历史仍可查看,不能向已变更身份的目标继续发送。
|
||||
|
||||
私聊命令新增可选 `clientUid`;浏览器提交当前选定身份,网关在调用 SDK 前核对,防止请求途中发生编号复用。省略字段的旧客户端仍可使用现有协议,但没有该新增校验;旧网关是否支持确认及目标校验纳入事项 03 的兼容验收。
|
||||
|
||||
验收:服务器 A 和 B 都有编号相同的成员、同服务器内编号复用、目标离线,以及重连前后编号改变;旧选择不能自动指向新对象,其他会话的草稿不会出现在当前私聊。
|
||||
|
||||
### 04-L 统一会话通知清理规则
|
||||
|
||||
依据:[断开处理](../web/src/composables/useVoiceWebSocket.ts#L982)、[连接成功及事件处理](../web/src/composables/useVoiceWebSocket.ts#L1052)和[通知展示](../web/src/views/WebClient.vue#L933)。
|
||||
|
||||
修改前,显式断开没有清空事件和戳一戳通知;成功连接虽然替换事件,仍会展示旧通知。本批通过退出与替换目标用例复现。
|
||||
|
||||
已实施:消息状态与媒体释放保持独立,所有列表保留响应式引用。
|
||||
|
||||
| 场景 | 当前规则 |
|
||||
| --- | --- |
|
||||
| 显式退出、更换目标、普通 socket 关闭 | 清空目录、聊天、事件及通知,重置页面聊天选择和草稿 |
|
||||
| 同 socket 的 TeamSpeak 恢复等待 | 保留历史供查看,媒体和待确认命令释放,禁止发送 |
|
||||
| 恢复成功 | 替换成员、清除旧频道等待新快照、替换事件、清除通知;保留聊天历史,重新核对私聊身份 |
|
||||
| 恢复最终失败 | 保留失败面板及历史,禁止发送;后续重试连接或退出按新会话重置 |
|
||||
|
||||
验收:收到通知后退出、换服、重连成功或失败;旧通知不出现在新服务器,恢复目录和事件时不重复触发提示音。保留已存身份和用户音频偏好的现有语义。
|
||||
|
||||
### 06-G 防止异常频道层级导致递归失控
|
||||
|
||||
依据:[频道树遍历](../web/src/composables/useWebClientChannels.ts#L30)与[频道消息校验](../src/shared/server-messages.ts#L59)。
|
||||
|
||||
修改前,父子遍历 `visit` 没有访问保护。共享解析器允许形状有效但父子成环的目录,本批自环与双节点环用例实际触发栈溢出;不推定正常 TeamSpeak 一定产生这种目录。
|
||||
|
||||
已实施:父子及兄弟顺序都使用迭代遍历;重复 ID 保留第一项,缺少父节点的频道作为根,孤立环从其第一项展开,每个 ID 至多输出一次。深度由实际输出层级计算,不改变共享解析器的兼容范围。正常前驱顺序和 5,000 层目录用例通过。
|
||||
|
||||
验收:自环、双节点环、孤儿节点、重复 ID、深层目录,以及正常兄弟顺序;输出可终止、节点不重复、页面仍可操作。
|
||||
|
||||
## 连接与命令问题的修复结果
|
||||
|
||||
本节及后续“近期修复”记载此前已实施的工作;其中的“本批”指对应历史批次。本轮未重做这些修复,统一测试继续覆盖已有回归。
|
||||
|
||||
### 04-H 命令发送异常立即清理等待资源
|
||||
|
||||
当前实现:[commands.ts](../web/src/voice/commands.ts)。原入口先创建默认 8 秒计时器、登记等待,再发送命令。同步发送抛错后 Promise 拒绝,但登记和计时器未立即清理。本批通过发送故障注入复现该缺口。
|
||||
|
||||
已实施:每条命令拥有统一且幂等的结束函数,成功、服务端错误、发送异常、超时及断开都通过它清理。确认等待绑定原 socket 与连接代次,保留默认 8 秒期限、共享命令类型和现有调用接口。
|
||||
|
||||
已验证:正常确认、服务端拒绝及错误码、发送抛错、超时、断开、重复回复、已排队的旧期限和旧 socket 回复;发送失败后计时器立即移除,旧操作不影响替代连接的命令。
|
||||
|
||||
### 04-I 加入凭证请求可取消且等待有期限
|
||||
|
||||
当前实现:[connection.ts](../web/src/voice/connection.ts)。原请求只有代次检查,没有取消信号和应用层期限;请求或响应体迟迟不返回时,页面持续处于连接中。原 socket 关闭异常还会跳过后续页面状态清理。本批已通过边界替身复现。
|
||||
|
||||
已实施:连接控制器持有取消器、15 秒期限、socket 和连接代次。期限覆盖偏好就绪、HTTP 请求及响应体;新连接和断开立即取消旧请求,旧期限与迟到响应不能写回。socket 关闭前解绑所属监听,关闭异常不妨碍其余状态清理。超时用 `REQUEST_TIMEOUT` 和五语提示说明网关等待失败。
|
||||
|
||||
已验证:请求无响应、响应体挂起、主动取消、连续连接不同目标、取消后迟到成功或失败、旧期限、socket 关闭异常和网关关闭码。邀请、身份、频道、密码和中继参数保持一致。浏览器取消不撤销服务端已执行的邀请使用或凭证签发,服务端的有效期和一次性使用规则保持不变。
|
||||
|
||||
### WebRTC 与诊断实现的验证结果
|
||||
|
||||
[webrtc-transport.ts](../web/src/voice/webrtc-transport.ts) 已集中 peer、输入混音、电平监测、ICE 等待、answer 期限和兼容回退;[webrtc-playback.ts](../web/src/voice/webrtc-playback.ts) 已集中播放元素、播放中的 Promise 和用户手势重试监听。原始麦克风和 PCM 由采集层管理,控制 socket 由连接模块管理,入口负责组装。
|
||||
|
||||
诊断请求现由采样模块管理,保留等待期限直至网关和浏览器统计均返回,并检查原 socket、连接与传输代次和 peer;断开立即结束消费者等待。清理异常、旧播放重试、旧协商期限、回退信令失败、统计挂起、替换 peer 和诊断发送失败均已纳入 [voice-session.test.mjs](../web/test/voice-session.test.mjs),当前全部通过。此处验证浏览器边界行为,不等同于真实网络媒体验收。
|
||||
|
||||
### 04-J 诊断采样与展示只比较同一来源
|
||||
|
||||
当前实现:[audio-diagnostics.ts](../web/src/voice/audio-diagnostics.ts) 与 [useWebClientPerformance.ts](../web/src/composables/useWebClientPerformance.ts)。原面板直接相减前后样本中的下行计数,来源可能分别为 RTP 包、兼容音频帧或网关发送帧。peer 替换后新计数若大于旧值,也会被误当成同一流的增长。采样失败时保留旧活动状态,已排队的旧轮询会设置运行标志却无法清除;卸载后手动刷新仍能发起请求。
|
||||
|
||||
已实施:采样模块拥有等待登记、总期限、兼容计数和浏览器统计。样本携带仅用于浏览器内部的 `scopeId`,不修改网关协议;连接或传输变化以及会话释放会使范围失效。兼容计数随会话重置,旧快照保持独立。面板只比较相同范围、传输和下行计数来源;缺失或拒绝的采样清除旧状态,下一样本重新建立基线。轮询开始前与结果返回后均校验代次,卸载同时禁止旧回调和手动刷新。
|
||||
|
||||
[W3C WebRTC 统计定义](https://www.w3.org/TR/webrtc-stats/#dom-rtcsentrtpstreamstats-packetssent) 将 `packetsSent` 定义为已发送包总数。据此,上行丢包估算分母使用发送数,不再重复加上丢失数;下行仍以接收数加丢失数计算。浏览器提供的 `fractionLost` 用于采样中的上行百分比,否则按计数估算。RTCP 反馈和本地计数采样时间可能不同,不能将该估算表述为精确网络测量。
|
||||
|
||||
已验证:10 项实际 Vue 状态用例,其中 8 项先失败后通过;语音会话新增 3 项范围与重连用例并增强 1 项丢包率断言,均先失败后通过。保留每 2 秒轮询、采样总期限和已有音频状态提示。并行运行时发现 Vite 即使关闭 HMR 仍监听默认 WebSocket 端口,三个无界面测试入口现同时设置 `ws: false`,无需占用该端口。
|
||||
|
||||
## 近期修复的浏览器媒体问题
|
||||
|
||||
### 04-E 保留可用发送链并完整清理失败候选
|
||||
|
||||
修改前位置:`c9740c4` 中 [useVoiceWebSocket.ts](../web/src/composables/useVoiceWebSocket.ts) 的混音创建、替换和伴奏启停函数,原第 752–918 行。当前实现位于 [webrtc-input.ts](../web/src/voice/webrtc-input.ts) 和 [accompaniment.ts](../web/src/voice/accompaniment.ts)。
|
||||
|
||||
原实现的顺序及缺口:
|
||||
|
||||
- `createWebRtcMixStream` 先调用 `stopWebRtcMix`,其中会停止当前输出音轨;之后才创建新节点并调用 `sender.replaceTrack`。创建或替换失败时,旧音轨已经结束,没有可用旧链供回滚。
|
||||
- 更换伴奏时,在混音接入成功前就停止旧伴奏,并发送 `active: true`。失败后再发送 `false`,无法保留原本正常的伴奏;错误统一归为 `permission`,也不能区分用户授权与音频处理失败。
|
||||
- 混音节点先在局部变量中创建,之后才写入清理函数使用的引用;如果中途创建或连接失败,已取得的候选节点及输出音轨缺少完整释放路径。
|
||||
- 停止伴奏也会重建整个混音并替换发送轨道,因而停止操作同样依赖新节点分配成功。
|
||||
|
||||
本批通过故障注入实际复现旧发送轨道结束、旧伴奏丢失、部分节点及输出音轨未释放、停止依赖新分配,以及混音节点释放异常中断会话清理。测试使用实际 composable 和浏览器边界替身,不代表已测真实浏览器的故障频率或音质。
|
||||
|
||||
已实施:每个 WebRTC peer 保持稳定输出轨道,仅接入或移除伴奏源;新源连接成功后再解除旧源并停止旧采集。混音模块拥有节点和输出流,独立释放部分分配及关闭资源。只有接入成功后才更新活动状态;音频处理失败使用独立错误码和五语提示,可选内容提示失败不再遗留采集。
|
||||
|
||||
已验证:节点分配或连接失败保留原麦克风输出与旧伴奏;启停伴奏不结束或替换发送轨道;停止不依赖新输出分配;候选失败和重复清理释放所属资源。麦克风静音和音量设置在启停期间保持有效,伴奏不经过麦克风降噪与增益,也不额外添加固定衰减。
|
||||
|
||||
### 04-F 停止操作立即释放已取得的候选采集
|
||||
|
||||
位置:[accompaniment.ts](../web/src/voice/accompaniment.ts),由语音入口调用;回归位于 [voice-session.test.mjs](../web/test/voice-session.test.mjs)。以下描述修改前的行为。
|
||||
|
||||
`getDisplayMedia` 返回后,候选 `nextStream` 在等待 `applyConstraints` 期间仍是局部变量。停止或断开只清理已提交的 `accompanimentStream` 并使代次失效;候选流需等约束 Promise 结束,执行后续失效检查才被停止。现有取消用例也是先结束约束等待,再断言音轨已停止,没有覆盖立即释放。
|
||||
|
||||
此外,音轨的 `ended` 监听在约束等待后才注册,提交前也没有检查 `readyState`。若用户在等待期间结束采集,代码仍可能将已结束的音轨标记为活动。
|
||||
|
||||
已实施:伴奏控制器同时拥有当前流和已取得但未提交的候选流。停止、断开或新操作取代旧操作时,立即释放候选资源;仍未返回的授权请求在结果到达时立即释放。操作绑定原混音目标与代次,提交前复核目标和音轨状态,旧结束事件不能停止新采集。
|
||||
|
||||
已验证:约束 Promise 未完成时音轨已经停止;等待期间结束采集不会发送活动状态;迟到授权和旧失败不影响新伴奏。现有四项伴奏用例继续保留,其中取消用例增加立即释放断言;另验证无音频来源失败保留旧伴奏、断开清除旧错误,以及采集处理约束与五语错误映射。
|
||||
|
||||
### 04-G 电平监测失败不影响语音与后续连接
|
||||
|
||||
位置:[microphone-meter.ts](../web/src/voice/microphone-meter.ts),由语音入口的监测启停函数组装。
|
||||
|
||||
原实现只在全部节点连接完成后才记录清理引用,分析器分配或连接失败会遗留先前创建的节点。计时器回调读取全局分析器引用,已排队的旧回调会读取替代连接的分析器并更新电平;读取异常没有受控处理,释放异常也可能中断 peer 和麦克风清理。五项故障用例均在修复前复现。
|
||||
|
||||
已实施:每个监测实例独立拥有节点与计时器,停止先使回调失效,再逐项释放资源。准备或读取失败只停止电平监测,清除电平与发言提示,保留麦克风流和语音 peer。已验证 512 点采样、50 ms 周期、原有 RMS 电平比例及上限保持一致;此处不声称真实设备的电平与音质已验收。
|
||||
|
||||
## 本批施工前的只读整理结果
|
||||
|
||||
- 以 `cdc5f03` 和当前工作区为依据,核对模块职责、文件规模、36 个测试入口及既有打包流程。
|
||||
- 新增 06-I 皮肤异步激活归属、06-J 首屏等待期限两项待修改问题,说明静态依据、触发顺序、修改方向和验收条件,未声称已经复现。
|
||||
- 将管理页三组件由“待提取”改为“工作区已有、待验收”,列明样式边界和真实模板交互检查;保留客户端拆分、协议、媒体、Android 和发布待办。
|
||||
- 保留历史实施记录;此次仅修改本文,开始时已有的业务代码与测试改动保持原样。
|
||||
|
||||
## 身份模块施工前的只读整理结果
|
||||
|
||||
- 以 `28eda60` 为基线更新当前结构与剩余待办,区分静态判断、待验收项目和历史验证结果。
|
||||
- 新增 06-H 身份文件异步覆盖问题,细化 06-C 的组件职责、状态归属、样式和交互验证方向。
|
||||
- 保留既有修复记录;只修改本文,未修改业务代码、测试、配置、依赖和本地产物,未运行测试或构建,未提交或推送。
|
||||
|
||||
## 本批施工前的只读整理记录
|
||||
|
||||
- 基于 `a97fa54` 更新当前基线,核对模块职责、入口规模和 35 个显式测试文件的存在性。
|
||||
- 新增五项待修改问题,写明源码依据、触发条件、大致修改方向和验收要求;按用户交互问题、生命周期、结构拆分和真实环境安排后续顺序。
|
||||
- 将已实施的 04-E 至 04-J 移出剩余待办表,保留历史实现及测试结果,避免重复施工。
|
||||
- 本轮仅修改本文;未修改业务代码、测试、配置或依赖,未运行测试和构建,未删除产物,未提交或推送。
|
||||
|
||||
## 连接与命令实施前的只读整理结果
|
||||
|
||||
- 更新当前提交、工作区状态、模块职责和文件规模,保留既有实现与验证记录。
|
||||
- 新增命令发送异常清理、加入凭证取消与期限两项待修改问题,注明静态依据、修改方向及验收条件。
|
||||
- 将已有 WebRTC 拆分列为待核对实现,按连接与命令、页面组件、真实环境和发布整理后续顺序。
|
||||
- 该轮仅修改本文;原有源码与测试改动保留,未新增代码修改、测试运行、构建、提交或推送。其后的施工与验证见本批实施记录。
|
||||
|
||||
## 前轮只记录的整理结果
|
||||
|
||||
- 更新到 `c9740c4` 的干净代码基线,整理当前模块边界及已完成事项。
|
||||
- 新增伴奏混音失败回滚和候选采集取消的具体待办,注明静态依据、建议方案与验收条件。
|
||||
- 明确前端拆分、页面整理、契约、真机及发布的后续方向,保留下方历史实施记录。
|
||||
- 仅修改本文;未修改源码、测试、配置或依赖,未运行测试和构建,未删除产物,未提交或推送。
|
||||
|
||||
## 已有实施与验证记录
|
||||
|
||||
以下保留实施与验证记录,段落内“本批”指该批次。旧结果仅适用于各自提交或快照;播放、录音及设备验证见各自条目。Android 预览及首次清单提交为 `0276b6e`;第一批构建、测试及文档修正记录对应 `5c11bd9`。
|
||||
|
||||
| 事项 | 已实施内容 | 验证依据 |
|
||||
| --- | --- | --- |
|
||||
| 01 | 新增 `npm run verify`;根目录前端构建包含类型检查;CI 覆盖 `dev`、`master`、PR 和手动运行;镜像及发布包工作流先调用同一验证工作流 | 本地完整验证成功;`5c11bd9` 的远端 `verify` 和 `docker-smoke` 均已通过 |
|
||||
| 02 | 新增凭证、身份占用、会话状态与清理、目录同步、重连策略等 5 个测试文件,共 18 项测试 | 单元测试由 33 项增加至 51 项,全部通过 |
|
||||
| 02 发现的问题 | 离开成员可能被迟到的分段快照重新加入目录;记录离开状态,直到明确重新进入或连接目录重置 | 回归测试先复现失败,修复后通过;同时覆盖迟到更新、重新进入和目录重置 |
|
||||
| 08 | 更新 `CLAUDE.md` 的协议、音频、配置、容量、构建及 Android 边界说明 | 对照入口、SDK 适配、配置导入、常量及工作流核对 |
|
||||
|
||||
第一批本地验证环境为 Windows、Node.js 24.12.0,执行过 `npm run verify`,包含 51 项单元测试、后端 TypeScript 编译及前端类型检查和生产构建。随后共享协议迁移增加了 7 项测试,当时 58 项测试及前后端构建通过。该阶段前端存在单个产物超过 500 kB 的提示;本批路由分包后的结果见事项 06。
|
||||
|
||||
此前记录的[提交 `5c11bd9` 的 GitHub Actions](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36796987777) 已完成并成功,包括 Node.js 22.22.2 下的测试与构建、Docker 镜像构建和容器 HTTP 健康检查。该结果不覆盖随后新增的共享协议和媒体改动;后续提交需重新通过 CI。
|
||||
|
||||
### 共享协议与前端生命周期实施记录
|
||||
|
||||
- 对应提交 `ab4ad48` 已推送至 `dev`;[远端 CI](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36799503102) 的验证、Docker 构建和容器健康检查均通过。
|
||||
- 共享命令、服务端消息、屏幕共享模型和皮肤目录类型集中到 `src/shared/`;服务端发送与前端接收均接入公共契约。
|
||||
- 屏幕共享控制器只依赖传输状态与发送接口,自行管理采集音轨、PeerConnection、ICE 配置、协商计时器和统计。
|
||||
- 新增 11 项前端测试。其中 9 项先复现了失败:旧 socket 污染新成员列表、异常断开未停止共享、断开后获批的共享采集未释放、取消后协商仍发送信令、旧开始确认干扰新采集、旧授权结果覆盖新采集参数、缺少视频轨时其他轨道未释放,以及麦克风授权迟到和旧授权阻塞新会话。
|
||||
- 本地 `npm run verify` 通过:69 项测试、后端编译、前端类型检查及生产构建;开发服务器实际请求确认共享协议与屏幕共享模块可返回成功响应。Vite 依赖扫描限定为网页入口,避免扫描 Android 生成页面。
|
||||
- 尚未完成真实 TeamSpeak 双向音频、WebRTC 语音回退、浏览器实际媒体连接、Android 真机及各平台发布包验证。此处的模拟边界测试只证明相应状态和资源生命周期行为。
|
||||
|
||||
### 服务端桥接拆分实施记录
|
||||
|
||||
- 对应提交 `254bc4b`;[远端 CI](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36800632198) 的测试、构建、Docker 构建和容器健康检查均已确认成功。
|
||||
- 拆出命令处理、目录展示、音频统计和屏幕共享协调四个模块,入口保留会话组装职责;原有统计类型导出保持兼容。
|
||||
- 新增 20 项测试,其中 7 项先复现失败后修复:统计快照共享实时对象、结构化权限错误映射遗漏、其他成员换频道误停共享、跨服务器客户端 ID 混用、重复或迟到的原生发布通知生成多余共享、最后会话离开后发现状态未重置,以及旧加入失败移除新观看关系。
|
||||
- TeamSpeak 连接中断时清理共享关系;原生源频道从当前服务器目录确定,无法确认所属频道时不猜测广播范围。
|
||||
- 本地 `npm run verify` 通过:89 项测试、后端编译、前端类型检查及生产构建。该提交远端 CI 已通过,真实媒体联调仍待验证。
|
||||
|
||||
### 媒体协商与平台启动实施记录
|
||||
|
||||
- 对应提交 `8138969`;本批再次查询确认其[远端 CI](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36804423805) 的验证、Docker 构建和健康检查成功。以下其余内容为该批次已有记录。
|
||||
- 前端新增 14 项、服务端桥接新增 8 项行为测试;其中 15 项在修改前实际复现失败,修复后通过。取消后的采集、协商、播放及服务端音频回调不再修改新会话。
|
||||
- 协商失败和音轨挂载失败均可回到兼容采集,测试验证实际发送 1,920 字节 PCM 帧,并且不会错误报告麦克风故障。此处未使用真实网络媒体连接。
|
||||
- Android 启动已独立到 `web/src/platform/`,7 项启动测试通过。错误、超时和取消统一清理监听器及计时器,重试仅重做健康握手。
|
||||
- 忽略规则和本地产物说明已整理;代表性发布包、缓存和实验编解码脚本被忽略,共享协议、平台源码、Android Java、Gradle wrapper 和皮肤资源仍可跟踪。
|
||||
- 该批次本地 `npm run verify` 完整通过,共 118 项测试。额外使用真实原生 Opus 将 1,920 字节 PCM 编为 202 字节并解回 1,920 字节,未使用实验替身;这只证明本机编解码路径可运行。
|
||||
- Android 资源打包、Capacitor 同步及 `assembleDebug` 通过,生成 arm64-v8a、armeabi-v7a 和 x86_64 三种 APK。x86_64 APK 在 Android 15 只读模拟器安装、冷启动成功,`/health` 返回 `webspeak-android`,公共配置返回 `mobile: true`,截图确认 WebView 已显示首页。窄屏头部重叠已列入事项 06;真实 TeamSpeak、Android 真机和后台音频仍未验收。
|
||||
|
||||
### 前轮只读文档核对记录
|
||||
|
||||
- 只读取 Git 状态、提交记录、相关源码、测试定义、构建脚本和已有文档,更新本清单。
|
||||
- 修正基线、文件规模和状态:Android 启动及忽略规则已提交;WebRTC 契约、管理页文案、头部组件和路由延迟加载已有未提交实现。
|
||||
- 新增路由全局样式隔离缺口及布局待验收事项,明确后续顺序、模块边界和完成条件。
|
||||
- 未执行代码修复、测试或构建,未删除产物,未提交或推送。后续实施需以新的验证结果更新状态。
|
||||
|
||||
### 共享契约与页面请求层实施记录
|
||||
|
||||
- 对应提交 `9bfe4b9`;本批重新查询确认其 [CI](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36808150705) 的应用验证、Docker 构建和健康检查成功。
|
||||
|
||||
- 完成 WebRTC 控制契约与 SDP 校验统一,新增 3 项兼容和边界测试。
|
||||
- 管理输入与响应模型集中到共享目录;新增 8 项请求层用例和 1 项真实 HTTP 集成用例,临时数据库覆盖配置、密码和中继令牌动作、邀请、登录状态及 SQLite 备份。未连接外部 TeamSpeak 服务。
|
||||
- 管理页文案、样式、网络请求及首页头部独立成模块,路由改为延迟加载。修复头部窄屏分行、长品牌名溢出、状态圆点、管理样式路由限制及暗色选择框。
|
||||
- 本地 130 项测试、后端编译、前端类型检查和生产构建通过。最后的样式与错误反馈调整再次通过前端构建;浏览器用隔离的本机测试数据验证保存失败和成功、登录过期、退出失败以及管理页面展示。
|
||||
- 该批没有重做真实语音、Android 设备和跨平台发布包验收,也没有完成 04、05 和 06 的所有剩余拆分。
|
||||
|
||||
### 前轮只读梳理补充记录
|
||||
|
||||
- 核对 Git 状态、主要模块、测试定义、构建与发布工作流,以及现有文档;更新本文的基线、待办、修改方向与验收要求。
|
||||
- 记录远端播放迁移的旧函数引用,补充录音、设备切换、管理请求竞态、剩余文案及平台文档状态等待办。
|
||||
- 仅更新本文;未修改业务代码、测试、配置或依赖,未运行测试与构建,未提交或推送。已有未提交源码继续保留。
|
||||
|
||||
### 远端播放与录音测试实施记录
|
||||
|
||||
- 对应提交 `ad83c87`;[远端 CI](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36809738335) 的应用验证、Docker 构建和健康检查已确认成功。
|
||||
- 远端播放控制器统一拥有每位成员的解码器、播放源、增益节点和排队时间;重置、失败和成员退出都释放所属资源,旧回调不能清理替代资源。
|
||||
- 修复提取过程中遗漏的成员退出调用点。该用例先复现成员无法移除,修复后验证只停止离开者的音频。
|
||||
- 录音测试独立管理操作身份、录音器、五秒期限与试听 URL。六项录音问题先复现失败后修复:断开未停止、连续启动未停止旧录音、旧权限错误清除新状态、取消后仍创建录音器、自然结束仍显示活动,以及启动失败遗留采集。
|
||||
- 相对起始提交新增 19 项测试。当前 149 项测试、后端编译、前端类型检查和生产构建通过;录音与解码使用浏览器边界替身,未声称真实音质或设备兼容性已通过。
|
||||
- 输入输出设备切换、管理请求竞态、剩余模块提取、真实 TeamSpeak、Android 真机与各平台发布包仍待完成,持续目标保持未完成。
|
||||
|
||||
### 设备切换与采集连续性实施记录
|
||||
|
||||
- 输入设备和降噪设置共用配置操作,只有当前操作能够提交或回滚,持久化保存最后成功的选择。麦克风授权失败保留原有 WebRTC peer 和采集流。
|
||||
- 输出切换按 AudioContext 或音频元素分别串行执行;断开后跳过排队任务,旧端点回调不能设置新端点。某个端点拒绝时尝试恢复先前输出。
|
||||
- 设备列表只采用当前查询结果;迟到的成功或失败不能覆盖新列表,或在断开后恢复错误提示。
|
||||
- 分离采集申请与已运行处理链的失效标识,保持等待新设备及授权失败时的兼容 PCM 发送。替换处理链或断开后,旧回调失效。
|
||||
- 新增 15 项测试,其中 10 项先复现失败后修复,包括复查发现的上一批录音提取遗漏:关闭设置但未启动录音时,仍须释放独立采集。
|
||||
- `npm run verify` 通过 164 项测试、后端编译、前端类型检查及生产构建。实际媒体设备和 TeamSpeak 仍未验收;剩余采集模块提取、管理页面与服务端任务继续推进。
|
||||
|
||||
### 前轮只记录的整理结果
|
||||
|
||||
- 以 `407311d` 和当前工作区为依据,更新模块现状、待修改优先级、建议顺序及验收标准。
|
||||
- 登记已有 7 个源码与测试文件的未提交改动,明确三个管理模块尚未接入页面、新增页面测试尚未进入统一命令。
|
||||
- 仅更新本文。未运行测试或构建,未修改源码、测试、配置、依赖及已有草稿,未提交或推送。
|
||||
|
||||
### 管理页面请求与状态实施记录
|
||||
|
||||
- 起始提交为 `407311d`,实施结果已纳入 `11d2fa5`;后者的 [CI](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36813991856) 及 Docker 健康检查已记录成功。该结果不覆盖之后的未提交多语言改动。
|
||||
- 三个功能模块已接入实际页面,请求分别绑定登录会话、页面与功能生命周期,覆盖 JSON、上传校验和备份读取。过期响应不再修改当前页面或触发旧跳转。
|
||||
- 保存按快照保留后续编辑,秘密值与更新动作成组处理;保存不回填过期探测信息。各功能提交状态独立,皮肤操作互斥,撤销邀请防重复,退出失败保留草稿。
|
||||
- 相对基线新增 25 项测试,共 189 项通过,后端编译、前端类型检查和生产构建通过。本批 10 个页面测试先复现失败再通过;控制 HTTP 顺序的页面测试不声称真实登录或数据库端到端已通过。
|
||||
- 本机内存数据库与模拟响应的浏览器检查确认:旧保存响应保留新输入,保存失败保留草稿;皮肤请求期间相关控件禁用,失败保留启用状态,成功切换与默认项保存正常;跨功能页清除旧错误。浏览器日志未见警告或错误。
|
||||
- 临时浏览器页和预览进程已关闭。剩余内联文案、页面组件、媒体模块、真实 TeamSpeak、Android 真机及各平台发布包验收继续推进,完整目标尚未完成。
|
||||
|
||||
### 本次待修改文档整理记录
|
||||
|
||||
- 基线更新为 `11d2fa5`,保留各批历史实施及验证范围,避免把已修复的管理请求问题再次列为待开发。
|
||||
- 登记三处现有未提交源码,说明五语文案与格式化已有实现;新增管理页窄屏长文案布局待办 06-D。
|
||||
- 建议实施顺序为管理页文案与布局收尾、剩余媒体职责整理、页面组件拆分;真实服务、真机和干净打包按独立验收项推进。
|
||||
- 本次整理仅更新本文,未继续修改源码、测试、配置或依赖,未重新运行测试与构建,未提交或推送。
|
||||
|
||||
### 管理页五语与窄屏工具栏实施记录
|
||||
|
||||
- 五种语言各有 267 个显式键,不再通过展开英语字典掩盖缺项;统一时间、状态、审计事件及错误映射,保留未知值回退和两类密码错误的区别。
|
||||
- 管理页状态圆点与按钮分组,窄屏主题按钮采用图标,状态文字和按钮名称保留辅助技术可读性。
|
||||
- 当前代码通过 19 项实际 SFC 页面测试和前端类型检查、生产构建;此前同批文案快照通过完整 189 项测试和前后端构建。
|
||||
- 本机隔离数据浏览器检查覆盖五语状态、时长、审计与中继失败提示;五语及 320、393、740、1440 像素共 20 组工具栏边界检查全部通过,键盘主题切换和明暗布局正常,控制台未见警告或错误。临时页面、视口覆盖和预览进程已清理。
|
||||
- 本批没有验证真实 TeamSpeak 媒体或 Android 真机;后续继续采集失败回滚、设备热插拔、媒体模块提取及页面组件拆分。
|
||||
|
||||
### 采集处理链与设备热插拔实施记录
|
||||
|
||||
- 新增 `web/src/voice/microphone-capture.ts`,集中管理原始音轨、处理节点、RNNoise、worklet 加载、PCM 激活和释放;处理设置类型由原入口继续导出,保持调用兼容。
|
||||
- 新处理链完全就绪后才替换旧流;节点创建失败、worklet 等待及取消不影响仍在运行的旧链。中断准备立即释放候选音轨与节点,迟到回调不能向新连接发送音频。首次创建失败现在产生麦克风错误提示。
|
||||
- 设备热插拔复用输入与输出切换事务,默认输入替换后重新协商 WebRTC;失败保留最后成功设置,输出失败提供五语提示。新的失败切换以实际已运行的处理链作为回滚基线。
|
||||
- 新增 10 项回归测试,其中 7 项先复现既有问题;另外覆盖 worklet 正常发送、准备中断的资源清理,以及迁移后初始设备查询期间断开的取消语义。
|
||||
- `npm run verify` 通过 199 项测试、后端编译、前端类型检查与生产构建。媒体设备、worklet 和 WebRTC 使用边界替身,不能据此认定真实音质、物理热插拔或 TeamSpeak 双向语音已验收。
|
||||
- 伴奏与 WebRTC 控制、服务端音频、剩余页面组件、Android 真机及干净发布包验证尚未完成。
|
||||
|
||||
### 服务端音频与关闭流程实施记录
|
||||
|
||||
- 提取 `SessionAudioTransport`,三条媒体路径共用当前会话校验、耳语分发与统计;迟到帧不能写入已移除会话,WebRTC 与兼容 PCM 不重复转发。
|
||||
- 保留 1,920 字节 PCM、下行 3 字节头和 4,096 字节背压阈值;补齐无效说话者标识、编码失败与发送失败的受控处理。
|
||||
- 会话构造失败释放准入名额;音频清理早于等待 peer 关闭;保留 WebSocketServer 关闭监听,最后的统计读取失败不打断资源清理。
|
||||
- WebRTC 逐项容错释放资源,共享同一关闭 Promise;本批实际先复现资源释放中断和并发关闭提前完成,再验证修复。补充关闭失败结果共享测试。
|
||||
- 新增 20 项测试,统一入口包含 31 个测试文件。`npm run verify` 通过 219 项测试、后端编译、前端类型检查和生产构建。
|
||||
- 网关集成测试使用本机真实 HTTP/WebSocket 和原生 Opus,外部 TeamSpeak SDK 使用替身;没有据此认定真实服务、网络媒体或设备验收完成。SDK 事件、剩余前端媒体与页面拆分继续推进。
|
||||
|
||||
### 成员头像生命周期实施记录
|
||||
|
||||
- 从桥接入口提取 `MemberAvatarLoader`,拥有计时器和下载批次;重连清空缓存并立即失效旧工作,终止会话先关闭头像控制器再等待其他资源。
|
||||
- 三项网关集成用例先复现再通过:终止后迟到结果回填且继续下载、等待心跳响应时错误停止刷新、SDK 中断后继续使用旧批次结果。
|
||||
- 七项独立测试覆盖 UID 去重且同步所有匹配成员、权限或格式失败、旧成功和失败与新批次交错、定时器清理、成员 ID 重用、50 位成员分批及新增成员调度。
|
||||
- 统一入口包含 32 个测试文件,本地 `npm run verify` 通过 229 项测试和前后端构建。外部 SDK 下载仍使用替身;实际服务器头像权限与文件传输兼容不据此认定已验收。
|
||||
- 音频批次 `972ee79` 的 CI 与 Docker 检查已确认通过。头像批次仍需对应提交的独立 CI;SDK 目录事件整体拆分及真实媒体、真机与发布包验收继续保留。
|
||||
|
||||
### SDK 头像下载边界实施记录
|
||||
|
||||
- 前一头像控制器批次 `e9b8c2b` 的 CI 与 Docker 检查已确认通过。
|
||||
- 复查并修复下载方法内部重新读取 `this.client` 的问题:各异步阶段使用原 SDK 客户端,结合连接代次校验;主动断开、SDK 中断及开始连接都会使旧下载失效。
|
||||
- 新增 6 项实际适配方法测试,其中 4 项先复现失败:旧元数据在替代客户端上发起传输、初始化期间断开后空引用、断开后返回已下载内容、同一 SDK 对象重用时恢复旧请求。另覆盖正常内容与 UID 校验、旧客户端断线不能干扰新请求。
|
||||
- 当前统一入口包含 33 个测试文件,`npm run verify` 通过 235 项测试和前后端构建。SDK 网络边界使用替身,本批未声称实际 TeamSpeak 文件传输或媒体连接已验收。
|
||||
- 剩余 SDK 目录事件提取、前端媒体与页面组件、真实服务及平台验收仍未完成,完整目标保持进行中。
|
||||
|
||||
### SDK 会话事件与目录实施记录
|
||||
|
||||
- 新增 `SessionEventCoordinator`,集中 SDK 订阅、目录与成员投影、自身频道、耳语目标收敛、频道事件、聊天及头像协调;桥接入口继续负责准入、连接恢复与传输组装。
|
||||
- 先复现并修复关闭等待期间目录回填、重连等待期间旧快照污染下一连接,以及十类旧 SDK 客户端事件进入替代会话。监听按所属模块解绑,已捕获的旧回调也会被拒绝。
|
||||
- 额外先复现断线通知早于踢出时继续重连的问题;现在两种到达顺序均终止会话,保留踢出错误码和服务器原因。
|
||||
- 新增 19 项测试,其中 13 项先失败后通过;统一入口共 34 个测试文件,`npm run verify` 通过 254 项测试、后端编译、前端类型检查和生产构建。
|
||||
- `cc9714b` 的 CI 与 Docker 检查已确认成功。本批真实服务、网络媒体、Android 真机及发布包未验收,剩余前端媒体与页面组件继续推进。
|
||||
|
||||
### 伴奏采集与 WebRTC 输入混音实施记录
|
||||
|
||||
- 提取 `accompaniment.ts` 与 `webrtc-input.ts`,分别拥有候选和当前采集,以及稳定的 WebRTC 输出、麦克风增益和伴奏源;语音入口由 2,129 行降至 1,988 行,页面调用接口保留。
|
||||
- 伴奏启停不再结束或替换正在发送的输出轨道,新源连接成功后才替换旧源和旧采集。节点创建或连接失败保留可用输入;部分分配和单节点释放失败均不会遗漏后续清理。
|
||||
- 停止、断开或新采集取代旧采集时,立即释放已经取得的候选流,不等待约束结束;准备期间结束的音轨不能被激活。可选内容提示失败不丢失采集,旧授权失败不影响替代操作。
|
||||
- 活动状态只在接入成功后发布;音频接入失败与授权失败分开提示,新增五语文案。麦克风静音和增益、应用音频不经过语音处理的约束保持不变。
|
||||
- 新增 14 项测试并增强 1 项已有取消用例,其中 12 项先失败后通过。`npm run verify` 通过全部 268 项测试、后端编译、前端类型检查和生产构建,显式入口仍为 34 个测试文件。
|
||||
- 前一事件协调提交 `c9740c4` 的 CI 与 Docker 检查已确认成功。本批媒体用例使用浏览器边界替身,未声称真实音质、TeamSpeak 双向语音、Android 真机或发布包验收完成;WebRTC 传输、连接与命令及页面组件仍有后续工作。
|
||||
|
||||
### 麦克风电平监测实施记录
|
||||
|
||||
- 前一伴奏提交 `0f0c52d` 的 CI 与 Docker 构建及健康检查已确认成功。
|
||||
- 提取 `microphone-meter.ts`,独立拥有分析节点、静音输出与计时器;语音入口只处理电平和发言提示,降至 1,960 行。
|
||||
- 五项用例先复现再通过:分析器不可用时遗留输入源、连接失败遗留候选节点、旧计时器读取替代会话、分析读取异常外泄,以及释放异常阻断会话清理。另验证原有周期、RMS 比例、上限和停止行为。
|
||||
- 监测失败不会关闭语音 peer 或停止外部拥有的麦克风;失效回调不再读取新分析器,停止或读取失败清除展示状态。
|
||||
- 本批新增 6 项测试,`npm run verify` 通过 274 项测试、后端编译、前端类型检查和生产构建。真实媒体、Android 真机和跨平台发布仍未验收。
|
||||
|
||||
### WebRTC 传输与诊断实施记录
|
||||
|
||||
- 提取 `webrtc-transport.ts` 与 `webrtc-playback.ts`,分别拥有协商尝试及播放元素;原始麦克风和 PCM 仍归采集层。语音入口由 1,960 行降至 1,743 行。
|
||||
- 协商尝试独立持有 ICE 等待和 answer 期限;播放元素独立持有手势重试与播放 Promise。旧计时器和旧播放回调不能触及替代实例,重叠手势合并为一次播放尝试。
|
||||
- 单个播放元素或 peer 释放失败不再中断其余清理;回退信令发送失败仍释放 WebRTC 并恢复兼容采集,旧回退授权失败不修改新会话。
|
||||
- 诊断保留总期限直至两端统计完成,断开立即结束等待;旧 peer 的统计不混入新会话,发送失败受控返回空结果。
|
||||
- 增加 13 项回归用例,其中 12 项先失败后通过。接续检查确认既有验证进程成功完成;本批后续 300 项统一验证也覆盖这些用例。真实媒体仍未验收。
|
||||
|
||||
### 连接控制与命令等待实施记录
|
||||
|
||||
- 提取 `connection.ts` 与 `commands.ts`,独立拥有凭证请求、socket、连接代次,以及命令确认登记和期限。页面状态与业务错误映射仍由入口持有,入口降至 1,664 行。
|
||||
- 命令发送异常立即移除登记和计时器;成功、拒绝、超时和断开统一结束且幂等。旧 socket 的回复和旧期限不影响替代命令,默认 8 秒确认期限不变。
|
||||
- 凭证获取增加 15 秒期限,覆盖偏好等待、HTTP 和响应体读取。断开和替换立即 abort,旧响应不再继续读取正文;旧期限无法取消新请求。socket 关闭失败不再阻止状态清理,保留网关关闭码优先规则。
|
||||
- 增加 13 项测试,其中 7 项故障回归和 1 项新提示缺失检查先失败后通过。另验证命令确认与错误码、旧期限、请求字段及五语超时提示。旧音频事件用例改为执行已捕获的回调,继续覆盖监听解绑后的迟到执行。
|
||||
- `npm run verify` 通过 300 项测试、后端编译、前端类型检查和生产构建;显式入口仍包含 34 个测试文件。起始提交 `44f2b7d` 的 CI 与 Docker 检查已重新确认成功,本批远端结果按新提交核对。
|
||||
- 本批未完成真实 TeamSpeak 双向语音、Android 真机或跨平台发布验收;诊断与状态投影、页面组件仍有后续工作,完整目标继续进行。
|
||||
|
||||
### 诊断采样与面板状态实施记录
|
||||
|
||||
- 起始提交 `6700466` 的 CI、Docker 构建和 HTTP 健康检查已查询确认成功。
|
||||
- 提取 `audio-diagnostics.ts`,集中统计等待、期限、来源范围和兼容播放计数;原有诊断类型通过语音入口继续导出,入口降至 1,519 行。
|
||||
- 样本比较增加范围与来源检查,修复跨传输、跨 peer 和浏览器统计缺失时的虚假速率。采样捕获 WebRTC 代次,开始于 peer 分配前的旧探测不能跨越失败回退。
|
||||
- 面板采样失败清除旧活动状态,下一次成功重新建立基线;旧轮询、卸载后的回调与手动刷新不再开启请求或遗留运行标志。会话恢复重置兼容计数且不修改旧快照。
|
||||
- 修正上行丢包率分母;新增 13 项测试并增强 1 项已有断言,其中 12 项新增或增强用例先失败后通过。三个 Vue 测试入口禁用 Vite WebSocket 监听,消除并行测试端口竞争。
|
||||
- 统一入口增加到 35 个测试文件,`npm run verify` 通过 313 项测试、后端编译、前端类型检查和生产构建。真实 TeamSpeak、Android 真机及发布包仍未验收,状态投影和页面组件继续跟踪。
|
||||
|
||||
### 消息状态与聊天归属实施记录
|
||||
|
||||
- 基线 `a97fa54` 的 CI 与 Docker 检查已确认成功。保留并更新此前只读整理文档,本批进入代码实施。
|
||||
- 提取 172 行的 `session-state.ts`,集中目录、聊天历史、事件、通知和私聊身份范围;语音入口现为 1,468 行。修复目录双份数据不同步、进入字段丢失、离开残留、编号复用继承临时音量,以及退出未清通知等问题。
|
||||
- 聊天等待命令确认后写入成功历史;未连接、拒绝和超时保留草稿,退出或卸载使迟到反馈失效。按目标保存等待、草稿及错误,切换标签再返回不能重复发送。网关恢复期间的拒绝保留请求标识。
|
||||
- 私聊历史按 UID 或成员生命周期分组,保留对方名称;未知发送者与后来的同编号成员隔离。新增可选私聊 UID 和频道 ID 字段,网关在调用 SDK 前核对,旧客户端省略字段仍可使用原协议。
|
||||
- 频道树改为迭代遍历,重复 ID 保留第一项,孤儿及环受控展开;保留正常兄弟顺序,验证 5,000 层目录。
|
||||
- 新增 25 项测试,其中 20 项先失败后通过;35 个测试文件的 `npm run verify` 通过 338 项测试及前后端构建。新增聊天状态的五语提示及公开皮肤节点已登记,完整皮肤契约测试通过。
|
||||
- 本机网关使用真实 HTTP/WebSocket、模拟 TeamSpeak SDK。实际浏览器验证等待、拒绝、成功及私聊标签,检查桌面与 390 × 844 布局,无浏览器错误日志;临时页面、视口覆盖及进程已清理。浏览器验证不代表真实语音或真机验收。
|
||||
- 06-C 页面组件、03 实际消息兼容、02-C 真实媒体、07-A Android、09-A 发布复现仍未完成,完整目标保持进行中。
|
||||
|
||||
### 管理下载与审计名称验收记录
|
||||
|
||||
- 使用实际管理路由、登录与 CSRF、独立 SQLite 数据库和皮肤目录搭建本地验收环境;会话枚举和终止回调使用一次性测试数据,没有连接实际 TeamSpeak 服务。
|
||||
- 页面诊断链接下载 `webspeak-diagnostic-report.json`(750 字节),备份按钮下载 `webspeak-backup-2026-10-01.db`(61,440 字节)。浏览器完成事件与下载目录文件一致;JSON 可解析,版本和统计符合临时环境且不含测试密码及目标字段;SQLite 文件头正确,`PRAGMA integrity_check` 返回 `ok`。
|
||||
- 备份下载的高层事件等待超时,但底层浏览器下载完成事件和落盘文件均正常。因此不将该工具超时认定为应用下载失败,也不修改 Blob URL 释放逻辑。
|
||||
- 实际页面发现备份与密码变更退化为“系统事件”;补齐同一审计映射中十类缺失事件的中文、英文、德文、俄文及日文名称,覆盖密码、备份、断开、皮肤与邀请。保留未知事件回退;20 项已有管理测试、前端类型检查及生产构建一次通过,浏览器复查显示具体操作名称。
|
||||
- 原生移除确认框依然导致按键和调试命令超时,弹窗查询为空,关闭该页也超时。已停止重复尝试;此结果不证明移除或断开业务失败,两项确认/取消流程保留待验收。独立新页的下载验收不受影响。
|
||||
- 复查 Android 文档与锁定 SDK 的运行时约束,差异已在 07-A 登记;此前 Node 18 冒烟不能替代真实 SDK 连接,本轮没有据此升级依赖或重复运行已完成的冒烟。
|
||||
|
||||
### 皮肤生命周期实施记录
|
||||
|
||||
- 基线 `cdc5f03` 的 CI 与 Docker 检查确认成功;保留此前的管理组件工作区改动。
|
||||
- 先复现 5 个皮肤和目录竞态,再接入运行时取消、8 秒总期限、共享页面控制器及可取消存储事务。新增 23 项用例,38 个测试文件的统一验证通过 385 项测试及前后端构建。
|
||||
- 浏览器验证目录挂起后恢复、旧下载取消、刷新保留最后选择、正常自定义皮肤及演示页恢复。管理三页桌面样式与基线一致;窄屏导航溢出登记为 06-K,管理组件交互和客户端组件继续待办。
|
||||
- 真实 TeamSpeak 收发及媒体、Android 真机和跨平台发布仍未验收,完整目标保持进行中。
|
||||
@@ -0,0 +1,64 @@
|
||||
# WebSpeak 本地产物与源码边界
|
||||
|
||||
源码、依赖锁文件、构建脚本、Android 原生工程和必要的皮肤资源纳入版本管理。运行数据和可再生成的产物留在本地,按以下规则处理;本次整理没有删除、移动或覆盖既有发布包与参考素材。
|
||||
|
||||
| 路径 | 用途 | 处理方式 |
|
||||
| --- | --- | --- |
|
||||
| `src/`、`web/src/`、`mobile/` 中的入口及打包脚本 | 服务端、网页和 Android 实现 | 跟踪源码;各自依赖和锁文件明确保留 |
|
||||
| `web/android/` | Android 原生工程 | 跟踪原生源码、Gradle 配置与 wrapper;忽略缓存、生成资产和本机 SDK 路径;整个目录不进入服务端 Docker 构建上下文 |
|
||||
| 各级 `node_modules/`、`dist/` | 安装依赖和构建输出 | 忽略 Git;Docker 重新安装并构建;Android 资产由 `npm run android:sync` 生成 |
|
||||
| `release-artifacts/` | 本地发布包及校验和,包括 Android APK | 本地保留,忽略 Git 和 Docker;正式发布使用发布工作流的产物 |
|
||||
| 根目录 `webspeak-deploy*.tar.gz`、`webspeak-update*.tar.gz` | 历史部署与更新包 | 本地保留,按项目专用名称忽略,不使用忽略全部压缩包的 Git 规则 |
|
||||
| 根目录 `teamspeak6-server-linux-amd64.tar.xz` | 下载的 TeamSpeak 服务端归档 | 本地保留,忽略 Git 和 Docker |
|
||||
| `界面参考/stitch_teamspeak_web_interface.zip` | 界面参考归档 | 本地保留并忽略 Git;参考素材不进入服务端 Docker 上下文 |
|
||||
| `.local-opus-hook.cjs` | 用原样缓冲区替代编解码的实验脚本 | 本地保留,忽略 Git 和 Docker;不接入正式启动、构建及媒体验收 |
|
||||
| `data/`、`config.json`、`.env`、日志 | 运行数据和本机设置 | 按部署备份策略保管,不能当作可删除的构建缓存;Docker 上下文显式排除 `.env` 及 `.env.*`,避免本地环境文件进入构建阶段 |
|
||||
|
||||
检查规则时,用 `git check-ignore` 确认构建产物被忽略,同时确认 `src/shared/`、平台启动源码、Android Java 文件、Gradle wrapper 和皮肤资源仍可跟踪。新增文件若是构建必需输入,应随源码声明;构建不得依赖上述历史发布包或实验脚本。
|
||||
|
||||
未来需要清理磁盘时,先核对产物的来源、是否可重新生成及保留位置,再选择具体文件。未跟踪或已忽略状态本身不是删除依据。
|
||||
|
||||
## 2026-10-08 v0.2.6 Android APK 构建
|
||||
|
||||
在当前 v0.2.6 发布准备工作树中执行 `npm run android:sync` 和 Gradle `assembleDebug`,使用 Android Studio JDK 25.0.2、Gradle 9.5.0、Android SDK 36。134 个 Gradle 任务通过;APK 清单均为 `versionName=0.2.6`、`versionCode=206`、最低 SDK 24、目标 SDK 36。`apksigner` 验证了三包的 v2 签名;这是 debug 签名,仅适合手动侧载测试。没有 Android 模拟器连接,本轮未安装或测试真实 TeamSpeak 语音。
|
||||
|
||||
文件保存在被 Git 忽略的 `release-artifacts/android/`:
|
||||
|
||||
| APK | 字节数 | 本机复算 SHA-256 |
|
||||
| --- | ---: | --- |
|
||||
| `webspeak-android-v0.2.6-arm64-v8a-debug.apk` | 76,341,182 | `e1851ecbff6b7d133b8f3747781be6d79aeae94bb5a6add723a4b6a7cf868b12` |
|
||||
| `webspeak-android-v0.2.6-armeabi-v7a-debug.apk` | 72,114,332 | `08007e23e384577872f6f9747ec33bcfb59bbef44b819d7ad7fc032a1e923929` |
|
||||
| `webspeak-android-v0.2.6-x86_64-debug.apk` | 80,953,005 | `69a5a71aa0d78f6a8ca43131107eb308d6df31858fce972a5d3d4852ce95c94c` |
|
||||
|
||||
## 2026-10-01 干净构建记录(09-A)
|
||||
|
||||
构建输入为提交 `662dad36fc4d8cf9f35268a99b8221851f6fc52c`,应用版本 `0.2.5-preview`。本轮没有创建版本标签或发布正式 Release。
|
||||
|
||||
[手动发布构建 36857782727](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36857782727) 的测试、Docker、Windows x64、Linux x64 四个作业全部成功;正式发布步骤按分支条件跳过。服务器构建使用工作流指定的 Node.js 22.22.2,Docker 使用 Dockerfile 声明的 Node.js 22 镜像。各平台重新检出源码、安装依赖、构建锁定的 SDK,再编译和打包;Windows 和 Linux 包均包含 Node.js 运行时,并在独立临时目录通过 HTTP 健康状态及版本检查。Docker 镜像也通过 HTTP 健康检查。这些结果不证明真实语音和屏幕共享可用,也不表示产物逐字节可重现。
|
||||
|
||||
| Actions 产物 | 归档字节数 | Actions 报告的 SHA-256 |
|
||||
| --- | ---: | --- |
|
||||
| windows-x64 | 52,431,874 | `790e2d712060b1254498641590c9aed05c065eec416797c4280140531e78ee05` |
|
||||
| linux-x64 | 59,322,525 | `892aaa190f8d138917ef5775dbf05b620abc2033fbc5089821eb8bda15c99e9c` |
|
||||
|
||||
上表摘要属于 Actions 外层产物归档,不是其中部署包的摘要;当前证据来自 Actions API,不能写成已在本机复算。对应部署包由工作流生成,版本和启动结果已由平台作业检查。
|
||||
|
||||
Android 使用同一提交的 `git archive` 源码归档,在新目录安装根、web、mobile 三套锁定依赖并重建 SDK,没有复制当前工作区的 node_modules 或历史发布包。构建主机为 Windows x64,Node.js 24.12.0、Android Studio JDK 25.0.2、Gradle 9.5.0、Android SDK 36;依次执行依赖安装、`prepare:sdk`、`android:sync`、`assembleDebug --no-daemon`。短路径目录 `<TEMP_BUILD_DIR>` 构建成功,134 个 Gradle 任务全部执行。
|
||||
|
||||
| Android 调试产物 | 字节数 | 本机复算 SHA-256 |
|
||||
| --- | ---: | --- |
|
||||
| app-arm64-v8a-debug.apk | 76,289,469 | `7bd977906397ab467655862e1182b1021d6d0b2f255aebcae644eaf5db201006` |
|
||||
| app-armeabi-v7a-debug.apk | 72,062,619 | `a28471b248e944d01c1e72d1066711aafe7dda6524ad1736becfb4d436a064a8` |
|
||||
| app-x86_64-debug.apk | 80,901,292 | `853a82786d1733686329568661954642c60482fd9ad3e7b910856b050d157532` |
|
||||
|
||||
APK 位于上述目录的 `web/android/app/build/outputs/apk/debug`。逐包检查了移动网关入口、TeamSpeak SDK、Opus WASM、网页和匹配 ABI 的 Node.js 原生库;未发现项目私有配置或实验 Opus 脚本。arm64 包的清单版本为 `0.2.5-preview` / code `25`,最低 SDK 24、目标 SDK 36。构建当日尚未安装新包;后续 x86_64 安装与启动结果见下节,Android 布局和真机媒体仍待验收。
|
||||
|
||||
本轮发现并处理两处构建边界问题:`.dockerignore` 补充排除本地 `.env` 与 `.env.*`;Android 深层临时目录触发 CMake 250 字符对象路径警告及 Ninja 建目录失败,同源码在短路径重建通过,已将该主机构建约束补入移动文档。没有为此更改应用或原生插件逻辑。Windows 首次 npm ci 约耗时三分钟,随后构建、打包和启动均正常。
|
||||
|
||||
## 2026-10-02 Android 安装与冷启动(09-A)
|
||||
|
||||
安装对象为上表同一 `662dad3` 的 x86_64 APK,安装前复算 SHA-256 与记录一致。使用已有 `ws` AVD 的只读 Android 15 / x86_64 实例,启动参数包含 `-read-only -no-snapshot-save -no-window -no-audio -port 5580`,没有修改原 AVD 数据或保存新快照。
|
||||
|
||||
`adb -s emulator-5580 install -r <APK>` 返回 `Success`;包管理器报告 `versionName=0.2.5-preview`、`versionCode=25`、最低 SDK 24、目标 SDK 36。强制停止后启动 `io.webspeak.client/.MainActivity` 返回 `Status: ok`、`LaunchState: COLD`,启动耗时 1,822 毫秒。
|
||||
|
||||
通过临时 ADB 转发 `tcp:53040` → 设备 `tcp:3040`,实际内嵌网关 `/health` 返回 `status: ok`、`engine: webspeak-android`;`/api/public-config` 返回 `version: 0.2.5-preview`、`mobile: true`、`initialized: true`。这补齐该干净构建产物的安装、冷启动及 HTTP 网关证据;没有交互式检查 Android WebView 布局、触屏或真实媒体,不能据此关闭这些待办。验收后移除端口转发并关闭该只读模拟器。
|
||||
@@ -15,6 +15,7 @@ Die öffentliche Demo läuft in Hongkong. Netzwerkbedingungen und Auslastung kö
|
||||
| Funktion | Beschreibung |
|
||||
| --- | --- |
|
||||
| TeamSpeak-Kompatibilität | Unterstützt TeamSpeak 3 und TeamSpeak 6 und erkennt das Zielprotokoll automatisch. |
|
||||
| Plattformübergreifendes P2P-Bildschirmteilen | Browsernutzer und native TeamSpeak-6-Clients können die Bildschirmfreigabe gegenseitig starten und ansehen; WebRTC/ICE überträgt Medien direkt, WebSpeak leitet nur die Signalisierung weiter. |
|
||||
| IPv6-Ziele | IPv6-TeamSpeak-Ziele und über DNS aufgelöste IPv6-Adressen werden standardmäßig unterstützt. |
|
||||
| Kanäle und Mitglieder | Kanalstruktur und aktuelle Mitglieder anzeigen und Kanäle wechseln. |
|
||||
| Echtzeit-Sprache | Opus-Audio mit kompatiblem Transport und optional integriertem WebRTC für geringere Latenz. |
|
||||
@@ -24,7 +25,8 @@ Die öffentliche Demo läuft in Hongkong. Netzwerkbedingungen und Auslastung kö
|
||||
| Desktop-Begleitton | Audio eines freigegebenen Fensters oder Browser-Tabs im aktuellen Kanal teilen. |
|
||||
| Identität und Zugriff | Gespeicherte Identität, eigene Ziele und widerrufbare Einladungslinks mit Ablaufzeit. |
|
||||
| Administration | Ziele, Zugriff, WebRTC, Relays, Einladungen, Sitzungen, Protokolle, Diagnosen und Backups verwalten. |
|
||||
| Oberfläche | Chinesische, englische, deutsche, russische und japanische Oberfläche, helle/dunkle Designs sowie responsive Desktop-/Mobilansicht. |
|
||||
| Skins | Geschützte Tages-, Nacht- und ILLUSIA-Skins sowie instanzverwaltete `.wskin`-Designs mit Aktivierungs- und Standardauswahl im Adminbereich. |
|
||||
| Oberfläche | Chinesische, englische, deutsche, russische und japanische Oberfläche sowie responsive Desktop-/Mobilansicht. |
|
||||
| Selbsthosting | Daten bleiben beim Betreiber; Docker-, Windows-x64- und Linux-x64-Bereitstellung sind verfügbar. |
|
||||
|
||||
## 🖼️ Screenshots
|
||||
@@ -62,6 +64,20 @@ WebRTC verwendet für Browser-Sprache einen Echtzeit-Medienpfad und ermöglicht
|
||||
|
||||
Der Portbereich ist bei aktiviertem WebRTC gesperrt. Zum Ändern WebRTC zuerst deaktivieren und speichern, danach die Firewall-Regeln anpassen. Für öffentliche Bereitstellungen ist HTTPS erforderlich.
|
||||
|
||||
### ICE-Kandidaten für Bildschirmfreigabe
|
||||
|
||||
Die Medien der Bildschirmfreigabe versuchen weiterhin eine direkte Browser-zu-Browser-Verbindung; WebSpeak leitet nur die Signalisierung weiter. Standardmäßig werden die öffentlichen TeamSpeak-STUN-Dienste zur Ermittlung öffentlicher Kandidaten verwendet. STUN überträgt keine Medien. Ein autorisierter externer TURN-Dienst kann über `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` als JSON-Array konfiguriert werden, zum Beispiel:
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
Mit TURN kann die Medienübertragung diesen externen Dienst verwenden, aber niemals das WebSpeak-Gateway. Ohne TURN werden nur direkte ICE-Pfade und STUN verwendet.
|
||||
|
||||
### Plattformübergreifendes P2P-Bildschirmteilen
|
||||
|
||||
Browsernutzer und native TeamSpeak-6-Clients können Bildschirmfreigaben gegenseitig erkennen, starten und ansehen. Zwischen Browsern sowie zwischen Browser und nativem Client werden die Bildschirmmedien möglichst über eine direkte WebRTC/ICE-Peer-to-Peer-Verbindung übertragen; WebSpeak übernimmt Sitzungsberechtigung, Freigabestatus und SDP-/ICE-Signalisierung, transportiert aber keine Bildschirmmedien. Die Oberfläche zeigt Live-Status und Zuschauerzahl und bietet Lautstärke-, Vollbild- und Beenden-Steuerung. Für die Aufnahme stehen bis zu 1080p und 60 FPS sowie WebRTC-Statistiken zur Verfügung.
|
||||
|
||||
### 2. Relay-Modus
|
||||
|
||||
Ein Relay hilft, wenn ein TeamSpeak-Server Verbindungen aus einer anderen Region ablehnt oder der direkte Weg instabil ist. Es ist kein VPN, sondern leitet nur den TeamSpeak-Verkehr der aktuellen WebSpeak-Sitzung weiter.
|
||||
@@ -138,6 +154,10 @@ Relay deaktivieren und speichern, um die Option von der Willkommensseite zu entf
|
||||
|
||||
| Version | Datum | Zusammenfassung |
|
||||
| --- | --- | --- |
|
||||
| [v0.2.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.6) | 2026-10-08 | Gegenüber 0.2.5 #10 behoben, #9/#12 umgesetzt, #6/#7 abgesichert und den in PR #13 beschriebenen TS6-Freigabefall korrigiert; Sprach- und Mobilinteraktionen verbessert; Windows x64, Linux x64/ARM64, Docker amd64/arm64 und Android-APKs für drei ABIs ergänzt. |
|
||||
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | `.wskin`-Skins, Aktivierungs-/Standardverwaltung und geschützte Tages-, Nacht- und ILLUSIA-Skins ergänzt; unfertiges Aurora-Voice-Beispiel entfernt, Skin-Ladeblitze, dunkle Bedienelemente und Artwork-Ebenen im Sprachbereich korrigiert sowie offiziellen Skin-Entwicklungs-Agent-Skill hinzugefügt. |
|
||||
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | 2026-09-22 | Plattformübergreifendes P2P-Bildschirmteilen zwischen Browsern und nativen TeamSpeak-6-Clients ergänzt; STUN-/externes-TURN-Konfiguration, Live-Player und Zuschauerstatus, Aufnahmeoptionen bis 1080p/60 FPS und WebRTC-Statistiken hinzugefügt; Bildschirmfreigabe-Interaktion verbessert und Besucherzählung ergänzt. |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | Mitgliederplanung und direkte Verschiebung nach Berechtigung ergänzt; Avatar-, Stummschaltstatus- und Identitätsunterstützung hinzugefügt; Screenshots und Dokumentation für alle fünf Sprachen aktualisiert. |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | 2026-09-17 | Browserseitige Mikrofon-Geräuschunterdrückung, russische und japanische Oberfläche sowie sprachabhängige Begrüßungstexte ergänzt; Lautstärkeinteraktion und Fehlertexte/-codes auf Basis von PR #2 verbessert. |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | 2026-09-13 | Verbindungsfehler auf der Willkommensseite verbessert, Fehlercodes erhalten und sicher gekürzt sowie IPv6-Ziele standardmäßig unterstützt. |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | 2026-09-10 | Passwortabfrage, dedizierter Relay-Modus, Auswahl mehrerer Relays und Ursachendarstellung in der Administration ergänzt. |
|
||||
@@ -155,7 +175,7 @@ Vollständige Historie: [CHANGELOG.md](../CHANGELOG.md).
|
||||
| Methode | Geeignet für | Umgebung |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose (empfohlen) | Dauerbetrieb, einfache Updates und persistente Daten | Docker Engine + Docker Compose |
|
||||
| Release-Paket | Betrieb ohne Node.js und Build-Werkzeuge | Windows x64 oder Linux x64 |
|
||||
| Release-Paket | Betrieb ohne Node.js und Build-Werkzeuge | Windows x64 oder Linux x64/ARM64 |
|
||||
| Aus dem Quellcode | Entwicklung und Anpassungen | Node.js 22.5+, Git und native Build-Werkzeuge |
|
||||
|
||||
### Docker Compose (empfohlen)
|
||||
@@ -186,7 +206,9 @@ docker compose up -d
|
||||
|
||||
### Release-Paket
|
||||
|
||||
Das passende `windows-x64.zip` oder `linux-x64.tar.gz` aus den [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) herunterladen, in ein eigenes Verzeichnis entpacken und `start-webspeak.cmd` bzw. `./start-webspeak.sh` starten. Die Pakete enthalten Node.js und Produktionsabhängigkeiten.
|
||||
Das passende `windows-x64.zip`, `linux-x64.tar.gz` oder `linux-arm64.tar.gz` aus den [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) herunterladen und den enthaltenen Starter ausführen. Die Pakete enthalten Node.js und Produktionsabhängigkeiten. Docker unterstützt amd64/arm64.
|
||||
|
||||
Android-APKs für `arm64-v8a`, `armeabi-v7a` und `x86_64` sind ebenfalls verfügbar. Sie sind für Tests per Sideload debug-signiert, keine Google-Play-Pakete; echte TeamSpeak-Sprachtests auf Geräten stehen noch aus.
|
||||
|
||||
### Aus dem Quellcode
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ The public demo is hosted in Hong Kong and its network conditions and load may b
|
||||
| Capability | Description |
|
||||
| --- | --- |
|
||||
| TeamSpeak compatibility | Supports TeamSpeak 3 and TeamSpeak 6 and automatically detects the target protocol. |
|
||||
| Cross-platform P2P screen sharing | Browser users and native TeamSpeak 6 clients can start and watch each other's screen shares; WebRTC/ICE carries media directly while WebSpeak relays negotiation signaling only. |
|
||||
| IPv6 targets | IPv6 TeamSpeak targets and IPv6 addresses resolved from hostnames are supported by default. |
|
||||
| Channels and members | Browse the channel tree, see live member states, and switch channels. |
|
||||
| Realtime voice | Opus audio with a compatibility transport and optional bundled WebRTC low-latency transport. |
|
||||
@@ -24,8 +25,9 @@ The public demo is hosted in Hong Kong and its network conditions and load may b
|
||||
| Desktop accompaniment | Select an audio-enabled window or browser tab and share its sound with the current channel. |
|
||||
| Identity and access | Remembered identity, visitor-defined targets, and revocable expiring invite links. |
|
||||
| Administration | Manage targets, access policy, WebRTC, relays, invites, sessions, logs, diagnostics, and backups. |
|
||||
| User experience | Chinese, English, German, Russian, and Japanese UI, light/dark themes, and responsive desktop/mobile layouts. |
|
||||
| Self-hosting | Data stays with the operator; Docker, Windows x64, and Linux x64 deployment options are provided. |
|
||||
| Skins | Protected Day, Night, and ILLUSIA skins, plus instance-managed `.wskin` appearances with administrator enable/default controls. |
|
||||
| User experience | Chinese, English, German, Russian, and Japanese UI with responsive desktop/mobile layouts. |
|
||||
| Self-hosting | Data stays with the operator; Docker amd64/arm64, Windows x64 and Linux x64/ARM64 packages, and an Android client are provided. |
|
||||
|
||||
## 🖼️ Screenshots
|
||||
|
||||
@@ -62,6 +64,28 @@ WebRTC moves browser voice to a realtime media path and also enables desktop acc
|
||||
|
||||
The port range is locked while WebRTC is enabled. Disable and save WebRTC before changing it, then update the firewall rules. Public deployments also need HTTPS.
|
||||
|
||||
### Voice WebRTC behind a reverse proxy or TCP tunnel
|
||||
|
||||
The WebRTC advanced settings now include a **public media address**, **IPv6 candidates**, and a **voice STUN server**. The media address must be a gateway IP or hostname reachable over UDP, without a scheme, path or port. It overrides the address inferred from `Origin`, `X-Forwarded-Host`, or `Host`; DNS names are resolved into IP candidates. IPv6 is opt-in and retains IPv4 candidates.
|
||||
|
||||
Set a UDP STUN URL such as `stun:turn.teamspeak.com:3478` to use the same discovery service in the browser and gateway. Empty preserves the previous behavior: the gateway library uses its built-in STUN service while the browser has none. The gateway requires an IPv4-reachable UDP STUN hostname or IPv4 address; IPv6 literals and TURN credentials are not accepted. IPv6 media candidates work independently of STUN. Save and reconnect to apply changes.
|
||||
|
||||
HTTP/WebSocket reachability does not imply media reachability. Allow the complete configured UDP range and preserve port numbers when using static port forwarding. STUN discovers mappings but cannot relay audio or traverse every NAT. Deployments with only a TCP tunnel and no usable UDP/IPv6 path still fall back to compatibility transport.
|
||||
|
||||
### Screen-share ICE candidates
|
||||
|
||||
Screen-share media still prefers a direct browser-to-browser path; WebSpeak only relays negotiation signaling. By default it uses TeamSpeak's public STUN services to discover server-reflexive candidates; STUN does not carry media. If the deployment has an authorized external TURN service, set `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` before starting WebSpeak with a JSON array, for example:
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
With TURN configured, media may use that external TURN service but never the WebSpeak gateway; without it, only direct ICE paths and STUN are used.
|
||||
|
||||
### Cross-platform P2P screen sharing
|
||||
|
||||
Browser users and native TeamSpeak 6 clients can discover, start, and watch each other's screen shares. Screen media between browsers, and between a browser and a native client, is sent over a WebRTC/ICE peer-to-peer path whenever possible; WebSpeak handles session authorization, share state, and SDP/ICE signaling, but does not carry the screen media. The UI includes live status, viewer count, player volume, fullscreen, and exit controls. Share settings support up to 1080p and 60 FPS, with live WebRTC statistics for diagnosis.
|
||||
|
||||
### 2. Relay mode
|
||||
|
||||
Use a relay when a TeamSpeak server rejects connections from another region or when the direct path is unstable. It is not a VPN: it forwards only the TeamSpeak traffic of the current WebSpeak session, while the visitor still chooses the target server in the web page.
|
||||
@@ -138,6 +162,10 @@ Disable and save the relay configuration to remove the relay option from the wel
|
||||
|
||||
| Version | Date | Summary |
|
||||
| --- | --- | --- |
|
||||
| [v0.2.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.6) | 2026-10-08 | Relative to 0.2.5, fixed #10, implemented #9/#12, hardened #6/#7, and fixed the existing-share discovery case reported in PR #13; improved voice and mobile interactions; added Windows x64, Linux x64/ARM64, amd64/arm64 Docker, and three-ABI Android packages. |
|
||||
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | Added `.wskin` skins, administrator enable/default controls, and protected Day/Night/ILLUSIA built-ins; removed the unfinished Aurora Voice sample, fixed skin-load flashes, dark-control contrast, and voice-room artwork layering, and added the official skin-development Agent Skill. |
|
||||
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | 2026-09-22 | Added cross-platform P2P screen sharing between browsers and native TeamSpeak 6 clients; added STUN/external-TURN configuration, live player and viewer state, 1080p/60 FPS capture settings, and WebRTC statistics; refined screen-share interactions and added visitor numbering. |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | Added channel member scheduling and permission-aware direct moves; added avatar, mute-state, and remembered-identity support; refreshed feature screenshots and documentation for all five languages. |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | 2026-09-17 | Added browser-side microphone noise suppression, Russian and Japanese UI, and per-language welcome text; refined volume interaction and error messages/codes on top of PR #2. |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | 2026-09-13 | Improved welcome-page connection errors, preserved and safely truncated error codes, and added default IPv6 target support. |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | 2026-09-10 | Added server-password prompts, formal relay mode, multiple relay selection, and administrator connection-reason reporting. |
|
||||
@@ -155,7 +183,7 @@ See the complete history in [CHANGELOG.md](../CHANGELOG.md).
|
||||
| Method | Best for | Environment |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose (recommended) | Long-running servers, simple upgrades, and persistent data | Docker Engine + Docker Compose |
|
||||
| Release package | Running without Node.js or build dependencies | Windows x64 or Linux x64 |
|
||||
| Release package | Running without Node.js or build dependencies | Windows x64 or Linux x64/ARM64 |
|
||||
| From source | Development, debugging, and customization | Node.js 22.5+, Git, and native build tools |
|
||||
|
||||
### Docker Compose (recommended)
|
||||
@@ -186,7 +214,9 @@ Do not run `docker compose down -v`; it removes the database and administrator s
|
||||
|
||||
### Release package
|
||||
|
||||
Download the matching `windows-x64.zip` or `linux-x64.tar.gz` from [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest), extract it into a dedicated directory, and run `start-webspeak.cmd` on Windows or `./start-webspeak.sh` on Linux. Packages include the Node.js runtime and production dependencies.
|
||||
Download the matching `windows-x64.zip`, `linux-x64.tar.gz`, or `linux-arm64.tar.gz` from [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). Extract it and run the included launcher. Packages include the Node.js runtime and production dependencies. Docker images support amd64/arm64.
|
||||
|
||||
Android APKs for `arm64-v8a`, `armeabi-v7a`, and `x86_64` are also attached. They use debug signing for sideload testing; they are not Google Play packages, and real-device voice still needs validation.
|
||||
|
||||
### From source
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
| 機能 | 説明 |
|
||||
| --- | --- |
|
||||
| TeamSpeak | TeamSpeak 3 / 6 に対応し、対象プロトコルを自動検出します。 |
|
||||
| クロスプラットフォーム P2P 画面共有 | ブラウザユーザーと TeamSpeak 6 ネイティブクライアントが互いに画面共有を開始・視聴できます。メディアは WebRTC/ICE で直接送信し、WebSpeak はシグナリングだけを中継します。 |
|
||||
| IPv6 | IPv6 の接続先と DNS から解決された IPv6 アドレスに標準対応します。 |
|
||||
| チャンネルとメンバー | チャンネルツリー、リアルタイムのメンバー状態、チャンネル移動。 |
|
||||
| リアルタイム音声 | Opus、互換トランスポート、内蔵 WebRTC による低遅延音声。 |
|
||||
@@ -30,7 +31,28 @@
|
||||
| BGM共有 | デスクトップブラウザで音声付きウィンドウやタブの音をチャンネルに共有。 |
|
||||
| ID とアクセス | ID の保存、接続先の指定、期限・回数付き招待リンク。 |
|
||||
| 管理コンソール | 接続先、アクセス、WebRTC、中継、招待、セッション、ログ、診断、バックアップ。 |
|
||||
| インターフェース | 中文、English、Deutsch、Русский、日本語、ライト/ダークテーマ、レスポンシブ表示。 |
|
||||
| スキン | 保護された昼・夜・ILLUSIA スキンに加え、管理者が有効化とデフォルトを管理するインスタンス `.wskin` に対応。 |
|
||||
| インターフェース | 中文、English、Deutsch、Русский、日本語、レスポンシブ表示。 |
|
||||
|
||||
## 🖼️ インターフェースのスクリーンショット
|
||||
|
||||
日本語のホーム、音声ワークスペース、オーディオ設定、メンバー操作メニューを掲載しています。
|
||||
|
||||
### ホーム
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja-home.png" alt="WebSpeak 日本語ホーム" width="100%" /></p>
|
||||
|
||||
### 音声ワークスペース
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja.png" alt="WebSpeak 日本語音声ワークスペース" width="100%" /></p>
|
||||
|
||||
### オーディオ設定
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja-audio.png" alt="WebSpeak 日本語オーディオ設定" width="100%" /></p>
|
||||
|
||||
### メンバーメニュー
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja-menu.png" alt="WebSpeak 日本語メンバーメニュー" width="100%" /></p>
|
||||
|
||||
## 🧩 高度な機能
|
||||
|
||||
@@ -38,6 +60,20 @@
|
||||
|
||||
**管理コンソール → サーバー → 詳細設定** で有効にします。無効の状態で UDP ポート範囲(初期値 `40000–40099`)を設定し、ファイアウォールで許可して保存してください。有効中は範囲がロックされ、新しい接続で WebRTC を使用します。非対応のブラウザは互換トランスポートに戻ります。公開サイトでは HTTPS が必要です。
|
||||
|
||||
### 画面共有の ICE 候補
|
||||
|
||||
画面共有のメディアは引き続きブラウザ間の直接接続を優先し、WebSpeak はシグナリングだけを中継します。初期状態では TeamSpeak の公開 STUN サービスで外部候補を検出します。STUN はメディアを運びません。認可済みの外部 TURN を使う場合は、起動前に `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` を JSON 配列で設定できます。
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
TURN を設定した場合、メディアは外部 TURN サービスを経由することがありますが、WebSpeak ゲートウェイは経由しません。未設定時は直接接続と STUN のみを使用します。
|
||||
|
||||
### クロスプラットフォーム P2P 画面共有
|
||||
|
||||
ブラウザユーザーと TeamSpeak 6 ネイティブクライアントは、互いの画面共有を検出・開始・視聴できます。ブラウザ間、およびブラウザとネイティブクライアント間の画面メディアは、可能な限り WebRTC/ICE の直接接続で送信されます。WebSpeak はセッション認証、共有状態、SDP/ICE シグナリングを担当しますが、画面メディア自体は転送しません。画面には配信中の状態と視聴者数が表示され、音量、全画面、終了を操作できます。取得設定は最大 1080p / 60 FPS に対応し、WebRTC 統計も確認できます。
|
||||
|
||||
### 中継サーバー
|
||||
|
||||
中継は現在の WebSpeak セッションの TeamSpeak 通信だけを転送し、VPN ではありません。管理コンソールで複数のノードに名前、アドレス、トークンを設定すると、ユーザーは直接接続または中継を選択できます。中継モードは専用の転送サービスとして動作し、ゲスト画面や管理コンソールを提供しません。
|
||||
@@ -65,7 +101,7 @@ docker compose up -d
|
||||
|
||||
### Release パッケージ
|
||||
|
||||
[Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) から Windows x64 または Linux x64 のパッケージを取得し、専用フォルダーに展開して `start-webspeak.cmd` または `./start-webspeak.sh` を実行します。
|
||||
[Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) から `windows-x64.zip`、`linux-x64.tar.gz`、`linux-arm64.tar.gz` のいずれかを取得し、同梱ランチャーを実行します。Docker は amd64/arm64 に対応します。`arm64-v8a`、`armeabi-v7a`、`x86_64` の Android APK もあります。APK は手動インストールとテスト向けのデバッグ署名で、Google Play 用ではありません。実機 TeamSpeak 音声は未検証です。
|
||||
|
||||
### ソースから
|
||||
|
||||
@@ -99,6 +135,10 @@ npm start
|
||||
|
||||
| バージョン | 内容 |
|
||||
| --- | --- |
|
||||
| [v0.2.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.6) | #10 を修正、#9/#12 の設定を実装し、#6/#7 を強化。PR #13 が報告した TS6 共有の見落としも修正しました。Windows x64、Linux x64/ARM64、Docker amd64/arm64、3 ABI の Android APK を追加しました。 |
|
||||
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | `.wskin` スキン、管理者向けの有効化/デフォルト設定、保護された昼・夜・ILLUSIA 内蔵スキンを追加。未完成の Aurora Voice サンプルを削除し、読み込み時のちらつき、ダークモードの視認性、音声画面のアートレイヤーを修正。公式スキン開発 Agent Skill も追加しました。 |
|
||||
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | ブラウザと TeamSpeak 6 ネイティブクライアント間のクロスプラットフォーム P2P 画面共有を追加しました。STUN/外部 TURN 設定、プレーヤーと視聴者状態、1080p/60 FPS 取得設定、WebRTC 統計に対応し、共有操作と訪問者番号も改善しました。 |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | チャンネルメンバーの移動操作と権限に応じた直接移動を追加し、アバター表示、ミュート状態の同期、保存 ID の復元に対応しました。5 言語のスクリーンショットとドキュメントも更新しました。 |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | ブラウザ側マイクノイズ抑制、ロシア語・日本語 UI、言語別ウェルカム文を追加。音量操作と PR #2 を基にしたエラー表示・エラーコードを改善しました。 |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | 接続エラー表示を改善し、IPv6 接続先を標準対応しました。 |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | パスワード案内、正式な中継モード、複数中継選択、接続診断を追加しました。 |
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
| Возможность | Описание |
|
||||
| --- | --- |
|
||||
| TeamSpeak | Поддержка TeamSpeak 3 и TeamSpeak 6 с автоматическим определением протокола. |
|
||||
| Кроссплатформенная P2P-трансляция экрана | Пользователи браузера и нативные клиенты TeamSpeak 6 могут запускать и смотреть трансляции друг друга; медиаданные идут напрямую по WebRTC/ICE, а WebSpeak передаёт только сигнальные сообщения. |
|
||||
| IPv6 | IPv6-цели и IPv6-адреса, полученные через DNS, поддерживаются по умолчанию. |
|
||||
| Каналы и участники | Дерево каналов, состояние участников в реальном времени и переход между каналами. |
|
||||
| Голос в реальном времени | Opus, совместимый транспорт и встроенный WebRTC с низкой задержкой. |
|
||||
@@ -30,7 +31,28 @@
|
||||
| Фоновая музыка | На компьютере можно поделиться звуком окна или вкладки с текущим каналом. |
|
||||
| Идентичность и доступ | Сохранение идентичности, собственные цели и приглашения с ограничением срока и числа использований. |
|
||||
| Панель администратора | Цели, доступ, WebRTC, ретрансляторы, приглашения, сессии, логи, диагностика и резервные копии. |
|
||||
| Интерфейс | 中文, English, Deutsch, Русский и 日本語, светлая/тёмная тема и адаптивная верстка. |
|
||||
| Скины | Защищённые дневная, ночная и ILLUSIA-темы, а также `.wskin` экземпляра с управлением включением и темой по умолчанию в панели администратора. |
|
||||
| Интерфейс | 中文, English, Deutsch, Русский и 日本語, адаптивная верстка. |
|
||||
|
||||
## 🖼️ Скриншоты интерфейса
|
||||
|
||||
Скриншоты показывают русскую главную страницу, голосовое пространство, настройки аудио и меню участника.
|
||||
|
||||
### Главная страница
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru-home.png" alt="Главная страница WebSpeak на русском" width="100%" /></p>
|
||||
|
||||
### Голосовое пространство
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru.png" alt="Русское голосовое пространство WebSpeak" width="100%" /></p>
|
||||
|
||||
### Настройки аудио
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru-audio.png" alt="Настройки аудио WebSpeak на русском" width="100%" /></p>
|
||||
|
||||
### Меню участника
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru-menu.png" alt="Меню участника WebSpeak на русском" width="100%" /></p>
|
||||
|
||||
## 🧩 Расширенные функции
|
||||
|
||||
@@ -38,6 +60,20 @@
|
||||
|
||||
Включается в **Панель администратора → Сервер → Расширенные настройки**. До включения задайте диапазон UDP-портов (по умолчанию `40000–40099`), откройте его в firewall и сохраните. При включённом WebRTC диапазон заблокирован; новые подключения используют WebRTC, а неподдерживаемые браузеры переходят на совместимый транспорт. Для публичного доступа нужен HTTPS.
|
||||
|
||||
### ICE для демонстрации экрана
|
||||
|
||||
Медиа демонстрации экрана по-прежнему предпочитает прямое соединение между браузерами; WebSpeak только передаёт сигнальные сообщения. По умолчанию используются публичные STUN-серверы TeamSpeak для поиска внешних кандидатов, STUN не передаёт медиаданные. Авторизованный внешний TURN можно задать через `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` в виде JSON-массива, например:
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
При настроенном TURN медиа может идти через этот внешний сервис, но не через шлюз WebSpeak. Без TURN используются только прямые ICE-пути и STUN.
|
||||
|
||||
### Кроссплатформенная P2P-трансляция экрана
|
||||
|
||||
Пользователи браузера и нативные клиенты TeamSpeak 6 могут обнаруживать, запускать и смотреть трансляции друг друга. Между браузерами, а также между браузером и нативным клиентом, экран передаётся по прямому соединению WebRTC/ICE, когда это возможно; WebSpeak отвечает за авторизацию сессии, состояние трансляции и передачу SDP/ICE-сигналов, но не переносит медиаданные экрана. Интерфейс показывает статус трансляции и число зрителей и предоставляет регулировку громкости, полноэкранный режим и выход. Для захвата доступны настройки до 1080p и 60 FPS, а также статистика WebRTC.
|
||||
|
||||
### Ретрансляторы
|
||||
|
||||
Ретранслятор передаёт только TeamSpeak-трафик текущей сессии и не является VPN. В панели администратора добавьте один или несколько узлов, задайте имя, адрес и токен. Пользователь сможет выбрать прямое подключение или настроенный ретранслятор. Режим ретранслятора запускается отдельно и не предоставляет страницу посетителя или панель администратора.
|
||||
@@ -65,7 +101,7 @@ docker compose up -d
|
||||
|
||||
### Пакет Release
|
||||
|
||||
Скачайте подходящий пакет Windows x64 или Linux x64 из [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest), распакуйте в отдельную папку и запустите `start-webspeak.cmd` или `./start-webspeak.sh`.
|
||||
Скачайте подходящий пакет `windows-x64.zip`, `linux-x64.tar.gz` или `linux-arm64.tar.gz` из [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) и запустите приложенный скрипт. Docker поддерживает amd64/arm64. Также доступны Android APK для `arm64-v8a`, `armeabi-v7a` и `x86_64`; они подписаны отладочным ключом для ручной установки и тестирования, а не для Google Play. Голос TeamSpeak на реальных устройствах пока не проверен.
|
||||
|
||||
### Из исходников
|
||||
|
||||
@@ -99,6 +135,10 @@ npm start
|
||||
|
||||
| Версия | Изменения |
|
||||
| --- | --- |
|
||||
| [v0.2.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.6) | Исправлена #10, реализованы настройки #9/#12, усилены исправления #6/#7 и исправлен случай из PR #13; улучшено мобильное управление; добавлены Windows x64, Linux x64/ARM64, Docker amd64/arm64 и Android APK для трёх ABI. |
|
||||
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | Добавлены скины `.wskin`, управление включением и темой по умолчанию, а также защищённые темы «День», «Ночь» и ILLUSIA; удалён незавершённый пример Aurora Voice, исправлены мерцание при загрузке скина, контраст элементов в тёмном режиме и слои иллюстраций в голосовом пространстве; добавлен официальный Agent Skill для разработки скинов. |
|
||||
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | Добавлена кроссплатформенная P2P-трансляция экрана между браузерами и нативными клиентами TeamSpeak 6; добавлены настройка STUN/внешнего TURN, проигрыватель и состояние зрителей, захват до 1080p/60 FPS и статистика WebRTC; улучшено управление трансляцией и добавлен номер посетителя. |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | Добавлены управление перемещением участников и прямое перемещение с учётом прав; поддержаны аватары, синхронизация микрофона и восстановление идентичности; обновлены скриншоты и документация для пяти языков. |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | Добавлены браузерное шумоподавление микрофона, русский и японский интерфейсы и отдельные тексты приветствия; улучшены управление громкостью и сообщения/коды ошибок на основе PR #2. |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | Улучшены ошибки на странице входа и добавлена поддержка IPv6-целей по умолчанию. |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | Добавлены подсказки пароля, режим ретранслятора, выбор нескольких узлов и диагностика подключений. |
|
||||
|
||||
@@ -15,6 +15,7 @@ WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端
|
||||
| 能力 | 说明 |
|
||||
| --- | --- |
|
||||
| TeamSpeak 兼容 | 支持 TeamSpeak 3 与 TeamSpeak 6,并自动探测目标服务器协议。 |
|
||||
| 跨端 P2P 屏幕共享 | 支持浏览器用户与 TeamSpeak 6 原生客户端互相发起和观看屏幕共享;媒体优先通过 WebRTC/ICE 直连,WebSpeak 仅转发协商信令。 |
|
||||
| IPv6 目标 | 默认支持 IPv6 TeamSpeak 目标和域名解析出的 IPv6 地址。 |
|
||||
| 频道与成员 | 浏览频道树、查看实时成员状态并切换频道。 |
|
||||
| 实时语音 | 使用 Opus,支持兼容传输和可选的内置 WebRTC 低延迟传输。 |
|
||||
@@ -24,8 +25,9 @@ WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端
|
||||
| 桌面端伴奏 | 在桌面浏览器选择带音频的窗口或标签页,将声音分享给当前频道。 |
|
||||
| 身份与访问 | 支持身份保持、访客自定义目标和可撤销、可过期的邀请链接。 |
|
||||
| 管理控制台 | 管理目标、访问策略、WebRTC、中继、邀请、会话、日志、诊断和备份。 |
|
||||
| 界面体验 | 提供中文、English、Deutsch、Русский、日本語、浅色/深色主题及响应式桌面/移动布局。 |
|
||||
| 自托管 | 数据由部署者保存,提供 Docker、Windows x64 和 Linux x64 方案。 |
|
||||
| 皮肤 | 提供日间、夜间和 ILLUSIA 三款受保护皮肤,并支持实例自定义 `.wskin` 外观与管理员默认/启用管理。 |
|
||||
| 界面体验 | 提供中文、English、Deutsch、Русский、日本語及响应式桌面/移动布局。 |
|
||||
| 自托管 | 数据由部署者保存,支持 Docker amd64/arm64、Windows x64、Linux x64/ARM64 服务端包和 Android 客户端。 |
|
||||
|
||||
## 🖼️ 界面截图
|
||||
|
||||
@@ -62,6 +64,30 @@ WebRTC 将浏览器语音切换到实时媒体通道,也支持桌面端伴奏
|
||||
|
||||
WebRTC 启用后端口范围会锁定。要修改端口,先关闭 WebRTC 并保存,再修改端口并同步防火墙规则。公网使用还需要 HTTPS。
|
||||
|
||||
### 反向代理 / TCP 隧道下的语音 WebRTC
|
||||
|
||||
在管理后台的 WebRTC 高级参数中可设置:
|
||||
|
||||
- **公网媒体地址**:WebSpeak 网关可被 UDP 访问的 IP 或域名,不含协议、路径或端口。优先于网页入口推断;留空时按 `Origin`、`X-Forwarded-Host`、`Host` 推断。域名会解析为 IP 候选。反代域名不一定是媒体地址。
|
||||
- **启用 IPv6 候选**:默认关闭;开启后保留 IPv4,同时收集 IPv6。需确保 IPv6 路由及 UDP 防火墙放行。
|
||||
- **语音 STUN 服务**:可设置 `stun:turn.teamspeak.com:3478`,浏览器和网关使用同一服务发现公网映射。留空保留旧行为:werift 网关仍使用库内置 STUN,浏览器不配置 STUN。当前字段仅支持可通过 IPv4 访问的 UDP STUN 域名或 IPv4 地址,不接受 IPv6 字面量、TURN 或凭据;IPv6 媒体候选独立于 STUN 开关。
|
||||
|
||||
保存后重新连接。网页和 WebSocket 经反代可达,不代表媒体 UDP 可达;STUN 仅发现地址,不中继音频,也不保证穿透所有 NAT。只有 TCP 隧道而无可用 UDP/IPv6 路径时,仍会回退兼容传输。应开放配置的整个 UDP 端口范围;静态端口转发需保持相同端口映射。
|
||||
|
||||
### 屏幕共享的 ICE 候选
|
||||
|
||||
屏幕共享媒体仍优先走浏览器之间的直连,WebSpeak 只转发协商信令。默认使用 TeamSpeak 官方 STUN 服务发现公网候选地址;STUN 不承载媒体。若部署者有合规的外部 TURN 服务,可在启动 WebSpeak 前设置 `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS`,值为 JSON 数组,例如:
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
配置 TURN 后,媒体可能经过该外部 TURN 服务,但不会经过 WebSpeak 网关;未配置时只使用直连和 STUN。
|
||||
|
||||
### 跨端 P2P 屏幕共享
|
||||
|
||||
浏览器用户与 TeamSpeak 6 原生客户端可以互相发现、发起和观看屏幕共享。浏览器之间以及浏览器与原生客户端之间的屏幕媒体优先通过 WebRTC/ICE 端到端传输;WebSpeak 负责会话鉴权、共享状态和 SDP/ICE 信令转发,不承载屏幕媒体流量。页面提供直播状态、观众人数、播放器音量、全屏和退出控制,也可在共享设置窗口中选择最高 1080p 与 60 FPS,并查看 WebRTC 统计。
|
||||
|
||||
### 2. 中继模式
|
||||
|
||||
中继适用于 TeamSpeak 拒绝境外连接或直连不稳定的情况。它不是 VPN,只转发当前 WebSpeak 会话的 TeamSpeak 数据;目标服务器仍由用户在网页中选择。
|
||||
@@ -138,6 +164,10 @@ docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
|
||||
| 版本 | 日期 | 摘要 |
|
||||
| --- | --- | --- |
|
||||
| [v0.2.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.6) | 2026-10-08 | 相对 0.2.5 修复 #10、实现 #9/#12,并加固 #6/#7;修复 PR #13 所报告的既有屏幕共享漏同步;改善语音和移动端交互;发布 Windows x64、Linux x64/ARM64、Docker amd64/arm64 和 Android 三种 ABI 构建包。 |
|
||||
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | 新增 `.wskin` 皮肤系统、管理员启用/默认管理和受保护的日间/夜间/ILLUSIA 内置皮肤;移除未完成 Aurora Voice 样例,修复皮肤加载闪烁、暗色控件可读性与语音界面美术层级,并加入官方皮肤开发 Agent Skill。 |
|
||||
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | 2026-09-22 | 新增浏览器与 TeamSpeak 6 原生客户端之间的跨端 P2P 屏幕共享;提供 STUN/外部 TURN 配置、直播播放器、观众状态、1080p/60 FPS 采集设置和 WebRTC 统计;优化屏幕共享交互并新增访客编号。 |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | 新增频道成员调度与按权限直接移动;支持头像、静音状态同步和身份恢复;更新五种语言的功能截图与文档。 |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | 2026-09-17 | 提供浏览器端麦克风降噪、俄语和日语支持及按语言欢迎词配置;优化音量交互和 PR #2 基础上的错误提示与错误代码。 |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | 2026-09-13 | 优化首页连接错误显示,保留并安全截断错误代码;默认支持 IPv6 TeamSpeak 目标。 |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | 2026-09-10 | 增加服务器密码提示、正式中继部署模式、多中继选择和管理员日志原因显示。 |
|
||||
@@ -155,7 +185,7 @@ docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
| 方案 | 适用场景 | 环境 |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose(推荐) | 长期运行、升级简单、数据持久化 | Docker Engine + Docker Compose |
|
||||
| 发布包 | 不安装 Node.js 和构建依赖 | Windows x64 或 Linux x64 |
|
||||
| 发布包 | 不安装 Node.js 和构建依赖 | Windows x64 或 Linux x64/ARM64 |
|
||||
| 源码运行 | 开发、调试和二次开发 | Node.js 22.5+、Git 和本地编译工具 |
|
||||
|
||||
### Docker Compose(推荐)
|
||||
@@ -186,7 +216,9 @@ docker compose up -d
|
||||
|
||||
### 发布包
|
||||
|
||||
从 [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 下载对应的 `windows-x64.zip` 或 `linux-x64.tar.gz`,解压后运行 Windows 的 `start-webspeak.cmd` 或 Linux 的 `./start-webspeak.sh`。发布包自带 Node.js 运行时和生产依赖。
|
||||
从 [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 下载与系统和架构匹配的 `windows-x64.zip`、`linux-x64.tar.gz` 或 `linux-arm64.tar.gz`,解压后运行对应启动脚本。发布包自带 Node.js 运行时和生产依赖。Docker 镜像支持 amd64/arm64。
|
||||
|
||||
Release 同时提供 Android `arm64-v8a`、`armeabi-v7a` 和 `x86_64` APK。它们使用 debug 签名,可手动侧载测试;不是 Google Play 发布包,Android 真机语音仍需验收。
|
||||
|
||||
### 源码运行
|
||||
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
# WebSpeak 皮肤开发规范
|
||||
|
||||
本文说明如何制作、校验并发布 WebSpeak `.wskin` 皮肤包。皮肤可为公开页面逐个部件定制二次元美术表现:背景、素材、配色、轮廓、圆角、阴影、头像装饰、按钮质感、滚动条颜色和播放器外观都可以自定义;但组件的位置、尺寸、排列、文字排版空间及交互结构由 WebSpeak 固定提供,皮肤不得重排或覆盖。
|
||||
|
||||
页面结构、必要控件和所有基础翻译均由 WebSpeak 提供。皮肤包不必携带文案;如果只包含样式与美术素材,所有界面文字仍由 WebSpeak 按当前语言显示。`content.json` 仅用于可选覆盖,缺少的语言或字段回退到 WebSpeak 的基础内容。皮肤不注入 HTML 或 JavaScript,也不改变语音、权限、连接、拖动和屏幕共享行为。**管理后台 `/admin/**` 不属于皮肤范围,始终使用 WebSpeak 自己的固定样式。**
|
||||
|
||||
可直接查看 [ILLUSIA 风示例源码](examples/illusia-voice/) 与 [示例说明](examples/ILLUSIA-VOICE.md)。它使用本地美术素材和 CSS 完整定制首页、语音房间、成员区、聊天空状态及播放器,同时沿用 WebSpeak 提供的基础翻译;也是管理控制台内置且不可移除的示例皮肤。
|
||||
|
||||
## 使用与发布
|
||||
|
||||
管理员在 `/admin/skins` 查看三款随 WebSpeak 提供的内置皮肤,并可导入、替换、启用/停用或删除实例自定义皮肤;还可指定访客首次访问时使用的默认皮肤。默认日间、默认夜间和 ILLUSIA 风为受保护内置项,不可替换、停用或移除。访客手动选择的皮肤保存在该浏览器,后续实例默认值变更不会覆盖该明确选择;仅自动套用过旧默认值的浏览器会采用最新实例默认值。皮肤包会缓存在浏览器本地;页面启动时会查询实例目录,目录可用且版本更新时拉取新包。若网络不可用,已缓存的版本仍可使用。
|
||||
|
||||
选择器提供默认日间、默认夜间、内置 ILLUSIA 风和已启用的实例皮肤;没有“跟随系统”选项。停用的实例皮肤不向访客展示,也不能从服务端下载;若它是当前默认皮肤,系统会安全回退到默认日间。管理员设置的默认值只影响未手动选择皮肤的访客。自定义皮肤是独立的外观选择,不继承之前的日间或夜间模式;皮肤未覆盖的部件回退到浅色基础外观,避免一套组件混入另一套模式。自定义皮肤可自行声明 `color-scheme` 并定义深色外观;切换为日间或夜间时,会停用当前自定义包。文档级 `data-theme` 仍由 WebSpeak 保留给管理后台使用。
|
||||
|
||||
## 包结构
|
||||
|
||||
`.wskin` 是标准 ZIP 容器,推荐把下列文件直接放在 ZIP 根目录:
|
||||
|
||||
```text
|
||||
manifest.json # 必需:身份、版本与入口
|
||||
skin.css # 必需:皮肤样式
|
||||
content.json # 可选:首页内容与多语言界面文案
|
||||
assets/preview.jpg # 可选:管理后台显示的预览图,也可在 CSS 中使用
|
||||
assets/background.webp # 可选:页面艺术素材
|
||||
assets/brand.woff2 # 可选:自带字体
|
||||
```
|
||||
|
||||
所有资源路径使用 `/`,区分大小写,并相对于包根目录。CSS 的 `url()` 使用同样的包根相对路径,例如 `url("assets/background.webp")`。不得使用机器本地路径、站点绝对路径或远程 URL。
|
||||
|
||||
### `manifest.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "community.illusia-voice",
|
||||
"name": "ILLUSIA风",
|
||||
"version": "1.0.25",
|
||||
"author": "WebSpeak Project",
|
||||
"license": "All rights reserved",
|
||||
"description": "A visual-only art skin using the WebSpeak interface translations.",
|
||||
"entry": "skin.css",
|
||||
"preview": "assets/background-composite.webp",
|
||||
"minAppVersion": "0.2.6"
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 规则 |
|
||||
| --- | --- |
|
||||
| `schemaVersion` | 当前必须为数字 `1`。 |
|
||||
| `id` | 必需,最多 80 个字符;只允许小写字母、数字、点和连字符;不能以 `builtin.` 开头,也不能使用受保护 ID `builtin.light`、`builtin.dark` 或 `community.illusia-voice`。发布后不要更改。 |
|
||||
| `name`、`author`、`license` | 必需,各最多 80 个字符。资源授权由作者负责确认。 |
|
||||
| `version`、`minAppVersion` | 必需,使用语义化版本号,例如 `1.2.0`。 |
|
||||
| `entry` | 必需,包内 CSS 文件路径,最多 120 个字符。 |
|
||||
| `content` | 可选,包内 JSON 文件路径,最多 120 个字符。 |
|
||||
| `preview` | 可选,包内 PNG、JPG/JPEG、WebP、AVIF 或 GIF 图片路径,最多 120 个字符。 |
|
||||
| `description` | 可选,最多 400 个字符。 |
|
||||
|
||||
清单不得重复声明同一个文件为 CSS、内容或预览入口。
|
||||
|
||||
## 首页内容和文案
|
||||
|
||||
`content.json` 完全可选。WebSpeak 自带中文、英语、德语、俄语和日语的基础内容,因此纯美术皮肤无需复制翻译文件。若希望为皮肤定制部分文案,可按 locale 覆盖连接首页内容和公开界面文案;未定义的语言、字段或翻译键会回退到 WebSpeak 内容,不要求皮肤重复提供整套文字。当前允许 1–20 个 locale,locale 写作 `en`、`zh-CN`、`ja-JP` 等形式。`defaultLocale` 必须指向一个已定义的 locale。示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"defaultLocale": "en",
|
||||
"locales": {
|
||||
"en": {
|
||||
"home": {
|
||||
"eyebrow": "A room of your own",
|
||||
"title": "Talk",
|
||||
"titleAccent": "together",
|
||||
"description": "Join a voice room from your browser.",
|
||||
"welcomeTitle": "Join the room",
|
||||
"welcomeDescription": "Choose a name and connect.",
|
||||
"features": [
|
||||
{ "title": "Clear voice", "description": "Low-latency Opus audio." }
|
||||
]
|
||||
},
|
||||
"messages": {
|
||||
"home.connect": "Enter the room",
|
||||
"voice.activity-heading": "Voice activity",
|
||||
"demo.heroLead": "A preview customized by this skin."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`home` 支持 `brandName`、`eyebrow`、`title`、`titleAccent`、`description`、`welcomeTitle`、`welcomeDescription` 和 `features`。普通文字最多 500 个字符;`features` 最多 8 项,每项的 `title` 最多 80 个字符、`description` 最多 240 个字符。功能卡片图标和状态由应用提供,皮肤不能通过 JSON 注入节点。
|
||||
|
||||
`messages` 的键是公开页面中翻译调用使用的键;首页/语音页键可在 `web/src/i18n/web-client.ts` 查找,演示页键使用 `demo.` 前缀加字段名(例如 `demo.heroLead`、`demo.speakingNow`)。每个 locale 最多覆盖 200 条,每条文案最多 500 个字符。键只能由小写字母开头,并包含字母、数字或点。语言回退顺序为默认 locale、当前语言和更具体的 locale;之后回退到 WebSpeak 原文。
|
||||
|
||||
管理后台的文字不读取皮肤包,不能通过 `messages` 修改。
|
||||
|
||||
## CSS 皮肤接口
|
||||
|
||||
### 自动隔离
|
||||
|
||||
运行时把 `skin.css` 的每个选择器限定在皮肤自己的公开页面根节点内:
|
||||
|
||||
```css
|
||||
/* 选择器必须使用公开的页面/部件钩子;运行时再加上皮肤根作用域。 */
|
||||
[data-ws-page="voice"] [data-ws-part="voice.member.avatar"] {
|
||||
outline: 2px solid var(--skin-accent);
|
||||
outline-offset: 4px;
|
||||
}
|
||||
```
|
||||
|
||||
实际规则会被限定在类似下面的根节点内,不会匹配 `/admin/**`:
|
||||
|
||||
```css
|
||||
[data-ws-page="voice"] [data-ws-part="voice.member.avatar"]
|
||||
```
|
||||
|
||||
也可以写 `:root { --skin-accent: ... }` 设置皮肤自己的变量;`:root` 会被转换成当前皮肤根。选择器必须包含 `:root`、`[data-ws-page]` 或 `[data-ws-part]`。不要写 `:global()`、`html`、`body` 或 Vue 内部 class 作为公开接口。组件 class 可能随版本调整,`data-ws-part` 才是皮肤作者接口。自定义变量名必须使用 `--skin-` 前缀,不能覆盖 WebSpeak 的内部令牌。
|
||||
|
||||
页面根节点使用 `data-ws-page` 区分 `home`、`voice` 和 `demo`。使用 `data-ws-state` 选择明确状态,如 `active`、`idle`、`current`、`open`、`closed`、`drag-over`、`dragging`、`speaking`、`connected`、`self`、`mine` 或 `other`。语音成员还提供 `data-ws-speaking="true|false"` 和 `data-ws-self="true|false"`。交互元素会带有 `data-ws-critical="true"`;没有专属部件名称的按钮、链接、输入框、滑块和可拖动成员会使用通用部件 `data-ws-part="control"`,并以 `data-ws-control-kind` 标出 `button`、`link`、`input`、`checkbox`、`range`、`select`、`textarea`、`menuitem` 或 `draggable`。
|
||||
|
||||
### 已发布的部件名称
|
||||
|
||||
下列名称来自当前前端模板。对新功能,作者可以先用通用 `control` 部件;后续新增稳定部件会更新本目录。
|
||||
|
||||
| 页面区域 | `data-ws-part` |
|
||||
| --- | --- |
|
||||
| 通用 | `app`、`app.toast`、`control`、`skin.trigger`、`skin.menu`、`skin.option`、`language.trigger`、`language.menu`、`language.option` |
|
||||
| 首页 | `home`、`home.header`、`home.brand`、`home.header-tools`、`home.gateway-status`、`home.content`、`home.hero`、`home.hero.eyebrow`、`home.hero.title`、`home.hero.description`、`home.features`、`home.feature`、`home.visitors`、`home.join-card`、`home.join-card.waveform`、`home.join-card.sonar`、`home.join-title`、`home.join-description`、`home.notice`、`home.form`、`home.server-target`、`home.field-label`、`home.field`、`home.relay-choice`、`home.relay-choice.copy`、`home.server-history`、`home.server-history.group`、`home.favorite-toggle`、`home.identity`、`home.identity-actions`、`home.identity-import.open`、`home.identity-export.button`、`home.identity-import-dialog`、`home.identity-import.header`、`home.identity-import.close`、`home.identity-import.textarea`、`home.identity-import.drop-zone`、`home.identity-import.file-button`、`home.identity-import.error`、`home.identity-import.security`、`home.identity-import.footer`、`home.identity-import.cancel`、`home.identity-import.submit`、`home.connect`、`home.security-note`、`home.footer`、`home.community-dialog` |
|
||||
| 语音工作区 | `voice.shell`、`voice.workspace`、`voice.header`、`voice.header-actions`、`voice.breadcrumbs`、`voice.performance`、`voice.performance.panel`、`voice.performance.route`、`voice.performance.metrics`、`voice.performance.status`、`voice.performance.webrtc-stats`、`voice.connection-status`、`voice.audio-status`、`voice.poke`、`voice.scroll`、`voice.content`、`voice.activity`、`voice.activity.artwork`、`voice.activity-heading`、`voice.screen-share-error`、`voice.members`、`voice.members.empty`、`voice.member`、`voice.member.avatar-wrap`、`voice.member.avatar`、`voice.member.name`、`voice.member.status`、`voice.member.live-indicator`、`voice.member.stop-share`、`voice.member.share-actions`、`voice.member-panel`、`voice.member-panel.heading`、`voice.member-panel.search`、`voice.member-panel.channels`、`voice.channel-group`、`voice.channel-group.heading`、`voice.channel-group.members`、`voice.member-row`、`voice.member-row.avatar`、`voice.member-row.copy`、`voice.member-row.flags`、`voice.member-row.volume`、`voice.whisper-strip`、`voice.audio-dock`、`voice.audio-dock.microphone`、`voice.audio-dock.microphone-panel`、`voice.audio-dock.output`、`voice.audio-dock.output-panel`、`voice.audio-settings`、`voice.mobile-more`、`voice.mobile-nav` |
|
||||
| 聊天与菜单 | `voice.chat`、`voice.chat.tabs`、`voice.chat.tab`、`voice.chat.heading`、`voice.chat.messages`、`voice.chat.event`、`voice.chat.message`、`voice.chat.message-avatar`、`voice.chat.message-body`、`voice.chat.message-bubble`、`voice.chat.empty`、`voice.chat.composer`、`voice.chat.status`、`voice.context-menu-backdrop`、`voice.context-menu`、`voice.context-menu.header`、`voice.context-menu.move-submenu` |
|
||||
| 屏幕共享 | `voice.screen-share-settings`、`voice.screen-share-settings.heading`、`voice.screen-share-settings.fields`、`voice.screen-share-settings.note`、`voice.screen-share-settings.actions`、`voice.screen-player`、`voice.screen-player.stage`、`voice.screen-player.video`、`voice.screen-player.placeholder`、`voice.screen-player.exit`、`voice.screen-player.viewers`、`voice.screen-player.viewer-avatar`、`voice.screen-player.live`、`voice.screen-player.source`、`voice.screen-player.controls`、`voice.screen-player.volume`、`voice.screen-player.fullscreen` |
|
||||
| `/demo` 演示页 | `demo.header`、`demo.brand`、`demo.header-tools`、`demo.badge`、`demo.skin-switcher`、`demo.language-switcher`、`demo.home-link`、`demo.reconnect`、`demo.reconnect.restore`、`demo.layout`、`demo.channels`、`demo.channels.heading`、`demo.channel`、`demo.channel.select`、`demo.channel.members`、`demo.main`、`demo.hero`、`demo.live`、`demo.hero.title`、`demo.hero.description`、`demo.hero.online`、`demo.wave`、`demo.voice-heading`、`demo.voice-grid`、`demo.voice-card`、`demo.avatar`、`demo.member-name`、`demo.member-status`、`demo.chat.heading`、`demo.chat.tabs`、`demo.chat.tab`、`demo.chat.messages`、`demo.chat.message`、`demo.chat.empty`、`demo.chat.composer`、`demo.chat.input`、`demo.chat.send`、`demo.actions`、`demo.actions.heading`、`demo.action.speaking`、`demo.action.poke`、`demo.action.reconnect`、`demo.note`、`demo.user`、`demo.poke-notification`、`demo.poke.dismiss` |
|
||||
|
||||
`voice.member.avatar` 是语音活动区头像;`voice.member-row.avatar` 是右侧成员树头像。状态属性还会使用 `current`、`drag-over`、`dragging`、`self`、`events-empty` 和 `messages-empty`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。
|
||||
|
||||
首页身份选项支持导入 TeamSpeak `.ini` 或身份字段,并可导出为 TeamSpeak `.ini`;导入弹窗解析身份的过程在浏览器本地完成。自定义皮肤可以分别调整身份操作按钮、粘贴区、拖放区域、安全提示和弹窗按钮,但不得隐藏或弱化权限继承与私钥安全提示。
|
||||
|
||||
`voice.activity.artwork` 是位于语音活动区内容上方的固定装饰平面。皮肤可以在其上绘制带透明背景的立绘,让角色压住成员卡片或直播画面的边缘;平面本身不占布局空间、不拦截点击,成员和播放器控件仍保持可交互。只通过背景图及背景定位/缩放来适配素材,不改变其定位和层级。
|
||||
|
||||
`voice.member-panel` 的 `::before` 是成员栏耳机/场景插画层,宿主已固定它的尺寸、位置、透视和前后层级;皮肤只需提供透明背景素材并调整背景显示、滤镜或阴影,不能自行定位或改变尺寸。消息空状态的 `::before` / `::after` 预留给气泡等小型装饰,宿主负责形状位置;皮肤可以绘制边框、底色和点状背景,但标题和说明文字仍由 WebSpeak 翻译并保持可见。
|
||||
|
||||
皮肤与语言选择器的触发按钮、菜单和每个选项都提供上述通用部件钩子。`skin.option` 另带有 `data-ws-skin-id`(内置项为 `builtin.light`、`builtin.dark` 和 `community.illusia-voice`,实例皮肤项为其清单 ID);`language.option` 带有 `data-ws-language`。皮肤可以据此只装饰自己的选择项,而不影响其他皮肤、语言选项或选择器交互。例如:
|
||||
|
||||
```css
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"] {
|
||||
background-image: linear-gradient(110deg, #efffff, #c8f3f2);
|
||||
}
|
||||
```
|
||||
|
||||
### 令牌、字体、动效和图片
|
||||
|
||||
皮肤只负责“画什么样”,不负责“放在哪里”。可用的视觉规则包括文字/背景颜色、背景图片及其裁切、圆角、轮廓、阴影、滤镜和动画;边框可用不占空间的内阴影绘制。推荐先定义皮肤变量,再为公开部件编写视觉规则:
|
||||
|
||||
```css
|
||||
:root {
|
||||
--skin-page-bg: #091317;
|
||||
--skin-panel: #142329;
|
||||
--skin-text: #edf8f5;
|
||||
--skin-muted: #9db5af;
|
||||
--skin-accent: #47dcc4;
|
||||
--skin-card-radius: 20px;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player"] {
|
||||
border-radius: var(--skin-card-radius);
|
||||
box-shadow: 0 18px 50px #0008, inset 0 0 0 1px color-mix(in srgb, var(--skin-accent) 50%, transparent);
|
||||
}
|
||||
```
|
||||
|
||||
`url()` 只允许引用包内图片或 WOFF2 字体。支持 PNG、JPG/JPEG、WebP、AVIF、GIF 和 WOFF2;SVG 不接受。自带字体示例:
|
||||
|
||||
```css
|
||||
@font-face {
|
||||
font-family: "ILLUSIA Sans";
|
||||
src: url("assets/illusia-sans.woff2") format("woff2");
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
[data-ws-page="voice"] { font-family: "ILLUSIA Sans", sans-serif; }
|
||||
```
|
||||
|
||||
字体必须随包附带并拥有可再分发许可。自定义字体可能改变不同语言的字宽,因此校验器会给出提示;发布前必须检查中文、英语、德语、俄语和日语下的标题、按钮和长文案是否仍完整可读。字体族名和 `@keyframes` / `@layer` 名称会自动隔离,避免与其他皮肤冲突。请支持 `prefers-reduced-motion`,并确保焦点、错误、静音、正在说话等状态仍容易辨认。
|
||||
|
||||
### 固定布局与交互边界
|
||||
|
||||
皮肤校验器会拒绝改变布局、定位、尺寸、文字流向/换行或交互命中区域的 CSS 声明,包括 `display`、`position`、`inset`、`z-index`、宽高、内外边距、网格/弹性布局、间距、溢出裁切、变换、指针事件、字号、行高、字距、大小写转换和换行方式等。也不能通过 `all` 重置组件或用伪元素生成/替换文字。动画可以用于颜色、阴影、滤镜等装饰效果,但关键帧同样不能动画化布局属性。
|
||||
|
||||
因此,皮肤可以把成员头像绘制成角色徽章、给屏幕播放器加主题边框和背景、换首页美术素材,但不能移动播放器、压缩文字、扩大/缩小成员卡片、把锚定浮层改成模态弹窗,或挪动按钮的点击区域。用 `background-position` / `background-size` 只调整图片在既有区域中的裁切,不改变组件盒子。轮廓或内阴影可作为不参与排版的描边。
|
||||
|
||||
外观可以因窄屏而更换图片裁切或装饰,但 `@media` 规则也受同一限制,不能用来重排组件。上线前仍需预览桌面与窄屏、所有五种语言、日夜基础主题、键盘焦点、减少动效偏好,并确认浮层和必要控件保持在原位、文字未被裁切。
|
||||
|
||||
## 安全边界和限制
|
||||
|
||||
校验在上传端和服务端执行;服务端只登记有效皮肤包,访客只能下载登记的包。当前限制如下:
|
||||
|
||||
| 项目 | 上限 |
|
||||
| --- | ---: |
|
||||
| ZIP `.wskin` | 20 MiB |
|
||||
| 解压总大小 | 50 MiB |
|
||||
| ZIP 条目数 | 128 |
|
||||
| 单个 CSS 文件 | 512 KiB |
|
||||
| `content.json` | 256 KiB |
|
||||
| 单张图片(包括预览) | 16 MiB |
|
||||
| 单个 WOFF2 字体 | 4 MiB |
|
||||
| 每实例皮肤数 | 50 |
|
||||
| 每实例皮肤包总存储 | 200 MiB |
|
||||
|
||||
压缩包路径穿越、重复/冲突路径、符号链接、异常 ZIP 元数据和本地文件头/目录不一致都会被拒绝。仅允许受支持的 CSS at-rule:`@media`、`@supports`、`@container`、具名 `@layer`、`@font-face` 和 keyframes。`@import`、脚本、HTML、外部网络资源会被拒绝;`!important` 可用于皮肤作用域内的样式。字体 `local()` 也会拒绝,避免绕过包内字体来源。
|
||||
|
||||
必要操作控件(加入/退出、麦克风、设置、菜单、屏幕共享退出、音量、全屏等)及其布局容器不能被隐藏或整体重置。只有下列明确标记为可选的装饰部件,才允许通过不改变排版盒子的透明度效果淡出:
|
||||
|
||||
```css
|
||||
[data-ws-part="home.hero.eyebrow"]
|
||||
[data-ws-part="home.gateway-status"]
|
||||
[data-ws-part="home.features"]
|
||||
[data-ws-part="home.feature"]
|
||||
[data-ws-part="home.visitors"]
|
||||
[data-ws-part="voice.activity-heading"]
|
||||
[data-ws-part="voice.member.avatar"]
|
||||
[data-ws-part="voice.member.live-indicator"]
|
||||
[data-ws-part="voice.member-row.avatar"]
|
||||
[data-ws-part="voice.screen-player.viewer-avatar"]
|
||||
[data-ws-part="voice.screen-player.live"]
|
||||
[data-ws-part="demo.badge"]
|
||||
[data-ws-part="demo.wave"]
|
||||
[data-ws-part="demo.avatar"]
|
||||
[data-ws-part="demo.member-status"]
|
||||
[data-ws-part="demo.note"]
|
||||
```
|
||||
|
||||
上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。关键帧只有在其动画仅被这些可选部件引用时,才可使用透明度归零;若关键帧也被必要控件引用或动画名通过变量指定,则会被拒绝。`clip`、`clip-path` 和 `mask` 一律不允许,避免视觉裁切误伤真实控件。校验器是防止布局回归的边界,不是视觉质量证明;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。
|
||||
|
||||
皮肤可以重画控制外观,但不能重新布置或阻断加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等必要操作。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、日夜基础主题、键盘焦点与减少动效设置。
|
||||
|
||||
CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删除实例里的包会停止从服务器提供该包;已经下载过的浏览器副本会保留在本地存储,因此仍可能在该浏览器的选择器中出现。清除该站点的浏览器数据可移除本地副本。
|
||||
|
||||
## 制作与验收
|
||||
|
||||
1. 复制 `docs/examples/illusia-voice/`,先修改 `manifest.json` 的唯一 `id`、名称、作者、版本和授权。ILLUSIA 是完整的美术参考,不是必须沿用的角色或配色。
|
||||
2. 只使用本目录公开的 `data-ws-part`、`data-ws-page`、状态属性和包内静态资源。不要依赖 Vue 内部 class。
|
||||
3. 使用本地资源编写 `skin.css`;需要改首页文字或公开翻译时补充 `content.json`。
|
||||
4. 在包根目录生成 ZIP,再改扩展名为 `.wskin`。PowerShell 示例:
|
||||
|
||||
```powershell
|
||||
Compress-Archive -Path .\docs\examples\illusia-voice\* -DestinationPath .\illusia-voice.zip -Force
|
||||
Rename-Item .\illusia-voice.zip illusia-voice.wskin
|
||||
```
|
||||
|
||||
5. 在管理员后台 `/admin/skins` 上传。用访客浏览器分别检查连接首页、进入语音页和 `/demo`;测试自定义图片、所有交互控件、语音/静音状态、成员列表、聊天、屏幕共享播放器和设置,确认组件位置、尺寸、排列与未启用皮肤时一致。
|
||||
6. 检查至少一个窄屏尺寸和桌面尺寸,并检查焦点可见、对比度、动效偏好;确认没有第三方素材授权问题。
|
||||
|
||||
当前自动化回归涵盖 ZIP/清单验证、资源路径、CSS 隔离与拒绝规则、文案结构和服务端皮肤目录读写。视觉排版、内容遮挡和浏览器间表现仍须人工预览。
|
||||
@@ -0,0 +1,14 @@
|
||||
# ILLUSIA风
|
||||
|
||||
ILLUSIA风 is a visual-only `.wskin` example built from the local artwork in `illusia-voice/assets/`. It styles the WebSpeak home page, voice workspace, screen-share player, and `/demo` with bright glass surfaces and cyan accents. The homepage skin follows the supplied reference art for the translucent navigation, matching glass skin and language selectors, an illustrated animated ILLUSIA skin option, a floating mascot with a visibly pulsing cyan waveform and expanding halo in the join card, a softly animated cyan aurora inspired by the visitor badge, three feature tiles, character visitor badge, mascot-accented join action, and full-width curved footer. The ambient waveform and halo slow down when reduced motion is enabled instead of disappearing. The voice-room skin uses the resting chibi illustration as the message-empty backdrop and places the main character illustration on the dedicated non-interactive artwork layer so it can rest over the edge of member cards or a live screen-share player without moving or blocking their controls.
|
||||
|
||||
This package intentionally omits `content.json`: the existing WebSpeak translations supply every label and message, including the current and total visitor counts. A skin may optionally add localized copy overrides, but missing locales and fields continue to use WebSpeak's base content. Its CSS is visual-only: WebSpeak retains its component positions, dimensions, text flow, and interactions. In the voice room, the main illustration and headset use separate, non-interactive foreground layers with restrained perspective and shadows; the chat's empty state includes a CSS-drawn speech-bubble ornament, while its translated copy remains visible. The footer wave is a pre-rendered transparent asset sampled from the example's original curve, so it decorates the existing footer instead of introducing another layout element.
|
||||
|
||||
The package source is in [`illusia-voice/`](illusia-voice/). To build it from the repository root:
|
||||
|
||||
```powershell
|
||||
Compress-Archive -Path .\docs\examples\illusia-voice\* -DestinationPath .\docs\examples\illusia-voice.zip -Force
|
||||
Rename-Item .\docs\examples\illusia-voice.zip illusia-voice.wskin -Force
|
||||
```
|
||||
|
||||
Use only artwork you have permission to redistribute when publishing a skin to other WebSpeak instances.
|
||||
|
After Width: | Height: | Size: 1014 KiB |
|
After Width: | Height: | Size: 365 KiB |
|
After Width: | Height: | Size: 113 KiB |
|
After Width: | Height: | Size: 74 KiB |
|
After Width: | Height: | Size: 358 KiB |
|
After Width: | Height: | Size: 738 KiB |
|
After Width: | Height: | Size: 72 KiB |
|
After Width: | Height: | Size: 249 KiB |
|
After Width: | Height: | Size: 7.7 KiB |
|
After Width: | Height: | Size: 168 KiB |
|
After Width: | Height: | Size: 217 KiB |
|
After Width: | Height: | Size: 85 KiB |
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "community.illusia-voice",
|
||||
"name": "ILLUSIA风",
|
||||
"version": "1.0.27",
|
||||
"author": "WebSpeak Project",
|
||||
"license": "All rights reserved",
|
||||
"description": "A bright original-character art skin for the home, voice room, and demo pages.",
|
||||
"entry": "skin.css",
|
||||
"preview": "assets/background-composite.webp",
|
||||
"minAppVersion": "0.2.6"
|
||||
}
|
||||
@@ -0,0 +1,972 @@
|
||||
/* ILLUSIA风: bright glass surfaces, cyan accents, and project artwork. */
|
||||
:root {
|
||||
--skin-illusia-ink: #123849;
|
||||
--skin-illusia-muted: #4f6974;
|
||||
--skin-illusia-teal: #087e86;
|
||||
--skin-illusia-aqua: #47c9d4;
|
||||
--skin-illusia-glass: rgba(250, 254, 255, .96);
|
||||
--skin-illusia-line: rgba(115, 205, 218, .38);
|
||||
--skin-illusia-shadow: 0 20px 56px rgba(29, 91, 113, .16);
|
||||
}
|
||||
|
||||
/* Homepage uses the full-resolution original-character composition. */
|
||||
[data-ws-part="home"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
background-color: #eaf7fc;
|
||||
background-image:
|
||||
radial-gradient(ellipse at 14% 78%, rgba(90, 222, 230, .28), transparent 34%),
|
||||
radial-gradient(ellipse at 83% 21%, rgba(94, 190, 255, .24), transparent 30%),
|
||||
radial-gradient(ellipse at 52% 56%, rgba(190, 239, 255, .16), transparent 42%),
|
||||
linear-gradient(90deg, rgba(246, 252, 255, .91) 0%, rgba(246, 252, 255, .82) 33%, rgba(246, 252, 255, .32) 60%, rgba(246, 252, 255, .08) 100%),
|
||||
url("assets/background-composite.webp");
|
||||
background-position: 0% 100%, 100% 0%, 50% 50%, center, center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: 132% 130%, 122% 124%, 116% 116%, cover, cover;
|
||||
animation: illusia-home-aura 18s ease-in-out infinite alternate;
|
||||
}
|
||||
|
||||
@keyframes illusia-home-aura {
|
||||
from { background-position: 0% 100%, 100% 0%, 50% 50%, center, center; }
|
||||
to { background-position: 20% 82%, 78% 18%, 55% 45%, center, center; }
|
||||
}
|
||||
|
||||
[data-ws-part="home.header"] {
|
||||
border-color: rgba(255, 255, 255, .85);
|
||||
border-radius: 999px;
|
||||
background: linear-gradient(135deg, rgba(255, 255, 255, .8), rgba(255, 255, 255, .45));
|
||||
box-shadow: 0 26px 80px rgba(78, 150, 173, .17), inset 0 1px 0 rgba(255, 255, 255, .9);
|
||||
backdrop-filter: blur(22px) saturate(1.18);
|
||||
}
|
||||
|
||||
[data-ws-part="home.header"] [data-ws-part="control"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(255, 255, 255, .76);
|
||||
border-radius: 999px;
|
||||
background: rgba(250, 254, 255, .84);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .42);
|
||||
}
|
||||
|
||||
[data-ws-part="home.header"] [data-ws-part="control"]:hover {
|
||||
background: rgba(255, 255, 255, .98);
|
||||
}
|
||||
|
||||
/* ARIA selectors raise specificity over component defaults without private classes. */
|
||||
[data-ws-part="skin.trigger"][aria-haspopup="listbox"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(255, 255, 255, .82);
|
||||
border-radius: 999px;
|
||||
background: rgba(250, 254, 255, .86);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .5);
|
||||
}
|
||||
|
||||
[data-ws-part="skin.trigger"][aria-haspopup="listbox"]:hover,
|
||||
[data-ws-part="skin.trigger"][aria-haspopup="listbox"]:focus-visible,
|
||||
[data-ws-part="skin.trigger"][aria-haspopup="listbox"][aria-expanded="true"][data-ws-state="open"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(71, 201, 212, .52);
|
||||
background: rgba(255, 255, 255, .98);
|
||||
}
|
||||
|
||||
[data-ws-part="skin.menu"][role="listbox"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(104, 196, 211, .58);
|
||||
border-radius: 15px;
|
||||
background: linear-gradient(145deg, rgba(250, 255, 255, .98), rgba(222, 246, 250, .96));
|
||||
box-shadow: 0 18px 42px rgba(29, 115, 139, .22), inset 0 1px 0 rgba(255, 255, 255, .96);
|
||||
backdrop-filter: blur(18px) saturate(1.18);
|
||||
}
|
||||
|
||||
[data-ws-part="skin.option"][role="option"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-radius: 9px;
|
||||
background: rgba(255, 255, 255, .54);
|
||||
transition: color .16s, background .16s, border-color .16s, box-shadow .16s;
|
||||
}
|
||||
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"] {
|
||||
color: #075e68;
|
||||
border-color: rgba(82, 195, 204, .46);
|
||||
background-image: linear-gradient(112deg, rgba(255, 255, 255, .96), rgba(225, 250, 249, .96), rgba(188, 241, 237, .94), rgba(255, 255, 255, .96));
|
||||
background-position: 0% 50%;
|
||||
background-size: 240% 100%;
|
||||
box-shadow: 0 4px 14px rgba(30, 170, 184, .17), inset 0 0 0 1px rgba(255, 255, 255, .86);
|
||||
animation: illusia-option-gradient 8s ease-in-out infinite alternate;
|
||||
}
|
||||
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"] > :first-child {
|
||||
color: #07858a;
|
||||
filter: drop-shadow(0 0 5px rgba(71, 201, 212, .54));
|
||||
}
|
||||
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"]:hover,
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"]:focus-visible,
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"][aria-selected="true"] {
|
||||
color: #056e76;
|
||||
border-color: rgba(44, 186, 197, .7);
|
||||
background-image: linear-gradient(112deg, #faffff 0%, #c8f5f1 36%, #82e2dc 70%, #d9fbf8 100%);
|
||||
background-position: 100% 50%;
|
||||
box-shadow: 0 5px 18px rgba(30, 170, 184, .23), inset 0 0 0 1px rgba(255, 255, 255, .94);
|
||||
}
|
||||
|
||||
@keyframes illusia-option-gradient {
|
||||
from { background-position: 0% 50%; }
|
||||
to { background-position: 100% 50%; }
|
||||
}
|
||||
|
||||
[data-ws-part="language.trigger"][aria-haspopup="listbox"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(255, 255, 255, .82);
|
||||
border-radius: 999px;
|
||||
background: rgba(250, 254, 255, .86);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .5);
|
||||
}
|
||||
|
||||
[data-ws-part="language.trigger"][aria-haspopup="listbox"]:hover,
|
||||
[data-ws-part="language.trigger"][aria-haspopup="listbox"]:focus-visible,
|
||||
[data-ws-part="language.trigger"][aria-haspopup="listbox"][aria-expanded="true"][data-ws-state="open"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(71, 201, 212, .52);
|
||||
background: rgba(255, 255, 255, .98);
|
||||
}
|
||||
|
||||
[data-ws-part="language.menu"][role="listbox"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(104, 196, 211, .58);
|
||||
border-radius: 15px;
|
||||
background: linear-gradient(145deg, rgba(250, 255, 255, .98), rgba(222, 246, 250, .96));
|
||||
box-shadow: 0 18px 42px rgba(29, 115, 139, .22), inset 0 1px 0 rgba(255, 255, 255, .96);
|
||||
backdrop-filter: blur(18px) saturate(1.18);
|
||||
}
|
||||
|
||||
[data-ws-part="language.option"][role="option"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-radius: 9px;
|
||||
background: rgba(255, 255, 255, .54);
|
||||
}
|
||||
|
||||
[data-ws-part="language.option"][role="option"]:hover,
|
||||
[data-ws-part="language.option"][role="option"]:focus-visible,
|
||||
[data-ws-part="language.option"][role="option"][aria-selected="true"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(71, 201, 212, .42);
|
||||
background: rgba(211, 245, 248, .92);
|
||||
}
|
||||
|
||||
[data-ws-part="skin.option"][role="option"]:hover,
|
||||
[data-ws-part="skin.option"][role="option"]:focus-visible,
|
||||
[data-ws-part="skin.option"][role="option"][aria-selected="true"] {
|
||||
color: #087e86;
|
||||
border-color: rgba(71, 201, 212, .42);
|
||||
background: rgba(211, 245, 248, .92);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .82);
|
||||
}
|
||||
|
||||
[data-ws-part="home.brand"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
}
|
||||
|
||||
[data-ws-part="home.brand"] strong,
|
||||
[data-ws-part="home.hero.title"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="home.brand"] small,
|
||||
[data-ws-part="home.hero.description"],
|
||||
[data-ws-part="home.join-description"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="home.hero.title"] em {
|
||||
color: var(--skin-illusia-teal);
|
||||
text-shadow: 0 8px 28px rgba(47, 192, 202, .2);
|
||||
}
|
||||
|
||||
[data-ws-part="home.hero.eyebrow"] {
|
||||
color: #087a76;
|
||||
}
|
||||
|
||||
[data-ws-part="home.feature"] {
|
||||
border-color: rgba(255, 255, 255, .94);
|
||||
border-radius: 18px;
|
||||
background: rgba(255, 255, 255, .79);
|
||||
box-shadow: 0 14px 28px rgba(68, 158, 173, .12), inset 0 0 0 1px rgba(255, 255, 255, .42);
|
||||
backdrop-filter: blur(12px) saturate(1.08);
|
||||
}
|
||||
|
||||
[data-ws-part="home.feature"] > span:first-child {
|
||||
box-shadow: 0 5px 14px rgba(43, 157, 167, .12), inset 0 0 0 1px rgba(255, 255, 255, .56);
|
||||
}
|
||||
|
||||
[data-ws-part="home.feature"] b {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="home.feature"] small {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="home.visitors"] {
|
||||
color: #075c67;
|
||||
border-color: var(--skin-illusia-line);
|
||||
background-color: rgba(247, 254, 255, .9);
|
||||
background-image: linear-gradient(105deg, rgba(247, 254, 255, .98), rgba(237, 252, 253, .84));
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: cover;
|
||||
box-shadow: 0 10px 28px rgba(19, 142, 157, .14), inset 0 0 0 1px rgba(255, 255, 255, .72);
|
||||
backdrop-filter: blur(14px) saturate(1.12);
|
||||
}
|
||||
|
||||
[data-ws-part="home.visitors"] > span:nth-child(2) {
|
||||
color: transparent;
|
||||
background-color: transparent;
|
||||
background-image: url("assets/visitor-avatar.webp");
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: cover;
|
||||
box-shadow: 0 0 0 3px rgba(71, 201, 212, .26), 0 5px 16px rgba(19, 142, 157, .2);
|
||||
}
|
||||
|
||||
[data-ws-part="home.visitors"] > span:nth-child(2) svg {
|
||||
color: transparent;
|
||||
}
|
||||
|
||||
[data-ws-part="home.visitors"] > span:last-child {
|
||||
color: #41bdcc;
|
||||
text-shadow: 0 0 12px rgba(71, 201, 212, .42);
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(255, 255, 255, .9);
|
||||
border-radius: 26px;
|
||||
background-color: var(--skin-illusia-glass);
|
||||
background-image: url("assets/banner-mascot-blob.webp");
|
||||
background-position: right 18px top 10px;
|
||||
background-repeat: no-repeat;
|
||||
background-size: 96px 68px;
|
||||
box-shadow: var(--skin-illusia-shadow), 0 0 15px rgba(71, 201, 212, .14), inset 0 0 0 1px rgba(255, 255, 255, .84);
|
||||
backdrop-filter: blur(22px);
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card.waveform"] {
|
||||
color: #47c9d4;
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card.waveform"] i {
|
||||
box-shadow: 0 0 8px rgba(71, 201, 212, .52);
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card.sonar"] {
|
||||
color: rgba(71, 201, 212, .72);
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card.sonar"] i {
|
||||
box-shadow: 0 0 12px rgba(71, 201, 212, .16);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"] {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-title"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="home.field"] {
|
||||
color: #4f6974;
|
||||
border-color: rgba(134, 190, 200, .42);
|
||||
border-radius: 12px;
|
||||
background: rgba(232, 244, 247, .96);
|
||||
box-shadow: inset 0 0 0 1px rgba(134, 190, 200, .24);
|
||||
}
|
||||
|
||||
[data-ws-part="home.field"] input {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="home.field"] input::placeholder {
|
||||
color: #8ba4aa;
|
||||
}
|
||||
|
||||
[data-ws-part="home.field-label"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="home"] [data-ws-part="home.connect"] {
|
||||
color: #fff;
|
||||
border-radius: 14px;
|
||||
background-color: var(--skin-illusia-teal);
|
||||
background:
|
||||
url("assets/button-mascot.webp") right 4px center / 112px 74px no-repeat,
|
||||
linear-gradient(100deg, #38d6d0 0%, #0c9caf 62%, #08788d 100%) center / cover no-repeat;
|
||||
box-shadow: 0 12px 22px rgba(16, 181, 192, .24), inset 0 1px 0 rgba(255, 255, 255, .55), inset 0 0 0 1px rgba(141, 255, 255, .52);
|
||||
}
|
||||
|
||||
[data-ws-part="home"] [data-ws-part="home.connect"]:hover {
|
||||
background-color: #087078;
|
||||
box-shadow: 0 14px 30px rgba(8, 126, 134, .3);
|
||||
}
|
||||
|
||||
[data-ws-part="home.security-note"],
|
||||
[data-ws-part="home.footer"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="home.footer"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
border-color: transparent;
|
||||
background-color: transparent;
|
||||
background-image: url("assets/footer-wave.png");
|
||||
background-position: center top;
|
||||
background-repeat: no-repeat;
|
||||
background-size: 100% 58px;
|
||||
box-shadow: none;
|
||||
backdrop-filter: blur(8px) saturate(1.04);
|
||||
}
|
||||
|
||||
/* Voice room: let the artwork flow through the UI instead of stacking opaque cards. */
|
||||
:root {
|
||||
--skin-room-line: rgba(76, 176, 193, .3);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.shell"] {
|
||||
color-scheme: light;
|
||||
color: var(--skin-illusia-ink);
|
||||
background-color: #dff4f8;
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(21, 139, 157, .075) 1px, transparent 1.55px),
|
||||
radial-gradient(circle at 100% 0%, transparent 0 188px, rgba(71, 201, 212, .13) 189px 190px, transparent 191px 229px, rgba(71, 201, 212, .09) 230px 231px, transparent 232px),
|
||||
radial-gradient(ellipse at 13% 5%, rgba(107, 226, 232, .2), transparent 36%),
|
||||
linear-gradient(125deg, rgba(229, 248, 251, .19), rgba(239, 251, 253, .06) 48%, rgba(190, 235, 242, .22)),
|
||||
url("assets/bg-room-main.webp");
|
||||
background-position: 0 0, right top, left top, center, center;
|
||||
background-repeat: repeat, no-repeat, no-repeat, no-repeat, no-repeat;
|
||||
background-size: 24px 24px, 560px 450px, auto, auto, cover;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.workspace"] {
|
||||
background: linear-gradient(145deg, rgba(239, 251, 253, .22), rgba(218, 244, 248, .12) 48%, rgba(245, 253, 254, .2));
|
||||
backdrop-filter: blur(2px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity"] {
|
||||
border-color: rgba(113, 211, 222, .62);
|
||||
border-radius: 24px;
|
||||
background-color: rgba(227, 247, 250, .64);
|
||||
background-image:
|
||||
radial-gradient(ellipse at 82% 48%, rgba(91, 215, 224, .19), rgba(91, 215, 224, .04) 34%, transparent 65%),
|
||||
linear-gradient(90deg, rgba(230, 248, 251, .78), rgba(230, 248, 251, .36) 38%, rgba(230, 248, 251, .08) 72%),
|
||||
url("assets/bg-room-main.webp");
|
||||
background-position: right 5% center, center, center 48%;
|
||||
background-repeat: no-repeat;
|
||||
background-size: 48% 100%, 100% 100%, cover;
|
||||
box-shadow: 0 15px 38px rgba(30, 111, 132, .13), inset 0 0 0 1px rgba(255, 255, 255, .7);
|
||||
backdrop-filter: blur(10px) saturate(1.08);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity.artwork"] {
|
||||
background-image: url("assets/banner-character-main.webp");
|
||||
background-position: right 16px bottom 8px;
|
||||
background-size: auto 150px;
|
||||
filter: drop-shadow(0 18px 22px rgba(30, 113, 134, .2));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.header"] {
|
||||
border-color: rgba(126, 191, 203, .36);
|
||||
background: linear-gradient(105deg, rgba(249, 254, 255, .76), rgba(222, 246, 250, .57) 56%, rgba(247, 253, 254, .72));
|
||||
box-shadow: 0 8px 28px rgba(27, 92, 112, .08), inset 0 1px 0 rgba(255, 255, 255, .62);
|
||||
backdrop-filter: blur(16px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-panel"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: var(--skin-room-line);
|
||||
background-color: rgba(221, 245, 249, .66);
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(25, 145, 161, .065) 1px, transparent 1.5px),
|
||||
radial-gradient(circle at 100% 0%, transparent 0 86px, rgba(71, 201, 212, .16) 87px 88px, transparent 89px 119px, rgba(71, 201, 212, .1) 120px 121px, transparent 122px),
|
||||
radial-gradient(ellipse at 100% 0%, rgba(107, 226, 232, .2), transparent 43%),
|
||||
linear-gradient(155deg, rgba(248, 254, 255, .75), rgba(222, 246, 249, .58) 48%, rgba(213, 241, 246, .7));
|
||||
background-position: 0 0, right top, right top, center;
|
||||
background-repeat: repeat, no-repeat, no-repeat, no-repeat;
|
||||
background-size: 22px 22px, 360px 320px, auto, auto;
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
/* Keep the headset as an independent foreground object instead of flattening
|
||||
it into the member rail's background. Its slight perspective and shadow
|
||||
make it sit in front of the room, while the actual controls remain above it. */
|
||||
[data-ws-part="voice.member-panel"]::before {
|
||||
background-image: url("assets/foreground-headphone.webp");
|
||||
background-position: left bottom;
|
||||
background-repeat: no-repeat;
|
||||
background-size: contain;
|
||||
filter: drop-shadow(16px 18px 17px rgba(36, 105, 119, .24));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-panel.search"] {
|
||||
color: #4f7982;
|
||||
border-color: rgba(103, 186, 198, .28);
|
||||
background: linear-gradient(110deg, rgba(232, 249, 251, .86), rgba(216, 242, 247, .68));
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .58);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-panel.search"] input {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-panel.search"] input::placeholder {
|
||||
color: #78979d;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.channel-group"] {
|
||||
border-color: rgba(8, 126, 134, .32);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.channel-group"][data-ws-state="current"] {
|
||||
border-color: rgba(8, 126, 134, .48);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.channel-group.heading"] {
|
||||
color: #386b75;
|
||||
border-radius: 10px;
|
||||
background: linear-gradient(100deg, rgba(223, 246, 249, .68), rgba(237, 250, 251, .34));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.channel-group.heading"][data-ws-state="current"] {
|
||||
color: #087e86;
|
||||
background: linear-gradient(100deg, rgba(179, 235, 239, .78), rgba(224, 248, 249, .5));
|
||||
box-shadow: inset 3px 0 0 rgba(37, 175, 188, .74);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-row"] {
|
||||
border-radius: 11px;
|
||||
transition: background .16s ease, box-shadow .16s ease;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-row"]:hover,
|
||||
[data-ws-part="voice.member-row"][data-ws-state="speaking"] {
|
||||
background: linear-gradient(100deg, rgba(198, 240, 243, .38), rgba(238, 251, 252, .28));
|
||||
box-shadow: inset 0 0 0 1px rgba(92, 190, 202, .16);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member"] {
|
||||
border-color: rgba(91, 184, 198, .36);
|
||||
border-radius: 20px;
|
||||
background-color: rgba(222, 246, 249, .7);
|
||||
background-image:
|
||||
radial-gradient(ellipse at 100% 0%, rgba(102, 220, 226, .24), transparent 62%),
|
||||
linear-gradient(145deg, rgba(250, 255, 255, .72), rgba(224, 246, 249, .62) 56%, rgba(210, 241, 246, .66));
|
||||
box-shadow: 0 12px 32px rgba(31, 99, 123, .12), inset 0 1px 0 rgba(255, 255, 255, .76);
|
||||
backdrop-filter: blur(12px) saturate(1.08);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.avatar"] {
|
||||
outline: 2px solid rgba(71, 201, 212, .8);
|
||||
outline-offset: 4px;
|
||||
box-shadow: 0 0 24px rgba(71, 201, 212, .28);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.live-indicator"] {
|
||||
color: #08706f;
|
||||
border-radius: 999px;
|
||||
background: rgba(237, 255, 251, .96);
|
||||
box-shadow: 0 6px 20px rgba(42, 160, 162, .18), inset 0 0 0 1px rgba(71, 201, 212, .5);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
border-color: rgba(116, 194, 205, .42);
|
||||
border-radius: 22px;
|
||||
background-color: rgba(222, 246, 249, .8);
|
||||
background-image:
|
||||
radial-gradient(circle at 0% 100%, transparent 0 35px, rgba(71, 201, 212, .16) 36px 37px, transparent 38px 57px, rgba(71, 201, 212, .1) 58px 59px, transparent 60px),
|
||||
linear-gradient(125deg, rgba(250, 255, 255, .76), rgba(222, 246, 249, .68) 55%, rgba(205, 238, 244, .76));
|
||||
box-shadow: 0 12px 34px rgba(28, 91, 111, .16), inset 0 1px 0 rgba(255, 255, 255, .74);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat"] {
|
||||
border-color: rgba(100, 184, 198, .34);
|
||||
border-radius: 20px;
|
||||
background-color: rgba(221, 245, 249, .58);
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(21, 139, 157, .055) 1px, transparent 1.5px),
|
||||
radial-gradient(ellipse at 0% 100%, rgba(102, 220, 226, .16), transparent 42%),
|
||||
linear-gradient(145deg, rgba(249, 254, 255, .72), rgba(226, 247, 250, .48) 52%, rgba(214, 242, 247, .62));
|
||||
background-position: 0 0, left bottom, center;
|
||||
background-repeat: repeat, no-repeat, no-repeat;
|
||||
background-size: 24px 24px, auto, auto;
|
||||
backdrop-filter: blur(14px) saturate(1.05);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.tab"] {
|
||||
color: #547780;
|
||||
border-color: rgba(95, 180, 193, .24);
|
||||
background: linear-gradient(115deg, rgba(242, 252, 253, .72), rgba(217, 243, 247, .56));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.tab"]:hover,
|
||||
[data-ws-part="voice.chat.tab"][data-ws-state="active"] {
|
||||
color: #087e86;
|
||||
border-color: rgba(71, 201, 212, .48);
|
||||
background: linear-gradient(115deg, rgba(207, 242, 245, .86), rgba(232, 250, 251, .72));
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .6);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
background-color: rgba(218, 244, 248, .4);
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(21, 139, 157, .075) 1px, transparent 1.5px),
|
||||
radial-gradient(circle at 100% 50%, transparent 0 102px, rgba(71, 201, 212, .13) 103px 104px, transparent 105px 137px, rgba(71, 201, 212, .09) 138px 139px, transparent 140px),
|
||||
linear-gradient(100deg, rgba(237, 250, 252, .76), rgba(228, 247, 250, .38) 52%, rgba(205, 240, 245, .26)),
|
||||
url("assets/chat-empty-chibi.webp");
|
||||
background-position: 0 0, right center, center, center 10px;
|
||||
background-repeat: repeat, no-repeat, no-repeat, no-repeat;
|
||||
background-size: 22px 22px, 300px 250px, cover, min(340px, 46vw) auto;
|
||||
backdrop-filter: blur(8px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
background-color: rgba(218, 244, 248, .4);
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(21, 139, 157, .075) 1px, transparent 1.5px),
|
||||
radial-gradient(circle at 100% 50%, transparent 0 102px, rgba(71, 201, 212, .13) 103px 104px, transparent 105px 137px, rgba(71, 201, 212, .09) 138px 139px, transparent 140px),
|
||||
linear-gradient(100deg, rgba(237, 250, 252, .68), rgba(228, 247, 250, .34) 50%, rgba(205, 240, 245, .08)),
|
||||
url("assets/chat-empty-chibi.webp");
|
||||
background-position: 0 0, right center, center, center 8px;
|
||||
background-repeat: repeat, no-repeat, no-repeat, no-repeat;
|
||||
background-size: 22px 22px, 300px 250px, cover, min(340px, 46vw) auto;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"]::before {
|
||||
color: rgba(71, 126, 148, .9);
|
||||
border-radius: 50%;
|
||||
background-color: rgba(250, 255, 255, .66);
|
||||
background-image:
|
||||
radial-gradient(circle, #527f91 0 1.6px, transparent 1.9px),
|
||||
radial-gradient(circle, #527f91 0 1.6px, transparent 1.9px),
|
||||
radial-gradient(circle, #527f91 0 1.6px, transparent 1.9px);
|
||||
background-position: 12px 16px, 22px 12px, 32px 9px;
|
||||
background-repeat: no-repeat;
|
||||
box-shadow: 0 3px 8px rgba(48, 115, 132, .1);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"]::after {
|
||||
color: rgba(71, 126, 148, .9);
|
||||
background: rgba(250, 255, 255, .7);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"] > strong,
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"] > span {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"] strong {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"] span {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.members.empty"] {
|
||||
color: #587a82;
|
||||
border-color: rgba(78, 176, 191, .38);
|
||||
background: linear-gradient(120deg, rgba(223, 247, 249, .68), rgba(235, 250, 251, .42));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.members.empty"] strong {
|
||||
color: #315c66;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.message-bubble"] {
|
||||
color: #315360;
|
||||
background: linear-gradient(135deg, rgba(250, 255, 255, .78), rgba(216, 243, 247, .68));
|
||||
box-shadow: 0 4px 14px rgba(34, 117, 136, .08), inset 0 0 0 1px rgba(255, 255, 255, .54);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.message"][data-ws-state="mine"] [data-ws-part="voice.chat.message-bubble"] {
|
||||
color: #fff;
|
||||
background: linear-gradient(130deg, #0b9da1, #087985);
|
||||
box-shadow: 0 5px 16px rgba(8, 126, 134, .2);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity-heading"] h2,
|
||||
[data-ws-part="voice.chat.heading"] h2 {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity-heading"] span,
|
||||
[data-ws-part="voice.chat.heading"] span {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.name"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.status"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
/* These controls use the active day/night palette by default. Give them the
|
||||
same readable glass treatment as the rest of this intentionally bright skin. */
|
||||
[data-ws-part="voice.performance"] > [data-ws-part="control"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(115, 205, 218, .42);
|
||||
background: rgba(249, 253, 255, .9);
|
||||
box-shadow: 0 5px 16px rgba(29, 91, 113, .1), inset 0 1px 0 rgba(255, 255, 255, .9);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance"] > [data-ws-part="control"]:hover,
|
||||
[data-ws-part="voice.performance"] > [data-ws-part="control"][aria-expanded="true"] {
|
||||
color: #075f69;
|
||||
border-color: rgba(71, 201, 212, .72);
|
||||
background: rgba(255, 255, 255, .98);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.panel"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .4);
|
||||
background-color: rgba(223, 246, 249, .96);
|
||||
background-image:
|
||||
radial-gradient(circle at 100% 0%, rgba(71, 201, 212, .16), transparent 52%),
|
||||
linear-gradient(145deg, rgba(250, 255, 255, .96), rgba(224, 246, 249, .94));
|
||||
box-shadow: var(--skin-illusia-shadow);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.panel"] small,
|
||||
[data-ws-part="voice.performance.status"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.panel"] [data-ws-part="control"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(115, 205, 218, .36);
|
||||
background: rgba(232, 247, 248, .9);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.route"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.route"] span,
|
||||
[data-ws-part="voice.performance.metrics"] article,
|
||||
[data-ws-part="voice.performance.webrtc-stats"] [data-ws-part="control"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
border-color: rgba(115, 205, 218, .28);
|
||||
background: linear-gradient(135deg, rgba(232, 248, 250, .88), rgba(212, 241, 245, .72));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.metrics"] strong,
|
||||
[data-ws-part="voice.performance.webrtc-stats"] strong {
|
||||
color: var(--skin-illusia-teal);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.metrics"] small,
|
||||
[data-ws-part="voice.performance.metrics"] span,
|
||||
[data-ws-part="voice.performance.webrtc-stats"] small,
|
||||
[data-ws-part="voice.performance.webrtc-stats"] span {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] strong {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] span {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] button[data-ws-part="control"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: transparent;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] button[data-ws-part="control"]:hover,
|
||||
[data-ws-part="voice.audio-dock"] button[data-ws-part="control"]:focus-visible {
|
||||
color: #075f69;
|
||||
border-color: rgba(71, 201, 212, .4);
|
||||
background: rgba(221, 246, 247, .86);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock.microphone-panel"],
|
||||
[data-ws-part="voice.audio-dock.output-panel"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .38);
|
||||
background: linear-gradient(145deg, rgba(250, 255, 255, .98), rgba(221, 246, 249, .96));
|
||||
box-shadow: var(--skin-illusia-shadow);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock.microphone-panel"] strong,
|
||||
[data-ws-part="voice.audio-dock.output-panel"] strong {
|
||||
color: var(--skin-illusia-teal);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.composer"] {
|
||||
background: linear-gradient(110deg, rgba(249, 254, 255, .82), rgba(225, 247, 250, .76) 58%, rgba(214, 242, 247, .82));
|
||||
box-shadow: inset 0 0 0 1px rgba(115, 205, 218, .32), 0 5px 18px rgba(36, 130, 148, .07);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.composer"]:focus-within {
|
||||
background: linear-gradient(110deg, rgba(250, 255, 255, .9), rgba(211, 242, 246, .82));
|
||||
box-shadow: inset 0 0 0 1px rgba(71, 201, 212, .55), 0 6px 20px rgba(36, 130, 148, .11);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.composer"] input {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.composer"] input::placeholder {
|
||||
color: #718b92;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.composer"] button[data-ws-part="control"] {
|
||||
color: #fff;
|
||||
border-color: rgba(8, 126, 134, .18);
|
||||
background: linear-gradient(135deg, #0a9291, #087580);
|
||||
box-shadow: 0 5px 13px rgba(8, 126, 134, .2);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.share-actions"] button[data-ws-part="control"] {
|
||||
color: #086b72;
|
||||
border-color: rgba(71, 201, 212, .45);
|
||||
background: rgba(237, 252, 251, .96);
|
||||
box-shadow: 0 3px 10px rgba(29, 120, 130, .12);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.share-actions"] button[data-ws-part="control"]:hover,
|
||||
[data-ws-part="voice.member.share-actions"] button[data-ws-part="control"]:focus-visible {
|
||||
color: #064f59;
|
||||
border-color: rgba(8, 126, 134, .58);
|
||||
background: rgba(219, 247, 246, .98);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.share-actions"] button[data-ws-part="control"][data-ws-state="viewing"] {
|
||||
color: #fff;
|
||||
border-color: #087e86;
|
||||
background: linear-gradient(135deg, #0a9291, #087580);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.stop-share"] {
|
||||
color: #a43e48;
|
||||
border-color: rgba(255, 255, 255, .96);
|
||||
background: #fff6f5;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .42);
|
||||
background: rgba(250, 254, 255, .98);
|
||||
box-shadow: var(--skin-illusia-shadow);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings.heading"] h2 {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings.heading"] p,
|
||||
[data-ws-part="voice.screen-share-settings.fields"] label,
|
||||
[data-ws-part="voice.screen-share-settings.note"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings"] select {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .42);
|
||||
background: rgba(235, 247, 248, .94);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings"] [data-ws-part="control"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(115, 205, 218, .38);
|
||||
background: rgba(232, 247, 248, .92);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings.actions"] [data-ws-part="control"] {
|
||||
color: #fff;
|
||||
border-color: rgba(8, 126, 134, .2);
|
||||
background: linear-gradient(135deg, #0a9291, #087580);
|
||||
}
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
[data-ws-part="voice.chat.empty"] {
|
||||
background-position: 0 0, right 8px center, center, center 8px;
|
||||
background-size: 22px 22px, 260px 220px, cover, min(300px, 66vw) auto;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity"] {
|
||||
background-position: right 1% center, center, center 48%;
|
||||
background-size: 56% 100%, 100% 100%, cover;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity.artwork"] {
|
||||
background-position: right 12px bottom 6px;
|
||||
background-size: auto 118px;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"] {
|
||||
background-position: 0 0, right center, center, center 8px;
|
||||
background-size: 22px 22px, 260px 220px, cover, min(300px, 66vw) auto;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 740px) {
|
||||
[data-ws-part="voice.activity"] {
|
||||
background-image: none;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity.artwork"] {
|
||||
background-image: none;
|
||||
}
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player"] {
|
||||
border-radius: 24px;
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .58);
|
||||
background: linear-gradient(135deg, rgba(250, 255, 255, .96), rgba(220, 245, 250, .94));
|
||||
box-shadow: 0 22px 60px rgba(10, 68, 88, .3), inset 0 0 0 1px rgba(185, 246, 249, .55);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.stage"] {
|
||||
border-radius: 22px;
|
||||
background: radial-gradient(ellipse at 50% 38%, rgba(248, 255, 255, .98), rgba(220, 246, 250, .92) 58%, rgba(202, 237, 244, .9));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.video"] {
|
||||
background: #e5f4f8;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.placeholder"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.placeholder"] strong {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.exit"],
|
||||
[data-ws-part="voice.screen-player.fullscreen"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .62);
|
||||
background: rgba(250, 255, 255, .9);
|
||||
box-shadow: 0 5px 18px rgba(40, 126, 148, .18);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.viewers"],
|
||||
[data-ws-part="voice.screen-player.volume"],
|
||||
[data-ws-part="voice.screen-player.source"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .58);
|
||||
background: rgba(250, 255, 255, .88);
|
||||
box-shadow: 0 5px 18px rgba(40, 126, 148, .16);
|
||||
backdrop-filter: blur(12px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.viewer-avatar"] {
|
||||
border-color: rgba(250, 255, 255, .96);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.live"] {
|
||||
border-radius: 999px;
|
||||
color: #075e68;
|
||||
border-color: rgba(82, 195, 204, .56);
|
||||
background: rgba(239, 253, 254, .94);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .76), 0 5px 18px rgba(40, 126, 148, .16);
|
||||
text-shadow: none;
|
||||
backdrop-filter: blur(12px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.viewer-avatar"] {
|
||||
box-shadow: 0 0 0 2px rgba(255, 255, 255, .94), 0 0 0 4px rgba(71, 201, 212, .72);
|
||||
}
|
||||
|
||||
/* The demo keeps its original controls, labels, and interactions. */
|
||||
[data-ws-page="demo"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
background-color: #eaf7fc;
|
||||
background-image: url("assets/foreground-headphone.webp"), linear-gradient(rgba(239, 250, 253, .7), rgba(239, 250, 253, .82)), url("assets/bg-room-main.webp");
|
||||
background-position: left bottom, center, center;
|
||||
background-repeat: no-repeat, no-repeat, no-repeat;
|
||||
background-size: min(34vw, 430px) auto, auto, cover;
|
||||
background-attachment: fixed, scroll, scroll;
|
||||
}
|
||||
|
||||
[data-ws-part="demo.header"] {
|
||||
border-color: rgba(126, 191, 203, .3);
|
||||
background: rgba(250, 254, 255, .72);
|
||||
backdrop-filter: blur(16px);
|
||||
}
|
||||
|
||||
[data-ws-part="demo.channels"],
|
||||
[data-ws-part="demo.actions"],
|
||||
[data-ws-part="demo.main"] {
|
||||
border-color: rgba(255, 255, 255, .8);
|
||||
border-radius: 20px;
|
||||
background: rgba(249, 253, 255, .84);
|
||||
box-shadow: var(--skin-illusia-shadow);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
[data-ws-part="demo.hero"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-radius: 22px;
|
||||
background-color: #d7f3f7;
|
||||
background-image: linear-gradient(90deg, rgba(239, 251, 254, .94), rgba(227, 248, 251, .48)), url("assets/banner-character-main.webp"), url("assets/banner-mascot-blob.webp");
|
||||
background-position: center, right 46px bottom, right 16px center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: cover, auto 112%, auto 72%;
|
||||
box-shadow: 0 14px 38px rgba(31, 99, 123, .12), inset 0 0 0 1px rgba(255, 255, 255, .8);
|
||||
}
|
||||
|
||||
[data-ws-part="demo.voice-card"] {
|
||||
border-color: rgba(115, 205, 218, .35);
|
||||
border-radius: 19px;
|
||||
background: rgba(255, 255, 255, .76);
|
||||
box-shadow: 0 10px 28px rgba(31, 99, 123, .1);
|
||||
}
|
||||
|
||||
[data-ws-part="demo.avatar"] {
|
||||
outline: 2px solid rgba(71, 201, 212, .7);
|
||||
outline-offset: 4px;
|
||||
}
|
||||
|
||||
[data-ws-part="demo.chat.send"] {
|
||||
color: #fff;
|
||||
border-radius: 12px;
|
||||
background: linear-gradient(110deg, #0a9291, #087580);
|
||||
}
|
||||
|
||||
@media (max-width: 740px) {
|
||||
[data-ws-page="demo"] {
|
||||
background-size: min(62vw, 300px) auto, auto, cover;
|
||||
background-attachment: scroll, scroll, scroll;
|
||||
}
|
||||
|
||||
[data-ws-part="demo.hero"] {
|
||||
background-position: center, right center;
|
||||
background-size: cover, auto 65%;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
[data-ws-part="home"] {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
[data-ws-part="home.connect"],
|
||||
[data-ws-part="voice.member"],
|
||||
[data-ws-part="demo.voice-card"] {
|
||||
transition-duration: .01ms;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
# WebSpeak 0.2.6
|
||||
|
||||
本版本相对于 [0.2.5 正式版](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) 更新。
|
||||
|
||||
## 问题修复与功能
|
||||
|
||||
- **已修复 [#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10)**:Docker/Compose 环境下短主机名的本地 DNS 解析回退;云端昵称发现加入超时和直接连接回退,避免外部发现服务不可用时阻塞连接。HTTPS 部署的健康检查也会根据证书配置选择 HTTPS。
|
||||
- **已实现 [#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9)**:导入 TeamSpeak 3 身份 INI 或身份字符串、导出 WebSpeak/TeamSpeak 兼容身份,并在本地校验格式和密钥一致性。
|
||||
- **已修复 [#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6)**:静音同步遇到服务端频率限制时有限重试;会话切换或重连后,旧请求不会覆盖当前麦克风状态。
|
||||
- **已修复 [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7)**:TS6 屏幕共享清理等待服务器确认,携带清理原因并对频率限制有限重试,避免本地提前显示清理成功。
|
||||
- **已实现 [#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12) 请求的配置入口**:管理员可设置公网媒体地址、IPv6 候选和语音 STUN,以适配反向代理或 TCP 隧道后的 UDP 媒体路径。直接媒体仍要求 UDP 可达,STUN 不提供中继。
|
||||
- 修复 [PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13) 所报告的问题:新 WebSpeak 会话会发现已经开始的 TS6 原生屏幕共享,并将发现过程按服务器协调。PR 本身没有合并。
|
||||
- 改善语音稳定性:隔离重连前后的音频帧、播放回调、目录事件和性能统计;保留连续 Opus 编码状态,只协商受支持的音频参数;切换麦克风或伴奏设置时尽量保留正在工作的采集链路。
|
||||
- 改善移动端布局和语音控制,增加语音会话期间的屏幕常亮行为;梳理管理后台状态请求和语音工作区组件边界。
|
||||
|
||||
## 发布包与架构
|
||||
|
||||
- Windows:`windows-x64.zip`。
|
||||
- Linux:`linux-x64.tar.gz`、`linux-arm64.tar.gz`。
|
||||
- Docker:同一镜像标签提供 `linux/amd64` 和 `linux/arm64`。
|
||||
- Android:分别提供 `arm64-v8a`、`armeabi-v7a`、`x86_64` APK。APK 使用 Android debug 签名,适合手动安装和测试,不是 Google Play 发布包。Android 端的真实 TeamSpeak 连接、双向语音和后台行为仍需真机验收。
|
||||
- `SHA256SUMS.txt` 列出本次附件的 SHA-256,可用于下载后校验。
|
||||
|
||||
## 验证
|
||||
|
||||
发布流程运行完整自动化测试和前后端构建;Windows x64、Linux x64/ARM64 发布包均启动内置健康检查,Android 流程构建三种 ABI 的 APK。Windows ARM64 未纳入本次发布:当前 `@discordjs/opus` 上游只声明支持 Windows x64,ARM64 源码构建在 MSVC 下失败。自动化构建成功不等于真实 TeamSpeak 服务器或 Android 真机媒体链路已经验收。
|
||||
|
Before Width: | Height: | Size: 67 KiB After Width: | Height: | Size: 53 KiB |
|
Before Width: | Height: | Size: 115 KiB After Width: | Height: | Size: 117 KiB |
|
Before Width: | Height: | Size: 68 KiB After Width: | Height: | Size: 76 KiB |
|
Before Width: | Height: | Size: 62 KiB After Width: | Height: | Size: 69 KiB |
|
Before Width: | Height: | Size: 63 KiB After Width: | Height: | Size: 50 KiB |
|
Before Width: | Height: | Size: 106 KiB After Width: | Height: | Size: 102 KiB |
|
Before Width: | Height: | Size: 63 KiB After Width: | Height: | Size: 72 KiB |
|
Before Width: | Height: | Size: 58 KiB After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 71 KiB |
|
After Width: | Height: | Size: 65 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
Before Width: | Height: | Size: 56 KiB After Width: | Height: | Size: 46 KiB |
|
Before Width: | Height: | Size: 97 KiB After Width: | Height: | Size: 103 KiB |
|
Before Width: | Height: | Size: 60 KiB After Width: | Height: | Size: 67 KiB |
|
Before Width: | Height: | Size: 56 KiB After Width: | Height: | Size: 61 KiB |
@@ -0,0 +1,48 @@
|
||||
# Android client
|
||||
|
||||
The Android app packages the Vue client with a small local gateway. Capacitor starts the embedded Node.js runtime, the gateway listens on `127.0.0.1:3040`, and the WebView opens that local address. The gateway is loopback-only; it does not expose an HTTP listener to the LAN. Release APKs are debug-signed sideload packages, not Google Play builds.
|
||||
|
||||
## Build on Windows
|
||||
|
||||
Use a short checkout path such as `C:\src\webspeak`. The Node.js plugin's CMake/Ninja object paths can exceed the Windows toolchain limit in deeply nested workspaces. A clean build in a nested validation directory failed with CMake's 250-character object-path warning and a Ninja `mkdir` error; the same source and dependencies built successfully from a shorter path. Changing application code or the embedded runtime is not required for this build-host issue.
|
||||
|
||||
Use the server development Node.js version (22.5 or newer) on the build host. Install all three dependency sets, then prepare and sync the Android project:
|
||||
|
||||
```powershell
|
||||
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
|
||||
npm --prefix mobile ci --no-audit --no-fund
|
||||
npm run android:sync
|
||||
```
|
||||
|
||||
Build the debug APKs with Android Studio's JDK and the checked-in Gradle wrapper:
|
||||
|
||||
```powershell
|
||||
$env:JAVA_HOME = "C:\Program Files\Android\Android Studio\jbr"
|
||||
$env:ANDROID_HOME = "$env:LOCALAPPDATA\Android\Sdk"
|
||||
Set-Location web\android
|
||||
.\gradlew.bat assembleDebug
|
||||
```
|
||||
|
||||
Gradle writes one APK per supported CPU architecture under `web/android/app/build/outputs/apk/debug/`: `arm64-v8a`, `armeabi-v7a`, and `x86_64`. Use `arm64-v8a` for most modern Android phones and `x86_64` for the Android emulator. GitHub Releases contains all three APKs with versioned filenames.
|
||||
|
||||
## Current scope
|
||||
|
||||
- Platform startup is isolated in `web/src/platform/`. Ordinary browser sessions mount directly; the native shell loads the Node.js plugin only while waiting for its loopback gateway. Startup errors, timeouts and page exit release polling and message listeners. Retry repeats the readiness handshake without restarting the embedded Node.js runtime.
|
||||
- The local gateway serves the join page, public configuration, skin package, join-ticket endpoint, and voice WebSocket bridge.
|
||||
- The admin console and server-side skin management are not available in the Android package.
|
||||
- Mobile audio encoding uses the JavaScript/WASM Opus codec. The normal server build continues to use the native Opus codec.
|
||||
- The embedded runtime supplied by the current Capacitor Node.js plugin is Node.js 18.20.4. The gateway, identity parsing, and Opus encode/decode paths have been smoke-checked on that runtime. The TeamSpeak SDK declares Node.js 20.19 or newer, so real TeamSpeak connectivity and two-way audio remain unverified on Android; the APKs are for sideload testing.
|
||||
- Android WebView on the tested emulator does not expose `getDisplayMedia`; screen sharing needs a native MediaProjection integration. A persistent Android foreground service and real-device background audio behavior also remain to be implemented and verified.
|
||||
|
||||
## Recorded validation
|
||||
|
||||
On October 1, 2026, the platform startup tests passed as part of 118 application tests. Backend compilation, frontend type checking, Vite production build, asset packaging, Capacitor sync and `assembleDebug` passed. Gradle produced arm64-v8a, armeabi-v7a and x86_64 debug APKs.
|
||||
|
||||
The x86_64 APK installed and cold-started in a read-only Android 15 emulator. The embedded gateway returned `webspeak-android` from `/health` and `mobile: true` from `/api/public-config`; a screenshot confirmed that the WebView reached the join homepage. The narrow header was subsequently corrected and checked in desktop responsive viewports. The clean rebuild below includes those changes; its installation and startup were checked on October 2, while Android layout checks remain pending. The earlier emulator check covers startup and rendering only; real TeamSpeak connectivity, two-way audio and physical-device behavior remain unverified.
|
||||
|
||||
Later on October 1, commit `662dad36fc4d8cf9f35268a99b8221851f6fc52c` was exported with `git archive` into a fresh short directory. All three dependency sets were installed again from their lock files, and the pinned TeamSpeak SDK was rebuilt. `android:sync` and `assembleDebug --no-daemon` passed using Windows x64, Node.js 24.12.0, Android Studio JDK 25.0.2, Gradle 9.5.0 and Android SDK 36. All 134 Gradle tasks executed. The three ABI-specific APKs contain the gateway entry, SDK bundle, Opus WASM, frontend and matching native Node.js libraries; their manifest reports version `0.2.5-preview` / code `25`, minimum SDK 24 and target SDK 36. Artifact hashes are recorded in `docs/LOCAL_ARTIFACTS.zh-CN.md`. This was a debug build check, not a signed release or a new device/media test.
|
||||
|
||||
On October 2, the same clean x86_64 APK was installed in a read-only Android 15 emulator after rechecking its SHA-256. Installation succeeded and the package manager confirmed version `0.2.5-preview` / code `25`. A cold start of `io.webspeak.client/.MainActivity` completed in 1,822 ms. An ADB-forwarded HTTP check reached the embedded gateway: `/health` returned `status: ok` and `engine: webspeak-android`, while `/api/public-config` reported the expected version and `mobile: true`. The forwarding and emulator were then closed without saving a snapshot. This check did not exercise WebView layout, touch input, real TeamSpeak connectivity or audio.
|
||||
@@ -0,0 +1,33 @@
|
||||
const path = require("node:path");
|
||||
const os = require("node:os");
|
||||
let app;
|
||||
let channel;
|
||||
try {
|
||||
({ app, channel } = require("bridge"));
|
||||
} catch (error) {
|
||||
if (error.code !== "MODULE_NOT_FOUND") throw error;
|
||||
app = { datadir: () => path.join(os.tmpdir(), "webspeak-android-gateway-dev") };
|
||||
channel = { on: () => {}, post: () => {} };
|
||||
}
|
||||
|
||||
process.env.WEBSPEAK_MOBILE = "1";
|
||||
process.env.WEBSPEAK_DATA_DIR = app.datadir();
|
||||
process.env.WEBSPEAK_MOBILE_WWW = path.join(__dirname, "www");
|
||||
process.env.WEBSPEAK_VERSION = require("./package.json").version;
|
||||
|
||||
let gatewayReady = false;
|
||||
const gatewayPort = Number(process.env.WEBSPEAK_MOBILE_PORT || 3040);
|
||||
channel.on("webspeak-health", () => {
|
||||
channel.post("webspeak-health", { ready: gatewayReady, port: gatewayPort });
|
||||
});
|
||||
|
||||
import("./dist/mobile/index.js")
|
||||
.then(() => {
|
||||
gatewayReady = true;
|
||||
channel.post("webspeak-health", { ready: true, port: gatewayPort });
|
||||
})
|
||||
.catch((error) => {
|
||||
const message = error instanceof Error ? error.stack || error.message : String(error);
|
||||
console.error("WebSpeak mobile gateway failed:", message);
|
||||
channel.post("webspeak-error", { message });
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { cp, mkdir, readdir, copyFile, stat, readFile, writeFile, rm } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const mobileDir = path.dirname(fileURLToPath(import.meta.url));
|
||||
const rootDir = path.resolve(mobileDir, "..");
|
||||
const webDist = path.join(rootDir, "web", "dist");
|
||||
const outputDir = path.join(webDist, "nodejs");
|
||||
|
||||
for (const required of [path.join(rootDir, "dist", "mobile", "index.js"), path.join(mobileDir, "node_modules"), path.join(webDist, "index.html")]) {
|
||||
if (!(await stat(required).catch(() => null))) throw new Error(`Missing Android build input: ${required}`);
|
||||
}
|
||||
|
||||
await rm(outputDir, { recursive: true, force: true });
|
||||
await mkdir(path.join(outputDir, "www"), { recursive: true });
|
||||
await cp(path.join(rootDir, "dist"), path.join(outputDir, "dist"), { recursive: true, force: true });
|
||||
await cp(path.join(mobileDir, "node_modules"), path.join(outputDir, "node_modules"), { recursive: true, force: true });
|
||||
await copyFile(path.join(mobileDir, "index.cjs"), path.join(outputDir, "index.cjs"));
|
||||
const appPackage = JSON.parse(await readFile(path.join(rootDir, "package.json"), "utf8"));
|
||||
const mobilePackage = JSON.parse(await readFile(path.join(mobileDir, "package.json"), "utf8"));
|
||||
mobilePackage.version = appPackage.version;
|
||||
await writeFile(path.join(outputDir, "package.json"), `${JSON.stringify(mobilePackage, null, 2)}\n`);
|
||||
|
||||
for (const entry of await readdir(webDist, { withFileTypes: true })) {
|
||||
if (entry.name === "nodejs") continue;
|
||||
await cp(path.join(webDist, entry.name), path.join(outputDir, "www", entry.name), { recursive: entry.isDirectory(), force: true });
|
||||
}
|
||||
|
||||
console.log(`Android gateway assets prepared at ${outputDir}`);
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "webspeak-android-gateway",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.cjs",
|
||||
"dependencies": {
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811",
|
||||
"express": "^4.21.2",
|
||||
"opusscript": "^0.1.1",
|
||||
"pino": "^10.3.1",
|
||||
"werift": "0.24.4",
|
||||
"ws": "^8.20.0"
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,16 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.2.2",
|
||||
"version": "0.2.6",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.2.2",
|
||||
"version": "0.2.6",
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#a145338",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"werift": "0.24.4",
|
||||
@@ -63,7 +63,7 @@
|
||||
},
|
||||
"node_modules/@echosixhiya/teamspeak-client": {
|
||||
"version": "0.2.4",
|
||||
"resolved": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#a145338c7a83044dee0951c412ad91292b570215",
|
||||
"resolved": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.2.2",
|
||||
"version": "0.2.6",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-only",
|
||||
"type": "module",
|
||||
@@ -11,9 +11,13 @@
|
||||
"scripts": {
|
||||
"dev": "tsx src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "node --import tsx --test src/admin/skin-registry.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/member-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/identity-import.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts",
|
||||
"verify": "npm test && npm run build && npm run web:build",
|
||||
"start": "node dist/index.js",
|
||||
"web:dev": "cd web && npx vite --host",
|
||||
"web:build": "cd web && npx vite build",
|
||||
"web:build": "npm --prefix web run build",
|
||||
"android:prepare": "npm run build && npm --prefix web run build && node mobile/pack.mjs",
|
||||
"android:sync": "npm run android:prepare && cd web && npx cap sync android",
|
||||
"prepare:sdk": "node scripts/prepare-sdk.mjs",
|
||||
"acceleration:poc": "node scripts/acceleration-poc/smoke.mjs",
|
||||
"acceleration:ipv6-smoke": "node scripts/acceleration-poc/smoke-ipv6.mjs",
|
||||
@@ -22,7 +26,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#a145338",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"werift": "0.24.4",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
它验证以下核心能力:
|
||||
|
||||
- 香港侧客户端向上海侧中继发起认证;
|
||||
- 客户端向远端中继发起认证;
|
||||
- 每个会话动态指定 TeamSpeak 目标地址;
|
||||
- 双向 UDP 数据报转发,并保持数据包边界;
|
||||
- 会话之间按随机 ID 隔离;
|
||||
@@ -27,16 +27,16 @@ IPv6 回环验证:
|
||||
npm run acceleration:ipv6-smoke
|
||||
```
|
||||
|
||||
## 通过隧道连接上海 TeamSpeak
|
||||
## 通过隧道连接指定 TeamSpeak
|
||||
|
||||
下面的命令会让 SDK 连接本地代理端口,再由 PoC 中继把 UDP 数据转发到指定 TeamSpeak。它不进入指定频道,只验证 TeamSpeak 握手和断开:
|
||||
必须先将下方示例域名替换为你获准测试的 TeamSpeak 地址;脚本不内置真实服务器默认值。下面的命令会让 SDK 连接本地代理端口,再由 PoC 中继把 UDP 数据转发到指定 TeamSpeak。它不进入指定频道,只验证 TeamSpeak 握手和断开:
|
||||
|
||||
```bash
|
||||
$env:WEBSPEAK_ACCEL_TS_TARGET="203.0.113.10#9987"
|
||||
$env:WEBSPEAK_ACCEL_TS_TARGET="ts.example.invalid#9987"
|
||||
npm run acceleration:sdk-smoke
|
||||
```
|
||||
|
||||
跨机器验证时,需要在上海启动 `relay-server.mjs`,再把 `WEBSPEAK_ACCEL_RELAY` 指向上海中继地址。当前项目不会自动部署或启动该远程进程。
|
||||
跨机器验证时,需要在目标服务器启动 `relay-server.mjs`,再把 `WEBSPEAK_ACCEL_RELAY` 指向中继地址。当前项目不会自动部署或启动该远程进程。
|
||||
|
||||
## 手动启动中继
|
||||
|
||||
|
||||
@@ -4,7 +4,11 @@ import { createRelayServer } from "./relay-server.mjs";
|
||||
import { parseEndpoint } from "./protocol.mjs";
|
||||
|
||||
const token = process.env.WEBSPEAK_ACCEL_TOKEN ?? "local-acceleration-poc-token";
|
||||
const target = parseEndpoint(process.env.WEBSPEAK_ACCEL_TS_TARGET ?? "203.0.113.10#9987", 9987);
|
||||
const targetAddress = process.env.WEBSPEAK_ACCEL_TS_TARGET;
|
||||
if (!targetAddress?.trim()) {
|
||||
throw new Error("Set WEBSPEAK_ACCEL_TS_TARGET to your authorized TeamSpeak test endpoint");
|
||||
}
|
||||
const target = parseEndpoint(targetAddress, 9987);
|
||||
const relayEndpoint = process.env.WEBSPEAK_ACCEL_RELAY;
|
||||
let relayServer = null;
|
||||
let relayClient = null;
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import http from "node:http";
|
||||
import https from "node:https";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const scriptDirectory = path.dirname(fileURLToPath(import.meta.url));
|
||||
const appRoot = path.resolve(scriptDirectory, "..");
|
||||
const defaultCertDirectory = path.join(appRoot, "certs");
|
||||
|
||||
export function healthcheckUsesHttps(certDirectory = defaultCertDirectory) {
|
||||
return existsSync(path.join(certDirectory, "cert.pem"));
|
||||
}
|
||||
|
||||
export function runDockerHealthcheck({ mode = process.env.WEBSPEAK_MODE, certDirectory = defaultCertDirectory } = {}) {
|
||||
if (mode?.trim().toLowerCase() === "relay") {
|
||||
process.exitCode = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
const secure = healthcheckUsesHttps(certDirectory);
|
||||
const client = secure ? https : http;
|
||||
const request = client.get({
|
||||
hostname: "127.0.0.1",
|
||||
port: 3040,
|
||||
path: "/health",
|
||||
...(secure ? { rejectUnauthorized: false } : {}),
|
||||
}, (response) => {
|
||||
response.resume();
|
||||
process.exitCode = response.statusCode >= 200 && response.statusCode < 300 ? 0 : 1;
|
||||
});
|
||||
request.setTimeout(4_000, () => request.destroy(new Error("Healthcheck timed out")));
|
||||
request.on("error", () => { process.exitCode = 1; });
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
runDockerHealthcheck();
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { healthcheckUsesHttps } from "./docker-healthcheck.mjs";
|
||||
|
||||
test("Docker healthcheck selects HTTP or HTTPS from the same certificate marker as the server", (context) => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-healthcheck-"));
|
||||
context.after(() => rmSync(directory, { recursive: true, force: true }));
|
||||
|
||||
assert.equal(healthcheckUsesHttps(directory), false);
|
||||
mkdirSync(directory, { recursive: true });
|
||||
writeFileSync(path.join(directory, "cert.pem"), "test certificate marker");
|
||||
assert.equal(healthcheckUsesHttps(directory), true);
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
|
||||
$width = 3200
|
||||
$height = 116
|
||||
$outputPath = Join-Path $PSScriptRoot "..\docs\examples\illusia-voice\assets\footer-wave.png"
|
||||
$bitmap = [System.Drawing.Bitmap]::new($width, $height, [System.Drawing.Imaging.PixelFormat]::Format32bppArgb)
|
||||
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
|
||||
$graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
|
||||
$graphics.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::HighQuality
|
||||
$graphics.CompositingQuality = [System.Drawing.Drawing2D.CompositingQuality]::HighQuality
|
||||
$graphics.Clear([System.Drawing.Color]::Transparent)
|
||||
|
||||
$topEdge = [System.Drawing.Drawing2D.GraphicsPath]::new()
|
||||
$topEdge.StartFigure()
|
||||
$topEdge.AddBezier(
|
||||
[System.Drawing.PointF]::new(0, 20),
|
||||
[System.Drawing.PointF]::new(240, 4),
|
||||
[System.Drawing.PointF]::new(460, 0),
|
||||
[System.Drawing.PointF]::new(700, 10)
|
||||
)
|
||||
$topEdge.AddBezier(
|
||||
[System.Drawing.PointF]::new(700, 10),
|
||||
[System.Drawing.PointF]::new(1000, 26),
|
||||
[System.Drawing.PointF]::new(1200, 36),
|
||||
[System.Drawing.PointF]::new(1600, 36)
|
||||
)
|
||||
$topEdge.AddBezier(
|
||||
[System.Drawing.PointF]::new(1600, 36),
|
||||
[System.Drawing.PointF]::new(2000, 36),
|
||||
[System.Drawing.PointF]::new(2200, 26),
|
||||
[System.Drawing.PointF]::new(2500, 10)
|
||||
)
|
||||
$topEdge.AddBezier(
|
||||
[System.Drawing.PointF]::new(2500, 10),
|
||||
[System.Drawing.PointF]::new(2740, 0),
|
||||
[System.Drawing.PointF]::new(2960, 4),
|
||||
[System.Drawing.PointF]::new(3200, 20)
|
||||
)
|
||||
|
||||
$surface = [System.Drawing.Drawing2D.GraphicsPath]::new()
|
||||
$surface.AddPath($topEdge, $false)
|
||||
$surface.AddLine(3200, 20, 3200, $height)
|
||||
$surface.AddLine(3200, $height, 0, $height)
|
||||
$surface.CloseFigure()
|
||||
|
||||
$brush = [System.Drawing.Drawing2D.LinearGradientBrush]::new(
|
||||
[System.Drawing.Rectangle]::new(0, 0, $width, $height),
|
||||
[System.Drawing.Color]::FromArgb(138, 244, 252, 254),
|
||||
[System.Drawing.Color]::FromArgb(245, 252, 255, 255),
|
||||
[System.Drawing.Drawing2D.LinearGradientMode]::Vertical
|
||||
)
|
||||
$blend = [System.Drawing.Drawing2D.ColorBlend]::new(3)
|
||||
$blend.Colors = [System.Drawing.Color[]]@(
|
||||
[System.Drawing.Color]::FromArgb(138, 244, 252, 254),
|
||||
[System.Drawing.Color]::FromArgb(194, 248, 253, 254),
|
||||
[System.Drawing.Color]::FromArgb(245, 252, 255, 255)
|
||||
)
|
||||
$blend.Positions = [single[]]@(0.0, 0.58, 1.0)
|
||||
$brush.InterpolationColors = $blend
|
||||
$pen = [System.Drawing.Pen]::new([System.Drawing.Color]::FromArgb(118, 103, 210, 221), 1.5)
|
||||
$pen.LineJoin = [System.Drawing.Drawing2D.LineJoin]::Round
|
||||
$accentBrush = [System.Drawing.SolidBrush]::new([System.Drawing.Color]::FromArgb(150, 99, 216, 225))
|
||||
$accentPath = [System.Drawing.Drawing2D.GraphicsPath]::new()
|
||||
$leftDiamond = [System.Drawing.PointF[]]@(
|
||||
[System.Drawing.PointF]::new(126, 47),
|
||||
[System.Drawing.PointF]::new(136, 58),
|
||||
[System.Drawing.PointF]::new(126, 69),
|
||||
[System.Drawing.PointF]::new(116, 58)
|
||||
)
|
||||
$rightDiamond = [System.Drawing.PointF[]]@(
|
||||
[System.Drawing.PointF]::new(3074, 47),
|
||||
[System.Drawing.PointF]::new(3084, 58),
|
||||
[System.Drawing.PointF]::new(3074, 69),
|
||||
[System.Drawing.PointF]::new(3064, 58)
|
||||
)
|
||||
$accentPen = [System.Drawing.Pen]::new([System.Drawing.Color]::FromArgb(94, 91, 211, 223), 1.2)
|
||||
$accentPen.StartCap = [System.Drawing.Drawing2D.LineCap]::Round
|
||||
$accentPen.EndCap = [System.Drawing.Drawing2D.LineCap]::Round
|
||||
|
||||
$graphics.FillPath($brush, $surface)
|
||||
$graphics.DrawPath($pen, $topEdge)
|
||||
$graphics.DrawLine($accentPen, 82, 58, 116, 58)
|
||||
$graphics.DrawLine($accentPen, 136, 58, 170, 58)
|
||||
$graphics.DrawLine($accentPen, 3030, 58, 3064, 58)
|
||||
$graphics.DrawLine($accentPen, 3084, 58, 3118, 58)
|
||||
$accentPath.AddPolygon($leftDiamond)
|
||||
$accentPath.AddPolygon($rightDiamond)
|
||||
$graphics.FillPath($accentBrush, $accentPath)
|
||||
[System.IO.Directory]::CreateDirectory((Split-Path -Parent $outputPath)) | Out-Null
|
||||
$bitmap.Save($outputPath, [System.Drawing.Imaging.ImageFormat]::Png)
|
||||
|
||||
$accentPen.Dispose()
|
||||
$accentBrush.Dispose()
|
||||
$accentPath.Dispose()
|
||||
$pen.Dispose()
|
||||
$brush.Dispose()
|
||||
$surface.Dispose()
|
||||
$topEdge.Dispose()
|
||||
$graphics.Dispose()
|
||||
$bitmap.Dispose()
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Router, type NextFunction, type Request, type Response } from "express";
|
||||
import { Router, raw as expressRaw, type NextFunction, type Request, type Response } from "express";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { AdminInputError, AdminService, type AdminSettingsInput, type RelayNodeInput } from "./admin-service.js";
|
||||
@@ -6,6 +6,7 @@ import { AdminSessionStore, isSecureRequest } from "./admin-session.js";
|
||||
import { AdminLoginRateLimiter, waitFor } from "./login-rate-limit.js";
|
||||
import { TeamSpeakProbeError } from "../server/teamspeak-probe.js";
|
||||
import type { AdminSessionSummary } from "../server/voice-bridge.js";
|
||||
import { SkinRegistry, SkinRegistryError } from "./skin-registry.js";
|
||||
|
||||
export interface AdminConnectionRecord {
|
||||
id: string;
|
||||
@@ -34,6 +35,7 @@ export interface AdminRouterOptions {
|
||||
terminateSession?: (id: string) => Promise<boolean>;
|
||||
version?: string;
|
||||
logFile?: string;
|
||||
skinRegistry?: SkinRegistry;
|
||||
startedAt: number;
|
||||
}
|
||||
|
||||
@@ -120,6 +122,81 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
response.json(options.service.getAdminSettings());
|
||||
});
|
||||
|
||||
router.get("/skins", async (_request, response) => {
|
||||
response.json({
|
||||
skins: await options.skinRegistry?.list() ?? [],
|
||||
defaultSkinId: await options.skinRegistry?.getDefaultSkinId() ?? "builtin.light",
|
||||
});
|
||||
});
|
||||
|
||||
router.put("/skins/default", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
|
||||
try {
|
||||
if (!options.skinRegistry) throw new SkinRegistryError("Skin storage is unavailable.", "SKIN_STORAGE_UNAVAILABLE");
|
||||
const id = typeof asRecord(request.body).id === "string" ? (asRecord(request.body).id as string).trim() : "";
|
||||
const settings = await options.skinRegistry.setDefaultSkin(id);
|
||||
response.json({ ok: true, defaultSkinId: settings.defaultSkinId });
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SkinRegistryError) {
|
||||
response.status(error.code === "SKIN_DEFAULT_INVALID" ? 400 : 409).json({ ok: false, code: error.code, message: error.message });
|
||||
return;
|
||||
}
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.put("/skins/:id/enabled", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
|
||||
try {
|
||||
const id = typeof request.params.id === "string" ? request.params.id : "";
|
||||
const body = asRecord(request.body);
|
||||
if (!options.skinRegistry || typeof body.enabled !== "boolean") throw new SkinRegistryError("A skin and boolean enabled value are required.", "SKIN_ENABLE_INVALID");
|
||||
const skin = await options.skinRegistry.setEnabled(id, body.enabled);
|
||||
options.service.database.addAudit(body.enabled ? "ADMIN_SKIN_ENABLED" : "ADMIN_SKIN_DISABLED", { id });
|
||||
response.json({ ok: true, skin, defaultSkinId: await options.skinRegistry.getDefaultSkinId() });
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SkinRegistryError) {
|
||||
const status = error.code === "SKIN_NOT_FOUND" ? 404 : error.code === "SKIN_ENABLE_INVALID" ? 400 : 409;
|
||||
response.status(status).json({ ok: false, code: error.code, message: error.message });
|
||||
return;
|
||||
}
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.put("/skins/:id", requireSameOriginBinary, requireCsrf(options.sessions), expressRaw({ type: "application/octet-stream", limit: "20mb" }), async (request, response) => {
|
||||
try {
|
||||
const id = typeof request.params.id === "string" ? request.params.id : "";
|
||||
if (!options.skinRegistry || !Buffer.isBuffer(request.body)) throw new SkinRegistryError("Skin storage is unavailable.", "SKIN_STORAGE_UNAVAILABLE");
|
||||
const skin = await options.skinRegistry.save(request.body, id);
|
||||
options.service.database.addAudit("ADMIN_SKIN_INSTALLED", { id: skin.id, version: skin.version });
|
||||
response.status(201).json({ ok: true, skin });
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SkinRegistryError) {
|
||||
const status = error.code === "SKIN_LIMIT" || error.code === "SKIN_STORAGE_LIMIT" || error.code === "SKIN_BUILTIN_PROTECTED" ? 409 : 400;
|
||||
response.status(status).json({ ok: false, code: error.code, message: error.message });
|
||||
return;
|
||||
}
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete("/skins/:id", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
|
||||
const id = typeof request.params.id === "string" ? request.params.id : "";
|
||||
try {
|
||||
if (!options.skinRegistry || !await options.skinRegistry.remove(id)) {
|
||||
response.status(404).json({ ok: false, code: "SKIN_NOT_FOUND" });
|
||||
return;
|
||||
}
|
||||
options.service.database.addAudit("ADMIN_SKIN_REMOVED", { id });
|
||||
response.json({ ok: true });
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SkinRegistryError) {
|
||||
response.status(error.code === "SKIN_BUILTIN_PROTECTED" ? 409 : 400).json({ ok: false, code: error.code, message: error.message });
|
||||
return;
|
||||
}
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/sessions", (_request, response) => {
|
||||
response.json({ sessions: options.getSessionSummaries?.() ?? [] });
|
||||
});
|
||||
@@ -184,7 +261,7 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
options.getActiveSessions(),
|
||||
options.getPeakSessions(),
|
||||
options.startedAt,
|
||||
) as unknown as AdminOverview;
|
||||
);
|
||||
response.json({
|
||||
generatedAt: new Date().toISOString(),
|
||||
gateway: {
|
||||
@@ -211,7 +288,7 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
options.getActiveSessions(),
|
||||
options.getPeakSessions(),
|
||||
options.startedAt,
|
||||
) as unknown as AdminOverview;
|
||||
);
|
||||
const report = {
|
||||
generatedAt: new Date().toISOString(),
|
||||
gateway: {
|
||||
@@ -327,6 +404,22 @@ function requireSameOrigin(request: Request, response: Response, next: NextFunct
|
||||
next();
|
||||
}
|
||||
|
||||
function requireSameOriginBinary(request: Request, response: Response, next: NextFunction): void {
|
||||
if (!request.is("application/octet-stream")) {
|
||||
response.status(415).json({ ok: false, code: "BINARY_REQUIRED" });
|
||||
return;
|
||||
}
|
||||
const origin = request.header("origin");
|
||||
const host = request.header("host");
|
||||
try {
|
||||
if (!origin || !host || new URL(origin).host !== host) throw new Error("origin mismatch");
|
||||
} catch {
|
||||
response.status(403).json({ ok: false, code: "ORIGIN_REJECTED" });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
async function runProbe(
|
||||
service: AdminService,
|
||||
response: Response,
|
||||
@@ -371,6 +464,9 @@ function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
|
||||
welcomeTextRu: typeof body.welcomeTextRu === "string" ? body.welcomeTextRu.slice(0, 500) : undefined,
|
||||
welcomeTextJa: typeof body.welcomeTextJa === "string" ? body.welcomeTextJa.slice(0, 500) : undefined,
|
||||
webRtcEnabled: body.webRtcEnabled === true,
|
||||
webRtcPublicHost: body.webRtcPublicHost as string | undefined,
|
||||
webRtcIpv6Enabled: body.webRtcIpv6Enabled as boolean | undefined,
|
||||
webRtcStunServer: body.webRtcStunServer as string | undefined,
|
||||
webRtcUdpStart: readOptionalInteger(body, "webRtcUdpStart"),
|
||||
webRtcUdpEnd: readOptionalInteger(body, "webRtcUdpEnd"),
|
||||
relaySettingsAction: readRelaySettingsAction(body.relaySettingsAction),
|
||||
@@ -595,17 +691,6 @@ function readStructuredLogs(logFile: string): StructuredLogEntry[] {
|
||||
return entries.sort((left, right) => Date.parse(left.timestamp ?? "") - Date.parse(right.timestamp ?? ""));
|
||||
}
|
||||
|
||||
interface AdminOverview {
|
||||
gateway: { uptimeSeconds: number };
|
||||
teamSpeak: {
|
||||
target: string;
|
||||
status: string;
|
||||
lastTestAt: string | null;
|
||||
latencyMs: number | null;
|
||||
lastError: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
function logLevelName(level: unknown): string {
|
||||
if (level === 10) return "DEBUG";
|
||||
if (level === 30) return "INFO";
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import type { AdminSettingsInput, RelayNodeInput, ManagedInviteInput } from "../shared/admin-inputs.js";
|
||||
export type { AdminSettingsInput, RelayNodeInput, ManagedInviteInput } from "../shared/admin-inputs.js";
|
||||
import type { AdminOverview, AdminSettings } from "../shared/admin-responses.js";
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { existsSync } from "node:fs";
|
||||
import type { Logger } from "../logger.js";
|
||||
@@ -8,55 +11,18 @@ import { hashAdminPassword, validateAdminPassword, verifyAdminPassword } from ".
|
||||
import { decryptSecret, encryptSecret } from "../security/secret-crypto.js";
|
||||
import { probeTeamSpeak, TeamSpeakProbeError } from "../server/teamspeak-probe.js";
|
||||
import { pingTeamSpeakHost } from "../server/network-probe.js";
|
||||
import { normalizeVoiceMediaHost, normalizeVoiceStunServer } from "../shared/voice-ice.js";
|
||||
import type { WebRtcAudioOptions } from "../server/webrtc-audio.js";
|
||||
import { DEFAULT_ACCELERATION_RELAY_PORT, type ConfiguredAccelerationRelay } from "../server/acceleration-relay.js";
|
||||
import { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_MAX, WEBRTC_UDP_PORT_MIN } from "../server/webrtc-config.js";
|
||||
import { DEFAULT_WELCOME_TEXTS, resolveWelcomeTexts } from "../site-copy.js";
|
||||
|
||||
export interface AdminSettingsInput {
|
||||
target: string;
|
||||
serverPassword?: string;
|
||||
passwordAction?: "keep" | "replace" | "remove";
|
||||
accessMode: AccessMode;
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
welcomeTextEn?: string;
|
||||
welcomeTextDe?: string;
|
||||
welcomeTextRu?: string;
|
||||
welcomeTextJa?: string;
|
||||
webRtcEnabled: boolean;
|
||||
webRtcUdpStart?: number;
|
||||
webRtcUdpEnd?: number;
|
||||
relaySettingsAction?: "keep" | "replace" | "remove";
|
||||
relayEnabled?: boolean;
|
||||
relayName?: string;
|
||||
relayTarget?: string;
|
||||
relayToken?: string;
|
||||
relayTokenAction?: "keep" | "replace" | "remove";
|
||||
relayNodes?: RelayNodeInput[];
|
||||
}
|
||||
|
||||
export interface RelayNodeInput {
|
||||
id?: string;
|
||||
name: string;
|
||||
target: string;
|
||||
enabled: boolean;
|
||||
token?: string;
|
||||
tokenAction?: "keep" | "replace" | "remove";
|
||||
}
|
||||
|
||||
export interface ConnectionPolicy {
|
||||
defaultTarget: TeamSpeakTarget;
|
||||
serverPassword: string;
|
||||
accessMode: AccessMode;
|
||||
}
|
||||
|
||||
export interface ManagedInviteInput {
|
||||
channel: string;
|
||||
expiresInHours: number;
|
||||
maxUses: number;
|
||||
}
|
||||
|
||||
export interface ManagedInviteView {
|
||||
id: string;
|
||||
target: string;
|
||||
@@ -136,7 +102,7 @@ export class AdminService {
|
||||
};
|
||||
}
|
||||
|
||||
getAdminSettings(): Record<string, unknown> {
|
||||
getAdminSettings(): AdminSettings {
|
||||
const settings = this.database.getSettings();
|
||||
return {
|
||||
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
|
||||
@@ -153,6 +119,9 @@ export class AdminService {
|
||||
lastTestLatencyMs: settings.lastTestLatencyMs,
|
||||
lastTestError: settings.lastTestError,
|
||||
webRtcEnabled: settings.webRtcEnabled,
|
||||
webRtcPublicHost: settings.webRtcPublicHost,
|
||||
webRtcIpv6Enabled: settings.webRtcIpv6Enabled,
|
||||
webRtcStunServer: settings.webRtcStunServer,
|
||||
webRtcUdpStart: settings.webRtcUdpStart,
|
||||
webRtcUdpEnd: settings.webRtcUdpEnd,
|
||||
relayConfigured: settings.relayConfigured,
|
||||
@@ -170,6 +139,9 @@ export class AdminService {
|
||||
const settings = this.database.getSettings();
|
||||
return {
|
||||
enabled: settings.webRtcEnabled,
|
||||
publicHost: settings.webRtcPublicHost,
|
||||
ipv6Enabled: settings.webRtcIpv6Enabled,
|
||||
stunServer: settings.webRtcStunServer,
|
||||
udpPortRange: [settings.webRtcUdpStart, settings.webRtcUdpEnd],
|
||||
};
|
||||
}
|
||||
@@ -276,7 +248,7 @@ export class AdminService {
|
||||
}
|
||||
}
|
||||
|
||||
getOverview(activeSessions: number, peakSessions: number, startedAt: number): Record<string, unknown> {
|
||||
getOverview(activeSessions: number, peakSessions: number, startedAt: number): AdminOverview {
|
||||
const settings = this.database.getSettings();
|
||||
return {
|
||||
gateway: {
|
||||
@@ -376,6 +348,12 @@ export class AdminService {
|
||||
if (typeof input.webRtcEnabled !== "boolean") {
|
||||
throw new AdminInputError("INVALID_WEBRTC_ENABLED", "WebRTC enabled value is invalid");
|
||||
}
|
||||
const webRtcPublicHost = normalizeVoiceMediaHost(input.webRtcPublicHost === undefined ? current.webRtcPublicHost : input.webRtcPublicHost);
|
||||
const webRtcStunServer = normalizeVoiceStunServer(input.webRtcStunServer === undefined ? current.webRtcStunServer : input.webRtcStunServer);
|
||||
const webRtcIpv6Enabled = input.webRtcIpv6Enabled === undefined ? current.webRtcIpv6Enabled : input.webRtcIpv6Enabled;
|
||||
if (webRtcPublicHost === null) throw new AdminInputError("INVALID_WEBRTC_PUBLIC_HOST", "Use an IP address or hostname without a scheme, path or port");
|
||||
if (webRtcStunServer === null) throw new AdminInputError("INVALID_WEBRTC_STUN_SERVER", "Use a UDP STUN URL: stun:host:port");
|
||||
if (typeof webRtcIpv6Enabled !== "boolean") throw new AdminInputError("INVALID_WEBRTC_IPV6", "WebRTC IPv6 value must be boolean");
|
||||
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) {
|
||||
@@ -456,6 +434,7 @@ export class AdminService {
|
||||
tsPort: target.port,
|
||||
tsPasswordEncrypted: encryptedPassword,
|
||||
webRtcEnabled: input.webRtcEnabled,
|
||||
webRtcPublicHost, webRtcIpv6Enabled, webRtcStunServer,
|
||||
webRtcUdpStart,
|
||||
webRtcUdpEnd,
|
||||
relayConfigured,
|
||||
@@ -573,6 +552,9 @@ export class AdminService {
|
||||
tsPort: settings.tsPort,
|
||||
tsPasswordEncrypted: settings.tsPasswordEncrypted,
|
||||
webRtcEnabled: settings.webRtcEnabled,
|
||||
webRtcPublicHost: settings.webRtcPublicHost,
|
||||
webRtcIpv6Enabled: settings.webRtcIpv6Enabled,
|
||||
webRtcStunServer: settings.webRtcStunServer,
|
||||
webRtcUdpStart: settings.webRtcUdpStart,
|
||||
webRtcUdpEnd: settings.webRtcUdpEnd,
|
||||
relayConfigured: settings.relayConfigured,
|
||||
@@ -601,6 +583,9 @@ export class AdminService {
|
||||
tsPort: legacy.tsPort,
|
||||
tsPasswordEncrypted: legacy.tsServerPassword ? encryptSecret(legacy.tsServerPassword, this.masterSecret) : null,
|
||||
webRtcEnabled: current.webRtcEnabled,
|
||||
webRtcPublicHost: current.webRtcPublicHost,
|
||||
webRtcIpv6Enabled: current.webRtcIpv6Enabled,
|
||||
webRtcStunServer: current.webRtcStunServer,
|
||||
webRtcUdpStart: current.webRtcUdpStart,
|
||||
webRtcUdpEnd: current.webRtcUdpEnd,
|
||||
relayConfigured: current.relayConfigured,
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { SkinRegistry, SkinRegistryError } from "./skin-registry.js";
|
||||
|
||||
const manifest = {
|
||||
schemaVersion: 1,
|
||||
id: "sample-skin",
|
||||
name: "Sample skin",
|
||||
version: "1.0.0",
|
||||
author: "WebSpeak test",
|
||||
license: "MIT",
|
||||
minAppVersion: "0.2.4",
|
||||
entry: "skin.css",
|
||||
content: "content.json",
|
||||
preview: "assets/preview.png",
|
||||
};
|
||||
|
||||
test("skin registry validates, lists, replaces, serves, and removes packages", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-registry-"));
|
||||
context.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const registry = new SkinRegistry(directory);
|
||||
|
||||
assert.equal(await registry.readArchive("sample-skin"), null);
|
||||
const firstArchive = createZip([
|
||||
["manifest.json", Buffer.from(JSON.stringify(manifest))],
|
||||
["skin.css", Buffer.from(".voice-card { background: url(assets/background.png); }")],
|
||||
["content.json", Buffer.from(JSON.stringify({ defaultLocale: "en", locales: { en: { home: { title: "Hello" } } } }))],
|
||||
["assets/background.png", Buffer.from([1, 2, 3, 4])],
|
||||
["assets/preview.png", Buffer.from([5, 6, 7, 8])],
|
||||
]);
|
||||
const first = await registry.save(firstArchive, "sample-skin");
|
||||
assert.equal(first.id, "sample-skin");
|
||||
assert.equal(first.previewUrl, "/api/skins/sample-skin/preview");
|
||||
assert.equal((await registry.list()).length, 1);
|
||||
assert.deepEqual(await registry.readArchive("sample-skin"), firstArchive);
|
||||
assert.deepEqual((await registry.readPreview("sample-skin"))?.bytes, Buffer.from([5, 6, 7, 8]));
|
||||
await registry.setEnabled("sample-skin", false);
|
||||
assert.equal(await registry.readArchive("sample-skin"), null);
|
||||
assert.equal(await registry.readPreview("sample-skin"), null);
|
||||
await registry.setEnabled("sample-skin", true);
|
||||
|
||||
const replacement = { ...manifest, version: "2.0.0", content: undefined, preview: undefined };
|
||||
const secondArchive = createZip([
|
||||
["manifest.json", Buffer.from(JSON.stringify(replacement))],
|
||||
["skin.css", Buffer.from(".voice-card { border-radius: 0; }")],
|
||||
]);
|
||||
const second = await registry.save(secondArchive, "sample-skin");
|
||||
assert.equal(second.version, "2.0.0");
|
||||
assert.equal(second.installedAt, first.installedAt);
|
||||
assert.equal(await registry.readPreview("sample-skin"), null);
|
||||
assert.deepEqual(await registry.readArchive("sample-skin"), secondArchive);
|
||||
|
||||
assert.equal(await registry.remove("sample-skin"), true);
|
||||
assert.deepEqual(await registry.list(), []);
|
||||
assert.equal(await registry.readArchive("sample-skin"), null);
|
||||
assert.equal(await registry.remove("sample-skin"), false);
|
||||
});
|
||||
|
||||
test("custom skins can be enabled, disabled, and selected as the instance default", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-settings-"));
|
||||
context.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const registry = new SkinRegistry(directory);
|
||||
const archive = createZip([
|
||||
["manifest.json", Buffer.from(JSON.stringify({ ...manifest, content: undefined, preview: undefined }))],
|
||||
["skin.css", Buffer.from("[data-ws-part=\"demo.voice-card\"] { color: teal; }")],
|
||||
]);
|
||||
|
||||
const skin = await registry.save(archive, "sample-skin");
|
||||
assert.equal(skin.enabled, true);
|
||||
assert.equal(await registry.getDefaultSkinId(), "builtin.light");
|
||||
await registry.setDefaultSkin("sample-skin");
|
||||
assert.equal(await registry.getDefaultSkinId(), "sample-skin");
|
||||
|
||||
const disabled = await registry.setEnabled("sample-skin", false);
|
||||
assert.equal(disabled.enabled, false);
|
||||
assert.equal(await registry.readArchive("sample-skin"), null);
|
||||
assert.equal(await registry.getDefaultSkinId(), "builtin.light");
|
||||
await assert.rejects(registry.setDefaultSkin("sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_DEFAULT_INVALID");
|
||||
|
||||
await registry.setEnabled("sample-skin", true);
|
||||
assert.deepEqual(await registry.readArchive("sample-skin"), archive);
|
||||
await registry.setDefaultSkin("sample-skin");
|
||||
assert.equal(await registry.remove("sample-skin"), true);
|
||||
assert.equal(await registry.getDefaultSkinId(), "builtin.light");
|
||||
});
|
||||
|
||||
test("skin registry rejects path traversal and mismatched local ZIP headers", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-invalid-"));
|
||||
context.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const registry = new SkinRegistry(directory);
|
||||
const goodFiles: Array<[string, Buffer]> = [
|
||||
["manifest.json", Buffer.from(JSON.stringify({ ...manifest, content: undefined, preview: undefined }))],
|
||||
["skin.css", Buffer.from(".voice-card { color: teal; }")],
|
||||
];
|
||||
|
||||
await assert.rejects(registry.save(createZip([["../escape.png", Buffer.from([1])], ...goodFiles]), "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_PATH_INVALID");
|
||||
const mismatched = createZip(goodFiles);
|
||||
mismatched[30] ^= 1;
|
||||
await assert.rejects(registry.save(mismatched, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_ZIP_INVALID");
|
||||
|
||||
await writeFile(path.join(directory, "orphan.wskin"), createZip(goodFiles));
|
||||
assert.equal(await registry.readArchive("orphan"), null);
|
||||
assert.deepEqual(await registry.list(), []);
|
||||
});
|
||||
|
||||
test("the three bundled skins cannot be replaced or removed through the registry", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-builtins-"));
|
||||
context.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const registry = new SkinRegistry(directory);
|
||||
for (const id of ["builtin.light", "builtin.dark", "community.illusia-voice"]) {
|
||||
await assert.rejects(registry.save(Buffer.alloc(22), id), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_BUILTIN_PROTECTED");
|
||||
await assert.rejects(registry.remove(id), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_BUILTIN_PROTECTED");
|
||||
await assert.rejects(registry.setEnabled(id, false), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_BUILTIN_PROTECTED");
|
||||
}
|
||||
});
|
||||
|
||||
function createZip(files: Array<[string, Buffer]>): Buffer {
|
||||
const localRecords: Buffer[] = [];
|
||||
const centralRecords: Buffer[] = [];
|
||||
let localOffset = 0;
|
||||
for (const [name, bytes] of files) {
|
||||
const filename = Buffer.from(name, "utf8");
|
||||
const checksum = crc32(bytes);
|
||||
const local = Buffer.alloc(30 + filename.length + bytes.length);
|
||||
local.writeUInt32LE(0x04034b50, 0);
|
||||
local.writeUInt16LE(20, 4);
|
||||
local.writeUInt16LE(0, 6);
|
||||
local.writeUInt16LE(0, 8);
|
||||
local.writeUInt32LE(checksum, 14);
|
||||
local.writeUInt32LE(bytes.length, 18);
|
||||
local.writeUInt32LE(bytes.length, 22);
|
||||
local.writeUInt16LE(filename.length, 26);
|
||||
filename.copy(local, 30);
|
||||
bytes.copy(local, 30 + filename.length);
|
||||
localRecords.push(local);
|
||||
|
||||
const central = Buffer.alloc(46 + filename.length);
|
||||
central.writeUInt32LE(0x02014b50, 0);
|
||||
central.writeUInt16LE(0x0314, 4);
|
||||
central.writeUInt16LE(20, 6);
|
||||
central.writeUInt16LE(0, 8);
|
||||
central.writeUInt16LE(0, 10);
|
||||
central.writeUInt32LE(checksum, 16);
|
||||
central.writeUInt32LE(bytes.length, 20);
|
||||
central.writeUInt32LE(bytes.length, 24);
|
||||
central.writeUInt16LE(filename.length, 28);
|
||||
central.writeUInt32LE(0x81a40000, 38);
|
||||
central.writeUInt32LE(localOffset, 42);
|
||||
filename.copy(central, 46);
|
||||
centralRecords.push(central);
|
||||
localOffset += local.length;
|
||||
}
|
||||
const centralDirectory = Buffer.concat(centralRecords);
|
||||
const end = Buffer.alloc(22);
|
||||
end.writeUInt32LE(0x06054b50, 0);
|
||||
end.writeUInt16LE(files.length, 8);
|
||||
end.writeUInt16LE(files.length, 10);
|
||||
end.writeUInt32LE(centralDirectory.length, 12);
|
||||
end.writeUInt32LE(localOffset, 16);
|
||||
return Buffer.concat([...localRecords, centralDirectory, end]);
|
||||
}
|
||||
|
||||
function crc32(bytes: Buffer): number {
|
||||
let crc = 0xffffffff;
|
||||
for (const byte of bytes) {
|
||||
crc ^= byte;
|
||||
for (let bit = 0; bit < 8; bit += 1) crc = crc & 1 ? (crc >>> 1) ^ 0xedb88320 : crc >>> 1;
|
||||
}
|
||||
return (crc ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
import type { SkinCatalogEntry as SharedSkinCatalogEntry } from "../shared/skin-catalog.js";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { inflateRawSync } from "node:zlib";
|
||||
|
||||
const MAX_ARCHIVE_BYTES = 20 * 1024 * 1024;
|
||||
const MAX_EXPANDED_BYTES = 50 * 1024 * 1024;
|
||||
const MAX_FILE_COUNT = 128;
|
||||
const MAX_CSS_BYTES = 512 * 1024;
|
||||
const MAX_CONTENT_BYTES = 256 * 1024;
|
||||
const MAX_IMAGE_BYTES = 16 * 1024 * 1024;
|
||||
const MAX_FONT_BYTES = 4 * 1024 * 1024;
|
||||
const MAX_SKINS = 50;
|
||||
const MAX_TOTAL_ARCHIVES = 200 * 1024 * 1024;
|
||||
export const BUILTIN_SKIN_IDS = ["builtin.light", "builtin.dark", "community.illusia-voice"] as const;
|
||||
const BUILTIN_SKIN_ID_SET = new Set<string>(BUILTIN_SKIN_IDS);
|
||||
const EOCD_SIGNATURE = 0x06054b50;
|
||||
const CENTRAL_SIGNATURE = 0x02014b50;
|
||||
const LOCAL_SIGNATURE = 0x04034b50;
|
||||
|
||||
export interface SkinCatalogEntry extends SharedSkinCatalogEntry {
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export interface SkinRegistrySettings {
|
||||
defaultSkinId: string;
|
||||
}
|
||||
|
||||
interface SkinArchiveEntry {
|
||||
path: string;
|
||||
compressedSize: number;
|
||||
expandedSize: number;
|
||||
compression: number;
|
||||
crc: number;
|
||||
localOffset: number;
|
||||
flags: number;
|
||||
isDirectory: boolean;
|
||||
unixFileType: number;
|
||||
}
|
||||
|
||||
type ParsedSkinManifest = Omit<SkinCatalogEntry, "installedAt" | "previewUrl" | "previewMimeType" | "enabled"> & {
|
||||
entry: string;
|
||||
content?: string;
|
||||
preview?: string;
|
||||
};
|
||||
|
||||
export class SkinRegistryError extends Error {
|
||||
constructor(message: string, readonly code: string) {
|
||||
super(message);
|
||||
this.name = "SkinRegistryError";
|
||||
}
|
||||
}
|
||||
|
||||
export function isBuiltinSkinId(id: string): boolean {
|
||||
return BUILTIN_SKIN_ID_SET.has(id);
|
||||
}
|
||||
|
||||
export class SkinRegistry {
|
||||
constructor(private readonly directory: string) {}
|
||||
|
||||
async list(): Promise<SkinCatalogEntry[]> {
|
||||
await mkdir(this.directory, { recursive: true });
|
||||
const names = await readdir(this.directory);
|
||||
const entries: SkinCatalogEntry[] = [];
|
||||
for (const filename of names.filter((item) => item.endsWith(".json"))) {
|
||||
try {
|
||||
const value: unknown = JSON.parse(await readFile(path.join(this.directory, filename), "utf8"));
|
||||
if (!isCatalogEntry(value) || filename !== `${value.id}.json`) continue;
|
||||
const archiveInfo = await stat(path.join(this.directory, `${value.id}.wskin`)).catch(() => null);
|
||||
if (!archiveInfo?.isFile() || archiveInfo.size < 22 || archiveInfo.size > MAX_ARCHIVE_BYTES) continue;
|
||||
entries.push({ ...value, enabled: value.enabled !== false });
|
||||
} catch {
|
||||
// Ignore incomplete or stale metadata. The archive itself remains untouched.
|
||||
}
|
||||
}
|
||||
return entries.sort((left, right) => left.name.localeCompare(right.name));
|
||||
}
|
||||
|
||||
async save(bytes: Buffer, expectedId: string): Promise<SkinCatalogEntry> {
|
||||
if (isBuiltinSkinId(expectedId)) throw new SkinRegistryError("Built-in skins cannot be replaced.", "SKIN_BUILTIN_PROTECTED");
|
||||
if (!isSafeSkinId(expectedId)) throw new SkinRegistryError("Skin ID is invalid.", "SKIN_ID_INVALID");
|
||||
const parsed = validateSkinArchive(bytes, expectedId);
|
||||
await mkdir(this.directory, { recursive: true });
|
||||
const current = await this.list();
|
||||
const replacing = current.some((entry) => entry.id === expectedId);
|
||||
if (!replacing && current.length >= MAX_SKINS) throw new SkinRegistryError("The instance already has the maximum number of skins.", "SKIN_LIMIT");
|
||||
const archivePaths = await Promise.all(current.map(async (entry) => ({ id: entry.id, size: (await stat(path.join(this.directory, `${entry.id}.wskin`)).catch(() => ({ size: 0 }))).size })));
|
||||
const totalBytes = archivePaths.reduce((sum, entry) => sum + (entry.id === expectedId ? 0 : entry.size), bytes.byteLength);
|
||||
if (totalBytes > MAX_TOTAL_ARCHIVES) throw new SkinRegistryError("The total skin storage limit is 200 MiB.", "SKIN_STORAGE_LIMIT");
|
||||
|
||||
const previous = current.find((entry) => entry.id === expectedId);
|
||||
const installedAt = previous?.installedAt ?? Date.now();
|
||||
const catalog: SkinCatalogEntry = {
|
||||
...parsed.manifest,
|
||||
installedAt,
|
||||
enabled: previous?.enabled ?? true,
|
||||
...(parsed.previewMime ? { previewUrl: `/api/skins/${expectedId}/preview`, previewMimeType: parsed.previewMime } : {}),
|
||||
};
|
||||
const nonce = randomBytes(6).toString("hex");
|
||||
const archiveTemp = path.join(this.directory, `.${expectedId}.${nonce}.tmp`);
|
||||
const catalogTemp = path.join(this.directory, `.${expectedId}.${nonce}.json.tmp`);
|
||||
const previewTemp = path.join(this.directory, `.${expectedId}.${nonce}.preview.tmp`);
|
||||
try {
|
||||
await writeFile(archiveTemp, bytes, { flag: "wx", mode: 0o600 });
|
||||
await writeFile(catalogTemp, JSON.stringify(catalog), { flag: "wx", mode: 0o600 });
|
||||
if (parsed.previewBytes) await writeFile(previewTemp, parsed.previewBytes, { flag: "wx", mode: 0o600 });
|
||||
await rename(archiveTemp, path.join(this.directory, `${expectedId}.wskin`));
|
||||
await rename(catalogTemp, path.join(this.directory, `${expectedId}.json`));
|
||||
const previewPath = path.join(this.directory, `${expectedId}.preview`);
|
||||
if (parsed.previewBytes) await rename(previewTemp, previewPath);
|
||||
else await unlink(previewPath).catch(() => undefined);
|
||||
} catch (error) {
|
||||
await Promise.all([archiveTemp, catalogTemp, previewTemp].map((file) => unlink(file).catch(() => undefined)));
|
||||
throw error;
|
||||
}
|
||||
return catalog;
|
||||
}
|
||||
|
||||
async readArchive(id: string): Promise<Buffer | null> {
|
||||
if (!isSafeSkinId(id)) return null;
|
||||
if (!(await this.list()).some((entry) => entry.id === id && entry.enabled)) return null;
|
||||
try { return await readFile(path.join(this.directory, `${id}.wskin`)); }
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
async readPreview(id: string): Promise<{ bytes: Buffer; mimeType: string } | null> {
|
||||
if (!isSafeSkinId(id)) return null;
|
||||
const catalog = (await this.list()).find((entry) => entry.id === id);
|
||||
if (!catalog?.enabled || !catalog.previewUrl) return null;
|
||||
const mimeType = catalog.previewMimeType || "application/octet-stream";
|
||||
try {
|
||||
const bytes = await readFile(path.join(this.directory, `${id}.preview`));
|
||||
return { bytes, mimeType };
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
async remove(id: string): Promise<boolean> {
|
||||
if (isBuiltinSkinId(id)) throw new SkinRegistryError("Built-in skins cannot be removed.", "SKIN_BUILTIN_PROTECTED");
|
||||
if (!isSafeSkinId(id)) return false;
|
||||
const wasDefault = await this.getDefaultSkinId() === id;
|
||||
const archive = path.join(this.directory, `${id}.wskin`);
|
||||
const catalog = path.join(this.directory, `${id}.json`);
|
||||
const preview = path.join(this.directory, `${id}.preview`);
|
||||
const present = await Promise.all([archive, catalog, preview].map((file) => stat(file).then(() => true).catch(() => false))).then((items) => items.some(Boolean));
|
||||
if (!present) return false;
|
||||
await Promise.all([archive, catalog, preview].map((file) => unlink(file).catch((error: unknown) => {
|
||||
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
|
||||
})));
|
||||
if (wasDefault) await this.setDefaultSkin("builtin.light");
|
||||
return true;
|
||||
}
|
||||
|
||||
async setEnabled(id: string, enabled: boolean): Promise<SkinCatalogEntry> {
|
||||
if (isBuiltinSkinId(id)) throw new SkinRegistryError("Built-in skins cannot be disabled.", "SKIN_BUILTIN_PROTECTED");
|
||||
const entry = (await this.list()).find((item) => item.id === id);
|
||||
if (!entry) throw new SkinRegistryError("The skin was not found.", "SKIN_NOT_FOUND");
|
||||
const wasDefault = await this.getDefaultSkinId() === id;
|
||||
const updated = { ...entry, enabled };
|
||||
await writeAtomicJson(path.join(this.directory, `${id}.json`), updated);
|
||||
if (!enabled && wasDefault) await this.setDefaultSkin("builtin.light");
|
||||
return updated;
|
||||
}
|
||||
|
||||
async getDefaultSkinId(): Promise<string> {
|
||||
try {
|
||||
const value: unknown = JSON.parse(await readFile(path.join(this.directory, "settings.json"), "utf8"));
|
||||
const id = value && typeof value === "object" ? (value as Record<string, unknown>).defaultSkinId : null;
|
||||
if (typeof id !== "string") return "builtin.light";
|
||||
if (isBuiltinSkinId(id)) return id;
|
||||
const entry = (await this.list()).find((skin) => skin.id === id && skin.enabled);
|
||||
return entry ? id : "builtin.light";
|
||||
} catch {
|
||||
return "builtin.light";
|
||||
}
|
||||
}
|
||||
|
||||
async setDefaultSkin(id: string): Promise<SkinRegistrySettings> {
|
||||
if (!isBuiltinSkinId(id)) {
|
||||
const entry = (await this.list()).find((skin) => skin.id === id && skin.enabled);
|
||||
if (!entry) throw new SkinRegistryError("The default skin must be enabled and installed.", "SKIN_DEFAULT_INVALID");
|
||||
}
|
||||
await mkdir(this.directory, { recursive: true });
|
||||
const settings = { defaultSkinId: id };
|
||||
await writeAtomicJson(path.join(this.directory, "settings.json"), settings);
|
||||
return settings;
|
||||
}
|
||||
}
|
||||
|
||||
async function writeAtomicJson(filename: string, value: unknown): Promise<void> {
|
||||
const temporary = `${filename}.${randomBytes(6).toString("hex")}.tmp`;
|
||||
try {
|
||||
await writeFile(temporary, JSON.stringify(value), { flag: "wx", mode: 0o600 });
|
||||
await rename(temporary, filename);
|
||||
} catch (error) {
|
||||
await unlink(temporary).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: ParsedSkinManifest; previewBytes?: Buffer; previewMime?: string } {
|
||||
const entries = inspectArchive(bytes);
|
||||
const regularEntries = entries.filter((entry) => !entry.isDirectory);
|
||||
const rootPrefix = singleRootPrefix(regularEntries.map((entry) => entry.path));
|
||||
const fileBytes = new Map<string, Buffer>();
|
||||
for (const entry of regularEntries) {
|
||||
const packagePath = rootPrefix ? entry.path.slice(rootPrefix.length) : entry.path;
|
||||
if (!isSafePackagePath(packagePath)) throw new SkinRegistryError("The package contains an unsafe path.", "SKIN_PATH_INVALID");
|
||||
const content = extractEntry(bytes, entry);
|
||||
if (content.byteLength !== entry.expandedSize || crc32(content) !== entry.crc) throw new SkinRegistryError("The package has a damaged file entry.", "SKIN_ZIP_INVALID");
|
||||
if (fileBytes.has(packagePath.toLowerCase())) throw new SkinRegistryError("The package contains duplicate paths.", "SKIN_PATH_DUPLICATE");
|
||||
fileBytes.set(packagePath, content);
|
||||
}
|
||||
const manifestBytes = fileBytes.get("manifest.json");
|
||||
if (!manifestBytes || manifestBytes.byteLength > 32 * 1024) throw new SkinRegistryError("The package needs a small root-level manifest.json.", "SKIN_MANIFEST_MISSING");
|
||||
const manifest = parseManifest(manifestBytes);
|
||||
if (expectedId && manifest.id !== expectedId) throw new SkinRegistryError("The skin ID does not match the upload target.", "SKIN_ID_MISMATCH");
|
||||
const cssBytes = fileBytes.get(manifest.entry);
|
||||
if (!cssBytes || !cssBytes.byteLength || cssBytes.byteLength > MAX_CSS_BYTES) throw new SkinRegistryError("The CSS entry is missing or exceeds 512 KiB.", "SKIN_CSS_SIZE");
|
||||
decodeUtf8(cssBytes, "The CSS entry is not valid UTF-8.");
|
||||
|
||||
let previewBytes: Buffer | undefined;
|
||||
let previewMime: string | undefined;
|
||||
for (const [packagePath, data] of fileBytes) {
|
||||
if (["manifest.json", manifest.entry, manifest.content, manifest.preview].includes(packagePath)) continue;
|
||||
const mimeType = imageMime(packagePath) ?? (packagePath.toLowerCase().endsWith(".woff2") ? "font/woff2" : null);
|
||||
if (!mimeType) throw new SkinRegistryError(`Unsupported package file: ${packagePath}`, "SKIN_FILE_UNSUPPORTED");
|
||||
if (mimeType.startsWith("image/") && data.byteLength > MAX_IMAGE_BYTES) throw new SkinRegistryError("Each image must be smaller than 16 MiB.", "SKIN_IMAGE_SIZE");
|
||||
if (mimeType.startsWith("font/") && data.byteLength > MAX_FONT_BYTES) throw new SkinRegistryError("Fonts must be smaller than 4 MiB.", "SKIN_FONT_SIZE");
|
||||
}
|
||||
if (manifest.content) {
|
||||
const content = fileBytes.get(manifest.content);
|
||||
if (!content || content.byteLength > MAX_CONTENT_BYTES) throw new SkinRegistryError("content.json is missing or exceeds 256 KiB.", "SKIN_CONTENT_SIZE");
|
||||
decodeUtf8(content, "content.json is not valid UTF-8.");
|
||||
try { JSON.parse(content.toString("utf8")); }
|
||||
catch { throw new SkinRegistryError("content.json is not valid JSON.", "SKIN_CONTENT_INVALID"); }
|
||||
}
|
||||
if (manifest.preview) {
|
||||
previewBytes = fileBytes.get(manifest.preview);
|
||||
previewMime = imageMime(manifest.preview) ?? undefined;
|
||||
if (!previewBytes || !previewMime || previewBytes.byteLength > MAX_IMAGE_BYTES) throw new SkinRegistryError("The preview must be a supported image inside the package.", "SKIN_PREVIEW_INVALID");
|
||||
}
|
||||
return { manifest, ...(previewBytes ? { previewBytes, previewMime } : {}) };
|
||||
}
|
||||
|
||||
function inspectArchive(bytes: Buffer): SkinArchiveEntry[] {
|
||||
if (bytes.byteLength < 22 || bytes.byteLength > MAX_ARCHIVE_BYTES) throw new SkinRegistryError("A skin package must be smaller than 20 MiB.", "SKIN_ARCHIVE_SIZE");
|
||||
const minOffset = Math.max(0, bytes.byteLength - 22 - 0xffff);
|
||||
let endOffset = -1;
|
||||
for (let offset = bytes.byteLength - 22; offset >= minOffset; offset -= 1) {
|
||||
if (bytes.readUInt32LE(offset) === EOCD_SIGNATURE) { endOffset = offset; break; }
|
||||
}
|
||||
if (endOffset < 0) throw new SkinRegistryError("The upload is not a valid ZIP package.", "SKIN_ZIP_INVALID");
|
||||
const disk = bytes.readUInt16LE(endOffset + 4);
|
||||
const centralDisk = bytes.readUInt16LE(endOffset + 6);
|
||||
const entriesOnDisk = bytes.readUInt16LE(endOffset + 8);
|
||||
const entryCount = bytes.readUInt16LE(endOffset + 10);
|
||||
const centralSize = bytes.readUInt32LE(endOffset + 12);
|
||||
const centralOffset = bytes.readUInt32LE(endOffset + 16);
|
||||
const commentLength = bytes.readUInt16LE(endOffset + 20);
|
||||
if (disk !== 0 || centralDisk !== 0 || entriesOnDisk !== entryCount || entryCount === 0xffff || centralSize === 0xffffffff || centralOffset === 0xffffffff || endOffset + 22 + commentLength !== bytes.byteLength) {
|
||||
throw new SkinRegistryError("Multi-disk and ZIP64 packages are not supported.", "SKIN_ZIP_FORMAT");
|
||||
}
|
||||
if (!entryCount || entryCount > MAX_FILE_COUNT || centralOffset + centralSize !== endOffset) throw new SkinRegistryError("The ZIP directory is invalid or contains too many files.", "SKIN_FILE_COUNT");
|
||||
|
||||
const decoder = new TextDecoder("utf-8", { fatal: true });
|
||||
const entries: SkinArchiveEntry[] = [];
|
||||
const seenPaths = new Set<string>();
|
||||
let offset = centralOffset;
|
||||
let totalExpanded = 0;
|
||||
for (let index = 0; index < entryCount; index += 1) {
|
||||
if (offset + 46 > endOffset || bytes.readUInt32LE(offset) !== CENTRAL_SIGNATURE) throw new SkinRegistryError("The ZIP directory entry is invalid.", "SKIN_ZIP_INVALID");
|
||||
const madeBy = bytes.readUInt16LE(offset + 4);
|
||||
const flags = bytes.readUInt16LE(offset + 8);
|
||||
const compression = bytes.readUInt16LE(offset + 10);
|
||||
const crc = bytes.readUInt32LE(offset + 16);
|
||||
const compressedSize = bytes.readUInt32LE(offset + 20);
|
||||
const expandedSize = bytes.readUInt32LE(offset + 24);
|
||||
const nameLength = bytes.readUInt16LE(offset + 28);
|
||||
const extraLength = bytes.readUInt16LE(offset + 30);
|
||||
const fileCommentLength = bytes.readUInt16LE(offset + 32);
|
||||
const diskStart = bytes.readUInt16LE(offset + 34);
|
||||
const externalAttributes = bytes.readUInt32LE(offset + 38);
|
||||
const localOffset = bytes.readUInt32LE(offset + 42);
|
||||
const recordEnd = offset + 46 + nameLength + extraLength + fileCommentLength;
|
||||
if (recordEnd > endOffset || diskStart !== 0 || flags & ~0x0800 || (compression !== 0 && compression !== 8) || compressedSize === 0xffffffff || expandedSize === 0xffffffff || localOffset === 0xffffffff) {
|
||||
throw new SkinRegistryError("Encrypted, multi-disk, and unsupported ZIP entries are not allowed.", "SKIN_ZIP_FORMAT");
|
||||
}
|
||||
let entryPath: string;
|
||||
try { entryPath = decoder.decode(bytes.subarray(offset + 46, offset + 46 + nameLength)); }
|
||||
catch { throw new SkinRegistryError("ZIP filenames must be valid UTF-8.", "SKIN_PATH_INVALID"); }
|
||||
if (!(flags & 0x800) && /[^\x00-\x7f]/.test(entryPath)) throw new SkinRegistryError("Non-ASCII ZIP filenames must be encoded as UTF-8.", "SKIN_PATH_INVALID");
|
||||
if (!isSafePackagePath(entryPath, entryPath.endsWith("/"))) throw new SkinRegistryError("The package contains an unsafe path.", "SKIN_PATH_INVALID");
|
||||
const normalizedPath = entryPath.toLowerCase();
|
||||
if (seenPaths.has(normalizedPath)) throw new SkinRegistryError("The package contains duplicate or case-conflicting paths.", "SKIN_PATH_DUPLICATE");
|
||||
seenPaths.add(normalizedPath);
|
||||
const unixFileType = madeBy >> 8 === 3 ? (externalAttributes >>> 16) & 0xf000 : 0;
|
||||
if (unixFileType !== 0 && unixFileType !== 0x8000 && unixFileType !== 0x4000) throw new SkinRegistryError("Only regular files and directories are allowed in a skin package.", "SKIN_FILE_TYPE");
|
||||
const isDirectory = entryPath.endsWith("/");
|
||||
if ((unixFileType === 0x4000) !== isDirectory && unixFileType !== 0) throw new SkinRegistryError("ZIP file type does not match its path.", "SKIN_FILE_TYPE");
|
||||
if (isDirectory && (compressedSize !== 0 || expandedSize !== 0)) throw new SkinRegistryError("ZIP directory entries cannot contain data.", "SKIN_ZIP_INVALID");
|
||||
if (compression === 0 && compressedSize !== expandedSize) throw new SkinRegistryError("A stored ZIP entry has inconsistent sizes.", "SKIN_ZIP_INVALID");
|
||||
if (!isDirectory) {
|
||||
totalExpanded += expandedSize;
|
||||
if (totalExpanded > MAX_EXPANDED_BYTES) throw new SkinRegistryError("The expanded package exceeds 50 MiB.", "SKIN_EXPANDED_SIZE");
|
||||
if (expandedSize > 1024 * 1024 && expandedSize > Math.max(compressedSize, 1) * 250) throw new SkinRegistryError("The package has an abnormal compression ratio.", "SKIN_COMPRESSION_RATIO");
|
||||
}
|
||||
entries.push({ path: entryPath, compressedSize, expandedSize, compression, crc, localOffset, flags, isDirectory, unixFileType });
|
||||
offset = recordEnd;
|
||||
}
|
||||
if (offset !== centralOffset + centralSize) throw new SkinRegistryError("The ZIP directory length is inconsistent.", "SKIN_ZIP_INVALID");
|
||||
validateLocalEntries(bytes, entries, centralOffset, decoder);
|
||||
return entries;
|
||||
}
|
||||
|
||||
function validateLocalEntries(bytes: Buffer, entries: SkinArchiveEntry[], centralOffset: number, decoder: TextDecoder): void {
|
||||
const spans: Array<{ start: number; end: number }> = [];
|
||||
for (const entry of entries) {
|
||||
const offset = entry.localOffset;
|
||||
if (offset + 30 > centralOffset || bytes.readUInt32LE(offset) !== LOCAL_SIGNATURE) throw new SkinRegistryError("A ZIP local file header is invalid.", "SKIN_ZIP_INVALID");
|
||||
const flags = bytes.readUInt16LE(offset + 6);
|
||||
const compression = bytes.readUInt16LE(offset + 8);
|
||||
const crc = bytes.readUInt32LE(offset + 14);
|
||||
const compressedSize = bytes.readUInt32LE(offset + 18);
|
||||
const expandedSize = bytes.readUInt32LE(offset + 22);
|
||||
const nameLength = bytes.readUInt16LE(offset + 26);
|
||||
const extraLength = bytes.readUInt16LE(offset + 28);
|
||||
const headerEnd = offset + 30 + nameLength + extraLength;
|
||||
if (headerEnd > centralOffset || flags !== entry.flags || compression !== entry.compression || crc !== entry.crc || compressedSize !== entry.compressedSize || expandedSize !== entry.expandedSize) {
|
||||
throw new SkinRegistryError("ZIP local and central headers disagree.", "SKIN_ZIP_INVALID");
|
||||
}
|
||||
let localPath: string;
|
||||
try { localPath = decoder.decode(bytes.subarray(offset + 30, offset + 30 + nameLength)); }
|
||||
catch { throw new SkinRegistryError("ZIP filenames must be valid UTF-8.", "SKIN_PATH_INVALID"); }
|
||||
if (localPath !== entry.path) throw new SkinRegistryError("ZIP local and central filenames disagree.", "SKIN_ZIP_INVALID");
|
||||
const end = headerEnd + entry.compressedSize;
|
||||
if (end > centralOffset) throw new SkinRegistryError("A ZIP entry overlaps the central directory.", "SKIN_ZIP_INVALID");
|
||||
spans.push({ start: offset, end });
|
||||
}
|
||||
spans.sort((left, right) => left.start - right.start);
|
||||
for (let index = 1; index < spans.length; index += 1) {
|
||||
if (spans[index].start < spans[index - 1].end) throw new SkinRegistryError("ZIP local file entries overlap.", "SKIN_ZIP_INVALID");
|
||||
}
|
||||
}
|
||||
|
||||
function extractEntry(archive: Buffer, entry: SkinArchiveEntry): Buffer {
|
||||
const offset = entry.localOffset;
|
||||
if (offset + 30 > archive.byteLength || archive.readUInt32LE(offset) !== LOCAL_SIGNATURE) throw new SkinRegistryError("A ZIP local file header is invalid.", "SKIN_ZIP_INVALID");
|
||||
const flags = archive.readUInt16LE(offset + 6);
|
||||
const compression = archive.readUInt16LE(offset + 8);
|
||||
const nameLength = archive.readUInt16LE(offset + 26);
|
||||
const extraLength = archive.readUInt16LE(offset + 28);
|
||||
if (flags !== entry.flags || compression !== entry.compression) throw new SkinRegistryError("ZIP headers disagree about file compression.", "SKIN_ZIP_INVALID");
|
||||
const dataStart = offset + 30 + nameLength + extraLength;
|
||||
const dataEnd = dataStart + entry.compressedSize;
|
||||
if (dataEnd > archive.byteLength) throw new SkinRegistryError("A ZIP entry extends past the archive.", "SKIN_ZIP_INVALID");
|
||||
const compressed = archive.subarray(dataStart, dataEnd);
|
||||
if (entry.compression === 0) return Buffer.from(compressed);
|
||||
try { return inflateRawSync(compressed, { maxOutputLength: entry.expandedSize + 1 }); }
|
||||
catch { throw new SkinRegistryError("A ZIP entry could not be safely decompressed.", "SKIN_ZIP_INVALID"); }
|
||||
}
|
||||
|
||||
function parseManifest(bytes: Buffer): ParsedSkinManifest {
|
||||
let raw: unknown;
|
||||
try { raw = JSON.parse(decodeUtf8(bytes, "manifest.json is not valid UTF-8.")); }
|
||||
catch { throw new SkinRegistryError("manifest.json must contain valid JSON.", "SKIN_MANIFEST_INVALID"); }
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new SkinRegistryError("manifest.json must be an object.", "SKIN_MANIFEST_INVALID");
|
||||
const value = raw as Record<string, unknown>;
|
||||
const read = (key: string, max: number): string => {
|
||||
const item = value[key];
|
||||
if (typeof item !== "string" || !item.trim() || item.length > max) throw new SkinRegistryError(`manifest.json has an invalid ${key} field.`, "SKIN_MANIFEST_INVALID");
|
||||
return item.trim();
|
||||
};
|
||||
const id = read("id", 80);
|
||||
if (value.schemaVersion !== 1 || !isSafeSkinId(id)) throw new SkinRegistryError("The skin schema version or ID is unsupported.", "SKIN_SCHEMA_VERSION");
|
||||
const version = read("version", 32);
|
||||
const minAppVersion = read("minAppVersion", 32);
|
||||
if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version) || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(minAppVersion)) throw new SkinRegistryError("Skin and minimum app versions must use semantic version format.", "SKIN_MANIFEST_INVALID");
|
||||
const entry = read("entry", 120);
|
||||
const readOptional = (key: string, max: number): string | undefined => value[key] == null ? undefined : read(key, max);
|
||||
const content = readOptional("content", 120);
|
||||
const preview = readOptional("preview", 120);
|
||||
for (const candidate of [entry, content, preview].filter((item): item is string => Boolean(item))) if (!isSafePackagePath(candidate)) throw new SkinRegistryError("The manifest references an unsafe path.", "SKIN_PATH_INVALID");
|
||||
if (!entry.toLowerCase().endsWith(".css") || (content && !content.toLowerCase().endsWith(".json")) || (preview && !imageMime(preview))) throw new SkinRegistryError("The entry must be CSS, content must be JSON, and preview must be a supported image.", "SKIN_MANIFEST_INVALID");
|
||||
if (new Set(["manifest.json", entry, ...(content ? [content] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase())).size !== 2 + Number(Boolean(content)) + Number(Boolean(preview))) throw new SkinRegistryError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID");
|
||||
const description = readOptional("description", 400);
|
||||
return { id, name: read("name", 80), version, author: read("author", 80), license: read("license", 80), minAppVersion, entry, ...(content ? { content } : {}), ...(preview ? { preview } : {}), ...(description ? { description } : {}) };
|
||||
}
|
||||
|
||||
function singleRootPrefix(paths: string[]): string {
|
||||
if (!paths.length) return "";
|
||||
const firstSlash = paths[0].indexOf("/");
|
||||
if (firstSlash < 1) return "";
|
||||
const prefix = paths[0].slice(0, firstSlash + 1);
|
||||
return paths.every((item) => item.startsWith(prefix)) ? prefix : "";
|
||||
}
|
||||
|
||||
function isSafePackagePath(value: string, allowDirectory = false): boolean {
|
||||
const candidate = allowDirectory ? value.slice(0, -1) : value;
|
||||
return Boolean(candidate) && !candidate.startsWith("/") && !candidate.includes("\\") && !candidate.includes("\0") && !/^[a-z]:/i.test(candidate)
|
||||
&& candidate.split("/").every((part) => Boolean(part) && part !== "." && part !== ".." && !part.includes(":"));
|
||||
}
|
||||
|
||||
function isSafeSkinId(value: unknown): value is string {
|
||||
return typeof value === "string" && value.length <= 80 && /^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(value) && !value.startsWith("builtin.");
|
||||
}
|
||||
|
||||
function imageMime(filename: string): string | null {
|
||||
switch (path.extname(filename).toLowerCase()) {
|
||||
case ".png": return "image/png";
|
||||
case ".jpg": case ".jpeg": return "image/jpeg";
|
||||
case ".webp": return "image/webp";
|
||||
case ".avif": return "image/avif";
|
||||
case ".gif": return "image/gif";
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
function decodeUtf8(bytes: Buffer, message: string): string {
|
||||
try { return new TextDecoder("utf-8", { fatal: true }).decode(bytes); }
|
||||
catch { throw new SkinRegistryError(message, "SKIN_ENCODING_INVALID"); }
|
||||
}
|
||||
|
||||
function isCatalogEntry(value: unknown): value is SkinCatalogEntry {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
||||
const item = value as Record<string, unknown>;
|
||||
const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
|
||||
if (!isSafeSkinId(item.id) || !isShortText(item.name, 80) || !isShortText(item.author, 80) || !isShortText(item.license, 80)) return false;
|
||||
if (typeof item.version !== "string" || !semver.test(item.version) || typeof item.minAppVersion !== "string" || !semver.test(item.minAppVersion)) return false;
|
||||
if (!Number.isSafeInteger(item.installedAt) || (item.installedAt as number) < 0) return false;
|
||||
if (item.enabled !== undefined && typeof item.enabled !== "boolean") return false;
|
||||
if (item.description !== undefined && (typeof item.description !== "string" || item.description.length > 400)) return false;
|
||||
const hasPreview = item.previewUrl !== undefined || item.previewMimeType !== undefined;
|
||||
return !hasPreview || (item.previewUrl === `/api/skins/${item.id}/preview` && ["image/png", "image/jpeg", "image/webp", "image/avif", "image/gif"].includes(String(item.previewMimeType)));
|
||||
}
|
||||
|
||||
function isShortText(value: unknown, limit: number): value is string {
|
||||
return typeof value === "string" && value.trim().length > 0 && value.length <= limit;
|
||||
}
|
||||
|
||||
const crcTable = (() => {
|
||||
const table = new Uint32Array(256);
|
||||
for (let index = 0; index < table.length; index += 1) {
|
||||
let value = index;
|
||||
for (let bit = 0; bit < 8; bit += 1) value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
|
||||
table[index] = value >>> 0;
|
||||
}
|
||||
return table;
|
||||
})();
|
||||
|
||||
function crc32(bytes: Buffer): number {
|
||||
let value = 0xffffffff;
|
||||
for (const byte of bytes) value = crcTable[(value ^ byte) & 0xff] ^ (value >>> 8);
|
||||
return (value ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import path from "node:path";
|
||||
import { existsSync, readFileSync, unlinkSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createAccelerationRelayServer } from "./server/acceleration-relay.js";
|
||||
import { normalizeScreenShareIceServers, type ScreenShareIceServer } from "./server/screen-share.js";
|
||||
import { SkinRegistry } from "./admin/skin-registry.js";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT_DIR = path.resolve(__dirname, "..");
|
||||
@@ -13,6 +15,7 @@ const DATA_DIR = process.env.WEBSPEAK_DATA_DIR?.trim() || path.join(ROOT_DIR, "d
|
||||
const LOG_DIR = path.join(DATA_DIR, "logs");
|
||||
const STATIC_DIR = path.join(ROOT_DIR, "web", "dist");
|
||||
const APP_VERSION = readPackageVersion();
|
||||
const SCREEN_SHARE_ICE_SERVERS = readScreenShareIceServers(process.env.WEBSPEAK_SCREEN_SHARE_ICE_SERVERS);
|
||||
|
||||
async function main() {
|
||||
if (process.env.WEBSPEAK_MODE?.trim().toLowerCase() === "relay") {
|
||||
@@ -56,6 +59,7 @@ async function main() {
|
||||
voiceBridgeOptions: {
|
||||
joinTickets,
|
||||
webRtc: () => adminService.getWebRtcAudioOptions(),
|
||||
screenShareIceServers: () => SCREEN_SHARE_ICE_SERVERS,
|
||||
// The public gateway only uses the relay configuration explicitly
|
||||
// saved in the admin console. Environment variables belong to the
|
||||
// standalone relay process and must never make the relay option appear
|
||||
@@ -64,7 +68,10 @@ async function main() {
|
||||
accelerationName: () => adminService.getAccelerationRelayName(),
|
||||
},
|
||||
adminService,
|
||||
skinRegistry: new SkinRegistry(path.join(DATA_DIR, "skins")),
|
||||
logger,
|
||||
nextVisitorNumber: () => database.nextVisitorNumber(),
|
||||
visitorCount: () => database.getVisitorCount(),
|
||||
});
|
||||
|
||||
await webServer.start();
|
||||
@@ -123,6 +130,18 @@ function parseBoolean(value: string | undefined): boolean {
|
||||
return value === "1" || value?.toLowerCase() === "true";
|
||||
}
|
||||
|
||||
function readScreenShareIceServers(value: string | undefined): ScreenShareIceServer[] {
|
||||
const raw = value?.trim();
|
||||
if (!raw) return normalizeScreenShareIceServers();
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
return normalizeScreenShareIceServers(Array.isArray(parsed) ? parsed : undefined);
|
||||
} catch {
|
||||
// A simple comma/space-separated list is convenient for STUN-only setups.
|
||||
return normalizeScreenShareIceServers(raw.split(/[\s,]+/).filter(Boolean).map((urls) => ({ urls })));
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error("Fatal error:", err);
|
||||
process.exit(1);
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import express from "express";
|
||||
import { createServer } from "node:http";
|
||||
import path from "node:path";
|
||||
import { existsSync } from "node:fs";
|
||||
import { identityFromString } from "@echosixhiya/teamspeak-client";
|
||||
import { createLogger } from "../logger.js";
|
||||
import { parseTeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { JoinTicketStore } from "../server/join-ticket.js";
|
||||
import { JoinRateLimiter } from "../server/join-rate-limit.js";
|
||||
import { VoiceBridge } from "../server/voice-bridge.js";
|
||||
import { DEFAULT_WELCOME_TEXTS } from "../site-copy.js";
|
||||
|
||||
const port = Number(process.env.WEBSPEAK_MOBILE_PORT || 3040);
|
||||
const host = "127.0.0.1";
|
||||
const dataDir = process.env.WEBSPEAK_DATA_DIR;
|
||||
const staticDir = process.env.WEBSPEAK_MOBILE_WWW;
|
||||
if (!dataDir || !staticDir || !existsSync(path.join(staticDir, "index.html"))) {
|
||||
throw new Error("Android gateway data or web assets are missing");
|
||||
}
|
||||
|
||||
const logger = createLogger(path.join(dataDir, "logs"));
|
||||
const app = express();
|
||||
const server = createServer(app);
|
||||
const joinTickets = new JoinTicketStore();
|
||||
const joinRateLimiter = new JoinRateLimiter();
|
||||
const voiceBridge = new VoiceBridge({ joinTickets, webRtc: { enabled: false } }, logger);
|
||||
|
||||
app.use(express.json({ limit: "100kb" }));
|
||||
app.get("/health", (_request, response) => response.json({ status: "ok", engine: "webspeak-android" }));
|
||||
app.get("/api/health", (_request, response) => response.json({ status: "ok", engine: "webspeak-android" }));
|
||||
app.get("/api/public-config", (_request, response) => {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
response.json({
|
||||
version: process.env.WEBSPEAK_VERSION ?? "0.2.6",
|
||||
initialized: true,
|
||||
siteName: "WebSpeak",
|
||||
welcomeText: DEFAULT_WELCOME_TEXTS.zh,
|
||||
welcomeTextEn: DEFAULT_WELCOME_TEXTS.en,
|
||||
welcomeTexts: DEFAULT_WELCOME_TEXTS,
|
||||
accessMode: "open",
|
||||
target: "",
|
||||
targetPrefillBlocked: false,
|
||||
accelerationAvailable: false,
|
||||
accelerationRelays: [],
|
||||
mobile: true,
|
||||
});
|
||||
});
|
||||
app.get("/api/skins", (_request, response) => {
|
||||
response.setHeader("Cache-Control", "no-cache");
|
||||
response.json({ skins: [], defaultSkinId: "builtin.light" });
|
||||
});
|
||||
app.post("/api/join-ticket", (request, response) => {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
if (!request.is("application/json") || !isSameOrigin(request)) {
|
||||
response.status(403).json({ ok: false, code: "ORIGIN_REJECTED" });
|
||||
return;
|
||||
}
|
||||
if (!joinRateLimiter.allow(request.socket.remoteAddress ?? "unknown")) {
|
||||
response.status(429).json({ ok: false, code: "RATE_LIMITED" });
|
||||
return;
|
||||
}
|
||||
const body = request.body && typeof request.body === "object" && !Array.isArray(request.body)
|
||||
? request.body as Record<string, unknown>
|
||||
: {};
|
||||
const nickname = typeof body.nickname === "string" ? body.nickname.trim().slice(0, 30) : "";
|
||||
const channel = typeof body.channel === "string" ? body.channel.trim().slice(0, 100) : "";
|
||||
const serverPassword = typeof body.serverPassword === "string" ? body.serverPassword.slice(0, 512) : "";
|
||||
if (!nickname) {
|
||||
response.status(400).json({ ok: false, code: "INVALID_NICKNAME" });
|
||||
return;
|
||||
}
|
||||
let target;
|
||||
try {
|
||||
target = parseTeamSpeakTarget(typeof body.target === "string" ? body.target : "");
|
||||
} catch {
|
||||
response.status(400).json({ ok: false, code: "TARGET_NOT_ALLOWED" });
|
||||
return;
|
||||
}
|
||||
let identity: string | undefined;
|
||||
if (typeof body.identity === "string" && body.identity.length <= 8192) {
|
||||
try {
|
||||
identityFromString(body.identity);
|
||||
identity = body.identity;
|
||||
} catch {
|
||||
// Corrupt local identity should not prevent an ephemeral join.
|
||||
}
|
||||
}
|
||||
const ticket = joinTickets.create({
|
||||
target,
|
||||
serverPassword,
|
||||
nickname,
|
||||
...(channel ? { channel } : {}),
|
||||
...(identity ? { identity, rememberIdentity: true } : body.rememberIdentity === true ? { rememberIdentity: true } : {}),
|
||||
});
|
||||
response.status(201).json({ ok: true, ticket });
|
||||
});
|
||||
|
||||
app.use(express.static(staticDir));
|
||||
app.get(/^(?!\/api|\/ws)/, (_request, response) => response.sendFile(path.join(staticDir, "index.html")));
|
||||
voiceBridge.attach(server);
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(port, host, () => {
|
||||
server.off("error", reject);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
logger.info({ host, port, dataDir }, "Android gateway started");
|
||||
|
||||
async function shutdown(): Promise<void> {
|
||||
await voiceBridge.shutdown();
|
||||
server.close();
|
||||
}
|
||||
process.once("SIGTERM", () => { void shutdown(); });
|
||||
process.once("SIGINT", () => { void shutdown(); });
|
||||
|
||||
function isSameOrigin(request: express.Request): boolean {
|
||||
const origin = request.header("origin");
|
||||
const requestHost = request.header("host");
|
||||
try {
|
||||
return Boolean(origin && requestHost && new URL(origin).host === requestHost);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ 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 = 7;
|
||||
export const DATABASE_SCHEMA_VERSION = 8;
|
||||
export type AccessMode = "fixed" | "open";
|
||||
|
||||
export interface PersistedSettings {
|
||||
@@ -25,6 +25,9 @@ export interface PersistedSettings {
|
||||
lastTestLatencyMs: number | null;
|
||||
lastTestError: string | null;
|
||||
webRtcEnabled: boolean;
|
||||
webRtcPublicHost: string;
|
||||
webRtcIpv6Enabled: boolean;
|
||||
webRtcStunServer: string;
|
||||
webRtcUdpStart: number;
|
||||
webRtcUdpEnd: number;
|
||||
relayConfigured: boolean;
|
||||
@@ -48,6 +51,9 @@ export interface SettingsUpdate {
|
||||
tsPort: number;
|
||||
tsPasswordEncrypted: string | null;
|
||||
webRtcEnabled: boolean;
|
||||
webRtcPublicHost?: string;
|
||||
webRtcIpv6Enabled?: boolean;
|
||||
webRtcStunServer?: string;
|
||||
webRtcUdpStart?: number;
|
||||
webRtcUdpEnd?: number;
|
||||
relayConfigured: boolean;
|
||||
@@ -114,6 +120,8 @@ interface SettingsRow extends Record<string, unknown> {
|
||||
last_test_error: string | null;
|
||||
webrtc_enabled: number;
|
||||
webrtc_public_host: string;
|
||||
webrtc_ipv6_enabled: number;
|
||||
webrtc_stun_server: string;
|
||||
webrtc_udp_start: number;
|
||||
webrtc_udp_end: number;
|
||||
relay_configured: number;
|
||||
@@ -208,6 +216,9 @@ export class WebSpeakDatabase {
|
||||
lastTestLatencyMs: row.last_test_latency_ms,
|
||||
lastTestError: row.last_test_error,
|
||||
webRtcEnabled: row.webrtc_enabled === 1,
|
||||
webRtcPublicHost: row.webrtc_public_host,
|
||||
webRtcIpv6Enabled: row.webrtc_ipv6_enabled === 1,
|
||||
webRtcStunServer: row.webrtc_stun_server,
|
||||
webRtcUdpStart: row.webrtc_udp_start,
|
||||
webRtcUdpEnd: row.webrtc_udp_end,
|
||||
relayConfigured: row.relay_configured === 1,
|
||||
@@ -377,6 +388,25 @@ export class WebSpeakDatabase {
|
||||
).run(key, value);
|
||||
}
|
||||
|
||||
nextVisitorNumber(): number {
|
||||
let nextNumber = 1;
|
||||
this.transaction(() => {
|
||||
const currentValue = this.getMeta("visitor_count");
|
||||
const current = currentValue ? Number.parseInt(currentValue, 10) : 0;
|
||||
nextNumber = Number.isSafeInteger(current) && current >= 0 && current < Number.MAX_SAFE_INTEGER
|
||||
? current + 1
|
||||
: 1;
|
||||
this.setMeta("visitor_count", String(nextNumber));
|
||||
});
|
||||
return nextNumber;
|
||||
}
|
||||
|
||||
getVisitorCount(): number {
|
||||
const value = this.getMeta("visitor_count");
|
||||
const count = value ? Number.parseInt(value, 10) : 0;
|
||||
return Number.isSafeInteger(count) && count >= 0 ? count : 0;
|
||||
}
|
||||
|
||||
addAudit(event: string, details: Record<string, unknown> = {}): void {
|
||||
this.insertAudit(event, details, new Date().toISOString());
|
||||
}
|
||||
@@ -557,6 +587,16 @@ export class WebSpeakDatabase {
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 7");
|
||||
});
|
||||
version = 7;
|
||||
}
|
||||
if (version === 7) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
ALTER TABLE settings ADD COLUMN webrtc_ipv6_enabled INTEGER NOT NULL DEFAULT 0 CHECK (webrtc_ipv6_enabled IN (0, 1));
|
||||
ALTER TABLE settings ADD COLUMN webrtc_stun_server TEXT NOT NULL DEFAULT '';
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 8");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -564,7 +604,7 @@ export class WebSpeakDatabase {
|
||||
this.database.prepare(
|
||||
`UPDATE settings SET
|
||||
site_name = ?, welcome_text = ?, welcome_text_en = ?, welcome_text_de = ?, welcome_text_ru = ?, welcome_text_ja = ?, access_mode = ?, ts_host = ?, ts_port = ?,
|
||||
ts_password_encrypted = ?, webrtc_enabled = ?, webrtc_udp_start = ?,
|
||||
ts_password_encrypted = ?, webrtc_enabled = ?, webrtc_public_host = ?, webrtc_ipv6_enabled = ?, webrtc_stun_server = ?, webrtc_udp_start = ?,
|
||||
webrtc_udp_end = ?, relay_configured = ?, relay_enabled = ?, relay_name = ?,
|
||||
relay_host = ?, relay_port = ?, relay_token_encrypted = ?, updated_at = ?
|
||||
WHERE id = 1`,
|
||||
@@ -580,6 +620,9 @@ export class WebSpeakDatabase {
|
||||
settings.tsPort,
|
||||
settings.tsPasswordEncrypted,
|
||||
settings.webRtcEnabled ? 1 : 0,
|
||||
settings.webRtcPublicHost ?? "",
|
||||
settings.webRtcIpv6Enabled ? 1 : 0,
|
||||
settings.webRtcStunServer ?? "",
|
||||
settings.webRtcUdpStart ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[0],
|
||||
settings.webRtcUdpEnd ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[1],
|
||||
settings.relayConfigured ? 1 : 0,
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { isSafeOpenTargetForPrefill } from "./open-target-policy.js";
|
||||
|
||||
test("open-mode target prefill follows the same allow/deny result as the join policy", async () => {
|
||||
assert.equal(await isSafeOpenTargetForPrefill({ host: "198.51.100.24", port: 9987 }, {
|
||||
resolveTarget: async (target) => target,
|
||||
}), true);
|
||||
assert.equal(await isSafeOpenTargetForPrefill({ host: "teamspeak", port: 9987 }, {
|
||||
resolveTarget: async () => { throw new Error("private or unresolved target"); },
|
||||
}), false);
|
||||
});
|
||||
|
||||
test("open-mode target prefill fails closed when DNS validation stalls", async () => {
|
||||
const result = await isSafeOpenTargetForPrefill({ host: "internal.example", port: 9987 }, {
|
||||
timeoutMs: 10,
|
||||
resolveTarget: async () => new Promise(() => undefined),
|
||||
});
|
||||
assert.equal(result, false);
|
||||
});
|
||||
@@ -27,6 +27,26 @@ export async function resolveSafeOpenTarget(target: TeamSpeakTarget): Promise<Te
|
||||
return { host: addresses[0]!.address, port: target.port };
|
||||
}
|
||||
|
||||
/** A bounded, non-authoritative check used only to avoid pre-filling a target that open mode will reject. */
|
||||
export async function isSafeOpenTargetForPrefill(
|
||||
target: TeamSpeakTarget,
|
||||
options: { timeoutMs?: number; resolveTarget?: (target: TeamSpeakTarget) => Promise<TeamSpeakTarget> } = {},
|
||||
): Promise<boolean> {
|
||||
const timeoutMs = options.timeoutMs ?? 1_000;
|
||||
const resolveTarget = options.resolveTarget ?? resolveSafeOpenTarget;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
return await Promise.race([
|
||||
Promise.resolve().then(() => resolveTarget(target)).then(() => true, () => false),
|
||||
new Promise<boolean>((resolve) => {
|
||||
timer = setTimeout(() => resolve(false), timeoutMs);
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
if (timer !== undefined) clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
export function isRestrictedAddress(address: string): boolean {
|
||||
const version = isIP(address);
|
||||
if (version === 4) return isRestrictedIpv4(address);
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { createAudioFlowStats, snapshotAudioStats, snapshotAudioStatus } from "./audio-stats.js";
|
||||
import type { WebRtcAudioStats } from "./webrtc-audio.js";
|
||||
|
||||
test("diagnostic snapshots remain stable while new traffic changes live counters", () => {
|
||||
const audio = createAudioFlowStats();
|
||||
audio.egressFramesByClient[2] = 3;
|
||||
const snapshot = snapshotAudioStats({ audio, webrtc: null });
|
||||
audio.egressFramesByClient[2]++;
|
||||
assert.equal(snapshot.egressFramesByClient[2], 3);
|
||||
snapshot.egressFramesByClient[2] = 10;
|
||||
assert.equal(audio.egressFramesByClient[2], 4);
|
||||
});
|
||||
|
||||
test("public audio status includes live WebRTC counters without losing gateway counters", () => {
|
||||
const audio = createAudioFlowStats();
|
||||
audio.ingressFrames = 12;
|
||||
const rtc: WebRtcAudioStats = {
|
||||
webrtcIngressRtpFrames: 7, webrtcIngressRtpFirstAt: 100, webrtcIngressRtpLastAt: 220, webrtcIngressRtpMaxGapMs: 20,
|
||||
webrtcEgressRtpFrames: 3, webrtcEgressRtpFirstAt: 100, webrtcEgressRtpLastAt: 140, webrtcEgressRtpMaxGapMs: 20,
|
||||
webrtcQueuePeakFrames: 2, webrtcQueueDroppedFrames: 1, webrtcQueueUnderrunTicks: 0, webrtcPacerLateTicks: 0,
|
||||
webrtcQueueCurrentFrames: 1, webrtcIngressQuietFrames: 0, webrtcIngressDecodeErrors: 0,
|
||||
webrtcDownlinkDecodedFrames: 3, webrtcDownlinkDecodeErrors: 0, webrtcDownlinkShortFrames: 0,
|
||||
};
|
||||
const source = { audio, webrtc: { getStats: () => rtc } };
|
||||
const status = snapshotAudioStatus(source);
|
||||
assert.equal(status.transport, "webrtc");
|
||||
assert.equal(status.ingressFrames, 12);
|
||||
assert.equal(status.webrtcIngressRtpFrames, 7);
|
||||
assert.equal(snapshotAudioStatus({ audio, webrtc: null }).transport, "websocket");
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import type { VoiceAudioBridgeStats } from "../shared/voice-models.js";
|
||||
import type { WebRtcAudioSession, WebRtcAudioStats } from "./webrtc-audio.js";
|
||||
|
||||
export interface AudioFlowStats extends WebRtcAudioStats {
|
||||
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>;
|
||||
|
||||
}
|
||||
|
||||
export interface AudioStatsSource {
|
||||
audio: AudioFlowStats;
|
||||
webrtc: Pick<WebRtcAudioSession, "getStats"> | null;
|
||||
}
|
||||
|
||||
export 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,
|
||||
};
|
||||
}
|
||||
|
||||
export function snapshotAudioStats(entry: AudioStatsSource): AudioFlowStats {
|
||||
const stats = { ...entry.audio, egressFramesByClient: { ...entry.audio.egressFramesByClient } };
|
||||
const webRtcStats: WebRtcAudioStats | undefined = entry.webrtc?.getStats();
|
||||
if (webRtcStats) Object.assign(stats, webRtcStats);
|
||||
return stats;
|
||||
}
|
||||
|
||||
export function snapshotAudioStatus(entry: AudioStatsSource): VoiceAudioBridgeStats {
|
||||
const stats = snapshotAudioStats(entry);
|
||||
return {
|
||||
transport: entry.webrtc ? "webrtc" : "websocket",
|
||||
ingressFrames: stats.ingressFrames,
|
||||
ingressDroppedFrames: stats.ingressDroppedFrames,
|
||||
ingressMaxGapMs: stats.ingressMaxGapMs,
|
||||
tsSendFrames: stats.tsSendFrames,
|
||||
tsSendErrors: stats.tsSendErrors,
|
||||
tsSendMaxGapMs: stats.tsSendMaxGapMs,
|
||||
tsReceiveFrames: stats.tsReceiveFrames,
|
||||
tsReceiveMaxGapMs: stats.tsReceiveMaxGapMs,
|
||||
egressFrames: stats.egressFrames,
|
||||
egressDroppedFrames: stats.egressDroppedFrames,
|
||||
egressMaxGapMs: stats.egressMaxGapMs,
|
||||
webrtcIngressRtpFrames: stats.webrtcIngressRtpFrames,
|
||||
webrtcIngressRtpMaxGapMs: stats.webrtcIngressRtpMaxGapMs,
|
||||
webrtcEgressRtpFrames: stats.webrtcEgressRtpFrames,
|
||||
webrtcEgressRtpMaxGapMs: stats.webrtcEgressRtpMaxGapMs,
|
||||
webrtcQueueDroppedFrames: stats.webrtcQueueDroppedFrames,
|
||||
webrtcQueueUnderrunTicks: stats.webrtcQueueUnderrunTicks,
|
||||
webrtcPacerLateTicks: stats.webrtcPacerLateTicks,
|
||||
webrtcIngressDecodeErrors: stats.webrtcIngressDecodeErrors,
|
||||
webrtcDownlinkDecodeErrors: stats.webrtcDownlinkDecodeErrors,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { DirectoryClientInfo, DirectorySnapshot } from "@echosixhiya/teamspeak-client";
|
||||
import { DirectorySynchronizer } from "./directory-sync.js";
|
||||
|
||||
function member(id: number, channelID = 1n, overrides: Partial<DirectoryClientInfo> = {}): DirectoryClientInfo {
|
||||
return { id, channelID, nickname: `Member ${id}`, uid: `uid-${id}`, serverGroups: [], type: 0, ...overrides };
|
||||
}
|
||||
|
||||
function snapshot(...clients: DirectoryClientInfo[]): DirectorySnapshot {
|
||||
return { channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Lobby", description: "" }], clients };
|
||||
}
|
||||
|
||||
test("events received during the welcome sequence override the initial snapshot in order", () => {
|
||||
const directory = new DirectorySynchronizer();
|
||||
directory.applyClientMoved(1, 2n);
|
||||
directory.applyClientLeave(2);
|
||||
directory.applyClientEnter(member(3));
|
||||
directory.applyClientUpdated(member(3, 1n, { inputMuted: true }));
|
||||
assert.equal(directory.ready, false);
|
||||
assert.equal(directory.getSnapshot(), null);
|
||||
directory.applySnapshot(snapshot(member(1), member(2)));
|
||||
assert.equal(directory.ready, true);
|
||||
assert.deepEqual(directory.getSnapshot()?.clients, [member(1, 2n), member(3, 1n, { inputMuted: true })]);
|
||||
});
|
||||
|
||||
test("partial snapshots retain earlier clients and state omitted by a later snapshot", () => {
|
||||
const directory = new DirectorySynchronizer();
|
||||
directory.applySnapshot(snapshot(member(1, 1n, { inputMuted: true }), member(2)));
|
||||
directory.applySnapshot(snapshot(member(1, 2n), member(3)));
|
||||
assert.deepEqual(directory.getSnapshot()?.clients, [member(1, 2n, { inputMuted: true }), member(2), member(3)]);
|
||||
});
|
||||
|
||||
test("a stale partial snapshot cannot bring back a departed client before an explicit rejoin", () => {
|
||||
const directory = new DirectorySynchronizer();
|
||||
directory.applySnapshot(snapshot(member(1), member(2)));
|
||||
directory.applyClientLeave(2);
|
||||
directory.applySnapshot(snapshot(member(2), member(3)));
|
||||
directory.applyClientUpdated(member(2, 1n, { away: true }));
|
||||
assert.deepEqual(directory.getSnapshot()?.clients.map((client) => client.id), [1, 3]);
|
||||
directory.applyClientEnter(member(2, 2n, { uid: "new-uid" }));
|
||||
assert.deepEqual(directory.getSnapshot()?.clients.find((client) => client.id === 2), member(2, 2n, { uid: "new-uid" }));
|
||||
});
|
||||
|
||||
test("a status refresh enriches current clients without adding clients or restoring departures", () => {
|
||||
const directory = new DirectorySynchronizer();
|
||||
directory.applySnapshot(snapshot(member(1), member(2)));
|
||||
directory.applyClientLeave(2);
|
||||
directory.applyClientListSnapshot([
|
||||
member(1, 1n, { away: true, inputMuted: true, outputMuted: false }),
|
||||
member(2, 1n, { away: false, inputMuted: false }),
|
||||
member(3, 1n, { inputMuted: true }),
|
||||
]);
|
||||
assert.deepEqual(directory.getSnapshot()?.clients, [
|
||||
member(1, 1n, { away: true, inputMuted: true, outputMuted: false }),
|
||||
]);
|
||||
});
|
||||
|
||||
test("a status snapshot received before the welcome directory is merged after queued enter and leave events", () => {
|
||||
const directory = new DirectorySynchronizer();
|
||||
directory.applyClientEnter(member(3));
|
||||
directory.applyClientLeave(2);
|
||||
directory.applyClientListSnapshot([member(2, 1n, { inputMuted: true }), member(3, 1n, { inputMuted: true })]);
|
||||
directory.applySnapshot(snapshot(member(1), member(2)));
|
||||
assert.deepEqual(directory.getSnapshot()?.clients, [
|
||||
member(1),
|
||||
member(3, 1n, { inputMuted: true }),
|
||||
]);
|
||||
});
|
||||
|
||||
test("clearing the directory drops pending events and departure history for a new connection", () => {
|
||||
const directory = new DirectorySynchronizer();
|
||||
directory.applyClientLeave(1);
|
||||
directory.applyClientEnter(member(2));
|
||||
directory.clear();
|
||||
directory.applySnapshot(snapshot(member(1)));
|
||||
directory.applyClientLeave(1);
|
||||
directory.clear();
|
||||
assert.equal(directory.ready, false);
|
||||
directory.applySnapshot(snapshot(member(1)));
|
||||
const exposed = directory.getSnapshot()!;
|
||||
assert.deepEqual(exposed.clients, [member(1)]);
|
||||
exposed.clients.pop();
|
||||
exposed.channels.pop();
|
||||
assert.equal(directory.getSnapshot()?.clients.length, 1);
|
||||
assert.equal(directory.getSnapshot()?.channels.length, 1);
|
||||
});
|
||||
@@ -1,10 +1,12 @@
|
||||
import type { ClientInfo } from "@echosixhiya/teamspeak-client";
|
||||
import type { ClientInfo, DirectoryClientInfo } from "@echosixhiya/teamspeak-client";
|
||||
import type { TSDirectorySnapshot } from "./ts-client.js";
|
||||
|
||||
type DirectoryDelta =
|
||||
| { type: "clientEnter"; info: ClientInfo }
|
||||
| { type: "clientLeave"; id: number }
|
||||
| { type: "clientMoved"; id: number; channelID: bigint };
|
||||
| { type: "clientMoved"; id: number; channelID: bigint }
|
||||
| { type: "clientUpdated"; info: DirectoryClientInfo }
|
||||
| { type: "clientListSnapshot"; clients: DirectoryClientInfo[] };
|
||||
|
||||
/**
|
||||
* Merges staged welcome snapshots with events received while the snapshot is
|
||||
@@ -14,7 +16,10 @@ type DirectoryDelta =
|
||||
*/
|
||||
export class DirectorySynchronizer {
|
||||
private snapshot: TSDirectorySnapshot | null = null;
|
||||
private clients = new Map<number, ClientInfo>();
|
||||
private clients = new Map<number, DirectoryClientInfo>();
|
||||
// A delayed welcome snapshot or update must not undo an explicit leave.
|
||||
// Client IDs can be reused, so a new enter event releases the tombstone.
|
||||
private departedClientIds = new Set<number>();
|
||||
private pending: DirectoryDelta[] = [];
|
||||
|
||||
get ready(): boolean {
|
||||
@@ -24,6 +29,7 @@ export class DirectorySynchronizer {
|
||||
applySnapshot(snapshot: TSDirectorySnapshot): void {
|
||||
this.snapshot = { channels: snapshot.channels.slice(), clients: [] };
|
||||
for (const client of snapshot.clients) {
|
||||
if (this.departedClientIds.has(client.id)) continue;
|
||||
const previous = this.clients.get(client.id);
|
||||
this.clients.set(client.id, previous ? { ...previous, ...client } : client);
|
||||
}
|
||||
@@ -43,6 +49,14 @@ export class DirectorySynchronizer {
|
||||
this.applyOrQueue({ type: "clientMoved", id, channelID });
|
||||
}
|
||||
|
||||
applyClientUpdated(info: DirectoryClientInfo): void {
|
||||
this.applyOrQueue({ type: "clientUpdated", info });
|
||||
}
|
||||
|
||||
applyClientListSnapshot(clients: DirectoryClientInfo[]): void {
|
||||
this.applyOrQueue({ type: "clientListSnapshot", clients });
|
||||
}
|
||||
|
||||
getSnapshot(): TSDirectorySnapshot | null {
|
||||
if (!this.snapshot) return null;
|
||||
return {
|
||||
@@ -54,6 +68,7 @@ export class DirectorySynchronizer {
|
||||
clear(): void {
|
||||
this.snapshot = null;
|
||||
this.clients.clear();
|
||||
this.departedClientIds.clear();
|
||||
this.pending = [];
|
||||
}
|
||||
|
||||
@@ -67,13 +82,30 @@ export class DirectorySynchronizer {
|
||||
|
||||
private applyDelta(delta: DirectoryDelta): void {
|
||||
if (delta.type === "clientEnter") {
|
||||
this.departedClientIds.delete(delta.info.id);
|
||||
this.clients.set(delta.info.id, delta.info);
|
||||
return;
|
||||
}
|
||||
if (delta.type === "clientLeave") {
|
||||
this.departedClientIds.add(delta.id);
|
||||
this.clients.delete(delta.id);
|
||||
return;
|
||||
}
|
||||
if (delta.type === "clientUpdated") {
|
||||
if (this.departedClientIds.has(delta.info.id)) return;
|
||||
const current = this.clients.get(delta.info.id);
|
||||
this.clients.set(delta.info.id, current ? { ...current, ...delta.info } : delta.info);
|
||||
return;
|
||||
}
|
||||
if (delta.type === "clientListSnapshot") {
|
||||
for (const info of delta.clients) {
|
||||
const current = this.clients.get(info.id);
|
||||
// A refresh enriches known members; it must not resurrect someone who
|
||||
// left while the asynchronous list request was in flight.
|
||||
if (current && !this.departedClientIds.has(info.id)) this.clients.set(info.id, { ...current, ...info });
|
||||
}
|
||||
return;
|
||||
}
|
||||
const current = this.clients.get(delta.id);
|
||||
if (current) this.clients.set(delta.id, { ...current, channelID: delta.channelID });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { TSDirectorySnapshot } from "./ts-client.js";
|
||||
import { mapChannelTree, normalizeDirectorySnapshot } from "./directory-view.js";
|
||||
import { parseServerMessage } from "../shared/server-messages.js";
|
||||
|
||||
const directory = (): TSDirectorySnapshot => ({
|
||||
channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Lobby", description: "" }, { id: 18446744073709551615n, parentID: 1n, order: 1n, name: "Room", description: "" }],
|
||||
clients: [{ id: 2, channelID: 1n, nickname: "Member", uid: "uid-2", type: 0, serverGroups: [], away: true, inputMuted: true }],
|
||||
});
|
||||
|
||||
test("self restoration uses the connected channel before a snapshot or requested channel", () => {
|
||||
const source = directory();
|
||||
const result = normalizeDirectorySnapshot(source, 2, 18446744073709551615n, "Self", "Lobby");
|
||||
assert.equal(result.clients[0]?.channelID, 18446744073709551615n);
|
||||
assert.equal(result.clients[0]?.uid, "uid-2");
|
||||
assert.equal(source.clients[0]?.channelID, 1n);
|
||||
assert.equal(normalizeDirectorySnapshot(source, 0, 1n, "Unknown"), source);
|
||||
});
|
||||
|
||||
test("partial welcome data can restore self by channel name without duplicating existing members", () => {
|
||||
const source = directory();
|
||||
const result = normalizeDirectorySnapshot(source, 3, 0n, "Self", " room ");
|
||||
assert.equal(result.clients.length, 2);
|
||||
assert.equal(result.clients[1]?.channelID, 18446744073709551615n);
|
||||
assert.equal(normalizeDirectorySnapshot(result, 3, 0n, "Self").clients.length, 2);
|
||||
assert.equal(source.clients.length, 1);
|
||||
});
|
||||
|
||||
test("directory presentation survives JSON transport with large IDs, member flags and cached avatars", () => {
|
||||
const source = directory();
|
||||
const channels = mapChannelTree(source, new Map([["uid-2", "data:image/png;base64,test"]]));
|
||||
const decoded = parseServerMessage(JSON.parse(JSON.stringify({ type: "channelList", channels })));
|
||||
assert.ok(decoded?.type === "channelList");
|
||||
assert.equal(decoded.channels[1]?.id, "18446744073709551615");
|
||||
assert.equal(decoded.channels[0]?.members?.[0]?.inputMuted, true);
|
||||
assert.equal(decoded.channels[0]?.members?.[0]?.away, true);
|
||||
assert.equal(decoded.channels[0]?.members?.[0]?.avatar, "data:image/png;base64,test");
|
||||
assert.deepEqual(decoded.channels[1]?.members, []);
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { ChannelInfo } from "../shared/voice-models.js";
|
||||
import type { TSDirectorySnapshot } from "./ts-client.js";
|
||||
|
||||
export function mapChannelTree(snapshot: TSDirectorySnapshot, avatarCache = new Map<string, string | null>()): ChannelInfo[] {
|
||||
return snapshot.channels.map((channel) => ({
|
||||
id: String(channel.id),
|
||||
parentID: String(channel.parentID),
|
||||
order: String(channel.order),
|
||||
name: channel.name || "未命名频道",
|
||||
description: channel.description || "",
|
||||
members: snapshot.clients
|
||||
.filter((client) => client.channelID === channel.id)
|
||||
.map((client) => {
|
||||
const avatar = client.uid ? avatarCache.get(client.uid) : undefined;
|
||||
return {
|
||||
id: client.id,
|
||||
nickname: client.nickname || "未知用户",
|
||||
uid: client.uid,
|
||||
...(avatar ? { avatar } : {}),
|
||||
away: client.away,
|
||||
awayMessage: client.awayMessage,
|
||||
inputMuted: client.inputMuted,
|
||||
outputMuted: client.outputMuted,
|
||||
channelCommander: client.channelCommander,
|
||||
};
|
||||
}),
|
||||
}));
|
||||
}
|
||||
|
||||
export function avatarDataUrl(data: Buffer): string | null {
|
||||
if (data.length >= 8 && data.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return `data:image/png;base64,${data.toString("base64")}`;
|
||||
if (data.length >= 3 && data.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff]))) return `data:image/jpeg;base64,${data.toString("base64")}`;
|
||||
if (data.length >= 6 && (data.subarray(0, 6).toString("ascii") === "GIF87a" || data.subarray(0, 6).toString("ascii") === "GIF89a")) return `data:image/gif;base64,${data.toString("base64")}`;
|
||||
if (data.length >= 12 && data.subarray(0, 4).toString("ascii") === "RIFF" && data.subarray(8, 12).toString("ascii") === "WEBP") return `data:image/webp;base64,${data.toString("base64")}`;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function normalizeDirectorySnapshot(
|
||||
snapshot: TSDirectorySnapshot,
|
||||
selfId: number,
|
||||
selfChannelId: bigint,
|
||||
nickname: string,
|
||||
requestedChannelName?: string,
|
||||
): TSDirectorySnapshot {
|
||||
if (selfId <= 0) return snapshot;
|
||||
|
||||
const clients = snapshot.clients.slice();
|
||||
const selfIndex = clients.findIndex((client) => client.id === selfId);
|
||||
const snapshotChannelId = selfIndex >= 0 ? clients[selfIndex]!.channelID : 0n;
|
||||
const requestedName = requestedChannelName?.trim().toLocaleLowerCase();
|
||||
const requestedChannel = requestedName
|
||||
? snapshot.channels.find((channel) => channel.name.trim().toLocaleLowerCase() === requestedName)
|
||||
: undefined;
|
||||
const resolvedChannelId = selfChannelId !== 0n
|
||||
? selfChannelId
|
||||
: snapshotChannelId !== 0n
|
||||
? snapshotChannelId
|
||||
: requestedChannel?.id ?? snapshot.channels[0]?.id ?? 0n;
|
||||
if (selfIndex >= 0) {
|
||||
const current = clients[selfIndex]!;
|
||||
if (resolvedChannelId !== 0n) clients[selfIndex] = { ...current, channelID: resolvedChannelId };
|
||||
} else if (resolvedChannelId !== 0n) {
|
||||
clients.push({ id: selfId, nickname, uid: "", channelID: resolvedChannelId, type: 1, serverGroups: [] });
|
||||
}
|
||||
|
||||
return { ...snapshot, clients };
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { IdentityLeaseStore } from "./identity-lease.js";
|
||||
|
||||
test("an identity lease rejects another session until its owner disconnects", () => {
|
||||
const leases = new IdentityLeaseStore();
|
||||
const key = "voice.example.com:9987|identity-1";
|
||||
assert.equal(leases.acquire(key, "session-a"), true);
|
||||
assert.equal(leases.acquire(key, "session-a"), true);
|
||||
assert.equal(leases.acquire(key, "session-b"), false);
|
||||
leases.release(key, "session-b");
|
||||
assert.equal(leases.acquire(key, "session-b"), false);
|
||||
leases.release(key, "session-a");
|
||||
assert.equal(leases.acquire(key, "session-b"), true);
|
||||
leases.release(key, "session-a");
|
||||
assert.equal(leases.acquire(key, "session-c"), false);
|
||||
});
|
||||
|
||||
test("distinct target or identity keys can be leased independently", () => {
|
||||
const leases = new IdentityLeaseStore();
|
||||
assert.equal(leases.acquire("one.example.com|identity-1", "a"), true);
|
||||
assert.equal(leases.acquire("two.example.com|identity-1", "b"), true);
|
||||
assert.equal(leases.acquire("one.example.com|identity-2", "c"), true);
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { JoinTicketStore, type JoinTicketPayload } from "./join-ticket.js";
|
||||
|
||||
const payload: JoinTicketPayload = {
|
||||
target: { host: "voice.example.com", port: 9987 },
|
||||
serverPassword: "test-password",
|
||||
nickname: "Visitor",
|
||||
channel: "Lobby",
|
||||
identity: "test-identity",
|
||||
rememberIdentity: true,
|
||||
accelerated: true,
|
||||
accelerationRelayId: "relay-1",
|
||||
};
|
||||
|
||||
test("join tickets preserve connection options and can only be consumed once", () => {
|
||||
const tickets = new JoinTicketStore();
|
||||
const token = tickets.create(payload, 1_000);
|
||||
assert.deepEqual(tickets.consume(token, 1_001), payload);
|
||||
assert.equal(tickets.consume(token, 1_002), null);
|
||||
assert.equal(tickets.consume("unknown-ticket", 1_002), null);
|
||||
});
|
||||
|
||||
test("join tickets expire at their deadline even if no new ticket was created", () => {
|
||||
const tickets = new JoinTicketStore(100);
|
||||
const valid = tickets.create(payload, 1_000);
|
||||
const expired = tickets.create(payload, 1_000);
|
||||
assert.deepEqual(tickets.consume(valid, 1_099), payload);
|
||||
assert.equal(tickets.consume(expired, 1_100), null);
|
||||
assert.equal(tickets.consume(expired, 1_101), null);
|
||||
});
|
||||
|
||||
test("ticket capacity evicts the oldest request while keeping newer joins usable", () => {
|
||||
const tickets = new JoinTicketStore(100, 2);
|
||||
const oldest = tickets.create(payload, 0);
|
||||
const second = tickets.create({ ...payload, nickname: "Second" }, 1);
|
||||
const newest = tickets.create({ ...payload, nickname: "Newest" }, 2);
|
||||
assert.equal(tickets.consume(oldest, 3), null);
|
||||
assert.equal(tickets.consume(second, 3)?.nickname, "Second");
|
||||
assert.equal(tickets.consume(newest, 3)?.nickname, "Newest");
|
||||
});
|
||||
|
||||
test("expired tickets do not evict a still-valid join when capacity is reclaimed", () => {
|
||||
const tickets = new JoinTicketStore(100, 2);
|
||||
const expired = tickets.create(payload, 0);
|
||||
const live = tickets.create(payload, 90);
|
||||
const latest = tickets.create(payload, 100);
|
||||
assert.equal(tickets.consume(expired, 100), null);
|
||||
assert.deepEqual(tickets.consume(live, 100), payload);
|
||||
assert.deepEqual(tickets.consume(latest, 100), payload);
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import { MemberAvatarLoader } from "./member-avatars.js";
|
||||
import type { TSClientAvatar } from "./ts-client.js";
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: Error) => void;
|
||||
const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no; });
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
const avatar = (value: string): TSClientAvatar => ({ cacheKey: value, data: Buffer.from(`GIF89a${value}`) });
|
||||
const dataUrl = (value: string) => `data:image/gif;base64,${avatar(value).data.toString("base64")}`;
|
||||
|
||||
function fixture(t: TestContext) {
|
||||
t.mock.timers.enable({ apis: ["setTimeout"] });
|
||||
const members = new Map<number, { id: number; uid: string; avatar?: string }>();
|
||||
const cache = new Map<string, string | null>();
|
||||
const calls: number[] = [];
|
||||
const published: Array<{ id: number; uid: string; avatar: string }> = [];
|
||||
const errors: unknown[] = [];
|
||||
const state = { current: true, load: async (_id: number, uid: string): Promise<TSClientAvatar | null> => avatar(uid) };
|
||||
const loader = new MemberAvatarLoader({
|
||||
members, cache, isCurrent: () => state.current,
|
||||
load: (id, uid) => { calls.push(id); return state.load(id, uid); },
|
||||
publish: (id, uid, image) => published.push({ id, uid, avatar: image }),
|
||||
onError: (_id, _uid, error) => errors.push(error),
|
||||
});
|
||||
const add = (id: number, uid = `user-${id}`) => { members.set(id, { id, uid }); };
|
||||
const tick = async (ms = 0) => { t.mock.timers.tick(ms); await nextTurn(); };
|
||||
t.after(() => loader.close());
|
||||
return { loader, members, cache, calls, published, errors, state, add, tick };
|
||||
}
|
||||
|
||||
test("avatar batches deduplicate identities and contain optional download failures", async t => {
|
||||
const f = fixture(t);
|
||||
f.add(1); f.add(2, "user-1"); f.add(3); f.add(4); f.add(5, ""); f.add(6);
|
||||
f.cache.set("user-6", null);
|
||||
f.state.load = async id => {
|
||||
if (id === 3) return { cacheKey: "invalid", data: Buffer.from("not an image") };
|
||||
if (id === 4) throw new Error("Permission denied");
|
||||
return avatar("one");
|
||||
};
|
||||
f.loader.schedule(); f.loader.schedule();
|
||||
await f.tick();
|
||||
assert.deepEqual(f.calls, [2, 3, 4]);
|
||||
assert.deepEqual(f.published, [1, 2].map(id => ({ id, uid: "user-1", avatar: dataUrl("one") })));
|
||||
assert.equal(f.members.get(1)?.avatar, dataUrl("one"));
|
||||
assert.equal(f.members.get(2)?.avatar, dataUrl("one"));
|
||||
assert.equal(f.cache.get("user-3"), null);
|
||||
assert.equal(f.cache.get("user-4"), null);
|
||||
assert.equal(f.errors.length, 1);
|
||||
f.loader.schedule(); await f.tick();
|
||||
assert.equal(f.calls.length, 3, "known absent/denied avatars must not cause a retry loop");
|
||||
});
|
||||
|
||||
for (const outcome of ["success", "failure"] as const) {
|
||||
test(`a late old avatar ${outcome} cannot cache data or unlock a newer batch`, async t => {
|
||||
const f = fixture(t);
|
||||
f.add(1);
|
||||
const old = deferred<TSClientAvatar | null>();
|
||||
const fresh = deferred<TSClientAvatar | null>();
|
||||
f.state.load = () => old.promise;
|
||||
f.loader.schedule(); await f.tick();
|
||||
f.loader.reset();
|
||||
f.state.load = () => fresh.promise;
|
||||
f.loader.schedule(); await f.tick();
|
||||
if (outcome === "success") old.resolve(avatar("old"));
|
||||
else old.reject(new Error("Old connection failed"));
|
||||
await nextTurn();
|
||||
assert.equal(f.cache.size, 0);
|
||||
assert.equal(f.errors.length, 0);
|
||||
f.loader.schedule(); await f.tick(250);
|
||||
assert.deepEqual(f.calls, [1, 1], "the newer pending batch must still own the work");
|
||||
fresh.resolve(avatar("fresh")); await nextTurn();
|
||||
assert.equal(f.cache.get("user-1"), dataUrl("fresh"));
|
||||
assert.deepEqual(f.published, [{ id: 1, uid: "user-1", avatar: dataUrl("fresh") }]);
|
||||
});
|
||||
}
|
||||
|
||||
test("closing a scheduled avatar loader clears its timer, cache and future work", async t => {
|
||||
const f = fixture(t);
|
||||
f.add(1); f.cache.set("other", dataUrl("other"));
|
||||
f.loader.schedule(100);
|
||||
f.loader.close(); f.loader.close();
|
||||
f.loader.schedule(); await f.tick(1_000);
|
||||
assert.equal(f.calls.length, 0);
|
||||
assert.equal(f.cache.size, 0);
|
||||
});
|
||||
|
||||
test("client ID reuse cannot attach a departed member's avatar to its replacement", async t => {
|
||||
const f = fixture(t);
|
||||
f.add(1, "departed");
|
||||
const pending = deferred<TSClientAvatar | null>();
|
||||
f.state.load = () => pending.promise;
|
||||
f.loader.schedule(); await f.tick();
|
||||
f.add(1, "replacement");
|
||||
pending.resolve(avatar("old")); await nextTurn();
|
||||
assert.equal(f.cache.size, 0);
|
||||
assert.equal(f.published.length, 0);
|
||||
f.state.load = async () => avatar("new");
|
||||
await f.tick(250);
|
||||
assert.equal(f.members.get(1)?.avatar, dataUrl("new"));
|
||||
assert.deepEqual(f.published.map(message => message.uid), ["replacement"]);
|
||||
});
|
||||
|
||||
test("avatar work keeps a 50-member batch and cancels the delayed remainder on close", async t => {
|
||||
const f = fixture(t);
|
||||
for (let id = 1; id <= 55; id++) f.add(id);
|
||||
f.loader.schedule(); await f.tick();
|
||||
assert.equal(f.calls.length, 50);
|
||||
await f.tick(249);
|
||||
assert.equal(f.calls.length, 50);
|
||||
await f.tick(1);
|
||||
assert.equal(f.calls.length, 55);
|
||||
f.add(56); f.loader.schedule(250); f.loader.close();
|
||||
await f.tick(250);
|
||||
assert.equal(f.calls.length, 55);
|
||||
});
|
||||
|
||||
test("members arriving during an active batch are scheduled without overlapping downloads", async t => {
|
||||
const f = fixture(t);
|
||||
const pending = deferred<TSClientAvatar | null>();
|
||||
f.add(1);
|
||||
f.state.load = () => pending.promise;
|
||||
f.loader.schedule(); await f.tick();
|
||||
f.add(2); f.loader.schedule(); await f.tick();
|
||||
assert.deepEqual(f.calls, [1]);
|
||||
f.state.load = async () => avatar("second");
|
||||
pending.resolve(avatar("first")); await nextTurn();
|
||||
await f.tick(250);
|
||||
assert.deepEqual(f.calls, [1, 2]);
|
||||
assert.deepEqual(f.published.map(message => message.id), [1, 2]);
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import { avatarDataUrl } from "./directory-view.js";
|
||||
import type { TSClientAvatar } from "./ts-client.js";
|
||||
|
||||
interface AvatarMember {
|
||||
id: number;
|
||||
uid: string;
|
||||
avatar?: string;
|
||||
}
|
||||
|
||||
export interface MemberAvatarOptions {
|
||||
members: ReadonlyMap<number, AvatarMember>;
|
||||
cache: Map<string, string | null>;
|
||||
isCurrent(): boolean;
|
||||
load(id: number, uid: string): Promise<TSClientAvatar | null>;
|
||||
publish(id: number, uid: string, avatar: string): void;
|
||||
onError(id: number, uid: string, error: unknown): void;
|
||||
}
|
||||
|
||||
/** Optional SDK downloads belong to one connected directory generation. */
|
||||
export class MemberAvatarLoader {
|
||||
private timer: ReturnType<typeof setTimeout> | null = null;
|
||||
private batch: symbol | null = null;
|
||||
private closed = false;
|
||||
|
||||
constructor(private readonly options: MemberAvatarOptions) {}
|
||||
|
||||
private isCurrent(): boolean {
|
||||
return !this.closed && this.options.isCurrent();
|
||||
}
|
||||
|
||||
private pendingMembers(): AvatarMember[] {
|
||||
const byUid = new Map<string, AvatarMember>();
|
||||
for (const member of this.options.members.values()) {
|
||||
if (member.uid && !this.options.cache.has(member.uid)) byUid.set(member.uid, member);
|
||||
}
|
||||
return [...byUid.values()];
|
||||
}
|
||||
|
||||
schedule(delayMs = 0): void {
|
||||
if (!this.isCurrent() || this.timer !== null || this.batch !== null) return;
|
||||
this.timer = setTimeout(() => {
|
||||
this.timer = null;
|
||||
void this.refresh();
|
||||
}, delayMs);
|
||||
this.timer.unref?.();
|
||||
}
|
||||
|
||||
private async refresh(): Promise<void> {
|
||||
if (!this.isCurrent() || this.batch !== null) return;
|
||||
const batch = Symbol("avatar batch");
|
||||
this.batch = batch;
|
||||
const isCurrent = () => this.batch === batch && this.isCurrent();
|
||||
try {
|
||||
// Keep SDK file transfers sequential and retain the existing batch limit.
|
||||
for (const member of this.pendingMembers().slice(0, 50)) {
|
||||
if (!isCurrent()) return;
|
||||
if (this.options.members.get(member.id)?.uid !== member.uid) continue;
|
||||
try {
|
||||
const loaded = await this.options.load(member.id, member.uid);
|
||||
if (!isCurrent()) return;
|
||||
const current = this.options.members.get(member.id);
|
||||
if (current?.uid !== member.uid) continue;
|
||||
const avatar = loaded ? avatarDataUrl(loaded.data) : null;
|
||||
this.options.cache.set(member.uid, avatar);
|
||||
if (avatar) {
|
||||
for (const candidate of this.options.members.values()) {
|
||||
if (candidate.uid !== member.uid) continue;
|
||||
candidate.avatar = avatar;
|
||||
this.options.publish(candidate.id, candidate.uid, avatar);
|
||||
}
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
if (!isCurrent()) return;
|
||||
if (this.options.members.get(member.id)?.uid !== member.uid) continue;
|
||||
// Permission and file-transfer failures are optional, not join errors.
|
||||
this.options.cache.set(member.uid, null);
|
||||
this.options.onError(member.id, member.uid, error);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
// A late old batch must not clear a newer generation's running work.
|
||||
if (this.batch === batch) {
|
||||
this.batch = null;
|
||||
if (this.isCurrent() && this.pendingMembers().length) this.schedule(250);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
if (this.timer !== null) clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
this.batch = null;
|
||||
this.options.cache.clear();
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
this.reset();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { createRequire } from "node:module";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
type NativeCodec = {
|
||||
encode(pcm: Buffer): Buffer;
|
||||
decode(data: Buffer): Buffer;
|
||||
};
|
||||
|
||||
type ScriptCodec = {
|
||||
encode(pcm: Buffer, frameSize: number): Buffer | Uint8Array;
|
||||
decode(data: Buffer): Buffer | Uint8Array;
|
||||
delete(): void;
|
||||
};
|
||||
|
||||
type OpusScriptModule = {
|
||||
new (sampleRate: number, channels: number, application: number): ScriptCodec;
|
||||
Application: { AUDIO: number };
|
||||
};
|
||||
|
||||
/** Keep the existing native codec on servers; the Android bundle uses the WASM codec. */
|
||||
export class OpusEncoder {
|
||||
private readonly codec: NativeCodec | ScriptCodec;
|
||||
private readonly channels: number;
|
||||
private readonly mobile: boolean;
|
||||
|
||||
constructor(sampleRate: number, channels: number) {
|
||||
this.channels = channels;
|
||||
this.mobile = process.env.WEBSPEAK_MOBILE === "1";
|
||||
if (this.mobile) {
|
||||
const OpusScript = require("opusscript") as OpusScriptModule;
|
||||
this.codec = new OpusScript(sampleRate, channels, OpusScript.Application.AUDIO);
|
||||
} else {
|
||||
const { OpusEncoder: NativeOpusEncoder } = require("@discordjs/opus") as {
|
||||
OpusEncoder: new (rate: number, channelCount: number) => NativeCodec;
|
||||
};
|
||||
this.codec = new NativeOpusEncoder(sampleRate, channels);
|
||||
}
|
||||
}
|
||||
|
||||
encode(pcm: Buffer): Buffer {
|
||||
const encoded = this.mobile
|
||||
? (this.codec as ScriptCodec).encode(pcm, pcm.length / (2 * this.channels))
|
||||
: (this.codec as NativeCodec).encode(pcm);
|
||||
return Buffer.isBuffer(encoded) ? encoded : Buffer.from(encoded);
|
||||
}
|
||||
|
||||
decode(data: Buffer): Buffer {
|
||||
const decoded = this.codec.decode(data);
|
||||
return Buffer.isBuffer(decoded) ? decoded : Buffer.from(decoded);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.mobile) (this.codec as ScriptCodec).delete();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { WebSpeakError } from "../errors.js";
|
||||
import { isRecoverable, reconnectDelayMs, reconnectWindowOpen, RECONNECT_WINDOW_MS } from "./reconnect-policy.js";
|
||||
|
||||
test("reconnect backoff has bounded jitter and stops growing for repeated failures", () => {
|
||||
assert.equal(reconnectDelayMs(1, () => 0), 900);
|
||||
assert.equal(reconnectDelayMs(1, () => 1), 1_100);
|
||||
assert.equal(reconnectDelayMs(2, () => 0.5), 2_000);
|
||||
assert.equal(reconnectDelayMs(100, () => 0), 27_000);
|
||||
assert.equal(reconnectDelayMs(100, () => 1), 33_000);
|
||||
assert.equal(reconnectDelayMs(0, () => 0.5), 1_000);
|
||||
});
|
||||
|
||||
test("reconnect attempts stop exactly at the recovery window deadline", () => {
|
||||
const interruptedAt = 1_000;
|
||||
assert.equal(reconnectWindowOpen(interruptedAt, interruptedAt), true);
|
||||
assert.equal(reconnectWindowOpen(interruptedAt, interruptedAt + RECONNECT_WINDOW_MS - 1), true);
|
||||
assert.equal(reconnectWindowOpen(interruptedAt, interruptedAt + RECONNECT_WINDOW_MS), false);
|
||||
assert.equal(reconnectWindowOpen(interruptedAt, interruptedAt + RECONNECT_WINDOW_MS + 1), false);
|
||||
});
|
||||
|
||||
test("retry policy respects terminal errors while allowing transient and unclassified disconnects", () => {
|
||||
assert.equal(isRecoverable(new WebSpeakError("timeout", "timed out", true)), true);
|
||||
assert.equal(isRecoverable(new WebSpeakError("authentication_failed", "wrong password", false)), false);
|
||||
assert.equal(isRecoverable(new WebSpeakError("banned", "banned", false)), false);
|
||||
assert.equal(isRecoverable(null), true);
|
||||
});
|
||||
@@ -0,0 +1,359 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import { ScreenShareCoordinator, type ScreenShareParticipant } from "./screen-share-coordinator.js";
|
||||
import { parseServerMessage, type ServerMessage } from "../shared/server-messages.js";
|
||||
import type { ScreenShareClientMessage } from "../shared/screen-share.js";
|
||||
|
||||
function fixture() {
|
||||
const entries = new Map<string, ScreenShareParticipant>();
|
||||
const messages: Array<{ to: string; message: ServerMessage }> = [];
|
||||
const commands: Array<{ from: string; command: string }> = [];
|
||||
const send = (to: string, message: ServerMessage) => {
|
||||
assert.ok(parseServerMessage(JSON.parse(JSON.stringify(message))), `invalid message: ${message.type}`);
|
||||
messages.push({ to, message });
|
||||
};
|
||||
const coordinator = new ScreenShareCoordinator(entries, send, { debug() {}, warn() {} });
|
||||
function participant(id: string, clientId: number, channel = 1n, host = "first.example") {
|
||||
const entry: ScreenShareParticipant = {
|
||||
id, nickname: id, screenPeerId: `peer-${id}`, target: { host, port: 9987 }, members: new Map([[clientId, {}]]),
|
||||
channelTree: [{ id: String(channel), parentID: "0", name: "Room", members: [{ id: clientId, nickname: id }] }],
|
||||
tsClient: {
|
||||
getClientId: () => clientId, getChannelId: () => channel, isConnected: () => true,
|
||||
sendProtocolCommand: async command => { commands.push({ from: id, command }); },
|
||||
},
|
||||
};
|
||||
entries.set(id, entry);
|
||||
return entry;
|
||||
}
|
||||
function handle(entry: ScreenShareParticipant, command: ScreenShareClientMessage) {
|
||||
coordinator.handleMessage(entry, command, message => send(entry.id, message));
|
||||
}
|
||||
function list(entry: ScreenShareParticipant) {
|
||||
handle(entry, { type: "screenShareList" });
|
||||
const message = messages.at(-1)?.message;
|
||||
assert.ok(message?.type === "screenShareList");
|
||||
return message.streams;
|
||||
}
|
||||
function start(entry: ScreenShareParticipant) {
|
||||
handle(entry, { type: "screenShareStart", requestId: "start", name: "Screen", audio: false });
|
||||
const share = list(entry)[0];
|
||||
assert.ok(share);
|
||||
return share.streamId;
|
||||
}
|
||||
return { entries, messages, commands, coordinator, participant, handle, list, start };
|
||||
}
|
||||
|
||||
test("sharing is isolated by server and channel, and only its owner can stop it", () => {
|
||||
const f = fixture();
|
||||
const owner = f.participant("owner", 1);
|
||||
const viewer = f.participant("viewer", 2);
|
||||
const otherChannel = f.participant("other-channel", 3, 2n);
|
||||
const otherServer = f.participant("other-server", 1, 1n, "second.example");
|
||||
const streamId = f.start(owner);
|
||||
assert.equal(f.messages.some(({ to }) => to === otherChannel.id || to === otherServer.id), false);
|
||||
for (const [entry, code] of [[otherServer, "SCREEN_SHARE_NOT_FOUND"], [otherChannel, "SCREEN_SHARE_TARGET_MISMATCH"]] as const) {
|
||||
f.handle(entry, { type: "screenShareJoin", streamId });
|
||||
const reply = f.messages.at(-1)?.message;
|
||||
assert.ok(reply?.type === "screenShareError");
|
||||
assert.equal(reply.code, code);
|
||||
}
|
||||
f.handle(viewer, { type: "screenShareStop", streamId });
|
||||
assert.equal(f.list(owner).length, 1);
|
||||
f.handle(owner, { type: "screenShareStop", streamId });
|
||||
assert.equal(f.list(owner).length, 0);
|
||||
});
|
||||
|
||||
test("signaling permits owner-viewer pairs but rejects viewer-to-viewer injection", () => {
|
||||
const f = fixture();
|
||||
const owner = f.participant("owner", 1);
|
||||
const left = f.participant("left", 2);
|
||||
const right = f.participant("right", 3);
|
||||
const streamId = f.start(owner);
|
||||
for (const viewer of [left, right]) f.handle(viewer, { type: "screenShareJoin", streamId });
|
||||
f.messages.length = 0;
|
||||
f.handle(left, { type: "screenShareSignal", streamId, targetPeerId: right.screenPeerId, signal: { kind: "offer", sdp: "invalid-peer" } });
|
||||
assert.equal(f.messages.some(({ to }) => to === right.id), false);
|
||||
assert.equal(f.messages[0]?.message.type, "screenShareError");
|
||||
f.handle(left, { type: "screenShareSignal", streamId, targetPeerId: owner.screenPeerId, signal: { kind: "offer", sdp: "offer" } });
|
||||
assert.equal(f.messages.at(-1)?.to, owner.id);
|
||||
assert.equal(f.messages.at(-1)?.message.type, "screenShareSignal");
|
||||
});
|
||||
|
||||
test("another member moving channels cannot stop the owner's share or evict its viewer", () => {
|
||||
const f = fixture();
|
||||
const owner = f.participant("owner", 1);
|
||||
const viewer = f.participant("viewer", 2);
|
||||
const streamId = f.start(owner);
|
||||
f.handle(viewer, { type: "screenShareJoin", streamId });
|
||||
f.coordinator.onClientMove(owner, 99, 2n);
|
||||
f.coordinator.onClientMove(viewer, 99, 2n);
|
||||
assert.equal(f.list(owner)[0]?.viewerCount, 1);
|
||||
f.coordinator.onClientMove(viewer, 2, 2n);
|
||||
assert.equal(f.list(owner)[0]?.viewerCount, 0);
|
||||
f.coordinator.onClientMove(owner, 1, 2n);
|
||||
assert.equal(f.list(owner).length, 0);
|
||||
});
|
||||
|
||||
test("native source lookup cannot use another server's colliding client ID", () => {
|
||||
const f = fixture();
|
||||
f.participant("collision", 17, 99n, "second.example");
|
||||
const observer = f.participant("observer", 1);
|
||||
const viewer = f.participant("viewer", 2, 3n);
|
||||
observer.channelTree.push({ id: "3", parentID: "0", name: "Source", members: [{ id: 17, nickname: "Native" }] });
|
||||
f.coordinator.handleNotification(observer, { name: "notifystreamstarted", params: { id: "native", clid: "17", name: "Native" } });
|
||||
assert.equal(f.list(observer).length, 0);
|
||||
assert.equal(f.list(viewer)[0]?.streamId, "native");
|
||||
});
|
||||
|
||||
test("a gateway publisher's repeated native notification cannot create a duplicate stream", () => {
|
||||
const f = fixture();
|
||||
const owner = f.participant("owner", 1);
|
||||
const streamId = f.start(owner);
|
||||
f.coordinator.handleNotification(owner, { name: "notifystreamstarted", params: { id: "native-copy", clid: "1" } });
|
||||
f.coordinator.handleNotification(owner, { name: "notifystreaminfo", params: { id: "native-copy", clid: "1" } });
|
||||
assert.deepEqual(f.list(owner).map(stream => stream.streamId), [streamId]);
|
||||
f.handle(owner, { type: "screenShareStop", streamId });
|
||||
f.coordinator.handleNotification(owner, { name: "notifystreamstarted", params: { id: "late-copy", clid: "1" } });
|
||||
assert.equal(f.list(owner).length, 0);
|
||||
assert.ok(f.commands.some(({ command }) => command.startsWith("stopstream id=late-copy ")));
|
||||
});
|
||||
|
||||
test("native discovery runs again when the last session on a target has left", async () => {
|
||||
const f = fixture();
|
||||
const first = f.participant("first", 1);
|
||||
await f.coordinator.discoverExistingStreams(first);
|
||||
f.coordinator.removePeer(first.id);
|
||||
f.entries.delete(first.id);
|
||||
const second = f.participant("second", 2);
|
||||
await f.coordinator.discoverExistingStreams(second);
|
||||
assert.ok(f.commands.some(({ from, command }) => from === second.id && command === "requeststreaminfo clid=2"));
|
||||
});
|
||||
|
||||
test("a later session rediscovers a previously queried source and announces it only once", async () => {
|
||||
const f = fixture();
|
||||
const first = f.participant("first", 1);
|
||||
first.members = new Map([[17, {}]]);
|
||||
first.channelTree[0]!.members!.push({ id: 17, nickname: "Native" });
|
||||
await f.coordinator.discoverExistingStreams(first);
|
||||
const later = f.participant("later", 2);
|
||||
later.members = first.members;
|
||||
later.channelTree = first.channelTree;
|
||||
let queries = 0;
|
||||
later.tsClient.sendProtocolCommand = async command => {
|
||||
assert.equal(command, "requeststreaminfo clid=17");
|
||||
queries++;
|
||||
f.coordinator.handleNotification(later, { name: "notifystreaminfo", params: { id: "native", clid: "17" } });
|
||||
};
|
||||
await f.coordinator.discoverExistingStreams(later);
|
||||
await f.coordinator.discoverExistingStreams(later);
|
||||
assert.equal(queries, 2);
|
||||
assert.equal(f.list(later)[0]?.streamId, "native");
|
||||
assert.equal(f.messages.filter(({ to, message }) => to === later.id && message.type === "screenShareStarted").length, 1);
|
||||
});
|
||||
|
||||
test("overlapping discovery uses one trailing pass with the latest directory and does not block another server", async () => {
|
||||
const f = fixture();
|
||||
const first = f.participant("first", 1);
|
||||
first.members = new Map([[17, {}]]);
|
||||
let release!: () => void;
|
||||
const blocked = new Promise<void>(resolve => { release = resolve; });
|
||||
let firstQueries = 0;
|
||||
first.tsClient.sendProtocolCommand = async () => { firstQueries++; await blocked; };
|
||||
const running = f.coordinator.discoverExistingStreams(first);
|
||||
await nextTurn();
|
||||
const second = f.participant("second", 2);
|
||||
const latest = f.participant("latest", 3);
|
||||
latest.members = new Map([[17, {}], [18, {}]]);
|
||||
const pending = f.coordinator.discoverExistingStreams(second);
|
||||
const coalesced = f.coordinator.discoverExistingStreams(latest);
|
||||
const other = f.participant("other", 4, 1n, "second.example");
|
||||
await f.coordinator.discoverExistingStreams(other);
|
||||
assert.deepEqual(f.commands, [{ from: "other", command: "requeststreaminfo clid=4" }]);
|
||||
release();
|
||||
await Promise.all([running, pending, coalesced]);
|
||||
assert.equal(firstQueries, 1);
|
||||
assert.deepEqual(f.commands.slice(1), [
|
||||
{ from: "latest", command: "requeststreaminfo clid=17" },
|
||||
{ from: "latest", command: "requeststreaminfo clid=18" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("discovery abandons a removed connection and falls back when its queued session also leaves", async () => {
|
||||
const f = fixture();
|
||||
const first = f.participant("first", 1);
|
||||
first.members = new Map([[17, {}], [18, {}]]);
|
||||
let release!: () => void;
|
||||
let firstQueries = 0;
|
||||
first.tsClient.sendProtocolCommand = async () => {
|
||||
firstQueries++;
|
||||
await new Promise<void>(resolve => { release = resolve; });
|
||||
};
|
||||
const running = f.coordinator.discoverExistingStreams(first);
|
||||
await nextTurn();
|
||||
const leaving = f.participant("leaving", 2);
|
||||
const pending = f.coordinator.discoverExistingStreams(leaving);
|
||||
f.participant("other-server", 3, 1n, "second.example");
|
||||
const survivor = f.participant("survivor", 4);
|
||||
survivor.members = first.members;
|
||||
f.entries.delete(first.id);
|
||||
f.entries.delete(leaving.id);
|
||||
release();
|
||||
await Promise.all([running, pending]);
|
||||
assert.equal(firstQueries, 1);
|
||||
assert.deepEqual(f.commands, [
|
||||
{ from: "survivor", command: "requeststreaminfo clid=17" },
|
||||
{ from: "survivor", command: "requeststreaminfo clid=18" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("a failed native query does not suppress later clients or future discovery passes", async () => {
|
||||
const f = fixture();
|
||||
const entry = f.participant("viewer", 1);
|
||||
entry.members = new Map([[17, {}], [18, {}]]);
|
||||
const queries: string[] = [];
|
||||
entry.tsClient.sendProtocolCommand = async command => {
|
||||
queries.push(command);
|
||||
if (queries.length === 1) throw new Error("query failed");
|
||||
};
|
||||
await f.coordinator.discoverExistingStreams(entry);
|
||||
await f.coordinator.discoverExistingStreams(entry);
|
||||
assert.deepEqual(queries, [17, 18, 17, 18].map(id => `requeststreaminfo clid=${id}`));
|
||||
});
|
||||
|
||||
test("native lookup can use a connected directory on the same server when the observer lacks the source", () => {
|
||||
const f = fixture();
|
||||
const collision = f.participant("collision", 3, 99n, "second.example");
|
||||
collision.channelTree[0]!.members!.push({ id: 17, nickname: "Collision" });
|
||||
const offline = f.participant("offline", 4, 88n);
|
||||
offline.channelTree[0]!.members!.push({ id: 17, nickname: "Stale" });
|
||||
offline.tsClient.isConnected = () => false;
|
||||
const observer = f.participant("observer", 1);
|
||||
const viewer = f.participant("viewer", 2, 2n);
|
||||
viewer.channelTree[0]!.members!.push({ id: 17, nickname: "Native" });
|
||||
f.coordinator.handleNotification(observer, { name: "notifystreaminfo", params: { id: "native", clid: "17" } });
|
||||
assert.deepEqual(f.messages.filter(({ message }) => message.type === "screenShareStarted").map(({ to }) => to), [viewer.id]);
|
||||
assert.equal(f.list(observer).length, 0);
|
||||
assert.equal(f.list(viewer)[0]?.streamId, "native");
|
||||
});
|
||||
|
||||
test("an unknown native source never inherits the observer's channel", () => {
|
||||
const f = fixture();
|
||||
const viewer = f.participant("viewer", 1);
|
||||
const collision = f.participant("collision", 2, 1n, "second.example");
|
||||
collision.channelTree[0]!.members!.push({ id: 17, nickname: "Other source" });
|
||||
f.coordinator.handleNotification(viewer, { name: "notifystreaminfo", params: { id: "native", clid: "17" } });
|
||||
assert.equal(f.list(viewer).length, 0);
|
||||
});
|
||||
|
||||
test("channel correction retires old viewers before announcing the native stream in its current channel", async () => {
|
||||
const f = fixture();
|
||||
const oldViewer = f.participant("old-viewer", 1);
|
||||
oldViewer.channelTree[0]!.members!.push({ id: 17, nickname: "Native" });
|
||||
const newViewer = f.participant("new-viewer", 2, 2n);
|
||||
f.coordinator.handleNotification(oldViewer, { name: "notifystreaminfo", params: { id: "native", clid: "17" } });
|
||||
f.handle(oldViewer, { type: "screenShareJoin", streamId: "native" });
|
||||
assert.equal(f.list(oldViewer)[0]?.viewerCount, 1);
|
||||
await nextTurn();
|
||||
f.messages.length = 0;
|
||||
// A fresh directory corrects the source channel without a clientMoved event.
|
||||
// The observer must take precedence over the first session's stale snapshot.
|
||||
newViewer.channelTree[0]!.members!.push({ id: 17, nickname: "Native" });
|
||||
f.coordinator.handleNotification(newViewer, { name: "notifystreaminfo", params: { id: "native", clid: "17" } });
|
||||
const stopped = f.messages.findIndex(({ to, message }) => to === oldViewer.id && message.type === "screenShareStopped");
|
||||
const started = f.messages.findIndex(({ to, message }) => to === newViewer.id && message.type === "screenShareStarted");
|
||||
assert.ok(stopped >= 0 && started > stopped);
|
||||
assert.ok(f.commands.some(({ from, command }) => from === oldViewer.id && command === "removeclientfromstream id=native clid=1 reason=1"));
|
||||
assert.equal(f.list(oldViewer).length, 0);
|
||||
assert.equal(f.list(newViewer)[0]?.viewerCount, 0);
|
||||
f.messages.length = 0;
|
||||
f.coordinator.handleNotification(oldViewer, { name: "notifyrespondjoinstreamrequest", params: { id: "native", offer: "late-offer" } });
|
||||
assert.equal(f.messages.some(({ message }) => message.type === "screenShareSignal"), false);
|
||||
f.handle(newViewer, { type: "screenShareJoin", streamId: "native" });
|
||||
assert.equal(f.list(newViewer)[0]?.viewerCount, 1);
|
||||
});
|
||||
|
||||
test("owner removal is idempotent and clears the stream from remaining viewers", async () => {
|
||||
const f = fixture();
|
||||
const owner = f.participant("owner", 1);
|
||||
const viewer = f.participant("viewer", 2);
|
||||
const streamId = f.start(owner);
|
||||
f.handle(viewer, { type: "screenShareJoin", streamId });
|
||||
f.messages.length = 0;
|
||||
f.coordinator.removePeer(owner.id);
|
||||
f.coordinator.removePeer(owner.id);
|
||||
await nextTurn();
|
||||
assert.equal(f.messages.filter(({ to, message }) => to === viewer.id && message.type === "screenShareStopped").length, 1);
|
||||
assert.equal(f.list(viewer).length, 0);
|
||||
});
|
||||
|
||||
test("a failed old native join cannot remove a newer membership", async () => {
|
||||
const f = fixture();
|
||||
const viewer = f.participant("viewer", 2);
|
||||
viewer.channelTree[0]!.members!.push({ id: 17, nickname: "Native" });
|
||||
f.coordinator.handleNotification(viewer, { name: "notifystreamstarted", params: { id: "native", clid: "17" } });
|
||||
let rejectOld!: (error: Error) => void;
|
||||
const old = new Promise<void>((_, reject) => { rejectOld = reject; });
|
||||
let joins = 0;
|
||||
viewer.tsClient.sendProtocolCommand = command => command.startsWith("joinstreamrequest") && ++joins === 1 ? old : Promise.resolve();
|
||||
f.handle(viewer, { type: "screenShareJoin", streamId: "native", requestId: "old" });
|
||||
f.handle(viewer, { type: "screenShareLeave", streamId: "native" });
|
||||
f.handle(viewer, { type: "screenShareJoin", streamId: "native", requestId: "new" });
|
||||
rejectOld(new Error("old request failed"));
|
||||
await nextTurn();
|
||||
assert.equal(f.list(viewer)[0]?.viewerCount, 1);
|
||||
assert.equal(f.messages.some(({ message }) => message.type === "screenShareError" && message.requestId === "old"), false);
|
||||
});
|
||||
|
||||
test("leaving a native source includes the removal reason required by TS6", () => {
|
||||
const f = fixture();
|
||||
const viewer = f.participant("viewer", 2);
|
||||
viewer.channelTree[0]!.members!.push({ id: 17, nickname: "Native" });
|
||||
f.coordinator.handleNotification(viewer, { name: "notifystreamstarted", params: { id: "native", clid: "17" } });
|
||||
f.handle(viewer, { type: "screenShareJoin", streamId: "native" });
|
||||
f.handle(viewer, { type: "screenShareLeave", streamId: "native" });
|
||||
assert.ok(f.commands.some(({ command }) => command === "removeclientfromstream id=native clid=2 reason=1"));
|
||||
});
|
||||
|
||||
test("a refused native viewer removal retains membership and reports failure until retry succeeds", async () => {
|
||||
const f = fixture();
|
||||
const owner = f.participant("owner", 1);
|
||||
const streamId = f.start(owner);
|
||||
f.coordinator.handleNotification(owner, { name: "notifystreamstarted", params: { id: "native", clid: "1" } });
|
||||
f.coordinator.handleNotification(owner, { name: "notifyjoinstreamrequest", params: { id: "native", clid: "17" } });
|
||||
let reject!: (error: Error) => void;
|
||||
const denied = new Promise<void>((_, no) => { reject = no; });
|
||||
owner.tsClient.sendProtocolCommand = command => {
|
||||
assert.equal(command, "removeclientfromstream id=native clid=17 reason=1");
|
||||
return denied;
|
||||
};
|
||||
const close: ScreenShareClientMessage = { type: "screenShareSignal", streamId, targetPeerId: "ts-viewer-17", signal: { kind: "close" } };
|
||||
f.handle(owner, close);
|
||||
assert.equal(f.list(owner)[0]?.viewerCount, 1);
|
||||
reject(new Error("denied"));
|
||||
await nextTurn();
|
||||
assert.equal(f.list(owner)[0]?.viewerCount, 1);
|
||||
assert.equal(f.messages.some(({ message }) => message.type === "screenShareViewerLeft"), false);
|
||||
assert.ok(f.messages.some(({ message }) => message.type === "screenShareError" && message.code === "SCREEN_SHARE_SIGNAL_FAILED"));
|
||||
owner.tsClient.sendProtocolCommand = async () => {};
|
||||
f.handle(owner, close);
|
||||
await nextTurn();
|
||||
assert.equal(f.list(owner)[0]?.viewerCount, 0);
|
||||
assert.equal(f.messages.filter(({ message }) => message.type === "screenShareViewerLeft").length, 1);
|
||||
});
|
||||
|
||||
test("native removal notification and acknowledgement publish only one viewer-left event", async () => {
|
||||
const f = fixture();
|
||||
const owner = f.participant("owner", 1);
|
||||
const streamId = f.start(owner);
|
||||
f.coordinator.handleNotification(owner, { name: "notifystreamstarted", params: { id: "native", clid: "1" } });
|
||||
f.coordinator.handleNotification(owner, { name: "notifyjoinstreamrequest", params: { id: "native", clid: "17" } });
|
||||
let resolve!: () => void;
|
||||
owner.tsClient.sendProtocolCommand = () => new Promise<void>(yes => { resolve = yes; });
|
||||
f.handle(owner, { type: "screenShareSignal", streamId, targetPeerId: "ts-viewer-17", signal: { kind: "close" } });
|
||||
f.coordinator.handleNotification(owner, { name: "notifystreamclientleft", params: { id: "native", clid: "17" } });
|
||||
resolve();
|
||||
await nextTurn();
|
||||
assert.equal(f.list(owner)[0]?.viewerCount, 0);
|
||||
assert.equal(f.messages.filter(({ message }) => message.type === "screenShareViewerLeft").length, 1);
|
||||
});
|
||||
@@ -0,0 +1,794 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { TSClient, TSRawNotification } from "./ts-client.js";
|
||||
import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import type { ServerMessage } from "../shared/server-messages.js";
|
||||
import type { ChannelInfo } from "../shared/voice-models.js";
|
||||
import type { ScreenShareClientMessage, ScreenSharePeerSignal, ScreenShareStreamDescription, ScreenShareViewerDescription } from "../shared/screen-share.js";
|
||||
|
||||
export interface ScreenShareParticipant {
|
||||
id: string;
|
||||
screenPeerId: string;
|
||||
nickname: string;
|
||||
target: TeamSpeakTarget;
|
||||
members: ReadonlyMap<number, { avatar?: string }>;
|
||||
channelTree: ChannelInfo[];
|
||||
tsClient: Pick<TSClient, "getClientId" | "getChannelId" | "isConnected" | "sendProtocolCommand">;
|
||||
}
|
||||
|
||||
interface ScreenStreamRecord extends ScreenShareStreamDescription {
|
||||
targetKey: string;
|
||||
channelId: bigint;
|
||||
ownerEntryId: string;
|
||||
viewerEntryIds: Map<string, symbol>;
|
||||
sourceClientId?: number;
|
||||
/** The gateway TS client that publishes a browser-owned stream to TS6. */
|
||||
teamSpeakPublisherEntryId?: string;
|
||||
/** The TS6 stream id paired with a browser-owned WebSpeak stream. */
|
||||
teamSpeakStreamId?: string;
|
||||
/** Native TS6 viewer client ids paired with a browser-owned stream. */
|
||||
nativeViewerClids: Set<number>;
|
||||
}
|
||||
|
||||
// Stream ids are scoped to a TeamSpeak server. Keep the target in the key so
|
||||
// two unrelated servers cannot overwrite each other's native stream record.
|
||||
function screenStreamKey(targetKey: string, streamId: string): string {
|
||||
return `${targetKey}\u0000${streamId}`;
|
||||
}
|
||||
|
||||
/** Coordinates channel-scoped browser/native sharing; media stays peer-to-peer. */
|
||||
export class ScreenShareCoordinator {
|
||||
private readonly screenStreams = new Map<string, ScreenStreamRecord>();
|
||||
private readonly discoveries = new Map<string, {
|
||||
pendingEntry: ScreenShareParticipant | undefined;
|
||||
completion: Promise<void>;
|
||||
}>();
|
||||
|
||||
constructor(
|
||||
private readonly entries: ReadonlyMap<string, ScreenShareParticipant>,
|
||||
private readonly sendToEntry: (entryId: string, message: ServerMessage) => void,
|
||||
private readonly logger: Pick<Logger, "debug" | "warn">,
|
||||
) {}
|
||||
|
||||
handleMessage(
|
||||
entry: ScreenShareParticipant,
|
||||
message: ScreenShareClientMessage,
|
||||
sendJson: (message: ServerMessage) => void,
|
||||
): void {
|
||||
if (message.type === "screenShareList") {
|
||||
sendJson({ type: "screenShareList", streams: this.listScreenStreamsFor(entry) });
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "screenShareStart") {
|
||||
if ([...this.screenStreams.values()].some((stream) => stream.source === "browser" && stream.ownerEntryId === entry.id)) {
|
||||
sendJson({ type: "screenShareError", requestId: message.requestId, code: "SCREEN_SHARE_ALREADY_ACTIVE", message: "你已经在共享屏幕" });
|
||||
return;
|
||||
}
|
||||
const stream: ScreenStreamRecord = {
|
||||
streamId: `screen-${randomUUID()}`,
|
||||
source: "browser",
|
||||
ownerPeerId: entry.screenPeerId,
|
||||
ownerClientId: entry.tsClient.getClientId() || undefined,
|
||||
ownerNickname: entry.nickname,
|
||||
name: message.name?.trim() || `${entry.nickname} 的屏幕`,
|
||||
audio: message.audio === true,
|
||||
createdAt: Date.now(),
|
||||
viewerCount: 0,
|
||||
viewers: [],
|
||||
targetKey: teamSpeakTargetKey(entry.target),
|
||||
channelId: entry.tsClient.getChannelId(),
|
||||
ownerEntryId: entry.id,
|
||||
viewerEntryIds: new Map(),
|
||||
teamSpeakPublisherEntryId: entry.id,
|
||||
nativeViewerClids: new Set(),
|
||||
};
|
||||
this.screenStreams.set(screenStreamKey(stream.targetKey, stream.streamId), stream);
|
||||
sendJson({ type: "screenShareStarted", requestId: message.requestId, stream: this.describeScreenStream(stream), owner: true });
|
||||
this.broadcastScreenMessage(stream, {
|
||||
type: "screenShareStarted",
|
||||
stream: this.describeScreenStream(stream),
|
||||
owner: false,
|
||||
}, entry.id);
|
||||
void this.publishBrowserScreenStream(entry, stream);
|
||||
return;
|
||||
}
|
||||
|
||||
const stream = this.screenStreams.get(screenStreamKey(teamSpeakTargetKey(entry.target), message.streamId));
|
||||
if (!stream) {
|
||||
sendJson({ type: "screenShareError", requestId: "requestId" in message ? message.requestId : undefined, code: "SCREEN_SHARE_NOT_FOUND", message: "屏幕共享已结束或不存在" });
|
||||
return;
|
||||
}
|
||||
if (stream.targetKey !== teamSpeakTargetKey(entry.target) || stream.channelId !== entry.tsClient.getChannelId()) {
|
||||
sendJson({ type: "screenShareError", requestId: "requestId" in message ? message.requestId : undefined, code: "SCREEN_SHARE_TARGET_MISMATCH", message: "屏幕共享不属于当前服务器或频道" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "screenShareStop") {
|
||||
if (stream.ownerEntryId !== entry.id) {
|
||||
sendJson({ type: "screenShareError", requestId: message.requestId, code: "SCREEN_SHARE_NOT_OWNER", message: "只有共享者可以结束共享" });
|
||||
return;
|
||||
}
|
||||
this.stopScreenStream(stream, "owner-stopped");
|
||||
if (message.requestId) sendJson({ type: "screenShareCompleted", requestId: message.requestId });
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "screenShareJoin") {
|
||||
if (stream.ownerEntryId === entry.id) {
|
||||
sendJson({ type: "screenShareError", requestId: message.requestId, code: "SCREEN_SHARE_OWNER_CANNOT_JOIN", message: "共享者不能作为观看者加入自己的共享" });
|
||||
return;
|
||||
}
|
||||
const alreadyJoined = stream.viewerEntryIds.has(entry.id);
|
||||
if (!alreadyJoined) stream.viewerEntryIds.set(entry.id, Symbol("screen-membership"));
|
||||
stream.viewerCount = this.screenShareViewerCount(stream);
|
||||
sendJson({
|
||||
type: "screenShareJoined",
|
||||
requestId: message.requestId,
|
||||
stream: this.describeScreenStream(stream),
|
||||
ownerPeerId: stream.ownerPeerId,
|
||||
mode: stream.source,
|
||||
});
|
||||
if (stream.source === "browser" && !alreadyJoined) {
|
||||
this.sendToEntry(stream.ownerEntryId, {
|
||||
type: "screenShareViewerJoined",
|
||||
streamId: stream.streamId,
|
||||
viewerPeerId: entry.screenPeerId,
|
||||
viewerNickname: entry.nickname,
|
||||
});
|
||||
} else if (stream.source === "teamspeak" && !alreadyJoined) {
|
||||
void this.joinNativeScreenStream(entry, stream, sendJson, message.requestId);
|
||||
}
|
||||
if (!alreadyJoined) {
|
||||
this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "screenShareLeave") {
|
||||
this.leaveScreenStream(entry, stream);
|
||||
if (message.requestId) sendJson({ type: "screenShareCompleted", requestId: message.requestId });
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "screenShareSignal") {
|
||||
this.relayScreenShareSignal(entry, stream, message.targetPeerId, message.signal, sendJson);
|
||||
}
|
||||
}
|
||||
|
||||
private listScreenStreamsFor(entry: ScreenShareParticipant): ScreenShareStreamDescription[] {
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
return [...this.screenStreams.values()]
|
||||
.filter((stream) => stream.targetKey === targetKey && stream.channelId === entry.tsClient.getChannelId())
|
||||
.map((stream) => this.describeScreenStream(stream));
|
||||
}
|
||||
|
||||
/**
|
||||
* A gateway session can connect after a native TeamSpeak stream has already
|
||||
* started. TS6 does not replay that stream in the normal welcome snapshot;
|
||||
* requeststreaminfo is the official client-protocol query for this case.
|
||||
* Rescan on each connection. Concurrent requests for the same server share
|
||||
* one running pass and one pending pass using the latest session directory.
|
||||
*/
|
||||
discoverExistingStreams(entry: ScreenShareParticipant): Promise<void> {
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
const active = this.discoveries.get(targetKey);
|
||||
if (active) {
|
||||
active.pendingEntry = entry;
|
||||
return active.completion;
|
||||
}
|
||||
const discovery = {
|
||||
pendingEntry: entry as ScreenShareParticipant | undefined,
|
||||
completion: Promise.resolve(),
|
||||
};
|
||||
discovery.completion = Promise.resolve().then(async () => {
|
||||
try {
|
||||
while (discovery.pendingEntry) {
|
||||
const requestedEntry = discovery.pendingEntry;
|
||||
discovery.pendingEntry = undefined;
|
||||
const queryEntry = this.entries.get(requestedEntry.id) === requestedEntry && requestedEntry.tsClient.isConnected()
|
||||
? requestedEntry
|
||||
: [...this.entries.values()].find(candidate => teamSpeakTargetKey(candidate.target) === targetKey && candidate.tsClient.isConnected());
|
||||
if (!queryEntry) continue;
|
||||
const clientIds = [...queryEntry.members.keys()].filter(clientId => Number.isInteger(clientId) && clientId > 0);
|
||||
for (const clientId of clientIds) {
|
||||
if (this.entries.get(queryEntry.id) !== queryEntry || !queryEntry.tsClient.isConnected()) break;
|
||||
try {
|
||||
await queryEntry.tsClient.sendProtocolCommand(`requeststreaminfo clid=${clientId}`);
|
||||
} catch (error: unknown) {
|
||||
this.logger.debug({
|
||||
target: formatTeamSpeakTarget(queryEntry.target),
|
||||
clientId,
|
||||
err: error instanceof Error ? error.message : String(error),
|
||||
}, "Could not query existing TeamSpeak screen stream");
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this.discoveries.delete(targetKey);
|
||||
}
|
||||
});
|
||||
this.discoveries.set(targetKey, discovery);
|
||||
return discovery.completion;
|
||||
}
|
||||
|
||||
private describeScreenStream(stream: ScreenStreamRecord): ScreenShareStreamDescription {
|
||||
return {
|
||||
streamId: stream.streamId,
|
||||
source: stream.source,
|
||||
ownerPeerId: stream.ownerPeerId,
|
||||
...(typeof stream.ownerClientId === "number" ? { ownerClientId: stream.ownerClientId } : {}),
|
||||
ownerNickname: stream.ownerNickname,
|
||||
name: stream.name,
|
||||
audio: stream.audio,
|
||||
createdAt: stream.createdAt,
|
||||
viewerCount: stream.viewerCount,
|
||||
viewers: this.describeScreenViewers(stream),
|
||||
};
|
||||
}
|
||||
|
||||
private describeScreenViewers(stream: ScreenStreamRecord): ScreenShareViewerDescription[] {
|
||||
return [...stream.viewerEntryIds.keys()]
|
||||
.map((entryId) => this.entries.get(entryId))
|
||||
.filter((entry): entry is ScreenShareParticipant => Boolean(entry))
|
||||
.slice(0, 64)
|
||||
.map((entry) => {
|
||||
const avatar = entry.members.get(entry.tsClient.getClientId())?.avatar;
|
||||
return {
|
||||
peerId: entry.screenPeerId,
|
||||
nickname: entry.nickname,
|
||||
...(avatar && avatar.length <= 128 * 1024 ? { avatar } : {}),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private screenShareViewerCountMessage(stream: ScreenStreamRecord): ServerMessage {
|
||||
return {
|
||||
type: "screenShareViewerCount",
|
||||
streamId: stream.streamId,
|
||||
viewerCount: stream.viewerCount,
|
||||
viewers: this.describeScreenViewers(stream),
|
||||
};
|
||||
}
|
||||
|
||||
private screenShareViewerCount(stream: ScreenStreamRecord): number {
|
||||
return stream.viewerEntryIds.size + stream.nativeViewerClids.size;
|
||||
}
|
||||
|
||||
private broadcastScreenMessage(stream: ScreenStreamRecord, message: ServerMessage, excludeEntryId?: string): void {
|
||||
for (const candidate of this.entries.values()) {
|
||||
if (candidate.id === excludeEntryId || candidate.target && teamSpeakTargetKey(candidate.target) !== stream.targetKey) continue;
|
||||
// A stream is scoped to the source channel. Do not leak its card or
|
||||
// viewer roster to users who are connected to another channel on the
|
||||
// same TeamSpeak target.
|
||||
if (candidate.id !== stream.ownerEntryId) {
|
||||
try {
|
||||
if (candidate.tsClient.getChannelId() !== stream.channelId) continue;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
this.sendToEntry(candidate.id, message);
|
||||
}
|
||||
}
|
||||
|
||||
private stopScreenStream(stream: ScreenStreamRecord, reason: string): void {
|
||||
if (!this.screenStreams.delete(screenStreamKey(stream.targetKey, stream.streamId))) return;
|
||||
if (stream.source === "browser" && stream.teamSpeakStreamId && stream.teamSpeakPublisherEntryId) {
|
||||
const publisher = this.entries.get(stream.teamSpeakPublisherEntryId);
|
||||
if (publisher) {
|
||||
void publisher.tsClient.sendProtocolCommand(buildTeamSpeakCommand("stopstream", {
|
||||
id: stream.teamSpeakStreamId,
|
||||
reason: "1",
|
||||
})).catch((error: unknown) => {
|
||||
this.logger.warn({ streamId: stream.teamSpeakStreamId, err: error instanceof Error ? error.message : String(error) }, "Could not stop native screen publication");
|
||||
});
|
||||
}
|
||||
}
|
||||
const message: ServerMessage = { type: "screenShareStopped", streamId: stream.streamId, reason };
|
||||
this.broadcastScreenMessage(stream, message);
|
||||
stream.viewerEntryIds.clear();
|
||||
stream.nativeViewerClids.clear();
|
||||
stream.viewerCount = 0;
|
||||
}
|
||||
|
||||
private leaveScreenStream(entry: ScreenShareParticipant, stream: ScreenStreamRecord): void {
|
||||
if (!stream.viewerEntryIds.delete(entry.id)) return;
|
||||
stream.viewerCount = this.screenShareViewerCount(stream);
|
||||
if (stream.source === "browser") this.sendToEntry(stream.ownerEntryId, { type: "screenShareViewerLeft", streamId: stream.streamId, viewerPeerId: entry.screenPeerId });
|
||||
else {
|
||||
void entry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("removeclientfromstream", {
|
||||
id: stream.streamId,
|
||||
clid: String(entry.tsClient.getClientId()),
|
||||
reason: "1",
|
||||
})).catch(() => undefined);
|
||||
}
|
||||
this.sendToEntry(entry.id, { type: "screenShareLeft", streamId: stream.streamId });
|
||||
this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream));
|
||||
}
|
||||
|
||||
private relayScreenShareSignal(
|
||||
entry: ScreenShareParticipant,
|
||||
stream: ScreenStreamRecord,
|
||||
targetPeerId: string,
|
||||
signal: ScreenSharePeerSignal,
|
||||
sendJson: (message: ServerMessage) => void,
|
||||
): void {
|
||||
if (stream.source === "teamspeak") {
|
||||
if (!stream.viewerEntryIds.has(entry.id) || targetPeerId !== stream.ownerPeerId) {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FORBIDDEN", message: "无权发送该屏幕共享信令" });
|
||||
return;
|
||||
}
|
||||
const sourceClientId = stream.sourceClientId;
|
||||
if (!sourceClientId) {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SOURCE_UNAVAILABLE", message: "共享来源暂不可用" });
|
||||
return;
|
||||
}
|
||||
if (signal.kind === "close") {
|
||||
this.leaveScreenStream(entry, stream);
|
||||
return;
|
||||
}
|
||||
if (signal.kind === "offer") {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_INVALID_SIGNAL", message: "观看端不能向 TeamSpeak 来源发送 offer" });
|
||||
return;
|
||||
}
|
||||
const payload = signal.kind === "iceCandidate"
|
||||
? { cmd: "iceCandidate", args: { sdp: signal.candidate, ...(signal.sdpMid !== undefined ? { mid: signal.sdpMid } : {}), ...(signal.sdpMLineIndex !== undefined ? { mLine: signal.sdpMLineIndex } : {}) } }
|
||||
: { cmd: "answer", args: { answer: signal.sdp } };
|
||||
void entry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("streamsignaling", {
|
||||
id: stream.streamId,
|
||||
clid: String(sourceClientId),
|
||||
json: JSON.stringify(payload),
|
||||
})).catch((error: unknown) => {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FAILED", message: error instanceof Error ? error.message : "屏幕共享信令发送失败" });
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (stream.source === "browser" && entry.id === stream.ownerEntryId && targetPeerId.startsWith("ts-viewer-")) {
|
||||
const viewerClid = parseNativeViewerPeerId(targetPeerId);
|
||||
const publisher = stream.teamSpeakPublisherEntryId ? this.entries.get(stream.teamSpeakPublisherEntryId) : undefined;
|
||||
if (!viewerClid || !publisher || !stream.teamSpeakStreamId || !stream.nativeViewerClids.has(viewerClid)) {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_PEER_NOT_FOUND", message: "TeamSpeak 观看者已离开" });
|
||||
return;
|
||||
}
|
||||
if (signal.kind === "close") {
|
||||
void publisher.tsClient.sendProtocolCommand(buildTeamSpeakCommand("removeclientfromstream", {
|
||||
id: stream.teamSpeakStreamId,
|
||||
clid: String(viewerClid),
|
||||
reason: "1",
|
||||
})).then(() => {
|
||||
if (this.entries.get(entry.id) !== entry
|
||||
|| this.screenStreams.get(screenStreamKey(stream.targetKey, stream.streamId)) !== stream
|
||||
|| !stream.nativeViewerClids.delete(viewerClid)) return;
|
||||
// The native notification may already have removed this viewer.
|
||||
stream.viewerCount = this.screenShareViewerCount(stream);
|
||||
this.sendToEntry(entry.id, { type: "screenShareViewerLeft", streamId: stream.streamId, viewerPeerId: targetPeerId });
|
||||
this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream));
|
||||
}).catch((error: unknown) => {
|
||||
if (this.entries.get(entry.id) !== entry
|
||||
|| this.screenStreams.get(screenStreamKey(stream.targetKey, stream.streamId)) !== stream) return;
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FAILED", message: error instanceof Error ? error.message : "无法移除 TeamSpeak 观看者" });
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (signal.kind === "answer") {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_INVALID_SIGNAL", message: "TeamSpeak 观看端不能先发送 answer" });
|
||||
return;
|
||||
}
|
||||
let command: string;
|
||||
if (signal.kind === "offer") {
|
||||
command = buildTeamSpeakCommand("respondjoinstreamrequest", {
|
||||
id: stream.teamSpeakStreamId,
|
||||
clid: String(viewerClid),
|
||||
msg: "",
|
||||
offer: signal.sdp,
|
||||
decision: "1",
|
||||
});
|
||||
} else if (signal.kind === "iceCandidate") {
|
||||
command = buildTeamSpeakCommand("streamsignaling", {
|
||||
id: stream.teamSpeakStreamId,
|
||||
clid: String(viewerClid),
|
||||
json: JSON.stringify({ cmd: "iceCandidate", args: { sdp: signal.candidate, ...(signal.sdpMid !== undefined ? { mid: signal.sdpMid } : {}), ...(signal.sdpMLineIndex !== undefined ? { mLine: signal.sdpMLineIndex } : {}) } }),
|
||||
});
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
void publisher.tsClient.sendProtocolCommand(command).catch((error: unknown) => {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FAILED", message: error instanceof Error ? error.message : "屏幕共享信令发送失败" });
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const owner = this.entries.get(stream.ownerEntryId);
|
||||
const isOwner = entry.id === stream.ownerEntryId;
|
||||
const isViewer = stream.viewerEntryIds.has(entry.id);
|
||||
if (!owner || (!isOwner && !isViewer)) {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FORBIDDEN", message: "无权发送该屏幕共享信令" });
|
||||
return;
|
||||
}
|
||||
// Keep the browser P2P graph bipartite: the owner may signal only an
|
||||
// active viewer, and a viewer may signal only the owner. Without this
|
||||
// check one viewer could inject SDP/ICE into another viewer's peer.
|
||||
const targetEntry = isOwner
|
||||
? [...stream.viewerEntryIds.keys()]
|
||||
.map((id) => this.entries.get(id))
|
||||
.find((candidate) => candidate?.screenPeerId === targetPeerId)
|
||||
: targetPeerId === owner.screenPeerId ? owner : undefined;
|
||||
if (!targetEntry || targetEntry.id === entry.id) {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_PEER_NOT_FOUND", message: "观看者已离开" });
|
||||
return;
|
||||
}
|
||||
this.sendToEntry(targetEntry.id, { type: "screenShareSignal", streamId: stream.streamId, fromPeerId: entry.screenPeerId, signal });
|
||||
}
|
||||
|
||||
private async publishBrowserScreenStream(entry: ScreenShareParticipant, stream: ScreenStreamRecord): Promise<void> {
|
||||
try {
|
||||
await entry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("setupstream", {
|
||||
name: stream.name,
|
||||
type: "3",
|
||||
bitrate: "4608",
|
||||
accessibility: "1",
|
||||
mode: "1",
|
||||
viewer_limit: "0",
|
||||
audio: stream.audio ? "1" : "0",
|
||||
}));
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
streamId: stream.streamId,
|
||||
err: error instanceof Error ? error.message : String(error),
|
||||
}, "Could not publish browser screen share to TeamSpeak");
|
||||
}
|
||||
}
|
||||
|
||||
private async joinNativeScreenStream(
|
||||
entry: ScreenShareParticipant,
|
||||
stream: ScreenStreamRecord,
|
||||
sendJson: (message: ServerMessage) => void,
|
||||
requestId?: string,
|
||||
): Promise<void> {
|
||||
const membership = stream.viewerEntryIds.get(entry.id);
|
||||
const sourceClientId = stream.sourceClientId;
|
||||
if (!entry.tsClient.getClientId() || !sourceClientId) {
|
||||
sendJson({ type: "screenShareError", requestId, code: "SCREEN_SHARE_SOURCE_UNAVAILABLE", message: "共享来源暂不可用" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await entry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("joinstreamrequest", {
|
||||
id: stream.streamId,
|
||||
// TS6 uses the source client id on joinstreamrequest. The requesting
|
||||
// gateway session is identified later by the response/signaling
|
||||
// notification delivered to this TS connection.
|
||||
clid: String(sourceClientId),
|
||||
msg: "",
|
||||
is_remove: "0",
|
||||
muted: "0",
|
||||
volume: "0",
|
||||
hidden: "0",
|
||||
}));
|
||||
} catch (error: unknown) {
|
||||
if (this.entries.get(entry.id) !== entry
|
||||
|| this.screenStreams.get(screenStreamKey(stream.targetKey, stream.streamId)) !== stream
|
||||
|| stream.viewerEntryIds.get(entry.id) !== membership) return;
|
||||
this.leaveScreenStream(entry, stream);
|
||||
sendJson({ type: "screenShareError", requestId, code: "SCREEN_SHARE_JOIN_FAILED", message: error instanceof Error ? error.message : "无法加入屏幕共享" });
|
||||
}
|
||||
}
|
||||
|
||||
removePeer(entryId: string): void {
|
||||
for (const stream of [...this.screenStreams.values()]) {
|
||||
if (stream.ownerEntryId === entryId) {
|
||||
this.stopScreenStream(stream, "owner-disconnected");
|
||||
continue;
|
||||
}
|
||||
const entry = this.entries.get(entryId);
|
||||
if (entry && stream.viewerEntryIds.has(entryId)) this.leaveScreenStream(entry, stream);
|
||||
}
|
||||
const departing = this.entries.get(entryId);
|
||||
if (!departing) return;
|
||||
const targetKey = teamSpeakTargetKey(departing.target);
|
||||
if (![...this.entries.values()].some(entry => entry.id !== entryId && teamSpeakTargetKey(entry.target) === targetKey)) {
|
||||
// Native notifications are not observed while no session is attached.
|
||||
// Rediscover on the next connection instead of retaining stale cards.
|
||||
for (const stream of [...this.screenStreams.values()]) {
|
||||
if (stream.targetKey === targetKey) this.stopScreenStream(stream, "target-disconnected");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onClientMove(entry: ScreenShareParticipant, movedClientId: number, targetChannelId: bigint): void {
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
const selfMoved = movedClientId === entry.tsClient.getClientId();
|
||||
for (const stream of [...this.screenStreams.values()]) {
|
||||
if (stream.targetKey !== targetKey) continue;
|
||||
// A browser share belongs to the gateway user's current channel. Stop
|
||||
// it when that user moves so existing viewers cannot keep a cross-
|
||||
// channel peer alive.
|
||||
if (selfMoved && stream.source === "browser" && stream.ownerEntryId === entry.id && stream.channelId !== targetChannelId) {
|
||||
this.stopScreenStream(stream, "owner-moved-channel");
|
||||
continue;
|
||||
}
|
||||
// Native TS6 shares are channel-scoped as well. The notification is
|
||||
// observed by every gateway session, so stop the shared record once the
|
||||
// native source changes channels.
|
||||
if (stream.source === "teamspeak" && stream.sourceClientId === movedClientId && stream.channelId !== targetChannelId) {
|
||||
this.stopScreenStream(stream, "source-moved-channel");
|
||||
continue;
|
||||
}
|
||||
if (selfMoved && stream.viewerEntryIds.has(entry.id) && stream.channelId !== targetChannelId) {
|
||||
this.leaveScreenStream(entry, stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onClientLeave(entry: ScreenShareParticipant, clientId: number): void {
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
for (const stream of [...this.screenStreams.values()]) {
|
||||
if (stream.targetKey === targetKey && stream.source === "teamspeak" && stream.sourceClientId === clientId) {
|
||||
this.stopScreenStream(stream, "source-left");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
handleNotification(entry: ScreenShareParticipant, notification: TSRawNotification): void {
|
||||
if (this.entries.get(entry.id) !== entry) return;
|
||||
const params = notification.params;
|
||||
if (notification.name === "notifyjoinstreamrequest") {
|
||||
const streamId = params.id || params.stream_id;
|
||||
const viewerClientId = parseNumber(params.clid);
|
||||
if (!streamId || !viewerClientId) return;
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
const stream = [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey
|
||||
&& candidate.source === "browser"
|
||||
&& candidate.teamSpeakPublisherEntryId === entry.id
|
||||
&& candidate.teamSpeakStreamId === streamId);
|
||||
if (!stream) return;
|
||||
stream.nativeViewerClids.add(viewerClientId);
|
||||
stream.viewerCount = this.screenShareViewerCount(stream);
|
||||
this.sendToEntry(stream.ownerEntryId, {
|
||||
type: "screenShareNativeViewerJoined",
|
||||
streamId: stream.streamId,
|
||||
viewerPeerId: nativeViewerPeerId(viewerClientId),
|
||||
viewerClientId,
|
||||
});
|
||||
this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream));
|
||||
return;
|
||||
}
|
||||
if (notification.name === "notifystreamstarted" || notification.name === "notifystreaminfo") {
|
||||
const streamId = params.id || params.stream_id;
|
||||
const sourceClientId = parseNumber(params.clid);
|
||||
if (!streamId || !sourceClientId) return;
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
const publisherEntry = [...this.entries.values()].find((candidate) => candidate.target
|
||||
&& teamSpeakTargetKey(candidate.target) === targetKey
|
||||
&& candidate.tsClient.getClientId() === sourceClientId);
|
||||
const browserStream = publisherEntry
|
||||
? [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey
|
||||
&& candidate.source === "browser"
|
||||
&& candidate.teamSpeakPublisherEntryId === publisherEntry.id
|
||||
&& (!candidate.teamSpeakStreamId || candidate.teamSpeakStreamId === streamId))
|
||||
: undefined;
|
||||
if (browserStream) {
|
||||
browserStream.teamSpeakStreamId = streamId;
|
||||
return;
|
||||
}
|
||||
if (publisherEntry) {
|
||||
// A delayed setup acknowledgement can arrive after the browser stopped.
|
||||
// A gateway-owned publication is never a second native source.
|
||||
void publisherEntry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("stopstream", { id: streamId, reason: "1" })).catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
// Prefer the observer's directory; another connection can still be
|
||||
// processing an older snapshot of the same source.
|
||||
const sourceChannel = [entry, ...this.entries.values()]
|
||||
.filter(candidate => teamSpeakTargetKey(candidate.target) === targetKey && candidate.tsClient.isConnected())
|
||||
.map(candidate => candidate.channelTree.find(channel => channel.id !== "0" && channel.members?.some(member => member.id === sourceClientId)))
|
||||
.find(channel => channel !== undefined);
|
||||
// Do not guess a channel from the observer, or from a colliding client id
|
||||
// on another server. Discovery will retry after the directory is ready.
|
||||
if (!sourceChannel) return;
|
||||
const key = screenStreamKey(targetKey, streamId);
|
||||
let current = this.screenStreams.get(key);
|
||||
if (current && current.channelId !== BigInt(sourceChannel.id)) {
|
||||
// Retire the old channel's card and memberships before announcing the
|
||||
// corrected source. Never carry viewers across a channel boundary.
|
||||
for (const viewerId of current.viewerEntryIds.keys()) {
|
||||
const viewer = this.entries.get(viewerId);
|
||||
if (viewer) this.leaveScreenStream(viewer, current);
|
||||
}
|
||||
this.stopScreenStream(current, "source-moved-channel");
|
||||
current = undefined;
|
||||
}
|
||||
const stream: ScreenStreamRecord = current ?? {
|
||||
streamId,
|
||||
source: "teamspeak",
|
||||
ownerPeerId: `ts-${sourceClientId}`,
|
||||
ownerClientId: sourceClientId,
|
||||
ownerNickname: params.name || `TeamSpeak 用户 ${sourceClientId}`,
|
||||
name: params.name || "TeamSpeak 屏幕共享",
|
||||
audio: params.audio === "1",
|
||||
createdAt: Date.now(),
|
||||
viewerCount: 0,
|
||||
viewers: [],
|
||||
targetKey,
|
||||
channelId: BigInt(sourceChannel.id),
|
||||
ownerEntryId: "",
|
||||
viewerEntryIds: new Map(),
|
||||
nativeViewerClids: new Set(),
|
||||
sourceClientId,
|
||||
};
|
||||
stream.sourceClientId = sourceClientId;
|
||||
stream.ownerNickname = params.name || stream.ownerNickname;
|
||||
stream.name = params.name || stream.name;
|
||||
stream.audio = params.audio === "1";
|
||||
this.screenStreams.set(key, stream);
|
||||
// Every gateway session attached to the same TS target sees the same
|
||||
// raw notification. Only the first one should announce a new stream to
|
||||
// browsers; otherwise each connected user receives duplicate cards.
|
||||
if (!current) {
|
||||
this.broadcastScreenMessage(stream, { type: "screenShareStarted", stream: this.describeScreenStream(stream), owner: false });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (notification.name === "notifystreamstopped") {
|
||||
const streamId = params.id || params.stream_id;
|
||||
if (!streamId) return;
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
const stream = this.screenStreams.get(screenStreamKey(targetKey, streamId));
|
||||
if (stream) {
|
||||
this.stopScreenStream(stream, "source-stopped");
|
||||
return;
|
||||
}
|
||||
const browserStream = [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey
|
||||
&& candidate.source === "browser"
|
||||
&& candidate.teamSpeakStreamId === streamId);
|
||||
if (browserStream) {
|
||||
browserStream.teamSpeakStreamId = undefined;
|
||||
browserStream.nativeViewerClids.clear();
|
||||
browserStream.viewerCount = this.screenShareViewerCount(browserStream);
|
||||
this.sendToEntry(browserStream.ownerEntryId, {
|
||||
type: "screenShareError",
|
||||
code: "SCREEN_SHARE_NATIVE_PUBLISHER_STOPPED",
|
||||
message: "TeamSpeak 客户端屏幕共享通道已停止,网页共享仍可继续",
|
||||
});
|
||||
this.broadcastScreenMessage(browserStream, this.screenShareViewerCountMessage(browserStream));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (notification.name === "notifystreamclientleft") {
|
||||
const streamId = params.id || params.stream_id;
|
||||
const viewerClientId = parseNumber(params.clid);
|
||||
if (!streamId || !viewerClientId) return;
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
const stream = [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey
|
||||
&& candidate.source === "browser"
|
||||
&& candidate.teamSpeakStreamId === streamId
|
||||
&& candidate.nativeViewerClids.has(viewerClientId));
|
||||
if (!stream) return;
|
||||
stream.nativeViewerClids.delete(viewerClientId);
|
||||
stream.viewerCount = this.screenShareViewerCount(stream);
|
||||
this.sendToEntry(stream.ownerEntryId, {
|
||||
type: "screenShareViewerLeft",
|
||||
streamId: stream.streamId,
|
||||
viewerPeerId: nativeViewerPeerId(viewerClientId),
|
||||
});
|
||||
this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream));
|
||||
return;
|
||||
}
|
||||
if (notification.name === "notifyrespondjoinstreamrequest" || notification.name === "notifystreamsignaling") {
|
||||
const streamId = params.id || params.stream_id;
|
||||
if (!streamId) return;
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
const browserStream = notification.name === "notifystreamsignaling"
|
||||
? [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey
|
||||
&& candidate.source === "browser"
|
||||
&& candidate.teamSpeakPublisherEntryId === entry.id
|
||||
&& candidate.teamSpeakStreamId === streamId)
|
||||
: undefined;
|
||||
if (browserStream) {
|
||||
const viewerClientId = parseNumber(params.clid);
|
||||
if (!viewerClientId || !browserStream.nativeViewerClids.has(viewerClientId)) return;
|
||||
const payload = parseStreamSignalPayload(params.json || params.data || "");
|
||||
if (!payload) return;
|
||||
const signal = toBrowserScreenSignal(payload);
|
||||
if (!signal) return;
|
||||
this.sendToEntry(browserStream.ownerEntryId, {
|
||||
type: "screenShareSignal",
|
||||
streamId: browserStream.streamId,
|
||||
fromPeerId: nativeViewerPeerId(viewerClientId),
|
||||
signal,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const stream = this.screenStreams.get(screenStreamKey(targetKey, streamId));
|
||||
if (!stream || stream.source !== "teamspeak" || !stream.viewerEntryIds.has(entry.id)) return;
|
||||
const payload = notification.name === "notifyrespondjoinstreamrequest"
|
||||
? { cmd: "offer", args: { offer: params.offer || "" } }
|
||||
: parseStreamSignalPayload(params.json || params.data || "");
|
||||
if (!payload) return;
|
||||
const signal = toBrowserScreenSignal(payload);
|
||||
if (!signal) return;
|
||||
this.sendToEntry(entry.id, { type: "screenShareSignal", streamId, fromPeerId: stream.ownerPeerId, signal });
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function parseNumber(value: string | undefined): number | undefined {
|
||||
if (!value || !/^\d+$/.test(value)) return undefined;
|
||||
const parsed = Number(value);
|
||||
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
|
||||
}
|
||||
|
||||
function nativeViewerPeerId(clientId: number): string {
|
||||
return `ts-viewer-${clientId}`;
|
||||
}
|
||||
|
||||
function parseNativeViewerPeerId(peerId: string): number | undefined {
|
||||
const match = /^ts-viewer-(\d+)$/.exec(peerId);
|
||||
if (!match) return undefined;
|
||||
return parseNumber(match[1]);
|
||||
}
|
||||
|
||||
function buildTeamSpeakCommand(command: string, params: Record<string, string>): string {
|
||||
return [command, ...Object.entries(params).map(([key, value]) => `${key}=${escapeTeamSpeakValue(value)}`)].join(" ");
|
||||
}
|
||||
|
||||
function parseStreamSignalPayload(raw: string): { cmd: string; args: Record<string, unknown> } | null {
|
||||
try {
|
||||
const value: unknown = JSON.parse(raw);
|
||||
if (!isRecord(value) || typeof value.cmd !== "string" || !isRecord(value.args)) return null;
|
||||
return { cmd: value.cmd, args: value.args };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function toBrowserScreenSignal(payload: { cmd: string; args: Record<string, unknown> }): ScreenSharePeerSignal | null {
|
||||
const args = payload.args;
|
||||
// TeamSpeak's native screen-share source wraps the initial SDP in a
|
||||
// `joinResponse` message after it accepts a viewer's join request. The
|
||||
// browser-side protocol uses the regular offer shape, so normalize it here
|
||||
// before forwarding it. Without this mapping the native source can accept a
|
||||
// viewer while the browser waits forever for its first SDP.
|
||||
if (payload.cmd === "joinResponse") {
|
||||
const decision = args.decision;
|
||||
if (decision === false || decision === 0 || decision === "0") return { kind: "close" };
|
||||
const sdp = typeof args.offer === "string" ? args.offer : typeof args.sdp === "string" ? args.sdp : "";
|
||||
return sdp ? { kind: "offer", sdp } : null;
|
||||
}
|
||||
if (payload.cmd === "offer" || payload.cmd === "reconnectOffer") {
|
||||
const sdp = typeof args.offer === "string" ? args.offer : typeof args.sdp === "string" ? args.sdp : "";
|
||||
return sdp ? { kind: "offer", sdp } : null;
|
||||
}
|
||||
if (payload.cmd === "answer") {
|
||||
const sdp = typeof args.answer === "string" ? args.answer : typeof args.sdp === "string" ? args.sdp : "";
|
||||
return sdp ? { kind: "answer", sdp } : null;
|
||||
}
|
||||
if (payload.cmd === "iceCandidate") {
|
||||
const candidate = typeof args.sdp === "string" ? args.sdp : typeof args.candidate === "string" ? args.candidate : "";
|
||||
if (!candidate) return null;
|
||||
return {
|
||||
kind: "iceCandidate",
|
||||
candidate,
|
||||
...(typeof args.mid === "string" ? { sdpMid: args.mid } : {}),
|
||||
...(typeof args.mLine === "number" ? { sdpMLineIndex: args.mLine } : {}),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function escapeTeamSpeakValue(value: string): string {
|
||||
return value
|
||||
.replace(/\\/g, "\\\\")
|
||||
.replace(/ /g, "\\s")
|
||||
.replace(/\//g, "\\/")
|
||||
.replace(/\|/g, "\\p")
|
||||
.replace(/\n/g, "\\n")
|
||||
.replace(/\r/g, "\\r");
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from "../shared/screen-share.js";
|
||||
@@ -9,10 +9,12 @@ import { parseTeamSpeakTarget, teamSpeakTargetKey } from "../domain/teamspeak-ta
|
||||
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 { isSafeOpenTargetForPrefill, resolveSafeOpenTarget } from "../security/open-target-policy.js";
|
||||
import { identityFromString } from "@echosixhiya/teamspeak-client";
|
||||
import { JoinRateLimiter } from "./join-rate-limit.js";
|
||||
import type { ConfiguredAccelerationRelay } from "./acceleration-relay.js";
|
||||
import type { SkinRegistry } from "../admin/skin-registry.js";
|
||||
import { resolveVisitorTotal } from "./visitor-count.js";
|
||||
|
||||
export interface WebServerOptions {
|
||||
port: number;
|
||||
@@ -22,7 +24,10 @@ export interface WebServerOptions {
|
||||
certDir?: string; // path to cert.pem + key.pem for HTTPS
|
||||
voiceBridgeOptions: VoiceBridgeOptions;
|
||||
adminService: AdminService;
|
||||
skinRegistry?: SkinRegistry;
|
||||
logger: Logger;
|
||||
nextVisitorNumber?: () => number;
|
||||
visitorCount?: () => number;
|
||||
}
|
||||
|
||||
export interface WebServer {
|
||||
@@ -30,6 +35,8 @@ export interface WebServer {
|
||||
stop(): Promise<void>;
|
||||
}
|
||||
|
||||
const VISITOR_NUMBER_COOKIE = "webspeak_visitor_number";
|
||||
|
||||
export function createWebServer(options: WebServerOptions): WebServer {
|
||||
const app = express();
|
||||
const logger = options.logger.child({ component: "web" });
|
||||
@@ -58,16 +65,88 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
app.get("/health", healthHandler);
|
||||
app.get("/api/health", healthHandler);
|
||||
|
||||
app.get("/api/public-config", (_request, response) => {
|
||||
app.get("/api/public-config", async (request, response) => {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
const acceleration = resolveAccelerationOptions(options.voiceBridgeOptions.acceleration);
|
||||
let visitorNumber = readVisitorNumberCookie(request.header("cookie"));
|
||||
if (visitorNumber === null && options.nextVisitorNumber) {
|
||||
try {
|
||||
visitorNumber = options.nextVisitorNumber();
|
||||
response.setHeader(
|
||||
"Set-Cookie",
|
||||
`${VISITOR_NUMBER_COOKIE}=${visitorNumber}; Max-Age=31536000; Path=/; SameSite=Lax${options.certDir ? "; Secure" : ""}`,
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Visitor number could not be assigned");
|
||||
}
|
||||
}
|
||||
let visitorTotal = resolveVisitorTotal(visitorNumber, null);
|
||||
if (options.visitorCount) {
|
||||
try {
|
||||
visitorTotal = resolveVisitorTotal(visitorNumber, options.visitorCount());
|
||||
} catch (error: unknown) {
|
||||
logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Visitor total could not be read");
|
||||
}
|
||||
} else if (visitorNumber !== null) {
|
||||
visitorTotal = visitorNumber;
|
||||
}
|
||||
const publicConfig = options.adminService.getPublicConfig();
|
||||
let target = typeof publicConfig.target === "string" ? publicConfig.target : "";
|
||||
let targetPrefillBlocked = false;
|
||||
if (publicConfig.accessMode === "open" && target.trim()) {
|
||||
try {
|
||||
targetPrefillBlocked = !await isSafeOpenTargetForPrefill(parseTeamSpeakTarget(target));
|
||||
} catch {
|
||||
targetPrefillBlocked = true;
|
||||
}
|
||||
if (targetPrefillBlocked) target = "";
|
||||
}
|
||||
response.json({
|
||||
...options.adminService.getPublicConfig(),
|
||||
...publicConfig,
|
||||
target,
|
||||
targetPrefillBlocked,
|
||||
...(visitorNumber === null ? {} : { visitorNumber }),
|
||||
...(visitorTotal === null ? {} : { visitorTotal }),
|
||||
accelerationAvailable: acceleration.length > 0,
|
||||
accelerationRelays: acceleration.map((relay) => ({ id: relay.id, name: relay.name })),
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/skins", async (_request, response) => {
|
||||
response.setHeader("Cache-Control", "no-cache");
|
||||
response.json({
|
||||
skins: await options.skinRegistry?.list() ?? [],
|
||||
defaultSkinId: await options.skinRegistry?.getDefaultSkinId() ?? "builtin.light",
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/skins/:id/package", async (request, response) => {
|
||||
const id = typeof request.params.id === "string" ? request.params.id : "";
|
||||
const archive = await options.skinRegistry?.readArchive(id);
|
||||
if (!archive) {
|
||||
response.status(404).json({ ok: false, code: "SKIN_NOT_FOUND" });
|
||||
return;
|
||||
}
|
||||
response.setHeader("Cache-Control", "no-cache");
|
||||
response.setHeader("Content-Type", "application/octet-stream");
|
||||
response.setHeader("Content-Disposition", `attachment; filename="${id}.wskin"`);
|
||||
response.setHeader("X-Content-Type-Options", "nosniff");
|
||||
response.send(archive);
|
||||
});
|
||||
|
||||
app.get("/api/skins/:id/preview", async (request, response) => {
|
||||
const id = typeof request.params.id === "string" ? request.params.id : "";
|
||||
const preview = await options.skinRegistry?.readPreview(id);
|
||||
if (!preview) {
|
||||
response.status(404).end();
|
||||
return;
|
||||
}
|
||||
response.setHeader("Cache-Control", "public, max-age=300");
|
||||
response.setHeader("Content-Type", preview.mimeType);
|
||||
response.setHeader("X-Content-Type-Options", "nosniff");
|
||||
response.send(preview.bytes);
|
||||
});
|
||||
|
||||
app.post("/api/join-ticket", async (request, response) => {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
if (!request.is("application/json") || !isSameOrigin(request)) {
|
||||
@@ -165,6 +244,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
getCreatedSessions: () => voiceBridge.getCreatedCount(),
|
||||
getSessionSummaries: () => voiceBridge.getSessionSummaries(),
|
||||
terminateSession: (id) => voiceBridge.terminateSession(id),
|
||||
skinRegistry: options.skinRegistry,
|
||||
version: options.version,
|
||||
logFile: options.logFile,
|
||||
startedAt,
|
||||
@@ -211,6 +291,20 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readVisitorNumberCookie(header: string | undefined): number | null {
|
||||
if (!header) return null;
|
||||
for (const entry of header.split(";")) {
|
||||
const separator = entry.indexOf("=");
|
||||
if (separator < 0) continue;
|
||||
const name = entry.slice(0, separator).trim();
|
||||
if (name !== VISITOR_NUMBER_COOKIE) continue;
|
||||
const rawValue = entry.slice(separator + 1).trim();
|
||||
const number = Number.parseInt(rawValue, 10);
|
||||
return Number.isSafeInteger(number) && number > 0 ? number : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isSameOrigin(request: express.Request): boolean {
|
||||
const origin = request.header("origin");
|
||||
const host = request.header("host");
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { SessionAudioTransport } from "./session-audio.js";
|
||||
import { createAudioFlowStats } from "./audio-stats.js";
|
||||
import type { ServerMessage } from "../shared/server-messages.js";
|
||||
import type { TSVoiceData } from "./ts-client.js";
|
||||
|
||||
function fixture() {
|
||||
const state = { current: true, ready: true, now: 0, targets: null as number[] | null, disposed: 0,
|
||||
peer: null as { pushTeamSpeakVoice(data: TSVoiceData): void } | null };
|
||||
const audio = createAudioFlowStats();
|
||||
const packets: Buffer[] = [];
|
||||
const encoded: Buffer[] = [];
|
||||
const forwarded: Array<{ data: Buffer; codec: number; targets?: number[] }> = [];
|
||||
const notices: ServerMessage[] = [];
|
||||
const socket = { readyState: 1 as 0 | 1 | 2 | 3, bufferedAmount: 0, send: (packet: Buffer) => { packets.push(packet); } };
|
||||
const client = {
|
||||
sendVoice: (data: Buffer, codec: number) => { forwarded.push({ data, codec }); },
|
||||
sendWhisper: (data: Buffer, targets: number[], codec: number) => { forwarded.push({ data, codec, targets }); },
|
||||
};
|
||||
const encoder = {
|
||||
encode(frame: Buffer) { encoded.push(frame); state.now += 3; return Buffer.from([9, 8, 7]); },
|
||||
dispose() { state.disposed++; },
|
||||
};
|
||||
const transport = new SessionAudioTransport({
|
||||
audio, socket, client, isCurrent: () => state.current, isReady: () => state.ready,
|
||||
selfId: () => 1, peer: () => state.peer, whisperTargets: () => state.targets,
|
||||
sendJson: message => { notices.push(message); },
|
||||
}, encoder, () => state.now);
|
||||
const remote = (clientId = 513) => ({ clientId, codec: 4, data: Buffer.from([11, 12, 13]) });
|
||||
return { transport, audio, state, socket, client, encoder, packets, encoded, forwarded, notices, remote };
|
||||
}
|
||||
|
||||
test("PCM framing preserves codec, whisper routing and timing counters", () => {
|
||||
const f = fixture();
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
f.state.now = 20;
|
||||
f.state.targets = [7, 8];
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.deepEqual(f.forwarded.map(({ codec, targets }) => ({ codec, targets })), [
|
||||
{ codec: 4, targets: undefined }, { codec: 4, targets: [7, 8] },
|
||||
]);
|
||||
assert.equal(f.audio.ingressFrames, 2);
|
||||
assert.equal(f.audio.ingressMaxGapMs, 20);
|
||||
assert.equal(f.audio.tsSendMaxGapMs, 20);
|
||||
assert.equal(f.audio.tsEncodeMaxMs, 3);
|
||||
});
|
||||
|
||||
test("invalid PCM is rejected and reconnecting sessions do not encode audio", () => {
|
||||
const f = fixture();
|
||||
f.transport.receivePcm(Buffer.alloc(1_919));
|
||||
f.transport.receivePcm(Buffer.alloc(1_921));
|
||||
assert.equal(f.notices.length, 2);
|
||||
assert.deepEqual(f.notices[0], { type: "error", error: { code: "INVALID_AUDIO_FRAME", message: "音频帧格式无效", recoverable: false } });
|
||||
f.state.ready = false;
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
f.transport.receiveWebRtc(Buffer.from([1]), 4);
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
assert.equal(f.audio.ingressDroppedFrames, 3);
|
||||
assert.equal(f.encoded.length, 0);
|
||||
assert.equal(f.forwarded.length, 0);
|
||||
assert.equal(f.packets.length, 0);
|
||||
});
|
||||
|
||||
test("WebRTC ingress excludes queued PCM and fallback re-enables PCM", () => {
|
||||
const f = fixture();
|
||||
f.state.peer = { pushTeamSpeakVoice() {} };
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
const opus = Buffer.from([3, 2, 1]);
|
||||
f.transport.receiveWebRtc(opus, 5);
|
||||
assert.equal(f.encoded.length, 0);
|
||||
assert.deepEqual(f.forwarded, [{ data: opus, codec: 5 }]);
|
||||
assert.equal(f.audio.ingressDroppedFrames, 1);
|
||||
f.state.peer = null;
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.equal(f.encoded.length, 1);
|
||||
assert.equal(f.audio.tsSendFrames, 2);
|
||||
});
|
||||
|
||||
test("TeamSpeak packets keep the three-byte header and exclude self playback", () => {
|
||||
const f = fixture();
|
||||
f.transport.receiveTeamSpeak(f.remote(1));
|
||||
const remote = f.remote();
|
||||
f.transport.receiveTeamSpeak(remote);
|
||||
remote.data.fill(0);
|
||||
assert.deepEqual([...f.packets[0]!], [4, 2, 1, 11, 12, 13]);
|
||||
assert.equal(f.audio.tsReceiveFrames, 2);
|
||||
assert.equal(f.audio.egressFrames, 1);
|
||||
assert.deepEqual(f.audio.egressFramesByClient, { "513": 1 });
|
||||
});
|
||||
|
||||
test("backpressure drops bursts above 4096 bytes and resumes without a retained queue", () => {
|
||||
const f = fixture();
|
||||
f.socket.bufferedAmount = 4_096;
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
f.socket.bufferedAmount = 4_097;
|
||||
for (let i = 0; i < 100; i++) f.transport.receiveTeamSpeak(f.remote());
|
||||
assert.equal(f.packets.length, 1);
|
||||
assert.equal(f.audio.egressDroppedFrames, 100);
|
||||
f.socket.bufferedAmount = 0;
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
assert.equal(f.packets.length, 2);
|
||||
assert.equal(f.audio.egressPeakBufferedBytes, 4_097);
|
||||
});
|
||||
|
||||
test("WebRTC downlink owns egress without a duplicate WebSocket packet", () => {
|
||||
const f = fixture();
|
||||
const received: TSVoiceData[] = [];
|
||||
f.state.peer = { pushTeamSpeakVoice: data => { received.push(data); } };
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
assert.equal(received.length, 1);
|
||||
assert.equal(f.packets.length, 0);
|
||||
f.state.peer = null;
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
assert.equal(received.length, 1);
|
||||
assert.equal(f.packets.length, 1);
|
||||
});
|
||||
|
||||
test("encoding failures are counted and reported at most once per five seconds", t => {
|
||||
const f = fixture();
|
||||
t.mock.method(f.encoder, "encode", () => { throw new Error("Codec failed"); });
|
||||
for (const now of [0, 1, 4_999, 5_000]) { f.state.now = now; f.transport.receivePcm(Buffer.alloc(1_920)); }
|
||||
assert.equal(f.audio.tsSendErrors, 4);
|
||||
assert.equal(f.audio.ingressDroppedFrames, 4);
|
||||
assert.equal(f.forwarded.length, 0);
|
||||
assert.equal(f.notices.length, 2);
|
||||
assert.deepEqual(f.notices[0], { type: "audioError", code: "AUDIO_ENCODER_UNAVAILABLE", detail: "Opus encoder unavailable" });
|
||||
t.mock.restoreAll();
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.equal(f.audio.tsSendFrames, 1);
|
||||
});
|
||||
|
||||
test("SDK and downlink failures cannot escape the audio callbacks", t => {
|
||||
const f = fixture();
|
||||
t.mock.method(f.client, "sendVoice", () => { throw new Error("SDK disconnected"); });
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.equal(f.audio.tsSendErrors, 1);
|
||||
assert.equal(f.notices.length, 0, "SDK failure must not be reported as an encoder failure");
|
||||
t.mock.method(f.socket, "send", () => { throw new Error("Socket closed"); });
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
f.state.peer = { pushTeamSpeakVoice() { throw new Error("Peer closed"); } };
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
assert.equal(f.audio.egressDroppedFrames, 2);
|
||||
});
|
||||
|
||||
test("removed sessions and closed sockets ignore late frames without changing counters", () => {
|
||||
const f = fixture();
|
||||
const baseline = structuredClone(f.audio);
|
||||
const lateFrames = () => {
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
f.transport.receiveWebRtc(Buffer.from([1]), 4);
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
};
|
||||
f.state.current = false;
|
||||
lateFrames();
|
||||
f.state.current = true;
|
||||
f.socket.readyState = 3;
|
||||
lateFrames();
|
||||
assert.deepEqual(f.audio, baseline);
|
||||
assert.equal(f.encoded.length, 0);
|
||||
});
|
||||
|
||||
test("codec cleanup is idempotent even if disposal throws", t => {
|
||||
const f = fixture();
|
||||
let attempts = 0;
|
||||
t.mock.method(f.encoder, "dispose", () => { attempts++; throw new Error("Already closed"); });
|
||||
f.transport.close();
|
||||
f.transport.close();
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
f.transport.receiveWebRtc(Buffer.from([1]), 4);
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
assert.equal(attempts, 1);
|
||||
assert.equal(f.audio.ingressFrames, 0);
|
||||
assert.equal(f.audio.tsReceiveFrames, 0);
|
||||
});
|
||||
|
||||
test("invalid SDK speaker IDs and codecs cannot throw while packing the header", () => {
|
||||
const f = fixture();
|
||||
for (const clientId of [-1, 65_536, NaN]) f.transport.receiveTeamSpeak(f.remote(clientId));
|
||||
for (const codec of [-1, 256, NaN]) f.transport.receiveTeamSpeak({ ...f.remote(), codec });
|
||||
assert.equal(f.audio.egressDroppedFrames, 6);
|
||||
assert.equal(f.packets.length, 0);
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
import { WebSocket } from "ws";
|
||||
import type { ServerMessage } from "../shared/server-messages.js";
|
||||
import type { AudioFlowStats } from "./audio-stats.js";
|
||||
import type { TSClient, TSVoiceData } from "./ts-client.js";
|
||||
import type { WebRtcAudioSession } from "./webrtc-audio.js";
|
||||
|
||||
const AUDIO_FRAME_BYTES = 1_920; // 20 ms of 48 kHz mono Int16 PCM.
|
||||
// Keep the established byte guard; the browser also bounds playback by time.
|
||||
const MAX_BUFFERED_BYTES = 4_096;
|
||||
|
||||
export interface VoiceEncoder {
|
||||
encode(frame: Buffer): Buffer;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export interface SessionAudioOptions {
|
||||
audio: AudioFlowStats;
|
||||
socket: Pick<WebSocket, "readyState" | "bufferedAmount"> & { send(packet: Buffer): void };
|
||||
client: Pick<TSClient, "sendVoice" | "sendWhisper">;
|
||||
isCurrent(): boolean;
|
||||
isReady(): boolean;
|
||||
selfId(): number;
|
||||
peer(): Pick<WebRtcAudioSession, "pushTeamSpeakVoice"> | null;
|
||||
whisperTargets(): readonly number[] | null;
|
||||
sendJson(message: ServerMessage): void;
|
||||
}
|
||||
|
||||
/** A session owns one encoder and one active audio route in each direction. */
|
||||
export class SessionAudioTransport {
|
||||
private encoder: VoiceEncoder | null;
|
||||
private closed = false;
|
||||
private warnedAt: number | null = null;
|
||||
|
||||
constructor(private readonly options: SessionAudioOptions, encoder: VoiceEncoder, private readonly clock: () => number = Date.now) {
|
||||
this.encoder = encoder;
|
||||
}
|
||||
|
||||
private isCurrent(): boolean {
|
||||
return !this.closed && this.options.isCurrent() && this.options.socket.readyState === WebSocket.OPEN;
|
||||
}
|
||||
|
||||
private recordIngress(): void {
|
||||
const stats = this.options.audio;
|
||||
const now = this.clock();
|
||||
if (stats.ingressLastAt !== null) stats.ingressMaxGapMs = Math.max(stats.ingressMaxGapMs, now - stats.ingressLastAt);
|
||||
stats.ingressFirstAt ??= now;
|
||||
stats.ingressLastAt = now;
|
||||
stats.ingressFrames++;
|
||||
}
|
||||
|
||||
private sendVoice(data: Buffer, codec: number): void {
|
||||
const stats = this.options.audio;
|
||||
try {
|
||||
const targets = this.options.whisperTargets();
|
||||
if (targets?.length) this.options.client.sendWhisper(data, [...targets], codec);
|
||||
else this.options.client.sendVoice(data, codec);
|
||||
const now = this.clock();
|
||||
if (stats.tsSendLastAt !== null) stats.tsSendMaxGapMs = Math.max(stats.tsSendMaxGapMs, now - stats.tsSendLastAt);
|
||||
stats.tsSendFirstAt ??= now;
|
||||
stats.tsSendLastAt = now;
|
||||
stats.tsSendFrames++;
|
||||
} catch {
|
||||
stats.tsSendErrors++;
|
||||
}
|
||||
}
|
||||
|
||||
private reportEncoderFailure(): void {
|
||||
const now = this.clock();
|
||||
if (this.warnedAt !== null && now - this.warnedAt < 5_000) return;
|
||||
this.warnedAt = now;
|
||||
try {
|
||||
this.options.sendJson({ type: "audioError", code: "AUDIO_ENCODER_UNAVAILABLE", detail: "Opus encoder unavailable" });
|
||||
} catch { /* the socket may have closed while reporting the failure */ }
|
||||
}
|
||||
|
||||
receivePcm(frame: Buffer): void {
|
||||
if (!this.isCurrent()) return;
|
||||
const stats = this.options.audio;
|
||||
if (frame.length !== AUDIO_FRAME_BYTES) {
|
||||
stats.ingressDroppedFrames++;
|
||||
this.options.sendJson({ type: "error", error: { code: "INVALID_AUDIO_FRAME", message: "音频帧格式无效", recoverable: false } });
|
||||
return;
|
||||
}
|
||||
// Late TCP frames from before a WebRTC switch must not duplicate RTP audio.
|
||||
if (!this.options.isReady() || this.options.peer()) { stats.ingressDroppedFrames++; return; }
|
||||
this.recordIngress();
|
||||
const startedAt = this.clock();
|
||||
let encoded: Buffer;
|
||||
try {
|
||||
if (!this.encoder) throw new Error("Encoder unavailable");
|
||||
encoded = this.encoder.encode(frame);
|
||||
stats.tsEncodeMaxMs = Math.max(stats.tsEncodeMaxMs, this.clock() - startedAt);
|
||||
} catch {
|
||||
stats.tsSendErrors++;
|
||||
stats.ingressDroppedFrames++;
|
||||
this.reportEncoderFailure();
|
||||
return;
|
||||
}
|
||||
this.sendVoice(encoded, 4);
|
||||
}
|
||||
|
||||
receiveWebRtc(data: Buffer, codec: number): void {
|
||||
if (!this.isCurrent() || !this.options.isReady()) return;
|
||||
this.recordIngress();
|
||||
this.sendVoice(data, codec);
|
||||
}
|
||||
|
||||
receiveTeamSpeak(data: TSVoiceData): void {
|
||||
if (!this.isCurrent() || !this.options.isReady()) return;
|
||||
const stats = this.options.audio;
|
||||
const now = this.clock();
|
||||
if (stats.tsReceiveLastAt !== null) stats.tsReceiveMaxGapMs = Math.max(stats.tsReceiveMaxGapMs, now - stats.tsReceiveLastAt);
|
||||
stats.tsReceiveFirstAt ??= now;
|
||||
stats.tsReceiveLastAt = now;
|
||||
stats.tsReceiveFrames++;
|
||||
if (data.clientId === this.options.selfId()) return;
|
||||
if (!Number.isInteger(data.clientId) || data.clientId < 1 || data.clientId > 65_535
|
||||
|| !Number.isInteger(data.codec) || data.codec < 0 || data.codec > 255 || !Buffer.isBuffer(data.data)) {
|
||||
stats.egressDroppedFrames++;
|
||||
return;
|
||||
}
|
||||
if (stats.egressLastAt !== null) stats.egressMaxGapMs = Math.max(stats.egressMaxGapMs, now - stats.egressLastAt);
|
||||
stats.egressFirstAt ??= now;
|
||||
stats.egressLastAt = now;
|
||||
const key = String(data.clientId);
|
||||
stats.egressFramesByClient[key] = (stats.egressFramesByClient[key] ?? 0) + 1;
|
||||
const peer = this.options.peer();
|
||||
if (peer) {
|
||||
try { peer.pushTeamSpeakVoice(data); stats.egressFrames++; }
|
||||
catch { stats.egressDroppedFrames++; }
|
||||
return;
|
||||
}
|
||||
const bufferedBytes = this.options.socket.bufferedAmount;
|
||||
stats.egressPeakBufferedBytes = Math.max(stats.egressPeakBufferedBytes, bufferedBytes);
|
||||
if (bufferedBytes > MAX_BUFFERED_BYTES) { stats.egressDroppedFrames++; return; }
|
||||
const packet = Buffer.allocUnsafe(3 + data.data.length);
|
||||
packet[0] = data.codec;
|
||||
packet.writeUInt16BE(data.clientId, 1);
|
||||
data.data.copy(packet, 3);
|
||||
try {
|
||||
this.options.socket.send(packet);
|
||||
stats.egressFrames++;
|
||||
const sentAt = this.clock();
|
||||
if (stats.egressSentLastAt !== null) stats.egressSentMaxGapMs = Math.max(stats.egressSentMaxGapMs, sentAt - stats.egressSentLastAt);
|
||||
stats.egressSentFirstAt ??= sentAt;
|
||||
stats.egressSentLastAt = sentAt;
|
||||
} catch { stats.egressDroppedFrames++; }
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
const encoder = this.encoder;
|
||||
this.encoder = null;
|
||||
try { encoder?.dispose(); } catch { /* other session resources must still be released */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { EventEmitter } from "node:events";
|
||||
import type { ClientInfo } from "@echosixhiya/teamspeak-client";
|
||||
import type { ServerMessage } from "../shared/server-messages.js";
|
||||
import { SessionEventCoordinator, type SessionDirectoryState } from "./session-events.js";
|
||||
import type { TSDirectorySnapshot } from "./ts-client.js";
|
||||
|
||||
const member = (id: number, channelID = 1n): ClientInfo => ({ id, channelID, nickname: `Member ${id}`, uid: `uid-${id}`, type: 1, serverGroups: [] });
|
||||
const channel = (id: bigint, name: string) => ({ id, parentID: 0n, order: 0n, name, description: "" });
|
||||
const snapshot = (...clients: ClientInfo[]): TSDirectorySnapshot => ({ channels: [channel(1n, "Lobby"), channel(2n, "Room")], clients });
|
||||
|
||||
function fixture(t: TestContext) {
|
||||
const phase = { current: true, accepting: true, published: false, connected: false, selfId: 1, channelId: 1n };
|
||||
const state: SessionDirectoryState = { channelTree: [], members: new Map(), avatarCache: new Map(), whisperTargetIds: new Set(), whisperActive: false };
|
||||
const messages: ServerMessage[] = [];
|
||||
const events: Array<{ kind: string; message: string }> = [];
|
||||
const callbacks: Array<{ kind: string; value?: unknown }> = [];
|
||||
const client = Object.assign(new EventEmitter(), {
|
||||
getClientId: () => phase.selfId, getChannelId: () => phase.channelId,
|
||||
getClientAvatar: async () => null,
|
||||
});
|
||||
const coordinator = new SessionEventCoordinator({
|
||||
state, client, nickname: "Self", requestedChannel: "Lobby",
|
||||
isCurrent: () => phase.current, acceptsDirectory: () => phase.accepting,
|
||||
isPublished: () => phase.published, isConnected: () => phase.connected,
|
||||
sendJson: message => messages.push(message), addEvent: (kind, message) => events.push({ kind, message }),
|
||||
onDirectoryReady: () => callbacks.push({ kind: "ready" }),
|
||||
onClientLeave: id => callbacks.push({ kind: "leave", value: id }),
|
||||
onClientMove: (id, channelId) => callbacks.push({ kind: "move", value: [id, channelId] }),
|
||||
onNotification: value => callbacks.push({ kind: "notification", value }),
|
||||
onVoice: value => callbacks.push({ kind: "voice", value }),
|
||||
onKick: value => callbacks.push({ kind: "kick", value }),
|
||||
onDisconnect: value => callbacks.push({ kind: "disconnect", value }),
|
||||
onAvatarError: (_id, _uid, value) => callbacks.push({ kind: "avatar-error", value }),
|
||||
});
|
||||
t.after(() => coordinator.close());
|
||||
return { phase, state, messages, events, callbacks, client, coordinator };
|
||||
}
|
||||
|
||||
test("welcome events reconcile before publication and self follows the connected SDK channel", t => {
|
||||
const f = fixture(t);
|
||||
f.phase.channelId = 2n;
|
||||
f.client.emit("clientLeave", { id: 2 });
|
||||
f.client.emit("clientEnter", member(3));
|
||||
f.client.emit("clientUpdated", { ...member(3), inputMuted: true });
|
||||
f.client.emit("directorySnapshot", snapshot(member(1), member(2)));
|
||||
f.coordinator.syncSelf();
|
||||
assert.equal(f.coordinator.ready, true);
|
||||
assert.equal(f.coordinator.selfId, 1);
|
||||
assert.deepEqual([...f.state.members.keys()], [1, 3]);
|
||||
assert.equal(f.state.members.get(3)?.inputMuted, true);
|
||||
assert.equal(f.state.channelTree.find(item => item.id === "2")?.members?.some(item => item.id === 1), true);
|
||||
assert.equal(f.messages.length, 0);
|
||||
assert.equal(f.events.length, 0);
|
||||
assert.equal(f.callbacks.filter(item => item.kind === "ready").length, 1);
|
||||
f.phase.published = true;
|
||||
f.client.emit("clientUpdated", { ...member(3), nickname: "Renamed" });
|
||||
assert.equal(f.state.members.get(3)?.nickname, "Renamed");
|
||||
assert.equal(f.messages.at(-1)?.type, "channelList");
|
||||
});
|
||||
|
||||
test("live movement and departure update directory, sharing callbacks and whisper targets", t => {
|
||||
const f = fixture(t);
|
||||
f.client.emit("directorySnapshot", snapshot(member(1), member(2)));
|
||||
f.coordinator.syncSelf(); f.phase.published = true;
|
||||
for (const id of [1, 2, 99]) f.state.whisperTargetIds.add(id);
|
||||
f.state.whisperActive = true;
|
||||
f.client.emit("clientUpdated", { ...member(2), away: true });
|
||||
assert.deepEqual([...f.state.whisperTargetIds], [2]);
|
||||
assert.deepEqual(f.messages.find(message => message.type === "whisperTargets"), { type: "whisperTargets", targetIds: [2], active: true });
|
||||
f.client.emit("clientMoved", { id: 2, targetChannelID: 0n });
|
||||
assert.equal(f.callbacks.some(item => item.kind === "move"), false);
|
||||
f.client.emit("clientMoved", { id: 2, targetChannelID: 2n });
|
||||
assert.deepEqual(f.callbacks.find(item => item.kind === "move")?.value, [2, 2n]);
|
||||
assert.equal(f.state.channelTree.find(item => item.id === "2")?.members?.some(item => item.id === 2), true);
|
||||
f.client.emit("clientLeave", { id: 2 });
|
||||
f.client.emit("clientLeave", { id: 2 });
|
||||
assert.equal(f.state.members.has(2), false);
|
||||
assert.equal(f.state.whisperActive, false);
|
||||
assert.equal(f.state.whisperTargetIds.size, 0);
|
||||
assert.equal(f.messages.filter(message => message.type === "memberLeave").length, 1);
|
||||
assert.deepEqual(f.events.map(item => item.kind), ["moved", "left"]);
|
||||
});
|
||||
|
||||
test("channel changes preserve large identifiers and publish only actual create, rename and delete events", t => {
|
||||
const f = fixture(t);
|
||||
f.client.emit("directorySnapshot", snapshot(member(1)));
|
||||
f.coordinator.syncSelf(); f.phase.published = true;
|
||||
const large = 9_007_199_254_740_993n;
|
||||
f.client.emit("directorySnapshot", { channels: [channel(1n, "Renamed"), channel(large, "Large")], clients: [member(3, large)] });
|
||||
assert.deepEqual(f.events.map(item => item.kind), ["moved", "joined", "left"]);
|
||||
assert.equal(f.state.channelTree[1]?.id, String(large));
|
||||
assert.equal(f.state.channelTree[1]?.members?.[0]?.id, 3);
|
||||
assert.doesNotThrow(() => JSON.stringify(f.messages));
|
||||
f.events.length = 0;
|
||||
f.client.emit("directorySnapshot", { channels: [channel(1n, "Renamed"), channel(large, "Large")], clients: [] });
|
||||
assert.equal(f.events.length, 0);
|
||||
});
|
||||
|
||||
test("reset rejects backoff events and close detaches only owned listeners including captured callbacks", t => {
|
||||
const f = fixture(t);
|
||||
f.client.emit("directorySnapshot", snapshot(member(1), member(2)));
|
||||
const captured = f.client.listeners("clientEnter")[0]!;
|
||||
let externalEvents = 0;
|
||||
f.client.on("clientEnter", () => externalEvents++);
|
||||
f.state.avatarCache.set("uid-2", "cached");
|
||||
f.coordinator.reset(); f.phase.accepting = false;
|
||||
f.client.emit("directorySnapshot", snapshot(member(9)));
|
||||
assert.equal(f.coordinator.ready, false);
|
||||
assert.equal(f.state.members.size, 0);
|
||||
assert.equal(f.state.avatarCache.size, 0);
|
||||
f.phase.accepting = true;
|
||||
f.client.emit("directorySnapshot", snapshot(member(1)));
|
||||
assert.equal(f.state.members.has(9), false);
|
||||
f.coordinator.close(); f.coordinator.close();
|
||||
f.client.emit("clientEnter", member(10));
|
||||
captured(member(11));
|
||||
assert.equal(f.state.members.size, 0);
|
||||
assert.equal(f.client.listenerCount("clientEnter"), 1);
|
||||
assert.equal(externalEvents, 1);
|
||||
assert.equal(f.client.listenerCount("directorySnapshot"), 0);
|
||||
});
|
||||
|
||||
test("chat routing, poke and forwarded SDK events retain their payloads and stop with the session", t => {
|
||||
const f = fixture(t);
|
||||
const chat = { invokerName: "Speaker", invokerId: 2, invokerUid: "uid-2", message: "Hello" };
|
||||
f.client.emit("textMessage", { ...chat, targetMode: 2, targetId: 0n });
|
||||
f.phase.channelId = 2n;
|
||||
f.client.emit("textMessage", { ...chat, targetMode: 1, targetId: 9_007_199_254_740_993n });
|
||||
f.client.emit("textMessage", { ...chat, targetMode: 3, targetId: 0n });
|
||||
const routed = f.messages.filter(message => message.type === "chatMessage");
|
||||
assert.deepEqual(routed.map(message => [message.scope, message.targetId]), [["channel", "1"], ["private", "9007199254740993"], ["server", undefined]]);
|
||||
f.client.emit("poked", { invokerID: 2, invokerUID: "uid-2", invokerName: "Speaker", message: "Wake up" });
|
||||
const voice = { clientId: 2, codec: 4, data: Buffer.from([1]) };
|
||||
const notification = { name: "stream", params: { id: "a" } };
|
||||
f.client.emit("voiceData", voice); f.client.emit("rawNotification", notification); f.client.emit("disconnected");
|
||||
assert.equal(f.events.at(-1)?.kind, "poke");
|
||||
assert.equal(f.callbacks.find(item => item.kind === "voice")?.value, voice);
|
||||
assert.equal(f.callbacks.find(item => item.kind === "notification")?.value, notification);
|
||||
f.phase.current = false;
|
||||
f.client.emit("textMessage", { ...chat, targetMode: 2 });
|
||||
f.client.emit("poked", {}); f.client.emit("voiceData", voice); f.client.emit("rawNotification", notification); f.client.emit("disconnected");
|
||||
assert.equal(f.messages.length, 4);
|
||||
assert.equal(f.callbacks.length, 3);
|
||||
});
|
||||
@@ -0,0 +1,253 @@
|
||||
import type { ClientInfo } from "@echosixhiya/teamspeak-client";
|
||||
import type { EventEmitter } from "node:events";
|
||||
import type { WebSpeakError } from "../errors.js";
|
||||
import type { ChannelInfo, ChannelMember } from "../shared/voice-models.js";
|
||||
import type { ServerMessage } from "../shared/server-messages.js";
|
||||
import { DirectorySynchronizer } from "./directory-sync.js";
|
||||
import { mapChannelTree, normalizeDirectorySnapshot } from "./directory-view.js";
|
||||
import { MemberAvatarLoader } from "./member-avatars.js";
|
||||
import type { TSClient, TSChatMessage, TSDirectoryClient, TSDirectorySnapshot, TSRawNotification, TSVoiceData } from "./ts-client.js";
|
||||
|
||||
export interface SessionDirectoryState {
|
||||
channelTree: ChannelInfo[];
|
||||
members: Map<number, ChannelMember & { uid: string }>;
|
||||
avatarCache: Map<string, string | null>;
|
||||
whisperTargetIds: Set<number>;
|
||||
whisperActive: boolean;
|
||||
}
|
||||
|
||||
interface SdkEvents {
|
||||
directorySnapshot: TSDirectorySnapshot;
|
||||
clientEnter: ClientInfo;
|
||||
clientLeave: { id: number };
|
||||
clientMoved: { id: number; targetChannelID?: bigint };
|
||||
clientUpdated: TSDirectoryClient;
|
||||
directoryClientsSnapshot: TSDirectoryClient[];
|
||||
rawNotification: TSRawNotification;
|
||||
voiceData: TSVoiceData;
|
||||
textMessage: TSChatMessage;
|
||||
poked: { invokerID: number; invokerUID: string; invokerName: string; message: string };
|
||||
kicked: WebSpeakError;
|
||||
disconnected: Error | undefined;
|
||||
}
|
||||
|
||||
export interface SessionEventOptions {
|
||||
state: SessionDirectoryState;
|
||||
client: Pick<TSClient, "getClientId" | "getChannelId" | "getClientAvatar"> & Partial<Pick<TSClient, "refreshDirectoryClients">> & Pick<EventEmitter, "on" | "off">;
|
||||
nickname: string;
|
||||
requestedChannel?: string;
|
||||
isCurrent(): boolean;
|
||||
acceptsDirectory(): boolean;
|
||||
isPublished(): boolean;
|
||||
isConnected(): boolean;
|
||||
sendJson(message: ServerMessage): void;
|
||||
addEvent(kind: "joined" | "left" | "moved" | "poke", message: string): void;
|
||||
onDirectoryReady(): void;
|
||||
onClientLeave(id: number): void;
|
||||
onClientMove(id: number, channelId: bigint): void;
|
||||
onNotification(notification: TSRawNotification): void;
|
||||
onVoice(data: TSVoiceData): void;
|
||||
onKick(error: WebSpeakError): void;
|
||||
onDisconnect(error?: Error): void;
|
||||
onAvatarError(id: number, uid: string, error: unknown): void;
|
||||
}
|
||||
|
||||
/** SDK listeners, directory projection and optional work owned by one session. */
|
||||
export class SessionEventCoordinator {
|
||||
private readonly directory = new DirectorySynchronizer();
|
||||
private readonly avatars: MemberAvatarLoader;
|
||||
private readonly subscriptions: Array<() => void> = [];
|
||||
private closed = false;
|
||||
private clientId = 0;
|
||||
private channelId = 0n;
|
||||
private directoryStatusRefreshTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
constructor(private readonly options: SessionEventOptions) {
|
||||
const { state, client } = options;
|
||||
this.avatars = new MemberAvatarLoader({
|
||||
members: state.members, cache: state.avatarCache,
|
||||
isCurrent: () => this.isCurrent() && options.isConnected(),
|
||||
load: (id, uid) => client.getClientAvatar(id, uid),
|
||||
publish: (id, uid, avatar) => options.sendJson({ type: "memberAvatar", id, uid, avatar }),
|
||||
onError: options.onAvatarError,
|
||||
});
|
||||
// Subscribe before connect(): welcome events may precede the first snapshot.
|
||||
this.listenDirectory("directorySnapshot", snapshot => {
|
||||
const previousChannels = state.channelTree;
|
||||
this.directory.applySnapshot(snapshot);
|
||||
this.refresh();
|
||||
this.trackChannelEvents(previousChannels);
|
||||
options.onDirectoryReady();
|
||||
this.publishDirectory();
|
||||
this.avatars.schedule();
|
||||
});
|
||||
this.listenDirectory("clientEnter", info => {
|
||||
const candidateSelfId = client.getClientId();
|
||||
if (candidateSelfId > 0 && info.id === candidateSelfId) {
|
||||
this.clientId = candidateSelfId;
|
||||
if (info.channelID !== undefined && info.channelID !== 0n) this.channelId = info.channelID;
|
||||
}
|
||||
const wasKnown = state.members.has(info.id);
|
||||
this.directory.applyClientEnter(info);
|
||||
this.refresh();
|
||||
if (this.directoryStatusRefreshTimer) clearTimeout(this.directoryStatusRefreshTimer);
|
||||
this.directoryStatusRefreshTimer = setTimeout(() => {
|
||||
this.directoryStatusRefreshTimer = null;
|
||||
void options.client.refreshDirectoryClients?.();
|
||||
}, 300);
|
||||
if (options.isPublished()) {
|
||||
this.publishDirectory();
|
||||
if (!wasKnown) options.sendJson({ type: "memberEnter", id: info.id, nickname: info.nickname, uid: info.uid, isSelf: info.id === this.clientId });
|
||||
if (!wasKnown && info.id !== this.clientId) options.addEvent("joined", `${info.nickname || "未知用户"} 加入了服务器`);
|
||||
this.avatars.schedule();
|
||||
}
|
||||
});
|
||||
this.listenDirectory("clientLeave", info => {
|
||||
options.onClientLeave(info.id);
|
||||
const member = state.members.get(info.id);
|
||||
this.directory.applyClientLeave(info.id);
|
||||
this.refresh();
|
||||
if (options.isPublished() && member) {
|
||||
options.sendJson({ type: "memberLeave", id: info.id });
|
||||
this.publishDirectory();
|
||||
if (info.id !== this.clientId) options.addEvent("left", `${member.nickname || "用户"} 离开了服务器`);
|
||||
}
|
||||
});
|
||||
this.listenDirectory("clientMoved", info => {
|
||||
if (info.targetChannelID === undefined || info.targetChannelID === 0n) return;
|
||||
options.onClientMove(info.id, info.targetChannelID);
|
||||
const member = state.members.get(info.id);
|
||||
if (info.id === this.clientId) this.channelId = info.targetChannelID;
|
||||
this.directory.applyClientMoved(info.id, info.targetChannelID);
|
||||
this.refresh();
|
||||
if (options.isPublished()) {
|
||||
this.publishDirectory();
|
||||
if (info.id !== this.clientId) options.addEvent("moved", `${member?.nickname || "用户"} 移动到了其他频道`);
|
||||
}
|
||||
});
|
||||
this.listenDirectory("clientUpdated", info => {
|
||||
this.directory.applyClientUpdated(info);
|
||||
this.refresh();
|
||||
this.publishDirectory();
|
||||
});
|
||||
this.listenDirectory("directoryClientsSnapshot", clients => {
|
||||
this.directory.applyClientListSnapshot(clients);
|
||||
this.refresh();
|
||||
this.publishDirectory();
|
||||
});
|
||||
this.listen("rawNotification", options.onNotification);
|
||||
this.listen("voiceData", options.onVoice);
|
||||
this.listen("textMessage", message => {
|
||||
const scope = message.targetMode === 1 ? "private" : message.targetMode === 2 ? "channel" : "server";
|
||||
const targetId = message.targetId ?? 0n;
|
||||
// Channel notifications can omit target; bind them to the current channel.
|
||||
const effectiveTargetId = scope === "channel" && targetId === 0n ? client.getChannelId() : targetId;
|
||||
options.sendJson({ type: "chatMessage", scope,
|
||||
...(effectiveTargetId !== 0n ? { targetId: String(effectiveTargetId) } : {}),
|
||||
senderUid: message.invokerUid, timestamp: Date.now(), invokerName: message.invokerName,
|
||||
invokerId: message.invokerId, message: message.message,
|
||||
});
|
||||
});
|
||||
this.listen("poked", event => {
|
||||
options.sendJson({ type: "pokeReceived", invokerId: event.invokerID, invokerUid: event.invokerUID, invokerName: event.invokerName, message: event.message, timestamp: Date.now() });
|
||||
options.addEvent("poke", `${event.invokerName || "用户"} 戳了你一下`);
|
||||
});
|
||||
this.listen("kicked", options.onKick);
|
||||
this.listen("disconnected", options.onDisconnect);
|
||||
}
|
||||
|
||||
get ready(): boolean { return this.directory.ready; }
|
||||
get selfId(): number { return this.clientId; }
|
||||
|
||||
private isCurrent(): boolean { return !this.closed && this.options.isCurrent(); }
|
||||
|
||||
private listen<K extends keyof SdkEvents>(name: K, handler: (data: SdkEvents[K]) => void): void {
|
||||
const listener = (data: SdkEvents[K]) => { if (this.isCurrent()) handler(data); };
|
||||
this.options.client.on(name, listener);
|
||||
this.subscriptions.push(() => this.options.client.off(name, listener));
|
||||
}
|
||||
|
||||
private listenDirectory<K extends keyof SdkEvents>(name: K, handler: (data: SdkEvents[K]) => void): void {
|
||||
this.listen(name, data => { if (this.options.acceptsDirectory()) handler(data); });
|
||||
}
|
||||
|
||||
syncSelf(): void {
|
||||
if (!this.isCurrent()) return;
|
||||
this.clientId = this.options.client.getClientId();
|
||||
const channelId = this.options.client.getChannelId();
|
||||
if (channelId !== 0n) this.channelId = channelId;
|
||||
this.refresh();
|
||||
if (this.clientId > 0 && !this.options.state.members.has(this.clientId)) {
|
||||
this.directory.applyClientEnter({ id: this.clientId, nickname: this.options.nickname, channelID: this.channelId, uid: "", type: 1, serverGroups: [] });
|
||||
this.refresh();
|
||||
}
|
||||
}
|
||||
|
||||
scheduleAvatars(): void { this.avatars.schedule(); }
|
||||
|
||||
private refresh(): void {
|
||||
const snapshot = this.directory.getSnapshot();
|
||||
if (!snapshot) return;
|
||||
const { state, client } = this.options;
|
||||
const previousTargets = [...state.whisperTargetIds].sort((a, b) => a - b);
|
||||
const selfId = this.clientId || client.getClientId();
|
||||
const sdkChannelId = client.getChannelId();
|
||||
if (this.channelId === 0n && sdkChannelId !== 0n) this.channelId = sdkChannelId;
|
||||
const normalized = normalizeDirectorySnapshot(snapshot, selfId, this.channelId, this.options.nickname, this.options.requestedChannel);
|
||||
state.channelTree = mapChannelTree(normalized, state.avatarCache);
|
||||
state.members.clear();
|
||||
for (const member of normalized.clients) {
|
||||
const avatar = member.uid ? state.avatarCache.get(member.uid) : undefined;
|
||||
state.members.set(member.id, { id: member.id, nickname: member.nickname, uid: member.uid,
|
||||
...(avatar ? { avatar } : {}), away: member.away, awayMessage: member.awayMessage,
|
||||
inputMuted: member.inputMuted, outputMuted: member.outputMuted, channelCommander: member.channelCommander,
|
||||
});
|
||||
}
|
||||
for (const id of state.whisperTargetIds) {
|
||||
if (!state.members.has(id) || id === selfId) state.whisperTargetIds.delete(id);
|
||||
}
|
||||
if (!state.whisperTargetIds.size) state.whisperActive = false;
|
||||
const nextTargets = [...state.whisperTargetIds].sort((a, b) => a - b);
|
||||
if (this.options.isPublished() && (previousTargets.length !== nextTargets.length || previousTargets.some((id, index) => id !== nextTargets[index]))) {
|
||||
this.options.sendJson({ type: "whisperTargets", targetIds: nextTargets, active: state.whisperActive });
|
||||
}
|
||||
}
|
||||
|
||||
private publishDirectory(): void {
|
||||
if (this.options.isPublished()) this.options.sendJson({ type: "channelList", channels: this.options.state.channelTree });
|
||||
}
|
||||
|
||||
private trackChannelEvents(previous: ChannelInfo[]): void {
|
||||
if (!this.options.isPublished()) return;
|
||||
const before = new Map(previous.map(channel => [channel.id, channel]));
|
||||
const after = new Map(this.options.state.channelTree.map(channel => [channel.id, channel]));
|
||||
for (const channel of after.values()) {
|
||||
if (!before.has(channel.id)) this.options.addEvent("joined", `频道「${channel.name}」已创建`);
|
||||
else if (before.get(channel.id)?.name !== channel.name) this.options.addEvent("moved", `频道已重命名为「${channel.name}」`);
|
||||
}
|
||||
for (const channel of before.values()) if (!after.has(channel.id)) this.options.addEvent("left", `频道「${channel.name}」已删除`);
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
if (this.directoryStatusRefreshTimer) clearTimeout(this.directoryStatusRefreshTimer);
|
||||
this.directoryStatusRefreshTimer = null;
|
||||
this.avatars.reset();
|
||||
this.clientId = 0;
|
||||
this.channelId = 0n;
|
||||
this.directory.clear();
|
||||
this.options.state.channelTree = [];
|
||||
this.options.state.members.clear();
|
||||
this.options.state.whisperTargetIds.clear();
|
||||
this.options.state.whisperActive = false;
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
if (this.directoryStatusRefreshTimer) clearTimeout(this.directoryStatusRefreshTimer);
|
||||
this.directoryStatusRefreshTimer = null;
|
||||
for (const unsubscribe of this.subscriptions.splice(0)) unsubscribe();
|
||||
this.avatars.close();
|
||||
this.reset();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { ConnectionStateMachine, SessionManager, type ManagedSession, type SessionTeardownReason } from "./session-manager.js";
|
||||
|
||||
function connect(session: ManagedSession | ConnectionStateMachine): void {
|
||||
session.transition("connecting");
|
||||
session.transition("authenticating");
|
||||
session.transition("syncing");
|
||||
session.transition("connected");
|
||||
}
|
||||
|
||||
test("a connected session can reconnect successfully and later fail cleanly", () => {
|
||||
const state = new ConnectionStateMachine();
|
||||
assert.throws(() => state.transition("connected"), /Illegal connection state transition/);
|
||||
assert.equal(state.state, "idle");
|
||||
connect(state);
|
||||
state.transition("interrupted");
|
||||
state.transition("reconnecting");
|
||||
connect(state);
|
||||
assert.equal(state.state, "connected");
|
||||
state.transition("interrupted");
|
||||
state.transition("reconnecting");
|
||||
state.transition("failed");
|
||||
state.transition("disconnecting");
|
||||
state.transition("idle");
|
||||
assert.equal(state.state, "idle");
|
||||
});
|
||||
|
||||
test("concurrent teardown requests run cleanup once and retain admission until it finishes", async () => {
|
||||
const manager = new SessionManager();
|
||||
const reasons: SessionTeardownReason[] = [];
|
||||
let release!: () => void;
|
||||
const pending = new Promise<void>((resolve) => { release = resolve; });
|
||||
const session = manager.admit("browser", async (reason) => { reasons.push(reason); await pending; });
|
||||
assert.ok(session);
|
||||
connect(session);
|
||||
|
||||
const first = manager.teardown("browser", "websocket-close");
|
||||
const second = manager.teardown("browser", "admin-terminated");
|
||||
assert.deepEqual(reasons, ["websocket-close"]);
|
||||
assert.equal(session.state, "disconnecting");
|
||||
assert.equal(manager.activeCount, 1);
|
||||
release();
|
||||
await Promise.all([first, second]);
|
||||
await manager.teardown("browser", "websocket-error");
|
||||
assert.equal(session.state, "idle");
|
||||
assert.equal(manager.activeCount, 0);
|
||||
assert.equal(manager.get("browser"), undefined);
|
||||
assert.deepEqual(reasons, ["websocket-close"]);
|
||||
});
|
||||
|
||||
test("cleanup errors still release the session and allow a new admission", async () => {
|
||||
const manager = new SessionManager();
|
||||
const session = manager.admit("browser", async () => { throw new Error("socket already closed"); });
|
||||
assert.ok(session);
|
||||
session.transition("connecting");
|
||||
await manager.teardown("browser", "teamSpeak-connect-failed");
|
||||
assert.equal(session.state, "idle");
|
||||
assert.equal(manager.activeCount, 0);
|
||||
assert.ok(manager.admit("browser", async () => {}));
|
||||
await manager.shutdown();
|
||||
});
|
||||
|
||||
test("admission enforces capacity and reuses slots only after teardown", async () => {
|
||||
const manager = new SessionManager();
|
||||
for (let index = 0; index < manager.maxSessions; index++) {
|
||||
assert.ok(manager.admit(String(index), async () => {}));
|
||||
}
|
||||
assert.equal(manager.admit("overflow", async () => {}), null);
|
||||
assert.equal(manager.createdCount, manager.maxSessions);
|
||||
await manager.teardown("0", "client-disconnect");
|
||||
assert.ok(manager.admit("replacement", async () => {}));
|
||||
assert.equal(manager.createdCount, manager.maxSessions + 1);
|
||||
assert.equal(manager.peakCount, manager.maxSessions);
|
||||
await manager.shutdown();
|
||||
assert.equal(manager.activeCount, 0);
|
||||
});
|
||||
|
||||
test("shutdown stops admission immediately and waits for every cleanup even when one fails", async () => {
|
||||
const manager = new SessionManager();
|
||||
const reasons: SessionTeardownReason[] = [];
|
||||
let release!: () => void;
|
||||
const pending = new Promise<void>((resolve) => { release = resolve; });
|
||||
manager.admit("slow", async (reason) => { reasons.push(reason); await pending; });
|
||||
manager.admit("failed", async (reason) => { reasons.push(reason); throw new Error("closed"); });
|
||||
const shutdown = manager.shutdown();
|
||||
assert.equal(manager.isAccepting, false);
|
||||
assert.equal(manager.admit("late", async () => {}), null);
|
||||
assert.deepEqual(reasons, ["gateway-shutdown", "gateway-shutdown"]);
|
||||
release();
|
||||
await shutdown;
|
||||
await manager.shutdown();
|
||||
assert.equal(manager.activeCount, 0);
|
||||
assert.equal(reasons.length, 2);
|
||||
});
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
type ClientOptions,
|
||||
type Identity,
|
||||
} from "@echosixhiya/teamspeak-client";
|
||||
import { WebSpeakTeamSpeakResolver } from "./teamspeak-resolver.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { normalizeTeamSpeakError } from "../errors.js";
|
||||
import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
@@ -85,6 +86,7 @@ export class TeamSpeakAdapter {
|
||||
) {
|
||||
this.identity = options.identity ?? generateIdentity(8);
|
||||
const clientOptions: ClientOptions = {
|
||||
resolver: new WebSpeakTeamSpeakResolver(),
|
||||
serverPassword: options.serverPassword,
|
||||
defaultChannel: options.defaultChannel,
|
||||
defaultChannelPassword: options.channelPassword,
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { AddrResolver, ResolvedAddr } from "@echosixhiya/teamspeak-client";
|
||||
import { WebSpeakTeamSpeakResolver } from "./teamspeak-resolver.js";
|
||||
|
||||
function fixedResolver(result: ResolvedAddr[], onResolve?: (signal?: AbortSignal) => void): AddrResolver {
|
||||
return {
|
||||
resolve: async (_address, signal) => {
|
||||
onResolve?.(signal);
|
||||
return result;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("private short hostnames use local DNS directly without cloud nickname discovery", async () => {
|
||||
let baseCalls = 0;
|
||||
const resolver = new WebSpeakTeamSpeakResolver({
|
||||
localLookup: async (hostname) => {
|
||||
assert.equal(hostname, "teamspeak");
|
||||
return [{ address: "172.18.0.6", family: 4 }];
|
||||
},
|
||||
baseResolver: {
|
||||
resolve: async () => {
|
||||
baseCalls++;
|
||||
return [];
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = await resolver.resolve("teamspeak:9988");
|
||||
assert.equal(result[0]?.addr, "172.18.0.6:9988");
|
||||
assert.equal(result[0]?.source, "Direct");
|
||||
assert.equal(baseCalls, 0);
|
||||
});
|
||||
|
||||
test("undotted nickname discovery is bounded and falls back to the direct host", async () => {
|
||||
let baseSignal: AbortSignal | undefined;
|
||||
const resolver = new WebSpeakTeamSpeakResolver({
|
||||
localLookup: async () => [],
|
||||
baseResolver: {
|
||||
resolve: async (_address, signal) => {
|
||||
baseSignal = signal;
|
||||
return new Promise<ResolvedAddr[]>(() => undefined);
|
||||
},
|
||||
},
|
||||
localAliasLookupTimeoutMs: 20,
|
||||
nicknameLookupTimeoutMs: 25,
|
||||
});
|
||||
|
||||
const result = await resolver.resolve("teamspeak:9987");
|
||||
assert.equal(result[0]?.addr, "teamspeak:9987");
|
||||
assert.equal(result[0]?.source, "Direct");
|
||||
assert.equal(baseSignal?.aborted, true);
|
||||
});
|
||||
|
||||
test("dotted hostnames preserve the SDK resolver path", async () => {
|
||||
const expected: ResolvedAddr[] = [{ addr: "voice.example.com:9987", source: "Direct", expiry: new Date(0) }];
|
||||
let lookupCalls = 0;
|
||||
let baseCalls = 0;
|
||||
const resolver = new WebSpeakTeamSpeakResolver({
|
||||
localLookup: async () => {
|
||||
lookupCalls++;
|
||||
return [];
|
||||
},
|
||||
baseResolver: fixedResolver(expected, () => { baseCalls++; }),
|
||||
});
|
||||
|
||||
assert.deepEqual(await resolver.resolve("voice.example.com:9987"), expected);
|
||||
assert.equal(lookupCalls, 0);
|
||||
assert.equal(baseCalls, 1);
|
||||
});
|
||||
|
||||
test("DNS resolution failures continue through bounded nickname discovery", async () => {
|
||||
const expected: ResolvedAddr[] = [{ addr: "public.example.com:9987", source: "Nickname", expiry: new Date(0) }];
|
||||
const resolver = new WebSpeakTeamSpeakResolver({
|
||||
localLookup: async () => { throw new Error("ENOTFOUND"); },
|
||||
baseResolver: fixedResolver(expected),
|
||||
nicknameLookupTimeoutMs: 100,
|
||||
});
|
||||
|
||||
assert.deepEqual(await resolver.resolve("public-alias"), expected);
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
import { lookup } from "node:dns/promises";
|
||||
import { isIP } from "node:net";
|
||||
import { Resolver as TeamSpeakResolver } from "@echosixhiya/teamspeak-client/discovery";
|
||||
import type { AddrResolver, ResolvedAddr } from "@echosixhiya/teamspeak-client";
|
||||
import { formatTeamSpeakTarget, parseTeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
|
||||
const LOCAL_ALIAS_LOOKUP_TIMEOUT_MS = 1_000;
|
||||
const NICKNAME_LOOKUP_TIMEOUT_MS = 3_000;
|
||||
|
||||
type LocalAddress = { address: string; family: number };
|
||||
type LocalLookup = (hostname: string) => Promise<LocalAddress[]>;
|
||||
|
||||
interface WebSpeakTeamSpeakResolverOptions {
|
||||
baseResolver?: AddrResolver;
|
||||
localLookup?: LocalLookup;
|
||||
localAliasLookupTimeoutMs?: number;
|
||||
nicknameLookupTimeoutMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep TeamSpeak nickname discovery for normal names, while allowing an
|
||||
* internal short hostname (for example a Docker Compose service name) to use
|
||||
* the local resolver directly. Bound cloud nickname discovery so a network
|
||||
* black hole cannot prevent the SDK's direct-host fallback indefinitely.
|
||||
*/
|
||||
export class WebSpeakTeamSpeakResolver implements AddrResolver {
|
||||
private readonly baseResolver: AddrResolver;
|
||||
private readonly localLookup: LocalLookup;
|
||||
private readonly localAliasLookupTimeoutMs: number;
|
||||
private readonly nicknameLookupTimeoutMs: number;
|
||||
|
||||
constructor(options: WebSpeakTeamSpeakResolverOptions = {}) {
|
||||
this.baseResolver = options.baseResolver ?? new TeamSpeakResolver();
|
||||
this.localLookup = options.localLookup ?? ((hostname) => lookup(hostname, { all: true, verbatim: true }));
|
||||
this.localAliasLookupTimeoutMs = options.localAliasLookupTimeoutMs ?? LOCAL_ALIAS_LOOKUP_TIMEOUT_MS;
|
||||
this.nicknameLookupTimeoutMs = options.nicknameLookupTimeoutMs ?? NICKNAME_LOOKUP_TIMEOUT_MS;
|
||||
}
|
||||
|
||||
async resolve(address: string, signal?: AbortSignal): Promise<ResolvedAddr[]> {
|
||||
if (signal?.aborted) throw signal.reason ?? new Error("TeamSpeak address resolution was aborted");
|
||||
|
||||
let target;
|
||||
try {
|
||||
target = parseTeamSpeakTarget(address);
|
||||
} catch {
|
||||
return this.resolveBase(address, signal);
|
||||
}
|
||||
|
||||
const { host, port } = target;
|
||||
if (isIP(host) || host === "localhost" || host.includes(".")) {
|
||||
return this.resolveBase(address, signal);
|
||||
}
|
||||
|
||||
const localAddresses = await raceWithTimeout(
|
||||
Promise.resolve().then(() => this.localLookup(host)),
|
||||
this.localAliasLookupTimeoutMs,
|
||||
signal,
|
||||
)
|
||||
.catch((error: unknown) => {
|
||||
if (signal?.aborted) throw signal.reason ?? error;
|
||||
return null;
|
||||
});
|
||||
const localAddress = localAddresses?.find(({ address: candidate }) => isPrivateNetworkAddress(candidate));
|
||||
if (localAddress) {
|
||||
return [directAddress(localAddress.address, port)];
|
||||
}
|
||||
|
||||
const baseResults = await this.resolveBaseWithTimeout(address, signal);
|
||||
return baseResults?.length ? baseResults : [directAddress(host, port)];
|
||||
}
|
||||
|
||||
private resolveBase(address: string, signal?: AbortSignal): Promise<ResolvedAddr[]> {
|
||||
return this.baseResolver.resolve(address, signal);
|
||||
}
|
||||
|
||||
private async resolveBaseWithTimeout(address: string, signal?: AbortSignal): Promise<ResolvedAddr[] | null> {
|
||||
const timeoutController = new AbortController();
|
||||
const combinedSignal = signal ? AbortSignal.any([signal, timeoutController.signal]) : timeoutController.signal;
|
||||
try {
|
||||
return await raceWithTimeout(
|
||||
Promise.resolve().then(() => this.baseResolver.resolve(address, combinedSignal)),
|
||||
this.nicknameLookupTimeoutMs,
|
||||
signal,
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
if (signal?.aborted) throw signal.reason ?? error;
|
||||
return null;
|
||||
} finally {
|
||||
timeoutController.abort(new Error("TeamSpeak nickname lookup timed out"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function directAddress(host: string, port: number): ResolvedAddr {
|
||||
return {
|
||||
addr: formatTeamSpeakTarget({ host, port }),
|
||||
source: "Direct",
|
||||
expiry: new Date(0),
|
||||
};
|
||||
}
|
||||
|
||||
function isPrivateNetworkAddress(address: string): boolean {
|
||||
const version = isIP(address);
|
||||
if (version === 4) {
|
||||
const [a, b] = address.split(".").map(Number) as [number, number, number, number];
|
||||
return a === 10
|
||||
|| a === 127
|
||||
|| (a === 169 && b === 254)
|
||||
|| (a === 172 && b >= 16 && b <= 31)
|
||||
|| (a === 192 && b === 168);
|
||||
}
|
||||
if (version !== 6) return false;
|
||||
|
||||
const normalized = address.toLowerCase();
|
||||
if (normalized.startsWith("::ffff:")) return isPrivateNetworkAddress(normalized.slice("::ffff:".length));
|
||||
if (normalized === "::" || normalized === "::1") return true;
|
||||
const firstGroup = Number.parseInt(normalized.split(":", 1)[0] || "0", 16);
|
||||
return (firstGroup & 0xfe00) === 0xfc00 || (firstGroup & 0xffc0) === 0xfe80;
|
||||
}
|
||||
|
||||
function raceWithTimeout<T>(work: Promise<T>, timeoutMs: number, signal?: AbortSignal): Promise<T | null> {
|
||||
if (signal?.aborted) return Promise.reject(signal.reason ?? new Error("TeamSpeak address resolution was aborted"));
|
||||
|
||||
return new Promise<T | null>((resolve, reject) => {
|
||||
let settled = false;
|
||||
const finish = (callback: (value: T | null) => void, value: T | null): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
callback(value);
|
||||
};
|
||||
const onAbort = (): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
reject(signal?.reason ?? new Error("TeamSpeak address resolution was aborted"));
|
||||
};
|
||||
const timer = setTimeout(() => finish(resolve, null), timeoutMs);
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
work.then(
|
||||
(value) => finish(resolve, value),
|
||||
(error: unknown) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
reject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||