feat: add Android gateway preview and refactoring plan

This commit is contained in:
illusia committed 2026-10-01 08:13:46 +08:00
1 parent 9e2b9bf564
commit aeaeb15965
73 files changed
+4347 -24

No files matched your search

+7
View File
@@ -1,6 +1,13 @@
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
+141
View File
@@ -0,0 +1,141 @@
# WebSpeak 代码待修改清单与修改方向
本文记录 `webspeak-webclient` 当前需要整理的代码、工程流程和文档,并给出大致修改方向及验收标准。建议先统一验证流程、补充关键行为测试,再逐步拆分语音与会话模块。本文中的事项均待实施。
## 范围与基线
- 记录日期:2026 年 10 月 1 日。
- 代码基线:`dev` 分支,提交 `377d5ce`,应用版本 `0.2.5-preview`。
- 分析对象:当前工作区,包含已有未提交改动,不等同于该提交的干净检出。
- 工作区现状:记录时已有 10 个受跟踪文件修改;Android 相关目录、Opus 适配文件及部分本地产物尚未跟踪。
- 验证范围:静态阅读源码、配置和工作流,未运行构建、单元测试、真实 TeamSpeak 连接或 Android 真机验证。
- 本次交付:新增本清单,未实施下面的代码修改。
下文将已确认的现状与建议方向分开描述。优先级表示建议实施顺序,不代表已确认的故障或安全漏洞等级。
## 当前代码边界
| 部分 | 主要位置 | 职责 |
| --- | --- | --- |
| 网关启动与 HTTP | `src/index.ts`、`src/server/server.ts` | 初始化服务、公共接口、加入凭证、静态页面和管理路由 |
| 实时会话与协议桥接 | `src/server/voice-bridge.ts`、`session-manager.ts`、`voice-protocol.ts` | 会话生命周期、命令分发、语音、事件同步和屏幕共享信令 |
| TeamSpeak 接入 | `src/server/ts-client.ts`、`teamspeak-adapter.ts`、`directory-sync.ts` | SDK 适配、连接、目录同步、聊天及语音收发 |
| 管理与持久化 | `src/admin/`、`src/persistence/`、`src/security/` | 认证、配置、邀请、中继节点、审计和 SQLite 存储 |
| 网页交互 | `web/src/views/`、`web/src/composables/` | 页面、连接、频道、成员、聊天、音频和屏幕共享交互 |
| 前端基础服务 | `web/src/services/`、`web/src/i18n/`、`web/src/skins/` | 身份导入、浏览器存储、皮肤和国际化 |
| 独立加速中继 | `src/relay.ts`、`src/server/acceleration-relay.ts` | 中继进程及网关侧中继接入 |
| Android 预览 | `src/mobile/`、`mobile/`、`web/android/` | 本机网关、资源打包和原生容器 |
连接主链路为:浏览器申请一次性加入凭证,建立 `/ws/voice`,网关创建独立 TeamSpeak 客户端。控制消息通过 WebSocket 传输;语音支持 WebSocket 兼容路径和可选 WebRTC 路径。屏幕媒体使用独立连接,网关负责共享状态和信令。
## 待修改事项总览
| 编号 | 优先级 | 事项 | 性质 | 状态 |
| --- | --- | --- | --- | --- |
| 01 | P1 | 统一构建命令与 CI 验证入口 | 已确认的工程配置差异 | 待实施 |
| 02 | P1 | 补齐会话与媒体关键行为测试 | 已观察到的测试缺口 | 待实施 |
| 03 | P2 | 集中前后端协议契约 | 重构建议 | 待实施 |
| 04 | P2 | 拆分前端语音核心模块 | 重构建议 | 待实施 |
| 05 | P2 | 拆分服务端实时桥接模块 | 重构建议 | 待实施 |
| 06 | P2 | 拆分页面组件与管理页逻辑 | 重构建议 | 待实施 |
| 07 | P2 | 明确 Android 平台边界与验证范围 | 未提交扩展的整理与验证 | 待实施 |
| 08 | P1 | 修正文档与实现不一致的说明 | 已确认的文档偏差 | 待实施 |
| 09 | P3 | 整理源码与本地产物边界 | 仓库维护建议 | 待实施 |
P1 为后续重构的准备工作,P2 为模块整理,P3 为维护便利性改进。大文件行数仅用于定位职责集中处,不作为拆分目标或质量评分。
## 修改方向与验收标准
### 01 统一构建命令与 CI 验证入口
**现状与位置:** [根目录 package.json](../package.json) 的 `web:build` 直接执行 Vite;[前端 package.json](../web/package.json) 的 `build` 先执行 `vue-tsc --noEmit`。[ci.yml](../.github/workflows/ci.yml) 没有执行 `npm test`,push 监听 `main`;[docker-publish.yml](../.github/workflows/docker-publish.yml) 的分支 push 监听 `master`。CI 同时配置了 pull request 触发,不能据此认定其他分支上的 PR 不会验证。
**修改方向:** 根目录前端构建命令统一委托给前端 `build`。在现有 CI 验证任务中执行单元测试,保留 SDK 准备及原生 Opus 构建步骤。按实际开发和发布流程统一分支触发策略,并明确发布前必须通过哪些检查;不要仅凭当前分支名选择发布分支。
**验收标准:** 本地与 CI 使用一致的前端类型检查和构建流程;类型错误、测试失败会使验证失败;开发分支、PR、发布分支及标签的触发范围有明确说明。
### 02 补齐会话与媒体关键行为测试
**现状与位置:** 根目录 `test` 脚本显式列出 9 个测试文件,涉及皮肤、身份导入、目标策略、解析器、部分协议逻辑和健康检查。在已检查的源码及工作流中,未看到语音会话、重连、屏幕共享的完整集成验证;本轮未测量覆盖率。
**修改方向:** 优先为即将拆分的模块建立行为基线。覆盖加入凭证过期及重复消费、会话重复清理、目录快照与实时事件合并、重连成功与失败、WebRTC 失败回退、屏幕共享退出后的资源释放。通过可替换的时钟、传输和 SDK 边界验证正常与异常路径;真实 TeamSpeak、浏览器媒体和 Android 行为另设可重复执行的集成验证步骤。
**验收标准:** 核心测试能在 CI 中运行;测试能够发现重复消费、重复清理、状态不同步和回退失败等行为回归;需要设备或真实服务的步骤记录环境与结果,不以类型检查或 HTTP 健康检查代替音频验证。
### 03 集中前后端协议契约
**现状与位置:** `ChannelMember`、`ServerEvent`、屏幕共享描述及 `SkinCatalogEntry` 在前后端分别定义。[useVoiceWebSocket.ts](../web/src/composables/useVoiceWebSocket.ts) 中的 `handleMessage` 使用 `any`,发送命令接受任意字符串。[voice-protocol.ts](../src/server/voice-protocol.ts) 已有运行时检查,但命令载荷仍统一表示为 `Record<string, unknown>`。
**修改方向:** 先梳理实际传输字段,区分公共协议和内部状态,再共享可以复用的类型及校验逻辑。按消息类型定义对应载荷,逐步用 `unknown` 加解析函数替换接收入口的 `any`。共享代码应兼容浏览器与服务端,并明确 TypeScript 编译和发布输出路径;后端当前 `rootDir` 为 `src`,不能直接移动到顶层目录后假定构建仍然成立。
**验收标准:** 已迁移消息的字段与类型只有一处权威定义;非法消息得到明确处理;现有错误码、请求标识和旧客户端兼容行为不因整理而变化;后端及前端均可独立构建。
### 04 拆分前端语音核心模块
**现状与位置:** [useVoiceWebSocket.ts](../web/src/composables/useVoiceWebSocket.ts) 当前为 3,149 行,集中处理连接、凭证请求、麦克风采集、降噪、播放、WebRTC、伴奏、屏幕共享和统计。
**修改方向:** 暂时保留现有 composable 作为页面调用入口,逐项提取连接与命令传输、麦克风处理、远端播放、WebRTC 语音、屏幕共享及统计模块。先明确各模块拥有的状态和资源,再移动实现,避免所有模块相互读取同一个大型可变对象。每次只迁移一项职责,并明确初始化、停止和销毁的责任。
**验收标准:** 页面调用接口保持兼容,或有范围明确的迁移;连接、断开、重连、设备切换及 WebRTC 回退行为保持一致;音轨、解码器、定时器和事件监听具有明确清理路径,重复连接不会累计资源。
### 05 拆分服务端实时桥接模块
**现状与位置:** [voice-bridge.ts](../src/server/voice-bridge.ts) 当前为 2,148 行,同时承担连接接入、会话编排、事件同步、命令处理、音频统计和跨端屏幕共享协调。项目已经存在 `SessionManager`、`DirectorySynchronizer`、协议解析和 WebRTC 音频模块。
**修改方向:** 保留 `VoiceBridge` 的接入与组装职责,沿现有边界提取命令处理、目录与成员事件协调、音频转发、屏幕共享协调。复用现有状态机和清理机制,明确断开、踢出、管理员终止和网关关闭等路径的责任归属。
**验收标准:** 一次性凭证、身份占用限制、并发会话上限和重连策略保持原有行为;清理操作可安全重复执行;屏幕共享仍遵守所属服务器、频道及参与者校验;语音热路径保留有界缓冲,不新增逐帧持久化日志。
### 06 拆分页面组件与管理页逻辑
**现状与位置:** [WebClient.vue](../web/src/views/WebClient.vue) 当前为 1,208 行,已经使用多个业务 composable,但仍保留较多模板和组装逻辑。[AdminView.vue](../web/src/views/AdminView.vue) 为 1,895 行,集中多个管理功能、文案和样式。
**修改方向:** 网页客户端按加入表单、频道树、聊天区、音频设置和弹窗等稳定界面边界拆组件;管理页按服务器设置、会话、邀请、皮肤和诊断等功能拆分。将数据请求和业务状态与展示分开,优先复用已有 composable,避免重建一套平行状态。
**验收标准:** 路由、交互、错误反馈和语言切换保持一致;皮肤公开接口 `data-ws-part` 与主题层叠关系保持兼容;验证主要页面在桌面和移动尺寸下的布局,不以组件文件变短代替行为验收。
### 07 明确 Android 平台边界与验证范围
**现状与位置:** 当前工作区已新增 [移动网关](../src/mobile/index.ts)、[移动资源打包](../mobile/pack.mjs)、Capacitor 启动逻辑及 [Opus 适配](../src/server/opus-codec.ts)。本地网关仅监听 `127.0.0.1`,当前关闭 WebRTC 语音。服务端使用原生 Opus,移动端使用 `opusscript`。
[mobile/README.md](../mobile/README.md) 记录内嵌运行时为 Node.js 18.20.4,而 SDK 声明要求 Node.js 20.19 或更高;文档同时记录真机连接、后台音频及原生屏幕共享仍待验证或实现。这些是现有文档记录,本轮未重新验证设备和 SDK 运行情况。
**修改方向:** 明确服务器、浏览器和 Android 的启动与能力差异,将平台启动逻辑从通用前端入口中分离。保留独立的编解码适配边界,按实际可用能力向页面暴露功能。先验证运行时兼容性与双向语音,再决定运行时升级或适配方案。后台前台服务、MediaProjection 等新增能力单独规划,避免与代码搬迁混合。
**验收标准:** 普通网页和服务端无需移动端运行时即可启动;Android 构建输入与依赖安装步骤完整;真实设备验证连接、双向语音、断线恢复和资源释放;明确记录后台音频与屏幕共享的支持状态,尚未验证的能力继续标注为预览限制。
### 08 修正文档与实现不一致的说明
**现状与位置:** [CLAUDE.md](../CLAUDE.md) 仍描述通过 WebQuery 和 API key 获取频道、使用旧配置字段以及最多 32 个用户。实际 [ts-client.ts](../src/server/ts-client.ts) 通过 SDK 客户端协议获取目录,主要配置位于 SQLite,[constants.ts](../src/constants.ts) 定义的网关会话上限为 100。该上限不代表目标 TeamSpeak 服务器容量或已验证的性能。
**修改方向:** 按当前实现更新架构、配置来源、连接鉴权、音频传输和运行限制;明确 `config.json` 的遗留导入用途、SQLite 持久化、浏览器存储及环境变量的不同职责。先修正已有误导性说明,模块拆分完成后再同步新的目录边界。
**验收标准:** 架构说明能够对应实际入口、配置和协议;不再要求已不使用的 WebQuery 凭证;区分网关代码上限、目标服务器限制及性能验证结果;部署与开发命令和实际脚本一致。
### 09 整理源码与本地产物边界
**现状与位置:** 根目录存在多份部署压缩包、`release-artifacts/`、参考素材和本地辅助内容,部分显示为未跟踪文件;已有 `.gitignore` 和 `.dockerignore` 对产物的处理范围也不同。
**修改方向:** 先列出需要版本管理的源码、保留的发布产物、运行数据、参考素材及实验脚本,再规划目录和忽略规则。新增 Android 路径时同步检查 Docker 构建上下文,避免把移动依赖或构建缓存带入服务端镜像构建。保留有用途的 SDK 准备和中继验证脚本,并注明用途。
**验收标准:** 常规构建产物和缓存不再干扰源码变更检查;源码及必要资源没有被误忽略;构建与打包不依赖未声明的本地文件。归档或清理前确认用途及保留位置,不按未跟踪状态直接删除文件。
## 建议实施顺序
| 批次 | 内容 | 完成条件 |
| --- | --- | --- |
| 第一批 | 01、08,并为下一批涉及的行为补充 02 | 构建和测试入口一致,已有说明得到修正,关键行为具备基线 |
| 第二批 | 03,逐项整理协议类型与边界校验 | 已迁移契约可供两端使用,构建和兼容验证通过 |
| 第三批 | 04、05,按单项职责分别提交 | 每次迁移都能验证连接和媒体行为,并独立回退 |
| 第四批 | 06,拆分页面和管理功能 | 页面行为、皮肤接口及布局验证通过 |
| 独立工作项 | 07、09 | 平台验证与产物整理分别完成,不混入大文件拆分 |
02 随各批次持续补充,只增加能够验证真实行为和资源生命周期的测试。Android 的运行时与真机验证可以提前开展,不必等待网页重构全部完成。
## 实施时需要保留的边界
- 当前未提交工作是后续实施的输入;开始修改前重新确认差异,避免覆盖已有 Android 和兼容处理。
- 纯结构调整保持现有公共 API、错误码、浏览器持久化格式和皮肤接口兼容;确需改变行为时另行说明迁移范围。
- SQLite schema、依赖主版本及新增原生功能按独立变更处理,以便验证和回退。
- 普通代码修改执行相关测试与前后端构建;涉及媒体行为时补充真实连接验证;涉及打包流程时执行对应平台构建。
- 各事项完成后记录修改范围、验证结果和剩余限制,再更新清单状态。本文的验收标准不代表相关检查已经通过。
+32
View File
@@ -0,0 +1,32 @@
# Android preview
The Android app packages the existing 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.
## Build on Windows
Install the root and mobile dependencies, then prepare and sync the Android project:
```powershell
npm install
npm install --prefix mobile
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/`. Use `app-arm64-v8a-debug.apk` for most Android phones and `app-x86_64-debug.apk` for the Android emulator.
## Current scope
- 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 this preview.
- 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 selected 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 a real connection to a TeamSpeak server still needs device testing before this is treated as a release build.
- 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.
+33
View File
@@ -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 });
});
+29
View File
@@ -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}`);
+1564
View File
File diff suppressed because it is too large. Load diff
+15
View File
@@ -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"
}
}
+2
View File
@@ -15,6 +15,8 @@
"start": "node dist/index.js",
"web:dev": "cd web && npx vite --host",
"web:build": "cd web && npx vite 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",
+126
View File
@@ -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.5-preview",
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;
}
}
+56
View File
@@ -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();
}
}
+3 -7
View File
@@ -1,6 +1,5 @@
import { WebSocketServer, WebSocket } from "ws";
import type { IncomingMessage, Server } from "node:http";
import { createRequire } from "node:module";
import { randomUUID } from "node:crypto";
import { isIP } from "node:net";
import { identityFromString } from "@echosixhiya/teamspeak-client";
@@ -18,11 +17,7 @@ import { WebRtcAudioSession, type WebRtcAudioOptions, type WebRtcAudioStats, typ
import { pingTeamSpeakSession } from "./network-probe.js";
import type { AccelerationRelayOptions, ConfiguredAccelerationRelay } from "./acceleration-relay.js";
import { normalizeScreenShareIceServers, parseScreenShareMessage, type ScreenShareClientMessage, type ScreenShareIceServer, type ScreenSharePeerSignal, type ScreenShareStreamDescription, type ScreenShareViewerDescription } from "./screen-share.js";
const require = createRequire(import.meta.url);
const { OpusEncoder } = require("@discordjs/opus") as {
OpusEncoder: new (sampleRate: number, channels: number) => { encode(pcm: Buffer): Buffer };
};
import { OpusEncoder } from "./opus-codec.js";
const HEARTBEAT_INTERVAL_MS = 30_000;
const AUDIO_FRAME_BYTES = 1_920;
@@ -145,7 +140,7 @@ interface WebClientEntry {
members: Map<number, ChannelMember>;
avatarCache: Map<string, string | null>;
eventLog: ServerEvent[];
opusEncoder: { encode(pcm: Buffer): Buffer } | null;
opusEncoder: OpusEncoder | null;
opusEncoderWarnedAt: number; // Opus 编码器不可用告警的时间戳,用于限流避免反复刷屏
whisperTargetIds: Set<number>;
whisperActive: boolean;
@@ -940,6 +935,7 @@ export class VoiceBridge {
clearTimeout(entry.reconnectTimer);
entry.reconnectTimer = null;
}
entry.opusEncoder?.dispose();
entry.opusEncoder = null;
const webRtc = entry.webrtc;
entry.webrtc = null;
+5 -11
View File
@@ -1,5 +1,4 @@
import { randomInt } from "node:crypto";
import { createRequire } from "node:module";
import {
MediaStreamTrack,
RtpHeader,
@@ -9,17 +8,10 @@ import {
import type { Logger as LoggerType } from "../logger.js";
import type { TSVoiceData } from "./ts-client.js";
import { WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
import { OpusEncoder } from "./opus-codec.js";
export { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
const require = createRequire(import.meta.url);
const { OpusEncoder } = require("@discordjs/opus") as {
OpusEncoder: new (sampleRate: number, channels: number) => {
decode(data: Buffer): Buffer;
encode(data: Buffer): Buffer;
};
};
const AUDIO_SAMPLE_RATE = 48_000;
const AUDIO_FRAME_SAMPLES = 960;
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
@@ -109,7 +101,7 @@ export class WebRtcAudioSession {
private readonly onVoiceFrame: (data: Buffer, codec: 4 | 5) => void;
private readonly onVoiceActivity: (clientIds: number[]) => void;
private readonly outgoingTrack: MediaStreamTrack;
private readonly decoderByClient = new Map<number, { decode(data: Buffer): Buffer }>();
private readonly decoderByClient = new Map<number, OpusEncoder>();
private readonly partialPcmByClient = new Map<number, Buffer>();
private readonly pendingFrames = new Map<number, PendingAudioFrame[]>();
private readonly memberVolumes = new Map<number, number>();
@@ -117,7 +109,7 @@ export class WebRtcAudioSession {
private readonly opusPayloadTypes = new Set<number>();
private audioTimer: ReturnType<typeof setTimeout> | null = null;
private readonly activityTimer: ReturnType<typeof setInterval>;
private encoder: { encode(data: Buffer): Buffer } | null;
private encoder: OpusEncoder | null;
private sequenceNumber = randomInt(0, 65_536);
private timestamp = randomInt(0, 0x1_0000_0000) >>> 0;
private readonly ssrc = randomInt(1, 0x1_0000_0000) >>> 0;
@@ -316,7 +308,9 @@ export class WebRtcAudioSession {
this.memberVolumes.clear();
this.partialPcmByClient.clear();
this.activeSpeakerIds.clear();
for (const decoder of this.decoderByClient.values()) decoder.dispose();
this.decoderByClient.clear();
this.encoder?.dispose();
this.encoder = null;
this.outgoingTrack.stop();
await this.peer.close();
+101
View File
@@ -0,0 +1,101 @@
# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore
# Built application files
*.apk
*.aar
*.ap_
*.aab
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Uncomment the following line in case you need and you don't have the release build type files in your app
# release/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# IntelliJ
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
# Android Studio 3 in .gitignore file.
.idea/caches
.idea/modules.xml
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
.idea/navEditor.xml
# Keystore files
# Uncomment the following lines if you do not want to check your keystore files in.
#*.jks
#*.keystore
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
.cxx/
# Google Services (e.g. APIs or Firebase)
# google-services.json
# Freeline
freeline.py
freeline/
freeline_project_description.json
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
# Version control
vcs.xml
# lint
lint/intermediates/
lint/generated/
lint/outputs/
lint/tmp/
# lint/reports/
# Android Profiling
*.hprof
# Cordova plugins for Capacitor
capacitor-cordova-android-plugins
# Copied web assets
app/src/main/assets/public
# Generated Config files
app/src/main/assets/capacitor.config.json
app/src/main/assets/capacitor.plugins.json
app/src/main/res/xml/config.xml
+2
View File
@@ -0,0 +1,2 @@
/build/*
!/build/.npmkeep
+62
View File
@@ -0,0 +1,62 @@
apply plugin: 'com.android.application'
android {
namespace = "io.webspeak.client"
compileSdk = rootProject.ext.compileSdkVersion
splits {
abi {
enable true
reset()
include 'armeabi-v7a', 'arm64-v8a', 'x86_64'
universalApk false
}
}
defaultConfig {
applicationId "io.webspeak.client"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 25
versionName "0.2.5-preview"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
flatDir{
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
implementation project(':capacitor-android')
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
implementation project(':capacitor-cordova-android-plugins')
}
apply from: 'capacitor.build.gradle'
try {
def servicesJSON = file('google-services.json')
if (servicesJSON.text) {
apply plugin: 'com.google.gms.google-services'
}
} catch(Exception e) {
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
}
+19
View File
@@ -0,0 +1,19 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_21
targetCompatibility JavaVersion.VERSION_21
}
}
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
implementation project(':capawesome-capacitor-nodejs')
}
if (hasProperty('postBuildExtras')) {
postBuildExtras()
}
+21
View File
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
@@ -0,0 +1,26 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import android.content.Context;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.getcapacitor.app", appContext.getPackageName());
}
}
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:networkSecurityConfig="@xml/network_security_config"
android:theme="@style/AppTheme">
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation|density"
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBarLaunch"
android:launchMode="singleTask"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>
</application>
<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
</manifest>
@@ -0,0 +1,5 @@
package io.webspeak.client;
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {}
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

@@ -0,0 +1,34 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillType="evenOdd"
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
android:strokeColor="#00000000"
android:strokeWidth="1">
<aapt:attr name="android:fillColor">
<gradient
android:endX="78.5885"
android:endY="90.9159"
android:startX="48.7653"
android:startY="61.0927"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
android:strokeColor="#00000000"
android:strokeWidth="1" />
</vector>
@@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillColor="#26A69A"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
</vector>
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#FFFFFF</color>
</resources>
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="app_name">WebSpeak</string>
<string name="title_activity_main">WebSpeak</string>
<string name="package_name">io.webspeak.client</string>
<string name="custom_url_scheme">io.webspeak.client</string>
</resources>
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:background">@null</item>
</style>
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
<item name="android:background">@drawable/splash</item>
</style>
</resources>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="." />
<cache-path name="my_cache_images" path="." />
</paths>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="false" />
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="false">127.0.0.1</domain>
<domain includeSubdomains="false">localhost</domain>
</domain-config>
</network-security-config>
@@ -0,0 +1,18 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
+29
View File
@@ -0,0 +1,29 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.13.0'
classpath 'com.google.gms:google-services:4.4.4'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
apply from: "variables.gradle"
allprojects {
repositories {
google()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
+6
View File
@@ -0,0 +1,6 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
include ':capacitor-android'
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
include ':capawesome-capacitor-nodejs'
project(':capawesome-capacitor-nodejs').projectDir = new File('../node_modules/@capawesome/capacitor-nodejs/android')
+22
View File
@@ -0,0 +1,22 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-bin.zip
networkTimeout=120000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+251
View File
@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+5
View File
@@ -0,0 +1,5 @@
include ':app'
include ':capacitor-cordova-android-plugins'
project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')
apply from: 'capacitor.settings.gradle'
+16
View File
@@ -0,0 +1,16 @@
ext {
minSdkVersion = 24
compileSdkVersion = 36
targetSdkVersion = 36
androidxActivityVersion = '1.11.0'
androidxAppCompatVersion = '1.7.1'
androidxCoordinatorLayoutVersion = '1.3.0'
androidxCoreVersion = '1.17.0'
androidxFragmentVersion = '1.8.9'
coreSplashScreenVersion = '1.2.0'
androidxWebkitVersion = '1.14.0'
junitVersion = '4.13.2'
androidxJunitVersion = '1.3.0'
androidxEspressoCoreVersion = '3.7.0'
cordovaAndroidVersion = '14.0.1'
}
+19
View File
@@ -0,0 +1,19 @@
/// <reference types="@capawesome/capacitor-nodejs" />
import type { CapacitorConfig } from "@capacitor/cli";
const config: CapacitorConfig = {
appId: "io.webspeak.client",
appName: "WebSpeak",
webDir: "dist",
server: {
allowNavigation: ["127.0.0.1"],
},
plugins: {
Nodejs: {
nodeDir: "nodejs",
startMode: "auto",
},
},
};
export default config;
+1236
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -8,6 +8,9 @@
"preview": "vite preview"
},
"dependencies": {
"@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2",
"@capawesome/capacitor-nodejs": "^0.1.1",
"@sapphi-red/web-noise-suppressor": "^0.4.0",
"fflate": "^0.8.3",
"pinia": "^3.0.2",
@@ -18,6 +21,7 @@
"vue-router": "^4.5.1"
},
"devDependencies": {
"@capacitor/cli": "^8.5.2",
"@vitejs/plugin-vue": "^5.2.3",
"typescript": "~5.7.0",
"vite": "^6.4.3",
+6 -1
View File
@@ -4,6 +4,7 @@
type="button"
class="skin-trigger"
data-ws-part="skin.trigger"
:disabled="options.length === 0"
:aria-label="menuLabel"
:title="`${menuLabel}: ${selectedOption.label}`"
aria-haspopup="listbox"
@@ -60,7 +61,11 @@ const emit = defineEmits<{
}>();
const options = computed(() => props.options);
const selectedOption = computed(() => options.value.find((option) => option.value === props.modelValue) ?? options.value[0]);
const selectedOption = computed(() => options.value.find((option) => option.value === props.modelValue) ?? options.value[0] ?? {
value: props.modelValue,
label: props.menuLabel,
icon: "compass",
});
const root = ref<HTMLElement | null>(null);
const open = ref(false);
const menuId = `skin-menu-${Math.random().toString(36).slice(2, 9)}`;
@@ -26,6 +26,7 @@ export function useWebClientPublicConfig({
}: UseWebClientPublicConfigOptions) {
const accessMode = ref<"fixed" | "open">("fixed");
const initialized = ref(false);
const mobileMode = ref(false);
const siteName = ref("WebSpeak");
const appVersion = ref("0.2.5-preview");
const visitorNumber = ref<number | null>(null);
@@ -45,6 +46,7 @@ export function useWebClientPublicConfig({
const config = await response.json() as {
version?: unknown;
initialized?: unknown;
mobile?: unknown;
siteName?: unknown;
welcomeText?: unknown;
welcomeTextEn?: unknown;
@@ -60,6 +62,7 @@ export function useWebClientPublicConfig({
visitorNumber.value = Number.isSafeInteger(config.visitorNumber) && Number(config.visitorNumber) > 0 ? Number(config.visitorNumber) : null;
visitorTotal.value = Number.isSafeInteger(config.visitorTotal) && Number(config.visitorTotal) > 0 ? Number(config.visitorTotal) : null;
initialized.value = config.initialized === true;
mobileMode.value = config.mobile === true;
if (typeof config.siteName === "string" && config.siteName.trim()) siteName.value = config.siteName.trim();
if (typeof config.welcomeText === "string") welcomeTexts.zh = config.welcomeText;
if (typeof config.welcomeTextEn === "string") welcomeTexts.en = config.welcomeTextEn;
@@ -101,6 +104,7 @@ export function useWebClientPublicConfig({
return {
accessMode,
initialized,
mobileMode,
siteName,
appVersion,
visitorNumber,
+63 -4
View File
@@ -1,6 +1,8 @@
import { createApp } from "vue";
import { createPinia } from "pinia";
import { createRouter, createWebHistory } from "vue-router";
import { Capacitor } from "@capacitor/core";
import { Nodejs } from "@capawesome/capacitor-nodejs";
import App from "./App.vue";
import WebClient from "./views/WebClient.vue";
import AdminView from "./views/AdminView.vue";
@@ -38,7 +40,64 @@ const router = createRouter({
routes,
});
const app = createApp(App);
app.use(createPinia());
app.use(router);
app.mount("#app");
if (Capacitor.isNativePlatform() && !(location.hostname === "127.0.0.1" && location.port === "3040")) {
void startAndroidGateway();
} else {
mountApp();
}
function mountApp(): void {
const app = createApp(App);
app.use(createPinia());
app.use(router);
app.mount("#app");
}
async function startAndroidGateway(): Promise<void> {
const root = document.getElementById("app");
if (!root) return;
root.innerHTML = '<main style="min-height:100dvh;display:grid;place-items:center;background:#e9fbfb;color:#0b5960;font:16px system-ui;text-align:center;padding:24px"><div><h1 style="font-size:26px">WebSpeak</h1><p id="mobile-gateway-status">正在启动本地语音服务…</p></div></main>';
const status = document.getElementById("mobile-gateway-status");
let complete = false;
let pollTimer = 0;
let timeoutTimer = 0;
try {
const listener = await Nodejs.addListener("message", (event) => {
if (complete) return;
if (event.eventName === "webspeak-error") {
complete = true;
window.clearInterval(pollTimer);
window.clearTimeout(timeoutTimer);
if (status) status.textContent = "本地语音服务启动失败,请重新打开应用。";
return;
}
if (event.eventName !== "webspeak-health") return;
const health = event.args[0];
if (!health || typeof health !== "object" || Array.isArray(health) || health.ready !== true) return;
complete = true;
window.clearInterval(pollTimer);
window.clearTimeout(timeoutTimer);
void listener.remove();
window.location.replace("http://127.0.0.1:3040/");
});
const poll = async () => {
if (complete) return;
const { ready } = await Nodejs.isReady();
if (ready) await Nodejs.send({ eventName: "webspeak-health", args: [] });
};
pollTimer = window.setInterval(() => { void poll().catch(() => {}); }, 500);
timeoutTimer = window.setTimeout(() => {
if (complete) return;
complete = true;
window.clearInterval(pollTimer);
if (status) status.textContent = "本地语音服务启动超时,请重新打开应用。";
}, 45_000);
await poll();
} catch {
complete = true;
window.clearInterval(pollTimer);
window.clearTimeout(timeoutTimer);
if (status) status.textContent = "本地语音服务启动失败,请重新打开应用。";
}
}
+2 -1
View File
@@ -10,7 +10,7 @@
<small>{{ t('browserWorkspace') }}</small>
</div>
</div>
<div class="header-tools" data-ws-part="home.header-tools"><div class="header-note" data-ws-part="home.gateway-status"><span class="tiny-dot"></span> {{ t('secureGateway') }}</div><a class="github-button" href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak" target="_blank" rel="noreferrer" :title="t('githubRepository')" :aria-label="t('githubRepository')"><Icon name="github" :size="18" /><span>{{ t('githubRepository') }}</span></a><button type="button" class="qq-button" :title="t('qqGroup')" :aria-label="t('qqGroup')" aria-haspopup="dialog" @click="qqModalOpen = true"><Icon name="qq" :size="18" /><span class="qq-label">{{ t('qqGroup') }}</span></button><a class="bilibili-button" href="https://space.bilibili.com/25414873" target="_blank" rel="noreferrer" :title="t('bilibiliProfile')" :aria-label="t('bilibiliProfile')"><span class="bilibili-glyph">B</span><span class="bilibili-label">{{ t('bilibiliProfile') }}</span></a><span class="version-badge" :title="`${t('currentVersion')}: v${appVersion}`" :aria-label="`${t('currentVersion')}: v${appVersion}`">v{{ appVersion }}</span><a class="changelog-button" href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/CHANGELOG.md" target="_blank" rel="noreferrer" :title="t('viewChangelog')" :aria-label="t('viewChangelog')"><Icon name="clock" :size="16" /><span>{{ t('viewChangelog') }}</span></a><a class="guide-button" href="/admin" :title="t('adminConsole')" :aria-label="t('adminConsole')"><Icon name="settings" :size="15" /><span>{{ t('adminConsole') }}</span></a><SkinSwitcher v-model="activeSkinId" class="join-skin-switcher" :menu-label="t('skinSelector')" :options="skinOptions" @change="onSkinChange" /><LanguageSwitcher v-model="language" class="join-language-switcher" :menu-label="t('languageMenu')" @change="persistLanguage" /></div>
<div class="header-tools" data-ws-part="home.header-tools"><div class="header-note" data-ws-part="home.gateway-status"><span class="tiny-dot"></span> {{ t('secureGateway') }}</div><a class="github-button" href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak" target="_blank" rel="noreferrer" :title="t('githubRepository')" :aria-label="t('githubRepository')"><Icon name="github" :size="18" /><span>{{ t('githubRepository') }}</span></a><button type="button" class="qq-button" :title="t('qqGroup')" :aria-label="t('qqGroup')" aria-haspopup="dialog" @click="qqModalOpen = true"><Icon name="qq" :size="18" /><span class="qq-label">{{ t('qqGroup') }}</span></button><a class="bilibili-button" href="https://space.bilibili.com/25414873" target="_blank" rel="noreferrer" :title="t('bilibiliProfile')" :aria-label="t('bilibiliProfile')"><span class="bilibili-glyph">B</span><span class="bilibili-label">{{ t('bilibiliProfile') }}</span></a><span class="version-badge" :title="`${t('currentVersion')}: v${appVersion}`" :aria-label="`${t('currentVersion')}: v${appVersion}`">v{{ appVersion }}</span><a class="changelog-button" href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/CHANGELOG.md" target="_blank" rel="noreferrer" :title="t('viewChangelog')" :aria-label="t('viewChangelog')"><Icon name="clock" :size="16" /><span>{{ t('viewChangelog') }}</span></a><a v-if="!mobileMode" class="guide-button" href="/admin" :title="t('adminConsole')" :aria-label="t('adminConsole')"><Icon name="settings" :size="15" /><span>{{ t('adminConsole') }}</span></a><SkinSwitcher v-model="activeSkinId" class="join-skin-switcher" :menu-label="t('skinSelector')" :options="skinOptions" @change="onSkinChange" /><LanguageSwitcher v-model="language" class="join-language-switcher" :menu-label="t('languageMenu')" @change="persistLanguage" /></div>
</header>
<main class="join-content" data-ws-part="home.content">
@@ -569,6 +569,7 @@ const {
const {
accessMode,
initialized,
mobileMode,
siteName,
appVersion,
visitorNumber,