TeamsPeach desktop client: Electron UI, Rust core bridge, TS6 stream viewer, CI
No files matched your search
@@ -0,0 +1,109 @@
|
||||
# Continuous integration on the self-hosted Gitea runner (Linux x64 container jobs).
|
||||
# Everything runs inside the job container; nothing is installed on the runner host.
|
||||
name: ci
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
linux-x64:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: node:22-bookworm
|
||||
env:
|
||||
CARGO_TERM_COLOR: never
|
||||
CARGO_BUILD_JOBS: "2"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: System packages (container only)
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends build-essential cmake curl ca-certificates git \
|
||||
xvfb xauth libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libgbm1 libgtk-3-0 \
|
||||
libasound2 libxss1 libxshmfence1 libxkbcommon0 libxcomposite1 libxdamage1 libxrandr2 libpango-1.0-0
|
||||
|
||||
- name: Rust toolchain
|
||||
run: |
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
|
||||
- name: glibc baseline
|
||||
run: ldd --version | head -n1
|
||||
|
||||
- name: Node dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Unit tests (desktop)
|
||||
run: npm test
|
||||
|
||||
- name: Core tests
|
||||
run: cargo test --manifest-path core/Cargo.toml --locked
|
||||
|
||||
- name: Core release build
|
||||
run: cargo build --manifest-path core/Cargo.toml --release --locked
|
||||
|
||||
- name: Core binary architecture
|
||||
run: node scripts/binary-arch.mjs core/target/release/teamspeach-core --expect linux-x64
|
||||
|
||||
- name: Core identity smoke (stdio, offline)
|
||||
run: node scripts/core-smoke.mjs core/target/release/teamspeach-core
|
||||
|
||||
- name: Electron UI smoke (Xvfb, offline, disposable profile)
|
||||
env:
|
||||
TEAMSPEACH_SMOKE_EXTRA_ARGS: --no-sandbox
|
||||
run: xvfb-run -a node scripts/smoke-ui.mjs --out smoke-out
|
||||
|
||||
- name: Upload smoke evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: ci-smoke-linux-x64
|
||||
path: smoke-out/
|
||||
if-no-files-found: ignore
|
||||
|
||||
linux-arm64-cross:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: node:22-bookworm
|
||||
env:
|
||||
CARGO_TERM_COLOR: never
|
||||
CARGO_BUILD_JOBS: "2"
|
||||
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc
|
||||
CC_aarch64_unknown_linux_gnu: aarch64-linux-gnu-gcc
|
||||
CXX_aarch64_unknown_linux_gnu: aarch64-linux-gnu-g++
|
||||
AR_aarch64_unknown_linux_gnu: aarch64-linux-gnu-ar
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Cross toolchain and user-mode emulator (container only, no binfmt)
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends build-essential cmake curl ca-certificates git \
|
||||
gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libc6-dev-arm64-cross qemu-user
|
||||
|
||||
- name: Rust toolchain
|
||||
run: |
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable --target aarch64-unknown-linux-gnu
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
|
||||
- name: Core cross build (aarch64-unknown-linux-gnu)
|
||||
run: cargo build --manifest-path core/Cargo.toml --release --locked --target aarch64-unknown-linux-gnu
|
||||
|
||||
- name: Core binary architecture
|
||||
run: node scripts/binary-arch.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --expect linux-arm64
|
||||
|
||||
- name: Required glibc symbols
|
||||
run: aarch64-linux-gnu-objdump -T core/target/aarch64-unknown-linux-gnu/release/teamspeach-core | grep -o 'GLIBC_[0-9.]*' | sort -Vu | tail -n1
|
||||
|
||||
- name: 16 KiB page compatibility (Asahi) of the core ELF
|
||||
run: node scripts/elf-pagesize.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --page 16384
|
||||
|
||||
- name: Core identity smoke under qemu-aarch64 (emulated, not native hardware)
|
||||
run: node scripts/core-smoke.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --wrapper "qemu-aarch64 -L /usr/aarch64-linux-gnu"
|
||||
@@ -0,0 +1,22 @@
|
||||
# dependencies and build output
|
||||
node_modules/
|
||||
dist/
|
||||
core-bin/
|
||||
core/target/
|
||||
|
||||
# local runtime data, logs and identities
|
||||
*.log
|
||||
identity*.ini
|
||||
teamspeach-identity*.ini
|
||||
smoke-out/
|
||||
smoke-voice-out/
|
||||
probe-stream-out/
|
||||
loopback-out/
|
||||
.env
|
||||
.env.*
|
||||
|
||||
# editors / OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
.vscode/
|
||||
.idea/
|
||||
@@ -0,0 +1,10 @@
|
||||
# TeamsPeach — notices
|
||||
|
||||
- TeamsPeach's own code carries no open-source license yet (`UNLICENSED` in package.json): all rights
|
||||
reserved by its owner until the owner chooses a license.
|
||||
- Electron and Chromium license texts ship at the root of the application directory
|
||||
(`LICENSE`, `LICENSES.chromium.html`), as placed there by electron-builder.
|
||||
- The native core (`teamspeach-core`, built on ReSpeak tsclientlib, libopus and other Rust crates)
|
||||
ships its complete third-party notices in `teamspeach-core-THIRD_PARTY_NOTICES.md` in this folder.
|
||||
- TeamSpeak is a trademark of TeamSpeak Systems GmbH. TeamsPeach is an independent client and is not
|
||||
affiliated with or endorsed by TeamSpeak Systems GmbH.
|
||||
@@ -0,0 +1,226 @@
|
||||
'use strict';
|
||||
|
||||
const { spawn } = require('node:child_process');
|
||||
const { EventEmitter } = require('node:events');
|
||||
const readline = require('node:readline');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const READY_TIMEOUT_MS = 15000;
|
||||
const STOP_TIMEOUT_MS = 6000;
|
||||
const AUDIO_BACKLOG_LIMIT = 128 * 1024;
|
||||
const MAX_LINE_BYTES = 256 * 1024;
|
||||
|
||||
const TIMEOUTS = {
|
||||
connect: 60000,
|
||||
disconnect: 10000,
|
||||
rename: 15000,
|
||||
join_channel: 15000,
|
||||
send_text: 15000,
|
||||
stream_list: 15000,
|
||||
default: 15000,
|
||||
};
|
||||
|
||||
/**
|
||||
* Owns one `teamspeach-core` child process speaking the newline-JSON protocol of docs/bridge.md.
|
||||
* Emits: 'event' (core event object), 'status' ({status, code?, message?, coreVersion?}).
|
||||
*/
|
||||
class CoreProcess extends EventEmitter {
|
||||
constructor({ binary, dataDir, logFile, logLevel }) {
|
||||
super();
|
||||
this.binary = binary;
|
||||
this.dataDir = dataDir;
|
||||
this.logFile = logFile;
|
||||
this.logLevel = logLevel || 'info';
|
||||
this.child = null;
|
||||
this.pending = new Map();
|
||||
this.nextId = 1;
|
||||
this.status = 'stopped';
|
||||
this.coreVersion = null;
|
||||
this.stopping = false;
|
||||
this.droppedAudioFrames = 0;
|
||||
}
|
||||
|
||||
start() {
|
||||
if (this.child) throw new Error('core already running');
|
||||
this.stopping = false;
|
||||
this.coreVersion = null;
|
||||
rotateLog(this.logFile);
|
||||
const log = fs.createWriteStream(this.logFile, { flags: 'a' });
|
||||
log.write(`\n=== ${new Date().toISOString()} start ${this.binary}\n`);
|
||||
|
||||
let child;
|
||||
try {
|
||||
child = spawn(this.binary, ['--data-dir', this.dataDir], {
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
windowsHide: true,
|
||||
env: { ...process.env, TEAMSPEACH_LOG: process.env.TEAMSPEACH_LOG || this.logLevel },
|
||||
});
|
||||
} catch (err) {
|
||||
log.end();
|
||||
this._setStatus('failed', { message: err.message });
|
||||
return;
|
||||
}
|
||||
this.child = child;
|
||||
this._setStatus('starting');
|
||||
|
||||
child.stderr.on('data', (chunk) => log.write(chunk));
|
||||
child.stdin.on('error', (err) => log.write(`[main] stdin error: ${err.message}\n`));
|
||||
|
||||
const rl = readline.createInterface({ input: child.stdout, crlfDelay: Infinity });
|
||||
rl.on('line', (line) => this._onLine(line, log));
|
||||
|
||||
const readyTimer = setTimeout(() => {
|
||||
if (this.status === 'starting') {
|
||||
log.write('[main] core did not report ready in time, terminating\n');
|
||||
this._setStatus('failed', { message: 'Ядро не ответило за 15 секунд' });
|
||||
child.kill();
|
||||
}
|
||||
}, READY_TIMEOUT_MS);
|
||||
|
||||
child.on('error', (err) => {
|
||||
clearTimeout(readyTimer);
|
||||
log.write(`[main] spawn error: ${err.message}\n`);
|
||||
this._setStatus('failed', { message: err.message });
|
||||
});
|
||||
|
||||
child.on('exit', (code, signal) => {
|
||||
clearTimeout(readyTimer);
|
||||
rl.close();
|
||||
log.write(`[main] core exited code=${code} signal=${signal}\n`);
|
||||
log.end();
|
||||
this.child = null;
|
||||
for (const [, entry] of this.pending) {
|
||||
clearTimeout(entry.timer);
|
||||
entry.resolve({ ok: false, error: { code: 'core_exited', message: 'Ядро завершило работу' } });
|
||||
}
|
||||
this.pending.clear();
|
||||
const expected = this.stopping;
|
||||
this._setStatus(expected ? 'stopped' : 'exited', { code, signal, message: exitMessage(code) });
|
||||
});
|
||||
|
||||
this.once('ready-internal', () => clearTimeout(readyTimer));
|
||||
}
|
||||
|
||||
_onLine(line, log) {
|
||||
if (!line) return;
|
||||
let msg;
|
||||
try {
|
||||
msg = JSON.parse(line);
|
||||
} catch {
|
||||
log.write(`[main] unparseable stdout line (${line.length} chars)\n`);
|
||||
return;
|
||||
}
|
||||
if (msg === null || typeof msg !== 'object') return;
|
||||
if (Object.prototype.hasOwnProperty.call(msg, 'id')) {
|
||||
const entry = this.pending.get(msg.id);
|
||||
if (!entry) return;
|
||||
this.pending.delete(msg.id);
|
||||
clearTimeout(entry.timer);
|
||||
entry.resolve(msg.ok ? { ok: true, result: msg.result ?? {} } : { ok: false, error: normalizeError(msg.error) });
|
||||
return;
|
||||
}
|
||||
if (msg.event === 'ready') {
|
||||
this.coreVersion = typeof msg.core_version === 'string' ? msg.core_version : null;
|
||||
if (msg.protocol !== 1) {
|
||||
log.write(`[main] unsupported core protocol ${msg.protocol}\n`);
|
||||
this._setStatus('failed', { message: `Неподдерживаемая версия протокола ядра: ${msg.protocol}` });
|
||||
this.child?.kill();
|
||||
return;
|
||||
}
|
||||
this.emit('ready-internal');
|
||||
this._setStatus('ready', { coreVersion: this.coreVersion });
|
||||
return;
|
||||
}
|
||||
if (typeof msg.event === 'string') this.emit('event', msg);
|
||||
}
|
||||
|
||||
_setStatus(status, extra = {}) {
|
||||
this.status = status;
|
||||
this.emit('status', { status, ...extra });
|
||||
}
|
||||
|
||||
get running() {
|
||||
return this.child !== null;
|
||||
}
|
||||
|
||||
request(cmd, args) {
|
||||
if (!this.child || this.status !== 'ready') {
|
||||
return Promise.resolve({ ok: false, error: { code: 'core_unavailable', message: 'Ядро не запущено' } });
|
||||
}
|
||||
const id = `m${this.nextId++}`;
|
||||
const payload = args === undefined ? { id, cmd } : { id, cmd, args };
|
||||
const line = JSON.stringify(payload) + '\n';
|
||||
if (Buffer.byteLength(line) > MAX_LINE_BYTES) {
|
||||
return Promise.resolve({ ok: false, error: { code: 'bad_request', message: 'Запрос слишком большой' } });
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
const timeoutMs = TIMEOUTS[cmd] ?? TIMEOUTS.default;
|
||||
const timer = setTimeout(() => {
|
||||
this.pending.delete(id);
|
||||
resolve({ ok: false, error: { code: 'timeout', message: `Ядро не ответило на «${cmd}» за ${Math.round(timeoutMs / 1000)} с` } });
|
||||
}, timeoutMs);
|
||||
this.pending.set(id, { resolve, timer });
|
||||
this.child.stdin.write(line);
|
||||
});
|
||||
}
|
||||
|
||||
/** audio_frame / audio_end: never answered. Frames are dropped instead of queueing unboundedly behind a stalled pipe. */
|
||||
sendAudio(cmd, args) {
|
||||
if (!this.child || this.status !== 'ready') return false;
|
||||
if (cmd === 'audio_frame' && this.child.stdin.writableLength > AUDIO_BACKLOG_LIMIT) {
|
||||
this.droppedAudioFrames += 1;
|
||||
return false;
|
||||
}
|
||||
this.child.stdin.write(JSON.stringify(args === undefined ? { cmd } : { cmd, args }) + '\n');
|
||||
return true;
|
||||
}
|
||||
|
||||
async stop() {
|
||||
const child = this.child;
|
||||
if (!child) return;
|
||||
this.stopping = true;
|
||||
const exited = new Promise((resolve) => child.once('exit', resolve));
|
||||
if (this.status === 'ready') {
|
||||
await Promise.race([this.request('shutdown'), delay(STOP_TIMEOUT_MS)]);
|
||||
} else {
|
||||
child.stdin.end();
|
||||
}
|
||||
const done = await Promise.race([exited.then(() => true), delay(STOP_TIMEOUT_MS).then(() => false)]);
|
||||
if (!done && this.child) {
|
||||
this.child.kill();
|
||||
await Promise.race([exited, delay(2000)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeError(error) {
|
||||
if (!error || typeof error !== 'object') return { code: 'internal', message: 'Пустой ответ об ошибке' };
|
||||
const out = { code: String(error.code ?? 'internal'), message: String(error.message ?? '') };
|
||||
if (error.ts_error && typeof error.ts_error === 'object') out.ts_error = error.ts_error;
|
||||
if (error.detail && typeof error.detail === 'object') out.detail = error.detail;
|
||||
return out;
|
||||
}
|
||||
|
||||
function exitMessage(code) {
|
||||
switch (code) {
|
||||
case 0: return 'Ядро завершило работу';
|
||||
case 2: return 'Ядро отклонило аргументы запуска';
|
||||
case 3: return 'Профиль уже используется другим экземпляром TeamsPeach или каталог данных недоступен';
|
||||
case 1: return 'Внутренняя ошибка ядра (подробности в журнале core.log)';
|
||||
default: return `Ядро завершилось с кодом ${code}`;
|
||||
}
|
||||
}
|
||||
|
||||
function rotateLog(file) {
|
||||
try {
|
||||
if (fs.statSync(file).size > 5 * 1024 * 1024) fs.renameSync(file, `${file}.1`);
|
||||
} catch {
|
||||
// no log yet
|
||||
}
|
||||
}
|
||||
|
||||
function delay(ms) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
module.exports = { CoreProcess };
|
||||
@@ -0,0 +1,137 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Allowlist + argument-shape validation for renderer → core requests.
|
||||
* The renderer may only call these bridge commands; `shutdown`, `audio_frame` and `audio_end`
|
||||
* are main-owned (audio has its own binary IPC channel). Unknown keys are rejected like the core does.
|
||||
*/
|
||||
|
||||
class ValidationError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.code = 'bad_request';
|
||||
}
|
||||
}
|
||||
|
||||
const CONTROL_CHARS = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
|
||||
|
||||
const str = (min, max, { multiline = false, maxBytes } = {}) => (value, key) => {
|
||||
if (typeof value !== 'string') throw new ValidationError(`${key}: ожидалась строка`);
|
||||
if (value.length < min || value.length > max) throw new ValidationError(`${key}: недопустимая длина`);
|
||||
if (maxBytes !== undefined && Buffer.byteLength(value, 'utf8') > maxBytes) throw new ValidationError(`${key}: слишком длинно`);
|
||||
if (multiline ? CONTROL_CHARS.test(value) : /[\u0000-\u001f\u007f]/.test(value)) {
|
||||
throw new ValidationError(`${key}: недопустимые управляющие символы`);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
const posInt = (value, key) => {
|
||||
if (!Number.isSafeInteger(value) || value < 0) throw new ValidationError(`${key}: ожидалось целое число`);
|
||||
return value;
|
||||
};
|
||||
|
||||
const bool = (value, key) => {
|
||||
if (typeof value !== 'boolean') throw new ValidationError(`${key}: ожидалось true/false`);
|
||||
return value;
|
||||
};
|
||||
|
||||
const oneOf = (...allowed) => (value, key) => {
|
||||
if (!allowed.includes(value)) throw new ValidationError(`${key}: недопустимое значение`);
|
||||
return value;
|
||||
};
|
||||
|
||||
const optional = (check) => {
|
||||
const wrapped = (value, key) => check(value, key);
|
||||
wrapped.optional = true;
|
||||
return wrapped;
|
||||
};
|
||||
|
||||
function isPlainObject(value) {
|
||||
return value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype;
|
||||
}
|
||||
|
||||
function shape(spec) {
|
||||
return (args) => {
|
||||
if (args === undefined || args === null) args = {};
|
||||
if (!isPlainObject(args)) throw new ValidationError('args: ожидался объект');
|
||||
for (const key of Object.keys(args)) {
|
||||
if (!Object.prototype.hasOwnProperty.call(spec, key)) throw new ValidationError(`${key}: неизвестный аргумент`);
|
||||
}
|
||||
const out = {};
|
||||
for (const [key, check] of Object.entries(spec)) {
|
||||
const value = args[key];
|
||||
if (value === undefined) {
|
||||
if (!check.optional) throw new ValidationError(`${key}: обязательный аргумент`);
|
||||
continue;
|
||||
}
|
||||
out[key] = check(value, key);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
}
|
||||
|
||||
const streamId = str(1, 256);
|
||||
const SIGNAL_COMMANDS = new Set(['answer', 'iceCandidate']);
|
||||
|
||||
function signalJson(value) {
|
||||
if (!isPlainObject(value)) throw new ValidationError('json: ожидался объект');
|
||||
const keys = Object.keys(value);
|
||||
if (keys.length !== 2 || !keys.includes('cmd') || !keys.includes('args')) throw new ValidationError('json: ожидались поля cmd и args');
|
||||
if (!SIGNAL_COMMANDS.has(value.cmd)) throw new ValidationError('json.cmd: недопустимая команда сигнализации');
|
||||
const args = value.args;
|
||||
if (!isPlainObject(args)) throw new ValidationError('json.args: ожидался объект');
|
||||
if (value.cmd === 'answer') {
|
||||
shape({ answer: str(1, 60000, { multiline: true }) })(args);
|
||||
} else {
|
||||
shape({
|
||||
mLine: posInt,
|
||||
mid: str(0, 64),
|
||||
sdp: str(0, 2048),
|
||||
})(args);
|
||||
}
|
||||
const serialized = JSON.stringify(value);
|
||||
if (Buffer.byteLength(serialized, 'utf8') > 60 * 1024) throw new ValidationError('json: больше 60 КиБ');
|
||||
return JSON.parse(serialized);
|
||||
}
|
||||
|
||||
const COMMANDS = {
|
||||
profile_get: shape({}),
|
||||
profile_create: shape({ nickname: str(1, 64) }),
|
||||
rename: shape({ nickname: str(1, 64) }),
|
||||
connect: shape({
|
||||
address: str(1, 255),
|
||||
server_password: optional(str(0, 255)),
|
||||
channel: optional(str(1, 512)),
|
||||
channel_password: optional(str(0, 255)),
|
||||
}),
|
||||
disconnect: shape({ message: optional(str(0, 80)) }),
|
||||
join_channel: shape({ channel_id: posInt, password: optional(str(0, 255)) }),
|
||||
send_text: (args) => {
|
||||
const out = shape({
|
||||
target: oneOf('channel', 'server', 'client'),
|
||||
client_id: optional(posInt),
|
||||
message: str(1, 8192, { multiline: true, maxBytes: 8192 }),
|
||||
})(args);
|
||||
if ((out.target === 'client') !== (out.client_id !== undefined)) {
|
||||
throw new ValidationError('client_id: обязателен только для личных сообщений');
|
||||
}
|
||||
return out;
|
||||
},
|
||||
set_audio: shape({ input_muted: optional(bool), output_muted: optional(bool) }),
|
||||
stream_list: shape({ client_id: optional(posInt) }),
|
||||
stream_join: shape({ stream_id: streamId, client_id: posInt, message: optional(str(0, 200)) }),
|
||||
stream_signal: shape({ stream_id: streamId, client_id: posInt, json: signalJson }),
|
||||
stream_leave: shape({ stream_id: streamId, client_id: posInt }),
|
||||
};
|
||||
|
||||
/** Returns sanitized args or throws ValidationError. */
|
||||
function validateRequest(cmd, args) {
|
||||
if (typeof cmd !== 'string' || !Object.prototype.hasOwnProperty.call(COMMANDS, cmd)) {
|
||||
const err = new ValidationError('Команда не разрешена');
|
||||
err.code = 'unknown_command';
|
||||
throw err;
|
||||
}
|
||||
return COMMANDS[cmd](args);
|
||||
}
|
||||
|
||||
module.exports = { validateRequest, ValidationError, RENDERER_COMMANDS: Object.keys(COMMANDS) };
|
||||
@@ -0,0 +1,431 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('node:path');
|
||||
const fs = require('node:fs');
|
||||
const { execFile } = require('node:child_process');
|
||||
const {
|
||||
app, BrowserWindow, ipcMain, protocol, session, nativeTheme, dialog, Menu, shell, clipboard,
|
||||
} = require('electron');
|
||||
|
||||
// A disposable profile directory for tests/second instances. Set by whoever launches the app, never by the renderer.
|
||||
const profileOverride = process.env.TEAMSPEACH_PROFILE_DIR;
|
||||
if (profileOverride) {
|
||||
if (!path.isAbsolute(profileOverride)) {
|
||||
console.error('TEAMSPEACH_PROFILE_DIR must be an absolute path');
|
||||
process.exit(2);
|
||||
}
|
||||
app.setPath('userData', profileOverride);
|
||||
}
|
||||
|
||||
const { RENDERER_DIR, resolveCoreBinary, dataDir, logsDir, prefsFile } = require('./paths');
|
||||
const { CoreProcess } = require('./core-process');
|
||||
const { validateRequest } = require('./ipc-validate');
|
||||
const { Prefs } = require('./prefs');
|
||||
|
||||
const APP_SCHEME = 'app';
|
||||
const APP_HOST = 'teamspeach';
|
||||
const APP_ORIGIN = `${APP_SCHEME}://${APP_HOST}`;
|
||||
|
||||
const CSP = [
|
||||
"default-src 'none'",
|
||||
"script-src 'self'",
|
||||
"style-src 'self'",
|
||||
"img-src 'self' data:",
|
||||
"media-src 'self' blob: mediastream:",
|
||||
"font-src 'self'",
|
||||
"connect-src 'none'",
|
||||
"worker-src 'self'",
|
||||
"base-uri 'none'",
|
||||
"form-action 'none'",
|
||||
"frame-src 'none'",
|
||||
"frame-ancestors 'none'",
|
||||
"object-src 'none'",
|
||||
].join('; ');
|
||||
|
||||
const MIME = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.png': 'image/png',
|
||||
'.woff2': 'font/woff2',
|
||||
'.json': 'application/json',
|
||||
};
|
||||
|
||||
// Chromium hides host candidates behind mDNS names when the page has no capture permission.
|
||||
// The TS6 streamer is native libwebrtc; plain host candidates keep LAN viewing working even while the mic is off.
|
||||
app.commandLine.appendSwitch('disable-features', 'WebRtcHideLocalIpsWithMdns');
|
||||
|
||||
protocol.registerSchemesAsPrivileged([
|
||||
{ scheme: APP_SCHEME, privileges: { standard: true, secure: true, supportFetchAPI: true, codeCache: true } },
|
||||
]);
|
||||
|
||||
let mainWindow = null;
|
||||
let core = null;
|
||||
let prefs = null;
|
||||
|
||||
const gotInstanceLock = app.requestSingleInstanceLock();
|
||||
if (!gotInstanceLock) {
|
||||
app.quit();
|
||||
} else {
|
||||
app.on('second-instance', () => {
|
||||
if (mainWindow) {
|
||||
if (mainWindow.isMinimized()) mainWindow.restore();
|
||||
mainWindow.focus();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let coreStatus = { status: 'starting' };
|
||||
let connectionState = 'disconnected';
|
||||
let quitting = false;
|
||||
let rendererLog = null;
|
||||
let rendererLogBudget = { windowStart: 0, count: 0 };
|
||||
|
||||
function isAppUrl(url) {
|
||||
return typeof url === 'string' && url.startsWith(`${APP_ORIGIN}/`);
|
||||
}
|
||||
|
||||
function trustedSender(event) {
|
||||
return Boolean(mainWindow && event.sender === mainWindow.webContents && event.senderFrame && isAppUrl(event.senderFrame.url));
|
||||
}
|
||||
|
||||
function sendToRenderer(channel, payload) {
|
||||
if (mainWindow && !mainWindow.isDestroyed()) mainWindow.webContents.send(channel, payload);
|
||||
}
|
||||
|
||||
// ---------- core lifecycle ----------
|
||||
|
||||
function startCore() {
|
||||
const binary = resolveCoreBinary();
|
||||
if (!binary.path) {
|
||||
coreStatus = { status: 'missing', candidates: binary.candidates };
|
||||
sendToRenderer('core:status', coreStatus);
|
||||
return;
|
||||
}
|
||||
fs.mkdirSync(logsDir(), { recursive: true });
|
||||
core = new CoreProcess({
|
||||
binary: binary.path,
|
||||
dataDir: dataDir(),
|
||||
logFile: path.join(logsDir(), 'core.log'),
|
||||
});
|
||||
core.on('status', (status) => {
|
||||
coreStatus = { ...status, binary: binary.path };
|
||||
if (status.status !== 'ready') connectionState = 'disconnected';
|
||||
sendToRenderer('core:status', coreStatus);
|
||||
});
|
||||
core.on('event', onCoreEvent);
|
||||
core.start();
|
||||
}
|
||||
|
||||
function onCoreEvent(evt) {
|
||||
if (evt.event === 'audio') {
|
||||
if (typeof evt.pcm !== 'string') return;
|
||||
const pcm = Buffer.from(evt.pcm, 'base64');
|
||||
if (pcm.length !== 1920) return;
|
||||
sendToRenderer('core:audio', { pcm, speakers: Array.isArray(evt.speakers) ? evt.speakers : [] });
|
||||
return;
|
||||
}
|
||||
if (evt.event === 'state' && typeof evt.state === 'string') connectionState = evt.state;
|
||||
sendToRenderer('core:event', evt);
|
||||
}
|
||||
|
||||
async function restartCore() {
|
||||
if (core) {
|
||||
const old = core;
|
||||
core = null;
|
||||
await old.stop();
|
||||
old.removeAllListeners();
|
||||
}
|
||||
startCore();
|
||||
}
|
||||
|
||||
function runCoreCli(args) {
|
||||
const binary = resolveCoreBinary();
|
||||
if (!binary.path) return Promise.resolve({ ok: false, error: { code: 'core_missing', message: 'Исполняемый файл ядра не найден' } });
|
||||
return new Promise((resolve) => {
|
||||
execFile(binary.path, args, { windowsHide: true, timeout: 30000, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
|
||||
if (stderr) appendLog('core-cli.log', stderr);
|
||||
const line = String(stdout || '').trim().split(/\r?\n/).filter(Boolean).pop();
|
||||
let parsed = null;
|
||||
try {
|
||||
parsed = line ? JSON.parse(line) : null;
|
||||
} catch {
|
||||
parsed = null;
|
||||
}
|
||||
if (parsed && typeof parsed === 'object') {
|
||||
resolve(parsed.ok ? { ok: true, uid: parsed.uid } : { ok: false, error: parsed.error || { code: 'internal', message: 'Неизвестная ошибка' } });
|
||||
return;
|
||||
}
|
||||
resolve({ ok: false, error: { code: 'internal', message: err ? err.message : 'Ядро не вернуло результат' } });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function appendLog(file, text) {
|
||||
try {
|
||||
fs.mkdirSync(logsDir(), { recursive: true });
|
||||
fs.appendFileSync(path.join(logsDir(), file), `${new Date().toISOString()} ${text}\n`);
|
||||
} catch {
|
||||
// logging must never break the app
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- identity backup (main-only, native dialogs) ----------
|
||||
|
||||
async function exportIdentity() {
|
||||
const result = await dialog.showSaveDialog(mainWindow, {
|
||||
title: 'Экспорт идентичности TeamsPeach',
|
||||
defaultPath: path.join(app.getPath('documents'), 'teamspeach-identity.ini'),
|
||||
filters: [{ name: 'Идентичность TeamSpeak', extensions: ['ini'] }],
|
||||
properties: ['showOverwriteConfirmation', 'createDirectory'],
|
||||
});
|
||||
if (result.canceled || !result.filePath) return { ok: false, canceled: true };
|
||||
const outcome = await runCoreCli(['identity', 'export', '--data-dir', dataDir(), '--out', result.filePath]);
|
||||
if (outcome.ok && process.platform !== 'win32') {
|
||||
try {
|
||||
fs.chmodSync(result.filePath, 0o600);
|
||||
} catch (err) {
|
||||
appendLog('core-cli.log', `chmod failed: ${err.message}`);
|
||||
}
|
||||
}
|
||||
return outcome.ok ? { ok: true, uid: outcome.uid, file: path.basename(result.filePath) } : outcome;
|
||||
}
|
||||
|
||||
async function importIdentity() {
|
||||
if (connectionState !== 'disconnected') {
|
||||
return { ok: false, error: { code: 'connected', message: 'Сначала отключитесь от сервера' } };
|
||||
}
|
||||
const identityExists = fs.existsSync(path.join(dataDir(), 'identity.json'));
|
||||
if (identityExists) {
|
||||
const confirm = await dialog.showMessageBox(mainWindow, {
|
||||
type: 'warning',
|
||||
title: 'Заменить идентичность?',
|
||||
message: 'Импорт заменит текущую идентичность.',
|
||||
detail: 'Текущий UID будет потерян, если у вас нет его резервной копии. Серверные права и группы привязаны к UID.',
|
||||
buttons: ['Отмена', 'Выбрать файл и заменить'],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
});
|
||||
if (confirm.response !== 1) return { ok: false, canceled: true };
|
||||
}
|
||||
const pick = await dialog.showOpenDialog(mainWindow, {
|
||||
title: 'Импорт идентичности',
|
||||
filters: [{ name: 'Идентичность TeamSpeak', extensions: ['ini'] }, { name: 'Все файлы', extensions: ['*'] }],
|
||||
properties: ['openFile'],
|
||||
});
|
||||
if (pick.canceled || pick.filePaths.length !== 1) return { ok: false, canceled: true };
|
||||
|
||||
const old = core;
|
||||
core = null;
|
||||
if (old) {
|
||||
await old.stop();
|
||||
old.removeAllListeners();
|
||||
}
|
||||
const args = ['identity', 'import', '--data-dir', dataDir(), '--in', pick.filePaths[0]];
|
||||
if (identityExists) args.push('--replace');
|
||||
const outcome = await runCoreCli(args);
|
||||
startCore();
|
||||
return outcome;
|
||||
}
|
||||
|
||||
// ---------- window ----------
|
||||
|
||||
function createWindow() {
|
||||
mainWindow = new BrowserWindow({
|
||||
width: 1220,
|
||||
height: 780,
|
||||
minWidth: 880,
|
||||
minHeight: 560,
|
||||
show: false,
|
||||
title: 'TeamsPeach',
|
||||
backgroundColor: nativeTheme.shouldUseDarkColors ? '#1a1817' : '#f6f3f0',
|
||||
icon: path.join(__dirname, '..', 'renderer', 'assets', 'icon.png'),
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, '..', 'preload', 'preload.js'),
|
||||
contextIsolation: true,
|
||||
sandbox: true,
|
||||
nodeIntegration: false,
|
||||
nodeIntegrationInWorker: false,
|
||||
webSecurity: true,
|
||||
spellcheck: false,
|
||||
autoplayPolicy: 'no-user-gesture-required',
|
||||
devTools: !app.isPackaged || process.env.TEAMSPEACH_DEVTOOLS === '1',
|
||||
},
|
||||
});
|
||||
mainWindow.once('ready-to-show', () => mainWindow.show());
|
||||
mainWindow.on('closed', () => {
|
||||
mainWindow = null;
|
||||
});
|
||||
mainWindow.loadURL(`${APP_ORIGIN}/index.html`);
|
||||
}
|
||||
|
||||
function registerProtocol() {
|
||||
protocol.handle(APP_SCHEME, async (request) => {
|
||||
const url = new URL(request.url);
|
||||
if (url.host !== APP_HOST) return new Response('Not found', { status: 404 });
|
||||
let rel;
|
||||
try {
|
||||
rel = decodeURIComponent(url.pathname);
|
||||
} catch {
|
||||
return new Response('Bad request', { status: 400 });
|
||||
}
|
||||
if (rel === '/' || rel === '') rel = '/index.html';
|
||||
const filePath = path.normalize(path.join(RENDERER_DIR, rel));
|
||||
if (!filePath.startsWith(RENDERER_DIR + path.sep)) return new Response('Forbidden', { status: 403 });
|
||||
const type = MIME[path.extname(filePath).toLowerCase()];
|
||||
if (!type) return new Response('Forbidden', { status: 403 });
|
||||
try {
|
||||
const body = await fs.promises.readFile(filePath);
|
||||
return new Response(body, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': type,
|
||||
'Content-Security-Policy': CSP,
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Cross-Origin-Opener-Policy': 'same-origin',
|
||||
'Referrer-Policy': 'no-referrer',
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
return new Response('Not found', { status: 404 });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function hardenSession() {
|
||||
const ses = session.defaultSession;
|
||||
ses.setPermissionRequestHandler((_wc, permission, callback, details) => {
|
||||
const mediaTypes = details && Array.isArray(details.mediaTypes) ? details.mediaTypes : [];
|
||||
const audioOnly = mediaTypes.length > 0 && mediaTypes.every((t) => t === 'audio');
|
||||
callback(permission === 'media' && audioOnly && isAppUrl(details.requestingUrl));
|
||||
});
|
||||
ses.setPermissionCheckHandler((_wc, permission, requestingOrigin) => {
|
||||
return (permission === 'media' || permission === 'speaker-selection') && requestingOrigin === APP_ORIGIN;
|
||||
});
|
||||
ses.setDisplayMediaRequestHandler((_request, callback) => callback({}));
|
||||
}
|
||||
|
||||
app.on('web-contents-created', (_event, contents) => {
|
||||
contents.on('will-navigate', (event, url) => {
|
||||
if (!isAppUrl(url)) event.preventDefault();
|
||||
});
|
||||
contents.on('will-redirect', (event, url) => {
|
||||
if (!isAppUrl(url)) event.preventDefault();
|
||||
});
|
||||
contents.setWindowOpenHandler(() => ({ action: 'deny' }));
|
||||
contents.on('will-attach-webview', (event) => event.preventDefault());
|
||||
});
|
||||
|
||||
// ---------- IPC ----------
|
||||
|
||||
function registerIpc() {
|
||||
ipcMain.handle('core:request', async (event, cmd, args) => {
|
||||
if (!trustedSender(event)) return { ok: false, error: { code: 'forbidden', message: 'forbidden' } };
|
||||
let clean;
|
||||
try {
|
||||
clean = validateRequest(cmd, args);
|
||||
} catch (err) {
|
||||
return { ok: false, error: { code: err.code || 'bad_request', message: err.message } };
|
||||
}
|
||||
if (!core) return { ok: false, error: { code: 'core_unavailable', message: 'Ядро не запущено' } };
|
||||
const hasArgs = Object.keys(clean).length > 0;
|
||||
return core.request(cmd, hasArgs ? clean : undefined);
|
||||
});
|
||||
|
||||
ipcMain.on('core:audio-frame', (event, frame) => {
|
||||
if (!core || !trustedSender(event)) return;
|
||||
if (!(frame instanceof Uint8Array) || frame.byteLength !== 1920) return;
|
||||
core.sendAudio('audio_frame', { pcm: Buffer.from(frame.buffer, frame.byteOffset, frame.byteLength).toString('base64') });
|
||||
});
|
||||
|
||||
ipcMain.on('core:audio-end', (event) => {
|
||||
if (!core || !trustedSender(event)) return;
|
||||
core.sendAudio('audio_end');
|
||||
});
|
||||
|
||||
ipcMain.handle('core:status', (event) => (trustedSender(event) ? coreStatus : null));
|
||||
|
||||
ipcMain.handle('core:restart', async (event) => {
|
||||
if (!trustedSender(event)) return false;
|
||||
await restartCore();
|
||||
return true;
|
||||
});
|
||||
|
||||
ipcMain.handle('app:info', (event) => {
|
||||
if (!trustedSender(event)) return null;
|
||||
return {
|
||||
appVersion: app.getVersion(),
|
||||
electron: process.versions.electron,
|
||||
chrome: process.versions.chrome,
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
packaged: app.isPackaged,
|
||||
coreVersion: core ? core.coreVersion : null,
|
||||
coreBinary: coreStatus.binary || null,
|
||||
dataDir: dataDir(),
|
||||
logsDir: logsDir(),
|
||||
};
|
||||
});
|
||||
|
||||
ipcMain.handle('prefs:get', (event) => (trustedSender(event) ? prefs.get() : null));
|
||||
ipcMain.handle('prefs:set', (event, partial) => {
|
||||
if (!trustedSender(event)) return { ok: false };
|
||||
try {
|
||||
return { ok: true, prefs: prefs.set(partial) };
|
||||
} catch (err) {
|
||||
return { ok: false, message: err.message };
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('identity:export', (event) => (trustedSender(event) ? exportIdentity() : { ok: false }));
|
||||
ipcMain.handle('identity:import', (event) => (trustedSender(event) ? importIdentity() : { ok: false }));
|
||||
|
||||
ipcMain.handle('clipboard:write', (event, text) => {
|
||||
if (!trustedSender(event) || typeof text !== 'string' || text.length > 4096) return false;
|
||||
clipboard.writeText(text);
|
||||
return true;
|
||||
});
|
||||
|
||||
ipcMain.handle('app:open-logs', async (event) => {
|
||||
if (!trustedSender(event)) return false;
|
||||
fs.mkdirSync(logsDir(), { recursive: true });
|
||||
return (await shell.openPath(logsDir())) === '';
|
||||
});
|
||||
|
||||
ipcMain.on('app:log', (event, level, message) => {
|
||||
if (!trustedSender(event) || typeof message !== 'string') return;
|
||||
const now = Date.now();
|
||||
if (now - rendererLogBudget.windowStart > 1000) rendererLogBudget = { windowStart: now, count: 0 };
|
||||
if (++rendererLogBudget.count > 40) return;
|
||||
const lvl = ['debug', 'info', 'warn', 'error'].includes(level) ? level : 'info';
|
||||
if (!rendererLog) {
|
||||
fs.mkdirSync(logsDir(), { recursive: true });
|
||||
rendererLog = fs.createWriteStream(path.join(logsDir(), 'renderer.log'), { flags: 'a' });
|
||||
}
|
||||
rendererLog.write(`${new Date().toISOString()} ${lvl} ${message.slice(0, 4000).replace(/[\r\n]+/g, ' ')}\n`);
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- app lifecycle ----------
|
||||
|
||||
app.whenReady().then(() => {
|
||||
if (!gotInstanceLock) return;
|
||||
Menu.setApplicationMenu(null);
|
||||
prefs = new Prefs(prefsFile());
|
||||
registerProtocol();
|
||||
hardenSession();
|
||||
registerIpc();
|
||||
createWindow();
|
||||
startCore();
|
||||
});
|
||||
|
||||
app.on('window-all-closed', () => app.quit());
|
||||
|
||||
app.on('before-quit', (event) => {
|
||||
if (quitting || !core || !core.running) return;
|
||||
event.preventDefault();
|
||||
quitting = true;
|
||||
core.stop().finally(() => app.quit());
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('node:path');
|
||||
const fs = require('node:fs');
|
||||
const { app } = require('electron');
|
||||
|
||||
const CORE_FILE = process.platform === 'win32' ? 'teamspeach-core.exe' : 'teamspeach-core';
|
||||
const APP_ROOT = path.resolve(__dirname, '..', '..');
|
||||
const RENDERER_DIR = path.join(APP_ROOT, 'app', 'renderer');
|
||||
|
||||
/** Candidate locations of the native core. Only main decides these; nothing comes from the renderer. */
|
||||
function coreCandidates() {
|
||||
if (app.isPackaged) return [path.join(process.resourcesPath, 'core', CORE_FILE)];
|
||||
return [
|
||||
path.join(APP_ROOT, 'core', 'target', 'release', CORE_FILE),
|
||||
path.join(APP_ROOT, 'core', 'target', 'debug', CORE_FILE),
|
||||
];
|
||||
}
|
||||
|
||||
/** Newest existing candidate wins in development so a fresh debug build is not shadowed by a stale release build. */
|
||||
function resolveCoreBinary() {
|
||||
const candidates = coreCandidates();
|
||||
let best = null;
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
const stat = fs.statSync(candidate);
|
||||
if (stat.isFile() && (!best || stat.mtimeMs > best.mtimeMs)) best = { path: candidate, mtimeMs: stat.mtimeMs };
|
||||
} catch {
|
||||
// missing candidate
|
||||
}
|
||||
}
|
||||
return { path: best ? best.path : null, candidates };
|
||||
}
|
||||
|
||||
function dataDir() {
|
||||
return path.join(app.getPath('userData'), 'core');
|
||||
}
|
||||
|
||||
function logsDir() {
|
||||
return path.join(app.getPath('userData'), 'logs');
|
||||
}
|
||||
|
||||
function prefsFile() {
|
||||
return path.join(app.getPath('userData'), 'prefs.json');
|
||||
}
|
||||
|
||||
module.exports = { APP_ROOT, RENDERER_DIR, CORE_FILE, resolveCoreBinary, dataDir, logsDir, prefsFile };
|
||||
@@ -0,0 +1,66 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
/**
|
||||
* UI preferences owned by main (identity/nickname live in the core data dir, never here).
|
||||
* Every key has a validator; unknown keys and wrong types are rejected.
|
||||
*/
|
||||
const SCHEMA = {
|
||||
lastAddress: { default: '', check: (v) => typeof v === 'string' && v.length <= 255 && !/[\u0000-\u001f]/.test(v) },
|
||||
transmitMode: { default: 'ptt', check: (v) => v === 'ptt' || v === 'open' },
|
||||
pttCode: { default: 'F8', check: (v) => typeof v === 'string' && /^[A-Za-z0-9]{1,32}$/.test(v) },
|
||||
inputDeviceId: { default: '', check: (v) => typeof v === 'string' && v.length <= 512 },
|
||||
outputDeviceId: { default: '', check: (v) => typeof v === 'string' && v.length <= 512 },
|
||||
echoCancellation: { default: true, check: (v) => typeof v === 'boolean' },
|
||||
noiseSuppression: { default: true, check: (v) => typeof v === 'boolean' },
|
||||
autoGainControl: { default: true, check: (v) => typeof v === 'boolean' },
|
||||
voiceVolume: { default: 100, check: (v) => Number.isInteger(v) && v >= 0 && v <= 200 },
|
||||
streamVolume: { default: 100, check: (v) => Number.isInteger(v) && v >= 0 && v <= 100 },
|
||||
};
|
||||
|
||||
class Prefs {
|
||||
constructor(file) {
|
||||
this.file = file;
|
||||
this.values = defaults();
|
||||
try {
|
||||
const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
if (raw && typeof raw === 'object') {
|
||||
for (const [key, spec] of Object.entries(SCHEMA)) {
|
||||
if (Object.prototype.hasOwnProperty.call(raw, key) && spec.check(raw[key])) this.values[key] = raw[key];
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// first run or unreadable file: defaults
|
||||
}
|
||||
}
|
||||
|
||||
get() {
|
||||
return { ...this.values };
|
||||
}
|
||||
|
||||
/** Applies a validated partial update; returns the full prefs or throws. */
|
||||
set(partial) {
|
||||
if (!partial || typeof partial !== 'object' || Array.isArray(partial)) throw new Error('prefs: ожидался объект');
|
||||
const next = { ...this.values };
|
||||
for (const [key, value] of Object.entries(partial)) {
|
||||
const spec = SCHEMA[key];
|
||||
if (!spec) throw new Error(`prefs: неизвестный ключ ${key}`);
|
||||
if (!spec.check(value)) throw new Error(`prefs: недопустимое значение ${key}`);
|
||||
next[key] = value;
|
||||
}
|
||||
this.values = next;
|
||||
fs.mkdirSync(path.dirname(this.file), { recursive: true });
|
||||
const tmp = `${this.file}.tmp`;
|
||||
fs.writeFileSync(tmp, JSON.stringify(next, null, 2));
|
||||
fs.renameSync(tmp, this.file);
|
||||
return this.get();
|
||||
}
|
||||
}
|
||||
|
||||
function defaults() {
|
||||
return Object.fromEntries(Object.entries(SCHEMA).map(([key, spec]) => [key, spec.default]));
|
||||
}
|
||||
|
||||
module.exports = { Prefs };
|
||||
@@ -0,0 +1,30 @@
|
||||
'use strict';
|
||||
|
||||
// Sandboxed preload: the only surface the renderer gets. No paths, no commands, no generic IPC.
|
||||
const { contextBridge, ipcRenderer } = require('electron');
|
||||
|
||||
function subscribe(channel, callback) {
|
||||
if (typeof callback !== 'function') throw new TypeError('callback must be a function');
|
||||
const handler = (_event, payload) => callback(payload);
|
||||
ipcRenderer.on(channel, handler);
|
||||
return () => ipcRenderer.removeListener(channel, handler);
|
||||
}
|
||||
|
||||
contextBridge.exposeInMainWorld('teamspeach', {
|
||||
request: (cmd, args) => ipcRenderer.invoke('core:request', cmd, args),
|
||||
sendAudioFrame: (frame) => ipcRenderer.send('core:audio-frame', frame),
|
||||
endAudio: () => ipcRenderer.send('core:audio-end'),
|
||||
onEvent: (callback) => subscribe('core:event', callback),
|
||||
onAudio: (callback) => subscribe('core:audio', callback),
|
||||
onCoreStatus: (callback) => subscribe('core:status', callback),
|
||||
getCoreStatus: () => ipcRenderer.invoke('core:status'),
|
||||
restartCore: () => ipcRenderer.invoke('core:restart'),
|
||||
getAppInfo: () => ipcRenderer.invoke('app:info'),
|
||||
getPrefs: () => ipcRenderer.invoke('prefs:get'),
|
||||
setPrefs: (partial) => ipcRenderer.invoke('prefs:set', partial),
|
||||
exportIdentity: () => ipcRenderer.invoke('identity:export'),
|
||||
importIdentity: () => ipcRenderer.invoke('identity:import'),
|
||||
copyText: (text) => ipcRenderer.invoke('clipboard:write', text),
|
||||
openLogs: () => ipcRenderer.invoke('app:open-logs'),
|
||||
log: (level, message) => ipcRenderer.send('app:log', level, String(message)),
|
||||
});
|
||||
|
After Width: | Height: | Size: 17 KiB |
@@ -0,0 +1,269 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; media-src 'self' blob: mediastream:; font-src 'self'; connect-src 'none'; worker-src 'self'; base-uri 'none'; form-action 'none'; frame-src 'none'; object-src 'none'">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<title>TeamsPeach</title>
|
||||
<link rel="stylesheet" href="styles/app.css">
|
||||
<script type="module" src="js/app.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<svg class="sprite" aria-hidden="true" focusable="false">
|
||||
<symbol id="i-mic" viewBox="0 0 24 24"><rect x="9" y="3" width="6" height="11" rx="3"/><path d="M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21"/></symbol>
|
||||
<symbol id="i-mic-off" viewBox="0 0 24 24"><path d="M15 9.5V6a3 3 0 0 0-5.6-1.5M9 9v2a3 3 0 0 0 4.7 2.5M18.5 11a6.5 6.5 0 0 1-1 3.4M5.5 11a6.5 6.5 0 0 0 10 5.5M12 17.5V21M4 4l16 16"/></symbol>
|
||||
<symbol id="i-headphones" viewBox="0 0 24 24"><path d="M4 15v-3a8 8 0 0 1 16 0v3"/><rect x="3" y="14" width="4.5" height="6.5" rx="1.6"/><rect x="16.5" y="14" width="4.5" height="6.5" rx="1.6"/></symbol>
|
||||
<symbol id="i-headphones-off" viewBox="0 0 24 24"><path d="M4 15v-3a8 8 0 0 1 12.2-6.8M19.3 9A8 8 0 0 1 20 12v3"/><rect x="3" y="14" width="4.5" height="6.5" rx="1.6"/><rect x="16.5" y="14" width="4.5" height="6.5" rx="1.6"/><path d="M3.5 3.5l17 17"/></symbol>
|
||||
<symbol id="i-sliders" viewBox="0 0 24 24"><path d="M4 7h9.5M18.5 7H20M4 17h3.5M12.5 17H20"/><circle cx="16" cy="7" r="2.3"/><circle cx="10" cy="17" r="2.3"/></symbol>
|
||||
<symbol id="i-monitor" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="12" rx="2"/><path d="M8.5 20h7M12 16v4"/></symbol>
|
||||
<symbol id="i-play" viewBox="0 0 24 24"><path d="M9 7.2v9.6l7.6-4.8z"/></symbol>
|
||||
<symbol id="i-x" viewBox="0 0 24 24"><path d="M6.5 6.5l11 11M17.5 6.5l-11 11"/></symbol>
|
||||
<symbol id="i-send" viewBox="0 0 24 24"><path d="M4.5 11.6L19.5 4.5l-5.2 15-2.9-6.2zM11.4 13.3l8.1-8.8"/></symbol>
|
||||
<symbol id="i-copy" viewBox="0 0 24 24"><rect x="8.5" y="8.5" width="11.5" height="11.5" rx="2"/><path d="M15.5 8.5V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v7.5a2 2 0 0 0 2 2h2.5"/></symbol>
|
||||
<symbol id="i-lock" viewBox="0 0 24 24"><rect x="5" y="11" width="14" height="9.5" rx="2"/><path d="M8.5 11V8a3.5 3.5 0 0 1 7 0v3"/></symbol>
|
||||
<symbol id="i-channel" viewBox="0 0 24 24"><path d="M5 9.5h14M5 14.5h14M10.5 4.5l-2 15M15.5 4.5l-2 15"/></symbol>
|
||||
<symbol id="i-logout" viewBox="0 0 24 24"><path d="M14.5 4.5h3a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2h-3M10 16l4-4-4-4M14 12H4.5"/></symbol>
|
||||
<symbol id="i-speaker" viewBox="0 0 24 24"><path d="M4.5 9.5v5h3.8l4.7 4V5.5l-4.7 4z"/><path d="M16.3 8.8a4.6 4.6 0 0 1 0 6.4M18.8 6.3a8.2 8.2 0 0 1 0 11.4"/></symbol>
|
||||
<symbol id="i-speaker-off" viewBox="0 0 24 24"><path d="M4.5 9.5v5h3.8l4.7 4V5.5l-4.7 4z"/><path d="M16.5 9.5l5 5M21.5 9.5l-5 5"/></symbol>
|
||||
<symbol id="i-fullscreen" viewBox="0 0 24 24"><path d="M4.5 9V4.5H9M15 4.5h4.5V9M19.5 15v4.5H15M9 19.5H4.5V15"/></symbol>
|
||||
<symbol id="i-back" viewBox="0 0 24 24"><path d="M14.5 5.5L8 12l6.5 6.5"/></symbol>
|
||||
<symbol id="i-moon" viewBox="0 0 24 24"><path d="M19.5 14.6A7.8 7.8 0 1 1 9.4 4.5a6.2 6.2 0 0 0 10.1 10.1z"/></symbol>
|
||||
<symbol id="i-message" viewBox="0 0 24 24"><path d="M4.5 5.5h15v10.5h-9.5l-5.5 4z"/></symbol>
|
||||
<symbol id="i-peach" viewBox="0 0 24 24"><path class="peach-body" d="M12 7.2c-4.6-1.6-8 1.6-8 6 0 4.6 3.6 8.3 8 8.3s8-3.7 8-8.3c0-4.4-3.4-7.6-8-6z"/><path class="peach-crease" d="M12 7.6c-1.8 2.6-2 8.6 0 13.6"/><path class="peach-leaf" d="M12.2 6.8c.2-2.6 2-4.2 5-4.3-.3 2.7-2.1 4.2-5 4.3z"/></symbol>
|
||||
</svg>
|
||||
|
||||
<div id="boot" class="boot" role="status">
|
||||
<svg class="icon brand-mark" aria-hidden="true"><use href="#i-peach"/></svg>
|
||||
<p id="boot-text">Запуск ядра…</p>
|
||||
</div>
|
||||
|
||||
<main id="view-fatal" class="fatal" hidden>
|
||||
<div class="fatal-inner">
|
||||
<svg class="icon brand-mark" aria-hidden="true"><use href="#i-peach"/></svg>
|
||||
<h1 id="fatal-title">Ядро недоступно</h1>
|
||||
<p id="fatal-text"></p>
|
||||
<ul id="fatal-list" class="fatal-list"></ul>
|
||||
<div class="fatal-actions">
|
||||
<button id="fatal-retry" class="btn btn-primary" type="button">Перезапустить ядро</button>
|
||||
<button id="fatal-import" class="btn" type="button" hidden>Импортировать резервную копию…</button>
|
||||
<button id="fatal-logs" class="btn" type="button">Открыть журналы</button>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<main id="view-onboarding" class="onboarding" hidden>
|
||||
<form id="onboarding-form" class="onboarding-form" novalidate>
|
||||
<svg class="icon brand-mark brand-mark-large" aria-hidden="true"><use href="#i-peach"/></svg>
|
||||
<h1>Как вас называть?</h1>
|
||||
<p class="lede">Никнейм видят все на сервере. Его можно сменить позже — ваш постоянный идентификатор (UID) при этом не меняется.</p>
|
||||
<label class="field">
|
||||
<span class="field-label">Никнейм</span>
|
||||
<input id="onboarding-nick" name="nickname" type="text" autocomplete="off" spellcheck="false" maxlength="30" required aria-describedby="onboarding-hint onboarding-error">
|
||||
</label>
|
||||
<p id="onboarding-hint" class="hint">От 3 до 30 символов.</p>
|
||||
<p id="onboarding-existing" class="hint" hidden></p>
|
||||
<p id="onboarding-error" class="form-error" role="alert"></p>
|
||||
<button id="onboarding-submit" class="btn btn-primary btn-wide" type="submit">Продолжить</button>
|
||||
<p class="hint">TeamsPeach создаст на этом компьютере криптографическую идентичность. Регистрация не нужна.</p>
|
||||
<button id="onboarding-import" class="btn btn-ghost" type="button">Восстановить из резервной копии…</button>
|
||||
</form>
|
||||
</main>
|
||||
|
||||
<div id="view-app" class="shell" hidden>
|
||||
<aside class="sidebar" aria-label="Сервер">
|
||||
<header class="server-head">
|
||||
<div class="server-title">
|
||||
<span id="server-name" class="server-name">Нет подключения</span>
|
||||
<span id="conn-badge" class="conn-badge" data-state="disconnected">не подключено</span>
|
||||
</div>
|
||||
<button id="btn-disconnect" class="icon-btn" type="button" aria-label="Отключиться от сервера" title="Отключиться" hidden>
|
||||
<svg class="icon" aria-hidden="true"><use href="#i-logout"/></svg>
|
||||
</button>
|
||||
</header>
|
||||
<p id="tree-empty" class="tree-empty">Каналы появятся после подключения к серверу.</p>
|
||||
<ul id="tree" class="tree" aria-label="Каналы и участники"></ul>
|
||||
<footer class="self">
|
||||
<div class="self-id">
|
||||
<span id="self-dot" class="status-dot" aria-hidden="true"></span>
|
||||
<div class="self-text">
|
||||
<div id="self-nick" class="self-nick"></div>
|
||||
<div id="self-sub" class="self-sub"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="self-actions">
|
||||
<button id="btn-mute" class="icon-btn" type="button" aria-pressed="false" aria-label="Микрофон" title="Выключить микрофон">
|
||||
<svg class="icon" aria-hidden="true"><use href="#i-mic"/></svg>
|
||||
</button>
|
||||
<button id="btn-deafen" class="icon-btn" type="button" aria-pressed="false" aria-label="Звук" title="Выключить звук">
|
||||
<svg class="icon" aria-hidden="true"><use href="#i-headphones"/></svg>
|
||||
</button>
|
||||
<button id="btn-settings" class="icon-btn" type="button" aria-label="Настройки" title="Настройки">
|
||||
<svg class="icon" aria-hidden="true"><use href="#i-sliders"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
</footer>
|
||||
</aside>
|
||||
|
||||
<main class="workspace">
|
||||
<section id="connect-view" class="connect-view" aria-labelledby="connect-title">
|
||||
<form id="connect-form" class="connect-form" novalidate>
|
||||
<h1 id="connect-title">Подключение к серверу</h1>
|
||||
<p id="connect-identity" class="lede"></p>
|
||||
<label class="field">
|
||||
<span class="field-label">Адрес сервера</span>
|
||||
<input id="connect-address" name="address" type="text" autocomplete="off" spellcheck="false" placeholder="адрес или адрес:9987" required>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Пароль сервера <span class="optional">необязательно</span></span>
|
||||
<input id="connect-password" name="password" type="password" autocomplete="off">
|
||||
</label>
|
||||
<p id="connect-error" class="form-error" role="alert"></p>
|
||||
<div class="form-actions">
|
||||
<button id="connect-submit" class="btn btn-primary" type="submit">Подключиться</button>
|
||||
<span id="connect-status" class="form-status" role="status"></span>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section id="session-view" class="session-view" hidden>
|
||||
<header class="session-head">
|
||||
<div class="session-title">
|
||||
<h1 id="channel-title"></h1>
|
||||
<p id="channel-topic" class="channel-topic"></p>
|
||||
</div>
|
||||
<div class="transmit">
|
||||
<span id="transmit-hint" class="transmit-hint"></span>
|
||||
<button id="btn-ptt" class="btn btn-ptt" type="button" aria-pressed="false">Удерживайте, чтобы говорить</button>
|
||||
</div>
|
||||
</header>
|
||||
<p id="session-notice" class="notice" role="status" hidden></p>
|
||||
|
||||
<section id="stream-view" class="stream-view" aria-label="Трансляция" hidden>
|
||||
<div class="stream-stage">
|
||||
<video id="stream-video" autoplay playsinline></video>
|
||||
<div id="stream-overlay" class="stream-overlay" role="status"></div>
|
||||
</div>
|
||||
<div class="stream-bar">
|
||||
<div class="stream-meta">
|
||||
<strong id="stream-title" class="stream-title"></strong>
|
||||
<span id="stream-stats" class="stream-stats"></span>
|
||||
</div>
|
||||
<div class="stream-controls">
|
||||
<button id="stream-mute" class="icon-btn" type="button" aria-pressed="false" aria-label="Звук трансляции" title="Выключить звук трансляции">
|
||||
<svg class="icon" aria-hidden="true"><use href="#i-speaker"/></svg>
|
||||
</button>
|
||||
<input id="stream-volume" class="range" type="range" min="0" max="100" step="1" aria-label="Громкость трансляции">
|
||||
<output id="stream-volume-value" class="range-value" for="stream-volume"></output>
|
||||
<button id="stream-fullscreen" class="icon-btn" type="button" aria-label="Во весь экран" title="Во весь экран">
|
||||
<svg class="icon" aria-hidden="true"><use href="#i-fullscreen"/></svg>
|
||||
</button>
|
||||
<button id="stream-stop" class="btn" type="button">Прекратить просмотр</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="chat" aria-label="Чат">
|
||||
<div id="chat-tabs" class="chat-tabs" role="tablist" aria-label="Чаты"></div>
|
||||
<ol id="chat-log" class="chat-log" role="log" aria-live="polite" aria-relevant="additions" tabindex="0"></ol>
|
||||
<form id="chat-form" class="composer" novalidate>
|
||||
<textarea id="chat-input" rows="1" aria-label="Сообщение" placeholder="Сообщение"></textarea>
|
||||
<button id="chat-send" class="icon-btn icon-btn-accent" type="submit" aria-label="Отправить" title="Отправить (Enter)">
|
||||
<svg class="icon" aria-hidden="true"><use href="#i-send"/></svg>
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section id="settings-view" class="settings-view" hidden aria-labelledby="settings-title">
|
||||
<header class="settings-head">
|
||||
<button id="settings-back" class="btn btn-ghost" type="button">
|
||||
<svg class="icon" aria-hidden="true"><use href="#i-back"/></svg>Назад
|
||||
</button>
|
||||
<h1 id="settings-title">Настройки</h1>
|
||||
</header>
|
||||
<div class="settings-body">
|
||||
<section class="settings-section" aria-labelledby="set-profile">
|
||||
<h2 id="set-profile">Профиль</h2>
|
||||
<form id="rename-form" class="row-form" novalidate>
|
||||
<label class="field field-grow">
|
||||
<span class="field-label">Никнейм</span>
|
||||
<input id="rename-input" type="text" autocomplete="off" spellcheck="false" maxlength="30">
|
||||
</label>
|
||||
<button id="rename-submit" class="btn btn-primary" type="submit">Сохранить</button>
|
||||
</form>
|
||||
<p id="rename-status" class="form-status" role="status"></p>
|
||||
<div class="uid-block">
|
||||
<span class="field-label">Публичный UID</span>
|
||||
<div class="uid-row">
|
||||
<code id="uid-value" class="uid-value"></code>
|
||||
<button id="uid-copy" class="btn btn-ghost" type="button"><svg class="icon" aria-hidden="true"><use href="#i-copy"/></svg>Копировать</button>
|
||||
</div>
|
||||
<p class="hint">UID — отпечаток вашего открытого ключа. Серверы TeamSpeak по нему узнают вас и выдают права; смена никнейма его не меняет.</p>
|
||||
<p id="security-level" class="hint"></p>
|
||||
</div>
|
||||
<div class="backup">
|
||||
<h3>Резервная копия идентичности</h3>
|
||||
<p class="hint">Файл содержит закрытый ключ. Храните его как пароль: тот, у кого он есть, может выдавать себя за вас.</p>
|
||||
<div class="form-actions">
|
||||
<button id="identity-export" class="btn" type="button">Экспортировать…</button>
|
||||
<button id="identity-import" class="btn" type="button">Импортировать…</button>
|
||||
</div>
|
||||
<p id="identity-status" class="form-status" role="status"></p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="settings-section" aria-labelledby="set-audio">
|
||||
<h2 id="set-audio">Звук</h2>
|
||||
<label class="field">
|
||||
<span class="field-label">Микрофон</span>
|
||||
<select id="input-device"></select>
|
||||
</label>
|
||||
<div class="meter-row">
|
||||
<div class="meter" aria-hidden="true"><div id="mic-meter" class="meter-fill"></div></div>
|
||||
<button id="mic-test" class="btn btn-ghost" type="button" aria-pressed="false">Проверить микрофон</button>
|
||||
</div>
|
||||
<label class="field">
|
||||
<span class="field-label">Устройство вывода</span>
|
||||
<select id="output-device"></select>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Громкость голосов <output id="voice-volume-value" for="voice-volume"></output></span>
|
||||
<input id="voice-volume" class="range" type="range" min="0" max="200" step="5">
|
||||
</label>
|
||||
<fieldset class="fieldset">
|
||||
<legend class="field-label">Передача голоса</legend>
|
||||
<label class="choice"><input type="radio" name="transmit" value="ptt"> Нажми и говори</label>
|
||||
<label class="choice"><input type="radio" name="transmit" value="open"> Открытый микрофон</label>
|
||||
</fieldset>
|
||||
<div class="ptt-row">
|
||||
<span class="field-label">Клавиша «нажми и говори»</span>
|
||||
<kbd id="ptt-key" class="kbd"></kbd>
|
||||
<button id="ptt-assign" class="btn btn-ghost" type="button">Назначить</button>
|
||||
</div>
|
||||
<p id="ptt-hint" class="hint">Клавиша работает, пока окно TeamsPeach активно. Буквенные клавиши не срабатывают во время набора текста.</p>
|
||||
<fieldset class="fieldset">
|
||||
<legend class="field-label">Обработка микрофона</legend>
|
||||
<label class="choice"><input id="opt-ns" type="checkbox"> Шумоподавление</label>
|
||||
<label class="choice"><input id="opt-ec" type="checkbox"> Эхоподавление</label>
|
||||
<label class="choice"><input id="opt-agc" type="checkbox"> Автоматическая громкость</label>
|
||||
</fieldset>
|
||||
</section>
|
||||
|
||||
<section class="settings-section" aria-labelledby="set-diag">
|
||||
<h2 id="set-diag">О программе</h2>
|
||||
<dl id="diag-list" class="diag-list"></dl>
|
||||
<h3>Видеокодеки для просмотра трансляций</h3>
|
||||
<p class="hint">Список, который движок Chromium этой сборки реально объявляет для приёма. Какой кодек выбран в трансляции, видно в панели просмотра.</p>
|
||||
<ul id="codec-list" class="codec-list"></ul>
|
||||
<div class="form-actions">
|
||||
<button id="open-logs" class="btn" type="button">Открыть журналы</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<div id="toasts" class="toasts" aria-live="polite" aria-atomic="false"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,468 @@
|
||||
// TeamsPeach renderer entry: core lifecycle, onboarding, connection, self controls and view routing.
|
||||
import { $, h, setIcon, setText } from './dom.js';
|
||||
import { S, emit, isConnected, ownChannel } from './state.js';
|
||||
import { tp, call, log } from './core.js';
|
||||
import { errorText, shortUid, stripBBCode } from './text.js';
|
||||
import { toast } from './toast.js';
|
||||
import { initTree, renderTree, updateTalking } from './tree.js';
|
||||
import * as chat from './chat.js';
|
||||
import * as watch from './watch.js';
|
||||
import * as voice from './voice.js';
|
||||
import * as settings from './settings.js';
|
||||
|
||||
const VIEWS = ['#boot', '#view-fatal', '#view-onboarding', '#view-app'];
|
||||
let welcomeShown = false;
|
||||
let lastOwnChannel = null;
|
||||
let lastAsyncError = { code: '', at: 0 };
|
||||
|
||||
function showView(id) {
|
||||
for (const v of VIEWS) $(v).hidden = v !== id;
|
||||
}
|
||||
|
||||
// ---------- prefs ----------
|
||||
|
||||
async function savePrefs(partial) {
|
||||
const r = await tp.setPrefs(partial);
|
||||
if (r && r.ok) S.prefs = r.prefs;
|
||||
else toast(`Настройка не сохранена: ${r?.message ?? 'ошибка'}`, 'error');
|
||||
renderSessionHead();
|
||||
return S.prefs;
|
||||
}
|
||||
|
||||
// ---------- core lifecycle ----------
|
||||
|
||||
function onCoreStatus(status) {
|
||||
S.core = status;
|
||||
switch (status.status) {
|
||||
case 'starting':
|
||||
setText($('#boot-text'), 'Запуск ядра…');
|
||||
showView('#boot');
|
||||
break;
|
||||
case 'stopped':
|
||||
setText($('#boot-text'), 'Перезапуск ядра…');
|
||||
showView('#boot');
|
||||
resetConnection(null);
|
||||
break;
|
||||
case 'ready':
|
||||
loadProfile();
|
||||
break;
|
||||
case 'missing':
|
||||
showFatal('Ядро TeamsPeach не найдено', 'Исполняемый файл ядра отсутствует. Соберите его (см. README) или переустановите приложение. Проверенные пути:', status.candidates ?? []);
|
||||
break;
|
||||
default:
|
||||
resetConnection(null);
|
||||
showFatal('Ядро остановилось', status.message || `Код завершения ${status.code}`, []);
|
||||
}
|
||||
}
|
||||
|
||||
function showFatal(title, text, list, { allowImport = false } = {}) {
|
||||
setText($('#fatal-title'), title);
|
||||
setText($('#fatal-text'), text);
|
||||
$('#fatal-list').replaceChildren(...list.map((item) => h('li', { text: item })));
|
||||
$('#fatal-import').hidden = !allowImport;
|
||||
$('#fatal-retry').hidden = S.core.status === 'missing';
|
||||
showView('#view-fatal');
|
||||
}
|
||||
|
||||
async function loadProfile() {
|
||||
try {
|
||||
S.profile = await call('profile_get');
|
||||
} catch (err) {
|
||||
if (err.code === 'identity_corrupt' || err.code === 'profile_corrupt') {
|
||||
showFatal('Профиль повреждён', `${errorText(err)} TeamsPeach никогда не создаёт новую идентичность поверх повреждённой.`, [], { allowImport: true });
|
||||
} else {
|
||||
showFatal('Не удалось прочитать профиль', errorText(err), []);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!S.profile.exists || !S.profile.nickname) showOnboarding();
|
||||
else showApp();
|
||||
}
|
||||
|
||||
// ---------- onboarding ----------
|
||||
|
||||
function showOnboarding() {
|
||||
const existing = $('#onboarding-existing');
|
||||
existing.hidden = !S.profile.exists;
|
||||
setText(existing, S.profile.exists ? `Идентичность уже есть (UID ${S.profile.uid}). Осталось выбрать никнейм.` : '');
|
||||
showView('#view-onboarding');
|
||||
$('#onboarding-nick').focus();
|
||||
}
|
||||
|
||||
async function submitOnboarding(e) {
|
||||
e.preventDefault();
|
||||
const input = $('#onboarding-nick');
|
||||
const error = $('#onboarding-error');
|
||||
const nickname = input.value.trim();
|
||||
const len = [...nickname].length;
|
||||
if (len < 3 || len > 30) {
|
||||
input.setAttribute('aria-invalid', 'true');
|
||||
setText(error, 'Никнейм должен содержать от 3 до 30 символов.');
|
||||
input.focus();
|
||||
return;
|
||||
}
|
||||
input.removeAttribute('aria-invalid');
|
||||
setText(error, '');
|
||||
const submit = $('#onboarding-submit');
|
||||
submit.disabled = true;
|
||||
setText(submit, 'Создаём идентичность…');
|
||||
try {
|
||||
S.profile = S.profile.exists ? await call('rename', { nickname }) : await call('profile_create', { nickname });
|
||||
showApp();
|
||||
toast(`Профиль создан. Ваш UID: ${S.profile.uid}`);
|
||||
} catch (err) {
|
||||
setText(error, errorText(err));
|
||||
} finally {
|
||||
submit.disabled = false;
|
||||
setText(submit, 'Продолжить');
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- main shell ----------
|
||||
|
||||
function showApp() {
|
||||
showView('#view-app');
|
||||
voice.startAudio();
|
||||
renderAll();
|
||||
if (S.view === 'main' && !isConnected()) $('#connect-address').focus();
|
||||
}
|
||||
|
||||
function renderAll() {
|
||||
renderConnection();
|
||||
renderTree();
|
||||
renderSelf();
|
||||
renderSessionHead();
|
||||
chat.renderTabs();
|
||||
chat.renderLog();
|
||||
settings.renderProfile();
|
||||
}
|
||||
|
||||
function renderConnection() {
|
||||
const state = S.conn.state;
|
||||
const badge = $('#conn-badge');
|
||||
badge.dataset.state = state;
|
||||
const labels = { connecting: 'подключение…', connected: 'подключено', disconnecting: 'отключение…', disconnected: 'не подключено' };
|
||||
setText(badge, labels[state] ?? state);
|
||||
setText($('#server-name'), isConnected() ? S.snap.server.name || S.conn.address : S.conn.address && state !== 'disconnected' ? S.conn.address : 'Нет подключения');
|
||||
$('#btn-disconnect').hidden = state === 'disconnected';
|
||||
|
||||
const inSettings = S.view === 'settings';
|
||||
$('#settings-view').hidden = !inSettings;
|
||||
$('#connect-view').hidden = inSettings || isConnected();
|
||||
$('#session-view').hidden = inSettings || !isConnected();
|
||||
|
||||
const busy = state === 'connecting' || state === 'disconnecting';
|
||||
$('#connect-submit').disabled = busy;
|
||||
setText($('#connect-status'), state === 'connecting' ? 'Подключение…' : '');
|
||||
setText($('#connect-identity'), S.profile ? `Вы войдёте как ${S.profile.nickname} · UID ${shortUid(S.profile.uid)}` : '');
|
||||
if (!$('#connect-address').value && S.prefs.lastAddress) $('#connect-address').value = S.prefs.lastAddress;
|
||||
}
|
||||
|
||||
function renderSelf() {
|
||||
const p = S.profile;
|
||||
if (!p) return;
|
||||
setText($('#self-nick'), p.nickname ?? '');
|
||||
const ch = ownChannel();
|
||||
setText($('#self-sub'), isConnected() && ch ? ch.name : `UID ${shortUid(p.uid)}`);
|
||||
$('#self-sub').title = `UID ${p.uid}`;
|
||||
$('#self-dot').dataset.talking = String(Boolean(S.audio.transmitting));
|
||||
|
||||
const mute = $('#btn-mute');
|
||||
mute.setAttribute('aria-pressed', String(S.audio.input_muted));
|
||||
setIcon(mute.firstElementChild, S.audio.input_muted ? 'mic-off' : 'mic');
|
||||
mute.title = S.audio.input_muted ? 'Включить микрофон' : 'Выключить микрофон';
|
||||
mute.setAttribute('aria-label', S.audio.input_muted ? 'Микрофон выключен' : 'Микрофон включён');
|
||||
|
||||
const deafen = $('#btn-deafen');
|
||||
deafen.setAttribute('aria-pressed', String(S.audio.output_muted));
|
||||
setIcon(deafen.firstElementChild, S.audio.output_muted ? 'headphones-off' : 'headphones');
|
||||
deafen.title = S.audio.output_muted ? 'Включить звук' : 'Выключить звук (и микрофон)';
|
||||
deafen.setAttribute('aria-label', S.audio.output_muted ? 'Звук выключен' : 'Звук включён');
|
||||
}
|
||||
|
||||
function renderSessionHead() {
|
||||
if (!S.prefs) return;
|
||||
const ch = ownChannel();
|
||||
setText($('#channel-title'), ch ? ch.name : '');
|
||||
setText($('#channel-topic'), ch ? stripBBCode(ch.topic) : '');
|
||||
const ptt = S.prefs.transmitMode === 'ptt';
|
||||
$('#btn-ptt').hidden = !ptt;
|
||||
setText($('#transmit-hint'), voice.transmitHint());
|
||||
|
||||
const notice = $('#session-notice');
|
||||
const codec = voice.channelCodecProblem();
|
||||
let text = '';
|
||||
if (codec) text = `Канал использует устаревший кодек (${codec}). TeamsPeach передаёт и принимает только Opus — говорить здесь не получится.`;
|
||||
else if (S.audio.output_muted) text = 'Звук выключен: вы не слышите других и не передаёте голос.';
|
||||
else if (S.audio.input_muted) text = 'Микрофон выключен.';
|
||||
notice.hidden = !text;
|
||||
setText(notice, text);
|
||||
}
|
||||
|
||||
// ---------- connection ----------
|
||||
|
||||
async function submitConnect(e) {
|
||||
e.preventDefault();
|
||||
const address = $('#connect-address').value.trim();
|
||||
const password = $('#connect-password').value;
|
||||
const error = $('#connect-error');
|
||||
setText(error, '');
|
||||
if (!address) {
|
||||
setText(error, 'Укажите адрес сервера.');
|
||||
$('#connect-address').focus();
|
||||
return;
|
||||
}
|
||||
const args = { address };
|
||||
if (password) args.server_password = password;
|
||||
S.conn = { state: 'connecting', address, reason: null };
|
||||
renderConnection();
|
||||
renderTree();
|
||||
try {
|
||||
await call('connect', args);
|
||||
await savePrefs({ lastAddress: address });
|
||||
$('#connect-password').value = '';
|
||||
} catch (err) {
|
||||
if (err.code !== 'already_connected') {
|
||||
setText(error, errorText(err));
|
||||
if (S.conn.state === 'connecting') S.conn = { state: 'disconnected', address, reason: null };
|
||||
renderConnection();
|
||||
renderTree();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function disconnect() {
|
||||
try {
|
||||
await call('disconnect', {});
|
||||
} catch (err) {
|
||||
if (err.code !== 'not_connected') toast(`Отключение: ${errorText(err)}`, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function resetConnection(reason) {
|
||||
const wasConnected = S.snap !== null;
|
||||
S.conn = { state: 'disconnected', address: S.conn.address, reason };
|
||||
S.snap = null;
|
||||
S.talking.clear();
|
||||
S.audio.transmitting = false;
|
||||
welcomeShown = false;
|
||||
lastOwnChannel = null;
|
||||
watch.onDisconnected();
|
||||
voice.setPtt(false);
|
||||
voice.syncCapture();
|
||||
if (wasConnected) {
|
||||
chat.addSystem('channel', reason ? `Отключено: ${errorText(reason)}` : 'Отключено от сервера');
|
||||
}
|
||||
if (reason) setText($('#connect-error'), errorText(reason));
|
||||
}
|
||||
|
||||
function onStateEvent(evt) {
|
||||
const prev = S.conn.state;
|
||||
if (evt.state === 'disconnected') {
|
||||
resetConnection(evt.reason ?? null);
|
||||
} else {
|
||||
S.conn = { state: evt.state, address: evt.address ?? S.conn.address, reason: null };
|
||||
if (evt.state === 'connecting' && prev === 'connected') chat.addSystem('channel', 'Связь потеряна, переподключение…');
|
||||
if (evt.state === 'connected') {
|
||||
setText($('#connect-error'), '');
|
||||
voice.syncCapture();
|
||||
}
|
||||
}
|
||||
log('info', `state ${prev} → ${evt.state}`);
|
||||
renderAll();
|
||||
}
|
||||
|
||||
function onSnapshot(snap) {
|
||||
S.snap = snap;
|
||||
if (S.conn.state !== 'connected' && S.conn.state !== 'disconnecting') S.conn.state = 'connected';
|
||||
const present = new Set(snap.clients.map((c) => c.id));
|
||||
for (const id of Array.from(S.talking)) if (!present.has(id)) S.talking.delete(id);
|
||||
if (!welcomeShown) {
|
||||
welcomeShown = true;
|
||||
chat.addSystem('server', `Подключено к «${snap.server.name}»${snap.server.version ? ` (${snap.server.version})` : ''}`);
|
||||
const welcome = stripBBCode(snap.server.welcome_message).trim();
|
||||
if (welcome) chat.addSystem('server', welcome);
|
||||
}
|
||||
if (snap.own_channel_id !== lastOwnChannel) {
|
||||
lastOwnChannel = snap.own_channel_id;
|
||||
const ch = ownChannel();
|
||||
if (ch) chat.addSystem('channel', `Вы в канале «${ch.name}»`);
|
||||
}
|
||||
watch.onSnapshot();
|
||||
renderConnection();
|
||||
renderTree();
|
||||
renderSelf();
|
||||
renderSessionHead();
|
||||
chat.renderTabs();
|
||||
}
|
||||
|
||||
function onAsyncError(error) {
|
||||
const code = error?.code;
|
||||
log('warn', `core error ${code}: ${error?.message ?? ''}`);
|
||||
if (code === 'audio_muted' || code === 'not_connected') return;
|
||||
const now = Date.now();
|
||||
if (lastAsyncError.code === code && now - lastAsyncError.at < 5000) return;
|
||||
lastAsyncError = { code, at: now };
|
||||
if (code === 'audio_codec_unsupported') {
|
||||
renderSessionHead();
|
||||
return;
|
||||
}
|
||||
toast(errorText(error), 'error');
|
||||
}
|
||||
|
||||
function onCoreEvent(evt) {
|
||||
switch (evt.event) {
|
||||
case 'state':
|
||||
onStateEvent(evt);
|
||||
break;
|
||||
case 'snapshot':
|
||||
onSnapshot(evt);
|
||||
break;
|
||||
case 'audio_state': {
|
||||
const wasDeaf = S.audio.output_muted;
|
||||
S.audio = { input_muted: Boolean(evt.input_muted), output_muted: Boolean(evt.output_muted), transmitting: Boolean(evt.transmitting) };
|
||||
if (S.audio.output_muted && !wasDeaf) voice.onOutputMuted(true);
|
||||
watch.applyVolume();
|
||||
renderSelf();
|
||||
renderSessionHead();
|
||||
const self = S.snap?.own_client_id;
|
||||
if (self !== undefined) updateTalking(self);
|
||||
break;
|
||||
}
|
||||
case 'talking':
|
||||
if (evt.talking) S.talking.add(evt.client_id);
|
||||
else S.talking.delete(evt.client_id);
|
||||
updateTalking(evt.client_id);
|
||||
break;
|
||||
case 'text':
|
||||
chat.onText(evt);
|
||||
break;
|
||||
case 'stream':
|
||||
watch.onStreamEvent(evt);
|
||||
break;
|
||||
case 'profile':
|
||||
S.profile = { exists: evt.exists, uid: evt.uid, nickname: evt.nickname, security_level: evt.security_level };
|
||||
renderSelf();
|
||||
renderConnection();
|
||||
settings.renderProfile();
|
||||
break;
|
||||
case 'error':
|
||||
onAsyncError(evt.error);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
emit(evt.event, evt);
|
||||
}
|
||||
|
||||
// ---------- self controls ----------
|
||||
|
||||
async function toggleAudio(key) {
|
||||
try {
|
||||
const result = await call('set_audio', { [key]: !S.audio[key] });
|
||||
S.audio = { ...S.audio, input_muted: result.input_muted, output_muted: result.output_muted, transmitting: result.transmitting ?? S.audio.transmitting };
|
||||
if (S.audio.output_muted) voice.onOutputMuted(true);
|
||||
watch.applyVolume();
|
||||
renderSelf();
|
||||
renderSessionHead();
|
||||
} catch (err) {
|
||||
toast(errorText(err), 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function openSettings() {
|
||||
S.view = 'settings';
|
||||
renderConnection();
|
||||
settings.open();
|
||||
}
|
||||
|
||||
async function closeSettings() {
|
||||
await settings.close();
|
||||
S.view = 'main';
|
||||
renderConnection();
|
||||
chat.renderLog();
|
||||
(isConnected() ? $('#chat-input') : $('#connect-address')).focus();
|
||||
}
|
||||
|
||||
// ---------- diagnostics for automated smoke runs (read-only) ----------
|
||||
|
||||
Object.defineProperty(window, 'teamspeachDiagnostics', {
|
||||
value: Object.freeze({
|
||||
snapshot: () => ({
|
||||
core: S.core.status,
|
||||
profile: S.profile ? { uid: S.profile.uid, nickname: S.profile.nickname } : null,
|
||||
conn: S.conn.state,
|
||||
server: S.snap?.server?.name ?? null,
|
||||
ownClientId: S.snap?.own_client_id ?? null,
|
||||
ownChannel: ownChannel()?.name ?? null,
|
||||
clients: S.snap ? S.snap.clients.map((c) => ({ id: c.id, nickname: c.nickname, channel: c.channel_id, type: c.client_type, inputMuted: c.input_muted })) : [],
|
||||
talking: Array.from(S.talking),
|
||||
audio: { ...S.audio },
|
||||
voice: { ...voice.voiceStats, sending: voice.isSending() },
|
||||
streams: Array.from(watch.directory.streams.values()).map((s) => ({ id: s.id, clientId: s.clientId, name: s.name })),
|
||||
watch: { ...watch.watchStats },
|
||||
videoCodecs: settings.videoCodecs(),
|
||||
}),
|
||||
playback: () => voice.playbackStats(),
|
||||
}),
|
||||
});
|
||||
|
||||
// ---------- boot ----------
|
||||
|
||||
async function boot() {
|
||||
S.prefs = await tp.getPrefs();
|
||||
$('#stream-volume').value = String(S.prefs.streamVolume);
|
||||
|
||||
initTree({
|
||||
openPrivate: (id) => chat.openPrivate(id),
|
||||
openSettings,
|
||||
toggleWatch: (s) => watch.toggleWatch(s),
|
||||
streamOf: (id) => watch.streamOf(id),
|
||||
watchingId: () => watch.watchingId(),
|
||||
});
|
||||
chat.initChat();
|
||||
watch.initWatch({ onChange: () => renderTree(), savePrefs });
|
||||
voice.initVoice({
|
||||
onPtt: () => renderSessionHead(),
|
||||
onTransmitChanged: () => {},
|
||||
});
|
||||
settings.initSettings({
|
||||
savePrefs,
|
||||
close: closeSettings,
|
||||
onProfile: (p) => {
|
||||
S.profile = p;
|
||||
renderSelf();
|
||||
renderConnection();
|
||||
settings.renderProfile();
|
||||
renderTree();
|
||||
},
|
||||
});
|
||||
|
||||
$('#onboarding-form').addEventListener('submit', submitOnboarding);
|
||||
$('#onboarding-import').addEventListener('click', async () => {
|
||||
const r = await tp.importIdentity();
|
||||
if (r.ok) toast(`Идентичность восстановлена. UID ${r.uid}`);
|
||||
else if (!r.canceled) setText($('#onboarding-error'), `Восстановление не удалось: ${errorText(r.error)}`);
|
||||
});
|
||||
$('#connect-form').addEventListener('submit', submitConnect);
|
||||
$('#btn-disconnect').addEventListener('click', disconnect);
|
||||
$('#btn-mute').addEventListener('click', () => toggleAudio('input_muted'));
|
||||
$('#btn-deafen').addEventListener('click', () => toggleAudio('output_muted'));
|
||||
$('#btn-settings').addEventListener('click', () => (S.view === 'settings' ? closeSettings() : openSettings()));
|
||||
$('#fatal-retry').addEventListener('click', () => tp.restartCore());
|
||||
$('#fatal-import').addEventListener('click', async () => {
|
||||
const r = await tp.importIdentity();
|
||||
if (!r.ok && !r.canceled) toast(`Импорт не удался: ${errorText(r.error)}`, 'error');
|
||||
});
|
||||
$('#fatal-logs').addEventListener('click', () => tp.openLogs());
|
||||
|
||||
tp.onEvent(onCoreEvent);
|
||||
tp.onCoreStatus(onCoreStatus);
|
||||
const status = await tp.getCoreStatus();
|
||||
if (status) onCoreStatus(status);
|
||||
}
|
||||
|
||||
boot().catch((err) => {
|
||||
log('error', `boot failed: ${err.stack || err.message}`);
|
||||
showFatal('Ошибка запуска интерфейса', String(err.message || err), []);
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
// Microphone → 20 ms frames of 960 signed 16-bit mono samples at 48 kHz (bridge §4.9).
|
||||
const FRAME = 960;
|
||||
|
||||
class CaptureProcessor extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
super();
|
||||
this.frame = new Int16Array(FRAME);
|
||||
this.pos = 0;
|
||||
this.sumSq = 0;
|
||||
this.peak = 0;
|
||||
if (sampleRate !== 48000) this.port.postMessage({ type: 'error', message: `sample rate ${sampleRate}` });
|
||||
}
|
||||
|
||||
process(inputs, outputs) {
|
||||
const input = inputs[0];
|
||||
const out = outputs[0] && outputs[0][0];
|
||||
if (out) out.fill(0);
|
||||
if (!input || input.length === 0) return true;
|
||||
const ch = input[0];
|
||||
for (let i = 0; i < ch.length; i += 1) {
|
||||
let s = ch[i];
|
||||
if (s > 1) s = 1;
|
||||
else if (s < -1) s = -1;
|
||||
this.frame[this.pos] = s < 0 ? Math.round(s * 0x8000) : Math.round(s * 0x7fff);
|
||||
this.pos += 1;
|
||||
this.sumSq += s * s;
|
||||
const a = s < 0 ? -s : s;
|
||||
if (a > this.peak) this.peak = a;
|
||||
if (this.pos === FRAME) {
|
||||
const pcm = this.frame.buffer;
|
||||
this.port.postMessage({ type: 'frame', pcm, rms: Math.sqrt(this.sumSq / FRAME), peak: this.peak }, [pcm]);
|
||||
this.frame = new Int16Array(FRAME);
|
||||
this.pos = 0;
|
||||
this.sumSq = 0;
|
||||
this.peak = 0;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor('tp-capture', CaptureProcessor);
|
||||
@@ -0,0 +1,145 @@
|
||||
// Web Audio side of voice: one 48 kHz AudioContext, a capture worklet producing bridge-format
|
||||
// frames and a playback worklet with a bounded ring buffer.
|
||||
|
||||
export class AudioEngine {
|
||||
constructor({ onFrame, onError, log }) {
|
||||
this.onFrame = onFrame;
|
||||
this.onError = onError ?? (() => {});
|
||||
this.log = log ?? (() => {});
|
||||
this.ctx = null;
|
||||
this.playback = null;
|
||||
this.voiceGain = null;
|
||||
this.capture = null;
|
||||
this.ready = null;
|
||||
this.stats = { framesOut: 0 };
|
||||
this.statsWaiters = [];
|
||||
}
|
||||
|
||||
init() {
|
||||
if (!this.ready) this.ready = this._init();
|
||||
return this.ready;
|
||||
}
|
||||
|
||||
async _init() {
|
||||
const ctx = new AudioContext({ sampleRate: 48000, latencyHint: 'interactive' });
|
||||
this.ctx = ctx;
|
||||
await ctx.audioWorklet.addModule(new URL('./capture-worklet.js', import.meta.url));
|
||||
await ctx.audioWorklet.addModule(new URL('./playback-worklet.js', import.meta.url));
|
||||
this.playback = new AudioWorkletNode(ctx, 'tp-playback', {
|
||||
numberOfInputs: 0,
|
||||
numberOfOutputs: 1,
|
||||
outputChannelCount: [1],
|
||||
});
|
||||
this.playback.port.onmessage = (event) => {
|
||||
if (event.data && event.data.type === 'stats') {
|
||||
const waiters = this.statsWaiters.splice(0);
|
||||
for (const resolve of waiters) resolve(event.data);
|
||||
}
|
||||
};
|
||||
this.voiceGain = ctx.createGain();
|
||||
this.playback.connect(this.voiceGain).connect(ctx.destination);
|
||||
if (ctx.state !== 'running') await ctx.resume();
|
||||
this.log('info', `audio: context ${ctx.sampleRate} Hz, baseLatency ${Math.round((ctx.baseLatency || 0) * 1000)} ms`);
|
||||
}
|
||||
|
||||
setVoiceVolume(percent) {
|
||||
if (this.voiceGain) this.voiceGain.gain.setTargetAtTime(percent / 100, this.ctx.currentTime, 0.02);
|
||||
}
|
||||
|
||||
async setOutputDevice(deviceId) {
|
||||
await this.init();
|
||||
if (typeof this.ctx.setSinkId !== 'function') throw new Error('Выбор устройства вывода не поддерживается');
|
||||
await this.ctx.setSinkId(deviceId || '');
|
||||
}
|
||||
|
||||
/** Copies the 1920-byte frame into the worklet (transfer). */
|
||||
pushPlayback(bytes) {
|
||||
if (!this.playback) return;
|
||||
const copy = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
||||
this.playback.port.postMessage(copy, [copy]);
|
||||
this.stats.framesOut += 1;
|
||||
}
|
||||
|
||||
flushPlayback() {
|
||||
if (this.playback) this.playback.port.postMessage({ type: 'flush' });
|
||||
}
|
||||
|
||||
playbackStats() {
|
||||
if (!this.playback) return Promise.resolve(null);
|
||||
return new Promise((resolve) => {
|
||||
this.statsWaiters.push(resolve);
|
||||
this.playback.port.postMessage({ type: 'stats' });
|
||||
});
|
||||
}
|
||||
|
||||
get capturing() {
|
||||
return this.capture !== null;
|
||||
}
|
||||
|
||||
async startCapture({ deviceId, echoCancellation, noiseSuppression, autoGainControl }) {
|
||||
await this.init();
|
||||
this.stopCapture();
|
||||
const audio = {
|
||||
channelCount: 1,
|
||||
echoCancellation,
|
||||
noiseSuppression,
|
||||
autoGainControl,
|
||||
};
|
||||
if (deviceId) audio.deviceId = { exact: deviceId };
|
||||
let stream;
|
||||
try {
|
||||
stream = await navigator.mediaDevices.getUserMedia({ audio, video: false });
|
||||
} catch (err) {
|
||||
if (deviceId && err && err.name === 'OverconstrainedError') {
|
||||
delete audio.deviceId;
|
||||
stream = await navigator.mediaDevices.getUserMedia({ audio, video: false });
|
||||
this.onError({ code: 'device_fallback', message: 'Выбранный микрофон недоступен, используется микрофон по умолчанию' });
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
const ctx = this.ctx;
|
||||
const source = ctx.createMediaStreamSource(stream);
|
||||
const node = new AudioWorkletNode(ctx, 'tp-capture', {
|
||||
numberOfInputs: 1,
|
||||
numberOfOutputs: 1,
|
||||
outputChannelCount: [1],
|
||||
channelCount: 1,
|
||||
channelCountMode: 'explicit',
|
||||
channelInterpretation: 'speakers',
|
||||
});
|
||||
const sink = ctx.createGain();
|
||||
sink.gain.value = 0;
|
||||
node.port.onmessage = (event) => {
|
||||
const data = event.data;
|
||||
if (data.type === 'frame') this.onFrame(data.pcm, data.rms, data.peak);
|
||||
else if (data.type === 'error') this.onError({ code: 'capture', message: data.message });
|
||||
};
|
||||
source.connect(node).connect(sink).connect(ctx.destination);
|
||||
const track = stream.getAudioTracks()[0];
|
||||
track.addEventListener('ended', () => {
|
||||
if (this.capture && this.capture.stream === stream) {
|
||||
this.stopCapture();
|
||||
this.onError({ code: 'device_lost', message: 'Микрофон отключён' });
|
||||
}
|
||||
});
|
||||
this.capture = { stream, source, node, sink, label: track ? track.label : '' };
|
||||
this.log('info', `audio: capture started (${track ? track.getSettings().sampleRate : '?'} Hz device)`);
|
||||
return this.capture.label;
|
||||
}
|
||||
|
||||
stopCapture() {
|
||||
const c = this.capture;
|
||||
if (!c) return;
|
||||
this.capture = null;
|
||||
c.node.port.onmessage = null;
|
||||
try {
|
||||
c.source.disconnect();
|
||||
c.node.disconnect();
|
||||
c.sink.disconnect();
|
||||
} catch {
|
||||
// already disconnected
|
||||
}
|
||||
for (const t of c.stream.getTracks()) t.stop();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// Mixed voice from the core → speakers. Bounded ring: 200 ms capacity (oldest dropped),
|
||||
// 40 ms prebuffer after every underrun, silence while empty (bridge §5 `audio`).
|
||||
const CAPACITY = 9600;
|
||||
const PREBUFFER = 1920;
|
||||
|
||||
class PlaybackProcessor extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
super();
|
||||
this.ring = new Float32Array(CAPACITY);
|
||||
this.read = 0;
|
||||
this.write = 0;
|
||||
this.size = 0;
|
||||
this.playing = false;
|
||||
this.framesIn = 0;
|
||||
this.dropped = 0;
|
||||
this.underruns = 0;
|
||||
this.port.onmessage = (event) => {
|
||||
const data = event.data;
|
||||
if (data instanceof ArrayBuffer) {
|
||||
this.push(new Int16Array(data));
|
||||
} else if (data && data.type === 'flush') {
|
||||
this.read = 0;
|
||||
this.write = 0;
|
||||
this.size = 0;
|
||||
this.playing = false;
|
||||
} else if (data && data.type === 'stats') {
|
||||
this.port.postMessage({
|
||||
type: 'stats',
|
||||
framesIn: this.framesIn,
|
||||
dropped: this.dropped,
|
||||
underruns: this.underruns,
|
||||
bufferedMs: Math.round((this.size / 48000) * 1000),
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
push(pcm) {
|
||||
this.framesIn += 1;
|
||||
for (let i = 0; i < pcm.length; i += 1) {
|
||||
if (this.size === CAPACITY) {
|
||||
this.read = (this.read + 1) % CAPACITY;
|
||||
this.size -= 1;
|
||||
this.dropped += 1;
|
||||
}
|
||||
this.ring[this.write] = pcm[i] / 32768;
|
||||
this.write = (this.write + 1) % CAPACITY;
|
||||
this.size += 1;
|
||||
}
|
||||
}
|
||||
|
||||
process(_inputs, outputs) {
|
||||
const out = outputs[0][0];
|
||||
if (!this.playing) {
|
||||
if (this.size < PREBUFFER) {
|
||||
out.fill(0);
|
||||
return true;
|
||||
}
|
||||
this.playing = true;
|
||||
}
|
||||
for (let i = 0; i < out.length; i += 1) {
|
||||
if (this.size > 0) {
|
||||
out[i] = this.ring[this.read];
|
||||
this.read = (this.read + 1) % CAPACITY;
|
||||
this.size -= 1;
|
||||
} else {
|
||||
out[i] = 0;
|
||||
if (this.playing) {
|
||||
this.playing = false;
|
||||
this.underruns += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor('tp-playback', PlaybackProcessor);
|
||||
@@ -0,0 +1,259 @@
|
||||
// Channel, server and private text chat. Message text is rendered as plain text only.
|
||||
import { $, h, icon, reconcile, setText, formatTime } from './dom.js';
|
||||
import { S, isConnected, ownChannel, clientById } from './state.js';
|
||||
import { call } from './core.js';
|
||||
import { errorText, stripBBCode } from './text.js';
|
||||
import { toast } from './toast.js';
|
||||
|
||||
const MAX_MESSAGES = 500;
|
||||
const chats = new Map();
|
||||
let active = 'channel';
|
||||
|
||||
function ensureChat(key, init) {
|
||||
let chat = chats.get(key);
|
||||
if (!chat) {
|
||||
chat = { key, messages: [], unread: 0, ...init };
|
||||
chats.set(key, chat);
|
||||
}
|
||||
return chat;
|
||||
}
|
||||
|
||||
ensureChat('channel', { kind: 'channel' });
|
||||
ensureChat('server', { kind: 'server' });
|
||||
|
||||
export function initChat() {
|
||||
const form = $('#chat-form');
|
||||
const input = $('#chat-input');
|
||||
form.addEventListener('submit', (e) => {
|
||||
e.preventDefault();
|
||||
send();
|
||||
});
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) {
|
||||
e.preventDefault();
|
||||
send();
|
||||
}
|
||||
});
|
||||
input.addEventListener('input', autosize);
|
||||
$('#chat-tabs').addEventListener('keydown', onTabKey);
|
||||
}
|
||||
|
||||
function autosize() {
|
||||
const input = $('#chat-input');
|
||||
input.style.height = 'auto';
|
||||
input.style.height = `${Math.min(input.scrollHeight, 160)}px`;
|
||||
}
|
||||
|
||||
function tabTitle(chat) {
|
||||
if (chat.kind === 'channel') return ownChannel()?.name ?? 'Канал';
|
||||
if (chat.kind === 'server') return 'Сервер';
|
||||
const cl = clientById(chat.clientId);
|
||||
return cl ? cl.nickname : `${chat.nickname} (вышел)`;
|
||||
}
|
||||
|
||||
function targetOf(chat) {
|
||||
if (chat.kind === 'client') return { target: 'client', client_id: chat.clientId };
|
||||
return { target: chat.kind };
|
||||
}
|
||||
|
||||
async function send() {
|
||||
const input = $('#chat-input');
|
||||
const text = input.value.replace(/\s+$/u, '');
|
||||
if (!text.trim() || !isConnected()) return;
|
||||
const chat = chats.get(active);
|
||||
if (!chat) return;
|
||||
if (chat.kind === 'client' && !clientById(chat.clientId)) {
|
||||
toast('Собеседник покинул сервер', 'error');
|
||||
return;
|
||||
}
|
||||
if (new TextEncoder().encode(text).length > 8192) {
|
||||
toast('Сообщение длиннее 8 КиБ', 'error');
|
||||
return;
|
||||
}
|
||||
input.disabled = true;
|
||||
try {
|
||||
await call('send_text', { ...targetOf(chat), message: text });
|
||||
input.value = '';
|
||||
autosize();
|
||||
} catch (err) {
|
||||
toast(`Сообщение не отправлено: ${errorText(err)}`, 'error');
|
||||
} finally {
|
||||
input.disabled = false;
|
||||
input.focus();
|
||||
}
|
||||
}
|
||||
|
||||
/** Incoming `text` event (bridge §5). Our own messages arrive here too, exactly once. */
|
||||
export function onText(evt) {
|
||||
const own = S.snap?.own_client_id;
|
||||
let key;
|
||||
if (evt.target === 'channel') key = 'channel';
|
||||
else if (evt.target === 'server') key = 'server';
|
||||
else {
|
||||
const other = evt.from_client_id === own ? evt.to_client_id : evt.from_client_id;
|
||||
if (!Number.isInteger(other)) return;
|
||||
key = openPrivate(other, { focus: false, nickname: evt.from_client_id === own ? undefined : evt.from_nickname });
|
||||
}
|
||||
addMessage(key, {
|
||||
author: evt.from_nickname ?? '?',
|
||||
own: evt.from_client_id === own,
|
||||
authorId: evt.from_client_id,
|
||||
text: stripBBCode(evt.message),
|
||||
});
|
||||
}
|
||||
|
||||
export function addSystem(key, text) {
|
||||
addMessage(key, { system: true, text });
|
||||
}
|
||||
|
||||
function addMessage(key, msg) {
|
||||
const chat = chats.get(key);
|
||||
if (!chat) return;
|
||||
msg.time = new Date();
|
||||
msg.id = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
chat.messages.push(msg);
|
||||
if (chat.messages.length > MAX_MESSAGES) chat.messages.splice(0, chat.messages.length - MAX_MESSAGES);
|
||||
if (key === active && S.view === 'main') {
|
||||
appendRow(chat, msg);
|
||||
} else if (!msg.system && !msg.own) {
|
||||
chat.unread += 1;
|
||||
}
|
||||
renderTabs();
|
||||
}
|
||||
|
||||
/** Opens (or creates) a private conversation; returns its key. */
|
||||
export function openPrivate(clientId, { focus = true, nickname } = {}) {
|
||||
const key = `client:${clientId}`;
|
||||
const cl = clientById(clientId);
|
||||
const chat = ensureChat(key, { kind: 'client', clientId, nickname: nickname ?? cl?.nickname ?? '?' });
|
||||
if (cl) chat.nickname = cl.nickname;
|
||||
if (focus) {
|
||||
select(key);
|
||||
$('#chat-input').focus();
|
||||
} else {
|
||||
renderTabs();
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function select(key) {
|
||||
if (!chats.has(key)) return;
|
||||
active = key;
|
||||
chats.get(key).unread = 0;
|
||||
renderTabs();
|
||||
renderLog();
|
||||
}
|
||||
|
||||
function closePrivate(key) {
|
||||
chats.delete(key);
|
||||
if (active === key) active = 'channel';
|
||||
renderTabs();
|
||||
renderLog();
|
||||
}
|
||||
|
||||
export function renderTabs() {
|
||||
const host = $('#chat-tabs');
|
||||
const list = Array.from(chats.values());
|
||||
reconcile(host, list, (c) => c.key, createTab, updateTab);
|
||||
updateComposer();
|
||||
}
|
||||
|
||||
function createTab(chat) {
|
||||
const tab = h('button', { class: 'chat-tab', type: 'button', role: 'tab' }, h('span', { class: 'tab-label' }), h('span', { class: 'unread', hidden: true }));
|
||||
tab.addEventListener('click', () => select(chat.key));
|
||||
const wrap = h('div', { class: 'tab-wrap', role: 'presentation' }, tab);
|
||||
if (chat.kind === 'client') {
|
||||
const close = h('button', { class: 'tab-close icon-btn', type: 'button', 'aria-label': 'Закрыть личный чат' }, icon('x'));
|
||||
close.addEventListener('click', () => closePrivate(chat.key));
|
||||
wrap.appendChild(close);
|
||||
}
|
||||
return wrap;
|
||||
}
|
||||
|
||||
function updateTab(wrap, chat) {
|
||||
const tab = wrap.firstElementChild;
|
||||
const [label, unread] = tab.children;
|
||||
const title = tabTitle(chat);
|
||||
setText(label, chat.kind === 'client' ? `@ ${title}` : title);
|
||||
const selected = chat.key === active;
|
||||
tab.setAttribute('aria-selected', String(selected));
|
||||
tab.tabIndex = selected ? 0 : -1;
|
||||
tab.title = chat.kind === 'channel' ? 'Чат текущего канала' : chat.kind === 'server' ? 'Чат всего сервера' : `Личные сообщения: ${title}`;
|
||||
unread.hidden = chat.unread === 0;
|
||||
setText(unread, chat.unread > 99 ? '99+' : String(chat.unread));
|
||||
tab.setAttribute('aria-label', `${tab.title}${chat.unread ? `, непрочитанных: ${chat.unread}` : ''}`);
|
||||
}
|
||||
|
||||
function onTabKey(e) {
|
||||
if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return;
|
||||
const tabs = Array.from(document.querySelectorAll('#chat-tabs [role="tab"]'));
|
||||
const idx = tabs.indexOf(document.activeElement);
|
||||
if (idx < 0) return;
|
||||
const next = tabs[(idx + (e.key === 'ArrowRight' ? 1 : tabs.length - 1)) % tabs.length];
|
||||
next.focus();
|
||||
next.click();
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
export function renderLog() {
|
||||
const log = $('#chat-log');
|
||||
const chat = chats.get(active);
|
||||
log.replaceChildren();
|
||||
if (!chat || chat.messages.length === 0) {
|
||||
log.appendChild(h('li', { class: 'chat-empty', text: emptyText(chat) }));
|
||||
updateComposer();
|
||||
return;
|
||||
}
|
||||
let prev = null;
|
||||
for (const msg of chat.messages) {
|
||||
log.appendChild(rowFor(msg, prev));
|
||||
prev = msg;
|
||||
}
|
||||
log.scrollTop = log.scrollHeight;
|
||||
updateComposer();
|
||||
}
|
||||
|
||||
function emptyText(chat) {
|
||||
if (!chat) return '';
|
||||
if (chat.kind === 'channel') return 'Сообщения в этом канале видят все, кто в нём находится.';
|
||||
if (chat.kind === 'server') return 'Сообщения сервера видят все подключённые.';
|
||||
return 'Личная переписка. Сообщения видит только собеседник.';
|
||||
}
|
||||
|
||||
function rowFor(msg, prev) {
|
||||
if (msg.system) return h('li', { class: 'msg-system', text: msg.text });
|
||||
const head = !prev || prev.system || prev.authorId !== msg.authorId || msg.time - prev.time > 5 * 60 * 1000;
|
||||
const li = h('li', { class: 'msg', dataset: { head: String(head), own: String(Boolean(msg.own)) } });
|
||||
if (head) {
|
||||
li.appendChild(h('div', { class: 'msg-head' }, h('span', { class: 'msg-author', text: msg.author }), h('time', { class: 'msg-time', datetime: msg.time.toISOString(), text: formatTime(msg.time) })));
|
||||
}
|
||||
li.appendChild(h('div', { class: 'msg-body', text: msg.text }));
|
||||
return li;
|
||||
}
|
||||
|
||||
function appendRow(chat, msg) {
|
||||
const log = $('#chat-log');
|
||||
const nearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 80;
|
||||
const empty = log.querySelector('.chat-empty');
|
||||
if (empty) empty.remove();
|
||||
const prev = chat.messages[chat.messages.length - 2] ?? null;
|
||||
log.appendChild(rowFor(msg, prev));
|
||||
if (nearBottom || msg.own) log.scrollTop = log.scrollHeight;
|
||||
}
|
||||
|
||||
export function updateComposer() {
|
||||
const input = $('#chat-input');
|
||||
const sendBtn = $('#chat-send');
|
||||
const chat = chats.get(active);
|
||||
const partnerGone = chat && chat.kind === 'client' && !clientById(chat.clientId);
|
||||
const enabled = isConnected() && !partnerGone;
|
||||
input.disabled = !enabled;
|
||||
sendBtn.disabled = !enabled;
|
||||
const title = chat ? tabTitle(chat) : '';
|
||||
input.placeholder = !isConnected() ? 'Нет подключения' : partnerGone ? 'Собеседник покинул сервер' : chat?.kind === 'client' ? `Сообщение для ${title}` : chat?.kind === 'server' ? 'Сообщение всему серверу' : `Сообщение в «${title}»`;
|
||||
}
|
||||
|
||||
/** Called when the connection ends: private chats keep their history but cannot be answered. */
|
||||
export function onConnectionChanged() {
|
||||
renderTabs();
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Thin wrapper over the preload API (window.teamspeach). Requests resolve to `result` or throw BridgeError.
|
||||
|
||||
export const tp = window.teamspeach;
|
||||
|
||||
export class BridgeError extends Error {
|
||||
constructor(error) {
|
||||
super(error?.message || error?.code || 'error');
|
||||
this.code = error?.code ?? 'internal';
|
||||
this.ts_error = error?.ts_error;
|
||||
this.detail = error?.detail;
|
||||
}
|
||||
}
|
||||
|
||||
export async function call(cmd, args) {
|
||||
const response = await tp.request(cmd, args);
|
||||
if (!response || !response.ok) throw new BridgeError(response?.error);
|
||||
return response.result;
|
||||
}
|
||||
|
||||
export function log(level, message) {
|
||||
tp.log(level, message);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
// DOM helpers. Server-provided text only ever reaches the page through textContent / attributes.
|
||||
|
||||
export function $(selector, root = document) {
|
||||
const el = root.querySelector(selector);
|
||||
if (!el) throw new Error(`missing element ${selector}`);
|
||||
return el;
|
||||
}
|
||||
|
||||
/**
|
||||
* h('button', {class: 'x', onclick, 'aria-label': 'y', dataset: {cid: 1}}, 'text', child)
|
||||
* Strings become text nodes; there is no innerHTML path.
|
||||
*/
|
||||
export function h(tag, props = {}, ...children) {
|
||||
const el = document.createElement(tag);
|
||||
for (const [key, value] of Object.entries(props)) {
|
||||
if (value === undefined || value === null || value === false) continue;
|
||||
if (key === 'class') el.className = value;
|
||||
else if (key === 'dataset') Object.assign(el.dataset, value);
|
||||
else if (key === 'text') el.textContent = value;
|
||||
else if (key.startsWith('on') && typeof value === 'function') el.addEventListener(key.slice(2), value);
|
||||
else if (key in el && typeof value !== 'string') el[key] = value;
|
||||
else el.setAttribute(key, value === true ? '' : String(value));
|
||||
}
|
||||
append(el, children);
|
||||
return el;
|
||||
}
|
||||
|
||||
function append(el, children) {
|
||||
for (const child of children) {
|
||||
if (child === undefined || child === null || child === false) continue;
|
||||
if (Array.isArray(child)) append(el, child);
|
||||
else if (child instanceof Node) el.appendChild(child);
|
||||
else el.appendChild(document.createTextNode(String(child)));
|
||||
}
|
||||
}
|
||||
|
||||
const SVG_NS = 'http://www.w3.org/2000/svg';
|
||||
|
||||
/** Reference to a symbol of the inline sprite in index.html. */
|
||||
export function icon(name, extraClass = '') {
|
||||
const svg = document.createElementNS(SVG_NS, 'svg');
|
||||
svg.setAttribute('class', `icon ${extraClass}`.trim());
|
||||
svg.setAttribute('aria-hidden', 'true');
|
||||
svg.setAttribute('focusable', 'false');
|
||||
const use = document.createElementNS(SVG_NS, 'use');
|
||||
use.setAttribute('href', `#i-${name}`);
|
||||
svg.appendChild(use);
|
||||
return svg;
|
||||
}
|
||||
|
||||
export function setIcon(svg, name) {
|
||||
svg.firstElementChild.setAttribute('href', `#i-${name}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Keyed list reconciliation: reuses nodes by key so focus and hover survive frequent snapshots.
|
||||
* create(item) → Element; update(el, item) mutates in place.
|
||||
*/
|
||||
export function reconcile(container, items, keyOf, create, update) {
|
||||
const existing = new Map();
|
||||
for (const child of Array.from(container.children)) {
|
||||
if (child.dataset.key) existing.set(child.dataset.key, child);
|
||||
}
|
||||
let cursor = container.firstElementChild;
|
||||
for (const item of items) {
|
||||
const key = keyOf(item);
|
||||
let el = existing.get(key);
|
||||
if (el) {
|
||||
existing.delete(key);
|
||||
update(el, item);
|
||||
} else {
|
||||
el = create(item);
|
||||
el.dataset.key = key;
|
||||
update(el, item);
|
||||
}
|
||||
if (el !== cursor) container.insertBefore(el, cursor);
|
||||
else cursor = cursor.nextElementSibling;
|
||||
}
|
||||
for (const el of existing.values()) el.remove();
|
||||
}
|
||||
|
||||
export function setText(el, text) {
|
||||
const value = text ?? '';
|
||||
if (el.textContent !== value) el.textContent = value;
|
||||
}
|
||||
|
||||
export function formatTime(date) {
|
||||
return date.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"type": "module"
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
// Settings: profile (rename, UID, identity backup), audio devices/transmit mode, diagnostics.
|
||||
import { $, h, setText } from './dom.js';
|
||||
import { S, isConnected } from './state.js';
|
||||
import { tp, call } from './core.js';
|
||||
import { errorText, keyLabel } from './text.js';
|
||||
import { toast } from './toast.js';
|
||||
import * as voice from './voice.js';
|
||||
import { applySink } from './watch.js';
|
||||
|
||||
let hooks = { savePrefs: async () => {}, close: () => {}, onProfile: () => {} };
|
||||
|
||||
export function initSettings(h0) {
|
||||
hooks = { ...hooks, ...h0 };
|
||||
|
||||
$('#settings-back').addEventListener('click', () => hooks.close());
|
||||
$('#settings-view').addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape' && !e.defaultPrevented) hooks.close();
|
||||
});
|
||||
|
||||
$('#rename-form').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const input = $('#rename-input');
|
||||
const status = $('#rename-status');
|
||||
const nickname = input.value.trim();
|
||||
const len = [...nickname].length;
|
||||
if (len < 3 || len > 30) {
|
||||
input.setAttribute('aria-invalid', 'true');
|
||||
setText(status, 'Никнейм должен содержать от 3 до 30 символов.');
|
||||
return;
|
||||
}
|
||||
if (nickname === S.profile?.nickname) {
|
||||
setText(status, 'Это уже ваш никнейм.');
|
||||
return;
|
||||
}
|
||||
input.removeAttribute('aria-invalid');
|
||||
$('#rename-submit').disabled = true;
|
||||
setText(status, 'Сохраняем…');
|
||||
const uidBefore = S.profile?.uid;
|
||||
try {
|
||||
const profile = await call('rename', { nickname });
|
||||
hooks.onProfile(profile);
|
||||
setText(status, profile.uid === uidBefore ? `Сохранено${isConnected() ? ' и применено на сервере' : ''}. UID не изменился.` : 'Сохранено.');
|
||||
} catch (err) {
|
||||
if (err.code === 'rename_not_persisted' && err.detail) {
|
||||
setText(status, `Сервер показал «${err.detail.server_nickname}», но на диске остался «${err.detail.saved_nickname}»${err.detail.reverted ? '; имя на сервере возвращено' : ''}.`);
|
||||
} else {
|
||||
setText(status, errorText(err));
|
||||
}
|
||||
} finally {
|
||||
$('#rename-submit').disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
$('#uid-copy').addEventListener('click', async () => {
|
||||
if (S.profile?.uid && (await tp.copyText(S.profile.uid))) toast('UID скопирован');
|
||||
});
|
||||
|
||||
$('#identity-export').addEventListener('click', async () => {
|
||||
const status = $('#identity-status');
|
||||
const r = await tp.exportIdentity();
|
||||
if (r.canceled) return;
|
||||
setText(status, r.ok ? `Сохранено в «${r.file}». UID ${r.uid}.` : `Экспорт не удался: ${errorText(r.error)}`);
|
||||
});
|
||||
|
||||
$('#identity-import').addEventListener('click', async () => {
|
||||
const status = $('#identity-status');
|
||||
if (S.conn.state !== 'disconnected') {
|
||||
setText(status, 'Сначала отключитесь от сервера.');
|
||||
return;
|
||||
}
|
||||
const r = await tp.importIdentity();
|
||||
if (r.canceled) return;
|
||||
if (r.ok) toast(`Идентичность импортирована. UID ${r.uid}`);
|
||||
else setText(status, `Импорт не удался: ${errorText(r.error)}`);
|
||||
});
|
||||
|
||||
$('#input-device').addEventListener('change', async (e) => {
|
||||
await hooks.savePrefs({ inputDeviceId: e.target.value });
|
||||
await voice.restartCapture();
|
||||
});
|
||||
$('#output-device').addEventListener('change', async (e) => {
|
||||
await hooks.savePrefs({ outputDeviceId: e.target.value });
|
||||
try {
|
||||
await voice.setOutputDevice(e.target.value);
|
||||
} catch (err) {
|
||||
toast(`Не удалось выбрать устройство вывода: ${err.message}`, 'error');
|
||||
}
|
||||
applySink();
|
||||
});
|
||||
$('#voice-volume').addEventListener('input', (e) => {
|
||||
const v = Number(e.target.value);
|
||||
voice.setVoiceVolume(v);
|
||||
setText($('#voice-volume-value'), `${v}%`);
|
||||
});
|
||||
$('#voice-volume').addEventListener('change', (e) => hooks.savePrefs({ voiceVolume: Number(e.target.value) }));
|
||||
|
||||
for (const radio of document.querySelectorAll('input[name="transmit"]')) {
|
||||
radio.addEventListener('change', async () => {
|
||||
if (radio.checked) {
|
||||
await hooks.savePrefs({ transmitMode: radio.value });
|
||||
renderAudio();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$('#ptt-assign').addEventListener('click', async () => {
|
||||
const btn = $('#ptt-assign');
|
||||
btn.disabled = true;
|
||||
setText($('#ptt-key'), 'нажмите клавишу…');
|
||||
const code = await voice.capturePttKey();
|
||||
btn.disabled = false;
|
||||
if (code) await hooks.savePrefs({ pttCode: code });
|
||||
renderAudio();
|
||||
btn.focus();
|
||||
});
|
||||
|
||||
const processing = [['#opt-ns', 'noiseSuppression'], ['#opt-ec', 'echoCancellation'], ['#opt-agc', 'autoGainControl']];
|
||||
for (const [sel, key] of processing) {
|
||||
$(sel).addEventListener('change', async (e) => {
|
||||
await hooks.savePrefs({ [key]: e.target.checked });
|
||||
await voice.restartCapture();
|
||||
});
|
||||
}
|
||||
|
||||
$('#mic-test').addEventListener('click', async () => {
|
||||
const btn = $('#mic-test');
|
||||
const on = btn.getAttribute('aria-pressed') !== 'true';
|
||||
btn.setAttribute('aria-pressed', String(on));
|
||||
setText(btn, on ? 'Остановить проверку' : 'Проверить микрофон');
|
||||
await voice.setMicTest(on);
|
||||
});
|
||||
|
||||
$('#open-logs').addEventListener('click', () => tp.openLogs());
|
||||
}
|
||||
|
||||
export function renderProfile() {
|
||||
const p = S.profile;
|
||||
if (!p) return;
|
||||
const input = $('#rename-input');
|
||||
if (document.activeElement !== input) input.value = p.nickname ?? '';
|
||||
setText($('#uid-value'), p.uid ?? '');
|
||||
setText($('#security-level'), p.security_level !== null && p.security_level !== undefined ? `Уровень безопасности идентичности: ${p.security_level}` : '');
|
||||
$('#identity-import').disabled = S.conn.state !== 'disconnected';
|
||||
$('#identity-import').title = S.conn.state !== 'disconnected' ? 'Доступно после отключения от сервера' : '';
|
||||
}
|
||||
|
||||
export function renderAudio() {
|
||||
const prefs = S.prefs;
|
||||
for (const radio of document.querySelectorAll('input[name="transmit"]')) radio.checked = radio.value === prefs.transmitMode;
|
||||
setText($('#ptt-key'), keyLabel(prefs.pttCode));
|
||||
$('#ptt-assign').disabled = false;
|
||||
$('#opt-ns').checked = prefs.noiseSuppression;
|
||||
$('#opt-ec').checked = prefs.echoCancellation;
|
||||
$('#opt-agc').checked = prefs.autoGainControl;
|
||||
$('#voice-volume').value = String(prefs.voiceVolume);
|
||||
setText($('#voice-volume-value'), `${prefs.voiceVolume}%`);
|
||||
}
|
||||
|
||||
export async function renderDiagnostics() {
|
||||
const info = await tp.getAppInfo();
|
||||
const rows = [
|
||||
['TeamsPeach', info.appVersion],
|
||||
['Ядро', info.coreVersion ?? 'не запущено'],
|
||||
['Electron', info.electron],
|
||||
['Chromium', info.chrome],
|
||||
['Платформа', `${info.platform} ${info.arch}`],
|
||||
['Исполняемый файл ядра', info.coreBinary ?? '—'],
|
||||
['Каталог данных', info.dataDir],
|
||||
];
|
||||
$('#diag-list').replaceChildren(...rows.flatMap(([k, v]) => [h('dt', { text: k }), h('dd', { text: v })]));
|
||||
$('#codec-list').replaceChildren(...videoCodecs().map((line) => h('li', { text: line })));
|
||||
}
|
||||
|
||||
const IGNORED = new Set(['video/rtx', 'video/red', 'video/ulpfec', 'video/flexfec-03']);
|
||||
|
||||
export function videoCodecs() {
|
||||
const caps = typeof RTCRtpReceiver.getCapabilities === 'function' ? RTCRtpReceiver.getCapabilities('video') : null;
|
||||
if (!caps) return ['Возможности приёма недоступны'];
|
||||
return caps.codecs.filter((c) => !IGNORED.has(c.mimeType.toLowerCase())).map((c) => `${c.mimeType.replace('video/', '')}${c.sdpFmtpLine ? ` ${c.sdpFmtpLine}` : ''}`);
|
||||
}
|
||||
|
||||
export function open() {
|
||||
renderProfile();
|
||||
renderAudio();
|
||||
voice.refreshDevices();
|
||||
renderDiagnostics();
|
||||
$('#settings-back').focus();
|
||||
}
|
||||
|
||||
export async function close() {
|
||||
const btn = $('#mic-test');
|
||||
if (btn.getAttribute('aria-pressed') === 'true') {
|
||||
btn.setAttribute('aria-pressed', 'false');
|
||||
setText(btn, 'Проверить микрофон');
|
||||
await voice.setMicTest(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// Single renderer state object plus a tiny topic bus. The core snapshot is replaced wholesale (bridge §5).
|
||||
|
||||
export const S = {
|
||||
core: { status: 'starting' },
|
||||
profile: null,
|
||||
prefs: null,
|
||||
conn: { state: 'disconnected', address: '', reason: null },
|
||||
snap: null,
|
||||
audio: { input_muted: false, output_muted: false, transmitting: false },
|
||||
talking: new Set(),
|
||||
view: 'main',
|
||||
ptt: false,
|
||||
codecBlocked: null,
|
||||
};
|
||||
|
||||
const listeners = new Map();
|
||||
|
||||
export function on(topic, fn) {
|
||||
if (!listeners.has(topic)) listeners.set(topic, new Set());
|
||||
listeners.get(topic).add(fn);
|
||||
}
|
||||
|
||||
export function emit(topic, payload) {
|
||||
const set = listeners.get(topic);
|
||||
if (!set) return;
|
||||
for (const fn of set) fn(payload);
|
||||
}
|
||||
|
||||
export function ownClient() {
|
||||
const snap = S.snap;
|
||||
if (!snap) return null;
|
||||
return snap.clients.find((c) => c.id === snap.own_client_id) ?? null;
|
||||
}
|
||||
|
||||
export function ownChannel() {
|
||||
const snap = S.snap;
|
||||
if (!snap) return null;
|
||||
return snap.channels.find((c) => c.id === snap.own_channel_id) ?? null;
|
||||
}
|
||||
|
||||
export function clientById(id) {
|
||||
return S.snap ? S.snap.clients.find((c) => c.id === id) ?? null : null;
|
||||
}
|
||||
|
||||
export function isConnected() {
|
||||
return S.conn.state === 'connected' && S.snap !== null;
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// Which clients are currently streaming, built only from server notifications
|
||||
// (notifystreamstarted / notifystreaminfo / notifystreamupdated / notifystreamstopped).
|
||||
|
||||
export class StreamDirectory {
|
||||
constructor() {
|
||||
/** @type {Map<string, {id:string, clientId:number, name:string, fields:Record<string,string>}>} */
|
||||
this.streams = new Map();
|
||||
this.sfuSeen = false;
|
||||
}
|
||||
|
||||
/** Returns true when the visible set changed. */
|
||||
handle(name, items) {
|
||||
let changed = false;
|
||||
for (const item of items) {
|
||||
switch (name) {
|
||||
case 'notifystreamstarted':
|
||||
case 'notifystreaminfo':
|
||||
case 'notifystreamupdated':
|
||||
changed = this._upsert(item, name !== 'notifystreamupdated') || changed;
|
||||
break;
|
||||
case 'notifystreamstopped':
|
||||
changed = this._remove(item) || changed;
|
||||
break;
|
||||
case 'notifysfuaccessinfo':
|
||||
if (!this.sfuSeen) changed = true;
|
||||
this.sfuSeen = true;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
_upsert(item, mayCreate) {
|
||||
if (!item || !item.id) return false;
|
||||
const id = String(item.id);
|
||||
const existing = this.streams.get(id);
|
||||
const clientId = item.clid !== undefined && item.clid !== '' ? Number(item.clid) : existing?.clientId;
|
||||
if (!existing && (!mayCreate || !Number.isInteger(clientId))) return false;
|
||||
const fields = { ...(existing?.fields ?? {}), ...item };
|
||||
this.streams.set(id, {
|
||||
id,
|
||||
clientId,
|
||||
name: typeof fields.name === 'string' ? fields.name : '',
|
||||
fields,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
_remove(item) {
|
||||
if (item && item.id && this.streams.delete(String(item.id))) return true;
|
||||
if (item && item.clid !== undefined) {
|
||||
let removed = false;
|
||||
for (const [id, s] of this.streams) {
|
||||
if (s.clientId === Number(item.clid)) {
|
||||
this.streams.delete(id);
|
||||
removed = true;
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Drop streams of clients that are no longer on the server. */
|
||||
prune(presentClientIds) {
|
||||
let changed = false;
|
||||
for (const [id, s] of this.streams) {
|
||||
if (!presentClientIds.has(s.clientId)) {
|
||||
this.streams.delete(id);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
byClient(clientId) {
|
||||
for (const s of this.streams.values()) if (s.clientId === clientId) return s;
|
||||
return null;
|
||||
}
|
||||
|
||||
get(id) {
|
||||
return this.streams.get(String(id)) ?? null;
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.streams.clear();
|
||||
this.sfuSeen = false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
// One viewing session of a TS6 screenshare (P2P path). DOM-free: the RTCPeerConnection factory is injected.
|
||||
//
|
||||
// Wire (server text channel, via core `stream_*` commands / `stream` events):
|
||||
// join → joinstreamrequest id clid msg is_remove=0
|
||||
// offer ← notifyrespondjoinstreamrequest decision=1 offer=<sdp>
|
||||
// answer → streamsignaling json={"cmd":"answer","args":{"answer":<sdp>}}
|
||||
// ICE ↔ {"cmd":"iceCandidate","args":{"mLine","mid","sdp"}}
|
||||
// realign← {"cmd":"offer"|"reconnectOffer","args":{"offer":<sdp>}} must be answered or media never starts
|
||||
// leave → joinstreamrequest … is_remove=1
|
||||
|
||||
export const JOIN_TIMEOUT_MS = 90_000;
|
||||
|
||||
/** Terminal states: no further signaling is accepted once one is reached. */
|
||||
const TERMINAL = new Set(['declined', 'ended', 'removed', 'failed', 'stopped', 'unsupported']);
|
||||
|
||||
export class StreamViewerSession {
|
||||
/**
|
||||
* @param {object} o
|
||||
* @param {string} o.streamId
|
||||
* @param {number} o.clientId streamer clid
|
||||
* @param {number} o.ownClientId
|
||||
* @param {string} o.message join message (our nickname)
|
||||
* @param {{join:Function, send:Function, leave:Function}} o.signal async core calls
|
||||
* @param {(config:object)=>RTCPeerConnection} o.createPeerConnection
|
||||
* @param {RTCIceServer[]} [o.iceServers]
|
||||
* @param {(state:string, detail?:string)=>void} [o.onState]
|
||||
* @param {(track:MediaStreamTrack)=>void} [o.onTrack]
|
||||
* @param {(level:string, msg:string)=>void} [o.log]
|
||||
* @param {(fn:Function, ms:number)=>any} [o.setTimer]
|
||||
* @param {(id:any)=>void} [o.clearTimer]
|
||||
*/
|
||||
constructor(o) {
|
||||
this.streamId = String(o.streamId);
|
||||
this.clientId = Number(o.clientId);
|
||||
this.ownClientId = Number(o.ownClientId);
|
||||
this.message = o.message ?? '';
|
||||
this.signal = o.signal;
|
||||
this.createPeerConnection = o.createPeerConnection;
|
||||
this.iceServers = o.iceServers ?? [];
|
||||
this.onState = o.onState ?? (() => {});
|
||||
this.onTrack = o.onTrack ?? (() => {});
|
||||
this.log = o.log ?? (() => {});
|
||||
this.setTimer = o.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
|
||||
this.clearTimer = o.clearTimer ?? ((id) => clearTimeout(id));
|
||||
|
||||
this.state = 'idle';
|
||||
this.detail = '';
|
||||
this.pc = null;
|
||||
this.queue = Promise.resolve();
|
||||
this.pendingRemote = [];
|
||||
this.pendingLocal = [];
|
||||
this.answersSent = 0;
|
||||
this.offersApplied = 0;
|
||||
this.remoteCandidatesAdded = 0;
|
||||
this.staleCandidates = 0;
|
||||
this.candidateErrors = 0;
|
||||
this.joinTimer = null;
|
||||
}
|
||||
|
||||
get closed() {
|
||||
return TERMINAL.has(this.state);
|
||||
}
|
||||
|
||||
async start() {
|
||||
this._setState('requesting');
|
||||
this.joinTimer = this.setTimer(() => {
|
||||
if (this.state === 'requesting') this._finish('failed', 'no_response', true);
|
||||
}, JOIN_TIMEOUT_MS);
|
||||
try {
|
||||
await this.signal.join(this.streamId, this.clientId, this.message);
|
||||
this.log('info', `watch: join sent id=${this.streamId} clid=${this.clientId}`);
|
||||
} catch (err) {
|
||||
if (!this.closed) this._finish('failed', describe(err), false);
|
||||
}
|
||||
}
|
||||
|
||||
/** User stopped or cancelled. Sends is_remove=1 unless the stream is already gone. */
|
||||
stop() {
|
||||
if (this.closed) return;
|
||||
this._finish('stopped', '', true);
|
||||
}
|
||||
|
||||
/** The stream or the connection went away underneath us: no leave command. */
|
||||
terminate(reason) {
|
||||
if (this.closed) return;
|
||||
this._finish('ended', reason, false);
|
||||
}
|
||||
|
||||
/** True when the notification belongs to this session (stream id + streamer/our clid). */
|
||||
matches(item) {
|
||||
if (!item || String(item.id) !== this.streamId) return false;
|
||||
if (item.clid === undefined || item.clid === '') return true;
|
||||
const clid = Number(item.clid);
|
||||
return clid === this.clientId || clid === this.ownClientId;
|
||||
}
|
||||
|
||||
/** Feeds one `stream` event item. Returns true when consumed. */
|
||||
handle(name, item) {
|
||||
if (this.closed) return false;
|
||||
switch (name) {
|
||||
case 'notifyrespondjoinstreamrequest': {
|
||||
if (!this.matches(item)) return false;
|
||||
this._clearJoinTimer();
|
||||
const offer = typeof item.offer === 'string' ? item.offer : '';
|
||||
if (item.decision === '1' && offer) {
|
||||
this.log('info', `watch: join accepted, offer ${offer.length} chars (clid field=${item.clid ?? '-'})`);
|
||||
this._enqueue(() => this._applyOffer(offer, 'join'));
|
||||
} else {
|
||||
this.log('info', `watch: join declined decision=${item.decision ?? '-'}`);
|
||||
this._finish('declined', item.msg || '', false);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
case 'notifystreamsignaling': {
|
||||
if (!this.matches(item)) return false;
|
||||
let message;
|
||||
try {
|
||||
message = JSON.parse(item.json ?? '');
|
||||
} catch {
|
||||
this.log('warn', 'watch: unparseable signaling json');
|
||||
return true;
|
||||
}
|
||||
this._onSignal(message);
|
||||
return true;
|
||||
}
|
||||
case 'notifystreamstopped': {
|
||||
if (String(item.id) !== this.streamId) return false;
|
||||
this._finish('ended', 'stream_stopped', false);
|
||||
return true;
|
||||
}
|
||||
case 'notifystreamclientleft': {
|
||||
if (String(item.id) !== this.streamId) return false;
|
||||
if (Number(item.clid) === this.ownClientId) {
|
||||
this._finish('removed', '', false);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
case 'notifysfuaccessinfo': {
|
||||
// The server routes this stream through its SFU (mediasoup); TeamsPeach only speaks the P2P path.
|
||||
if (this.state === 'requesting' || this.matches(item)) {
|
||||
this._finish('unsupported', 'sfu', true);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
_onSignal(message) {
|
||||
const cmd = message && message.cmd;
|
||||
const args = (message && message.args) || {};
|
||||
switch (cmd) {
|
||||
case 'offer':
|
||||
case 'reconnectOffer': {
|
||||
const sdp = typeof args.offer === 'string' ? args.offer : typeof args.sdp === 'string' ? args.sdp : '';
|
||||
if (!sdp) {
|
||||
this.log('warn', `watch: ${cmd} without sdp`);
|
||||
return;
|
||||
}
|
||||
this.log('info', `watch: ${cmd} received (${sdp.length} chars)`);
|
||||
this._enqueue(() => this._applyOffer(sdp, cmd));
|
||||
return;
|
||||
}
|
||||
case 'iceCandidate':
|
||||
this._enqueue(() => this._addRemoteCandidate(args));
|
||||
return;
|
||||
default:
|
||||
this.log('info', `watch: ignored signaling cmd=${String(cmd)}`);
|
||||
}
|
||||
}
|
||||
|
||||
_ensurePc() {
|
||||
if (this.pc) return this.pc;
|
||||
const pc = this.createPeerConnection({ iceServers: this.iceServers });
|
||||
this.pc = pc;
|
||||
pc.onicecandidate = (event) => {
|
||||
const c = event.candidate;
|
||||
if (!c || !c.candidate || this.closed) return;
|
||||
const msg = {
|
||||
cmd: 'iceCandidate',
|
||||
args: { mLine: c.sdpMLineIndex ?? 0, mid: c.sdpMid ?? String(c.sdpMLineIndex ?? 0), sdp: c.candidate },
|
||||
};
|
||||
if (this.answersSent === 0) this.pendingLocal.push(msg);
|
||||
else this._send(msg).catch(() => {});
|
||||
};
|
||||
pc.ontrack = (event) => {
|
||||
if (!this.closed) this.onTrack(event.track);
|
||||
};
|
||||
pc.onconnectionstatechange = () => {
|
||||
if (this.closed) return;
|
||||
const s = pc.connectionState;
|
||||
this.log('info', `watch: connectionState=${s}`);
|
||||
if (s === 'connected') this._setState('live');
|
||||
else if (s === 'disconnected') this._setState('unstable');
|
||||
else if (s === 'failed') this._finish('failed', 'ice_failed', true);
|
||||
};
|
||||
return pc;
|
||||
}
|
||||
|
||||
async _applyOffer(sdp, reason) {
|
||||
if (this.closed) return;
|
||||
const pc = this._ensurePc();
|
||||
if (this.state === 'requesting') this._setState('connecting');
|
||||
if (pc.signalingState === 'have-remote-offer') {
|
||||
// A newer offer superseded one we never answered: discard the stale one.
|
||||
await pc.setRemoteDescription({ type: 'rollback' });
|
||||
}
|
||||
await pc.setRemoteDescription({ type: 'offer', sdp });
|
||||
if (this.closed) return;
|
||||
this.offersApplied += 1;
|
||||
await this._flushRemoteCandidates();
|
||||
const answer = await pc.createAnswer();
|
||||
if (this.closed) return;
|
||||
await pc.setLocalDescription(answer);
|
||||
if (this.closed) return;
|
||||
await this._send({ cmd: 'answer', args: { answer: pc.localDescription.sdp } });
|
||||
if (this.closed) return;
|
||||
this.answersSent += 1;
|
||||
this.log('info', `watch: answer sent for ${reason} (#${this.answersSent})`);
|
||||
const local = this.pendingLocal.splice(0);
|
||||
for (const msg of local) this._send(msg).catch(() => {});
|
||||
}
|
||||
|
||||
async _addRemoteCandidate(args) {
|
||||
if (this.closed) return;
|
||||
const sdp = typeof args.sdp === 'string' ? args.sdp : typeof args.candidate === 'string' ? args.candidate : '';
|
||||
if (!sdp) return; // end-of-candidates marker
|
||||
const mLine = Number(args.mLine);
|
||||
const init = {
|
||||
candidate: sdp,
|
||||
sdpMid: args.mid === undefined || args.mid === null ? null : String(args.mid),
|
||||
sdpMLineIndex: Number.isInteger(mLine) ? mLine : null,
|
||||
};
|
||||
if (init.sdpMid === null && init.sdpMLineIndex === null) init.sdpMLineIndex = 0;
|
||||
if (!this.pc || !this.pc.remoteDescription) {
|
||||
this.pendingRemote.push(init);
|
||||
return;
|
||||
}
|
||||
await this._addCandidate(init);
|
||||
}
|
||||
|
||||
async _flushRemoteCandidates() {
|
||||
const list = this.pendingRemote.splice(0);
|
||||
for (const init of list) await this._addCandidate(init);
|
||||
}
|
||||
|
||||
async _addCandidate(init) {
|
||||
const ufrag = candidateUfrag(init.candidate);
|
||||
const current = remoteUfrags(this.pc.remoteDescription?.sdp ?? '');
|
||||
if (ufrag && current.size > 0 && !current.has(ufrag)) {
|
||||
// Belongs to an ICE generation replaced by a newer (reconnect) offer: skip deliberately.
|
||||
this.staleCandidates += 1;
|
||||
this.log('info', `watch: skipped candidate of previous ICE generation (${this.staleCandidates})`);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await this.pc.addIceCandidate(init);
|
||||
this.remoteCandidatesAdded += 1;
|
||||
} catch (err) {
|
||||
this.candidateErrors += 1;
|
||||
this.log('warn', `watch: current-generation candidate rejected (mid=${init.sdpMid} mLine=${init.sdpMLineIndex}): ${describe(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** No signaling leaves a closed session, so nothing can follow our is_remove=1. */
|
||||
_send(json) {
|
||||
if (this.closed) return Promise.resolve();
|
||||
return this.signal.send(this.streamId, this.clientId, json).catch((err) => {
|
||||
this.log('warn', `watch: signaling send failed: ${describe(err)}`);
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
|
||||
_enqueue(task) {
|
||||
this.queue = this.queue.then(task).catch((err) => {
|
||||
if (!this.closed) this._finish('failed', describe(err), true);
|
||||
});
|
||||
return this.queue;
|
||||
}
|
||||
|
||||
_clearJoinTimer() {
|
||||
if (this.joinTimer !== null) {
|
||||
this.clearTimer(this.joinTimer);
|
||||
this.joinTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
_finish(state, detail, sendLeave) {
|
||||
if (this.closed) return;
|
||||
this._clearJoinTimer();
|
||||
this.pendingRemote = [];
|
||||
this.pendingLocal = [];
|
||||
if (this.pc) {
|
||||
this.pc.onicecandidate = null;
|
||||
this.pc.ontrack = null;
|
||||
this.pc.onconnectionstatechange = null;
|
||||
try {
|
||||
this.pc.close();
|
||||
} catch {
|
||||
// already closed
|
||||
}
|
||||
}
|
||||
this._setState(state, detail);
|
||||
if (sendLeave) {
|
||||
this.signal.leave(this.streamId, this.clientId).catch((err) => this.log('info', `watch: leave failed: ${describe(err)}`));
|
||||
}
|
||||
}
|
||||
|
||||
_setState(state, detail = '') {
|
||||
this.state = state;
|
||||
this.detail = detail;
|
||||
this.onState(state, detail);
|
||||
}
|
||||
}
|
||||
|
||||
/** `ufrag` attribute of an ICE candidate line, if present. */
|
||||
export function candidateUfrag(candidate) {
|
||||
const m = / ufrag (\S+)/.exec(candidate);
|
||||
return m ? m[1] : null;
|
||||
}
|
||||
|
||||
/** All `a=ice-ufrag` values of the applied remote description. */
|
||||
export function remoteUfrags(sdp) {
|
||||
const set = new Set();
|
||||
for (const m of sdp.matchAll(/^a=ice-ufrag:(\S+)/gm)) set.add(m[1]);
|
||||
return set;
|
||||
}
|
||||
|
||||
function describe(err) {
|
||||
if (!err) return 'unknown';
|
||||
if (typeof err === 'string') return err;
|
||||
return err.code ? `${err.code}: ${err.message ?? ''}` : String(err.message ?? err);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// User-facing wording for bridge errors and plain-text rendering of TeamSpeak BBCode.
|
||||
|
||||
const ERROR_TEXT = {
|
||||
bad_request: 'Некорректный запрос',
|
||||
unknown_command: 'Команда не поддерживается',
|
||||
profile_missing: 'Профиль ещё не создан',
|
||||
profile_exists: 'Профиль уже существует',
|
||||
identity_corrupt: 'Файл идентичности повреждён. Восстановите его из резервной копии (Настройки → Импорт).',
|
||||
profile_corrupt: 'Файл профиля повреждён',
|
||||
invalid_nickname: 'Никнейм должен содержать от 3 до 30 символов без управляющих символов',
|
||||
nickname_required: 'Сначала задайте никнейм',
|
||||
not_connected: 'Нет подключения к серверу',
|
||||
already_connected: 'Уже подключено',
|
||||
connect_failed: 'Не удалось подключиться',
|
||||
server_error: 'Сервер отклонил действие',
|
||||
audio_overflow: 'Очередь микрофона переполнена, часть звука пропущена',
|
||||
audio_muted: 'Микрофон или звук выключены — передача не идёт',
|
||||
audio_codec: 'Ошибка кодека Opus',
|
||||
audio_codec_unsupported: 'Канал использует устаревший кодек (Speex/CELT): передача голоса невозможна',
|
||||
rename_not_persisted: 'Сервер принял никнейм, но сохранить его на диск не удалось',
|
||||
io: 'Ошибка доступа к каталогу данных',
|
||||
internal: 'Внутренняя ошибка ядра',
|
||||
timeout: 'Ядро не ответило вовремя',
|
||||
core_unavailable: 'Ядро не запущено',
|
||||
core_exited: 'Ядро завершило работу',
|
||||
core_missing: 'Исполняемый файл ядра не найден',
|
||||
connected: 'Сначала отключитесь от сервера',
|
||||
forbidden: 'Действие запрещено',
|
||||
};
|
||||
|
||||
/** "Код: сообщение сервера" with the TeamSpeak error id when present. */
|
||||
export function errorText(error) {
|
||||
if (!error) return 'Неизвестная ошибка';
|
||||
const base = ERROR_TEXT[error.code] ?? error.message ?? error.code ?? 'Ошибка';
|
||||
const ts = error.ts_error;
|
||||
if (ts && (ts.message || ts.name)) {
|
||||
const perm = ts.missing_permission !== undefined && ts.missing_permission !== null ? `, не хватает права ${ts.missing_permission}` : '';
|
||||
return `${base}: ${ts.message || ts.name} (TS ${ts.id}${perm})`;
|
||||
}
|
||||
if (error.code === 'connect_failed' && error.message) return `${base}: ${error.message}`;
|
||||
if (!ERROR_TEXT[error.code] && error.message) return error.message;
|
||||
return base;
|
||||
}
|
||||
|
||||
const BB_TAGS = /\[\/?(?:b|i|u|s|url(?:=[^\]]*)?|color(?:=[^\]]*)?|size(?:=[^\]]*)?|center|left|right|img|quote|code|list|\*|hr|table|tr|td|th)\]/gi;
|
||||
|
||||
/** TeamSpeak clients send BBCode; TeamsPeach shows the plain text and never interprets markup. */
|
||||
export function stripBBCode(text) {
|
||||
return String(text ?? '').replace(/\[url=([^\]]*)\]([\s\S]*?)\[\/url\]/gi, (_m, href, label) => {
|
||||
const l = label.trim();
|
||||
return l && l !== href ? `${l} (${href})` : href;
|
||||
}).replace(BB_TAGS, '');
|
||||
}
|
||||
|
||||
/** TeamSpeak spacer channels: "[cspacer]Title", "[*spacer]-", "[spacer0]…" (top level only). */
|
||||
export function parseSpacer(name) {
|
||||
const m = /^\[(c|r|\*)?spacer[^\]]*\](.*)$/i.exec(name);
|
||||
if (!m) return null;
|
||||
const kind = m[1] === 'c' ? 'center' : m[1] === 'r' ? 'right' : m[1] === '*' ? 'repeat' : 'left';
|
||||
return { kind, text: m[2] };
|
||||
}
|
||||
|
||||
export function shortUid(uid) {
|
||||
if (!uid) return '';
|
||||
return uid.length > 14 ? `${uid.slice(0, 8)}…${uid.slice(-4)}` : uid;
|
||||
}
|
||||
|
||||
const KEY_NAMES = {
|
||||
Space: 'Пробел',
|
||||
Backquote: '`',
|
||||
ControlLeft: 'Левый Ctrl',
|
||||
ControlRight: 'Правый Ctrl',
|
||||
AltLeft: 'Левый Alt',
|
||||
AltRight: 'Правый Alt',
|
||||
ShiftLeft: 'Левый Shift',
|
||||
ShiftRight: 'Правый Shift',
|
||||
MetaLeft: 'Левый Super',
|
||||
MetaRight: 'Правый Super',
|
||||
CapsLock: 'Caps Lock',
|
||||
Tab: 'Tab',
|
||||
};
|
||||
|
||||
export function keyLabel(code) {
|
||||
if (!code) return 'не назначена';
|
||||
if (KEY_NAMES[code]) return KEY_NAMES[code];
|
||||
if (code.startsWith('Key')) return code.slice(3);
|
||||
if (code.startsWith('Digit')) return code.slice(5);
|
||||
if (code.startsWith('Numpad')) return `Num ${code.slice(6)}`;
|
||||
return code;
|
||||
}
|
||||
|
||||
export function pluralMembers(n) {
|
||||
const mod10 = n % 10;
|
||||
const mod100 = n % 100;
|
||||
if (mod10 === 1 && mod100 !== 11) return `${n} участник`;
|
||||
if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return `${n} участника`;
|
||||
return `${n} участников`;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { $, h, icon } from './dom.js';
|
||||
|
||||
const MAX_TOASTS = 4;
|
||||
|
||||
/** Non-blocking notice in the polite live region. Errors stay longer. */
|
||||
export function toast(text, kind = 'info') {
|
||||
const host = $('#toasts');
|
||||
const close = h('button', { class: 'icon-btn', type: 'button', 'aria-label': 'Закрыть уведомление' }, icon('x'));
|
||||
const el = h('div', { class: 'toast', role: kind === 'error' ? 'alert' : 'status', dataset: { kind } }, h('span', { class: 'toast-text', text }), close);
|
||||
const remove = () => el.remove();
|
||||
close.addEventListener('click', remove);
|
||||
host.appendChild(el);
|
||||
while (host.children.length > MAX_TOASTS) host.firstElementChild.remove();
|
||||
setTimeout(remove, kind === 'error' ? 10000 : 5000);
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
// Channel tree with members (TeamSpeak order), talking state, mute flags and stream badges.
|
||||
import { $, h, icon, reconcile, setText } from './dom.js';
|
||||
import { S, isConnected } from './state.js';
|
||||
import { call } from './core.js';
|
||||
import { errorText, parseSpacer, pluralMembers } from './text.js';
|
||||
import { toast } from './toast.js';
|
||||
|
||||
let hooks = { openPrivate: () => {}, openSettings: () => {}, toggleWatch: () => {}, streamOf: () => null, watchingId: () => null };
|
||||
let pendingPasswordCid = null;
|
||||
|
||||
export function initTree(h0) {
|
||||
hooks = { ...hooks, ...h0 };
|
||||
}
|
||||
|
||||
function sortClients(a, b) {
|
||||
if (b.talk_power !== a.talk_power) return b.talk_power - a.talk_power;
|
||||
return a.nickname.localeCompare(b.nickname, 'ru', { sensitivity: 'base' });
|
||||
}
|
||||
|
||||
export function renderTree() {
|
||||
const list = $('#tree');
|
||||
const empty = $('#tree-empty');
|
||||
if (!isConnected()) {
|
||||
list.replaceChildren();
|
||||
empty.hidden = false;
|
||||
setText(empty, S.conn.state === 'connecting' ? 'Подключение…' : 'Каналы появятся после подключения к серверу.');
|
||||
pendingPasswordCid = null;
|
||||
return;
|
||||
}
|
||||
empty.hidden = true;
|
||||
const snap = S.snap;
|
||||
const byChannel = new Map();
|
||||
for (const c of snap.clients) {
|
||||
if (c.client_type === 'query') continue;
|
||||
if (!byChannel.has(c.channel_id)) byChannel.set(c.channel_id, []);
|
||||
byChannel.get(c.channel_id).push(c);
|
||||
}
|
||||
const items = [];
|
||||
for (const ch of snap.channels) {
|
||||
const members = (byChannel.get(ch.id) ?? []).sort(sortClients);
|
||||
const spacer = ch.parent_id === 0 ? parseSpacer(ch.name) : null;
|
||||
if (spacer) items.push({ type: 'spacer', ch, spacer });
|
||||
else items.push({ type: 'channel', ch, count: members.length });
|
||||
if (pendingPasswordCid === ch.id) items.push({ type: 'password', ch });
|
||||
for (const cl of members) items.push({ type: 'member', cl, depth: ch.depth + 1 });
|
||||
}
|
||||
reconcile(list, items, keyOf, createRow, updateRow);
|
||||
}
|
||||
|
||||
function keyOf(item) {
|
||||
switch (item.type) {
|
||||
case 'member': return `u:${item.cl.id}`;
|
||||
case 'password': return `p:${item.ch.id}`;
|
||||
case 'spacer': return `s:${item.ch.id}`;
|
||||
default: return `c:${item.ch.id}`;
|
||||
}
|
||||
}
|
||||
|
||||
function createRow(item) {
|
||||
switch (item.type) {
|
||||
case 'spacer':
|
||||
return h('li', { class: 'tree-row spacer-row', role: 'presentation' });
|
||||
case 'password':
|
||||
return createPasswordRow(item.ch);
|
||||
case 'member':
|
||||
return createMemberRow();
|
||||
default:
|
||||
return createChannelRow();
|
||||
}
|
||||
}
|
||||
|
||||
function updateRow(el, item) {
|
||||
switch (item.type) {
|
||||
case 'spacer': {
|
||||
el.style.setProperty('--depth', String(item.ch.depth));
|
||||
el.dataset.kind = item.spacer.kind;
|
||||
const text = item.spacer.kind === 'repeat' ? item.spacer.text.repeat(Math.max(1, Math.ceil(60 / Math.max(1, item.spacer.text.length)))) : item.spacer.text;
|
||||
setText(el, text);
|
||||
break;
|
||||
}
|
||||
case 'password':
|
||||
el.style.setProperty('--depth', String(item.ch.depth));
|
||||
break;
|
||||
case 'member':
|
||||
updateMemberRow(el, item.cl, item.depth);
|
||||
break;
|
||||
default:
|
||||
updateChannelRow(el, item.ch, item.count);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- channels ----------
|
||||
|
||||
function createChannelRow() {
|
||||
const btn = h('button', { class: 'row-btn', type: 'button' }, icon('channel'), h('span', { class: 'row-label' }), h('span', { class: 'channel-meta' }));
|
||||
const li = h('li', { class: 'tree-row channel-row' }, btn);
|
||||
btn.addEventListener('click', () => joinChannel(Number(li.dataset.cid)));
|
||||
return li;
|
||||
}
|
||||
|
||||
function updateChannelRow(li, ch, count) {
|
||||
li.dataset.cid = String(ch.id);
|
||||
li.style.setProperty('--depth', String(ch.depth));
|
||||
const current = ch.id === S.snap.own_channel_id;
|
||||
li.dataset.current = String(current);
|
||||
const btn = li.firstElementChild;
|
||||
const [ic, label, meta] = btn.children;
|
||||
ic.firstElementChild.setAttribute('href', ch.has_password ? '#i-lock' : '#i-channel');
|
||||
setText(label, ch.name);
|
||||
const max = ch.max_clients;
|
||||
setText(meta, max !== null && max !== undefined && max >= 0 && count > 0 ? `${count}/${max}` : max === 0 ? 'закрыт' : '');
|
||||
const parts = [ch.name];
|
||||
if (ch.has_password) parts.push('с паролем');
|
||||
parts.push(pluralMembers(count));
|
||||
if (current) parts.push('вы здесь');
|
||||
btn.setAttribute('aria-label', parts.join(', '));
|
||||
btn.title = ch.topic ? ch.topic : current ? 'Вы в этом канале' : 'Перейти в канал';
|
||||
if (current) btn.setAttribute('aria-current', 'location');
|
||||
else btn.removeAttribute('aria-current');
|
||||
}
|
||||
|
||||
async function joinChannel(cid) {
|
||||
if (!isConnected() || cid === S.snap.own_channel_id) return;
|
||||
const ch = S.snap.channels.find((c) => c.id === cid);
|
||||
if (!ch) return;
|
||||
if (ch.has_password) {
|
||||
pendingPasswordCid = pendingPasswordCid === cid ? null : cid;
|
||||
renderTree();
|
||||
const input = document.querySelector(`[data-key="p:${cid}"] input`);
|
||||
if (input) input.focus();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await call('join_channel', { channel_id: cid });
|
||||
} catch (err) {
|
||||
toast(`Не удалось перейти в «${ch.name}»: ${errorText(err)}`, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function createPasswordRow(ch) {
|
||||
const input = h('input', { type: 'password', autocomplete: 'off', 'aria-label': `Пароль канала ${ch.name}`, placeholder: 'Пароль канала' });
|
||||
const cancel = h('button', { class: 'btn btn-ghost', type: 'button' }, 'Отмена');
|
||||
const form = h('form', { novalidate: true }, input, h('button', { class: 'btn btn-primary', type: 'submit' }, 'Войти'), cancel);
|
||||
const li = h('li', { class: 'tree-row password-row' }, form);
|
||||
const close = () => {
|
||||
pendingPasswordCid = null;
|
||||
renderTree();
|
||||
};
|
||||
cancel.addEventListener('click', close);
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape') close();
|
||||
});
|
||||
form.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
await call('join_channel', { channel_id: ch.id, password: input.value });
|
||||
close();
|
||||
} catch (err) {
|
||||
input.setAttribute('aria-invalid', 'true');
|
||||
toast(`Не удалось войти в «${ch.name}»: ${errorText(err)}`, 'error');
|
||||
input.select();
|
||||
}
|
||||
});
|
||||
return li;
|
||||
}
|
||||
|
||||
// ---------- members ----------
|
||||
|
||||
function createMemberRow() {
|
||||
const btn = h(
|
||||
'button',
|
||||
{ class: 'row-btn', type: 'button' },
|
||||
h('span', { class: 'status-dot', 'aria-hidden': 'true' }),
|
||||
h('span', { class: 'row-label' }),
|
||||
h('span', { class: 'member-tag' }),
|
||||
h('span', { class: 'member-flags' }),
|
||||
);
|
||||
const li = h('li', { class: 'tree-row member-row' }, btn);
|
||||
btn.addEventListener('click', () => {
|
||||
const id = Number(li.dataset.clid);
|
||||
if (li.dataset.self === 'true') hooks.openSettings();
|
||||
else hooks.openPrivate(id);
|
||||
});
|
||||
return li;
|
||||
}
|
||||
|
||||
function updateMemberRow(li, cl, depth) {
|
||||
li.dataset.clid = String(cl.id);
|
||||
li.style.setProperty('--depth', String(depth));
|
||||
li.dataset.self = String(cl.is_self);
|
||||
const talking = cl.is_self ? S.audio.transmitting : S.talking.has(cl.id);
|
||||
li.dataset.talking = String(talking);
|
||||
const btn = li.firstElementChild;
|
||||
const [, label, tag, flags] = btn.children;
|
||||
setText(label, cl.nickname);
|
||||
setText(tag, cl.is_self ? 'вы' : '');
|
||||
|
||||
const flagIcons = [];
|
||||
const states = [];
|
||||
if (cl.output_muted) {
|
||||
flagIcons.push(['headphones-off', 'flag-muted', 'Звук выключен']);
|
||||
states.push('звук выключен');
|
||||
} else if (cl.input_muted) {
|
||||
flagIcons.push(['mic-off', 'flag-muted', 'Микрофон выключен']);
|
||||
states.push('микрофон выключен');
|
||||
}
|
||||
if (!cl.input_hardware && !cl.input_muted) {
|
||||
flagIcons.push(['mic-off', '', 'Нет микрофона']);
|
||||
states.push('нет микрофона');
|
||||
}
|
||||
if (cl.away) {
|
||||
flagIcons.push(['moon', '', cl.away_message ? `Отошёл: ${cl.away_message}` : 'Отошёл']);
|
||||
states.push('отошёл');
|
||||
}
|
||||
const flagKey = flagIcons.map((f) => f[0] + f[1]).join('|');
|
||||
if (flags.dataset.sig !== flagKey) {
|
||||
flags.dataset.sig = flagKey;
|
||||
flags.replaceChildren(...flagIcons.map(([name, cls, title]) => {
|
||||
const wrap = h('span', { title }, icon(name, cls));
|
||||
return wrap;
|
||||
}));
|
||||
}
|
||||
if (talking) states.unshift('говорит');
|
||||
btn.setAttribute('aria-label', `${cl.nickname}${cl.is_self ? ' (вы)' : ''}${states.length ? `, ${states.join(', ')}` : ''}${cl.is_self ? '. Открыть настройки профиля' : '. Написать личное сообщение'}`);
|
||||
btn.title = cl.is_self ? 'Настройки профиля' : 'Написать личное сообщение';
|
||||
|
||||
const stream = hooks.streamOf(cl.id);
|
||||
let watch = li.querySelector('.watch-btn');
|
||||
if (stream && !cl.is_self) {
|
||||
if (!watch) {
|
||||
watch = h('button', { class: 'watch-btn', type: 'button' }, icon('monitor'), h('span', { text: 'Смотреть' }));
|
||||
watch.addEventListener('click', () => {
|
||||
const s = hooks.streamOf(Number(li.dataset.clid));
|
||||
if (s) hooks.toggleWatch(s);
|
||||
});
|
||||
li.appendChild(watch);
|
||||
}
|
||||
const watching = hooks.watchingId() === stream.id;
|
||||
watch.setAttribute('aria-pressed', String(watching));
|
||||
setText(watch.lastElementChild, watching ? 'Смотрите' : 'Смотреть');
|
||||
watch.setAttribute('aria-label', `${watching ? 'Прекратить просмотр' : 'Смотреть'} трансляцию ${cl.nickname}${stream.name ? `: ${stream.name}` : ''}`);
|
||||
watch.title = stream.name || 'Трансляция экрана';
|
||||
} else if (watch) {
|
||||
watch.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/** Cheap talking update without a full reconcile. */
|
||||
export function updateTalking(clientId) {
|
||||
const li = document.querySelector(`#tree [data-key="u:${clientId}"]`);
|
||||
if (!li || !S.snap) return;
|
||||
const cl = S.snap.clients.find((c) => c.id === clientId);
|
||||
if (cl) updateMemberRow(li, cl, Number(li.style.getPropertyValue('--depth')) || 0);
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
// Voice: microphone capture → core (gated by mute/deafen/PTT/open mic), core mix → speakers,
|
||||
// device selection and push-to-talk keys.
|
||||
import { $, setText } from './dom.js';
|
||||
import { S, isConnected, ownChannel } from './state.js';
|
||||
import { tp, log } from './core.js';
|
||||
import { AudioEngine } from './audio/engine.js';
|
||||
import { toast } from './toast.js';
|
||||
import { keyLabel } from './text.js';
|
||||
|
||||
export const voiceStats = { framesSent: 0, bursts: 0, framesPlayed: 0, level: 0 };
|
||||
|
||||
let engine = null;
|
||||
let sending = false;
|
||||
let micTest = false;
|
||||
let meterRaf = 0;
|
||||
let assigningPtt = null;
|
||||
let hooks = { onPtt: () => {}, onPttAssigned: () => {}, onTransmitChanged: () => {} };
|
||||
|
||||
export function initVoice(h0) {
|
||||
hooks = { ...hooks, ...h0 };
|
||||
engine = new AudioEngine({
|
||||
onFrame,
|
||||
onError: (e) => toast(e.message, 'error'),
|
||||
log,
|
||||
});
|
||||
tp.onAudio(({ pcm }) => {
|
||||
voiceStats.framesPlayed += 1;
|
||||
engine.pushPlayback(pcm);
|
||||
});
|
||||
window.addEventListener('keydown', onKeyDown, true);
|
||||
window.addEventListener('keyup', onKeyUp, true);
|
||||
window.addEventListener('blur', () => setPtt(false));
|
||||
navigator.mediaDevices.addEventListener('devicechange', () => refreshDevices());
|
||||
const btn = $('#btn-ptt');
|
||||
btn.addEventListener('pointerdown', (e) => {
|
||||
if (e.button !== 0) return;
|
||||
btn.setPointerCapture(e.pointerId);
|
||||
setPtt(true);
|
||||
});
|
||||
const release = () => setPtt(false);
|
||||
btn.addEventListener('pointerup', release);
|
||||
btn.addEventListener('pointercancel', release);
|
||||
btn.addEventListener('lostpointercapture', release);
|
||||
btn.addEventListener('keydown', (e) => {
|
||||
if ((e.key === ' ' || e.key === 'Enter') && !e.repeat) {
|
||||
e.preventDefault();
|
||||
setPtt(true);
|
||||
}
|
||||
});
|
||||
btn.addEventListener('keyup', (e) => {
|
||||
if (e.key === ' ' || e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
setPtt(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Creates the AudioContext and applies output prefs; safe to call repeatedly. */
|
||||
export async function startAudio() {
|
||||
try {
|
||||
await engine.init();
|
||||
engine.setVoiceVolume(S.prefs.voiceVolume);
|
||||
if (S.prefs.outputDeviceId) await engine.setOutputDevice(S.prefs.outputDeviceId).catch((err) => toast(`Устройство вывода недоступно: ${err.message}`, 'error'));
|
||||
} catch (err) {
|
||||
toast(`Звук недоступен: ${err.message}`, 'error');
|
||||
log('error', `audio init failed: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function channelCanTransmit() {
|
||||
const ch = ownChannel();
|
||||
return !ch || ch.codec === null || ch.codec === undefined || ch.codec === 'opus_voice' || ch.codec === 'opus_music';
|
||||
}
|
||||
|
||||
export function shouldTransmit() {
|
||||
return isConnected()
|
||||
&& !S.audio.input_muted
|
||||
&& !S.audio.output_muted
|
||||
&& (S.prefs.transmitMode === 'open' || S.ptt)
|
||||
&& channelCanTransmit();
|
||||
}
|
||||
|
||||
function onFrame(pcm, rms, peak) {
|
||||
voiceStats.level = peak;
|
||||
if (micTest && !meterRaf) meterRaf = requestAnimationFrame(drawMeter);
|
||||
if (shouldTransmit()) {
|
||||
tp.sendAudioFrame(new Uint8Array(pcm));
|
||||
voiceStats.framesSent += 1;
|
||||
if (!sending) {
|
||||
sending = true;
|
||||
voiceStats.bursts += 1;
|
||||
hooks.onTransmitChanged();
|
||||
}
|
||||
} else if (sending) {
|
||||
tp.endAudio();
|
||||
sending = false;
|
||||
hooks.onTransmitChanged();
|
||||
}
|
||||
}
|
||||
|
||||
function drawMeter() {
|
||||
meterRaf = 0;
|
||||
const db = voiceStats.level > 0 ? 20 * Math.log10(voiceStats.level) : -100;
|
||||
const pct = Math.max(0, Math.min(100, ((db + 60) / 60) * 100));
|
||||
$('#mic-meter').style.width = `${pct.toFixed(0)}%`;
|
||||
}
|
||||
|
||||
/** Capture runs while connected (or during the settings mic test). */
|
||||
export async function syncCapture() {
|
||||
const want = isConnected() || micTest;
|
||||
if (want && !engine.capturing) {
|
||||
try {
|
||||
await engine.startCapture({
|
||||
deviceId: S.prefs.inputDeviceId,
|
||||
echoCancellation: S.prefs.echoCancellation,
|
||||
noiseSuppression: S.prefs.noiseSuppression,
|
||||
autoGainControl: S.prefs.autoGainControl,
|
||||
});
|
||||
refreshDevices();
|
||||
} catch (err) {
|
||||
toast(`Нет доступа к микрофону: ${err.message || err.name}`, 'error');
|
||||
log('error', `capture failed: ${err.name} ${err.message}`);
|
||||
}
|
||||
} else if (!want && engine.capturing) {
|
||||
engine.stopCapture();
|
||||
if (sending) {
|
||||
tp.endAudio();
|
||||
sending = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function restartCapture() {
|
||||
if (!engine.capturing) return;
|
||||
engine.stopCapture();
|
||||
await syncCapture();
|
||||
}
|
||||
|
||||
export function setMicTest(on) {
|
||||
micTest = on;
|
||||
if (!on) $('#mic-meter').style.width = '0%';
|
||||
return syncCapture();
|
||||
}
|
||||
|
||||
export function onOutputMuted(muted) {
|
||||
if (muted) engine.flushPlayback();
|
||||
}
|
||||
|
||||
export function setVoiceVolume(pct) {
|
||||
engine.setVoiceVolume(pct);
|
||||
}
|
||||
|
||||
export async function setOutputDevice(id) {
|
||||
await engine.setOutputDevice(id);
|
||||
}
|
||||
|
||||
export function playbackStats() {
|
||||
return engine.playbackStats();
|
||||
}
|
||||
|
||||
// ---------- devices ----------
|
||||
|
||||
export async function refreshDevices() {
|
||||
let devices = [];
|
||||
try {
|
||||
devices = await navigator.mediaDevices.enumerateDevices();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
fillSelect($('#input-device'), devices.filter((d) => d.kind === 'audioinput'), S.prefs.inputDeviceId, 'Микрофон');
|
||||
fillSelect($('#output-device'), devices.filter((d) => d.kind === 'audiooutput'), S.prefs.outputDeviceId, 'Динамики');
|
||||
}
|
||||
|
||||
function fillSelect(select, list, selected, fallback) {
|
||||
const options = [{ value: '', label: 'Системное устройство по умолчанию' }];
|
||||
let n = 0;
|
||||
for (const d of list) {
|
||||
if (d.deviceId === 'default' || d.deviceId === 'communications' || d.deviceId === '') continue;
|
||||
n += 1;
|
||||
options.push({ value: d.deviceId, label: d.label || `${fallback} ${n}` });
|
||||
}
|
||||
if (selected && !options.some((o) => o.value === selected)) options.push({ value: selected, label: 'Выбранное устройство (не подключено)' });
|
||||
select.replaceChildren(...options.map((o) => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = o.value;
|
||||
opt.textContent = o.label;
|
||||
return opt;
|
||||
}));
|
||||
select.value = selected || '';
|
||||
}
|
||||
|
||||
// ---------- push-to-talk ----------
|
||||
|
||||
function isTextField(el) {
|
||||
return el instanceof HTMLTextAreaElement || (el instanceof HTMLInputElement && !['checkbox', 'radio', 'range', 'button', 'submit'].includes(el.type)) || el?.isContentEditable;
|
||||
}
|
||||
|
||||
function onKeyDown(e) {
|
||||
if (assigningPtt) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const done = assigningPtt;
|
||||
assigningPtt = null;
|
||||
done(e.key === 'Escape' ? null : e.code);
|
||||
return;
|
||||
}
|
||||
if (e.code !== S.prefs?.pttCode || e.repeat) return;
|
||||
if (S.prefs.transmitMode !== 'ptt') return;
|
||||
if (isTextField(e.target) && e.key.length === 1) return;
|
||||
setPtt(true);
|
||||
}
|
||||
|
||||
function onKeyUp(e) {
|
||||
if (e.code === S.prefs?.pttCode) setPtt(false);
|
||||
}
|
||||
|
||||
export function setPtt(down) {
|
||||
if (S.ptt === down) return;
|
||||
S.ptt = down;
|
||||
const btn = $('#btn-ptt');
|
||||
btn.setAttribute('aria-pressed', String(down));
|
||||
setText(btn, down ? 'Говорите…' : 'Удерживайте, чтобы говорить');
|
||||
hooks.onPtt(down);
|
||||
}
|
||||
|
||||
/** Resolves with a KeyboardEvent.code, or null when cancelled with Escape. */
|
||||
export function capturePttKey() {
|
||||
return new Promise((resolve) => {
|
||||
assigningPtt = resolve;
|
||||
});
|
||||
}
|
||||
|
||||
export function transmitHint() {
|
||||
if (!S.prefs) return '';
|
||||
if (S.prefs.transmitMode === 'open') return 'Открытый микрофон';
|
||||
return `Клавиша: ${keyLabel(S.prefs.pttCode)}`;
|
||||
}
|
||||
|
||||
export function isSending() {
|
||||
return sending;
|
||||
}
|
||||
|
||||
export function channelCodecProblem() {
|
||||
const ch = ownChannel();
|
||||
if (!ch || channelCanTransmit()) return null;
|
||||
return ch.codec;
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
// TS6 screenshare: discovery (stream_list + notifications), one viewing session, the viewer panel.
|
||||
import { $, setIcon, setText } from './dom.js';
|
||||
import { S, isConnected, clientById } from './state.js';
|
||||
import { call, log } from './core.js';
|
||||
import { StreamDirectory } from './stream/directory.js';
|
||||
import { StreamViewerSession } from './stream/session.js';
|
||||
import { toast } from './toast.js';
|
||||
import { errorText } from './text.js';
|
||||
|
||||
// Same public STUN endpoints the official TS6 client ships with (see docs/evidence/ts6-official-client.md).
|
||||
const ICE_SERVERS = [{ urls: ['stun:turn.teamspeak.com:3478', 'stun:turn2.teamspeak.com:3478'] }];
|
||||
|
||||
export const directory = new StreamDirectory();
|
||||
let session = null;
|
||||
let current = null; // { id, clientId, name, nickname }
|
||||
let media = null;
|
||||
let statsTimer = null;
|
||||
let attachTimer = null;
|
||||
let lastCodecLogged = '';
|
||||
let sfuToastShown = false;
|
||||
let hooks = { onChange: () => {}, savePrefs: () => {} };
|
||||
let listTimer = null;
|
||||
let listFull = false;
|
||||
const listClients = new Set();
|
||||
let knownChannelPeers = new Set();
|
||||
let knownOwnChannel = null;
|
||||
|
||||
function emptyStats() {
|
||||
return {
|
||||
codec: '', fmtp: '', decoder: '', powerEfficientDecoder: null, width: 0, height: 0, fps: 0,
|
||||
framesDecoded: 0, videoPackets: 0, videoBytes: 0, packetsLost: 0, keyFrames: 0,
|
||||
audioTrackPresent: false, streamAdvertisesAudio: null, audioCodec: '', inboundAudioPackets: 0, inboundAudioBytes: 0,
|
||||
remoteCandidatesAdded: 0, staleCandidates: 0, candidateErrors: 0, offersApplied: 0, answersSent: 0, pair: '',
|
||||
sinkId: '', sinkError: '',
|
||||
};
|
||||
}
|
||||
|
||||
export const watchStats = { state: 'idle', ...emptyStats() };
|
||||
|
||||
export function initWatch(h0) {
|
||||
hooks = { ...hooks, ...h0 };
|
||||
const video = $('#stream-video');
|
||||
const volume = $('#stream-volume');
|
||||
volume.addEventListener('input', () => applyVolume());
|
||||
volume.addEventListener('change', () => hooks.savePrefs({ streamVolume: Number(volume.value) }));
|
||||
$('#stream-mute').addEventListener('click', () => {
|
||||
const btn = $('#stream-mute');
|
||||
btn.setAttribute('aria-pressed', String(btn.getAttribute('aria-pressed') !== 'true'));
|
||||
applyVolume();
|
||||
});
|
||||
$('#stream-fullscreen').addEventListener('click', () => {
|
||||
const view = $('#stream-view');
|
||||
if (document.fullscreenElement) document.exitFullscreen();
|
||||
else view.requestFullscreen().catch((err) => toast(`Полноэкранный режим недоступен: ${err.message}`, 'error'));
|
||||
});
|
||||
$('#stream-stop').addEventListener('click', () => stopWatching());
|
||||
video.addEventListener('resize', () => updateStatsLine());
|
||||
// The output device is applied to a running player only; an element without media has nothing to route.
|
||||
video.addEventListener('playing', () => applySink());
|
||||
}
|
||||
|
||||
export function streamOf(clientId) {
|
||||
return directory.byClient(clientId);
|
||||
}
|
||||
|
||||
export function watchingId() {
|
||||
return session && !session.closed ? current.id : null;
|
||||
}
|
||||
|
||||
export function toggleWatch(stream) {
|
||||
if (session && !session.closed && current && current.id === stream.id) {
|
||||
stopWatching();
|
||||
return;
|
||||
}
|
||||
startWatching(stream);
|
||||
}
|
||||
|
||||
// ---------- discovery ----------
|
||||
|
||||
/** Called for every snapshot: asks newly seen channel members whether they stream. */
|
||||
export function onSnapshot() {
|
||||
const snap = S.snap;
|
||||
const present = new Set(snap.clients.map((c) => c.id));
|
||||
let changed = directory.prune(present);
|
||||
const peers = new Set(snap.clients.filter((c) => c.channel_id === snap.own_channel_id && !c.is_self && c.client_type !== 'query').map((c) => c.id));
|
||||
if (knownOwnChannel !== snap.own_channel_id) {
|
||||
knownOwnChannel = snap.own_channel_id;
|
||||
scheduleList(null);
|
||||
} else {
|
||||
for (const id of peers) if (!knownChannelPeers.has(id)) scheduleList(id);
|
||||
}
|
||||
knownChannelPeers = peers;
|
||||
if (session && !session.closed && current && !present.has(current.clientId)) {
|
||||
session.terminate('streamer_left');
|
||||
changed = true;
|
||||
}
|
||||
if (changed) hooks.onChange();
|
||||
}
|
||||
|
||||
function scheduleList(clientId) {
|
||||
if (clientId === null) listFull = true;
|
||||
else listClients.add(clientId);
|
||||
if (listTimer) return;
|
||||
listTimer = setTimeout(runList, 300);
|
||||
}
|
||||
|
||||
async function runList() {
|
||||
listTimer = null;
|
||||
if (!isConnected()) return;
|
||||
const full = listFull;
|
||||
const ids = Array.from(listClients);
|
||||
listFull = false;
|
||||
listClients.clear();
|
||||
const requests = full ? [undefined] : ids.map((id) => ({ client_id: id }));
|
||||
for (const args of requests) {
|
||||
try {
|
||||
const result = await call('stream_list', args);
|
||||
let changed = false;
|
||||
for (const r of result.results ?? []) {
|
||||
// A client that is not streaming answers requeststreaminfo with an error only.
|
||||
if (!r.ok && directory.byClient(r.client_id)) {
|
||||
changed = directory.handle('notifystreamstopped', [{ clid: String(r.client_id) }]) || changed;
|
||||
}
|
||||
}
|
||||
if (changed) hooks.onChange();
|
||||
} catch (err) {
|
||||
log('warn', `stream_list failed: ${err.code}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** `stream` event from the core (bridge §5). */
|
||||
export function onStreamEvent(evt) {
|
||||
const name = evt.name;
|
||||
const items = Array.isArray(evt.items) ? evt.items : [];
|
||||
log('info', `stream event ${name} items=${items.length} keys=${items[0] ? Object.keys(items[0]).sort().join(',') : '-'}`);
|
||||
if (session && !session.closed) {
|
||||
for (const item of items) session.handle(name, item);
|
||||
}
|
||||
if (name === 'notifysfuaccessinfo' && !sfuToastShown) {
|
||||
sfuToastShown = true;
|
||||
toast('Сервер передаёт трансляции через SFU. TeamsPeach поддерживает только прямые (P2P) трансляции TeamSpeak 6.', 'error');
|
||||
}
|
||||
if (directory.handle(name, items)) hooks.onChange();
|
||||
}
|
||||
|
||||
export function onDisconnected() {
|
||||
if (session && !session.closed) session.terminate('disconnected');
|
||||
directory.clear();
|
||||
knownChannelPeers = new Set();
|
||||
knownOwnChannel = null;
|
||||
sfuToastShown = false;
|
||||
}
|
||||
|
||||
// ---------- viewing ----------
|
||||
|
||||
/** Core-backed signaling for a session (bridge §4.12–4.14). */
|
||||
const coreTransport = {
|
||||
join: (id, clid, msg) => call('stream_join', { stream_id: id, client_id: clid, message: msg }),
|
||||
send: (id, clid, json) => call('stream_signal', { stream_id: id, client_id: clid, json }),
|
||||
leave: (id, clid) => call('stream_leave', { stream_id: id, client_id: clid }),
|
||||
};
|
||||
|
||||
/**
|
||||
* Starts viewing `stream`. `transport` is the signaling path; production always uses the core.
|
||||
* Every async continuation below checks that its session is still the current one.
|
||||
*/
|
||||
export function startWatching(stream, transport = coreTransport) {
|
||||
stopWatching();
|
||||
const streamer = clientById(stream.clientId);
|
||||
current = { id: stream.id, clientId: stream.clientId, name: stream.name, nickname: streamer?.nickname ?? stream.nickname ?? '?' };
|
||||
const sessionMedia = new MediaStream();
|
||||
media = sessionMedia;
|
||||
const video = $('#stream-video');
|
||||
applyVolume();
|
||||
lastCodecLogged = '';
|
||||
Object.assign(watchStats, emptyStats());
|
||||
watchStats.streamAdvertisesAudio = stream.fields?.audio === '1' ? true : stream.fields?.audio === '0' ? false : null;
|
||||
$('#stream-view').hidden = false;
|
||||
setText($('#stream-title'), current.name ? `${current.nickname} — ${current.name}` : `Трансляция ${current.nickname}`);
|
||||
setText($('#stream-stats'), '');
|
||||
|
||||
const own = new StreamViewerSession({
|
||||
streamId: stream.id,
|
||||
clientId: stream.clientId,
|
||||
ownClientId: S.snap?.own_client_id ?? 0,
|
||||
message: S.profile?.nickname ?? '',
|
||||
signal: transport,
|
||||
createPeerConnection: (config) => new RTCPeerConnection(config),
|
||||
iceServers: ICE_SERVERS,
|
||||
onState: (state, detail) => {
|
||||
if (session === own) onSessionState(state, detail);
|
||||
},
|
||||
onTrack: (track) => {
|
||||
if (session !== own) return;
|
||||
sessionMedia.addTrack(track);
|
||||
if (track.kind === 'audio') watchStats.audioTrackPresent = true;
|
||||
track.addEventListener('ended', () => sessionMedia.removeTrack(track));
|
||||
// Both tracks of an offer arrive in one setRemoteDescription; attach the stream once after them.
|
||||
// Later tracks are picked up by the element from the same MediaStream.
|
||||
if (attachTimer === null && video.srcObject !== sessionMedia) {
|
||||
attachTimer = setTimeout(() => {
|
||||
attachTimer = null;
|
||||
if (session !== own || own.closed || media !== sessionMedia) return;
|
||||
video.srcObject = sessionMedia;
|
||||
video.play().catch((err) => log('warn', `watch: play() rejected: ${err.name}`));
|
||||
}, 0);
|
||||
}
|
||||
},
|
||||
log,
|
||||
});
|
||||
session = own;
|
||||
hooks.onChange();
|
||||
own.start();
|
||||
statsTimer = setInterval(pollStats, 1500);
|
||||
}
|
||||
|
||||
export function stopWatching() {
|
||||
if (session && !session.closed) session.stop();
|
||||
session = null;
|
||||
current = null;
|
||||
teardownMedia();
|
||||
$('#stream-view').hidden = true;
|
||||
watchStats.state = 'idle';
|
||||
hooks.onChange();
|
||||
}
|
||||
|
||||
function teardownMedia() {
|
||||
clearInterval(statsTimer);
|
||||
statsTimer = null;
|
||||
clearTimeout(attachTimer);
|
||||
attachTimer = null;
|
||||
const video = $('#stream-video');
|
||||
video.srcObject = null;
|
||||
if (media) for (const t of media.getTracks()) t.stop();
|
||||
media = null;
|
||||
if (document.fullscreenElement) document.exitFullscreen().catch(() => {});
|
||||
}
|
||||
|
||||
const STATE_TEXT = {
|
||||
requesting: 'Запрос отправлен. Ждём ответа стримера…',
|
||||
connecting: 'Соединение со стримером…',
|
||||
live: '',
|
||||
unstable: 'Связь со стримером прервалась, ждём восстановления…',
|
||||
declined: 'Стример отклонил запрос на просмотр.',
|
||||
removed: 'Стример убрал вас из зрителей.',
|
||||
stopped: '',
|
||||
};
|
||||
|
||||
function failureText(detail) {
|
||||
switch (detail) {
|
||||
case 'no_response': return 'Стример не ответил на запрос за 90 секунд.';
|
||||
case 'ice_failed': return 'Не удалось установить прямое соединение со стримером. Для просмотра нужен прямой сетевой доступ к его компьютеру (через STUN, без TURN).';
|
||||
default: return `Ошибка трансляции: ${detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
function endedText(detail) {
|
||||
switch (detail) {
|
||||
case 'stream_stopped': return 'Трансляция завершена.';
|
||||
case 'streamer_left': return 'Стример покинул сервер.';
|
||||
case 'disconnected': return 'Соединение с сервером потеряно.';
|
||||
default: return 'Трансляция завершена.';
|
||||
}
|
||||
}
|
||||
|
||||
function onSessionState(state, detail) {
|
||||
watchStats.state = state;
|
||||
log('info', `watch: state ${state}${detail ? ` (${detail})` : ''}`);
|
||||
if (state === 'stopped') return;
|
||||
let text = STATE_TEXT[state];
|
||||
if (state === 'failed') text = failureText(detail);
|
||||
else if (state === 'ended') text = endedText(detail);
|
||||
else if (state === 'unsupported') text = 'Эта трансляция идёт через SFU-сервер TeamSpeak. TeamsPeach поддерживает только прямые (P2P) трансляции.';
|
||||
else if (state === 'declined' && detail) text = `${STATE_TEXT.declined} ${detail}`;
|
||||
if (state === 'live' && watchStats.framesDecoded === 0) text = 'Соединение установлено, ждём первый кадр…';
|
||||
setText($('#stream-overlay'), text ?? '');
|
||||
const terminal = ['declined', 'ended', 'removed', 'failed', 'unsupported'].includes(state);
|
||||
setText($('#stream-stop'), terminal ? 'Закрыть' : state === 'requesting' ? 'Отменить' : 'Прекратить просмотр');
|
||||
if (terminal) {
|
||||
teardownMedia();
|
||||
if (state !== 'ended' || detail !== 'disconnected') toast(text, state === 'ended' ? 'info' : 'error');
|
||||
}
|
||||
hooks.onChange();
|
||||
}
|
||||
|
||||
async function pollStats() {
|
||||
const own = session;
|
||||
const pc = own?.pc;
|
||||
if (!own || !pc || own.closed) return;
|
||||
let report;
|
||||
try {
|
||||
report = await pc.getStats();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
// The user may have stopped or switched streams while getStats() was pending.
|
||||
if (session !== own || own.closed) return;
|
||||
let inbound = null;
|
||||
let audioIn = null;
|
||||
let pair = null;
|
||||
const codecs = new Map();
|
||||
report.forEach((s) => {
|
||||
if (s.type === 'inbound-rtp' && s.kind === 'video') inbound = s;
|
||||
if (s.type === 'inbound-rtp' && s.kind === 'audio') audioIn = s;
|
||||
if (s.type === 'candidate-pair' && s.nominated && s.state === 'succeeded') pair = s;
|
||||
if (s.type === 'codec') codecs.set(s.id, s);
|
||||
});
|
||||
watchStats.remoteCandidatesAdded = own.remoteCandidatesAdded;
|
||||
watchStats.staleCandidates = own.staleCandidates;
|
||||
watchStats.candidateErrors = own.candidateErrors;
|
||||
watchStats.offersApplied = own.offersApplied;
|
||||
watchStats.answersSent = own.answersSent;
|
||||
if (pair) {
|
||||
const local = report.get(pair.localCandidateId);
|
||||
const remote = report.get(pair.remoteCandidateId);
|
||||
watchStats.pair = `${local?.candidateType ?? '?'}/${local?.protocol ?? '?'} → ${remote?.candidateType ?? '?'}`;
|
||||
}
|
||||
if (audioIn) {
|
||||
const ac = codecs.get(audioIn.codecId);
|
||||
watchStats.audioCodec = ac ? ac.mimeType : '';
|
||||
watchStats.inboundAudioPackets = audioIn.packetsReceived ?? 0;
|
||||
watchStats.inboundAudioBytes = audioIn.bytesReceived ?? 0;
|
||||
}
|
||||
if (!inbound) return;
|
||||
watchStats.videoPackets = inbound.packetsReceived ?? 0;
|
||||
watchStats.videoBytes = inbound.bytesReceived ?? 0;
|
||||
watchStats.packetsLost = inbound.packetsLost ?? 0;
|
||||
watchStats.keyFrames = inbound.keyFramesDecoded ?? 0;
|
||||
const codec = codecs.get(inbound.codecId);
|
||||
watchStats.codec = codec ? codec.mimeType.replace(/^video\//, '') : '';
|
||||
watchStats.fmtp = codec?.sdpFmtpLine ?? '';
|
||||
watchStats.width = inbound.frameWidth ?? 0;
|
||||
watchStats.height = inbound.frameHeight ?? 0;
|
||||
watchStats.fps = Math.round(inbound.framesPerSecond ?? 0);
|
||||
const firstFrame = watchStats.framesDecoded === 0 && (inbound.framesDecoded ?? 0) > 0;
|
||||
watchStats.framesDecoded = inbound.framesDecoded ?? 0;
|
||||
watchStats.decoder = inbound.decoderImplementation ?? '';
|
||||
watchStats.powerEfficientDecoder = typeof inbound.powerEfficientDecoder === 'boolean' ? inbound.powerEfficientDecoder : null;
|
||||
if (firstFrame && own.state === 'live') setText($('#stream-overlay'), '');
|
||||
const sig = `${watchStats.codec} ${watchStats.fmtp}`;
|
||||
if (codec && sig !== lastCodecLogged) {
|
||||
lastCodecLogged = sig;
|
||||
log('info', `watch: negotiated ${codec.mimeType} fmtp="${codec.sdpFmtpLine ?? ''}" decoder=${watchStats.decoder}`);
|
||||
}
|
||||
updateStatsLine();
|
||||
}
|
||||
|
||||
function updateStatsLine() {
|
||||
if (!session) return;
|
||||
const parts = [];
|
||||
if (watchStats.codec) parts.push(watchStats.codec);
|
||||
if (watchStats.width) parts.push(`${watchStats.width}×${watchStats.height}`);
|
||||
if (watchStats.fps) parts.push(`${watchStats.fps} к/с`);
|
||||
if (session.state === 'live') {
|
||||
if (watchStats.streamAdvertisesAudio === false) parts.push('стример не передаёт звук');
|
||||
else if (watchStats.inboundAudioPackets > 0) parts.push('со звуком');
|
||||
}
|
||||
setText($('#stream-stats'), parts.join(' · '));
|
||||
}
|
||||
|
||||
export function applyVolume() {
|
||||
const video = $('#stream-video');
|
||||
const volume = $('#stream-volume');
|
||||
const muted = $('#stream-mute').getAttribute('aria-pressed') === 'true';
|
||||
video.volume = Number(volume.value) / 100;
|
||||
video.muted = muted || S.audio.output_muted;
|
||||
setText($('#stream-volume-value'), `${volume.value}%`);
|
||||
setIcon($('#stream-mute').firstElementChild, muted ? 'speaker-off' : 'speaker');
|
||||
$('#stream-mute').title = muted ? 'Включить звук трансляции' : 'Выключить звук трансляции';
|
||||
}
|
||||
|
||||
let sinkChain = Promise.resolve();
|
||||
|
||||
/**
|
||||
* Routes stream audio to the selected output device. Calls are serialized and only issued for a
|
||||
* playing element whose current sink differs; a failure is reported with the device name and the
|
||||
* element keeps playing on its current device.
|
||||
*/
|
||||
export function applySink() {
|
||||
const video = $('#stream-video');
|
||||
if (typeof video.setSinkId !== 'function' || !S.prefs) return;
|
||||
sinkChain = sinkChain.then(async () => {
|
||||
const own = session;
|
||||
const target = S.prefs.outputDeviceId || '';
|
||||
if (!own || !video.srcObject || video.sinkId === target) {
|
||||
watchStats.sinkId = video.sinkId;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await video.setSinkId(target);
|
||||
if (session !== own) return;
|
||||
watchStats.sinkId = video.sinkId;
|
||||
watchStats.sinkError = '';
|
||||
log('info', `watch: audio output set (${target ? 'selected device' : 'system default'})`);
|
||||
} catch (err) {
|
||||
log('warn', `watch: setSinkId failed ${err.name}: ${err.message}`);
|
||||
if (session !== own) return;
|
||||
watchStats.sinkError = `${err.name}: ${err.message}`;
|
||||
const label = Array.from($('#output-device').options).find((o) => o.value === target)?.textContent || 'выбранное устройство';
|
||||
toast(`Звук трансляции не удалось направить на «${label}» (${err.name}). Он продолжает играть через текущее устройство; выберите другое в Настройки → Звук.`, 'error');
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,609 @@
|
||||
/* TeamsPeach — restrained working UI: warm neutrals, one peach accent, state colours that mean something. */
|
||||
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
--font: system-ui, -apple-system, "Segoe UI", "Noto Sans", Ubuntu, Cantarell, "Helvetica Neue", Arial, sans-serif;
|
||||
--mono: ui-monospace, "Cascadia Mono", "SFMono-Regular", "DejaVu Sans Mono", Consolas, monospace;
|
||||
|
||||
--bg: #f6f3f0;
|
||||
--surface: #fffdfb;
|
||||
--sidebar: #eee9e4;
|
||||
--sunken: #e6e0da;
|
||||
--hover: rgba(70, 45, 30, 0.07);
|
||||
--border: #dcd3cb;
|
||||
--border-strong: #c3b7ad;
|
||||
--text: #221c18;
|
||||
--text-2: #5e544d;
|
||||
--text-3: #776c64;
|
||||
--accent: #b24f26;
|
||||
--accent-hover: #9c431e;
|
||||
--accent-ink: #ffffff;
|
||||
--accent-soft: #fbe2d4;
|
||||
--accent-soft-ink: #7c3112;
|
||||
--peach: #f3a37c;
|
||||
--talk: #1f8a5a;
|
||||
--talk-soft: rgba(31, 138, 90, 0.16);
|
||||
--danger: #b3261e;
|
||||
--danger-soft: #f9dedc;
|
||||
--warn-soft: #fbedd0;
|
||||
--warn-ink: #6b4a00;
|
||||
--focus: #b24f26;
|
||||
--shadow: 0 6px 20px rgba(40, 24, 12, 0.14), 0 1px 3px rgba(40, 24, 12, 0.1);
|
||||
--radius: 8px;
|
||||
--radius-sm: 6px;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg: #1a1817;
|
||||
--surface: #211e1c;
|
||||
--sidebar: #1e1b1a;
|
||||
--sunken: #151312;
|
||||
--hover: rgba(255, 235, 220, 0.06);
|
||||
--border: #35302c;
|
||||
--border-strong: #4a433e;
|
||||
--text: #ede6e0;
|
||||
--text-2: #b2a79f;
|
||||
--text-3: #978c84;
|
||||
--accent: #f09a6c;
|
||||
--accent-hover: #f6ae86;
|
||||
--accent-ink: #2a140a;
|
||||
--accent-soft: #3b2920;
|
||||
--accent-soft-ink: #f6c0a2;
|
||||
--peach: #f3a37c;
|
||||
--talk: #4fcf8e;
|
||||
--talk-soft: rgba(79, 207, 142, 0.18);
|
||||
--danger: #f08b82;
|
||||
--danger-soft: #42221f;
|
||||
--warn-soft: #3a2f17;
|
||||
--warn-ink: #f0d18a;
|
||||
--focus: #f09a6c;
|
||||
--shadow: 0 8px 24px rgba(0, 0, 0, 0.45), 0 1px 3px rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
html, body {
|
||||
margin: 0;
|
||||
height: 100%;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: 14px/1.45 var(--font);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
body { overflow: hidden; }
|
||||
|
||||
[hidden] { display: none !important; }
|
||||
|
||||
::selection { background: var(--accent-soft); color: var(--accent-soft-ink); }
|
||||
|
||||
:focus-visible {
|
||||
outline: 2px solid var(--focus);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
::-webkit-scrollbar-thumb { background: var(--border-strong); border-radius: 8px; border: 2px solid transparent; background-clip: padding-box; }
|
||||
::-webkit-scrollbar-thumb:hover { background-color: var(--text-3); }
|
||||
|
||||
h1, h2, h3 { margin: 0; font-weight: 650; text-wrap: balance; }
|
||||
h1 { font-size: 20px; line-height: 1.25; }
|
||||
h2 { font-size: 16px; }
|
||||
h3 { font-size: 14px; }
|
||||
p { margin: 0; }
|
||||
|
||||
.sprite { position: absolute; width: 0; height: 0; overflow: hidden; }
|
||||
|
||||
.icon {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
flex: none;
|
||||
fill: none;
|
||||
stroke: currentColor;
|
||||
stroke-width: 1.8;
|
||||
stroke-linecap: round;
|
||||
stroke-linejoin: round;
|
||||
}
|
||||
|
||||
.brand-mark { width: 40px; height: 40px; stroke: none; }
|
||||
.brand-mark-large { width: 56px; height: 56px; }
|
||||
.brand-mark .peach-body, .peach-body { fill: var(--peach); stroke: none; }
|
||||
.peach-crease { fill: none; stroke: rgba(120, 50, 20, 0.35); stroke-width: 1.2; }
|
||||
.peach-leaf { fill: #5f9e5a; stroke: none; }
|
||||
|
||||
/* ---------- controls ---------- */
|
||||
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
min-height: 34px;
|
||||
padding: 6px 14px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
font-weight: 550;
|
||||
cursor: pointer;
|
||||
transition: background-color 120ms ease-out, border-color 120ms ease-out;
|
||||
}
|
||||
.btn:hover { background: var(--hover); }
|
||||
.btn:disabled { opacity: 0.55; cursor: not-allowed; }
|
||||
.btn .icon { width: 18px; height: 18px; }
|
||||
.btn-primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||
.btn-primary:hover { background: var(--accent-hover); border-color: var(--accent-hover); }
|
||||
.btn-ghost { background: transparent; border-color: transparent; color: var(--text-2); padding-inline: 8px; }
|
||||
.btn-ghost:hover { background: var(--hover); color: var(--text); }
|
||||
.btn-ghost[aria-pressed="true"] { color: var(--accent-soft-ink); background: var(--accent-soft); }
|
||||
.btn-wide { width: 100%; }
|
||||
.btn-danger { color: var(--danger); }
|
||||
|
||||
.icon-btn {
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--radius-sm);
|
||||
background: transparent;
|
||||
color: var(--text-2);
|
||||
cursor: pointer;
|
||||
transition: background-color 120ms ease-out, color 120ms ease-out;
|
||||
}
|
||||
.icon-btn:hover { background: var(--hover); color: var(--text); }
|
||||
.icon-btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
.icon-btn[aria-pressed="true"] { color: var(--danger); background: var(--danger-soft); }
|
||||
.icon-btn-accent { color: var(--accent); }
|
||||
|
||||
.field { display: flex; flex-direction: column; gap: 6px; }
|
||||
.field-grow { flex: 1; }
|
||||
.field-label { font-size: 13px; font-weight: 600; color: var(--text-2); }
|
||||
.optional { font-weight: 400; color: var(--text-3); }
|
||||
|
||||
input[type="text"], input[type="password"], select, textarea {
|
||||
width: 100%;
|
||||
min-height: 36px;
|
||||
padding: 7px 10px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
caret-color: var(--accent);
|
||||
}
|
||||
input::placeholder, textarea::placeholder { color: var(--text-3); }
|
||||
input:focus-visible, select:focus-visible, textarea:focus-visible { outline: 2px solid var(--focus); outline-offset: 0; border-color: transparent; }
|
||||
input[aria-invalid="true"] { border-color: var(--danger); }
|
||||
|
||||
input[type="checkbox"], input[type="radio"] { accent-color: var(--accent); width: 16px; height: 16px; margin: 0; }
|
||||
|
||||
.range { accent-color: var(--accent); width: 100%; }
|
||||
.range-value { min-width: 3.5ch; font-variant-numeric: tabular-nums; color: var(--text-2); font-size: 12px; }
|
||||
|
||||
.fieldset { border: 0; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 8px; }
|
||||
.fieldset legend { margin-bottom: 8px; padding: 0; }
|
||||
.choice { display: flex; align-items: center; gap: 8px; cursor: pointer; }
|
||||
|
||||
.hint { font-size: 12.5px; color: var(--text-3); max-width: 68ch; }
|
||||
.lede { color: var(--text-2); max-width: 60ch; }
|
||||
.form-error { min-height: 1em; color: var(--danger); font-size: 13px; }
|
||||
.form-error:empty { display: none; }
|
||||
.form-status { color: var(--text-2); font-size: 13px; }
|
||||
.form-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
|
||||
|
||||
.kbd {
|
||||
display: inline-block;
|
||||
min-width: 2.4em;
|
||||
padding: 2px 8px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-bottom-width: 2px;
|
||||
border-radius: 5px;
|
||||
background: var(--surface);
|
||||
font: 12.5px var(--mono);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* ---------- boot / fatal / onboarding ---------- */
|
||||
|
||||
.boot, .fatal, .onboarding {
|
||||
height: 100%;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 32px;
|
||||
}
|
||||
.boot { gap: 12px; align-content: center; color: var(--text-2); }
|
||||
|
||||
.fatal-inner { max-width: 620px; display: flex; flex-direction: column; gap: 14px; }
|
||||
.fatal-list { margin: 0; padding-left: 18px; font: 12.5px var(--mono); color: var(--text-2); word-break: break-all; }
|
||||
.fatal-list:empty { display: none; }
|
||||
.fatal-actions { display: flex; gap: 10px; flex-wrap: wrap; }
|
||||
|
||||
.onboarding-form {
|
||||
width: min(420px, 100%);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
.onboarding-form h1 { font-size: 24px; margin-top: 6px; }
|
||||
|
||||
/* ---------- shell ---------- */
|
||||
|
||||
.shell {
|
||||
height: 100%;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(260px, 300px) 1fr;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
background: var(--sidebar);
|
||||
border-right: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.server-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 12px 10px 12px 14px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.server-title { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
|
||||
.server-name { font-weight: 650; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.conn-badge { font-size: 12px; color: var(--text-3); display: inline-flex; align-items: center; gap: 6px; }
|
||||
.conn-badge::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: var(--text-3); }
|
||||
.conn-badge[data-state="connected"] { color: var(--talk); }
|
||||
.conn-badge[data-state="connected"]::before { background: var(--talk); }
|
||||
.conn-badge[data-state="connecting"]::before, .conn-badge[data-state="disconnecting"]::before { background: var(--peach); }
|
||||
|
||||
.tree-empty { padding: 16px 14px; color: var(--text-3); font-size: 13px; }
|
||||
|
||||
.tree {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 6px 6px 12px;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.tree-row { --indent: calc(var(--depth, 0) * 14px); }
|
||||
|
||||
.row-btn {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
min-height: 30px;
|
||||
padding: 4px 8px 4px calc(8px + var(--indent));
|
||||
border: 0;
|
||||
border-radius: var(--radius-sm);
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.row-btn:hover { background: var(--hover); }
|
||||
.row-btn .icon { width: 17px; height: 17px; color: var(--text-3); }
|
||||
.row-label { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
|
||||
.channel-row .row-btn { font-weight: 600; color: var(--text-2); }
|
||||
.channel-row[data-current="true"] .row-btn { color: var(--text); background: var(--accent-soft); }
|
||||
.channel-row[data-current="true"] .row-btn .icon { color: var(--accent-soft-ink); }
|
||||
.channel-meta { font-size: 12px; font-weight: 400; color: var(--text-3); font-variant-numeric: tabular-nums; }
|
||||
|
||||
.spacer-row { padding: 8px 8px 4px calc(8px + var(--indent)); font-size: 12px; font-weight: 600; color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: clip; }
|
||||
.spacer-row[data-kind="center"] { text-align: center; }
|
||||
.spacer-row[data-kind="right"] { text-align: right; }
|
||||
|
||||
.member-row { display: flex; align-items: center; gap: 2px; padding-right: 2px; }
|
||||
.member-row .row-btn { padding-left: calc(24px + var(--indent)); min-height: 28px; font-weight: 450; }
|
||||
.member-row[data-self="true"] .row-label { font-weight: 650; }
|
||||
.member-tag { font-size: 12px; color: var(--text-3); }
|
||||
.member-flags { display: inline-flex; gap: 2px; color: var(--text-3); }
|
||||
.member-flags .icon { width: 15px; height: 15px; }
|
||||
.member-flags .flag-muted { color: var(--danger); }
|
||||
|
||||
.status-dot {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
flex: none;
|
||||
border-radius: 50%;
|
||||
border: 2px solid var(--border-strong);
|
||||
transition: background-color 90ms ease-out, border-color 90ms ease-out, box-shadow 90ms ease-out;
|
||||
}
|
||||
[data-talking="true"] > .row-btn .status-dot,
|
||||
.status-dot[data-talking="true"] {
|
||||
background: var(--talk);
|
||||
border-color: var(--talk);
|
||||
box-shadow: 0 0 0 3px var(--talk-soft);
|
||||
}
|
||||
|
||||
.watch-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
flex: none;
|
||||
height: 24px;
|
||||
padding: 0 8px 0 6px;
|
||||
border: 1px solid var(--accent);
|
||||
border-radius: 12px;
|
||||
background: transparent;
|
||||
color: var(--accent);
|
||||
font: 600 12px var(--font);
|
||||
cursor: pointer;
|
||||
}
|
||||
.watch-btn .icon { width: 14px; height: 14px; }
|
||||
.watch-btn:hover { background: var(--accent-soft); }
|
||||
.watch-btn[aria-pressed="true"] { background: var(--accent); color: var(--accent-ink); }
|
||||
|
||||
.password-row { padding: 4px 6px 8px calc(30px + var(--indent)); }
|
||||
.password-row form { display: flex; gap: 6px; }
|
||||
.password-row input { min-height: 30px; padding: 4px 8px; }
|
||||
.password-row .btn { min-height: 30px; padding: 4px 10px; }
|
||||
|
||||
.self {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 10px 8px 10px 14px;
|
||||
border-top: 1px solid var(--border);
|
||||
background: var(--sunken);
|
||||
}
|
||||
.self-id { flex: 1; min-width: 0; display: flex; align-items: center; gap: 10px; }
|
||||
.self-text { min-width: 0; }
|
||||
.self-nick { font-weight: 650; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.self-sub { font-size: 12px; color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-variant-numeric: tabular-nums; }
|
||||
.self-actions { display: flex; gap: 2px; }
|
||||
|
||||
/* ---------- workspace ---------- */
|
||||
|
||||
.workspace { min-width: 0; min-height: 0; display: flex; flex-direction: column; background: var(--surface); }
|
||||
|
||||
.connect-view { flex: 1; overflow-y: auto; display: grid; place-items: center; padding: 32px; }
|
||||
.connect-form { width: min(440px, 100%); display: flex; flex-direction: column; gap: 14px; }
|
||||
|
||||
.session-view { flex: 1; min-height: 0; display: flex; flex-direction: column; }
|
||||
|
||||
.session-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
padding: 12px 18px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.session-title { flex: 1; min-width: 0; }
|
||||
.session-title h1 { font-size: 17px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.channel-topic { font-size: 12.5px; color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.channel-topic:empty { display: none; }
|
||||
.transmit { display: flex; align-items: center; gap: 10px; flex: none; }
|
||||
.transmit-hint { font-size: 12.5px; color: var(--text-3); }
|
||||
.btn-ptt { user-select: none; touch-action: none; }
|
||||
.btn-ptt[aria-pressed="true"] { background: var(--talk); border-color: var(--talk); color: #fff; }
|
||||
|
||||
.notice {
|
||||
margin: 10px 18px 0;
|
||||
padding: 8px 12px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--warn-soft);
|
||||
color: var(--warn-ink);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* stream */
|
||||
.stream-view {
|
||||
flex: 0 0 58%;
|
||||
min-height: 220px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: #0d0c0b;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.stream-stage { position: relative; flex: 1; min-height: 0; }
|
||||
.stream-stage video { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; background: #0d0c0b; }
|
||||
.stream-overlay {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 24px;
|
||||
color: #e9e2dc;
|
||||
text-align: center;
|
||||
font-size: 14px;
|
||||
pointer-events: none;
|
||||
}
|
||||
.stream-overlay:empty { display: none; }
|
||||
.stream-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 8px 12px;
|
||||
background: #171514;
|
||||
color: #ede6e0;
|
||||
}
|
||||
.stream-bar .icon-btn { color: #c9bfb7; }
|
||||
.stream-bar .icon-btn:hover { background: rgba(255, 255, 255, 0.08); color: #fff; }
|
||||
.stream-bar .icon-btn[aria-pressed="true"] { background: rgba(240, 139, 130, 0.18); color: #f4a39b; }
|
||||
.stream-bar .btn { background: transparent; color: #ede6e0; border-color: #4a433e; }
|
||||
.stream-bar .btn:hover { background: rgba(255, 255, 255, 0.08); }
|
||||
.stream-bar .range { width: 120px; accent-color: #f09a6c; }
|
||||
.stream-bar .range-value { color: #b2a79f; }
|
||||
.stream-meta { flex: 1; min-width: 0; display: flex; flex-direction: column; }
|
||||
.stream-title { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.stream-stats { font-size: 12px; color: #b2a79f; font-variant-numeric: tabular-nums; }
|
||||
.stream-controls { display: flex; align-items: center; gap: 6px; }
|
||||
.stream-view:fullscreen .stream-stage video { object-fit: contain; }
|
||||
|
||||
/* chat */
|
||||
.chat { flex: 1; min-height: 160px; display: flex; flex-direction: column; }
|
||||
|
||||
.chat-tabs {
|
||||
display: flex;
|
||||
gap: 2px;
|
||||
padding: 8px 12px 0;
|
||||
border-bottom: 1px solid var(--border);
|
||||
overflow-x: auto;
|
||||
flex: none;
|
||||
}
|
||||
.tab-wrap { display: inline-flex; align-items: center; flex: none; }
|
||||
.chat-tab {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
max-width: 220px;
|
||||
padding: 7px 10px 8px;
|
||||
border: 0;
|
||||
border-bottom: 2px solid transparent;
|
||||
background: transparent;
|
||||
color: var(--text-2);
|
||||
font: inherit;
|
||||
font-weight: 550;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.chat-tab:hover { color: var(--text); }
|
||||
.chat-tab[aria-selected="true"] { color: var(--text); border-bottom-color: var(--accent); }
|
||||
.chat-tab .tab-label { overflow: hidden; text-overflow: ellipsis; }
|
||||
.chat-tab .unread {
|
||||
min-width: 18px;
|
||||
padding: 0 5px;
|
||||
border-radius: 9px;
|
||||
background: var(--accent);
|
||||
color: var(--accent-ink);
|
||||
font-size: 11px;
|
||||
line-height: 18px;
|
||||
text-align: center;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.tab-close {
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border-radius: 4px;
|
||||
color: var(--text-3);
|
||||
}
|
||||
.tab-close:hover { background: var(--hover); color: var(--text); }
|
||||
.tab-close .icon { width: 14px; height: 14px; }
|
||||
|
||||
.chat-log {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
margin: 0;
|
||||
padding: 12px 18px;
|
||||
list-style: none;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.chat-log:focus-visible { outline-offset: -2px; }
|
||||
.chat-empty { color: var(--text-3); font-size: 13px; padding: 8px 0; }
|
||||
|
||||
.msg { padding: 2px 0; max-width: 80ch; }
|
||||
.msg + .msg[data-head="true"] { margin-top: 10px; }
|
||||
.msg-head { display: flex; align-items: baseline; gap: 8px; }
|
||||
.msg-author { font-weight: 650; }
|
||||
.msg[data-own="true"] .msg-author { color: var(--accent); }
|
||||
.msg-time { font-size: 11.5px; color: var(--text-3); font-variant-numeric: tabular-nums; }
|
||||
.msg-body { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.msg-system { color: var(--text-3); font-size: 13px; padding: 4px 0; }
|
||||
.msg-system + .msg[data-head="true"], .msg + .msg-system { margin-top: 8px; }
|
||||
|
||||
.composer {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: 8px;
|
||||
margin: 0 18px 14px;
|
||||
padding: 6px 6px 6px 12px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
background: var(--surface);
|
||||
}
|
||||
.composer:focus-within { border-color: var(--focus); box-shadow: 0 0 0 1px var(--focus); }
|
||||
.composer textarea {
|
||||
min-height: 24px;
|
||||
max-height: 160px;
|
||||
padding: 5px 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
resize: none;
|
||||
line-height: 1.45;
|
||||
}
|
||||
.composer textarea:focus-visible { outline: none; }
|
||||
|
||||
/* settings */
|
||||
.settings-view { flex: 1; min-height: 0; display: flex; flex-direction: column; }
|
||||
.settings-head { display: flex; align-items: center; gap: 12px; padding: 12px 18px; border-bottom: 1px solid var(--border); }
|
||||
.settings-head h1 { font-size: 17px; }
|
||||
.settings-body { flex: 1; overflow-y: auto; padding: 8px 28px 40px; }
|
||||
.settings-section { max-width: 620px; padding: 22px 0 26px; border-bottom: 1px solid var(--border); display: flex; flex-direction: column; gap: 14px; }
|
||||
.settings-section:last-child { border-bottom: 0; }
|
||||
.settings-section h2 { margin-bottom: 2px; }
|
||||
.settings-section h3 { margin-top: 8px; }
|
||||
.row-form { display: flex; align-items: flex-end; gap: 10px; }
|
||||
.uid-block, .backup { display: flex; flex-direction: column; gap: 8px; }
|
||||
.uid-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.uid-value {
|
||||
padding: 6px 10px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--sunken);
|
||||
font: 13px var(--mono);
|
||||
user-select: all;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.meter-row { display: flex; align-items: center; gap: 12px; }
|
||||
.meter { flex: 1; height: 8px; border-radius: 4px; background: var(--sunken); overflow: hidden; }
|
||||
.meter-fill { height: 100%; width: 0%; background: var(--talk); transition: width 60ms linear; }
|
||||
.ptt-row { display: flex; align-items: center; gap: 10px; }
|
||||
.ptt-row .field-label { margin-right: 4px; }
|
||||
.diag-list { display: grid; grid-template-columns: max-content 1fr; gap: 6px 18px; margin: 0; font-size: 13px; }
|
||||
.diag-list dt { color: var(--text-3); }
|
||||
.diag-list dd { margin: 0; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
|
||||
.codec-list { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 4px; font: 12.5px var(--mono); color: var(--text-2); }
|
||||
|
||||
/* toasts */
|
||||
.toasts {
|
||||
position: fixed;
|
||||
right: 16px;
|
||||
bottom: 16px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
max-width: min(420px, calc(100vw - 32px));
|
||||
z-index: 10;
|
||||
}
|
||||
.toast {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
padding: 10px 8px 10px 14px;
|
||||
border-radius: var(--radius);
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
box-shadow: var(--shadow);
|
||||
font-size: 13px;
|
||||
animation: toast-in 180ms cubic-bezier(0.16, 1, 0.3, 1);
|
||||
}
|
||||
.toast[data-kind="error"] { border-color: var(--danger); }
|
||||
.toast-text { flex: 1; padding-top: 2px; }
|
||||
.toast .icon-btn { width: 26px; height: 26px; }
|
||||
.toast .icon { width: 16px; height: 16px; }
|
||||
|
||||
@keyframes toast-in {
|
||||
from { transform: translateY(8px); opacity: 0; }
|
||||
to { transform: none; opacity: 1; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after { transition: none !important; animation: none !important; }
|
||||
}
|
||||
|
||||
@media (max-width: 1000px) {
|
||||
.transmit-hint { display: none; }
|
||||
}
|
||||
|
After Width: | Height: | Size: 14 KiB |
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||
<rect x="24" y="24" width="464" height="464" rx="104" fill="#2a2320"/>
|
||||
<path d="M256 168c-86-30-150 30-150 112 0 86 67 156 150 156s150-70 150-156c0-82-64-142-150-112z" fill="#f3a37c"/>
|
||||
<path d="M256 176c-30 47-37 160 0 254" fill="none" stroke="#b9653d" stroke-width="12" stroke-linecap="round"/>
|
||||
<path d="M261 160c4-50 39-80 96-82-6 52-40 81-96 82z" fill="#6aa864"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 445 B |
@@ -0,0 +1,9 @@
|
||||
[env]
|
||||
# audiopus_sys builds the bundled libopus with CMake. Its CMakeLists.txt declares a minimum
|
||||
# version below 3.5, which CMake >= 4.0 refuses unless this policy floor is given.
|
||||
CMAKE_POLICY_VERSION_MINIMUM = "3.5"
|
||||
# Always build and statically link the bundled libopus (also on Linux, where audiopus_sys would
|
||||
# otherwise link a system libopus found via pkg-config dynamically). Keeps release binaries
|
||||
# self-contained and the shipped libopus version known for the notices file.
|
||||
LIBOPUS_STATIC = "1"
|
||||
LIBOPUS_NO_PKG = "1"
|
||||
@@ -0,0 +1 @@
|
||||
/target
|
||||
@@ -0,0 +1,39 @@
|
||||
[package]
|
||||
name = "teamspeach-core"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
rust-version = "1.89"
|
||||
description = "TeamsPeach native TeamSpeak protocol core (stdio JSON bridge)"
|
||||
publish = false
|
||||
|
||||
[[bin]]
|
||||
name = "teamspeach-core"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
# Vendored ReSpeak tsclientlib (MIT OR Apache-2.0), pinned, with a small patch: see vendor/README.md.
|
||||
tsclientlib = { path = "vendor/tsclientlib", default-features = false, features = ["audio"] }
|
||||
tsproto-packets = { git = "https://github.com/ReSpeak/tsclientlib", rev = "ee3bc6f45a7137db7793ba5593a321df400d53e5" }
|
||||
tsproto-types = { git = "https://github.com/ReSpeak/tsclientlib", rev = "ee3bc6f45a7137db7793ba5593a321df400d53e5" }
|
||||
audiopus = "0.3.0-rc.0"
|
||||
base64 = "0.22"
|
||||
futures = "0.3"
|
||||
num-traits = "0.2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = { version = "1", features = ["raw_value", "preserve_order"] }
|
||||
thiserror = "2"
|
||||
tokio = { version = "1", features = ["rt", "macros", "io-std", "io-util", "sync", "time"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Security",
|
||||
"Win32_Security_Authorization",
|
||||
"Win32_System_Threading",
|
||||
] }
|
||||
|
||||
[profile.release]
|
||||
lto = "thin"
|
||||
codegen-units = 4
|
||||
@@ -0,0 +1,459 @@
|
||||
//! Voice: Opus encoding of 20 ms mono PCM frames from the renderer, and per-speaker jitter
|
||||
//! buffering/decoding (tsclientlib `AudioHandler`) mixed down to one mono stream.
|
||||
|
||||
use std::collections::{HashSet, VecDeque};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::Mutex;
|
||||
|
||||
use audiopus::coder::Encoder;
|
||||
use audiopus::{Application, Bitrate, Channels, SampleRate};
|
||||
use base64::prelude::*;
|
||||
use tokio::sync::Notify;
|
||||
use tracing::debug;
|
||||
use tsclientlib::audio::AudioHandler;
|
||||
use tsclientlib::{ClientId, Codec};
|
||||
use tsproto_packets::packets::{AudioData, CodecType, InAudioBuf, OutAudio, OutPacket};
|
||||
|
||||
use crate::protocol::{Frame, FRAME_BYTES, FRAME_SAMPLES};
|
||||
|
||||
/// Outgoing PCM queue bound (frames of 20 ms).
|
||||
pub const TX_QUEUE_FRAMES: usize = 10;
|
||||
/// Opus packets are at most 1275 bytes.
|
||||
const MAX_OPUS_PACKET: usize = 1275;
|
||||
|
||||
// ---------------------------------------------------------------- input queue
|
||||
|
||||
pub enum AudioIn {
|
||||
Frame(Box<Frame>),
|
||||
End,
|
||||
}
|
||||
|
||||
/// Bounded single-consumer queue between the stdin reader and the session; drops the oldest
|
||||
/// frame when full.
|
||||
pub struct AudioInQueue {
|
||||
items: Mutex<VecDeque<AudioIn>>,
|
||||
notify: Notify,
|
||||
dropped: AtomicU64,
|
||||
}
|
||||
|
||||
/// Upper bound of queued entries: at most [`TX_QUEUE_FRAMES`] frames, and End markers are never
|
||||
/// adjacent, so at most one End before, between and after them.
|
||||
const TX_QUEUE_ENTRIES: usize = 2 * TX_QUEUE_FRAMES + 1;
|
||||
|
||||
impl AudioInQueue {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
items: Mutex::new(VecDeque::with_capacity(TX_QUEUE_ENTRIES)),
|
||||
notify: Notify::new(),
|
||||
dropped: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn push(&self, item: AudioIn) {
|
||||
{
|
||||
let mut q = self.items.lock().expect("audio queue poisoned");
|
||||
match item {
|
||||
// Consecutive ends carry no extra information.
|
||||
AudioIn::End if matches!(q.back(), Some(AudioIn::End)) => {}
|
||||
AudioIn::End => q.push_back(item),
|
||||
AudioIn::Frame(_) => {
|
||||
let frames = q.iter().filter(|i| matches!(i, AudioIn::Frame(_))).count();
|
||||
if frames >= TX_QUEUE_FRAMES {
|
||||
if let Some(pos) = q.iter().position(|i| matches!(i, AudioIn::Frame(_))) {
|
||||
q.remove(pos);
|
||||
self.dropped.fetch_add(1, Ordering::Relaxed);
|
||||
// Dropping a burst's only frame can leave two ends side by side.
|
||||
if pos > 0
|
||||
&& matches!(q.get(pos - 1), Some(AudioIn::End))
|
||||
&& matches!(q.get(pos), Some(AudioIn::End))
|
||||
{
|
||||
q.remove(pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
q.push_back(item);
|
||||
}
|
||||
}
|
||||
debug_assert!(q.len() <= TX_QUEUE_ENTRIES);
|
||||
}
|
||||
self.notify.notify_one();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn len(&self) -> usize { self.items.lock().unwrap().len() }
|
||||
|
||||
pub fn pop(&self) -> Option<AudioIn> { self.items.lock().expect("audio queue poisoned").pop_front() }
|
||||
|
||||
pub async fn notified(&self) { self.notify.notified().await }
|
||||
|
||||
/// Number of frames dropped since the last call.
|
||||
pub fn take_dropped(&self) -> u64 { self.dropped.swap(0, Ordering::Relaxed) }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- transmit
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum TxCodec {
|
||||
OpusVoice,
|
||||
OpusMusic,
|
||||
}
|
||||
|
||||
impl TxCodec {
|
||||
pub fn for_channel(codec: Codec) -> Option<Self> {
|
||||
match codec {
|
||||
Codec::OpusVoice => Some(TxCodec::OpusVoice),
|
||||
Codec::OpusMusic => Some(TxCodec::OpusMusic),
|
||||
Codec::SpeexNarrowband | Codec::SpeexWideband | Codec::SpeexUltrawideband | Codec::CeltMono => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn codec_type(self) -> CodecType {
|
||||
match self {
|
||||
TxCodec::OpusVoice => CodecType::OpusVoice,
|
||||
TxCodec::OpusMusic => CodecType::OpusMusic,
|
||||
}
|
||||
}
|
||||
|
||||
/// TeamsPeach's mapping of the channel quality setting (0–10) to an Opus bitrate.
|
||||
/// TeamSpeak does not publish its own table; these values are our choice.
|
||||
fn bitrate(self, quality: u8) -> i32 {
|
||||
let q = i32::from(quality.min(10));
|
||||
match self {
|
||||
TxCodec::OpusVoice => 8_000 + q * 4_000,
|
||||
TxCodec::OpusMusic => 24_000 + q * 8_000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn codec_name(codec: Codec) -> &'static str {
|
||||
match codec {
|
||||
Codec::SpeexNarrowband => "speex_narrowband",
|
||||
Codec::SpeexWideband => "speex_wideband",
|
||||
Codec::SpeexUltrawideband => "speex_ultrawideband",
|
||||
Codec::CeltMono => "celt_mono",
|
||||
Codec::OpusVoice => "opus_voice",
|
||||
Codec::OpusMusic => "opus_music",
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TxEncoder {
|
||||
encoder: Encoder,
|
||||
codec: TxCodec,
|
||||
quality: u8,
|
||||
stereo: Box<[i16; FRAME_SAMPLES * 2]>,
|
||||
out: Box<[u8; MAX_OPUS_PACKET]>,
|
||||
}
|
||||
|
||||
impl TxEncoder {
|
||||
pub fn new(codec: TxCodec, quality: u8) -> Result<Self, audiopus::Error> {
|
||||
let (channels, app) = match codec {
|
||||
TxCodec::OpusVoice => (Channels::Mono, Application::Voip),
|
||||
TxCodec::OpusMusic => (Channels::Stereo, Application::Audio),
|
||||
};
|
||||
let mut encoder = Encoder::new(SampleRate::Hz48000, channels, app)?;
|
||||
encoder.set_bitrate(Bitrate::BitsPerSecond(codec.bitrate(quality)))?;
|
||||
Ok(Self {
|
||||
encoder,
|
||||
codec,
|
||||
quality,
|
||||
stereo: Box::new([0; FRAME_SAMPLES * 2]),
|
||||
out: Box::new([0; MAX_OPUS_PACKET]),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn matches(&self, codec: TxCodec, quality: u8) -> bool { self.codec == codec && self.quality == quality }
|
||||
|
||||
pub fn codec(&self) -> TxCodec { self.codec }
|
||||
|
||||
/// Encode one mono frame into a voice packet for the current channel.
|
||||
pub fn encode(&mut self, frame: &Frame) -> Result<OutPacket, audiopus::Error> {
|
||||
let len = match self.codec {
|
||||
TxCodec::OpusVoice => self.encoder.encode(&frame[..], &mut self.out[..])?,
|
||||
TxCodec::OpusMusic => {
|
||||
for (pair, s) in self.stereo.chunks_exact_mut(2).zip(frame.iter()) {
|
||||
pair[0] = *s;
|
||||
pair[1] = *s;
|
||||
}
|
||||
self.encoder.encode(&self.stereo[..], &mut self.out[..])?
|
||||
}
|
||||
};
|
||||
Ok(OutAudio::new(&AudioData::C2S { id: 0, codec: self.codec.codec_type(), data: &self.out[..len] }))
|
||||
}
|
||||
}
|
||||
|
||||
/// The empty voice packet that tells the server and listeners that a transmission ended.
|
||||
pub fn end_of_voice(codec: TxCodec) -> OutPacket {
|
||||
OutAudio::new(&AudioData::C2S { id: 0, codec: codec.codec_type(), data: &[] })
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- receive
|
||||
|
||||
pub enum RxEvent {
|
||||
None,
|
||||
Started(u16),
|
||||
/// First non-Opus packet from this speaker.
|
||||
Unsupported { client_id: u16, codec: CodecType },
|
||||
}
|
||||
|
||||
pub struct Receiver {
|
||||
handler: AudioHandler<ClientId>,
|
||||
/// Interleaved stereo float mix (the decoder always outputs stereo).
|
||||
mix: Vec<f32>,
|
||||
speakers: Vec<u16>,
|
||||
unsupported_reported: HashSet<u16>,
|
||||
}
|
||||
|
||||
pub struct Mixed<'a> {
|
||||
pub speakers: &'a [u16],
|
||||
pub stopped: Vec<u16>,
|
||||
}
|
||||
|
||||
impl Receiver {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
handler: AudioHandler::new(),
|
||||
mix: vec![0.0; FRAME_SAMPLES * 2],
|
||||
speakers: Vec::new(),
|
||||
unsupported_reported: HashSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop all speaker state (connection or channel context changed). Returns who was talking.
|
||||
pub fn reset(&mut self) -> Vec<u16> {
|
||||
let talking: Vec<u16> = self.handler.get_queues().keys().map(|c| c.0).collect();
|
||||
self.handler.reset();
|
||||
// Client ids are recycled by the server; report codec problems afresh.
|
||||
self.unsupported_reported.clear();
|
||||
talking
|
||||
}
|
||||
|
||||
pub fn handle_packet(&mut self, packet: InAudioBuf) -> RxEvent {
|
||||
let (from, codec) = match packet.data().data() {
|
||||
AudioData::S2C { from, codec, .. } | AudioData::S2CWhisper { from, codec, .. } => (*from, *codec),
|
||||
_ => return RxEvent::None,
|
||||
};
|
||||
if codec != CodecType::OpusVoice && codec != CodecType::OpusMusic {
|
||||
return if self.unsupported_reported.insert(from) {
|
||||
RxEvent::Unsupported { client_id: from, codec }
|
||||
} else {
|
||||
RxEvent::None
|
||||
};
|
||||
}
|
||||
match self.handler.handle_packet(ClientId(from), packet) {
|
||||
Ok(Some(id)) => RxEvent::Started(id.0),
|
||||
Ok(None) => RxEvent::None,
|
||||
Err(error) => {
|
||||
// Late, duplicate or overflowing packets are normal jitter-buffer outcomes.
|
||||
debug!(%error, client = from, "audio packet not queued");
|
||||
RxEvent::None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pull 20 ms from every speaker's jitter buffer, mix, and downmix stereo to mono into `out`.
|
||||
pub fn mix(&mut self, out: &mut [i16; FRAME_SAMPLES]) -> Mixed<'_> {
|
||||
self.mix.iter_mut().for_each(|s| *s = 0.0);
|
||||
self.speakers.clear();
|
||||
let speakers = &mut self.speakers;
|
||||
let stopped = self.handler.fill_buffer_with_proc(&mut self.mix, |id, data| {
|
||||
if !data.is_empty() {
|
||||
speakers.push(id.0);
|
||||
}
|
||||
});
|
||||
for (o, lr) in out.iter_mut().zip(self.mix.chunks_exact(2)) {
|
||||
let m = (lr[0] + lr[1]) * 0.5;
|
||||
*o = (m.clamp(-1.0, 1.0) * f32::from(i16::MAX)) as i16;
|
||||
}
|
||||
Mixed { speakers: &self.speakers, stopped: stopped.into_iter().map(|c| c.0).collect() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Serialize a mixed frame as an `audio` event line.
|
||||
pub fn audio_event_line(pcm: &[i16; FRAME_SAMPLES], speakers: &[u16]) -> String {
|
||||
let mut bytes = [0u8; FRAME_BYTES];
|
||||
for (dst, s) in bytes.chunks_exact_mut(2).zip(pcm.iter()) {
|
||||
dst.copy_from_slice(&s.to_le_bytes());
|
||||
}
|
||||
let mut line = String::with_capacity(2560 + 64 + speakers.len() * 6);
|
||||
line.push_str(r#"{"event":"audio","pcm":""#);
|
||||
BASE64_STANDARD.encode_string(bytes, &mut line);
|
||||
line.push_str(r#"","speakers":["#);
|
||||
for (i, s) in speakers.iter().enumerate() {
|
||||
if i > 0 {
|
||||
line.push(',');
|
||||
}
|
||||
line.push_str(&s.to_string());
|
||||
}
|
||||
line.push_str("]}");
|
||||
line
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tsproto_packets::packets::Direction;
|
||||
|
||||
fn sine(phase: &mut f64, freq: f64) -> Box<Frame> {
|
||||
let mut f = Box::new([0i16; FRAME_SAMPLES]);
|
||||
for s in f.iter_mut() {
|
||||
*s = (phase.sin() * 8000.0) as i16;
|
||||
*phase += 2.0 * std::f64::consts::PI * freq / 48_000.0;
|
||||
}
|
||||
f
|
||||
}
|
||||
|
||||
/// Turn our C2S packet into the S2C packet a server would forward (inserting `from`).
|
||||
fn as_s2c(packet: OutPacket, voice_id: u16, from: u16) -> InAudioBuf {
|
||||
let content = packet.content();
|
||||
let codec = content[2];
|
||||
let data = &content[3..];
|
||||
let codec = match codec {
|
||||
4 => CodecType::OpusVoice,
|
||||
5 => CodecType::OpusMusic,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let out = OutAudio::new(&AudioData::S2C { id: voice_id, from, codec, data });
|
||||
InAudioBuf::try_new(Direction::S2C, out.into_vec()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encode_decode_mix_roundtrip_both_codecs() {
|
||||
for codec in [TxCodec::OpusVoice, TxCodec::OpusMusic] {
|
||||
let mut enc = TxEncoder::new(codec, 6).unwrap();
|
||||
let mut rx = Receiver::new();
|
||||
let mut phase = 0.0;
|
||||
let mut out = [0i16; FRAME_SAMPLES];
|
||||
let mut energy = 0.0f64;
|
||||
let mut started = false;
|
||||
for i in 0..40u16 {
|
||||
let pkt = enc.encode(&sine(&mut phase, 440.0)).unwrap();
|
||||
if let RxEvent::Started(id) = rx.handle_packet(as_s2c(pkt, i, 7)) {
|
||||
assert_eq!(id, 7);
|
||||
started = true;
|
||||
}
|
||||
let mixed = rx.mix(&mut out);
|
||||
if !mixed.speakers.is_empty() {
|
||||
assert_eq!(mixed.speakers, &[7]);
|
||||
energy += out.iter().map(|s| f64::from(*s).powi(2)).sum::<f64>();
|
||||
}
|
||||
}
|
||||
assert!(started);
|
||||
assert!(energy > 1e9, "{codec:?}: decoded audio is silent ({energy})");
|
||||
// End of stream: the speaker is reported as stopped.
|
||||
rx.handle_packet(as_s2c(end_of_voice(codec), 40, 7));
|
||||
let mut stopped = false;
|
||||
for _ in 0..20 {
|
||||
if rx.mix(&mut out).stopped.contains(&7) {
|
||||
stopped = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(stopped, "{codec:?}: end of voice not detected");
|
||||
}
|
||||
}
|
||||
|
||||
fn frame(tag: i16) -> AudioIn {
|
||||
let mut f = Box::new([0i16; FRAME_SAMPLES]);
|
||||
f[0] = tag;
|
||||
AudioIn::Frame(f)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_audio_end_is_coalesced() {
|
||||
let q = AudioInQueue::new();
|
||||
for _ in 0..1000 {
|
||||
q.push(AudioIn::End);
|
||||
}
|
||||
assert_eq!(q.len(), 1);
|
||||
q.push(frame(1));
|
||||
for _ in 0..1000 {
|
||||
q.push(AudioIn::End);
|
||||
}
|
||||
assert_eq!(q.len(), 3);
|
||||
assert!(matches!(q.pop(), Some(AudioIn::End)));
|
||||
assert!(matches!(q.pop(), Some(AudioIn::Frame(f)) if f[0] == 1));
|
||||
assert!(matches!(q.pop(), Some(AudioIn::End)));
|
||||
assert!(q.pop().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alternating_bursts_overflow_stays_bounded_and_terminated() {
|
||||
let q = AudioInQueue::new();
|
||||
for i in 0..500i16 {
|
||||
q.push(frame(i));
|
||||
q.push(AudioIn::End);
|
||||
q.push(AudioIn::End);
|
||||
assert!(q.len() <= TX_QUEUE_ENTRIES, "len {}", q.len());
|
||||
}
|
||||
assert_eq!(q.take_dropped(), 500 - TX_QUEUE_FRAMES as u64);
|
||||
// Newest frames survive in order, every burst still ends, no two ends are adjacent.
|
||||
let mut frames = Vec::new();
|
||||
let mut prev_end = false;
|
||||
let mut last_is_end = false;
|
||||
while let Some(item) = q.pop() {
|
||||
match item {
|
||||
AudioIn::Frame(f) => {
|
||||
frames.push(f[0]);
|
||||
prev_end = false;
|
||||
last_is_end = false;
|
||||
}
|
||||
AudioIn::End => {
|
||||
assert!(!prev_end, "adjacent end markers");
|
||||
prev_end = true;
|
||||
last_is_end = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(last_is_end);
|
||||
assert_eq!(frames, (490..500).collect::<Vec<i16>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_rearms_unsupported_codec_report() {
|
||||
let mut rx = Receiver::new();
|
||||
let speex = || {
|
||||
let out = OutAudio::new(&AudioData::S2C { id: 1, from: 9, codec: CodecType::SpeexWideband, data: &[1, 2, 3] });
|
||||
InAudioBuf::try_new(Direction::S2C, out.into_vec()).unwrap()
|
||||
};
|
||||
assert!(matches!(rx.handle_packet(speex()), RxEvent::Unsupported { client_id: 9, .. }));
|
||||
assert!(matches!(rx.handle_packet(speex()), RxEvent::None));
|
||||
rx.reset();
|
||||
assert!(matches!(rx.handle_packet(speex()), RxEvent::Unsupported { client_id: 9, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queue_drops_oldest_frames() {
|
||||
let q = AudioInQueue::new();
|
||||
for i in 0..(TX_QUEUE_FRAMES + 3) {
|
||||
let mut f = Box::new([0i16; FRAME_SAMPLES]);
|
||||
f[0] = i as i16;
|
||||
q.push(AudioIn::Frame(f));
|
||||
}
|
||||
q.push(AudioIn::End);
|
||||
assert_eq!(q.take_dropped(), 3);
|
||||
match q.pop() {
|
||||
Some(AudioIn::Frame(f)) => assert_eq!(f[0], 3),
|
||||
_ => panic!(),
|
||||
}
|
||||
let mut n = 1;
|
||||
while let Some(item) = q.pop() {
|
||||
if matches!(item, AudioIn::End) {
|
||||
break;
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
assert_eq!(n, TX_QUEUE_FRAMES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_line_shape() {
|
||||
let mut pcm = [0i16; FRAME_SAMPLES];
|
||||
pcm[0] = -2;
|
||||
let line = audio_event_line(&pcm, &[5, 9]);
|
||||
let v: serde_json::Value = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!(v["speakers"], serde_json::json!([5, 9]));
|
||||
let bytes = BASE64_STANDARD.decode(v["pcm"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(bytes.len(), FRAME_BYTES);
|
||||
assert_eq!(i16::from_le_bytes([bytes[0], bytes[1]]), -2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
//! TeamsPeach core: TeamSpeak protocol backend speaking newline-delimited JSON on stdio.
|
||||
//! Contract: `docs/bridge.md`.
|
||||
|
||||
mod audio;
|
||||
mod media;
|
||||
mod profile;
|
||||
mod protocol;
|
||||
mod rawcmd;
|
||||
mod secure_fs;
|
||||
mod session;
|
||||
mod snapshot;
|
||||
mod stdio;
|
||||
|
||||
use std::fs::{File, OpenOptions, TryLockError};
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::json;
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::{error, info};
|
||||
|
||||
use crate::audio::AudioInQueue;
|
||||
use crate::profile::Store;
|
||||
use crate::protocol::{ErrorObj, PROTOCOL_VERSION};
|
||||
use crate::stdio::Out;
|
||||
|
||||
const EXIT_FATAL: u8 = 1;
|
||||
const EXIT_USAGE: u8 = 2;
|
||||
const EXIT_DATA_DIR: u8 = 3;
|
||||
const MAX_IMPORT_BYTES: u64 = 64 * 1024;
|
||||
const USAGE: &str = "usage:
|
||||
teamspeach-core --data-dir <ABSOLUTE_DIR>
|
||||
teamspeach-core identity export --data-dir <ABSOLUTE_DIR> --out <FILE>
|
||||
teamspeach-core identity import --data-dir <ABSOLUTE_DIR> --in <FILE> [--replace]";
|
||||
|
||||
enum Mode {
|
||||
Run { data_dir: PathBuf },
|
||||
Export { data_dir: PathBuf, out: PathBuf },
|
||||
Import { data_dir: PathBuf, input: PathBuf, replace: bool },
|
||||
}
|
||||
|
||||
fn parse_args(args: &[String]) -> Result<Mode, String> {
|
||||
let (sub, rest) = match args {
|
||||
[a, b, rest @ ..] if a == "identity" && (b == "export" || b == "import") => (Some(b.as_str()), rest),
|
||||
rest => (None, rest),
|
||||
};
|
||||
let mut data_dir = None;
|
||||
let mut out = None;
|
||||
let mut input = None;
|
||||
let mut replace = false;
|
||||
let mut it = rest.iter();
|
||||
while let Some(a) = it.next() {
|
||||
let mut value = |name: &str| it.next().cloned().ok_or_else(|| format!("{name} needs a value"));
|
||||
match a.as_str() {
|
||||
"--data-dir" => data_dir = Some(PathBuf::from(value("--data-dir")?)),
|
||||
"--out" if sub == Some("export") => out = Some(PathBuf::from(value("--out")?)),
|
||||
"--in" if sub == Some("import") => input = Some(PathBuf::from(value("--in")?)),
|
||||
"--replace" if sub == Some("import") => replace = true,
|
||||
other => return Err(format!("unexpected argument {other:?}")),
|
||||
}
|
||||
}
|
||||
let data_dir = data_dir.ok_or("--data-dir is required")?;
|
||||
if !data_dir.is_absolute() {
|
||||
return Err("--data-dir must be an absolute path".into());
|
||||
}
|
||||
Ok(match sub {
|
||||
None => Mode::Run { data_dir },
|
||||
Some("export") => Mode::Export { data_dir, out: out.ok_or("--out is required")? },
|
||||
Some(_) => Mode::Import { data_dir, input: input.ok_or("--in is required")?, replace },
|
||||
})
|
||||
}
|
||||
|
||||
/// Exclusive lock on `<data-dir>/core.lock`, held for the process lifetime.
|
||||
fn lock_data_dir(dir: &Path) -> Result<File, String> {
|
||||
secure_fs::ensure_private_dir(dir).map_err(|e| format!("cannot create data dir {}: {e}", dir.display()))?;
|
||||
let path = dir.join("core.lock");
|
||||
let file = OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
|
||||
match file.try_lock() {
|
||||
Ok(()) => Ok(file),
|
||||
Err(TryLockError::WouldBlock) => Err(format!("data dir {} is in use by another teamspeach-core", dir.display())),
|
||||
Err(TryLockError::Error(e)) => Err(format!("cannot lock {}: {e}", path.display())),
|
||||
}
|
||||
}
|
||||
|
||||
fn print_cli_result(result: Result<String, ErrorObj>) -> ExitCode {
|
||||
let (line, code) = match result {
|
||||
Ok(uid) => (json!({ "ok": true, "uid": uid }), ExitCode::SUCCESS),
|
||||
Err(e) => (json!({ "ok": false, "error": e }), ExitCode::from(EXIT_FATAL)),
|
||||
};
|
||||
let mut stdout = std::io::stdout().lock();
|
||||
let _ = writeln!(stdout, "{line}");
|
||||
let _ = stdout.flush();
|
||||
code
|
||||
}
|
||||
|
||||
fn export(data_dir: &Path, out: &Path) -> Result<String, ErrorObj> {
|
||||
// identity.json is immutable after creation, so export does not need the lock.
|
||||
let (ini, uid) = Store::new(data_dir).export_ts_ini().map_err(session::store_error)?;
|
||||
secure_fs::write_atomic(out, ini.as_bytes(), true)
|
||||
.map_err(|e| ErrorObj::new(protocol::ErrorCode::Io, format!("writing {}: {e}", out.display())))?;
|
||||
Ok(uid)
|
||||
}
|
||||
|
||||
fn import(data_dir: &Path, input: &Path, replace: bool) -> Result<String, ErrorObj> {
|
||||
let io = |e: std::io::Error| ErrorObj::new(protocol::ErrorCode::Io, format!("reading {}: {e}", input.display()));
|
||||
let mut text = String::new();
|
||||
File::open(input).map_err(io)?.take(MAX_IMPORT_BYTES + 1).read_to_string(&mut text).map_err(io)?;
|
||||
if text.len() as u64 > MAX_IMPORT_BYTES {
|
||||
return Err(ErrorObj::new(protocol::ErrorCode::BadRequest, "identity file is too large"));
|
||||
}
|
||||
Store::new(data_dir).import_ts_ini(&text, replace).map_err(session::store_error)
|
||||
}
|
||||
|
||||
fn run(data_dir: PathBuf) -> ExitCode {
|
||||
let _lock = match lock_data_dir(&data_dir) {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
error!("{e}");
|
||||
return ExitCode::from(EXIT_DATA_DIR);
|
||||
}
|
||||
};
|
||||
let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() {
|
||||
Ok(rt) => rt,
|
||||
Err(e) => {
|
||||
error!(%e, "cannot start runtime");
|
||||
return ExitCode::from(EXIT_FATAL);
|
||||
}
|
||||
};
|
||||
rt.block_on(async move {
|
||||
let (out, out_rx) = Out::new();
|
||||
let writer = tokio::spawn(stdio::run_writer(out_rx));
|
||||
let audio_in = Arc::new(AudioInQueue::new());
|
||||
let (cmd_tx, cmd_rx) = mpsc::channel(64);
|
||||
{
|
||||
let audio_in = audio_in.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("stdin".into())
|
||||
.spawn(move || stdio::run_reader(std::io::stdin().lock(), cmd_tx, audio_in))
|
||||
.expect("spawn stdin thread");
|
||||
}
|
||||
out.json(&json!({ "event": "ready", "protocol": PROTOCOL_VERSION, "core_version": env!("CARGO_PKG_VERSION") }))
|
||||
.await;
|
||||
info!(data_dir = %data_dir.display(), "teamspeach-core ready");
|
||||
session::Session::new(Store::new(&data_dir), out, audio_in).run(cmd_rx).await;
|
||||
// All `Out` senders are gone once the session is dropped; the writer drains and exits.
|
||||
let _ = writer.await;
|
||||
});
|
||||
// The stdin thread may still block in read(); it ends with the process.
|
||||
rt.shutdown_timeout(Duration::from_millis(200));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
tracing_subscriber::fmt()
|
||||
.with_writer(std::io::stderr)
|
||||
.with_ansi(false)
|
||||
.with_env_filter(
|
||||
tracing_subscriber::EnvFilter::try_from_env("TEAMSPEACH_LOG")
|
||||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
|
||||
)
|
||||
.init();
|
||||
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let mode = match parse_args(&args) {
|
||||
Ok(m) => m,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}\n{USAGE}");
|
||||
return ExitCode::from(EXIT_USAGE);
|
||||
}
|
||||
};
|
||||
match mode {
|
||||
Mode::Run { data_dir } => run(data_dir),
|
||||
Mode::Export { data_dir, out } => print_cli_result(export(&data_dir, &out)),
|
||||
Mode::Import { data_dir, input, replace } => match lock_data_dir(&data_dir) {
|
||||
Ok(_lock) => print_cli_result(import(&data_dir, &input, replace)),
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
ExitCode::from(EXIT_DATA_DIR)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
//! Icons, avatars and banners downloaded through TeamSpeak file transfer (read-only).
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use base64::prelude::*;
|
||||
use serde_json::{json, Value};
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use crate::protocol::{ErrorCode, ErrorObj};
|
||||
|
||||
/// Concurrent file transfers per connection.
|
||||
pub const MAX_IN_FLIGHT: usize = 3;
|
||||
/// Whole download (request to last byte) deadline.
|
||||
pub const DEADLINE: Duration = Duration::from_secs(20);
|
||||
/// Icon ids below this are the client-bundled standard icons (100, 200, 300, 500, 600);
|
||||
/// the server has no file for them (live: `ftinitdownload` → error 2054 FileInvalidPath).
|
||||
pub const FIRST_UPLOADED_ICON_ID: u32 = 1000;
|
||||
const MAX_CHANNEL_PATH: usize = 512;
|
||||
|
||||
/// Which server file a fetch refers to. Only these fixed schemes are ever requested.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum MediaKind {
|
||||
Icon(u32),
|
||||
/// Client id plus the avatar file name derived from its UID.
|
||||
Avatar { client_id: u16, file: String },
|
||||
/// A file in a channel's file area, referenced by a server-provided `ts3image://` banner URL.
|
||||
ChannelFile { channel_id: u64, path: String },
|
||||
}
|
||||
|
||||
impl MediaKind {
|
||||
/// Channel whose file area holds the file (0 = virtual server root).
|
||||
pub fn channel_id(&self) -> u64 {
|
||||
match self {
|
||||
MediaKind::Icon(_) | MediaKind::Avatar { .. } => 0,
|
||||
MediaKind::ChannelFile { channel_id, .. } => *channel_id,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn path(&self) -> String {
|
||||
match self {
|
||||
MediaKind::Icon(id) => format!("/icon_{id}"),
|
||||
MediaKind::Avatar { file, .. } => format!("/avatar_{file}"),
|
||||
MediaKind::ChannelFile { path, .. } => path.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn max_bytes(&self) -> u64 {
|
||||
match self {
|
||||
MediaKind::Icon(_) => 256 * 1024,
|
||||
MediaKind::Avatar { .. } => 1024 * 1024,
|
||||
MediaKind::ChannelFile { .. } => 4 * 1024 * 1024,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn percent_decode(s: &str) -> Result<String, String> {
|
||||
let b = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(b.len());
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
if b[i] == b'%' {
|
||||
let hex = b.get(i + 1..i + 3).ok_or("truncated %-escape")?;
|
||||
let hex = std::str::from_utf8(hex).map_err(|_| "bad %-escape")?;
|
||||
out.push(u8::from_str_radix(hex, 16).map_err(|_| "bad %-escape")?);
|
||||
i += 3;
|
||||
} else {
|
||||
out.push(b[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
String::from_utf8(out).map_err(|_| "not UTF-8".into())
|
||||
}
|
||||
|
||||
/// Parse a `ts3image://host?port=P&channel=C&path=/dir&filename=name` banner reference into a
|
||||
/// channel id and file path. The host cannot be verified (it is a name for the server); a
|
||||
/// present `port` must equal the connected server's port when that is known.
|
||||
pub fn parse_ts3image(url: &str, server_port: Option<u16>) -> Result<MediaKind, String> {
|
||||
let rest = url
|
||||
.get(..11)
|
||||
.filter(|s| s.eq_ignore_ascii_case("ts3image://"))
|
||||
.map(|_| &url[11..])
|
||||
.ok_or("not a ts3image:// URL")?;
|
||||
let query = rest.split_once('?').map(|(_, q)| q).ok_or("missing query")?;
|
||||
let (mut port, mut channel, mut path, mut filename) = (None, None, None, None);
|
||||
for pair in query.split('&') {
|
||||
let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
|
||||
let v = percent_decode(v)?;
|
||||
match k {
|
||||
"port" => port = Some(v.parse::<u16>().map_err(|_| "bad port")?),
|
||||
"channel" => channel = Some(v.parse::<u64>().map_err(|_| "bad channel")?),
|
||||
"path" => path = Some(v),
|
||||
"filename" => filename = Some(v),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let (Some(p), Some(sp)) = (port, server_port) {
|
||||
if p != sp {
|
||||
return Err(format!("banner refers to port {p}, connected server uses {sp}"));
|
||||
}
|
||||
}
|
||||
let channel_id = channel.ok_or("missing channel")?;
|
||||
let filename = filename.filter(|f| !f.is_empty()).ok_or("missing filename")?;
|
||||
let dir = path.unwrap_or_else(|| "/".into());
|
||||
if !dir.starts_with('/') {
|
||||
return Err("path must be absolute".into());
|
||||
}
|
||||
if filename.contains(['/', '\\']) || filename == "." || filename == ".." {
|
||||
return Err("bad filename".into());
|
||||
}
|
||||
let full = if dir.ends_with('/') { format!("{dir}{filename}") } else { format!("{dir}/{filename}") };
|
||||
if full.len() > MAX_CHANNEL_PATH
|
||||
|| full.contains('\\')
|
||||
|| full.chars().any(char::is_control)
|
||||
|| full.split('/').any(|seg| seg == "..")
|
||||
{
|
||||
return Err("bad path".into());
|
||||
}
|
||||
Ok(MediaKind::ChannelFile { channel_id, path: full })
|
||||
}
|
||||
|
||||
/// Recognize image formats by magic bytes. Anything else is refused.
|
||||
pub fn sniff_image(b: &[u8]) -> Option<&'static str> {
|
||||
if b.starts_with(b"\x89PNG\r\n\x1a\n") {
|
||||
return Some("image/png");
|
||||
}
|
||||
if b.starts_with(&[0xFF, 0xD8, 0xFF]) {
|
||||
return Some("image/jpeg");
|
||||
}
|
||||
if b.starts_with(b"GIF87a") || b.starts_with(b"GIF89a") {
|
||||
return Some("image/gif");
|
||||
}
|
||||
if b.len() >= 12 && &b[0..4] == b"RIFF" && &b[8..12] == b"WEBP" {
|
||||
return Some("image/webp");
|
||||
}
|
||||
if b.starts_with(&[0, 0, 1, 0]) && b.len() > 6 {
|
||||
return Some("image/x-icon");
|
||||
}
|
||||
let head = &b[..b.len().min(512)];
|
||||
let text = String::from_utf8_lossy(head);
|
||||
let t = text.trim_start_matches('\u{feff}').trim_start().to_ascii_lowercase();
|
||||
if (t.starts_with("<svg") || t.starts_with("<?xml")) && t.contains("<svg") {
|
||||
return Some("image/svg+xml");
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Read exactly `size` bytes of a granted download and build the response result.
|
||||
pub async fn read_download(mut stream: TcpStream, size: u64) -> Result<Value, ErrorObj> {
|
||||
let mut data = vec![0u8; size as usize];
|
||||
stream
|
||||
.read_exact(&mut data)
|
||||
.await
|
||||
.map_err(|e| ErrorObj::new(ErrorCode::Io, format!("file transfer read failed: {e}")))?;
|
||||
let mime = sniff_image(&data)
|
||||
.ok_or_else(|| ErrorObj::new(ErrorCode::MediaUnsupported, "file is not a recognized image format"))?;
|
||||
Ok(json!({ "mime": mime, "bytes": data.len(), "data": BASE64_STANDARD.encode(&data) }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sniffing() {
|
||||
assert_eq!(sniff_image(b"\x89PNG\r\n\x1a\nrest"), Some("image/png"));
|
||||
assert_eq!(sniff_image(&[0xFF, 0xD8, 0xFF, 0xE0]), Some("image/jpeg"));
|
||||
assert_eq!(sniff_image(b"GIF89a...."), Some("image/gif"));
|
||||
assert_eq!(sniff_image(b"RIFF\x10\0\0\0WEBPVP8 "), Some("image/webp"));
|
||||
assert_eq!(sniff_image(b"\xef\xbb\xbf <?xml version=\"1.0\"?><svg xmlns=..."), Some("image/svg+xml"));
|
||||
assert_eq!(sniff_image(b"<html><script>"), None);
|
||||
assert_eq!(sniff_image(b""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_are_fixed_schemes() {
|
||||
assert_eq!(MediaKind::Icon(301694691).path(), "/icon_301694691");
|
||||
assert_eq!(MediaKind::Avatar { client_id: 1, file: "abcd".into() }.path(), "/avatar_abcd");
|
||||
assert_eq!(MediaKind::Icon(1).channel_id(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ts3image_banner_urls() {
|
||||
// Shape observed live on the test server.
|
||||
let k = parse_ts3image("ts3image://ip.example?port=9987&channel=1&path=/bez-negativa&filename=channel-1", Some(9987))
|
||||
.unwrap();
|
||||
assert_eq!(k, MediaKind::ChannelFile { channel_id: 1, path: "/bez-negativa/channel-1".into() });
|
||||
let k = parse_ts3image("TS3IMAGE://h?channel=7&path=%2F&filename=doka%20cover.png", None).unwrap();
|
||||
assert_eq!(k, MediaKind::ChannelFile { channel_id: 7, path: "/doka cover.png".into() });
|
||||
for bad in [
|
||||
"https://example.org/x.png",
|
||||
"ts3image://h?port=1&channel=1&path=/a&filename=b",
|
||||
"ts3image://h?channel=1&path=/a/../b&filename=c",
|
||||
"ts3image://h?channel=1&path=/a&filename=..",
|
||||
"ts3image://h?channel=1&path=a&filename=b",
|
||||
"ts3image://h?channel=1&path=/a&filename=x%2Fy",
|
||||
"ts3image://h?path=/a&filename=b",
|
||||
"ts3image://h?channel=1&path=/a&filename=b%0a",
|
||||
] {
|
||||
assert!(parse_ts3image(bad, Some(9987)).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
//! Persistent identity (private key, never leaves this module except for TS export) and nickname.
|
||||
//!
|
||||
//! - `identity.json`: owner-only, written at creation; rewritten only when the server forces a
|
||||
//! higher security level (key offset changes, key and UID never change) or on explicit import.
|
||||
//! - `profile.json`: the nickname, replaced atomically by `rename`.
|
||||
//!
|
||||
//! Corrupt files are reported, never regenerated.
|
||||
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
use tsclientlib::Identity;
|
||||
use tsproto_types::crypto::EccKeyPrivP256;
|
||||
|
||||
use crate::secure_fs;
|
||||
|
||||
const IDENTITY_FILE: &str = "identity.json";
|
||||
const PROFILE_FILE: &str = "profile.json";
|
||||
const FORMAT_VERSION: u32 = 1;
|
||||
/// Identity security level generated for new identities (TeamSpeak default requirement).
|
||||
pub const NEW_IDENTITY_LEVEL: u8 = 8;
|
||||
const NICK_MIN_CHARS: usize = 3;
|
||||
const NICK_MAX_CHARS: usize = 30;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum StoreError {
|
||||
#[error("no identity exists")]
|
||||
Missing,
|
||||
#[error("an identity already exists")]
|
||||
Exists,
|
||||
#[error("identity file {path} is corrupt: {reason}")]
|
||||
IdentityCorrupt { path: String, reason: String },
|
||||
#[error("profile file {path} is corrupt: {reason}")]
|
||||
ProfileCorrupt { path: String, reason: String },
|
||||
#[error("invalid nickname: {0}")]
|
||||
InvalidNickname(String),
|
||||
#[error("invalid identity import: {0}")]
|
||||
ImportInvalid(String),
|
||||
#[error("{context}: {source}")]
|
||||
Io {
|
||||
context: String,
|
||||
#[source]
|
||||
source: io::Error,
|
||||
},
|
||||
}
|
||||
|
||||
fn io_err(context: impl Into<String>) -> impl FnOnce(io::Error) -> StoreError {
|
||||
let context = context.into();
|
||||
move |source| StoreError::Io { context, source }
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct IdentityFile {
|
||||
version: u32,
|
||||
/// Public unique identifier, stored to detect corruption.
|
||||
uid: String,
|
||||
/// Base64 of the libtomcrypt DER private key (`EccKeyPrivP256::to_ts`).
|
||||
private_key: String,
|
||||
/// Hash-cash counter (`client_key_offset`) giving the security level.
|
||||
key_offset: u64,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ProfileFile {
|
||||
version: u32,
|
||||
nickname: String,
|
||||
}
|
||||
|
||||
/// A loaded identity. The private key stays inside [`Identity`].
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct StoredIdentity {
|
||||
pub identity: Identity,
|
||||
pub uid: String,
|
||||
}
|
||||
|
||||
impl StoredIdentity {
|
||||
pub fn security_level(&self) -> u8 { self.identity.level() }
|
||||
}
|
||||
|
||||
pub fn uid_of(key: &EccKeyPrivP256) -> String { key.to_pub().get_uid() }
|
||||
|
||||
/// Validate and normalize (trim) a nickname.
|
||||
pub fn validate_nickname(raw: &str) -> Result<String, StoreError> {
|
||||
let nick = raw.trim();
|
||||
let n = nick.chars().count();
|
||||
if !(NICK_MIN_CHARS..=NICK_MAX_CHARS).contains(&n) {
|
||||
return Err(StoreError::InvalidNickname(format!(
|
||||
"must be {NICK_MIN_CHARS}-{NICK_MAX_CHARS} characters after trimming, got {n}"
|
||||
)));
|
||||
}
|
||||
if nick.chars().any(char::is_control) {
|
||||
return Err(StoreError::InvalidNickname("must not contain control characters".into()));
|
||||
}
|
||||
Ok(nick.to_owned())
|
||||
}
|
||||
|
||||
pub struct Store {
|
||||
dir: PathBuf,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub fn new(dir: impl Into<PathBuf>) -> Self { Self { dir: dir.into() } }
|
||||
|
||||
fn identity_path(&self) -> PathBuf { self.dir.join(IDENTITY_FILE) }
|
||||
fn profile_path(&self) -> PathBuf { self.dir.join(PROFILE_FILE) }
|
||||
|
||||
fn corrupt_identity(&self, reason: impl Into<String>) -> StoreError {
|
||||
StoreError::IdentityCorrupt {
|
||||
path: self.identity_path().display().to_string(),
|
||||
reason: reason.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `Ok(None)` if no identity file exists.
|
||||
pub fn load_identity(&self) -> Result<Option<StoredIdentity>, StoreError> {
|
||||
let path = self.identity_path();
|
||||
let text = match fs::read_to_string(&path) {
|
||||
Ok(t) => t,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) if e.kind() == io::ErrorKind::InvalidData => {
|
||||
return Err(self.corrupt_identity("not valid UTF-8"));
|
||||
}
|
||||
Err(e) => return Err(io_err(format!("reading {}", path.display()))(e)),
|
||||
};
|
||||
let file: IdentityFile = serde_json::from_str(&text)
|
||||
.map_err(|e| self.corrupt_identity(format!("invalid JSON: {e}")))?;
|
||||
if file.version != FORMAT_VERSION {
|
||||
return Err(self.corrupt_identity(format!("unsupported version {}", file.version)));
|
||||
}
|
||||
let key = EccKeyPrivP256::from_ts(&file.private_key)
|
||||
.map_err(|e| self.corrupt_identity(format!("invalid private key: {e}")))?;
|
||||
let uid = uid_of(&key);
|
||||
if uid != file.uid {
|
||||
return Err(self.corrupt_identity("stored UID does not match the private key"));
|
||||
}
|
||||
Ok(Some(StoredIdentity { identity: Identity::new(key, file.key_offset), uid }))
|
||||
}
|
||||
|
||||
/// `Ok(None)` if no nickname was saved yet.
|
||||
pub fn load_nickname(&self) -> Result<Option<String>, StoreError> {
|
||||
let path = self.profile_path();
|
||||
let corrupt = |reason: String| StoreError::ProfileCorrupt {
|
||||
path: path.display().to_string(),
|
||||
reason,
|
||||
};
|
||||
let text = match fs::read_to_string(&path) {
|
||||
Ok(t) => t,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) if e.kind() == io::ErrorKind::InvalidData => {
|
||||
return Err(corrupt("not valid UTF-8".into()));
|
||||
}
|
||||
Err(e) => return Err(io_err(format!("reading {}", path.display()))(e)),
|
||||
};
|
||||
let file: ProfileFile =
|
||||
serde_json::from_str(&text).map_err(|e| corrupt(format!("invalid JSON: {e}")))?;
|
||||
if file.version != FORMAT_VERSION {
|
||||
return Err(corrupt(format!("unsupported version {}", file.version)));
|
||||
}
|
||||
let nick = validate_nickname(&file.nickname).map_err(|e| corrupt(e.to_string()))?;
|
||||
Ok(Some(nick))
|
||||
}
|
||||
|
||||
fn write_identity(&self, identity: &Identity) -> Result<String, StoreError> {
|
||||
let uid = uid_of(identity.key());
|
||||
let file = IdentityFile {
|
||||
version: FORMAT_VERSION,
|
||||
uid: uid.clone(),
|
||||
private_key: identity.key().to_ts(),
|
||||
key_offset: identity.counter(),
|
||||
};
|
||||
let json = serde_json::to_vec_pretty(&file).expect("identity serializes");
|
||||
let path = self.identity_path();
|
||||
secure_fs::write_atomic(&path, &json, true)
|
||||
.map_err(io_err(format!("writing {}", path.display())))?;
|
||||
Ok(uid)
|
||||
}
|
||||
|
||||
/// Persist an already validated nickname.
|
||||
pub fn save_nickname(&self, nickname: &str) -> Result<(), StoreError> {
|
||||
let nickname = validate_nickname(nickname)?;
|
||||
let json = serde_json::to_vec_pretty(&ProfileFile { version: FORMAT_VERSION, nickname })
|
||||
.expect("profile serializes");
|
||||
let path = self.profile_path();
|
||||
secure_fs::write_atomic(&path, &json, false)
|
||||
.map_err(io_err(format!("writing {}", path.display())))
|
||||
}
|
||||
|
||||
/// Error unless no identity file exists at all (a corrupt one counts as existing).
|
||||
fn ensure_no_identity(&self) -> Result<(), StoreError> {
|
||||
match self.load_identity() {
|
||||
Ok(None) => Ok(()),
|
||||
Ok(Some(_)) => Err(StoreError::Exists),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate and persist a new identity plus nickname. Never overwrites an existing identity.
|
||||
pub fn create(&self, nickname: &str) -> Result<(StoredIdentity, String), StoreError> {
|
||||
let nickname = validate_nickname(nickname)?;
|
||||
self.ensure_no_identity()?;
|
||||
let mut identity = Identity::new(EccKeyPrivP256::create(), 0);
|
||||
identity.upgrade_level(NEW_IDENTITY_LEVEL);
|
||||
let uid = self.write_identity(&identity)?;
|
||||
self.save_nickname(&nickname)?;
|
||||
Ok((StoredIdentity { identity, uid }, nickname))
|
||||
}
|
||||
|
||||
/// Persist a higher key offset computed by tsclientlib for the same key.
|
||||
pub fn update_key_offset(
|
||||
&self, current: &StoredIdentity, upgraded: &Identity,
|
||||
) -> Result<StoredIdentity, StoreError> {
|
||||
let uid = uid_of(upgraded.key());
|
||||
if uid != current.uid || upgraded.key().to_ts() != current.identity.key().to_ts() {
|
||||
return Err(self.corrupt_identity("refusing to store an upgraded identity with a different key"));
|
||||
}
|
||||
self.write_identity(upgraded)?;
|
||||
Ok(StoredIdentity { identity: upgraded.clone(), uid })
|
||||
}
|
||||
|
||||
/// TeamSpeak-compatible identity export (`[Identity]` ini). Contains the private key.
|
||||
pub fn export_ts_ini(&self) -> Result<(String, String), StoreError> {
|
||||
let stored = self.load_identity()?.ok_or(StoreError::Missing)?;
|
||||
let nickname = self.load_nickname()?;
|
||||
let mut ini = String::from("[Identity]\nid=TeamsPeach\n");
|
||||
ini.push_str(&format!(
|
||||
"identity=\"{}V{}\"\n",
|
||||
stored.identity.counter(),
|
||||
stored.identity.key().to_ts_obfuscated()
|
||||
));
|
||||
if let Some(n) = nickname {
|
||||
ini.push_str(&format!("nickname={n}\n"));
|
||||
}
|
||||
Ok((ini, stored.uid))
|
||||
}
|
||||
|
||||
/// Import a TeamSpeak `[Identity]` ini. Returns the imported UID.
|
||||
pub fn import_ts_ini(&self, ini: &str, replace: bool) -> Result<String, StoreError> {
|
||||
let mut identity_value = None;
|
||||
let mut nickname = None;
|
||||
for line in ini.lines() {
|
||||
let line = line.trim();
|
||||
if let Some((k, v)) = line.split_once('=') {
|
||||
let v = v.trim();
|
||||
match k.trim() {
|
||||
"identity" => identity_value = Some(v.trim_matches('"').to_owned()),
|
||||
"nickname" => nickname = Some(v.to_owned()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let value = identity_value.ok_or_else(|| StoreError::ImportInvalid("no identity= entry".into()))?;
|
||||
let identity = Identity::new_from_ts_str(&value)
|
||||
.map_err(|e| StoreError::ImportInvalid(format!("cannot decode identity: {e}")))?;
|
||||
let nickname = match nickname {
|
||||
Some(n) => Some(validate_nickname(&n)?),
|
||||
None => None,
|
||||
};
|
||||
if !replace {
|
||||
self.ensure_no_identity()?;
|
||||
}
|
||||
let uid = self.write_identity(&identity)?;
|
||||
if let Some(n) = nickname {
|
||||
self.save_nickname(&n)?;
|
||||
}
|
||||
Ok(uid)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub mod tests {
|
||||
use super::*;
|
||||
|
||||
pub struct TempDir(pub PathBuf);
|
||||
impl TempDir {
|
||||
pub fn new(tag: &str) -> Self {
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
static N: AtomicU32 = AtomicU32::new(0);
|
||||
let p = std::env::temp_dir().join(format!(
|
||||
"teamspeach-test-{tag}-{}-{}",
|
||||
std::process::id(),
|
||||
N.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
let _ = fs::remove_dir_all(&p);
|
||||
secure_fs::ensure_private_dir(&p).unwrap();
|
||||
Self(p)
|
||||
}
|
||||
}
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) { let _ = fs::remove_dir_all(&self.0); }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_keeps_uid_and_key_and_persists_across_restart() {
|
||||
let dir = TempDir::new("rename");
|
||||
let store = Store::new(&dir.0);
|
||||
let (created, nick) = store.create(" TeamsPeach-Probe ").unwrap();
|
||||
assert_eq!(nick, "TeamsPeach-Probe");
|
||||
assert!(created.security_level() >= NEW_IDENTITY_LEVEL);
|
||||
let identity_bytes = fs::read(dir.0.join(IDENTITY_FILE)).unwrap();
|
||||
|
||||
for name in ["Second Name", "Третий ник", "Final-Name"] {
|
||||
store.save_nickname(name).unwrap();
|
||||
// "Restart": a fresh store instance reads everything from disk.
|
||||
let reopened = Store::new(&dir.0);
|
||||
let loaded = reopened.load_identity().unwrap().unwrap();
|
||||
assert_eq!(loaded.uid, created.uid);
|
||||
assert_eq!(loaded.identity.key().to_ts(), created.identity.key().to_ts());
|
||||
assert_eq!(loaded.identity.counter(), created.identity.counter());
|
||||
assert_eq!(reopened.load_nickname().unwrap().as_deref(), Some(name));
|
||||
assert_eq!(fs::read(dir.0.join(IDENTITY_FILE)).unwrap(), identity_bytes, "rename touched identity");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_refuses_to_overwrite() {
|
||||
let dir = TempDir::new("exists");
|
||||
let store = Store::new(&dir.0);
|
||||
let (first, _) = store.create("Alice").unwrap();
|
||||
assert!(matches!(store.create("Bob"), Err(StoreError::Exists)));
|
||||
assert_eq!(store.load_identity().unwrap().unwrap().uid, first.uid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_identity_is_reported_and_never_regenerated() {
|
||||
let dir = TempDir::new("corrupt");
|
||||
let store = Store::new(&dir.0);
|
||||
let path = dir.0.join(IDENTITY_FILE);
|
||||
for garbage in [&b"{not json"[..], b"\xff\xfe\x00", br#"{"version":1,"uid":"x","private_key":"AAAA","key_offset":1}"#] {
|
||||
fs::write(&path, garbage).unwrap();
|
||||
assert!(matches!(store.load_identity(), Err(StoreError::IdentityCorrupt { .. })));
|
||||
assert!(matches!(store.create("Alice"), Err(StoreError::IdentityCorrupt { .. })));
|
||||
assert_eq!(fs::read(&path).unwrap(), garbage, "corrupt identity was modified");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uid_mismatch_is_corrupt() {
|
||||
let dir = TempDir::new("mismatch");
|
||||
let store = Store::new(&dir.0);
|
||||
store.create("Alice").unwrap();
|
||||
let path = dir.0.join(IDENTITY_FILE);
|
||||
let mut file: IdentityFile = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
|
||||
let other = EccKeyPrivP256::create();
|
||||
file.uid = uid_of(&other);
|
||||
let tampered = serde_json::to_vec(&file).unwrap();
|
||||
fs::write(&path, &tampered).unwrap();
|
||||
assert!(matches!(store.load_identity(), Err(StoreError::IdentityCorrupt { .. })));
|
||||
assert!(matches!(store.create("Bob"), Err(StoreError::IdentityCorrupt { .. })));
|
||||
assert_eq!(fs::read(&path).unwrap(), tampered, "tampered identity was modified");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn independent_identities_differ() {
|
||||
let a = TempDir::new("a");
|
||||
let b = TempDir::new("b");
|
||||
let (ia, _) = Store::new(&a.0).create("Probe-A").unwrap();
|
||||
let (ib, _) = Store::new(&b.0).create("Probe-B").unwrap();
|
||||
assert_ne!(ia.uid, ib.uid);
|
||||
assert_ne!(ia.identity.key().to_ts(), ib.identity.key().to_ts());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nickname_rules() {
|
||||
assert!(validate_nickname("ab").is_err());
|
||||
assert!(validate_nickname(" ab ").is_err());
|
||||
assert!(validate_nickname(&"x".repeat(31)).is_err());
|
||||
assert!(validate_nickname("bad\nname").is_err());
|
||||
assert_eq!(validate_nickname(&"ж".repeat(30)).unwrap().chars().count(), 30);
|
||||
let dir = TempDir::new("nick");
|
||||
let store = Store::new(&dir.0);
|
||||
assert!(matches!(store.create("x"), Err(StoreError::InvalidNickname(_))));
|
||||
assert!(store.load_identity().unwrap().is_none(), "invalid nickname must not create identity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_profile_is_reported() {
|
||||
let dir = TempDir::new("profile");
|
||||
let store = Store::new(&dir.0);
|
||||
store.create("Alice").unwrap();
|
||||
fs::write(dir.0.join(PROFILE_FILE), b"{\"version\":1,\"nickname\":\"a\"}").unwrap();
|
||||
assert!(matches!(store.load_nickname(), Err(StoreError::ProfileCorrupt { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upgraded_key_offset_keeps_uid() {
|
||||
let dir = TempDir::new("upgrade");
|
||||
let store = Store::new(&dir.0);
|
||||
let (created, _) = store.create("Alice").unwrap();
|
||||
let mut upgraded = created.identity.clone();
|
||||
upgraded.upgrade_level(created.security_level() + 1);
|
||||
let stored = store.update_key_offset(&created, &upgraded).unwrap();
|
||||
let loaded = store.load_identity().unwrap().unwrap();
|
||||
assert_eq!(loaded.uid, created.uid);
|
||||
assert_eq!(loaded.identity.counter(), stored.identity.counter());
|
||||
assert!(loaded.security_level() > created.security_level());
|
||||
let foreign = Identity::new(EccKeyPrivP256::create(), 0);
|
||||
assert!(store.update_key_offset(&created, &foreign).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ts_ini_export_import_roundtrip() {
|
||||
let a = TempDir::new("export");
|
||||
let b = TempDir::new("import");
|
||||
let src = Store::new(&a.0);
|
||||
let (created, _) = src.create("Exporter").unwrap();
|
||||
let (ini, uid) = src.export_ts_ini().unwrap();
|
||||
assert_eq!(uid, created.uid);
|
||||
assert!(ini.starts_with("[Identity]\n"));
|
||||
let dst = Store::new(&b.0);
|
||||
assert_eq!(dst.import_ts_ini(&ini, false).unwrap(), created.uid);
|
||||
assert_eq!(dst.load_identity().unwrap().unwrap().identity.counter(), created.identity.counter());
|
||||
assert_eq!(dst.load_nickname().unwrap().as_deref(), Some("Exporter"));
|
||||
assert!(matches!(dst.import_ts_ini(&ini, false), Err(StoreError::Exists)));
|
||||
assert!(dst.import_ts_ini("[Identity]\nidentity=\"1Vgarbage\"\n", true).is_err());
|
||||
assert_eq!(dst.load_identity().unwrap().unwrap().uid, created.uid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_file_is_owner_only() {
|
||||
let dir = TempDir::new("perm");
|
||||
Store::new(&dir.0).create("Alice").unwrap();
|
||||
let path = dir.0.join(IDENTITY_FILE);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let sid = secure_fs::win::current_user_sid().unwrap();
|
||||
assert_eq!(secure_fs::win::dacl_sddl(&path).unwrap(), format!("D:P(A;;FA;;;{sid})"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
//! Bridge protocol v1 (see `docs/bridge.md`): request parsing and error objects.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use base64::prelude::*;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::value::RawValue;
|
||||
use serde_json::Value;
|
||||
|
||||
pub const PROTOCOL_VERSION: u32 = 1;
|
||||
/// Maximum accepted stdin line (bytes, without the newline).
|
||||
pub const MAX_LINE_BYTES: usize = 256 * 1024;
|
||||
/// Samples per 20 ms mono frame at 48 kHz.
|
||||
pub const FRAME_SAMPLES: usize = 960;
|
||||
/// Bytes of one PCM frame (i16 little endian).
|
||||
pub const FRAME_BYTES: usize = FRAME_SAMPLES * 2;
|
||||
/// Maximum serialized size of `stream_signal.json`.
|
||||
pub const MAX_SIGNAL_JSON_BYTES: usize = 60 * 1024;
|
||||
const MAX_ID_CHARS: usize = 64;
|
||||
const MAX_TEXT_BYTES: usize = 8192;
|
||||
const MAX_STREAM_ID_CHARS: usize = 256;
|
||||
const MAX_FIELD_CHARS: usize = 1024;
|
||||
|
||||
pub type Frame = [i16; FRAME_SAMPLES];
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ErrorCode {
|
||||
BadRequest,
|
||||
UnknownCommand,
|
||||
ProfileMissing,
|
||||
ProfileExists,
|
||||
IdentityCorrupt,
|
||||
ProfileCorrupt,
|
||||
InvalidNickname,
|
||||
NicknameRequired,
|
||||
NotConnected,
|
||||
AlreadyConnected,
|
||||
ConnectFailed,
|
||||
ServerError,
|
||||
AudioFormat,
|
||||
AudioOverflow,
|
||||
AudioMuted,
|
||||
AudioCodec,
|
||||
AudioCodecUnsupported,
|
||||
RenameNotPersisted,
|
||||
NotFound,
|
||||
MediaTooLarge,
|
||||
MediaUnsupported,
|
||||
ExternalMedia,
|
||||
Io,
|
||||
Internal,
|
||||
}
|
||||
|
||||
/// TeamSpeak server error attached to an [`ErrorObj`].
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
pub struct TsErrorInfo {
|
||||
/// Numeric TeamSpeak error id (e.g. 513 = nickname in use).
|
||||
pub id: u32,
|
||||
/// tsclientlib name of the error id (e.g. `ClientNicknameInuse`).
|
||||
pub name: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub missing_permission: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
pub struct ErrorObj {
|
||||
pub code: ErrorCode,
|
||||
pub message: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub ts_error: Option<TsErrorInfo>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub detail: Option<Value>,
|
||||
}
|
||||
|
||||
impl ErrorObj {
|
||||
pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
|
||||
Self { code, message: message.into(), ts_error: None, detail: None }
|
||||
}
|
||||
pub fn with_ts(mut self, ts: TsErrorInfo) -> Self {
|
||||
self.ts_error = Some(ts);
|
||||
self
|
||||
}
|
||||
pub fn with_detail(mut self, detail: Value) -> Self {
|
||||
self.detail = Some(detail);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
fn bad(msg: impl Into<String>) -> ErrorObj { ErrorObj::new(ErrorCode::BadRequest, msg) }
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TextTarget {
|
||||
Channel,
|
||||
Server,
|
||||
Client,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Command {
|
||||
ProfileGet,
|
||||
ProfileCreate { nickname: String },
|
||||
Rename { nickname: String },
|
||||
Connect(ConnectArgs),
|
||||
Disconnect { message: Option<String> },
|
||||
JoinChannel { channel_id: u64, password: Option<String> },
|
||||
SendText { target: TextTarget, client_id: Option<u16>, message: String },
|
||||
SetAudio { input_muted: Option<bool>, output_muted: Option<bool> },
|
||||
StreamList { client_id: Option<u16> },
|
||||
StreamJoin { stream_id: String, client_id: u16, message: Option<String> },
|
||||
/// `json` is already compact-serialized and size checked.
|
||||
StreamSignal { stream_id: String, client_id: u16, json: String },
|
||||
StreamLeave { stream_id: String, client_id: u16 },
|
||||
FetchIcon { icon_id: u32 },
|
||||
FetchAvatar { client_id: u16 },
|
||||
FetchBanner { channel_id: u64 },
|
||||
FetchServerBanner,
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
impl Command {
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
Command::ProfileGet => "profile_get",
|
||||
Command::ProfileCreate { .. } => "profile_create",
|
||||
Command::Rename { .. } => "rename",
|
||||
Command::Connect(_) => "connect",
|
||||
Command::Disconnect { .. } => "disconnect",
|
||||
Command::JoinChannel { .. } => "join_channel",
|
||||
Command::SendText { .. } => "send_text",
|
||||
Command::SetAudio { .. } => "set_audio",
|
||||
Command::StreamList { .. } => "stream_list",
|
||||
Command::StreamJoin { .. } => "stream_join",
|
||||
Command::StreamSignal { .. } => "stream_signal",
|
||||
Command::StreamLeave { .. } => "stream_leave",
|
||||
Command::FetchIcon { .. } => "fetch_icon",
|
||||
Command::FetchAvatar { .. } => "fetch_avatar",
|
||||
Command::FetchBanner { .. } => "fetch_banner",
|
||||
Command::FetchServerBanner => "fetch_server_banner",
|
||||
Command::Shutdown => "shutdown",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ConnectArgs {
|
||||
pub address: String,
|
||||
#[serde(default)]
|
||||
pub server_password: Option<String>,
|
||||
#[serde(default)]
|
||||
pub channel: Option<String>,
|
||||
#[serde(default)]
|
||||
pub channel_password: Option<String>,
|
||||
}
|
||||
|
||||
/// One parsed stdin line.
|
||||
#[derive(Debug)]
|
||||
pub enum Input {
|
||||
Request { id: String, cmd: Command },
|
||||
AudioFrame(Box<Frame>),
|
||||
AudioEnd,
|
||||
/// The line could not be turned into a command. `id` is set if it could be recovered.
|
||||
Invalid { id: Option<String>, error: ErrorObj },
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Envelope<'a> {
|
||||
#[serde(default, borrow)]
|
||||
id: Option<Cow<'a, str>>,
|
||||
#[serde(borrow)]
|
||||
cmd: Cow<'a, str>,
|
||||
#[serde(default, borrow)]
|
||||
args: Option<&'a RawValue>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Empty {}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct NicknameArgs {
|
||||
nickname: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct DisconnectArgs {
|
||||
#[serde(default)]
|
||||
message: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct JoinChannelArgs {
|
||||
channel_id: u64,
|
||||
#[serde(default)]
|
||||
password: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct SendTextArgs {
|
||||
target: TextTarget,
|
||||
#[serde(default)]
|
||||
client_id: Option<u16>,
|
||||
message: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct SetAudioArgs {
|
||||
#[serde(default)]
|
||||
input_muted: Option<bool>,
|
||||
#[serde(default)]
|
||||
output_muted: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct StreamListArgs {
|
||||
#[serde(default)]
|
||||
client_id: Option<u16>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct StreamJoinArgs {
|
||||
stream_id: String,
|
||||
client_id: u16,
|
||||
#[serde(default)]
|
||||
message: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct StreamSignalArgs<'a> {
|
||||
stream_id: String,
|
||||
client_id: u16,
|
||||
#[serde(borrow)]
|
||||
json: &'a RawValue,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct FetchIconArgs {
|
||||
icon_id: u32,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct FetchAvatarArgs {
|
||||
client_id: u16,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct FetchBannerArgs {
|
||||
channel_id: u64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct StreamLeaveArgs {
|
||||
stream_id: String,
|
||||
client_id: u16,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct AudioFrameArgs<'a> {
|
||||
#[serde(borrow)]
|
||||
pcm: Cow<'a, str>,
|
||||
}
|
||||
|
||||
fn args<'a, T: Deserialize<'a>>(raw: Option<&'a RawValue>) -> Result<T, ErrorObj> {
|
||||
let text = raw.map(RawValue::get).unwrap_or("{}");
|
||||
serde_json::from_str(text).map_err(|e| bad(format!("invalid args: {e}")))
|
||||
}
|
||||
|
||||
fn args_owned<T: DeserializeOwned>(raw: Option<&RawValue>) -> Result<T, ErrorObj> {
|
||||
let text = raw.map(RawValue::get).unwrap_or("{}");
|
||||
serde_json::from_str(text).map_err(|e| bad(format!("invalid args: {e}")))
|
||||
}
|
||||
|
||||
fn check_text(field: &str, value: &str, max_chars: usize, allow_empty: bool) -> Result<(), ErrorObj> {
|
||||
if !allow_empty && value.is_empty() {
|
||||
return Err(bad(format!("{field} must not be empty")));
|
||||
}
|
||||
if value.chars().count() > max_chars {
|
||||
return Err(bad(format!("{field} longer than {max_chars} characters")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_opt(field: &str, value: &Option<String>) -> Result<(), ErrorObj> {
|
||||
if let Some(v) = value {
|
||||
check_text(field, v, MAX_FIELD_CHARS, true)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_stream_id(id: &str) -> Result<(), ErrorObj> {
|
||||
check_text("stream_id", id, MAX_STREAM_ID_CHARS, false)?;
|
||||
if id.chars().any(char::is_control) {
|
||||
return Err(bad("stream_id contains control characters"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decodes base64 PCM straight into a frame without intermediate heap buffers.
|
||||
pub fn decode_frame(b64: &str) -> Result<Box<Frame>, ErrorObj> {
|
||||
let mut bytes = [0u8; FRAME_BYTES];
|
||||
// decode_slice fails if the output would not fit, so oversized input is rejected here.
|
||||
let n = BASE64_STANDARD
|
||||
.decode_slice(b64.as_bytes(), &mut bytes)
|
||||
.map_err(|e| ErrorObj::new(ErrorCode::AudioFormat, format!("pcm is not valid base64: {e}")))?;
|
||||
if n != FRAME_BYTES {
|
||||
return Err(ErrorObj::new(
|
||||
ErrorCode::AudioFormat,
|
||||
format!("pcm must be {FRAME_BYTES} bytes (960 i16le samples), got {n}"),
|
||||
));
|
||||
}
|
||||
let mut frame = Box::new([0i16; FRAME_SAMPLES]);
|
||||
for (dst, src) in frame.iter_mut().zip(bytes.chunks_exact(2)) {
|
||||
*dst = i16::from_le_bytes([src[0], src[1]]);
|
||||
}
|
||||
Ok(frame)
|
||||
}
|
||||
|
||||
/// Parse one stdin line (without trailing newline).
|
||||
pub fn parse_line(line: &str) -> Input {
|
||||
let env: Envelope = match serde_json::from_str(line) {
|
||||
Ok(e) => e,
|
||||
Err(e) => {
|
||||
// Try to recover the id for the response.
|
||||
let id = serde_json::from_str::<Value>(line)
|
||||
.ok()
|
||||
.and_then(|v| v.get("id").and_then(Value::as_str).map(str::to_owned))
|
||||
.filter(|id| valid_id(id));
|
||||
return Input::Invalid { id, error: bad(format!("malformed request: {e}")) };
|
||||
}
|
||||
};
|
||||
|
||||
// High-rate audio commands carry no id and get no response.
|
||||
match env.cmd.as_ref() {
|
||||
"audio_frame" => {
|
||||
return match args::<AudioFrameArgs>(env.args).and_then(|a| decode_frame(&a.pcm)) {
|
||||
Ok(frame) => Input::AudioFrame(frame),
|
||||
Err(error) => Input::Invalid { id: None, error },
|
||||
};
|
||||
}
|
||||
"audio_end" => {
|
||||
return match args::<Empty>(env.args) {
|
||||
Ok(_) => Input::AudioEnd,
|
||||
Err(error) => Input::Invalid { id: None, error },
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
let id = match env.id {
|
||||
Some(id) if valid_id(&id) => id.into_owned(),
|
||||
Some(_) => {
|
||||
return Input::Invalid { id: None, error: bad("id must be a string of 1-64 characters") };
|
||||
}
|
||||
None => return Input::Invalid { id: None, error: bad("missing id") },
|
||||
};
|
||||
match parse_command(&env.cmd, env.args) {
|
||||
Ok(cmd) => Input::Request { id, cmd },
|
||||
Err(error) => Input::Invalid { id: Some(id), error },
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_id(id: &str) -> bool {
|
||||
let n = id.chars().count();
|
||||
(1..=MAX_ID_CHARS).contains(&n) && !id.chars().any(char::is_control)
|
||||
}
|
||||
|
||||
fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result<Command, ErrorObj> {
|
||||
Ok(match cmd {
|
||||
"profile_get" => {
|
||||
args::<Empty>(raw)?;
|
||||
Command::ProfileGet
|
||||
}
|
||||
"profile_create" => Command::ProfileCreate { nickname: args_owned::<NicknameArgs>(raw)?.nickname },
|
||||
"rename" => Command::Rename { nickname: args_owned::<NicknameArgs>(raw)?.nickname },
|
||||
"connect" => {
|
||||
let a: ConnectArgs = args_owned(raw)?;
|
||||
check_text("address", &a.address, 255, false)?;
|
||||
check_opt("server_password", &a.server_password)?;
|
||||
check_opt("channel", &a.channel)?;
|
||||
check_opt("channel_password", &a.channel_password)?;
|
||||
Command::Connect(a)
|
||||
}
|
||||
"disconnect" => {
|
||||
let a: DisconnectArgs = args_owned(raw)?;
|
||||
check_opt("message", &a.message)?;
|
||||
Command::Disconnect { message: a.message }
|
||||
}
|
||||
"join_channel" => {
|
||||
let a: JoinChannelArgs = args_owned(raw)?;
|
||||
check_opt("password", &a.password)?;
|
||||
Command::JoinChannel { channel_id: a.channel_id, password: a.password }
|
||||
}
|
||||
"send_text" => {
|
||||
let a: SendTextArgs = args_owned(raw)?;
|
||||
if a.message.is_empty() || a.message.len() > MAX_TEXT_BYTES {
|
||||
return Err(bad(format!("message must be 1-{MAX_TEXT_BYTES} bytes")));
|
||||
}
|
||||
match (a.target, a.client_id) {
|
||||
(TextTarget::Client, None) => return Err(bad("client_id is required for target client")),
|
||||
(TextTarget::Channel | TextTarget::Server, Some(_)) => {
|
||||
return Err(bad("client_id is only allowed for target client"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Command::SendText { target: a.target, client_id: a.client_id, message: a.message }
|
||||
}
|
||||
"set_audio" => {
|
||||
let a: SetAudioArgs = args_owned(raw)?;
|
||||
Command::SetAudio { input_muted: a.input_muted, output_muted: a.output_muted }
|
||||
}
|
||||
"stream_list" => Command::StreamList { client_id: args_owned::<StreamListArgs>(raw)?.client_id },
|
||||
"stream_join" => {
|
||||
let a: StreamJoinArgs = args_owned(raw)?;
|
||||
check_stream_id(&a.stream_id)?;
|
||||
check_opt("message", &a.message)?;
|
||||
Command::StreamJoin { stream_id: a.stream_id, client_id: a.client_id, message: a.message }
|
||||
}
|
||||
"stream_signal" => {
|
||||
let a: StreamSignalArgs = args(raw)?;
|
||||
check_stream_id(&a.stream_id)?;
|
||||
let value: Value = serde_json::from_str(a.json.get())
|
||||
.map_err(|e| bad(format!("json is not valid JSON: {e}")))?;
|
||||
if !value.is_object() {
|
||||
return Err(bad("json must be an object"));
|
||||
}
|
||||
let json = serde_json::to_string(&value).map_err(|e| bad(format!("json: {e}")))?;
|
||||
if json.len() > MAX_SIGNAL_JSON_BYTES {
|
||||
return Err(bad(format!("json larger than {MAX_SIGNAL_JSON_BYTES} bytes")));
|
||||
}
|
||||
Command::StreamSignal { stream_id: a.stream_id, client_id: a.client_id, json }
|
||||
}
|
||||
"stream_leave" => {
|
||||
let a: StreamLeaveArgs = args_owned(raw)?;
|
||||
check_stream_id(&a.stream_id)?;
|
||||
Command::StreamLeave { stream_id: a.stream_id, client_id: a.client_id }
|
||||
}
|
||||
"fetch_icon" => {
|
||||
let a: FetchIconArgs = args_owned(raw)?;
|
||||
if a.icon_id == 0 {
|
||||
return Err(bad("icon_id 0 means no icon"));
|
||||
}
|
||||
Command::FetchIcon { icon_id: a.icon_id }
|
||||
}
|
||||
"fetch_avatar" => Command::FetchAvatar { client_id: args_owned::<FetchAvatarArgs>(raw)?.client_id },
|
||||
"fetch_banner" => Command::FetchBanner { channel_id: args_owned::<FetchBannerArgs>(raw)?.channel_id },
|
||||
"fetch_server_banner" => {
|
||||
args::<Empty>(raw)?;
|
||||
Command::FetchServerBanner
|
||||
}
|
||||
"shutdown" => {
|
||||
args::<Empty>(raw)?;
|
||||
Command::Shutdown
|
||||
}
|
||||
other => {
|
||||
return Err(ErrorObj::new(ErrorCode::UnknownCommand, format!("unknown command {other:?}")));
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn frame_b64(f: impl Fn(usize) -> i16) -> String {
|
||||
let mut bytes = Vec::with_capacity(FRAME_BYTES);
|
||||
for i in 0..FRAME_SAMPLES {
|
||||
bytes.extend_from_slice(&f(i).to_le_bytes());
|
||||
}
|
||||
BASE64_STANDARD.encode(bytes)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_frame_decodes_little_endian() {
|
||||
let line = format!(r#"{{"cmd":"audio_frame","args":{{"pcm":"{}"}}}}"#, frame_b64(|i| i as i16 - 480));
|
||||
match parse_line(&line) {
|
||||
Input::AudioFrame(f) => {
|
||||
assert_eq!(f[0], -480);
|
||||
assert_eq!(f[959], 479);
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_frame_wrong_size_is_rejected() {
|
||||
let short = BASE64_STANDARD.encode([0u8; 1918]);
|
||||
let long = BASE64_STANDARD.encode([0u8; 1922]);
|
||||
for pcm in [short, long, "@@@".to_string()] {
|
||||
let line = format!(r#"{{"cmd":"audio_frame","args":{{"pcm":"{pcm}"}}}}"#);
|
||||
match parse_line(&line) {
|
||||
Input::Invalid { error, .. } => assert_eq!(error.code, ErrorCode::AudioFormat),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requests_need_valid_id_and_known_args() {
|
||||
assert!(matches!(
|
||||
parse_line(r#"{"id":"a","cmd":"profile_get"}"#),
|
||||
Input::Request { cmd: Command::ProfileGet, .. }
|
||||
));
|
||||
match parse_line(r#"{"cmd":"profile_get"}"#) {
|
||||
Input::Invalid { id: None, error } => assert_eq!(error.code, ErrorCode::BadRequest),
|
||||
o => panic!("{o:?}"),
|
||||
}
|
||||
match parse_line(r#"{"id":"x","cmd":"rename","args":{"nickname":"abc","evil":1}}"#) {
|
||||
Input::Invalid { id: Some(id), error } => {
|
||||
assert_eq!(id, "x");
|
||||
assert_eq!(error.code, ErrorCode::BadRequest);
|
||||
}
|
||||
o => panic!("{o:?}"),
|
||||
}
|
||||
match parse_line(r#"{"id":"x","cmd":"read_file","args":{"path":"C:/x"}}"#) {
|
||||
Input::Invalid { error, .. } => assert_eq!(error.code, ErrorCode::UnknownCommand),
|
||||
o => panic!("{o:?}"),
|
||||
}
|
||||
match parse_line(r#"{"id":"x","cmd":"send_text","args":{"target":"client","message":"hi"}}"#) {
|
||||
Input::Invalid { error, .. } => assert_eq!(error.code, ErrorCode::BadRequest),
|
||||
o => panic!("{o:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_signal_json_is_compacted_object() {
|
||||
let line = r#"{"id":"s","cmd":"stream_signal","args":{"stream_id":"7","client_id":5,"json":{ "cmd" : "answer", "args": {"answer":"v=0\r\no=- 1 2 IN IP4 0.0.0.0"} }}}"#;
|
||||
match parse_line(line) {
|
||||
Input::Request { cmd: Command::StreamSignal { json, client_id, .. }, .. } => {
|
||||
assert_eq!(client_id, 5);
|
||||
assert_eq!(json, r#"{"cmd":"answer","args":{"answer":"v=0\r\no=- 1 2 IN IP4 0.0.0.0"}}"#);
|
||||
}
|
||||
o => panic!("{o:?}"),
|
||||
}
|
||||
let arr = r#"{"id":"s","cmd":"stream_signal","args":{"stream_id":"7","client_id":5,"json":[1]}}"#;
|
||||
assert!(matches!(parse_line(arr), Input::Invalid { .. }));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
//! TeamSpeak 6 screen-share signalling: allowlisted raw commands out, raw notifications in.
|
||||
//!
|
||||
//! tsclientlib has no declarations for these verbs. Outgoing commands are built with
|
||||
//! tsproto-packets' `OutCommand` (which applies TeamSpeak escaping); incoming ones arrive via the
|
||||
//! vendored `StreamItem::UnknownCommand` patch and are split with `CommandParser`.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use tsproto_packets::commands::{CommandItem, CommandParser};
|
||||
use tsproto_packets::packets::{Direction, Flags, OutCommand, PacketType};
|
||||
|
||||
/// Outgoing verbs the bridge may send (never caller-chosen names).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum StreamVerb {
|
||||
RequestStreamInfo,
|
||||
JoinStreamRequest,
|
||||
StreamSignaling,
|
||||
}
|
||||
|
||||
impl StreamVerb {
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
StreamVerb::RequestStreamInfo => "requeststreaminfo",
|
||||
StreamVerb::JoinStreamRequest => "joinstreamrequest",
|
||||
StreamVerb::StreamSignaling => "streamsignaling",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Build an escaped client→server command. Empty values are written as bare flags (`msg`),
|
||||
/// which is how TeamSpeak encodes an empty string.
|
||||
pub fn build(verb: StreamVerb, args: &[(&str, &str)]) -> OutCommand {
|
||||
let mut cmd = OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, verb.name());
|
||||
for (k, v) in args {
|
||||
cmd.write_arg(k, v);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
pub fn request_stream_info(client_id: u16) -> OutCommand {
|
||||
build(StreamVerb::RequestStreamInfo, &[("clid", &client_id.to_string())])
|
||||
}
|
||||
|
||||
pub fn join_stream(stream_id: &str, client_id: u16, msg: &str, remove: bool) -> OutCommand {
|
||||
build(StreamVerb::JoinStreamRequest, &[
|
||||
("id", stream_id),
|
||||
("clid", &client_id.to_string()),
|
||||
("msg", msg),
|
||||
("is_remove", if remove { "1" } else { "0" }),
|
||||
])
|
||||
}
|
||||
|
||||
pub fn stream_signaling(stream_id: &str, client_id: u16, json: &str) -> OutCommand {
|
||||
build(StreamVerb::StreamSignaling, &[("id", stream_id), ("clid", &client_id.to_string()), ("json", json)])
|
||||
}
|
||||
|
||||
/// Known commands copied raw (vendored `raw_command_tap`) because tsclientlib's book drops some
|
||||
/// of their arguments: channel banners and the TeamSpeak 6 `client_is_streaming` flag. The
|
||||
/// leave/delete notifications are tapped so those copied values follow the objects' lifecycle.
|
||||
pub fn tap(name: &[u8]) -> bool {
|
||||
matches!(
|
||||
name,
|
||||
b"channellist"
|
||||
| b"notifychannelcreated"
|
||||
| b"notifychanneledited"
|
||||
| b"notifychanneldeleted"
|
||||
| b"notifycliententerview"
|
||||
| b"notifyclientupdated"
|
||||
| b"notifyclientleftview"
|
||||
)
|
||||
}
|
||||
|
||||
/// Incoming notification names forwarded as `stream` events.
|
||||
pub fn is_stream_notification(name: &str) -> bool {
|
||||
name.starts_with("notifystream")
|
||||
|| matches!(name, "notifyjoinstreamrequest" | "notifyrespondjoinstreamrequest" | "notifysfuaccessinfo")
|
||||
}
|
||||
|
||||
/// A parsed raw command: name plus one unescaped key/value map per `|`-separated entry.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub struct RawNotification {
|
||||
pub name: String,
|
||||
pub items: Vec<BTreeMap<String, String>>,
|
||||
}
|
||||
|
||||
/// Parse raw command content. Returns `None` if there is no valid command name.
|
||||
pub fn parse(content: &[u8]) -> Option<RawNotification> {
|
||||
let (name, parser) = CommandParser::new(content);
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let name = std::str::from_utf8(name).ok()?.to_owned();
|
||||
let mut items = vec![BTreeMap::new()];
|
||||
for item in parser {
|
||||
match item {
|
||||
CommandItem::NextCommand => items.push(BTreeMap::new()),
|
||||
CommandItem::Argument(arg) => {
|
||||
let key = String::from_utf8_lossy(arg.name()).into_owned();
|
||||
let value = String::from_utf8_lossy(&arg.value().get()).into_owned();
|
||||
items.last_mut().expect("non-empty").insert(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(RawNotification { name, items })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn content(cmd: OutCommand) -> Vec<u8> { cmd.into_packet().content().to_vec() }
|
||||
|
||||
#[test]
|
||||
fn escaping_matches_teamspeak_rules() {
|
||||
let raw = content(build(StreamVerb::StreamSignaling, &[("json", "a b|c\\d/e\nf\tg\rh\x0bi\x0cj")]));
|
||||
assert_eq!(
|
||||
std::str::from_utf8(&raw).unwrap(),
|
||||
r"streamsignaling json=a\sb\pc\\d\/e\nf\tg\rh\vi\fj"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signaling_json_roundtrips_through_escaping() {
|
||||
let json = r#"{"cmd":"answer","args":{"answer":"v=0\r\no=- 4611 2 IN IP4 127.0.0.1\r\na=fmtp:96 profile-level-id=640c1f|x \\ / é"}}"#;
|
||||
let raw = content(stream_signaling("stream 1/2", 42, json));
|
||||
let parsed = parse(&raw).unwrap();
|
||||
assert_eq!(parsed.name, "streamsignaling");
|
||||
assert_eq!(parsed.items.len(), 1);
|
||||
assert_eq!(parsed.items[0]["id"], "stream 1/2");
|
||||
assert_eq!(parsed.items[0]["clid"], "42");
|
||||
assert_eq!(parsed.items[0]["json"], json);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn join_request_uses_flag_for_empty_message() {
|
||||
let raw = content(join_stream("9", 3, "", true));
|
||||
assert_eq!(std::str::from_utf8(&raw).unwrap(), "joinstreamrequest id=9 clid=3 msg is_remove=1");
|
||||
let parsed = parse(&raw).unwrap();
|
||||
assert_eq!(parsed.items[0]["msg"], "");
|
||||
assert_eq!(parsed.items[0]["is_remove"], "1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_entry_notifications_are_split() {
|
||||
let parsed = parse(br"notifystreaminfo id=1 clid=5 name=My\sStream|id=2 clid=6 name=b\pc").unwrap();
|
||||
assert_eq!(parsed.name, "notifystreaminfo");
|
||||
assert_eq!(parsed.items.len(), 2);
|
||||
assert_eq!(parsed.items[0]["name"], "My Stream");
|
||||
assert_eq!(parsed.items[1]["name"], "b|c");
|
||||
assert_eq!(parsed.items[1]["clid"], "6");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allowlist() {
|
||||
for ok in [
|
||||
"notifystreaminfo",
|
||||
"notifystreamsignaling",
|
||||
"notifystreamstarted",
|
||||
"notifyjoinstreamrequest",
|
||||
"notifyrespondjoinstreamrequest",
|
||||
"notifysfuaccessinfo",
|
||||
] {
|
||||
assert!(is_stream_notification(ok), "{ok}");
|
||||
}
|
||||
for no in ["notifytextmessage", "notifyclientmoved", "streamsignaling", "notifyfoo"] {
|
||||
assert!(!is_stream_notification(no), "{no}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
//! Atomic file replacement and owner-only permissions for secret files.
|
||||
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn tmp_path(path: &Path) -> PathBuf {
|
||||
let mut name = path.file_name().map(|n| n.to_os_string()).unwrap_or_default();
|
||||
name.push(".tmp");
|
||||
path.with_file_name(name)
|
||||
}
|
||||
|
||||
fn create_file(path: &Path, private: bool) -> io::Result<File> {
|
||||
let mut opts = OpenOptions::new();
|
||||
opts.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
if private {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
opts.mode(0o600);
|
||||
}
|
||||
let file = opts.open(path)?;
|
||||
#[cfg(windows)]
|
||||
if private {
|
||||
win::set_owner_only(path)?;
|
||||
}
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
if private {
|
||||
return Err(io::Error::new(io::ErrorKind::Unsupported, "private files unsupported on this OS"));
|
||||
}
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// Write `data` to `path` atomically: temp file (owner-only if `private`) + fsync + rename.
|
||||
///
|
||||
/// The caller must hold the data-dir lock, so a leftover temp file can only stem from a crash.
|
||||
pub fn write_atomic(path: &Path, data: &[u8], private: bool) -> io::Result<()> {
|
||||
let tmp = tmp_path(path);
|
||||
match fs::remove_file(&tmp) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
let result = (|| {
|
||||
let mut file = create_file(&tmp, private)?;
|
||||
file.write_all(data)?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
fs::rename(&tmp, path)?;
|
||||
#[cfg(unix)]
|
||||
if let Some(dir) = path.parent() {
|
||||
File::open(dir)?.sync_all()?;
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Create the data directory (owner-only on Unix).
|
||||
pub fn ensure_private_dir(dir: &Path) -> io::Result<()> {
|
||||
fs::create_dir_all(dir)?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::set_permissions(dir, fs::Permissions::from_mode(0o700))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub mod win {
|
||||
//! Owner-only DACL: `D:P(A;;FA;;;<current user SID>)` — protected (no inheritance), one ACE.
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::io;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::Path;
|
||||
use std::ptr::null_mut;
|
||||
|
||||
use windows_sys::Win32::Foundation::{CloseHandle, LocalFree, HANDLE};
|
||||
#[cfg(test)]
|
||||
use windows_sys::Win32::Security::Authorization::ConvertSecurityDescriptorToStringSecurityDescriptorW;
|
||||
use windows_sys::Win32::Security::Authorization::{
|
||||
ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use windows_sys::Win32::Security::GetFileSecurityW;
|
||||
use windows_sys::Win32::Security::{
|
||||
GetTokenInformation, SetFileSecurityW, TokenUser, DACL_SECURITY_INFORMATION,
|
||||
PROTECTED_DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, TOKEN_QUERY, TOKEN_USER,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
|
||||
|
||||
fn wide(s: &OsStr) -> Vec<u16> { s.encode_wide().chain(std::iter::once(0)).collect() }
|
||||
|
||||
unsafe fn from_wide_ptr(p: *const u16) -> String {
|
||||
let mut len = 0;
|
||||
while *p.add(len) != 0 {
|
||||
len += 1;
|
||||
}
|
||||
String::from_utf16_lossy(std::slice::from_raw_parts(p, len))
|
||||
}
|
||||
|
||||
/// String SID (`S-1-5-21-…`) of the user running this process.
|
||||
pub fn current_user_sid() -> io::Result<String> {
|
||||
unsafe {
|
||||
let mut token: HANDLE = null_mut();
|
||||
if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let mut needed = 0u32;
|
||||
GetTokenInformation(token, TokenUser, null_mut(), 0, &mut needed);
|
||||
// u64 storage keeps TOKEN_USER suitably aligned.
|
||||
let mut buf = vec![0u64; (needed as usize).div_ceil(8)];
|
||||
let ok = GetTokenInformation(token, TokenUser, buf.as_mut_ptr().cast(), needed, &mut needed);
|
||||
let err = io::Error::last_os_error();
|
||||
CloseHandle(token);
|
||||
if ok == 0 {
|
||||
return Err(err);
|
||||
}
|
||||
let user = &*(buf.as_ptr() as *const TOKEN_USER);
|
||||
let mut sid_str: *mut u16 = null_mut();
|
||||
if ConvertSidToStringSidW(user.User.Sid, &mut sid_str) == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let sid = from_wide_ptr(sid_str);
|
||||
LocalFree(sid_str.cast());
|
||||
Ok(sid)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_owner_only(path: &Path) -> io::Result<()> {
|
||||
let sddl = wide(OsStr::new(&format!("D:P(A;;FA;;;{})", current_user_sid()?)));
|
||||
let path_w = wide(path.as_os_str());
|
||||
unsafe {
|
||||
let mut sd: PSECURITY_DESCRIPTOR = null_mut();
|
||||
if ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
||||
sddl.as_ptr(),
|
||||
SDDL_REVISION_1,
|
||||
&mut sd,
|
||||
null_mut(),
|
||||
) == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let ok = SetFileSecurityW(
|
||||
path_w.as_ptr(),
|
||||
DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
|
||||
sd,
|
||||
);
|
||||
let err = io::Error::last_os_error();
|
||||
LocalFree(sd);
|
||||
if ok == 0 {
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The DACL of `path` in SDDL form (used to verify permissions in tests).
|
||||
#[cfg(test)]
|
||||
pub fn dacl_sddl(path: &Path) -> io::Result<String> {
|
||||
let path_w = wide(path.as_os_str());
|
||||
unsafe {
|
||||
let mut needed = 0u32;
|
||||
GetFileSecurityW(path_w.as_ptr(), DACL_SECURITY_INFORMATION, null_mut(), 0, &mut needed);
|
||||
if needed == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let mut buf = vec![0u64; (needed as usize).div_ceil(8)];
|
||||
if GetFileSecurityW(
|
||||
path_w.as_ptr(),
|
||||
DACL_SECURITY_INFORMATION,
|
||||
buf.as_mut_ptr().cast(),
|
||||
needed,
|
||||
&mut needed,
|
||||
) == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let mut out: *mut u16 = null_mut();
|
||||
if ConvertSecurityDescriptorToStringSecurityDescriptorW(
|
||||
buf.as_mut_ptr().cast(),
|
||||
SDDL_REVISION_1,
|
||||
DACL_SECURITY_INFORMATION,
|
||||
&mut out,
|
||||
null_mut(),
|
||||
) == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let s = from_wide_ptr(out);
|
||||
LocalFree(out.cast());
|
||||
Ok(s)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
//! Full server-view snapshot (`snapshot` event) built from tsclientlib's book plus the few raw
|
||||
//! arguments the book does not keep (see [`RawExtras`]).
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use tsclientlib::data::{Channel, ChannelGroup, Client, Connection, ServerGroup};
|
||||
use tsclientlib::{ChannelId, ClientType, GroupNamingMode, GroupType, HostBannerMode, IconId, MaxClients};
|
||||
|
||||
use crate::audio::codec_name;
|
||||
use crate::rawcmd::RawNotification;
|
||||
|
||||
/// Arguments copied from raw commands because tsclientlib's book drops them.
|
||||
///
|
||||
/// Lifecycle: a channel/client entry is replaced when the object (re)appears
|
||||
/// (`channellist`, `notifychannelcreated`, `notifycliententerview`), merged on edits/updates,
|
||||
/// removed on `notifychanneldeleted`/`notifyclientleftview`, and [`RawExtras::prune`] drops
|
||||
/// anything the book no longer has (e.g. sub-channels of a deleted channel) — so a recycled
|
||||
/// client or channel id never inherits stale values.
|
||||
#[derive(Default)]
|
||||
pub struct RawExtras {
|
||||
channels: HashMap<u64, ChannelExtra>,
|
||||
clients: HashMap<u16, ClientExtra>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ChannelExtra {
|
||||
banner_url: Option<String>,
|
||||
banner_mode: Option<String>,
|
||||
}
|
||||
|
||||
impl ChannelExtra {
|
||||
fn merge(&mut self, item: &BTreeMap<String, String>) {
|
||||
if let Some(u) = item.get("channel_banner_gfx_url") {
|
||||
self.banner_url = non_empty(u);
|
||||
}
|
||||
if let Some(m) = item.get("channel_banner_mode") {
|
||||
self.banner_mode = non_empty(m);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ClientExtra {
|
||||
is_streaming: Option<bool>,
|
||||
}
|
||||
|
||||
impl ClientExtra {
|
||||
fn merge(&mut self, item: &BTreeMap<String, String>) {
|
||||
if let Some(v) = item.get("client_is_streaming") {
|
||||
self.is_streaming = Some(v == "1");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn non_empty(s: &str) -> Option<String> { (!s.is_empty()).then(|| s.to_owned()) }
|
||||
|
||||
impl RawExtras {
|
||||
/// Raw banner URL of a channel as sent by the server.
|
||||
pub fn channel_banner(&self, channel_id: u64) -> Option<&str> {
|
||||
self.channels.get(&channel_id).and_then(|e| e.banner_url.as_deref())
|
||||
}
|
||||
|
||||
/// Apply a tapped command. Returns true if it concerned tracked objects.
|
||||
pub fn apply(&mut self, raw: &RawNotification) -> bool {
|
||||
let cids = || raw.items.iter().filter_map(|i| Some((i.get("cid")?.parse::<u64>().ok()?, i)));
|
||||
let clids = || raw.items.iter().filter_map(|i| Some((i.get("clid")?.parse::<u16>().ok()?, i)));
|
||||
let mut changed = false;
|
||||
match raw.name.as_str() {
|
||||
"channellist" | "notifychannelcreated" => {
|
||||
for (cid, item) in cids() {
|
||||
let mut e = ChannelExtra::default();
|
||||
e.merge(item);
|
||||
self.channels.insert(cid, e);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
"notifychanneledited" => {
|
||||
for (cid, item) in cids() {
|
||||
self.channels.entry(cid).or_default().merge(item);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
"notifychanneldeleted" => {
|
||||
for (cid, _) in cids() {
|
||||
changed |= self.channels.remove(&cid).is_some();
|
||||
}
|
||||
}
|
||||
"notifycliententerview" => {
|
||||
for (clid, item) in clids() {
|
||||
// TEMP-INVESTIGATION (remove): which avatar/identity fields does TS6 send?
|
||||
tracing::info!(
|
||||
clid,
|
||||
keys = ?item.keys().collect::<Vec<_>>(),
|
||||
flag_avatar_len = item.get("client_flag_avatar").map(|s| s.len()),
|
||||
myts_avatar = ?item.get("client_myteamspeak_avatar"),
|
||||
myts_id_len = item.get("client_myteamspeak_id").map(|s| s.len()),
|
||||
"TEMP enterview"
|
||||
);
|
||||
let mut e = ClientExtra::default();
|
||||
e.merge(item);
|
||||
self.clients.insert(clid, e);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
"notifyclientupdated" => {
|
||||
for (clid, item) in clids() {
|
||||
self.clients.entry(clid).or_default().merge(item);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
"notifyclientleftview" => {
|
||||
for (clid, _) in clids() {
|
||||
changed |= self.clients.remove(&clid).is_some();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Drop entries for channels/clients the book no longer contains.
|
||||
pub fn prune(&mut self, book: &Connection) {
|
||||
self.channels.retain(|cid, _| book.channels.contains_key(&ChannelId(*cid)));
|
||||
self.clients.retain(|clid, _| book.clients.contains_key(&tsclientlib::ClientId(*clid)));
|
||||
}
|
||||
}
|
||||
|
||||
fn uid_string(uid: &Option<tsclientlib::UidBuf>) -> Value {
|
||||
match uid {
|
||||
Some(u) => Value::String(format!("{}", &**u)),
|
||||
None => Value::Null,
|
||||
}
|
||||
}
|
||||
|
||||
fn icon(id: IconId) -> Value { if id.0 == 0 { Value::Null } else { Value::from(id.0) } }
|
||||
|
||||
fn name_mode(m: GroupNamingMode) -> &'static str {
|
||||
match m {
|
||||
GroupNamingMode::None => "none",
|
||||
GroupNamingMode::Before => "before",
|
||||
GroupNamingMode::After => "after",
|
||||
}
|
||||
}
|
||||
|
||||
fn group_type(t: GroupType) -> &'static str {
|
||||
match t {
|
||||
GroupType::Template => "template",
|
||||
GroupType::Regular => "regular",
|
||||
GroupType::Query => "query",
|
||||
}
|
||||
}
|
||||
|
||||
fn hostbanner_mode(m: HostBannerMode) -> &'static str {
|
||||
match m {
|
||||
HostBannerMode::NoAdjust => "no_adjust",
|
||||
HostBannerMode::AdjustIgnoreAspect => "adjust_ignore_aspect",
|
||||
HostBannerMode::AdjustKeepAspect => "adjust_keep_aspect",
|
||||
}
|
||||
}
|
||||
|
||||
fn server_group_json(g: &ServerGroup) -> Value {
|
||||
json!({
|
||||
"id": g.id.0, "name": g.name, "icon_id": icon(g.icon), "sort_id": g.sort_id,
|
||||
"name_mode": name_mode(g.naming_mode), "type": group_type(g.group_type),
|
||||
})
|
||||
}
|
||||
|
||||
fn channel_group_json(g: &ChannelGroup) -> Value {
|
||||
json!({
|
||||
"id": g.id.0, "name": g.name, "icon_id": icon(g.icon), "sort_id": g.sort_id,
|
||||
"name_mode": name_mode(g.naming_mode), "type": group_type(g.group_type),
|
||||
})
|
||||
}
|
||||
|
||||
fn channel_json(c: &Channel, depth: usize, extras: &RawExtras) -> Value {
|
||||
let extra = extras.channels.get(&c.id.0);
|
||||
json!({
|
||||
"id": c.id.0,
|
||||
"parent_id": c.parent.0,
|
||||
"order": c.order.0,
|
||||
"name": c.name,
|
||||
"topic": c.topic.clone().unwrap_or_default(),
|
||||
"has_password": c.has_password.unwrap_or(false),
|
||||
"is_default": c.is_default.unwrap_or(false),
|
||||
"max_clients": match c.max_clients {
|
||||
Some(MaxClients::Limited(n)) => Value::from(n),
|
||||
_ => Value::Null,
|
||||
},
|
||||
"needed_talk_power": c.needed_talk_power.unwrap_or(0),
|
||||
"codec": codec_name(c.codec),
|
||||
"codec_quality": c.codec_quality,
|
||||
"icon_id": c.icon.map_or(Value::Null, icon),
|
||||
"banner_url": extra.and_then(|e| e.banner_url.clone()),
|
||||
"banner_mode": extra.and_then(|e| e.banner_mode.as_deref()).and_then(|m| m.parse::<i64>().ok()),
|
||||
"depth": depth,
|
||||
})
|
||||
}
|
||||
|
||||
fn client_json(c: &Client, own: u16, extras: &RawExtras) -> Value {
|
||||
let mut groups: Vec<u64> = c.server_groups.iter().map(|g| g.0).collect();
|
||||
groups.sort_unstable();
|
||||
json!({
|
||||
"id": c.id.0,
|
||||
"uid": uid_string(&c.uid),
|
||||
"nickname": c.name,
|
||||
"channel_id": c.channel.0,
|
||||
"is_self": c.id.0 == own,
|
||||
"client_type": match c.client_type { ClientType::Normal => "normal", ClientType::Query { .. } => "query" },
|
||||
"input_muted": c.input_muted,
|
||||
"output_muted": c.output_muted,
|
||||
"input_hardware": c.input_hardware_enabled,
|
||||
"output_hardware": c.output_hardware_enabled,
|
||||
"away": c.away_message.is_some(),
|
||||
"away_message": c.away_message,
|
||||
"talk_power": c.talk_power,
|
||||
"is_talker": c.talk_power_granted,
|
||||
"is_channel_commander": c.is_channel_commander,
|
||||
"is_priority_speaker": c.is_priority_speaker,
|
||||
"is_recording": c.is_recording,
|
||||
"is_streaming": extras.clients.get(&c.id.0).and_then(|e| e.is_streaming),
|
||||
"description": non_empty(&c.description),
|
||||
"country": non_empty(&c.country_code),
|
||||
"server_groups": groups,
|
||||
"channel_group_id": c.channel_group.0,
|
||||
"channel_group_inherited_from": c.inherited_channel_group_from_channel.0,
|
||||
"avatar_hash": non_empty(&c.avatar_hash),
|
||||
"icon_id": icon(c.icon),
|
||||
"badges": non_empty(&c.badges),
|
||||
})
|
||||
}
|
||||
|
||||
/// Channel ids in display order (pre-order walk; siblings chained by `order` = preceding id).
|
||||
pub fn ordered_channels(channels: &HashMap<ChannelId, Channel>) -> Vec<(ChannelId, usize)> {
|
||||
let mut children: BTreeMap<u64, Vec<&Channel>> = BTreeMap::new();
|
||||
for c in channels.values() {
|
||||
let parent = if channels.contains_key(&c.parent) { c.parent.0 } else { 0 };
|
||||
children.entry(parent).or_default().push(c);
|
||||
}
|
||||
let mut out = Vec::with_capacity(channels.len());
|
||||
let mut visited = HashSet::new();
|
||||
walk(0, 0, &children, &mut visited, &mut out);
|
||||
// Anything unreachable (inconsistent parents/cycles) is appended so nothing disappears.
|
||||
let mut rest: Vec<_> = channels.keys().filter(|id| !visited.contains(&id.0)).copied().collect();
|
||||
rest.sort_by_key(|id| id.0);
|
||||
out.extend(rest.into_iter().map(|id| (id, 0)));
|
||||
out
|
||||
}
|
||||
|
||||
fn walk(
|
||||
parent: u64, depth: usize, children: &BTreeMap<u64, Vec<&Channel>>, visited: &mut HashSet<u64>,
|
||||
out: &mut Vec<(ChannelId, usize)>,
|
||||
) {
|
||||
let Some(siblings) = children.get(&parent) else { return };
|
||||
let mut by_pred: HashMap<u64, Vec<&Channel>> = HashMap::new();
|
||||
for c in siblings {
|
||||
by_pred.entry(c.order.0).or_default().push(c);
|
||||
}
|
||||
for list in by_pred.values_mut() {
|
||||
list.sort_by_key(|c| c.id.0);
|
||||
}
|
||||
let sibling_ids: HashSet<u64> = siblings.iter().map(|c| c.id.0).collect();
|
||||
let mut sorted: Vec<&Channel> = Vec::with_capacity(siblings.len());
|
||||
let mut placed = HashSet::new();
|
||||
// Start from channels whose predecessor is 0 or not a sibling, then follow the chain.
|
||||
let mut starts: Vec<&Channel> =
|
||||
siblings.iter().filter(|c| c.order.0 == 0 || !sibling_ids.contains(&c.order.0)).copied().collect();
|
||||
starts.sort_by_key(|c| (c.order.0 != 0, c.id.0));
|
||||
for start in starts {
|
||||
let mut stack = vec![start];
|
||||
while let Some(c) = stack.pop() {
|
||||
if !placed.insert(c.id.0) {
|
||||
continue;
|
||||
}
|
||||
sorted.push(c);
|
||||
if let Some(next) = by_pred.get(&c.id.0) {
|
||||
stack.extend(next.iter().rev().copied());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut leftover: Vec<&Channel> = siblings.iter().filter(|c| !placed.contains(&c.id.0)).copied().collect();
|
||||
leftover.sort_by_key(|c| c.id.0);
|
||||
sorted.extend(leftover);
|
||||
|
||||
for c in sorted {
|
||||
if !visited.insert(c.id.0) {
|
||||
continue;
|
||||
}
|
||||
out.push((c.id, depth));
|
||||
walk(c.id.0, depth + 1, children, visited, out);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build(book: &Connection, rev: u64, extras: &RawExtras) -> Value {
|
||||
let own = book.own_client.0;
|
||||
let own_channel = book.clients.get(&book.own_client).map(|c| c.channel.0);
|
||||
let channels: Vec<Value> = ordered_channels(&book.channels)
|
||||
.into_iter()
|
||||
.filter_map(|(id, depth)| book.channels.get(&id).map(|c| channel_json(c, depth, extras)))
|
||||
.collect();
|
||||
let mut clients: Vec<&Client> = book.clients.values().collect();
|
||||
clients.sort_by_key(|c| c.id.0);
|
||||
let clients: Vec<Value> = clients.into_iter().map(|c| client_json(c, own, extras)).collect();
|
||||
let mut sgroups: Vec<&ServerGroup> = book.server_groups.values().collect();
|
||||
sgroups.sort_by_key(|g| (g.sort_id, g.id.0));
|
||||
let mut cgroups: Vec<&ChannelGroup> = book.channel_groups.values().collect();
|
||||
cgroups.sort_by_key(|g| (g.sort_id, g.id.0));
|
||||
let s = &book.server;
|
||||
json!({
|
||||
"event": "snapshot",
|
||||
"rev": rev,
|
||||
"server": {
|
||||
"name": s.name,
|
||||
"welcome_message": s.welcome_message,
|
||||
"platform": s.platform,
|
||||
"version": s.version,
|
||||
"icon_id": icon(s.icon),
|
||||
"hostbanner_url": non_empty(&s.hostbanner_url),
|
||||
"hostbanner_gfx_url": non_empty(&s.hostbanner_gfx_url),
|
||||
"hostbanner_gfx_interval_s": s.hostbanner_gfx_interval.whole_seconds(),
|
||||
"hostbanner_mode": hostbanner_mode(s.hostbanner_mode),
|
||||
"hostbutton_url": non_empty(&s.hostbutton_url),
|
||||
"hostbutton_gfx_url": non_empty(&s.hostbutton_gfx_url),
|
||||
"hostbutton_tooltip": non_empty(&s.hostbutton_tooltip),
|
||||
"default_server_group": s.default_server_group.0,
|
||||
"default_channel_group": s.default_channel_group.0,
|
||||
},
|
||||
"own_client_id": own,
|
||||
"own_channel_id": own_channel,
|
||||
"server_groups": sgroups.into_iter().map(server_group_json).collect::<Vec<_>>(),
|
||||
"channel_groups": cgroups.into_iter().map(channel_group_json).collect::<Vec<_>>(),
|
||||
"channels": channels,
|
||||
"clients": clients,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::rawcmd;
|
||||
|
||||
#[test]
|
||||
fn raw_extras_track_banners_and_streaming() {
|
||||
let mut x = RawExtras::default();
|
||||
let list = rawcmd::parse(
|
||||
br"channellist cid=20 cpid=12 channel_name=cs channel_banner_gfx_url=https:\/\/example.org\/b\sx.png channel_banner_mode=2|cid=21 channel_name=b channel_banner_gfx_url channel_banner_mode=0",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(x.apply(&list));
|
||||
assert_eq!(x.channels[&20].banner_url.as_deref(), Some("https://example.org/b x.png"));
|
||||
assert_eq!(x.channels[&20].banner_mode.as_deref(), Some("2"));
|
||||
assert_eq!(x.channels[&21].banner_url, None);
|
||||
let edit = rawcmd::parse(br"notifychanneledited cid=20 reasonid=10 channel_banner_gfx_url").unwrap();
|
||||
assert!(x.apply(&edit));
|
||||
assert_eq!(x.channels[&20].banner_url, None);
|
||||
assert_eq!(x.channels[&20].banner_mode.as_deref(), Some("2"), "mode untouched by partial edit");
|
||||
let unrelated = rawcmd::parse(br"notifychanneledited cid=20 reasonid=10 channel_name=x").unwrap();
|
||||
assert!(!x.apply(&unrelated));
|
||||
|
||||
let enter = rawcmd::parse(br"notifycliententerview clid=16 client_is_streaming=1|clid=6 client_is_streaming=0").unwrap();
|
||||
assert!(x.apply(&enter));
|
||||
assert_eq!(x.clients[&16].is_streaming, Some(true));
|
||||
assert_eq!(x.clients[&6].is_streaming, Some(false));
|
||||
let upd = rawcmd::parse(br"notifyclientupdated clid=16 client_is_streaming=0").unwrap();
|
||||
x.apply(&upd);
|
||||
assert_eq!(x.clients[&16].is_streaming, Some(false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
//! Newline-delimited JSON over stdio. stdout carries only protocol lines.
|
||||
|
||||
use std::io::{BufRead, BufReader, Read};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::Serialize;
|
||||
use tokio::io::{AsyncWriteExt, BufWriter};
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::{error, warn};
|
||||
|
||||
use crate::audio::{AudioIn, AudioInQueue};
|
||||
use crate::protocol::{self, ErrorCode, ErrorObj, Input, MAX_LINE_BYTES};
|
||||
|
||||
/// Control lines (responses/events) are awaited; audio lines are dropped when the pipe is full.
|
||||
const OUT_QUEUE: usize = 1024;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Out {
|
||||
tx: mpsc::Sender<String>,
|
||||
}
|
||||
|
||||
impl Out {
|
||||
pub fn new() -> (Self, mpsc::Receiver<String>) {
|
||||
let (tx, rx) = mpsc::channel(OUT_QUEUE);
|
||||
(Self { tx }, rx)
|
||||
}
|
||||
|
||||
pub async fn line(&self, line: String) {
|
||||
if self.tx.send(line).await.is_err() {
|
||||
error!("stdout writer is gone");
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn json<T: Serialize>(&self, value: &T) {
|
||||
match serde_json::to_string(value) {
|
||||
Ok(s) => self.line(s).await,
|
||||
Err(e) => error!(%e, "failed to serialize output"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Non-blocking send for high-rate audio. Returns false if dropped.
|
||||
pub fn try_line(&self, line: String) -> bool { self.tx.try_send(line).is_ok() }
|
||||
|
||||
pub async fn ok(&self, id: &str, result: serde_json::Value) {
|
||||
self.json(&serde_json::json!({ "id": id, "ok": true, "result": result })).await
|
||||
}
|
||||
|
||||
pub async fn err(&self, id: &str, error: ErrorObj) {
|
||||
self.json(&serde_json::json!({ "id": id, "ok": false, "error": error })).await
|
||||
}
|
||||
|
||||
pub async fn error_event(&self, error: ErrorObj) {
|
||||
self.json(&serde_json::json!({ "event": "error", "error": error })).await
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run_writer(mut rx: mpsc::Receiver<String>) {
|
||||
let mut out = BufWriter::new(tokio::io::stdout());
|
||||
while let Some(first) = rx.recv().await {
|
||||
let mut line = Some(first);
|
||||
while let Some(l) = line {
|
||||
if out.write_all(l.as_bytes()).await.is_err() || out.write_all(b"\n").await.is_err() {
|
||||
error!("stdout closed");
|
||||
return;
|
||||
}
|
||||
line = rx.try_recv().ok();
|
||||
}
|
||||
if out.flush().await.is_err() {
|
||||
error!("stdout closed");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocking stdin reader (runs on its own thread). Lines longer than [`MAX_LINE_BYTES`] are
|
||||
/// discarded up to their newline. Audio goes into `audio`, everything else into `cmds`.
|
||||
/// Returning drops `cmds`, which tells the session that stdin reached EOF.
|
||||
pub fn run_reader(input: impl Read, cmds: mpsc::Sender<Input>, audio: Arc<AudioInQueue>) {
|
||||
let mut reader = BufReader::with_capacity(64 * 1024, input);
|
||||
let mut line: Vec<u8> = Vec::with_capacity(8 * 1024);
|
||||
let mut overlong = false;
|
||||
loop {
|
||||
let buf = match reader.fill_buf() {
|
||||
Ok(b) => b,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||
Err(e) => {
|
||||
error!(%e, "stdin read failed");
|
||||
return;
|
||||
}
|
||||
};
|
||||
if buf.is_empty() {
|
||||
return; // EOF
|
||||
}
|
||||
let (chunk, found_newline) = match buf.iter().position(|b| *b == b'\n') {
|
||||
Some(i) => (&buf[..i], true),
|
||||
None => (buf, false),
|
||||
};
|
||||
if !overlong {
|
||||
if line.len() + chunk.len() > MAX_LINE_BYTES {
|
||||
overlong = true;
|
||||
line.clear();
|
||||
} else {
|
||||
line.extend_from_slice(chunk);
|
||||
}
|
||||
}
|
||||
let consumed = chunk.len() + usize::from(found_newline);
|
||||
reader.consume(consumed);
|
||||
if !found_newline {
|
||||
continue;
|
||||
}
|
||||
|
||||
let input = if overlong {
|
||||
overlong = false;
|
||||
Input::Invalid {
|
||||
id: None,
|
||||
error: ErrorObj::new(ErrorCode::BadRequest, format!("line longer than {MAX_LINE_BYTES} bytes")),
|
||||
}
|
||||
} else {
|
||||
if line.last() == Some(&b'\r') {
|
||||
line.pop();
|
||||
}
|
||||
if line.iter().all(u8::is_ascii_whitespace) {
|
||||
line.clear();
|
||||
continue;
|
||||
}
|
||||
let input = match std::str::from_utf8(&line) {
|
||||
Ok(text) => protocol::parse_line(text),
|
||||
Err(_) => Input::Invalid { id: None, error: ErrorObj::new(ErrorCode::BadRequest, "line is not UTF-8") },
|
||||
};
|
||||
line.clear();
|
||||
input
|
||||
};
|
||||
match input {
|
||||
Input::AudioFrame(frame) => audio.push(AudioIn::Frame(frame)),
|
||||
Input::AudioEnd => audio.push(AudioIn::End),
|
||||
other => {
|
||||
if cmds.blocking_send(other).is_err() {
|
||||
warn!("session stopped; ignoring further input");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reader_splits_lines_and_rejects_overlong() {
|
||||
let mut data = Vec::new();
|
||||
data.extend_from_slice(b"{\"id\":\"1\",\"cmd\":\"profile_get\"}\r\n\n");
|
||||
data.extend_from_slice(b"{\"id\":\"2\",\"cmd\":\"x\",\"args\":\"");
|
||||
data.extend(std::iter::repeat(b'a').take(MAX_LINE_BYTES + 10));
|
||||
data.extend_from_slice(b"\"}\n{\"cmd\":\"audio_end\"}\n{\"id\":\"3\",\"cmd\":\"shutdown\"}");
|
||||
let (tx, mut rx) = mpsc::channel(16);
|
||||
let audio = Arc::new(AudioInQueue::new());
|
||||
run_reader(&data[..], tx, audio.clone());
|
||||
match rx.try_recv().unwrap() {
|
||||
Input::Request { id, .. } => assert_eq!(id, "1"),
|
||||
o => panic!("{o:?}"),
|
||||
}
|
||||
match rx.try_recv().unwrap() {
|
||||
Input::Invalid { id: None, error } => assert!(error.message.contains("longer")),
|
||||
o => panic!("{o:?}"),
|
||||
}
|
||||
assert!(matches!(audio.pop(), Some(AudioIn::End)));
|
||||
// The last line has no trailing newline: it is incomplete and must not be executed.
|
||||
assert!(rx.try_recv().is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
//! Offline end-to-end smoke of the real binary over stdio (no network): identity lifecycle,
|
||||
//! UID stability across rename and restart, instance lock, export/import CLI, error surfacing.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const BIN: &str = env!("CARGO_BIN_EXE_teamspeach-core");
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let p = std::env::temp_dir().join(format!("teamspeach-smoke-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&p);
|
||||
std::fs::create_dir_all(&p).unwrap();
|
||||
Self(p)
|
||||
}
|
||||
}
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); }
|
||||
}
|
||||
|
||||
struct Core {
|
||||
child: Child,
|
||||
stdin: ChildStdin,
|
||||
lines: mpsc::Receiver<Value>,
|
||||
}
|
||||
|
||||
impl Core {
|
||||
fn start(dir: &Path) -> Self {
|
||||
let mut child = Command::new(BIN)
|
||||
.arg("--data-dir")
|
||||
.arg(dir)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.expect("spawn core");
|
||||
let stdin = child.stdin.take().unwrap();
|
||||
let stdout = child.stdout.take().unwrap();
|
||||
let (tx, lines) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
for line in BufReader::new(stdout).lines() {
|
||||
let line = line.unwrap();
|
||||
let v: Value = serde_json::from_str(&line).unwrap_or_else(|e| panic!("stdout is not JSON ({e}): {line}"));
|
||||
if tx.send(v).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let mut core = Self { child, stdin, lines };
|
||||
let ready = core.next();
|
||||
assert_eq!(ready["event"], "ready");
|
||||
assert_eq!(ready["protocol"], 1);
|
||||
core
|
||||
}
|
||||
|
||||
fn next(&mut self) -> Value { self.lines.recv_timeout(Duration::from_secs(20)).expect("core output") }
|
||||
|
||||
fn send(&mut self, v: Value) {
|
||||
writeln!(self.stdin, "{v}").unwrap();
|
||||
self.stdin.flush().unwrap();
|
||||
}
|
||||
|
||||
/// Send a request and return its response, collecting events seen meanwhile.
|
||||
fn request(&mut self, id: &str, cmd: &str, args: Value) -> (Value, Vec<Value>) {
|
||||
self.send(json!({ "id": id, "cmd": cmd, "args": args }));
|
||||
let mut events = Vec::new();
|
||||
loop {
|
||||
let v = self.next();
|
||||
if v.get("id").and_then(Value::as_str) == Some(id) {
|
||||
return (v, events);
|
||||
}
|
||||
events.push(v);
|
||||
}
|
||||
}
|
||||
|
||||
fn shutdown(mut self) {
|
||||
let (resp, _) = self.request("bye", "shutdown", json!({}));
|
||||
assert_eq!(resp["ok"], true);
|
||||
let status = self.child.wait().unwrap();
|
||||
assert!(status.success(), "exit status {status:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn cli(args: &[&std::ffi::OsStr]) -> (i32, Value) {
|
||||
let out = Command::new(BIN).args(args).output().unwrap();
|
||||
let line = String::from_utf8(out.stdout).unwrap();
|
||||
let v = if line.trim().is_empty() { Value::Null } else { serde_json::from_str(line.trim()).unwrap() };
|
||||
(out.status.code().unwrap(), v)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_lifecycle_over_stdio() {
|
||||
let dir = TempDir::new("life");
|
||||
let mut core = Core::start(&dir.0);
|
||||
|
||||
let (r, _) = core.request("1", "profile_get", json!({}));
|
||||
assert_eq!(r["result"]["exists"], false);
|
||||
|
||||
let (r, _) = core.request("2", "rename", json!({ "nickname": "Nobody" }));
|
||||
assert_eq!(r["error"]["code"], "profile_missing");
|
||||
|
||||
let (r, events) = core.request("3", "profile_create", json!({ "nickname": "TeamsPeach-Smoke" }));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
let uid = r["result"]["uid"].as_str().unwrap().to_owned();
|
||||
assert_eq!(r["result"]["nickname"], "TeamsPeach-Smoke");
|
||||
assert!(r["result"]["security_level"].as_u64().unwrap() >= 8);
|
||||
assert!(events.iter().any(|e| e["event"] == "profile" && e["uid"] == uid.as_str()));
|
||||
assert!(r.to_string().find("private").is_none(), "private key material leaked: {r}");
|
||||
|
||||
let (r, _) = core.request("4", "profile_create", json!({ "nickname": "Other" }));
|
||||
assert_eq!(r["error"]["code"], "profile_exists");
|
||||
|
||||
let (r, _) = core.request("5", "rename", json!({ "nickname": "Renamed Smoke" }));
|
||||
assert_eq!(r["result"]["uid"], uid.as_str());
|
||||
assert_eq!(r["result"]["nickname"], "Renamed Smoke");
|
||||
|
||||
let (r, _) = core.request("6", "rename", json!({ "nickname": "x" }));
|
||||
assert_eq!(r["error"]["code"], "invalid_nickname");
|
||||
|
||||
// Second instance on the same data dir is refused.
|
||||
let second = Command::new(BIN).arg("--data-dir").arg(&dir.0).stdin(Stdio::null()).output().unwrap();
|
||||
assert_eq!(second.status.code(), Some(3));
|
||||
assert!(second.stdout.is_empty());
|
||||
|
||||
// Protocol errors are surfaced.
|
||||
let (r, _) = core.request("7", "read_file", json!({ "path": "/etc/passwd" }));
|
||||
assert_eq!(r["error"]["code"], "unknown_command");
|
||||
let (r, _) = core.request("8", "join_channel", json!({ "channel_id": 1 }));
|
||||
assert_eq!(r["error"]["code"], "not_connected");
|
||||
core.send(json!({ "cmd": "audio_frame", "args": { "pcm": "AAAA" } }));
|
||||
let e = core.next();
|
||||
assert_eq!(e["event"], "error");
|
||||
assert_eq!(e["error"]["code"], "audio_format");
|
||||
core.send(json!({ "cmd": "audio_frame", "args": { "pcm": base64_silence() } }));
|
||||
let e = core.next();
|
||||
assert_eq!(e["error"]["code"], "not_connected");
|
||||
core.send(json!({ "cmd": "audio_end" }));
|
||||
let (r, _) = core.request("9", "set_audio", json!({ "input_muted": true }));
|
||||
assert_eq!(r["result"], json!({ "input_muted": true, "output_muted": false, "transmitting": false }));
|
||||
core.shutdown();
|
||||
|
||||
// Restart: same UID, renamed nickname persisted.
|
||||
let mut core = Core::start(&dir.0);
|
||||
let (r, _) = core.request("1", "profile_get", json!({}));
|
||||
assert_eq!(r["result"]["uid"], uid.as_str());
|
||||
assert_eq!(r["result"]["nickname"], "Renamed Smoke");
|
||||
core.shutdown();
|
||||
|
||||
// Export (allowed while a core runs) and import into a fresh data dir.
|
||||
let running = Core::start(&dir.0);
|
||||
let export_file = dir.0.join("export.ini");
|
||||
let (code, v) = cli(&["identity".as_ref(), "export".as_ref(), "--data-dir".as_ref(), dir.0.as_os_str(), "--out".as_ref(), export_file.as_os_str()]);
|
||||
assert_eq!(code, 0, "{v}");
|
||||
assert_eq!(v["uid"], uid.as_str());
|
||||
running.shutdown();
|
||||
|
||||
let other = TempDir::new("import");
|
||||
let (code, v) = cli(&["identity".as_ref(), "import".as_ref(), "--data-dir".as_ref(), other.0.as_os_str(), "--in".as_ref(), export_file.as_os_str()]);
|
||||
assert_eq!(code, 0, "{v}");
|
||||
assert_eq!(v["uid"], uid.as_str());
|
||||
let (code, v) = cli(&["identity".as_ref(), "import".as_ref(), "--data-dir".as_ref(), other.0.as_os_str(), "--in".as_ref(), export_file.as_os_str()]);
|
||||
assert_eq!(code, 1);
|
||||
assert_eq!(v["error"]["code"], "profile_exists");
|
||||
let mut core = Core::start(&other.0);
|
||||
let (r, _) = core.request("1", "profile_get", json!({}));
|
||||
assert_eq!(r["result"]["uid"], uid.as_str());
|
||||
assert_eq!(r["result"]["nickname"], "Renamed Smoke");
|
||||
core.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_identity_is_reported_not_replaced() {
|
||||
let dir = TempDir::new("corrupt");
|
||||
let path = dir.0.join("identity.json");
|
||||
std::fs::write(&path, b"{\"version\":1,\"uid\":\"broken\"").unwrap();
|
||||
let mut core = Core::start(&dir.0);
|
||||
let (r, _) = core.request("1", "profile_get", json!({}));
|
||||
assert_eq!(r["error"]["code"], "identity_corrupt");
|
||||
let (r, _) = core.request("2", "profile_create", json!({ "nickname": "Fresh" }));
|
||||
assert_eq!(r["error"]["code"], "identity_corrupt");
|
||||
let (r, _) = core.request("3", "connect", json!({ "address": "127.0.0.1:9" }));
|
||||
assert_eq!(r["error"]["code"], "identity_corrupt");
|
||||
core.shutdown();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"{\"version\":1,\"uid\":\"broken\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_eof_exits_cleanly() {
|
||||
let dir = TempDir::new("eof");
|
||||
let mut core = Core::start(&dir.0);
|
||||
drop(core.stdin);
|
||||
let status = core.child.wait().unwrap();
|
||||
assert!(status.success());
|
||||
}
|
||||
|
||||
fn base64_silence() -> String { "A".repeat(2560) }
|
||||
@@ -0,0 +1,161 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate core/THIRD_PARTY_NOTICES.md from `cargo metadata` (all target platforms).
|
||||
|
||||
Run from anywhere: `python core/tools/third_party_notices.py`. Requires cargo on PATH and the
|
||||
dependency sources fetched (`cargo fetch`). Covers every crate reachable through normal
|
||||
(non-dev, non-build) dependencies on any platform, plus the libopus sources that
|
||||
audiopus_sys builds and links statically.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
CORE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
OUT = os.path.join(CORE, "THIRD_PARTY_NOTICES.md")
|
||||
|
||||
MIT_TEXT = """Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE."""
|
||||
|
||||
BSD3_TEXT = """Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."""
|
||||
|
||||
|
||||
def fallback_text(pkg):
|
||||
"""Standard text for a crate that ships no license file, or None if not MIT/BSD-3-Clause."""
|
||||
lic = pkg.get("license") or ""
|
||||
holders = ", ".join(pkg.get("authors") or []) or f'the {pkg["name"]} authors ({pkg.get("repository") or "see crates.io"})'
|
||||
if "MIT" in lic:
|
||||
return "MIT", f"Copyright (c) {holders}\n\n{MIT_TEXT}"
|
||||
if "BSD-3-Clause" in lic:
|
||||
return "BSD-3-Clause", f"Copyright (c) {holders}\n\n{BSD3_TEXT}"
|
||||
return None
|
||||
LICENSE_RE = re.compile(r"^(licen[cs]e|copying|notice|copyright|unlicense)", re.IGNORECASE)
|
||||
|
||||
|
||||
def license_files(directory, stop):
|
||||
"""License files in the package dir; for crates inside a git checkout, walk up to its root."""
|
||||
d = directory
|
||||
while True:
|
||||
try:
|
||||
names = sorted(n for n in os.listdir(d) if LICENSE_RE.match(n) and os.path.isfile(os.path.join(d, n)))
|
||||
except OSError:
|
||||
names = []
|
||||
if names:
|
||||
return [os.path.join(d, n) for n in names]
|
||||
parent = os.path.dirname(d)
|
||||
if d == stop or parent == d or not d.startswith(stop):
|
||||
return []
|
||||
d = parent
|
||||
|
||||
|
||||
def main():
|
||||
meta = json.loads(subprocess.check_output(["cargo", "metadata", "--format-version", "1"], cwd=CORE))
|
||||
pkgs = {p["id"]: p for p in meta["packages"]}
|
||||
nodes = {n["id"]: n for n in meta["resolve"]["nodes"]}
|
||||
root = meta["resolve"]["root"]
|
||||
seen, stack = set(), [root]
|
||||
while stack:
|
||||
nid = stack.pop()
|
||||
for dep in nodes[nid]["deps"]:
|
||||
if any(k["kind"] is None for k in dep["dep_kinds"]) and dep["pkg"] not in seen:
|
||||
seen.add(dep["pkg"])
|
||||
stack.append(dep["pkg"])
|
||||
|
||||
git_root = os.path.join(os.path.expanduser("~"), ".cargo", "git", "checkouts")
|
||||
crates, groups, missing = [], {}, []
|
||||
for pid in sorted(seen, key=lambda i: (pkgs[i]["name"], pkgs[i]["version"])):
|
||||
p = pkgs[pid]
|
||||
pdir = os.path.dirname(p["manifest_path"])
|
||||
stop = pdir
|
||||
if pdir.startswith(git_root):
|
||||
stop = git_root
|
||||
elif os.path.abspath(pdir).startswith(os.path.join(CORE, "vendor")):
|
||||
stop = pdir
|
||||
files = license_files(pdir, stop)
|
||||
source = p.get("source") or "vendored (core/vendor)"
|
||||
crates.append((p["name"], p["version"], p.get("license") or "see files", source))
|
||||
if not files:
|
||||
missing.append(f'{p["name"]} {p["version"]}')
|
||||
fb = fallback_text(p)
|
||||
if fb is None:
|
||||
sys.exit(f'{p["name"]} {p["version"]}: no license file and no known standard text for {p.get("license")!r}')
|
||||
spdx, text = fb
|
||||
key = hashlib.sha256(text.encode()).hexdigest()
|
||||
groups.setdefault(key, (text, []))[1].append(
|
||||
f'{p["name"]} {p["version"]} (no license file in package; standard {spdx} text, license {p.get("license")})')
|
||||
for f in files:
|
||||
with open(f, "rb") as fh:
|
||||
text = fh.read().decode("utf-8", "replace").replace("\r\n", "\n").strip()
|
||||
key = hashlib.sha256(text.encode()).hexdigest()
|
||||
groups.setdefault(key, (text, []))[1].append(f'{p["name"]} {p["version"]} ({os.path.basename(f)})')
|
||||
|
||||
opus = None
|
||||
for p in pkgs.values():
|
||||
if p["name"] == "audiopus_sys" and p["id"] in seen:
|
||||
opus = os.path.join(os.path.dirname(p["manifest_path"]), "opus", "COPYING")
|
||||
|
||||
out = ["# Third-party notices for teamspeach-core", "",
|
||||
"Generated by `core/tools/third_party_notices.py` from `cargo metadata`. Lists every crate",
|
||||
"reachable through normal dependencies on any target platform (a superset of what a single",
|
||||
"platform build links), followed by the license texts shipped with those crates.", "",
|
||||
"| Crate | Version | License | Source |", "|---|---|---|---|"]
|
||||
for name, ver, lic, src in crates:
|
||||
out.append(f"| {name} | {ver} | {lic} | {src} |")
|
||||
if missing:
|
||||
out += ["", "Crates whose package ships no license file (standard texts of their declared license are "
|
||||
"included below with the authors from their Cargo.toml): " + ", ".join(missing) + "."]
|
||||
if opus:
|
||||
with open(opus, "rb") as fh:
|
||||
out += ["", "## libopus (bundled in audiopus_sys, statically linked)", "", "```",
|
||||
fh.read().decode("utf-8", "replace").replace("\r\n", "\n").strip(), "```"]
|
||||
out += ["", "## License texts", ""]
|
||||
for text, users in sorted(groups.values(), key=lambda g: g[1][0]):
|
||||
out += ["### " + "; ".join(users), "", "```", text.replace("```", "'''"), "```", ""]
|
||||
with open(OUT, "w", encoding="utf-8", newline="\n") as fh:
|
||||
fh.write("\n".join(out) + "\n")
|
||||
print(f"wrote {OUT}: {len(crates)} crates, {len(groups)} distinct license texts, "
|
||||
f"{len(missing)} without files: {', '.join(missing)}", file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,32 @@
|
||||
# Vendored third-party code
|
||||
|
||||
## `tsclientlib/`
|
||||
|
||||
- Upstream: <https://github.com/ReSpeak/tsclientlib>, crate `tsclientlib/` at revision
|
||||
`ee3bc6f45a7137db7793ba5593a321df400d53e5` (2026-07-22, "Fix pulling partial packets from AudioQueue").
|
||||
- Authors: Flakebi and the ReSpeak contributors.
|
||||
- License: dual MIT OR Apache-2.0 — see `tsclientlib/LICENSE-MIT` and
|
||||
`tsclientlib/LICENSE-APACHE` (copied verbatim from the upstream repository root).
|
||||
- Only the `tsclientlib` crate (`Cargo.toml`, `README.md`, `src/`) is vendored. Its sibling
|
||||
crates (`tsproto`, `ts-bookkeeping`, `tsproto-packets`, `tsproto-types`) are used unmodified
|
||||
as git dependencies pinned to the same revision.
|
||||
|
||||
### Local modifications
|
||||
|
||||
The complete diff against upstream is `tsclientlib.patch` (apply with `git apply -p1` inside
|
||||
upstream's `tsclientlib/` crate directory at the revision above; it reproduces this tree):
|
||||
|
||||
1. `Cargo.toml`: the workspace `path` dependencies are replaced by git dependencies pinned to
|
||||
the same revision.
|
||||
2. `src/lib.rs`: new `StreamItem::UnknownCommand(InCommandBuf)`. Upstream parses every incoming
|
||||
command into `InMessage` and drops (with a warning) commands it has no declaration for. The
|
||||
TeamSpeak 6 screen-share signalling (`notifystream*`, `notifyjoinstreamrequest`,
|
||||
`notifyrespondjoinstreamrequest`, `notifysfuaccessinfo`) is such a family, so the patch hands
|
||||
those packets to the application unparsed instead of dropping them.
|
||||
3. `src/lib.rs`: opt-in `ConnectOptions::raw_command_tap(fn(&[u8]) -> bool)` and
|
||||
`StreamItem::RawCommandCopy(Vec<u8>)`: a copy of each incoming command whose name the
|
||||
predicate selects, emitted before normal processing. Used to read arguments the book does not
|
||||
store (channel banners, TeamSpeak 6 `client_is_streaming`). Off by default.
|
||||
4. `src/sync.rs`: `SyncStreamItem` mirrors the two new variants so the crate keeps compiling.
|
||||
|
||||
No other behaviour changes.
|
||||
@@ -0,0 +1,130 @@
|
||||
diff --git a/Cargo.toml b/Cargo.toml
|
||||
index a58f145..c3d9252 100644
|
||||
--- a/Cargo.toml
|
||||
+++ b/Cargo.toml
|
||||
@@ -46,10 +46,12 @@ tokio-stream = "0.1"
|
||||
tracing = "0.1"
|
||||
hickory-net = "0.26"
|
||||
hickory-resolver = "0.26"
|
||||
-ts-bookkeeping = { path = "../utils/ts-bookkeeping", version = "0.1" }
|
||||
-tsproto = { path = "../tsproto", version = "0.2" }
|
||||
-tsproto-packets = { path = "../utils/tsproto-packets", version = "0.1" }
|
||||
-tsproto-types = { path = "../utils/tsproto-types", version = "0.1" }
|
||||
+# TeamsPeach vendoring: the upstream workspace path dependencies are replaced by the
|
||||
+# same crates pinned to the vendored upstream revision (see ../README.md).
|
||||
+ts-bookkeeping = { git = "https://github.com/ReSpeak/tsclientlib", rev = "ee3bc6f45a7137db7793ba5593a321df400d53e5" }
|
||||
+tsproto = { git = "https://github.com/ReSpeak/tsclientlib", rev = "ee3bc6f45a7137db7793ba5593a321df400d53e5" }
|
||||
+tsproto-packets = { git = "https://github.com/ReSpeak/tsclientlib", rev = "ee3bc6f45a7137db7793ba5593a321df400d53e5" }
|
||||
+tsproto-types = { git = "https://github.com/ReSpeak/tsclientlib", rev = "ee3bc6f45a7137db7793ba5593a321df400d53e5" }
|
||||
url = "2"
|
||||
|
||||
[dev-dependencies]
|
||||
diff --git a/src/lib.rs b/src/lib.rs
|
||||
index d41b601..d7184f6 100644
|
||||
--- a/src/lib.rs
|
||||
+++ b/src/lib.rs
|
||||
@@ -253,6 +253,15 @@ pub enum StreamItem {
|
||||
NetworkStatsUpdated,
|
||||
/// A change related to audio.
|
||||
AudioChange(AudioEvent),
|
||||
+ /// TeamsPeach patch: a command whose name tsclientlib does not know (e.g. the TeamSpeak 6
|
||||
+ /// `notifystream*` family). Upstream logs and drops these; they are handed out unparsed so
|
||||
+ /// the application can read them with
|
||||
+ /// [`CommandParser`](tsproto_packets::commands::CommandParser).
|
||||
+ UnknownCommand(InCommandBuf),
|
||||
+ /// TeamsPeach patch: copy of the content of a command selected by
|
||||
+ /// [`ConnectOptions::raw_command_tap`], emitted before tsclientlib processes the command.
|
||||
+ /// Lets the application read arguments the book does not store.
|
||||
+ RawCommandCopy(Vec<u8>),
|
||||
}
|
||||
|
||||
/// The `Connection` is the main interaction point with this library.
|
||||
@@ -391,6 +400,7 @@ impl Connection {
|
||||
log_commands: false,
|
||||
log_packets: false,
|
||||
log_udp_packets: false,
|
||||
+ raw_command_tap: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1340,9 +1350,21 @@ impl ConnectedConnection {
|
||||
&mut self, book: &mut data::Connection, stream_items: &mut VecDeque<Result<StreamItem>>,
|
||||
options: &mut ConnectOptions, cmd: InCommandBuf,
|
||||
) -> Option<TemporaryDisconnectReason> {
|
||||
+ // TeamsPeach patch: optional raw copy of selected commands.
|
||||
+ if let Some(tap) = options.raw_command_tap {
|
||||
+ let content = cmd.data().packet().content();
|
||||
+ if tap(CommandParser::new(content).0) {
|
||||
+ stream_items.push_back(Ok(StreamItem::RawCommandCopy(content.to_vec())));
|
||||
+ }
|
||||
+ }
|
||||
let msg = match InMessage::new(cmd.data().packet().header(), cmd.data().packet().content())
|
||||
{
|
||||
Ok(r) => r,
|
||||
+ // TeamsPeach patch: hand unknown commands to the application instead of dropping them.
|
||||
+ Err(ts_bookkeeping::messages::ParseError::UnknownCommand(_)) => {
|
||||
+ stream_items.push_back(Ok(StreamItem::UnknownCommand(cmd)));
|
||||
+ return None;
|
||||
+ }
|
||||
Err(error) => {
|
||||
warn!(%error, "Failed to parse message");
|
||||
return None;
|
||||
@@ -1705,6 +1727,8 @@ pub struct ConnectOptions {
|
||||
log_commands: bool,
|
||||
log_packets: bool,
|
||||
log_udp_packets: bool,
|
||||
+ /// TeamsPeach patch: selects commands (by name) to copy into [`StreamItem::RawCommandCopy`].
|
||||
+ raw_command_tap: Option<fn(&[u8]) -> bool>,
|
||||
}
|
||||
|
||||
impl ConnectOptions {
|
||||
@@ -2001,6 +2025,17 @@ impl ConnectOptions {
|
||||
self
|
||||
}
|
||||
|
||||
+ /// TeamsPeach patch: emit [`StreamItem::RawCommandCopy`] for every incoming command whose
|
||||
+ /// name makes `tap` return `true`.
|
||||
+ ///
|
||||
+ /// # Default
|
||||
+ /// `None`
|
||||
+ #[inline]
|
||||
+ pub fn raw_command_tap(mut self, tap: fn(&[u8]) -> bool) -> Self {
|
||||
+ self.raw_command_tap = Some(tap);
|
||||
+ self
|
||||
+ }
|
||||
+
|
||||
#[inline]
|
||||
pub fn get_address(&self) -> &ServerAddress { &self.address }
|
||||
#[inline]
|
||||
diff --git a/src/sync.rs b/src/sync.rs
|
||||
index afad689..2e6ef53 100644
|
||||
--- a/src/sync.rs
|
||||
+++ b/src/sync.rs
|
||||
@@ -15,6 +15,7 @@ use ts_bookkeeping::ChannelId;
|
||||
use tsproto_packets::packets::InAudioBuf;
|
||||
#[cfg(feature = "unstable")]
|
||||
use tsproto_packets::packets::OutCommand;
|
||||
+use tsproto_packets::packets::InCommandBuf;
|
||||
|
||||
use crate::{
|
||||
events, AudioEvent, DisconnectOptions, Error, InMessage, Result, StreamItem,
|
||||
@@ -79,6 +80,10 @@ pub enum SyncStreamItem {
|
||||
NetworkStatsUpdated,
|
||||
/// A change related to audio.
|
||||
AudioChange(AudioEvent),
|
||||
+ /// TeamsPeach patch: see [`StreamItem::UnknownCommand`](crate::StreamItem::UnknownCommand).
|
||||
+ UnknownCommand(InCommandBuf),
|
||||
+ /// TeamsPeach patch: see [`StreamItem::RawCommandCopy`](crate::StreamItem::RawCommandCopy).
|
||||
+ RawCommandCopy(Vec<u8>),
|
||||
}
|
||||
|
||||
/// A handle for a [`SyncConnection`] which can be sent across threads.
|
||||
@@ -281,6 +286,8 @@ impl Stream for SyncConnection {
|
||||
}
|
||||
StreamItem::NetworkStatsUpdated => SyncStreamItem::NetworkStatsUpdated,
|
||||
StreamItem::AudioChange(change) => SyncStreamItem::AudioChange(change),
|
||||
+ StreamItem::UnknownCommand(cmd) => SyncStreamItem::UnknownCommand(cmd),
|
||||
+ StreamItem::RawCommandCopy(c) => SyncStreamItem::RawCommandCopy(c),
|
||||
})),
|
||||
Some(Err(e)) => Some(Err(e)),
|
||||
None => {
|
||||
@@ -0,0 +1,66 @@
|
||||
[package]
|
||||
name = "tsclientlib"
|
||||
version = "0.2.0"
|
||||
authors = ["Flakebi <flakebi@t-online.de>"]
|
||||
description = "A library to create TeamSpeak clients and bots."
|
||||
repository = "https://github.com/ReSpeak/tsclientlib"
|
||||
readme = "README.md"
|
||||
keywords = ["teamspeak3", "ts3", "voip"]
|
||||
categories = ["multimedia"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
edition = "2018"
|
||||
include = [
|
||||
"/Cargo.toml",
|
||||
"/README.md",
|
||||
"**/*.rs",
|
||||
]
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["unstable"]
|
||||
|
||||
[features]
|
||||
default = ["audio", "default-tls"]
|
||||
# Enable the unstable api
|
||||
unstable = []
|
||||
audio = ["audiopus"]
|
||||
# Enable default reqwest features.
|
||||
# Use default-features=false on tsclientlib to configure reqwest differently.
|
||||
default-tls = ["reqwest/charset", "reqwest/default-tls", "reqwest/http2"]
|
||||
# Use API of audiopus fork at https://github.com/Flakebi/audiopus for more features
|
||||
audiopus-unstable = []
|
||||
|
||||
[dependencies]
|
||||
audiopus = { version = "0.3.0-rc.0", optional = true }
|
||||
base64 = "0.22"
|
||||
futures = "0.3"
|
||||
git-testament = "0.2"
|
||||
itertools = "0.14"
|
||||
num-traits = "0.2"
|
||||
pin-utils = "0.1"
|
||||
rand = "0.10"
|
||||
reqwest = { version = "0.13", default-features = false }
|
||||
thiserror = "2"
|
||||
time = "0.3"
|
||||
tokio = { version = "1", features = ["time"] }
|
||||
tokio-stream = "0.1"
|
||||
tracing = "0.1"
|
||||
hickory-net = "0.26"
|
||||
hickory-resolver = "0.26"
|
||||
# TeamsPeach vendoring: the upstream workspace path dependencies are replaced by the
|
||||
# same crates pinned to the vendored upstream revision (see ../README.md).
|
||||
ts-bookkeeping = { git = "https://github.com/ReSpeak/tsclientlib", rev = "ee3bc6f45a7137db7793ba5593a321df400d53e5" }
|
||||
tsproto = { git = "https://github.com/ReSpeak/tsclientlib", rev = "ee3bc6f45a7137db7793ba5593a321df400d53e5" }
|
||||
tsproto-packets = { git = "https://github.com/ReSpeak/tsclientlib", rev = "ee3bc6f45a7137db7793ba5593a321df400d53e5" }
|
||||
tsproto-types = { git = "https://github.com/ReSpeak/tsclientlib", rev = "ee3bc6f45a7137db7793ba5593a321df400d53e5" }
|
||||
url = "2"
|
||||
|
||||
[dev-dependencies]
|
||||
anyhow = "1"
|
||||
audiopus = "0.3.0-rc.0"
|
||||
cpal = "0.18"
|
||||
once_cell = "1"
|
||||
quickcheck = "1"
|
||||
quickcheck_macros = "1"
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
tokio = { version = "1", features = ["io-util", "net", "rt-multi-thread", "rt", "signal"] }
|
||||
tracing-subscriber = "0.3"
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
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
|
||||
|
||||
http://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.
|
||||
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2020 tsclientlib contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,21 @@
|
||||
# TsClientlib [](https://docs.rs/tsclientlib)
|
||||
tsclientlib is a library which makes it simple to create TeamSpeak clients
|
||||
and bots.
|
||||
|
||||
For a full client application, you might want to have a look at [Qint].
|
||||
|
||||
If more power over the internals of a connection is needed, the `unstable` feature can be
|
||||
enabled. Beware that functionality behind this feature may change on any minor release.
|
||||
|
||||
The base class of this library is the [`Connection`]. One instance of this
|
||||
struct manages a single connection to a server.
|
||||
|
||||
[Qint]: https://github.com/ReSpeak/Qint
|
||||
|
||||
## License
|
||||
Licensed under either of
|
||||
|
||||
* [Apache License, Version 2.0](../LICENSE-APACHE)
|
||||
* [MIT license](../LICENSE-MIT)
|
||||
|
||||
at your option.
|
||||
@@ -0,0 +1,876 @@
|
||||
//! Handle receiving audio.
|
||||
//!
|
||||
//! The [`AudioHandler`] collects all incoming audio packets and queues them per
|
||||
//! client. It decodes the audio, handles out-of-order packets and missing
|
||||
//! packets. It automatically adjusts the queue length based on the jitter of
|
||||
//! incoming packets.
|
||||
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::convert::TryInto;
|
||||
use std::fmt::Debug;
|
||||
use std::hash::Hash;
|
||||
|
||||
use audiopus::coder::Decoder;
|
||||
#[cfg(feature = "audiopus-unstable")]
|
||||
use audiopus::coder::GenericCtl;
|
||||
use audiopus::{Channels, SampleRate, packet};
|
||||
use thiserror::Error;
|
||||
use tracing::{Span, debug, info_span, trace, warn};
|
||||
use tsproto_packets::packets::{AudioData, CodecType, InAudioBuf};
|
||||
|
||||
use crate::ClientId;
|
||||
|
||||
const SAMPLE_RATE: SampleRate = SampleRate::Hz48000;
|
||||
const CHANNELS: Channels = Channels::Stereo;
|
||||
const CHANNEL_NUM: usize = 2;
|
||||
/// If this amount of packets is lost consecutively, we assume the stream stopped.
|
||||
const MAX_PACKET_LOSSES: usize = 3;
|
||||
/// Store the buffer sizes for the last `LAST_BUFFER_SIZE_COUNT` packets.
|
||||
const LAST_BUFFER_SIZE_COUNT: u8 = 255;
|
||||
/// The amount of samples to maximally buffer. Equivalent to 0.5 s.
|
||||
const MAX_BUFFER_SIZE: usize = 48_000 / 2;
|
||||
/// Maximum number of packets in the queue.
|
||||
const MAX_BUFFER_PACKETS: usize = 50;
|
||||
/// Buffer for maximal 0.5 s without playing anything.
|
||||
const MAX_BUFFER_TIME: usize = 48_000 / 2;
|
||||
/// Duplicate or remove every `step` sample when speeding-up.
|
||||
const SPEED_CHANGE_STEPS: usize = 100;
|
||||
/// The usual amount of samples in a frame.
|
||||
///
|
||||
/// Use 48 kHz, 20 ms frames (50 per second) and mono data (1 channel).
|
||||
/// This means 1920 samples and 7.5 kiB.
|
||||
const USUAL_FRAME_SIZE: usize = 48000 / 50;
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum Error {
|
||||
#[error("Failed to create opus decoder: {0}")]
|
||||
CreateDecoder(#[source] audiopus::Error),
|
||||
#[error("Opus decode failed: {error} (packet: {packet:?})")]
|
||||
Decode {
|
||||
#[source]
|
||||
error: audiopus::Error,
|
||||
packet: Option<Vec<u8>>,
|
||||
},
|
||||
#[error("Get duplicate packet id {0}")]
|
||||
Duplicate(u16),
|
||||
#[error("Failed to get packet samples: {0}")]
|
||||
GetPacketSample(#[source] audiopus::Error),
|
||||
#[error("Audio queue is full, dropping")]
|
||||
QueueFull,
|
||||
#[error("Audio packet is too late, dropping (wanted {wanted}, got {got})")]
|
||||
TooLate { wanted: u16, got: u16 },
|
||||
#[error("Packet has too many samples")]
|
||||
TooManySamples,
|
||||
#[error("Only opus audio is supported, ignoring {0:?}")]
|
||||
UnsupportedCodec(CodecType),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct SlidingWindowMinimum<T: Copy + Default + Ord> {
|
||||
/// How long a value stays in the sliding window.
|
||||
size: u8,
|
||||
/// This is a sliding window minimum, it contains
|
||||
/// `(insertion time, value)`.
|
||||
///
|
||||
/// When we insert a value, we can remove all bigger sample counts,
|
||||
/// thus the queue always stays sorted with the minimum at the front
|
||||
/// and the maximum at the back (latest entry).
|
||||
///
|
||||
/// Provides amortized O(1) minimum.
|
||||
/// Source: https://people.cs.uct.ac.za/~ksmith/articles/sliding_window_minimum.html#sliding-window-minimum-algorithm
|
||||
queue: VecDeque<(u8, T)>,
|
||||
/// The current insertion time.
|
||||
cur_time: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct QueuePacket {
|
||||
packet: InAudioBuf,
|
||||
samples: usize,
|
||||
id: u16,
|
||||
}
|
||||
|
||||
/// A queue for audio packets for one audio stream.
|
||||
pub struct AudioQueue {
|
||||
span: Span,
|
||||
decoder: Decoder,
|
||||
pub volume: f32,
|
||||
/// The id of the next packet that should be decoded.
|
||||
///
|
||||
/// Used to check for packet loss.
|
||||
next_id: u16,
|
||||
/// If the last packet was a whisper packet.
|
||||
whispering: bool,
|
||||
packet_buffer: VecDeque<QueuePacket>,
|
||||
/// Amount of samples in the `packet_buffer`.
|
||||
packet_buffer_samples: usize,
|
||||
/// Temporary buffer that contains the samples of one decoded packet.
|
||||
decoded_buffer: Vec<f32>,
|
||||
/// The number of samples in `decoded_buffer` that have been returned.
|
||||
decoded_pos: usize,
|
||||
/// The number of samples in the last packet.
|
||||
last_packet_samples: usize,
|
||||
/// The last `packet_loss_num` packet decodes were a loss.
|
||||
packet_loss_num: usize,
|
||||
/// The amount of samples to buffer until this queue is ready to play.
|
||||
buffering_samples: usize,
|
||||
/// The amount of packets in the buffer when a packet was decoded.
|
||||
///
|
||||
/// Uses the amount of samples in the `packet_buffer` / `USUAL_PACKET_SAMPLES`.
|
||||
/// Used to expand or reduce the buffer.
|
||||
last_buffer_size_min: SlidingWindowMinimum<u8>,
|
||||
last_buffer_size_max: SlidingWindowMinimum<Reverse<u8>>,
|
||||
/// Buffered for this duration.
|
||||
buffered_for_samples: usize,
|
||||
}
|
||||
|
||||
/// Handles incoming audio, has one [`AudioQueue`] per sending client.
|
||||
pub struct AudioHandler<Id: Clone + Debug + Eq + Hash + PartialEq = ClientId> {
|
||||
queues: HashMap<Id, AudioQueue>,
|
||||
/// Buffer this amount of samples for new queues before starting to play.
|
||||
///
|
||||
/// Updated when a new queue gets added.
|
||||
avg_buffer_samples: usize,
|
||||
}
|
||||
|
||||
impl<T: Copy + Default + Ord> SlidingWindowMinimum<T> {
|
||||
fn new(size: u8) -> Self { Self { size, queue: Default::default(), cur_time: 0 } }
|
||||
|
||||
fn push(&mut self, value: T) {
|
||||
while self.queue.back().map(|(_, s)| *s >= value).unwrap_or_default() {
|
||||
self.queue.pop_back();
|
||||
}
|
||||
let i = self.cur_time;
|
||||
self.queue.push_back((i, value));
|
||||
while self
|
||||
.queue
|
||||
.front()
|
||||
.map(|(i, _)| self.cur_time.wrapping_sub(*i) >= self.size)
|
||||
.unwrap_or_default()
|
||||
{
|
||||
self.queue.pop_front();
|
||||
}
|
||||
self.cur_time = self.cur_time.wrapping_add(1);
|
||||
}
|
||||
|
||||
fn get_min(&self) -> T { self.queue.front().map(|(_, s)| *s).unwrap_or_default() }
|
||||
}
|
||||
|
||||
impl AudioQueue {
|
||||
fn new(packet: InAudioBuf) -> Result<Self> {
|
||||
let data = packet.data().data();
|
||||
let opus_packet = data.data().try_into().map_err(Error::GetPacketSample)?;
|
||||
let last_packet_samples =
|
||||
packet::nb_samples(opus_packet, SAMPLE_RATE).map_err(Error::GetPacketSample)?;
|
||||
if last_packet_samples > MAX_BUFFER_SIZE {
|
||||
return Err(Error::TooManySamples);
|
||||
}
|
||||
|
||||
let last_packet_samples = last_packet_samples * CHANNEL_NUM;
|
||||
let whispering = matches!(data, AudioData::S2CWhisper { .. });
|
||||
let decoder = Decoder::new(SAMPLE_RATE, CHANNELS).map_err(Error::CreateDecoder)?;
|
||||
|
||||
// Enable DRED and NoLACE, ignore errors e.g. if unsupported
|
||||
#[cfg(feature = "audiopus-unstable")]
|
||||
let decoder = {
|
||||
let mut decoder = decoder;
|
||||
if let Err(error) = decoder.set_complexity(7) {
|
||||
debug!(%error, "Failed setting opus decoder complexity, ignoring");
|
||||
}
|
||||
decoder
|
||||
};
|
||||
|
||||
let mut res = Self {
|
||||
span: Span::current(),
|
||||
decoder,
|
||||
volume: 1.0,
|
||||
next_id: data.id(),
|
||||
whispering,
|
||||
packet_buffer: Default::default(),
|
||||
packet_buffer_samples: 0,
|
||||
decoded_buffer: Default::default(),
|
||||
decoded_pos: 0,
|
||||
last_packet_samples,
|
||||
packet_loss_num: 0,
|
||||
buffering_samples: 0,
|
||||
last_buffer_size_min: SlidingWindowMinimum::new(LAST_BUFFER_SIZE_COUNT),
|
||||
last_buffer_size_max: SlidingWindowMinimum::<Reverse<u8>>::new(LAST_BUFFER_SIZE_COUNT),
|
||||
buffered_for_samples: 0,
|
||||
};
|
||||
res.add_buffer_size(0);
|
||||
res.add_packet(packet)?;
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
pub fn get_decoder(&self) -> &Decoder { &self.decoder }
|
||||
pub fn is_whispering(&self) -> bool { self.whispering }
|
||||
|
||||
/// Size is in samples.
|
||||
fn add_buffer_size(&mut self, size: usize) {
|
||||
if let Ok(size) = (size / USUAL_FRAME_SIZE).try_into() {
|
||||
self.last_buffer_size_min.push(size);
|
||||
self.last_buffer_size_max.push(Reverse(size));
|
||||
} else {
|
||||
warn!(parent: &self.span, size, "Failed to put amount of packets into an u8");
|
||||
}
|
||||
}
|
||||
|
||||
/// The approximate deviation of the buffer size.
|
||||
fn get_deviation(&self) -> u8 {
|
||||
let min = self.last_buffer_size_min.get_min();
|
||||
let max = self.last_buffer_size_max.get_min();
|
||||
max.0 - min
|
||||
}
|
||||
|
||||
fn add_packet(&mut self, packet: InAudioBuf) -> Result<()> {
|
||||
let _span = self.span.enter();
|
||||
if self.packet_buffer.len() >= MAX_BUFFER_PACKETS {
|
||||
return Err(Error::QueueFull);
|
||||
}
|
||||
let samples;
|
||||
if packet.data().data().data().len() <= 1 {
|
||||
// End of stream
|
||||
samples = 0;
|
||||
} else {
|
||||
let opus_packet =
|
||||
packet.data().data().data().try_into().map_err(Error::GetPacketSample)?;
|
||||
samples =
|
||||
packet::nb_samples(opus_packet, SAMPLE_RATE).map_err(Error::GetPacketSample)?;
|
||||
if samples > MAX_BUFFER_SIZE {
|
||||
return Err(Error::TooManySamples);
|
||||
}
|
||||
}
|
||||
|
||||
let id = packet.data().data().id();
|
||||
let packet = QueuePacket { packet, samples, id };
|
||||
if id.wrapping_sub(self.next_id) > MAX_BUFFER_PACKETS as u16 {
|
||||
return Err(Error::TooLate { wanted: self.next_id, got: id });
|
||||
}
|
||||
|
||||
// Put into first spot where the id is smaller
|
||||
let i = self.packet_buffer.len()
|
||||
- self
|
||||
.packet_buffer
|
||||
.iter()
|
||||
.enumerate()
|
||||
.rev()
|
||||
.take_while(|(_, p)| p.id.wrapping_sub(id) <= MAX_BUFFER_PACKETS as u16)
|
||||
.count();
|
||||
// Check for duplicate packet
|
||||
if let Some(p) = self.packet_buffer.get(i) {
|
||||
if p.id == packet.id {
|
||||
return Err(Error::Duplicate(p.id));
|
||||
}
|
||||
}
|
||||
|
||||
trace!("Insert packet {} at {}", id, i);
|
||||
let last_id = self.packet_buffer.back().map(|p| p.id.wrapping_add(1)).unwrap_or(id);
|
||||
if last_id <= id {
|
||||
self.buffering_samples = self.buffering_samples.saturating_sub(samples);
|
||||
// Reduce buffering counter by lost packets if there are some
|
||||
self.buffering_samples = self
|
||||
.buffering_samples
|
||||
.saturating_sub(usize::from(id - last_id) * self.last_packet_samples);
|
||||
}
|
||||
|
||||
self.packet_buffer_samples += packet.samples;
|
||||
self.packet_buffer.insert(i, packet);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn decode_packet(&mut self, packet: Option<&QueuePacket>, fec: bool) -> Result<()> {
|
||||
let _span = self.span.clone().entered();
|
||||
trace!(has_packet = packet.is_some(), fec, "Decoding packet");
|
||||
let packet_data;
|
||||
let len;
|
||||
if let Some(p) = packet {
|
||||
packet_data =
|
||||
Some(p.packet.data().data().data().try_into().map_err(Error::GetPacketSample)?);
|
||||
len = p.samples;
|
||||
self.whispering = matches!(p.packet.data().data(), AudioData::S2CWhisper { .. });
|
||||
} else {
|
||||
packet_data = None;
|
||||
len = self.last_packet_samples;
|
||||
}
|
||||
self.packet_loss_num += 1;
|
||||
|
||||
let orig_buffer_len = self.decoded_buffer.len();
|
||||
self.decoded_buffer.resize(orig_buffer_len + len * CHANNEL_NUM, 0.0);
|
||||
let len = self
|
||||
.decoder
|
||||
.decode_float(
|
||||
packet_data,
|
||||
(&mut self.decoded_buffer[orig_buffer_len..])
|
||||
.try_into()
|
||||
.map_err(Error::GetPacketSample)?,
|
||||
fec,
|
||||
)
|
||||
.map_err(|e| Error::Decode {
|
||||
error: e,
|
||||
packet: packet.map(|p| p.packet.raw_data().to_vec()),
|
||||
})?;
|
||||
self.last_packet_samples = len;
|
||||
self.decoded_buffer.truncate(orig_buffer_len + len * CHANNEL_NUM);
|
||||
|
||||
// Update packet_loss_num
|
||||
if packet.is_some() && !fec {
|
||||
self.packet_loss_num = 0;
|
||||
}
|
||||
|
||||
// Update last_buffer_size
|
||||
let mut count = self.packet_buffer_samples;
|
||||
if let Some(last) = self.packet_buffer.back() {
|
||||
// Lost packets
|
||||
trace!(
|
||||
last.id,
|
||||
next_id = self.next_id,
|
||||
first_id = self.packet_buffer.front().unwrap().id,
|
||||
buffer_len = self.packet_buffer.len(),
|
||||
"Ids"
|
||||
);
|
||||
count += (usize::from(last.id.wrapping_sub(self.next_id)) + 1
|
||||
- self.packet_buffer.len())
|
||||
* self.last_packet_samples;
|
||||
}
|
||||
self.add_buffer_size(count);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decode data and return the requested length of buffered data.
|
||||
///
|
||||
/// Returns `true` in the second return value when the stream ended,
|
||||
/// `false` when it continues normally.
|
||||
pub fn get_next_data(&mut self, len: usize) -> Result<(&[f32], bool)> {
|
||||
let _span = self.span.clone().entered();
|
||||
if self.buffering_samples > 0 {
|
||||
if self.buffered_for_samples >= MAX_BUFFER_TIME {
|
||||
self.buffering_samples = 0;
|
||||
self.buffered_for_samples = 0;
|
||||
trace!(
|
||||
buffered_for_samples = self.buffered_for_samples,
|
||||
buffering_samples = self.buffering_samples,
|
||||
"Buffered for too long"
|
||||
);
|
||||
} else {
|
||||
self.buffered_for_samples += len;
|
||||
trace!(
|
||||
buffered_for_samples = self.buffered_for_samples,
|
||||
buffering_samples = self.buffering_samples,
|
||||
"Buffering"
|
||||
);
|
||||
return Ok((&[], false));
|
||||
}
|
||||
}
|
||||
// Need to refill buffer
|
||||
self.decoded_buffer.drain(..self.decoded_pos);
|
||||
|
||||
while self.decoded_buffer.len() < len {
|
||||
trace!(decoded_buffer = self.decoded_buffer.len(), len, "get_next_data");
|
||||
|
||||
// Decode a packet
|
||||
if let Some(packet) = self.packet_buffer.pop_front() {
|
||||
if packet.packet.data().data().data().len() <= 1 {
|
||||
// End of stream
|
||||
return Ok((&self.decoded_buffer, true));
|
||||
}
|
||||
|
||||
self.packet_buffer_samples -= packet.samples;
|
||||
let cur_id = self.next_id;
|
||||
self.next_id = self.next_id.wrapping_add(1);
|
||||
if packet.id != cur_id {
|
||||
debug_assert!(
|
||||
packet.id.wrapping_sub(cur_id) < MAX_BUFFER_PACKETS as u16,
|
||||
"Invalid packet queue state: {} < {}",
|
||||
packet.id,
|
||||
cur_id
|
||||
);
|
||||
// Packet loss
|
||||
debug!(need = cur_id, have = packet.id, "Audio packet loss");
|
||||
if packet.id == self.next_id {
|
||||
// Can use forward-error-correction
|
||||
self.decode_packet(Some(&packet), true)?;
|
||||
} else {
|
||||
self.decode_packet(None, false)?;
|
||||
}
|
||||
self.packet_buffer_samples += packet.samples;
|
||||
self.packet_buffer.push_front(packet);
|
||||
} else {
|
||||
self.decode_packet(Some(&packet), false)?;
|
||||
}
|
||||
} else {
|
||||
debug!("No packets in queue");
|
||||
// Packet loss or end of stream
|
||||
self.decode_packet(None, false)?;
|
||||
}
|
||||
|
||||
if self.last_packet_samples == 0 {
|
||||
break;
|
||||
}
|
||||
|
||||
// Check if we should speed-up playback
|
||||
let min = self.last_buffer_size_min.get_min();
|
||||
let dev = self.get_deviation();
|
||||
if min > (MAX_BUFFER_SIZE / USUAL_FRAME_SIZE) as u8 {
|
||||
debug!(min, "Truncating buffer");
|
||||
// Throw out all but min samples
|
||||
let mut keep_samples = 0;
|
||||
let keep = self
|
||||
.packet_buffer
|
||||
.iter()
|
||||
.rev()
|
||||
.take_while(|p| {
|
||||
keep_samples += p.samples;
|
||||
keep_samples < usize::from(min) + USUAL_FRAME_SIZE
|
||||
})
|
||||
.count();
|
||||
let len = self.packet_buffer.len() - keep;
|
||||
self.packet_buffer.drain(..len);
|
||||
self.packet_buffer_samples = self.packet_buffer.iter().map(|p| p.samples).sum();
|
||||
if let Some(p) = self.packet_buffer.front() {
|
||||
self.next_id = p.id;
|
||||
}
|
||||
} else if min > dev {
|
||||
// Speed-up
|
||||
debug!(
|
||||
min,
|
||||
cur_packet_count = self.packet_buffer.len(),
|
||||
last_packet_samples = self.last_packet_samples,
|
||||
dev,
|
||||
"Speed-up buffer"
|
||||
);
|
||||
let start = self.decoded_buffer.len() - self.last_packet_samples * CHANNEL_NUM;
|
||||
for i in 0..(self.last_packet_samples / SPEED_CHANGE_STEPS) {
|
||||
let i = start + i * (SPEED_CHANGE_STEPS - 1) * CHANNEL_NUM;
|
||||
self.decoded_buffer.drain(i..(i + CHANNEL_NUM));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.decoded_pos = len;
|
||||
Ok((&self.decoded_buffer[..len], false))
|
||||
}
|
||||
}
|
||||
|
||||
impl<Id: Clone + Debug + Eq + Hash + PartialEq> Default for AudioHandler<Id> {
|
||||
fn default() -> Self { Self { queues: Default::default(), avg_buffer_samples: 0 } }
|
||||
}
|
||||
|
||||
impl<Id: Clone + Debug + Eq + Hash + PartialEq> AudioHandler<Id> {
|
||||
pub fn new() -> Self { Default::default() }
|
||||
|
||||
/// Delete all queues
|
||||
pub fn reset(&mut self) { self.queues.clear(); }
|
||||
|
||||
pub fn get_queues(&self) -> &HashMap<Id, AudioQueue> { &self.queues }
|
||||
pub fn get_mut_queues(&mut self) -> &mut HashMap<Id, AudioQueue> { &mut self.queues }
|
||||
|
||||
/// `buf` is not cleared before filling it.
|
||||
///
|
||||
/// Returns the clients that are not talking anymore.
|
||||
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<Id> {
|
||||
self.fill_buffer_with_proc(buf, |_, _| {})
|
||||
}
|
||||
|
||||
/// `buf` is not cleared before filling it.
|
||||
///
|
||||
/// Same as [`fill_buffer`] but before merging a queue into the output buffer, a preprocessor
|
||||
/// function is called. The queue volume is applied after calling the preprocessor.
|
||||
///
|
||||
/// Returns the clients that are not talking anymore.
|
||||
pub fn fill_buffer_with_proc<F: FnMut(&Id, &[f32])>(
|
||||
&mut self, buf: &mut [f32], mut handle: F,
|
||||
) -> Vec<Id> {
|
||||
trace!(len = buf.len(), "Filling audio buffer");
|
||||
let mut to_remove = Vec::new();
|
||||
for (id, queue) in self.queues.iter_mut() {
|
||||
if queue.packet_loss_num >= MAX_PACKET_LOSSES {
|
||||
debug!(packet_loss_num = queue.packet_loss_num, "Removing talker");
|
||||
to_remove.push(id.clone());
|
||||
continue;
|
||||
}
|
||||
|
||||
let vol = queue.volume;
|
||||
match queue.get_next_data(buf.len()) {
|
||||
Err(error) => {
|
||||
warn!(%error, "Failed to decode audio packet");
|
||||
}
|
||||
Ok((r, is_end)) => {
|
||||
handle(id, r);
|
||||
for i in 0..r.len() {
|
||||
buf[i] += r[i] * vol;
|
||||
}
|
||||
if is_end {
|
||||
to_remove.push(id.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for id in &to_remove {
|
||||
self.queues.remove(id);
|
||||
}
|
||||
to_remove
|
||||
}
|
||||
|
||||
/// Add a packet to the audio queue.
|
||||
///
|
||||
/// If a new client started talking, returns the id of this client.
|
||||
pub fn handle_packet(&mut self, id: Id, packet: InAudioBuf) -> Result<Option<Id>> {
|
||||
let empty = packet.data().data().data().len() <= 1;
|
||||
let codec = packet.data().data().codec();
|
||||
if codec != CodecType::OpusMusic && codec != CodecType::OpusVoice {
|
||||
return Err(Error::UnsupportedCodec(codec));
|
||||
}
|
||||
|
||||
if let Some(queue) = self.queues.get_mut(&id) {
|
||||
queue.add_packet(packet)?;
|
||||
Ok(None)
|
||||
} else {
|
||||
if empty {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let _span = info_span!("audio queue", client = ?id);
|
||||
trace!("Adding talker");
|
||||
let mut queue = AudioQueue::new(packet)?;
|
||||
if !self.queues.is_empty() {
|
||||
// Update avg_buffer_samples
|
||||
self.avg_buffer_samples = USUAL_FRAME_SIZE
|
||||
+ self
|
||||
.queues
|
||||
.values()
|
||||
.map(|q| usize::from(q.last_buffer_size_min.get_min()))
|
||||
.sum::<usize>() / self.queues.len();
|
||||
}
|
||||
queue.buffering_samples = self.avg_buffer_samples;
|
||||
self.queues.insert(id.clone(), queue);
|
||||
Ok(Some(id))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use anyhow::{Result, bail};
|
||||
use audiopus::coder::Encoder;
|
||||
use tsproto_packets::packets::{Direction, OutAudio};
|
||||
|
||||
use super::*;
|
||||
use crate::tests::create_logger;
|
||||
|
||||
enum SimulateAction {
|
||||
CreateEncoder,
|
||||
/// Create packet with id.
|
||||
///
|
||||
/// The `bool` is `false` if packet handling should fail.
|
||||
ReceivePacket(u16, bool),
|
||||
ReceiveRaw(u16, Vec<u8>),
|
||||
/// Fetch audio of this sample count and expect a certain packet id.
|
||||
FillBuffer(usize, Option<u16>),
|
||||
/// Custom check
|
||||
Check(Box<dyn FnOnce(&AudioHandler<ClientId>)>),
|
||||
}
|
||||
|
||||
/// Helper function to check an audio packet.
|
||||
#[allow(dead_code)]
|
||||
fn check_packet(data: &[u8]) -> Result<()> {
|
||||
create_logger();
|
||||
let mut handler = AudioHandler::<ClientId>::new();
|
||||
let id = ClientId(0);
|
||||
let mut buf = vec![0.0; 48_000 / 100 * 2];
|
||||
|
||||
// Sometimes, TS sends short, non-opus packets
|
||||
let packet =
|
||||
OutAudio::new(&AudioData::S2C { id: 30, codec: CodecType::OpusMusic, from: 0, data });
|
||||
let input = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
|
||||
handler.handle_packet(id, input)?;
|
||||
|
||||
handler.fill_buffer(&mut buf);
|
||||
handler.fill_buffer(&mut buf);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn simulate(actions: Vec<SimulateAction>) -> Result<()> {
|
||||
let mut encoder = None;
|
||||
let mut opus_output = [0; 1275]; // Max size for an opus packet
|
||||
let id = ClientId(0);
|
||||
create_logger();
|
||||
let mut handler = AudioHandler::<ClientId>::new();
|
||||
|
||||
for a in actions {
|
||||
println!("\nCurrent state");
|
||||
for q in &handler.queues {
|
||||
print!("Queue {:?}:", q.0);
|
||||
for p in &q.1.packet_buffer {
|
||||
print!(" {:?},", p);
|
||||
}
|
||||
println!();
|
||||
}
|
||||
|
||||
match a {
|
||||
SimulateAction::CreateEncoder => {
|
||||
encoder = Some(Encoder::new(
|
||||
audiopus::SampleRate::Hz48000,
|
||||
audiopus::Channels::Mono,
|
||||
audiopus::Application::Voip,
|
||||
)?);
|
||||
}
|
||||
SimulateAction::ReceivePacket(i, success) => {
|
||||
let e = encoder.as_mut().unwrap();
|
||||
let data = vec![i as f32; USUAL_FRAME_SIZE];
|
||||
let len = e.encode_float(&data, &mut opus_output[..])?;
|
||||
let packet = OutAudio::new(&AudioData::S2C {
|
||||
id: i,
|
||||
codec: CodecType::OpusMusic,
|
||||
from: 0,
|
||||
data: &opus_output[..len],
|
||||
});
|
||||
let input = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
|
||||
if handler.handle_packet(id, input).is_ok() != success {
|
||||
bail!("handle_packet returned {:?} but expected {:?}", !success, success);
|
||||
}
|
||||
}
|
||||
SimulateAction::ReceiveRaw(i, data) => {
|
||||
let packet = OutAudio::new(&AudioData::S2C {
|
||||
id: i,
|
||||
codec: CodecType::OpusMusic,
|
||||
from: 0,
|
||||
data: &data,
|
||||
});
|
||||
let input = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
|
||||
let _ = handler.handle_packet(id, input);
|
||||
}
|
||||
SimulateAction::FillBuffer(size, expect) => {
|
||||
let mut buf = vec![0.0; size * 2]; // Stereo
|
||||
let cur_packet_id =
|
||||
handler.queues.get(&id).and_then(|q| q.packet_buffer.front()).map(|p| p.id);
|
||||
handler.fill_buffer(&mut buf);
|
||||
let next_packet_id =
|
||||
handler.queues.get(&id).and_then(|q| q.packet_buffer.front()).map(|p| p.id);
|
||||
|
||||
if expect.is_some() {
|
||||
assert_eq!(expect, cur_packet_id);
|
||||
assert_ne!(cur_packet_id, next_packet_id);
|
||||
}
|
||||
|
||||
/*if let Some(e) = expect {
|
||||
let e = *e as f32;
|
||||
for b in &buf {
|
||||
if (*b - e).abs() > 0.01 {
|
||||
bail!("Buffer contains wrong value, \
|
||||
expected {}: {:?}", e, buf);
|
||||
}
|
||||
}
|
||||
}*/
|
||||
}
|
||||
SimulateAction::Check(f) => {
|
||||
f(&handler);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sliding_window_minimum() {
|
||||
let data = &[
|
||||
(5, 5),
|
||||
(6, 5),
|
||||
(3, 3),
|
||||
(4, 3),
|
||||
(6, 3),
|
||||
(5, 3),
|
||||
(6, 3),
|
||||
(6, 4),
|
||||
(6, 5),
|
||||
(6, 5),
|
||||
(6, 6),
|
||||
(7, 6),
|
||||
(5, 5),
|
||||
];
|
||||
let mut window = SlidingWindowMinimum::new(5);
|
||||
assert_eq!(window.get_min(), 0);
|
||||
for (i, (val, min)) in data.iter().enumerate() {
|
||||
println!("{:?}", window);
|
||||
window.push(*val);
|
||||
assert_eq!(window.get_min(), *min, "Failed in iteration {} ({:?})", i, window);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sliding_window_minimum_full() {
|
||||
let mut window = SlidingWindowMinimum::new(255);
|
||||
window.push(1);
|
||||
assert_eq!(window.get_min(), 1);
|
||||
for _ in 0..254 {
|
||||
window.push(2);
|
||||
}
|
||||
assert_eq!(window.get_min(), 1);
|
||||
window.push(2);
|
||||
assert_eq!(window.get_min(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packets_wrapping() {
|
||||
create_logger();
|
||||
let mut handler = AudioHandler::<ClientId>::new();
|
||||
let id = ClientId(0);
|
||||
let mut buf = vec![0.0; 48_000 / 100 * 2];
|
||||
|
||||
for i in 0..100 {
|
||||
let packet = OutAudio::new(&AudioData::S2C {
|
||||
id: 65_500u16.wrapping_add(i),
|
||||
codec: CodecType::OpusMusic,
|
||||
from: 0,
|
||||
data: &[0, 0, 0, 0, 0, 0, 0],
|
||||
});
|
||||
let input = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
|
||||
handler.handle_packet(id, input).unwrap();
|
||||
|
||||
if i > 5 {
|
||||
handler.fill_buffer(&mut buf);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[quickcheck_macros::quickcheck]
|
||||
fn short_packet_quickcheck(data: Vec<Vec<u8>>) {
|
||||
create_logger();
|
||||
let mut handler = AudioHandler::<ClientId>::new();
|
||||
let id = ClientId(0);
|
||||
let mut buf = vec![0.0; 48_000 / 100 * 2];
|
||||
|
||||
for p in data {
|
||||
// Sometimes, TS sends short, non-opus packets
|
||||
let packet = OutAudio::new(&AudioData::S2C {
|
||||
id: 30,
|
||||
codec: CodecType::OpusMusic,
|
||||
from: 0,
|
||||
data: &p,
|
||||
});
|
||||
let input = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
|
||||
let _ = handler.handle_packet(id, input);
|
||||
|
||||
handler.fill_buffer(&mut buf);
|
||||
handler.fill_buffer(&mut buf);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packets_wrapping2() -> Result<()> {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for i in 0..100 {
|
||||
let i = 65_500u16.wrapping_add(i);
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
|
||||
}
|
||||
for _ in 0..4 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silence() -> Result<()> {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for _ in 0..100 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reversed() -> Result<()> {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for i in 0..5 {
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
|
||||
}
|
||||
a.push(SimulateAction::ReceivePacket(4, false));
|
||||
a.push(SimulateAction::ReceivePacket(3, false));
|
||||
for _ in 0..4 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate() -> Result<()> {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
a.push(SimulateAction::ReceivePacket(0, true));
|
||||
a.push(SimulateAction::ReceivePacket(0, false));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(0)));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn big_whole() -> Result<()> {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for i in 27120..27124 {
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
|
||||
}
|
||||
a.push(SimulateAction::ReceiveRaw(27124, vec![2]));
|
||||
for _ in 0..10 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
for i in 27339..27349 {
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
for _ in 0..4 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_packet() -> Result<()> {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for i in 0..10 {
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
|
||||
}
|
||||
a.push(SimulateAction::ReceiveRaw(10, vec![]));
|
||||
for _ in 0..4 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packet_loss() -> Result<()> {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
a.push(SimulateAction::ReceivePacket(50, true));
|
||||
a.push(SimulateAction::ReceivePacket(53, true));
|
||||
for _ in 0..8 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packet_wrapping_loss() -> Result<()> {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
a.push(SimulateAction::ReceivePacket(65534, true));
|
||||
a.push(SimulateAction::ReceivePacket(0, true));
|
||||
for _ in 0..7 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
pub use ts_bookkeeping::data::exts::*;
|
||||
pub use ts_bookkeeping::messages::OutMessageTrait;
|
||||
|
||||
pub use crate::OutCommandExt as _;
|
||||
@@ -0,0 +1,514 @@
|
||||
//! Resolve TeamSpeak server addresses of any kind.
|
||||
// Changes with TeamSpeak client 3.1:
|
||||
// https://support.teamspeakusa.com/index.php?/Knowledgebase/Article/View/332
|
||||
|
||||
use std::net::{IpAddr, Ipv6Addr, SocketAddr};
|
||||
use std::str;
|
||||
|
||||
use futures::prelude::*;
|
||||
use hickory_net::proto::rr::RData;
|
||||
use hickory_resolver::TokioResolver;
|
||||
use hickory_resolver::config::{CLOUDFLARE, ResolverConfig, ResolverOpts};
|
||||
use hickory_resolver::net::runtime::TokioRuntimeProvider;
|
||||
use itertools::Itertools;
|
||||
use rand::RngExt;
|
||||
use thiserror::Error;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{self, TcpStream};
|
||||
use tokio::time::Duration;
|
||||
use tracing::{debug, instrument, warn};
|
||||
|
||||
const DEFAULT_PORT: u16 = 9987;
|
||||
const DNS_PREFIX_TCP: &str = "_tsdns._tcp.";
|
||||
const DNS_PREFIX_UDP: &str = "_ts3._udp.";
|
||||
const NICKNAME_LOOKUP_ADDRESS: &str = "https://named.myteamspeak.com/lookup";
|
||||
/// Wait this amount of seconds before giving up.
|
||||
const TIMEOUT_SECONDS: u64 = 10;
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum Error {
|
||||
#[error("Failed to create resolver: {0}")]
|
||||
CreateResolver(#[source] hickory_net::NetError),
|
||||
#[error("Invalid IPv4 address")]
|
||||
InvalidIp4Address,
|
||||
#[error("Invalid IPv6 address")]
|
||||
InvalidIp6Address,
|
||||
#[error("Invalid IP address")]
|
||||
InvalidIpAddress,
|
||||
#[error("Not a valid nickname")]
|
||||
InvalidNickname,
|
||||
#[error("Failed to parse port: {0}")]
|
||||
InvalidPort(#[source] std::num::ParseIntError),
|
||||
#[error("Failed to contact {0} server: {1}")]
|
||||
Io(&'static str, #[source] std::io::Error),
|
||||
#[error("Failed to parse url: {0}")]
|
||||
NicknameParseUrl(#[source] url::ParseError),
|
||||
#[error("Failed to resolve nickname: {0}")]
|
||||
NicknameResolve(#[source] reqwest::Error),
|
||||
#[error("Failed to resolve hostname: {0}")]
|
||||
ResolveHost(#[source] tokio::io::Error),
|
||||
#[error("Failed to get SRV record")]
|
||||
SrvLookup(#[source] hickory_net::NetError),
|
||||
#[error("tsdns did not return an ip address but {0:?}")]
|
||||
TsdnsAddressInvalidResponse(String),
|
||||
#[error("tsdns server does not know the address")]
|
||||
TsdnsAddressNotFound,
|
||||
#[error("Failed to parse tsdns response: {0}")]
|
||||
TsdnsParseResponse(#[source] std::str::Utf8Error),
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum ParseIpResult<'a> {
|
||||
Addr(SocketAddr),
|
||||
Other(&'a str, Option<u16>),
|
||||
}
|
||||
|
||||
/// Beware that this may be slow because it tries all available methods.
|
||||
///
|
||||
/// The following methods are tried:
|
||||
/// 1. If the address is an ip, the ip is returned
|
||||
/// 1. Server nicknames are resolved by a http request to TeamSpeak
|
||||
/// 1. The SRV record at `_ts3._udp.<address>`
|
||||
/// 1. The SRV record at `_tsdns._tcp.address.tld` to get the address of a tsdns
|
||||
/// server, e.g. when the address is `ts3.subdomain.from.com`, the SRV record
|
||||
/// at `_tsdns._tcp.from.com` is requested
|
||||
/// 1. Directly resolve the address to an ip address
|
||||
///
|
||||
/// If a port is given with `:port`, it overwrites the automatically determined
|
||||
/// port. IPv6 addresses are put in square brackets when a port is present:
|
||||
/// `[::1]:9987`
|
||||
#[instrument]
|
||||
pub fn resolve(address: String) -> impl Stream<Item = Result<SocketAddr>> {
|
||||
debug!("Starting resolve");
|
||||
let addr;
|
||||
let port;
|
||||
match parse_ip(&address) {
|
||||
Ok(ParseIpResult::Addr(res)) => {
|
||||
return stream::once(future::ok(res)).left_stream();
|
||||
}
|
||||
Ok(ParseIpResult::Other(a, p)) => {
|
||||
addr = a.to_string();
|
||||
port = p;
|
||||
if let Some(port) = port {
|
||||
debug!(port, "Found port");
|
||||
}
|
||||
}
|
||||
Err(res) => return stream::once(future::err(res)).left_stream(),
|
||||
}
|
||||
|
||||
// Resolve as nickname
|
||||
let res = if !address.contains('.') && addr != "localhost" {
|
||||
debug!("Resolving nickname");
|
||||
// Could be a server nickname
|
||||
resolve_nickname(address.clone())
|
||||
.map_ok(move |mut addr| {
|
||||
if let Some(port) = port {
|
||||
addr.set_port(port);
|
||||
}
|
||||
addr
|
||||
})
|
||||
.left_stream()
|
||||
} else {
|
||||
stream::once(future::err(Error::InvalidNickname)).right_stream()
|
||||
};
|
||||
|
||||
// The system config does not yet work on android:
|
||||
// https://github.com/bluejekyll/trust-dns/issues/652
|
||||
let addr2 = addr.clone();
|
||||
// TODO Move current span into stream
|
||||
let res = res.chain(
|
||||
stream::once(async move {
|
||||
let resolver = create_resolver()?;
|
||||
|
||||
// Try to get the address by an SRV record
|
||||
Result::<_>::Ok(resolve_srv(resolver, format!("{DNS_PREFIX_UDP}{addr2}.")))
|
||||
})
|
||||
.try_flatten(),
|
||||
);
|
||||
|
||||
// Try to get the address of a tsdns server by an SRV record
|
||||
let addr2 = addr.clone();
|
||||
// TODO Move current span into stream
|
||||
let res = res.chain(
|
||||
stream::once(async move {
|
||||
let resolver = create_resolver()?;
|
||||
// Trim address to two components
|
||||
let name = if let Some(i) = addr2.rfind('.').and_then(|i| addr2[..i].rfind('.')) {
|
||||
&addr2[i + 1..]
|
||||
} else {
|
||||
&addr2
|
||||
};
|
||||
// Pick the first srv record of the first server that answers
|
||||
Result::<_>::Ok(resolve_srv(resolver, format!("{DNS_PREFIX_TCP}{name}.")).and_then(
|
||||
move |srv| {
|
||||
let address = address.clone();
|
||||
async move {
|
||||
// Got tsdns server
|
||||
let mut addr = resolve_tsdns(srv, &address).await?;
|
||||
if let Some(port) = port {
|
||||
// Overwrite port if it was specified
|
||||
addr.set_port(port);
|
||||
}
|
||||
Ok(addr)
|
||||
}
|
||||
},
|
||||
))
|
||||
})
|
||||
.try_flatten(),
|
||||
);
|
||||
|
||||
// Interpret as normal address and resolve with system resolver
|
||||
let res = res.chain(
|
||||
stream::once(async move {
|
||||
let res = net::lookup_host((addr.as_str(), port.unwrap_or(DEFAULT_PORT)))
|
||||
.await
|
||||
.map_err(Error::ResolveHost)?
|
||||
.map(Ok)
|
||||
.collect::<Vec<_>>();
|
||||
Result::<_>::Ok(stream::iter(res))
|
||||
})
|
||||
.try_flatten(),
|
||||
);
|
||||
|
||||
// TODO Move current span into stream
|
||||
tokio_stream::StreamExt::timeout(res, Duration::from_secs(TIMEOUT_SECONDS))
|
||||
.filter_map(move |r: std::result::Result<Result<SocketAddr>, _>| {
|
||||
future::ready(match r {
|
||||
// Timeout
|
||||
Err(_) => None,
|
||||
// Error
|
||||
Ok(Err(error)) => {
|
||||
debug!(%error, "Resolver failed in one step");
|
||||
None
|
||||
}
|
||||
// Success
|
||||
Ok(Ok(r)) => Some(Ok(r)),
|
||||
})
|
||||
})
|
||||
.right_stream()
|
||||
}
|
||||
|
||||
// Windows for some reason automatically adds a link-local address to the dns
|
||||
// resolver. These addresses are usually not reachable and should be filtered out.
|
||||
// See: https://superuser.com/questions/638566/strange-value-in-dns-shown-in-ipconfig
|
||||
const FILTERED_IPS: &[IpAddr] = &[
|
||||
IpAddr::V6(Ipv6Addr::new(0xfec0, 0, 0, 0xffff, 0, 0, 0, 1)),
|
||||
IpAddr::V6(Ipv6Addr::new(0xfec0, 0, 0, 0xffff, 0, 0, 0, 2)),
|
||||
IpAddr::V6(Ipv6Addr::new(0xfec0, 0, 0, 0xffff, 0, 0, 0, 3)),
|
||||
];
|
||||
|
||||
fn create_resolver() -> Result<TokioResolver> {
|
||||
let (config, options) = match hickory_resolver::system_conf::read_system_conf() {
|
||||
Ok((mut config, options)) => {
|
||||
config.name_servers.retain(|ns| !FILTERED_IPS.contains(&ns.ip));
|
||||
(config, options)
|
||||
}
|
||||
Err(error) => {
|
||||
warn!(%error, "Failed to use system dns resolver config");
|
||||
// Fallback
|
||||
(ResolverConfig::udp_and_tcp(&CLOUDFLARE), ResolverOpts::default())
|
||||
}
|
||||
};
|
||||
let mut builder = TokioResolver::builder_with_config(config, TokioRuntimeProvider::default());
|
||||
*builder.options_mut() = options;
|
||||
builder.build().map_err(Error::CreateResolver)
|
||||
}
|
||||
|
||||
fn parse_ip(address: &str) -> Result<ParseIpResult<'_>> {
|
||||
let mut addr = address;
|
||||
let mut port = None;
|
||||
if let Some(pos) = address.rfind(':') {
|
||||
// Either with port or IPv6 address
|
||||
if address.find(':').unwrap() == pos {
|
||||
// Port is appended
|
||||
addr = &address[..pos];
|
||||
port = Some(&address[pos + 1..]);
|
||||
if addr.chars().all(|c| c.is_ascii_digit() || c == '.') {
|
||||
// IPv4 address
|
||||
return Ok(ParseIpResult::Addr(
|
||||
std::net::ToSocketAddrs::to_socket_addrs(address)
|
||||
.map_err(|_| Error::InvalidIp4Address)?
|
||||
.next()
|
||||
.ok_or(Error::InvalidIp4Address)?,
|
||||
));
|
||||
}
|
||||
} else if let Some(pos_bracket) = address.rfind(']') {
|
||||
if pos_bracket < pos {
|
||||
// IPv6 address and port
|
||||
return Ok(ParseIpResult::Addr(
|
||||
std::net::ToSocketAddrs::to_socket_addrs(address)
|
||||
.map_err(|_| Error::InvalidIp6Address)?
|
||||
.next()
|
||||
.ok_or(Error::InvalidIp6Address)?,
|
||||
));
|
||||
} else if pos_bracket == address.len() - 1 && address.starts_with('[') {
|
||||
// IPv6 address
|
||||
return Ok(ParseIpResult::Addr(
|
||||
std::net::ToSocketAddrs::to_socket_addrs(&(
|
||||
&address[1..pos_bracket],
|
||||
DEFAULT_PORT,
|
||||
))
|
||||
.map_err(|_| Error::InvalidIp6Address)?
|
||||
.next()
|
||||
.ok_or(Error::InvalidIp6Address)?,
|
||||
));
|
||||
} else {
|
||||
return Err(Error::InvalidIpAddress);
|
||||
}
|
||||
} else {
|
||||
// IPv6 address
|
||||
return Ok(ParseIpResult::Addr(
|
||||
std::net::ToSocketAddrs::to_socket_addrs(&(address, DEFAULT_PORT))
|
||||
.map_err(|_| Error::InvalidIp6Address)?
|
||||
.next()
|
||||
.ok_or(Error::InvalidIp6Address)?,
|
||||
));
|
||||
}
|
||||
} else if address.chars().all(|c| c.is_ascii_digit() || c == '.') {
|
||||
// IPv4 address
|
||||
return Ok(ParseIpResult::Addr(
|
||||
std::net::ToSocketAddrs::to_socket_addrs(&(address, DEFAULT_PORT))
|
||||
.map_err(|_| Error::InvalidIp4Address)?
|
||||
.next()
|
||||
.ok_or(Error::InvalidIp4Address)?,
|
||||
));
|
||||
}
|
||||
let port = if let Some(port) = port.map(|p| p.parse().map_err(Error::InvalidPort)) {
|
||||
Some(port?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(ParseIpResult::Other(addr, port))
|
||||
}
|
||||
|
||||
pub fn resolve_nickname(nickname: String) -> impl Stream<Item = Result<SocketAddr>> {
|
||||
stream::once(async {
|
||||
let nickname = nickname;
|
||||
let url =
|
||||
reqwest::Url::parse_with_params(NICKNAME_LOOKUP_ADDRESS, Some(("name", &nickname)))
|
||||
.map_err(Error::NicknameParseUrl)?;
|
||||
let body = reqwest::get(url)
|
||||
.await
|
||||
.map_err(Error::NicknameResolve)?
|
||||
.error_for_status()
|
||||
.map_err(Error::NicknameResolve)?
|
||||
.text()
|
||||
.await
|
||||
.map_err(Error::NicknameResolve)?;
|
||||
let addrs = body
|
||||
.split(&['\r', '\n'][..])
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| Result::<_>::Ok(s.to_string()))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
Result::<_>::Ok(
|
||||
stream::iter(addrs)
|
||||
.and_then(|addr| async move {
|
||||
match parse_ip(&addr)? {
|
||||
ParseIpResult::Addr(a) => Ok(stream::once(future::ok(a)).left_stream()),
|
||||
ParseIpResult::Other(a, p) => {
|
||||
let addrs = net::lookup_host((a, p.unwrap_or(DEFAULT_PORT)))
|
||||
.await
|
||||
.map_err(Error::ResolveHost)?
|
||||
.collect::<Vec<_>>();
|
||||
Ok(stream::iter(addrs).map(Result::<_>::Ok).right_stream())
|
||||
}
|
||||
}
|
||||
})
|
||||
.try_flatten(),
|
||||
)
|
||||
})
|
||||
.try_flatten()
|
||||
}
|
||||
|
||||
pub async fn resolve_tsdns<A: net::ToSocketAddrs>(server: A, addr: &str) -> Result<SocketAddr> {
|
||||
let mut stream = TcpStream::connect(server).await.map_err(|e| Error::Io("tsdns", e))?;
|
||||
stream.write_all(addr.as_bytes()).await.map_err(|e| Error::Io("tsdns", e))?;
|
||||
let mut data = Vec::new();
|
||||
stream.read_to_end(&mut data).await.map_err(|e| Error::Io("tsdns", e))?;
|
||||
|
||||
let addr = str::from_utf8(&data).map_err(Error::TsdnsParseResponse)?;
|
||||
if addr.starts_with("404") {
|
||||
return Err(Error::TsdnsAddressNotFound);
|
||||
}
|
||||
match parse_ip(addr)? {
|
||||
ParseIpResult::Addr(a) => Ok(a),
|
||||
_ => Err(Error::TsdnsAddressInvalidResponse(addr.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_srv(resolver: TokioResolver, addr: String) -> impl Stream<Item = Result<SocketAddr>> {
|
||||
stream::once(async {
|
||||
let lookup = resolver.srv_lookup(addr).await.map_err(Error::SrvLookup)?;
|
||||
let srvs = lookup
|
||||
.answers()
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let RData::SRV(srv) = &r.data else { panic!("Unexpected answer") };
|
||||
srv.clone()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let prios = srvs.iter().chunk_by(|srv| srv.priority);
|
||||
let entries = prios.into_iter().sorted_by_key(|(p, _)| *p);
|
||||
|
||||
// Select by weight
|
||||
let mut sorted_entries = Vec::new();
|
||||
for (_, es) in entries {
|
||||
let mut zero_entries = Vec::new();
|
||||
|
||||
// All non-zero entries
|
||||
let mut entries = es
|
||||
.filter_map(|e| {
|
||||
if e.weight == 0 {
|
||||
zero_entries.push(e);
|
||||
None
|
||||
} else {
|
||||
Some(e)
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
while !entries.is_empty() {
|
||||
let weight: u32 = entries.iter().map(|e| e.weight as u32).sum();
|
||||
let mut w = rand::rng().random_range(0..=weight);
|
||||
if w == 0 {
|
||||
// Pick the first entry with weight 0
|
||||
if let Some(i) = entries.iter().position(|e| e.weight == 0) {
|
||||
sorted_entries.push(entries.remove(i));
|
||||
}
|
||||
}
|
||||
for i in 0..entries.len() {
|
||||
let weight = entries[i].weight as u32;
|
||||
if w <= weight {
|
||||
sorted_entries.push(entries.remove(i));
|
||||
break;
|
||||
}
|
||||
w -= weight;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let res = sorted_entries
|
||||
.into_iter()
|
||||
.map(|e| Ok((e.target.to_ascii(), e.port)))
|
||||
.collect::<Vec<Result<(String, u16)>>>();
|
||||
drop(resolver);
|
||||
Ok(stream::iter(res)
|
||||
.and_then(|(e, port)| async move {
|
||||
let res = net::lookup_host((e.as_str(), port))
|
||||
.await
|
||||
.map_err(Error::ResolveHost)?
|
||||
.map(Ok)
|
||||
.collect::<Vec<_>>();
|
||||
Ok(stream::iter(res))
|
||||
})
|
||||
.try_flatten())
|
||||
})
|
||||
.try_flatten()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use crate::tests::create_logger;
|
||||
|
||||
#[test]
|
||||
fn parse_ip_without_port() {
|
||||
let res = parse_ip("127.0.0.1");
|
||||
assert_eq!(
|
||||
res.unwrap(),
|
||||
ParseIpResult::Addr(format!("127.0.0.1:{}", DEFAULT_PORT).parse().unwrap())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ip_with_port() {
|
||||
let res = parse_ip("127.0.0.1:1");
|
||||
assert_eq!(res.unwrap(), ParseIpResult::Addr("127.0.0.1:1".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ip6_without_port() {
|
||||
let res = parse_ip("::");
|
||||
assert_eq!(
|
||||
res.unwrap(),
|
||||
ParseIpResult::Addr(format!("[::]:{}", DEFAULT_PORT).parse().unwrap())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ip6_without_port2() {
|
||||
let res = parse_ip("[::]");
|
||||
assert_eq!(
|
||||
res.unwrap(),
|
||||
ParseIpResult::Addr(format!("[::]:{}", DEFAULT_PORT).parse().unwrap())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ip6_with_port() {
|
||||
let res = parse_ip("[::]:1");
|
||||
assert_eq!(res.unwrap(), ParseIpResult::Addr("[::]:1".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ip_address_without_port() {
|
||||
assert_eq!(parse_ip("localhost").unwrap(), ParseIpResult::Other("localhost", None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ip_address_with_port() {
|
||||
assert_eq!(parse_ip("localhost:1").unwrap(), ParseIpResult::Other("localhost", Some(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ip_with_large_port() {
|
||||
assert!(parse_ip("127.0.0.1:65536").is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resolve_localhost() {
|
||||
create_logger();
|
||||
let res: Vec<_> = resolve("127.0.0.1".into()).map(|r| r.unwrap()).collect().await;
|
||||
let addr = format!("127.0.0.1:{}", DEFAULT_PORT).parse::<SocketAddr>().unwrap();
|
||||
assert_eq!(res.as_slice(), &[addr]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resolve_localhost2() {
|
||||
create_logger();
|
||||
let res: Vec<_> = resolve("localhost".into()).map(|r| r.unwrap()).collect().await;
|
||||
assert!(res.contains(&format!("127.0.0.1:{}", DEFAULT_PORT).parse().unwrap()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resolve_example() {
|
||||
create_logger();
|
||||
let res: Vec<_> = resolve("example.com".into()).map(|r| r.unwrap()).collect().await;
|
||||
assert!(!res.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resolve_splamy_de() {
|
||||
create_logger();
|
||||
|
||||
let res: Vec<_> = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
resolve("splamy.de".into()).map(|r| r.unwrap()).collect(),
|
||||
)
|
||||
.await
|
||||
.expect("Resolve takes unacceptable long");
|
||||
assert!(res.contains(&format!("37.120.179.68:{}", DEFAULT_PORT).parse().unwrap()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resolve_loc() {
|
||||
create_logger();
|
||||
let res: Vec<_> = resolve("loc".into()).map(|r| r.unwrap()).collect().await;
|
||||
assert!(res.contains(&format!("127.0.0.1:{}", DEFAULT_PORT).parse().unwrap()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,477 @@
|
||||
//! The `sync` module contains an easier to use interface for a connection.
|
||||
//!
|
||||
//! It makes it easier to use a connection from multiple threads and use
|
||||
//! `async`/`await` syntax for the cost of a little bit performance.
|
||||
use std::collections::HashMap;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use futures::prelude::*;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tracing::{error, info};
|
||||
use ts_bookkeeping::ChannelId;
|
||||
#[cfg(feature = "audio")]
|
||||
use tsproto_packets::packets::InAudioBuf;
|
||||
#[cfg(feature = "unstable")]
|
||||
use tsproto_packets::packets::OutCommand;
|
||||
use tsproto_packets::packets::InCommandBuf;
|
||||
|
||||
use crate::{
|
||||
events, AudioEvent, DisconnectOptions, Error, InMessage, Result, StreamItem,
|
||||
TemporaryDisconnectReason,
|
||||
};
|
||||
|
||||
enum SyncConMessage {
|
||||
RunFn(Box<dyn FnOnce(&mut SyncConnection) + Send>),
|
||||
#[cfg(feature = "unstable")]
|
||||
SendCommand(OutCommand, oneshot::Sender<Result<()>>),
|
||||
WaitConnected(oneshot::Sender<Result<()>>),
|
||||
Disconnect(DisconnectOptions, oneshot::Sender<Result<()>>),
|
||||
DownloadFile {
|
||||
channel_id: ChannelId,
|
||||
path: String,
|
||||
channel_password: Option<String>,
|
||||
seek_position: Option<u64>,
|
||||
send: oneshot::Sender<Result<super::FileDownloadResult>>,
|
||||
},
|
||||
UploadFile {
|
||||
channel_id: ChannelId,
|
||||
path: String,
|
||||
channel_password: Option<String>,
|
||||
size: u64,
|
||||
overwrite: bool,
|
||||
resume: bool,
|
||||
send: oneshot::Sender<Result<super::FileUploadResult>>,
|
||||
},
|
||||
}
|
||||
|
||||
/// This is a subset of [`StreamItem`](crate::StreamItem).
|
||||
pub enum SyncStreamItem {
|
||||
/// All the incoming book events.
|
||||
///
|
||||
/// If a connection to the server was established this will contain an added event of a server.
|
||||
BookEvents(Vec<events::Event>),
|
||||
/// All incoming messages that are not related to the book.
|
||||
///
|
||||
/// This contains messages like `ChannelListFinished` or `ClientChatComposing`.
|
||||
/// All events related to channels or clients are returned as events in the `BookEvents`
|
||||
/// variant. Other messages handled by tsclientlib, e.g. for filetransfer are also not included
|
||||
/// in these events.
|
||||
MessageEvent(InMessage),
|
||||
/// Received an audio packet.
|
||||
///
|
||||
/// Audio packets can be handled by the [`AudioHandler`](crate::audio::AudioHandler), which
|
||||
/// builds a queue per client and handles packet loss and jitter.
|
||||
#[cfg(feature = "audio")]
|
||||
Audio(InAudioBuf),
|
||||
/// The needed level.
|
||||
IdentityLevelIncreasing(u8),
|
||||
/// This event may occur without an `IdentityLevelIncreasing` event before
|
||||
/// if a new identity is created because no identity was supplied.
|
||||
IdentityLevelIncreased,
|
||||
/// The connection timed out or the server shut down. The connection will be
|
||||
/// rebuilt automatically.
|
||||
DisconnectedTemporarily(TemporaryDisconnectReason),
|
||||
/// The network statistics were updated.
|
||||
///
|
||||
/// This means e.g. the packet loss got a new value. Clients with audio probably want to update
|
||||
/// the packet loss option of opus.
|
||||
NetworkStatsUpdated,
|
||||
/// A change related to audio.
|
||||
AudioChange(AudioEvent),
|
||||
/// TeamsPeach patch: see [`StreamItem::UnknownCommand`](crate::StreamItem::UnknownCommand).
|
||||
UnknownCommand(InCommandBuf),
|
||||
/// TeamsPeach patch: see [`StreamItem::RawCommandCopy`](crate::StreamItem::RawCommandCopy).
|
||||
RawCommandCopy(Vec<u8>),
|
||||
}
|
||||
|
||||
/// A handle for a [`SyncConnection`] which can be sent across threads.
|
||||
///
|
||||
/// All actions like sending messages, downloading and uploading happens through
|
||||
/// a handle.
|
||||
#[derive(Clone)]
|
||||
pub struct SyncConnectionHandle {
|
||||
send: mpsc::Sender<SyncConMessage>,
|
||||
}
|
||||
|
||||
pub struct SyncConnection {
|
||||
con: super::Connection,
|
||||
recv: mpsc::Receiver<SyncConMessage>,
|
||||
send: mpsc::Sender<SyncConMessage>,
|
||||
|
||||
commands: HashMap<super::MessageHandle, oneshot::Sender<Result<()>>>,
|
||||
connects: Vec<oneshot::Sender<Result<()>>>,
|
||||
disconnects: Vec<oneshot::Sender<Result<()>>>,
|
||||
downloads:
|
||||
HashMap<super::FiletransferHandle, oneshot::Sender<Result<super::FileDownloadResult>>>,
|
||||
uploads: HashMap<super::FiletransferHandle, oneshot::Sender<Result<super::FileUploadResult>>>,
|
||||
}
|
||||
|
||||
impl From<super::Connection> for SyncConnection {
|
||||
fn from(con: super::Connection) -> Self {
|
||||
let (send, recv) = mpsc::channel(1);
|
||||
Self {
|
||||
con,
|
||||
recv,
|
||||
send,
|
||||
|
||||
commands: Default::default(),
|
||||
connects: Default::default(),
|
||||
disconnects: Default::default(),
|
||||
downloads: Default::default(),
|
||||
uploads: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for SyncConnection {
|
||||
type Target = super::Connection;
|
||||
#[inline]
|
||||
fn deref(&self) -> &Self::Target { &self.con }
|
||||
}
|
||||
|
||||
impl DerefMut for SyncConnection {
|
||||
#[inline]
|
||||
fn deref_mut(&mut self) -> &mut <Self as Deref>::Target { &mut self.con }
|
||||
}
|
||||
|
||||
impl Stream for SyncConnection {
|
||||
type Item = Result<SyncStreamItem>;
|
||||
fn poll_next(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll<Option<Self::Item>> {
|
||||
let _span = self.con.span.clone().entered();
|
||||
loop {
|
||||
if let Poll::Ready(msg) = self.recv.poll_recv(ctx) {
|
||||
if let Some(msg) = msg {
|
||||
match msg {
|
||||
SyncConMessage::RunFn(f) => f(&mut self),
|
||||
#[cfg(feature = "unstable")]
|
||||
SyncConMessage::SendCommand(arg, send) => {
|
||||
let handle = match self.con.send_command_with_result(arg) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
let _ = send.send(Err(e));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
self.commands.insert(handle, send);
|
||||
}
|
||||
SyncConMessage::WaitConnected(send) => {
|
||||
if self.con.get_state().is_ok() {
|
||||
let _ = send.send(Ok(()));
|
||||
} else {
|
||||
self.connects.push(send);
|
||||
}
|
||||
}
|
||||
SyncConMessage::Disconnect(arg, send) => {
|
||||
match self.con.disconnect(arg) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
let _ = send.send(Err(e));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
self.disconnects.push(send);
|
||||
}
|
||||
SyncConMessage::DownloadFile {
|
||||
channel_id,
|
||||
path,
|
||||
channel_password,
|
||||
seek_position,
|
||||
send,
|
||||
} => {
|
||||
let handle = match self.con.download_file(
|
||||
channel_id,
|
||||
&path,
|
||||
channel_password.as_deref(),
|
||||
seek_position,
|
||||
) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
let _ = send.send(Err(e));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
self.downloads.insert(handle, send);
|
||||
}
|
||||
SyncConMessage::UploadFile {
|
||||
channel_id,
|
||||
path,
|
||||
channel_password,
|
||||
size,
|
||||
overwrite,
|
||||
resume,
|
||||
send,
|
||||
} => {
|
||||
let handle = match self.con.upload_file(
|
||||
channel_id,
|
||||
&path,
|
||||
channel_password.as_deref(),
|
||||
size,
|
||||
overwrite,
|
||||
resume,
|
||||
) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
let _ = send.send(Err(e));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
self.uploads.insert(handle, send);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
} else {
|
||||
error!("Message stream ended unexpectedly");
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
loop {
|
||||
break if let Poll::Ready(item) = self.con.poll_next(ctx) {
|
||||
Poll::Ready(match item {
|
||||
Some(Ok(item)) => Some(Ok(match item {
|
||||
StreamItem::BookEvents(i) => {
|
||||
self.connects.drain(..).for_each(|send| {
|
||||
let _ = send.send(Ok(()));
|
||||
});
|
||||
SyncStreamItem::BookEvents(i)
|
||||
}
|
||||
StreamItem::MessageEvent(i) => SyncStreamItem::MessageEvent(i),
|
||||
#[cfg(feature = "audio")]
|
||||
StreamItem::Audio(i) => SyncStreamItem::Audio(i),
|
||||
StreamItem::IdentityLevelIncreasing(i) => {
|
||||
SyncStreamItem::IdentityLevelIncreasing(i)
|
||||
}
|
||||
StreamItem::IdentityLevelIncreased => {
|
||||
SyncStreamItem::IdentityLevelIncreased
|
||||
}
|
||||
StreamItem::DisconnectedTemporarily(reason) => {
|
||||
SyncStreamItem::DisconnectedTemporarily(reason)
|
||||
}
|
||||
StreamItem::MessageResult(handle, res) => {
|
||||
if let Some(send) = self.commands.remove(&handle) {
|
||||
let _ = send.send(res.map_err(|e| e.into()));
|
||||
} else {
|
||||
info!("Got untracked message result");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
StreamItem::FileDownload(handle, res) => {
|
||||
if let Some(send) = self.downloads.remove(&handle) {
|
||||
let _ = send.send(Ok(res));
|
||||
} else {
|
||||
info!("Got untracked download");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
StreamItem::FileUpload(handle, res) => {
|
||||
if let Some(send) = self.uploads.remove(&handle) {
|
||||
let _ = send.send(Ok(res));
|
||||
} else {
|
||||
info!("Got untracked upload");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
StreamItem::FiletransferFailed(handle, res) => {
|
||||
if let Some(send) = self.downloads.remove(&handle) {
|
||||
let _ = send.send(Err(res));
|
||||
} else if let Some(send) = self.uploads.remove(&handle) {
|
||||
let _ = send.send(Err(res));
|
||||
} else {
|
||||
info!("Got untracked file transfer");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
StreamItem::NetworkStatsUpdated => SyncStreamItem::NetworkStatsUpdated,
|
||||
StreamItem::AudioChange(change) => SyncStreamItem::AudioChange(change),
|
||||
StreamItem::UnknownCommand(cmd) => SyncStreamItem::UnknownCommand(cmd),
|
||||
StreamItem::RawCommandCopy(c) => SyncStreamItem::RawCommandCopy(c),
|
||||
})),
|
||||
Some(Err(e)) => Some(Err(e)),
|
||||
None => {
|
||||
self.disconnects.drain(..).for_each(|send| {
|
||||
let _ = send.send(Ok(()));
|
||||
});
|
||||
None
|
||||
}
|
||||
})
|
||||
} else {
|
||||
Poll::Pending
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SyncConnection {
|
||||
/// Get a handle to the connection that can be sent across threads.
|
||||
#[inline]
|
||||
pub fn get_handle(&self) -> SyncConnectionHandle {
|
||||
SyncConnectionHandle { send: self.send.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
impl SyncConnectionHandle {
|
||||
/// Run a function on the connection.
|
||||
pub async fn with_connection<
|
||||
T: Send + 'static,
|
||||
F: FnOnce(&mut SyncConnection) -> T + Send + 'static,
|
||||
>(
|
||||
&mut self, f: F,
|
||||
) -> Result<T> {
|
||||
let (send, recv) = oneshot::channel();
|
||||
self.send
|
||||
.send(SyncConMessage::RunFn(Box::new(move |con| {
|
||||
let _ = send.send(f(con));
|
||||
})))
|
||||
.await
|
||||
.map_err(|_| Error::ConnectionGone)?;
|
||||
recv.await.map_err(|_| Error::ConnectionGone)
|
||||
}
|
||||
|
||||
/// Adds a `return_code` to the command and returns if the corresponding
|
||||
/// answer is received. If an error occurs, the future will return an error.
|
||||
#[cfg(feature = "unstable")]
|
||||
pub async fn send_command(&mut self, arg: OutCommand) -> Result<()> {
|
||||
let (send, recv) = oneshot::channel();
|
||||
self.send
|
||||
.send(SyncConMessage::SendCommand(arg, send))
|
||||
.await
|
||||
.map_err(|_| Error::ConnectionGone)?;
|
||||
recv.await.map_err(|_| Error::ConnectionGone)?
|
||||
}
|
||||
|
||||
/// This future resolves once the connection is connected to the server.
|
||||
pub async fn wait_until_connected(&mut self) -> Result<()> {
|
||||
let (send, recv) = oneshot::channel();
|
||||
self.send
|
||||
.send(SyncConMessage::WaitConnected(send))
|
||||
.await
|
||||
.map_err(|_| Error::ConnectionGone)?;
|
||||
recv.await.map_err(|_| Error::ConnectionGone)?
|
||||
}
|
||||
|
||||
/// Disconnect from the server.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `options`: Either `None` or `DisconnectOptions`.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Use default options:
|
||||
///
|
||||
/// ```no_run
|
||||
/// # use futures::prelude::*;
|
||||
/// # use tsclientlib::{Connection, ConnectOptions, DisconnectOptions, StreamItem};
|
||||
/// # use tsclientlib::sync::SyncConnection;
|
||||
///
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() {
|
||||
/// let con: SyncConnection = Connection::build("localhost").connect().unwrap().into();
|
||||
/// let mut handle = con.get_handle();
|
||||
/// tokio::spawn(con.for_each(|_| future::ready(())));
|
||||
/// // Wait until connected
|
||||
/// handle.wait_until_connected().await.unwrap();
|
||||
///
|
||||
/// // Disconnect
|
||||
/// handle.disconnect(DisconnectOptions::new()).await.unwrap();
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// Specify a reason and a quit message:
|
||||
///
|
||||
/// ```no_run
|
||||
/// # use futures::prelude::*;
|
||||
/// # use tsclientlib::{Connection, ConnectOptions, DisconnectOptions, Reason, StreamItem};
|
||||
/// # use tsclientlib::sync::SyncConnection;
|
||||
///
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() {
|
||||
/// let con: SyncConnection = Connection::build("localhost").connect().unwrap().into();
|
||||
/// let mut handle = con.get_handle();
|
||||
/// tokio::spawn(con.for_each(|_| future::ready(())));
|
||||
/// // Wait until connected
|
||||
/// handle.wait_until_connected().await.unwrap();
|
||||
///
|
||||
/// // Disconnect
|
||||
/// let options = DisconnectOptions::new()
|
||||
/// .reason(Reason::Clientdisconnect)
|
||||
/// .message("Away for a while");
|
||||
/// handle.disconnect(DisconnectOptions::new()).await.unwrap();
|
||||
/// # }
|
||||
/// ```
|
||||
pub async fn disconnect(&mut self, arg: DisconnectOptions) -> Result<()> {
|
||||
let (send, recv) = oneshot::channel();
|
||||
self.send
|
||||
.send(SyncConMessage::Disconnect(arg, send))
|
||||
.await
|
||||
.map_err(|_| Error::ConnectionGone)?;
|
||||
recv.await.map_err(|_| Error::ConnectionGone)?
|
||||
}
|
||||
|
||||
/// Download a file from a channel of the connected TeamSpeak server.
|
||||
///
|
||||
/// Returns the size of the file and a tcp stream of the requested file.
|
||||
///
|
||||
/// # Example
|
||||
/// Download an icon.
|
||||
///
|
||||
/// ```no_run
|
||||
/// # use tsclientlib::ChannelId;
|
||||
/// # let handle: tsclientlib::sync::SyncConnectionHandle = panic!();
|
||||
/// # let id = 0;
|
||||
/// let download = handle.download_file(ChannelId(0), format!("/icon_{}", id), None, None);
|
||||
/// ```
|
||||
pub async fn download_file(
|
||||
&mut self, channel_id: ChannelId, path: String, channel_password: Option<String>,
|
||||
seek_position: Option<u64>,
|
||||
) -> Result<super::FileDownloadResult> {
|
||||
let (send, recv) = oneshot::channel();
|
||||
self.send
|
||||
.send(SyncConMessage::DownloadFile {
|
||||
channel_id,
|
||||
path,
|
||||
channel_password,
|
||||
seek_position,
|
||||
send,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| Error::ConnectionGone)?;
|
||||
recv.await.map_err(|_| Error::ConnectionGone)?
|
||||
}
|
||||
|
||||
/// Upload a file to a channel of the connected TeamSpeak server.
|
||||
///
|
||||
/// Returns the size of the part which is already uploaded (when resume is
|
||||
/// specified) and a tcp stream where the requested file should be uploaded.
|
||||
///
|
||||
/// # Example
|
||||
/// Upload an avatar.
|
||||
///
|
||||
/// ```no_run
|
||||
/// # use tsclientlib::ChannelId;
|
||||
/// # let handle: tsclientlib::sync::SyncConnectionHandle = panic!();
|
||||
/// # let size = 0;
|
||||
/// let upload = handle.upload_file(ChannelId(0), "/avatar".to_string(), None, size, true, false);
|
||||
/// ```
|
||||
pub async fn upload_file(
|
||||
&mut self, channel_id: ChannelId, path: String, channel_password: Option<String>,
|
||||
size: u64, overwrite: bool, resume: bool,
|
||||
) -> Result<super::FileUploadResult> {
|
||||
let (send, recv) = oneshot::channel();
|
||||
self.send
|
||||
.send(SyncConMessage::UploadFile {
|
||||
channel_id,
|
||||
path,
|
||||
channel_password,
|
||||
size,
|
||||
overwrite,
|
||||
resume,
|
||||
send,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| Error::ConnectionGone)?;
|
||||
recv.await.map_err(|_| Error::ConnectionGone)?
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
use once_cell::sync::Lazy;
|
||||
use ts_bookkeeping::messages::s2c::InMessage;
|
||||
use tsproto_packets::packets::{Direction, Flags, OutPacket, PacketType};
|
||||
|
||||
static TRACING: Lazy<()> = Lazy::new(|| tracing_subscriber::fmt().with_test_writer().init());
|
||||
|
||||
pub(crate) fn create_logger() { Lazy::force(&TRACING); }
|
||||
|
||||
fn parse_msg(msg: &str) -> InMessage {
|
||||
let header = OutPacket::new_with_dir(Direction::S2C, Flags::empty(), PacketType::Command);
|
||||
|
||||
InMessage::new(&header.header(), msg.as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
fn test_iconid(input: &str, expected: u32) {
|
||||
create_logger();
|
||||
|
||||
let msg = parse_msg(&format!(
|
||||
r#"initserver virtualserver_name=TeamSpeak\s]I[\sServer virtualserver_welcomemessage=Welcome\sto\sTeamSpeak,\scheck\s[URL]www.teamspeak.com[\/URL]\sfor\slatest\sinformation virtualserver_platform=Linux virtualserver_version=3.11.0\s[Build:\s1578903157] virtualserver_maxclients=32 virtualserver_created=1571572631 virtualserver_codec_encryption_mode=2 virtualserver_hostmessage virtualserver_hostmessage_mode=0 virtualserver_default_server_group=8 virtualserver_default_channel_group=8 virtualserver_hostbanner_url virtualserver_hostbanner_gfx_url virtualserver_hostbanner_gfx_interval=0 virtualserver_priority_speaker_dimm_modificator=-18.0000 virtualserver_id=1 virtualserver_hostbutton_tooltip virtualserver_hostbutton_url virtualserver_hostbutton_gfx_url virtualserver_name_phonetic virtualserver_ip=0.0.0.0,\s:: virtualserver_ask_for_privilegekey=0 virtualserver_hostbanner_mode=0 virtualserver_channel_temp_delete_delay_default=0 virtualserver_nickname client_nickname=TeamSpeakUser client_version=3.?.?\s[Build:\s5680278000] client_platform=Windows client_input_muted=0 client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 client_output_hardware=1 client_default_channel client_default_channel_password client_server_password client_meta_data client_version_sign=DX5NIYLvfJEUjuIbCidnoeozxIDRRkpq3I9vVMBmE9L2qnekOoBzSenkzsg2lC9CMv8K5hkEzhr2TYUYSwUXCg== client_security_hash client_key_offset=354 client_away=0 client_away_message client_nickname_phonetic client_default_token client_badges client_myteamspeak_id client_integrations client_active_integrations_info client_myteamspeak_avatar client_signed_badges acn=TeamSpeakUser aclid=2 pv=7 client_talk_power=75 client_needed_serverquery_view_power=75 virtualserver_icon_id={}"#,
|
||||
input
|
||||
));
|
||||
if let InMessage::InitServer(list) = msg {
|
||||
let cmd = list.iter().next().unwrap();
|
||||
assert_eq!(cmd.icon, ts_bookkeeping::IconId(expected));
|
||||
} else {
|
||||
panic!("Failed to parse as initserver");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_iconid() { test_iconid("96136942", 96136942); }
|
||||
|
||||
#[test]
|
||||
fn negative_iconid() { test_iconid("-96136942", 4198830354); }
|
||||
|
||||
#[test]
|
||||
fn big_iconid() { test_iconid("18446744073225738240", 3811153920); }
|
||||
@@ -0,0 +1,433 @@
|
||||
# TeamsPeach core bridge — protocol v1
|
||||
|
||||
Contract between the Electron **main** process and the native protocol core
|
||||
(`teamspeach-core`, Rust, built on ReSpeak tsclientlib). The renderer never talks
|
||||
to the core directly: main forwards only the commands listed here, after checking
|
||||
`cmd` against this allowlist and argument shapes.
|
||||
|
||||
## 1. Process model
|
||||
|
||||
```
|
||||
teamspeach-core --data-dir <ABSOLUTE_DIR>
|
||||
```
|
||||
|
||||
- `--data-dir` is resolved and passed **only by main** (e.g. `<userData>/core`).
|
||||
The core creates it if missing. One core process per data dir: the core takes an
|
||||
exclusive lock (`<data-dir>/core.lock`); a second instance fails at startup
|
||||
with exit code 3 and a stderr message.
|
||||
- **stdin**: UTF-8, one JSON object per line (`\n`, `\r\n` tolerated). Max line **256 KiB**;
|
||||
a longer line is discarded up to its newline and answered with an `error` event
|
||||
`bad_request` (no `id` can be recovered).
|
||||
- **stdout**: UTF-8, one JSON object per line. Nothing else is ever written to stdout.
|
||||
- **stderr**: human-readable logs only (never parse). Verbosity: env
|
||||
`TEAMSPEACH_LOG` (`error|warn|info|debug|trace`, tracing filter syntax), default `info`.
|
||||
- **stdin EOF** or `shutdown` command → graceful disconnect (if connected), then exit 0.
|
||||
- Exit codes: `0` clean, `2` bad CLI arguments, `3` data dir locked/unusable, `1` fatal internal error.
|
||||
- Windows dev binary: `core/target/release/teamspeach-core.exe`
|
||||
(debug: `core/target/debug/teamspeach-core.exe`). Packaged: `resources/core/teamspeach-core[.exe]`.
|
||||
|
||||
The first stdout line is always:
|
||||
|
||||
```json
|
||||
{"event":"ready","protocol":1,"core_version":"0.1.0"}
|
||||
```
|
||||
|
||||
## 2. Framing
|
||||
|
||||
Request (stdin):
|
||||
|
||||
```json
|
||||
{"id":"r1","cmd":"connect","args":{"address":"10.10.10.160:9987"}}
|
||||
```
|
||||
|
||||
- `id`: string, 1–64 chars, chosen by main; echoed in the response.
|
||||
Required for every command **except** `audio_frame` and `audio_end`
|
||||
(high-rate, never answered; an `id` there is ignored).
|
||||
- `cmd`: one of the commands in §4. Unknown `cmd` → `unknown_command`.
|
||||
- `args`: object; may be omitted when a command takes no arguments.
|
||||
Unknown argument keys are rejected (`bad_request`).
|
||||
|
||||
Response (stdout), exactly one per request with `id`:
|
||||
|
||||
```json
|
||||
{"id":"r1","ok":true,"result":{}}
|
||||
{"id":"r1","ok":false,"error":{"code":"not_connected","message":"..."}}
|
||||
```
|
||||
|
||||
Event (stdout), no `id`, discriminated by `event`:
|
||||
|
||||
```json
|
||||
{"event":"state","state":"connected", ...}
|
||||
```
|
||||
|
||||
A line is a response iff it has an `id` key; otherwise it is an event.
|
||||
Events may be emitted before the response of the command that caused them
|
||||
(e.g. `state: connecting` precedes the `connect` response).
|
||||
|
||||
## 3. Error object
|
||||
|
||||
`{"code": string, "message": string, "ts_error"?: {"id": number, "name": string, "missing_permission"?: number}, "detail"?: object}`
|
||||
|
||||
`ts_error` is present when the TeamSpeak server rejected a command: numeric TeamSpeak
|
||||
error id and tsclientlib's name for it (live example: send_text to a channel without
|
||||
permission → `{"id":2568,"name":"PermissionsClientInsufficient","missing_permission":224}`).
|
||||
`detail` carries structured extra state where stated (e.g. `rename`).
|
||||
|
||||
| code | meaning |
|
||||
|---|---|
|
||||
| `bad_request` | malformed JSON, missing/unknown/invalid argument, bad `id` |
|
||||
| `unknown_command` | `cmd` not in allowlist |
|
||||
| `profile_missing` | no identity yet → call `profile_create` |
|
||||
| `profile_exists` | `profile_create` when an identity already exists (never overwritten) |
|
||||
| `identity_corrupt` | identity file unreadable/invalid/UID mismatch. Core **never** regenerates; user/main must resolve (restore backup / import) |
|
||||
| `profile_corrupt` | profile (nickname) file unreadable/invalid |
|
||||
| `invalid_nickname` | nickname rule violated (§4.3) |
|
||||
| `nickname_required` | identity exists but no nickname saved (connect refused) |
|
||||
| `not_connected` | command needs an active connection |
|
||||
| `already_connected` | `connect` while connecting/connected |
|
||||
| `connect_failed` | could not connect (resolve, timeout, server refused …; `ts_error` when the server sent one) |
|
||||
| `server_error` | server answered a command with an error (`ts_error` set) |
|
||||
| `audio_format` | `audio_frame.pcm` not 1920 bytes after base64 decode |
|
||||
| `audio_overflow` | outgoing PCM queue full, oldest frames dropped (event, throttled ≤1/s) |
|
||||
| `audio_muted` | `audio_frame` while input or output muted; frames discarded (event, once per burst) |
|
||||
| `audio_codec` | Opus encode/decode failure (event) |
|
||||
| `audio_codec_unsupported` | current channel codec is not Opus (legacy Speex/CELT): we cannot transmit there (event, once per burst); received non-Opus voice is reported once per speaker |
|
||||
| `rename_not_persisted` | server accepted the new nickname but saving it failed; see §4.3 |
|
||||
| `not_found` | requested icon/avatar/banner does not exist (`detail.builtin:true` for built-in icon ids) |
|
||||
| `media_too_large` | file exceeds the size limit of its kind (§4.16) |
|
||||
| `media_unsupported` | file is not a recognized image, or a banner reference the core cannot fetch |
|
||||
| `external_media` | banner is an `http(s)://` URL (`detail.url`); main may fetch it itself |
|
||||
| `io` | data dir I/O failure |
|
||||
| `internal` | bug; message has details |
|
||||
|
||||
Asynchronous failures (not tied to a request) are emitted as
|
||||
`{"event":"error","error":{...}}`.
|
||||
|
||||
## 4. Commands
|
||||
|
||||
### 4.1 `profile_get` — no args
|
||||
|
||||
Result = profile object:
|
||||
|
||||
```json
|
||||
{"exists":true,"uid":"Zx1...base64...=","nickname":"Alice","security_level":8}
|
||||
{"exists":false,"uid":null,"nickname":null,"security_level":null}
|
||||
```
|
||||
|
||||
`uid` is the permanent public TeamSpeak unique identifier (base64 SHA-1 of the
|
||||
public key). The private key is **never** sent over the bridge.
|
||||
If the identity exists but no nickname is saved: `exists:true, nickname:null`
|
||||
(UI should prompt and call `rename`). Corrupt files → error `identity_corrupt` /
|
||||
`profile_corrupt`.
|
||||
|
||||
### 4.2 `profile_create` — `{nickname: string}`
|
||||
|
||||
Generates a new P-256 identity (security level ≥ 8), persists it privately, saves
|
||||
the nickname. Fails with `profile_exists` if any identity exists. Result = profile object.
|
||||
Also emits `{"event":"profile", ...profile object}`.
|
||||
|
||||
### 4.3 `rename` — `{nickname: string}`
|
||||
|
||||
Persists the nickname. **UID never changes.**
|
||||
|
||||
- Disconnected: validate → atomically save `profile.json` → result.
|
||||
- Connected: send `clientupdate client_nickname` and wait for the server's answer.
|
||||
Server rejects (e.g. nickname in use) → `server_error`, nothing saved, nothing changed.
|
||||
Server accepts → save atomically. If saving fails, the core immediately sends
|
||||
`clientupdate` back to the saved nickname and answers `rename_not_persisted` with
|
||||
`detail: {"saved_nickname": "<still on disk>", "server_nickname": "<what the server shows now>", "reverted": bool}`
|
||||
(`reverted:false` = revert also failed; the server keeps the new name for this session only).
|
||||
|
||||
Result = profile object; emits `profile` event.
|
||||
|
||||
Nickname rules: after trimming, 3–30 Unicode scalar values, no control characters.
|
||||
|
||||
### 4.4 `connect` — `{address, server_password?, channel?, channel_password?}`
|
||||
|
||||
- `address`: `host`, `host:port`, `[v6]:port` (default port 9987). Not a path.
|
||||
- `server_password`: optional string.
|
||||
- `channel`: optional initial channel, either numeric channel id string `"cid:12"` or a
|
||||
path `"Parent/Child"`.
|
||||
- Uses the persisted identity and nickname (`profile_missing` / `nickname_required` otherwise).
|
||||
If the nickname is taken on the server, the server appends digits (e.g. `Name1`); the
|
||||
snapshot shows the server-side name, the profile keeps the saved one.
|
||||
- After connecting the core subscribes to all channels (`channelsubscribeall`), so the
|
||||
snapshot lists clients in every channel.
|
||||
|
||||
Emits `state: connecting`, then on success `snapshot`, `audio_state`, `state: connected`,
|
||||
then the response `{"ok":true,"result":{"own_client_id":7}}`. On failure the response is
|
||||
`connect_failed` and `state: disconnected` with `reason`.
|
||||
|
||||
### 4.5 `disconnect` — `{message?: string}`
|
||||
|
||||
Sends a clean `clientdisconnect` and waits (≤ 3 s) for the server. Result
|
||||
`{"clean": true}` when the server confirmed, `{"clean": false}` on timeout or when a
|
||||
pending connect attempt was abandoned. `not_connected` if idle. Emits
|
||||
`state: disconnecting` → `state: disconnected`.
|
||||
|
||||
### 4.6 `join_channel` — `{channel_id: number, password?: string}`
|
||||
|
||||
Moves self (`clientmove`). Result `{}` after the server confirms; snapshot follows.
|
||||
|
||||
### 4.7 `send_text` — `{target: "channel"|"server"|"client", client_id?: number, message: string}`
|
||||
|
||||
`client_id` required iff `target = "client"`. Message 1–8192 bytes UTF-8;
|
||||
TeamSpeak escaping is done by the core. Result `{}` after server confirmation.
|
||||
The server echoes our own messages as `text` events (verified live for private messages:
|
||||
the sender receives exactly one `text` with `to_client_id` = recipient); the core adds no
|
||||
synthetic echo.
|
||||
|
||||
### 4.8 `set_audio` — `{input_muted?: bool, output_muted?: bool}`
|
||||
|
||||
`input_muted` = mute microphone, `output_muted` = deafen. Updates the server-visible
|
||||
flags (`client_input_muted` / `client_output_muted`) when connected, and the core-side
|
||||
gates: while `input_muted || output_muted` outgoing frames are discarded; while
|
||||
`output_muted` no `audio` events are emitted. Allowed when disconnected (applied at
|
||||
next connect). Result = audio state object; emits `audio_state`.
|
||||
Initial state at process start: both `false`.
|
||||
|
||||
### 4.9 `audio_frame` — `{pcm: string}` (no `id`, no response)
|
||||
|
||||
One 20 ms microphone frame: base64 (standard alphabet, padded) of **960 signed
|
||||
16-bit little-endian mono samples at 48 kHz = 1920 bytes** (2560 base64 chars).
|
||||
The renderer gates push-to-talk / voice activation: it sends frames only while
|
||||
transmitting and `audio_end` when it stops. The core Opus-encodes 20 ms frames
|
||||
with the **current channel's codec**: Opus Voice (mono) or Opus Music (stereo — the
|
||||
mono frame is duplicated to both channels). Legacy Speex/CELT channels →
|
||||
`audio_codec_unsupported` event and nothing is sent. Outgoing queue bound: 10 frames
|
||||
(200 ms); on overflow the oldest frames are dropped (`audio_overflow` event).
|
||||
If no frame arrives for 200 ms during a burst the core ends the burst itself.
|
||||
Not connected → frames dropped with one `not_connected` error event per burst.
|
||||
|
||||
### 4.10 `audio_end` — no args (no `id`, no response)
|
||||
|
||||
Ends the current transmission burst (core sends the TeamSpeak end-of-voice packet).
|
||||
|
||||
### 4.11 `stream_list` — `{client_id?: number}`
|
||||
|
||||
TS6 screenshare discovery. Sends `requeststreaminfo clid=<id>` for `client_id`, or for
|
||||
every other client in our current channel when omitted. Result:
|
||||
|
||||
```json
|
||||
{"results":[{"client_id":5,"ok":true},{"client_id":9,"ok":false,"ts_error":{"id":...}}]}
|
||||
```
|
||||
|
||||
Live behaviour (TS6 6.0.0-beta13.1): every `requeststreaminfo` is answered `ok`, plus one
|
||||
`stream` event `notifystreaminfo` per request. For a streaming client the item carries
|
||||
`id` (stream UUID), `clid`, `name`, `type`, `mode`, `accessibility`, `audio`, `bitrate`,
|
||||
`viewer`, `viewer_limit`; for a non-streaming client the item has only `return_code`.
|
||||
So: "is streaming" ⇔ the `notifystreaminfo` item has `id`.
|
||||
|
||||
### 4.12 `stream_join` — `{stream_id: string, client_id: number, message?: string}`
|
||||
|
||||
Sends `joinstreamrequest id=<stream_id> clid=<client_id> msg=<message|our nickname> is_remove=0`.
|
||||
Result `{}` (or `server_error`). The SDP offer arrives as `stream` event
|
||||
`notifyrespondjoinstreamrequest` (`decision=1`, `offer=<sdp>`).
|
||||
|
||||
### 4.13 `stream_signal` — `{stream_id: string, client_id: number, json: object}`
|
||||
|
||||
Sends `streamsignaling id=<stream_id> clid=<client_id> json=<compact JSON of json>`.
|
||||
Examples of `json`: `{"cmd":"answer","args":{"answer":"<sdp>"}}`,
|
||||
`{"cmd":"iceCandidate","args":{"mLine":0,"mid":"0","sdp":"candidate:..."}}`.
|
||||
Max serialized `json` size 60 KiB (the whole stdin line is capped at 256 KiB). Result `{}` or `server_error`.
|
||||
|
||||
### 4.14 `stream_leave` — `{stream_id: string, client_id: number}`
|
||||
|
||||
Sends `joinstreamrequest id=… clid=… msg= is_remove=1`. Result `{}`.
|
||||
|
||||
### 4.15 `shutdown` — no args
|
||||
|
||||
Disconnects cleanly if needed, responds `{}`, exits 0.
|
||||
|
||||
### 4.16 Media: `fetch_icon`, `fetch_avatar`, `fetch_banner`, `fetch_server_banner`
|
||||
|
||||
Read-only downloads over TeamSpeak file transfer from the connected server. No paths
|
||||
cross the bridge: the core derives the server file from ids it already knows.
|
||||
|
||||
| command | args | server file | limit |
|
||||
|---|---|---|---|
|
||||
| `fetch_icon` | `{icon_id: number}` (u32, non-zero) | `/icon_<id>` in the server root | 256 KiB |
|
||||
| `fetch_avatar` | `{client_id: number}` | `/avatar_<uid>` of that visible client (needs `avatar_hash`) | 1 MiB |
|
||||
| `fetch_banner` | `{channel_id: number}` | file referenced by the channel's `banner_url` | 4 MiB |
|
||||
| `fetch_server_banner` | — | file referenced by `server.hostbanner_gfx_url` | 4 MiB |
|
||||
|
||||
Result: `{"mime":"image/png","bytes":108726,"data":"<base64>"}`. `mime` is sniffed from the
|
||||
bytes (`image/png|jpeg|gif|webp|x-icon|svg+xml`); anything else → `media_unsupported`.
|
||||
Render only via `<img>`/canvas (SVG included). Cache by `icon_id` / `avatar_hash` / URL.
|
||||
|
||||
- Icon ids below 1000 (100, 200, 300, 500, 600 seen live) are TeamSpeak's built-in group
|
||||
icons; the server has no file for them (live: error 2054 `FileInvalidPath`), so the core
|
||||
answers `not_found` with `detail.builtin:true` without asking. Draw built-in glyphs.
|
||||
- Banners: `ts3image://<host>?port=<p>&channel=<cid>&path=<dir>&filename=<name>` references
|
||||
are fetched from that channel's file area on the connected server (port must match;
|
||||
`..`/backslashes/control characters rejected). `http(s)://` → `external_media` with
|
||||
`detail.url` for main to fetch (untrusted URL).
|
||||
- At most 3 transfers run at once (the rest queue); each has a 20 s deadline (`io` error).
|
||||
Server refusals surface as `server_error` with `ts_error`.
|
||||
|
||||
## 5. Events
|
||||
|
||||
### `ready`
|
||||
See §1.
|
||||
|
||||
### `profile`
|
||||
`{"event":"profile","exists":true,"uid":"...","nickname":"...","security_level":8}` — after
|
||||
`profile_create` / `rename`.
|
||||
|
||||
### `state`
|
||||
```json
|
||||
{"event":"state","state":"connecting|connected|disconnecting|disconnected",
|
||||
"address":"10.10.10.160:9987","reason":{"code":"...","message":"...","ts_error":{...}}}
|
||||
```
|
||||
`reason` only on `disconnected` when not user-initiated (kicked, banned, timeout,
|
||||
server shutdown, connect failure) and on an automatic-reconnect `connecting`. For a
|
||||
server-closed connection `reason.detail.reason` is one of `kicked`, `banned`,
|
||||
`server_shutdown`, `timeout`, `connection_closed`. tsclientlib reconnects automatically
|
||||
after a timeout: `connecting` may then follow `connected` without a `connect` command.
|
||||
|
||||
### `snapshot`
|
||||
Full replacement of the server view, emitted after connect and after every change
|
||||
(coalesced, ≤ 1 per 50 ms). The UI must replace its model wholesale.
|
||||
|
||||
```json
|
||||
{"event":"snapshot","rev":12,
|
||||
"server":{"name":"...","welcome_message":"...","platform":"...","version":"...",
|
||||
"icon_id":null,"hostbanner_url":null,"hostbanner_gfx_url":"ts3image://…",
|
||||
"hostbanner_gfx_interval_s":0,"hostbanner_mode":"adjust_keep_aspect",
|
||||
"hostbutton_url":null,"hostbutton_gfx_url":null,"hostbutton_tooltip":null,
|
||||
"default_server_group":8,"default_channel_group":8},
|
||||
"own_client_id":7,"own_channel_id":1,
|
||||
"server_groups":[{"id":10,"name":"…","icon_id":3558086607,"sort_id":0,
|
||||
"name_mode":"after","type":"regular"}],
|
||||
"channel_groups":[{"id":5,"name":"Channel Admin","icon_id":100,"sort_id":0,
|
||||
"name_mode":"none","type":"regular"}],
|
||||
"channels":[{"id":1,"parent_id":0,"order":0,"name":"Lobby","topic":"",
|
||||
"has_password":false,"is_default":true,"max_clients":null,
|
||||
"needed_talk_power":0,"codec":"opus_voice","codec_quality":6,
|
||||
"icon_id":1775712350,"banner_url":"ts3image://…","banner_mode":2,"depth":0}],
|
||||
"clients":[{"id":7,"uid":"...","nickname":"Alice","channel_id":1,"is_self":true,
|
||||
"client_type":"normal","input_muted":false,"output_muted":false,
|
||||
"input_hardware":true,"output_hardware":true,"away":false,
|
||||
"away_message":null,"talk_power":0,"is_talker":false,
|
||||
"is_channel_commander":false,"is_priority_speaker":false,"is_recording":false,
|
||||
"is_streaming":false,"description":null,"country":"RU","server_groups":[7,10],
|
||||
"channel_group_id":8,"channel_group_inherited_from":20,"avatar_hash":null,
|
||||
"icon_id":null,"badges":null}]}
|
||||
```
|
||||
|
||||
- `channels` is in display order (pre-order tree walk following TeamSpeak `order`);
|
||||
`depth` = nesting level. `max_clients: null` = unlimited.
|
||||
- `codec`: `"opus_voice"`, `"opus_music"`, `"speex_narrowband"`, `"speex_wideband"`,
|
||||
`"speex_ultrawideband"`, `"celt_mono"` or `null` if unknown. Only Opus channels can
|
||||
transmit; the UI should show the reason for others.
|
||||
- `client_type`: `"normal"` or `"query"`. `uid` may be `null` if not visible.
|
||||
- `icon_id`: TeamSpeak icon id or `null` (0 = none). Fetch with `fetch_icon` (§4.16).
|
||||
- Groups: `server_groups`/`channel_groups` are the server's group catalogs (sent to every
|
||||
client on connect; sorted by `sort_id`, then `id`). A client's `server_groups` and
|
||||
`channel_group_id` reference them. `name_mode` (`none|before|after`) is TeamSpeak's
|
||||
"show group name in tree" setting: live, the label shown next to a nickname by the
|
||||
official client is the name of a server group with `name_mode:"after"` (verified: a
|
||||
client with groups `[7,10]`, group 10 `name_mode:"after"` → that group's name is the
|
||||
label). Group icons are drawn from `icon_id`. `type`: `template|regular|query`.
|
||||
- `country`: ISO code or `null` (flag). `description`: client description or `null`.
|
||||
`badges`: raw myTeamSpeak badges string (not groups) or `null`.
|
||||
- `avatar_hash`: non-null when the client has an avatar (`fetch_avatar`).
|
||||
- `is_streaming`: TeamSpeak 6 `client_is_streaming` flag (`null` if the server did not send
|
||||
it). Confirm/obtain the stream id with `stream_list`.
|
||||
- Channel `banner_url` / `banner_mode` (int) are the TS5/6 channel banner properties,
|
||||
`null` when unset; fetch with `fetch_banner`. Server `hostbanner_*` likewise via
|
||||
`fetch_server_banner`. All strings here are server-controlled, untrusted input.
|
||||
|
||||
### `audio_state`
|
||||
`{"event":"audio_state","input_muted":false,"output_muted":false,"transmitting":false}`
|
||||
|
||||
### `talking`
|
||||
`{"event":"talking","client_id":5,"talking":true}` — start/stop of a remote speaker's
|
||||
voice stream (also for self: `transmitting` in `audio_state`).
|
||||
|
||||
### `audio`
|
||||
`{"event":"audio","pcm":"<base64 1920 bytes>","speakers":[5,9]}` — mixed playback,
|
||||
960 i16le mono samples at 48 kHz, emitted on a 20 ms clock **only while someone is
|
||||
audible** and output is not muted. Per-speaker jitter buffering and Opus decoding
|
||||
(incl. packet-loss concealment) happen in the core. The renderer should keep a small
|
||||
playback ring (target 40–60 ms, drop oldest beyond ~200 ms, play silence on underrun).
|
||||
|
||||
### `text`
|
||||
```json
|
||||
{"event":"text","target":"channel|server|client|poke","from_client_id":5,
|
||||
"from_uid":"...","from_nickname":"Bob","message":"hi","to_client_id":7}
|
||||
```
|
||||
`to_client_id` only for `target:"client"` (recipient: our id for incoming, the peer for
|
||||
our own echoed message). `poke` = a TeamSpeak poke addressed to us.
|
||||
|
||||
### `stream`
|
||||
Raw TS6 screenshare notifications, lifted from the protocol layer before
|
||||
tsclientlib would discard them:
|
||||
|
||||
```json
|
||||
{"event":"stream","name":"notifystreamsignaling",
|
||||
"items":[{"id":"…","clid":"5","json":"{\"cmd\":\"offer\",…}"}]}
|
||||
```
|
||||
|
||||
- `name` ∈ every `notifystream*` notification (`notifystreaminfo`, `notifystreamstarted`,
|
||||
`notifystreamstopped`, `notifystreamupdated`, `notifystreamsignaling`,
|
||||
`notifystreamclientjoined`, `notifystreamclientleft`, `notifystreamattendees`, …),
|
||||
`notifyjoinstreamrequest`, `notifyrespondjoinstreamrequest`, and `notifysfuaccessinfo`.
|
||||
TeamsPeach supports only the P2P path: on `notifysfuaccessinfo` (SFU/mediasoup
|
||||
stream) the UI must report "SFU streams are not supported" instead of "no stream".
|
||||
The core never logs stream payloads (SDP/ICE/tokens).
|
||||
- `items`: one map per `|`-separated entry; keys and values are unescaped strings
|
||||
(JSON/SDP stay raw strings — parse them in the renderer). Flags without value → `""`.
|
||||
|
||||
### `error`
|
||||
`{"event":"error","error":{...}}` — asynchronous error (see §3).
|
||||
|
||||
## 6. Identity storage (main-only concern)
|
||||
|
||||
Files in `--data-dir` (never sent over the bridge):
|
||||
|
||||
- `identity.json` — private key + key offset + UID; written at creation
|
||||
(atomic temp+rename), never rewritten by `rename`. Only when a server demands a higher
|
||||
security level does the core rewrite it with the larger key offset (same key, same UID;
|
||||
checked before writing). Permissions: owner-only
|
||||
(Unix `0600`; Windows protected DACL granting only the current user).
|
||||
- `profile.json` — nickname; rewritten atomically by `rename`.
|
||||
- `core.lock` — instance lock.
|
||||
|
||||
On load the UID is recomputed from the key and must match the stored UID; any
|
||||
mismatch or parse failure → `identity_corrupt` (no regeneration).
|
||||
|
||||
Backup/migration is **not** a bridge command (no paths cross stdin). Main runs the
|
||||
binary separately with the core process stopped:
|
||||
|
||||
```
|
||||
teamspeach-core identity export --data-dir <DIR> --out <FILE>
|
||||
teamspeach-core identity import --data-dir <DIR> --in <FILE> [--replace]
|
||||
```
|
||||
|
||||
`<FILE>` comes from main's native dialog. Exit 0 on success with one JSON line on
|
||||
stdout (`{"ok":true,"uid":"..."}`), else non-zero and `{"ok":false,"error":{...}}`.
|
||||
`import` refuses to overwrite an existing identity unless `--replace`. Export file
|
||||
format: TeamSpeak-compatible ini (`[Identity]`, `id`, `identity="<offset>V<key>"`,
|
||||
`nickname`) — contains the private key; the core creates it owner-only (same permissions as
|
||||
`identity.json`, atomic write next to `<FILE>`).
|
||||
|
||||
## 7. Build prerequisites
|
||||
|
||||
All platforms: Rust stable ≥ 1.89 (rustup), CMake (any version; `core/.cargo/config.toml`
|
||||
sets `CMAKE_POLICY_VERSION_MINIMUM=3.5` for CMake ≥ 4 and forces the bundled libopus to be
|
||||
built and linked statically: `LIBOPUS_STATIC=1`, `LIBOPUS_NO_PKG=1`), a C compiler, and
|
||||
network access to crates.io and github.com (tsclientlib git dependencies at the pinned
|
||||
revision, including its `tsdeclarations` submodule, fetched by cargo).
|
||||
|
||||
- Windows: target `x86_64-pc-windows-msvc`, Visual Studio Build Tools (MSVC) + Windows SDK.
|
||||
The VS-bundled CMake must know the installed VS generator (with VS 18/2026 installed use
|
||||
the VS 18 CMake 4.x; VS 2022's CMake 3.31 fails with "Could not create named generator").
|
||||
- Linux/macOS: `cc`/`c++` toolchain and CMake; no system libopus needed.
|
||||
- Build: `cargo build --release --locked --manifest-path core/Cargo.toml` →
|
||||
`core/target/release/teamspeach-core[.exe]`. On memory-constrained machines add `-j 2`
|
||||
(full parallelism exhausted the Windows commit limit here: link.exe `0xc000012d`).
|
||||
- Tests: `cargo test --locked --manifest-path core/Cargo.toml` (unit tests + offline stdio
|
||||
smoke of the built binary; no network).
|
||||
- tsclientlib is vendored with a small patch (`core/vendor/README.md`); third-party notices:
|
||||
`core/THIRD_PARTY_NOTICES.md` (regenerate with `python core/tools/third_party_notices.py`).
|
||||
@@ -0,0 +1,16 @@
|
||||
# Linux build/target hosts — read-only reachability (2026-10-24)
|
||||
|
||||
Probed from the Windows dev machine (10.10.10.111) with SSH Manager, read-only commands only
|
||||
(`uname`, `/etc/os-release`, `command -v`, `free`, `df`). Nothing was installed or changed.
|
||||
|
||||
| Host (ssh-manager name) | Address | Result |
|
||||
|---|---|---|
|
||||
| `fedora_mac` | 10.0.0.142:22 | **Unreachable**: two SSH attempts → `connect ETIMEDOUT 10.0.0.142:22`. ICMP partially answers (1 of 2, then 2 of 4 lost). OS, model and architecture of the intended Asahi M1 Pro target are **not verified**. |
|
||||
| `orange_pi` | 10.10.10.100 | aarch64, Debian 12 (bookworm), 8 CPU, 7.9 GB RAM, docker present, no rust/node/cmake. **Not to be used** (runs HA/NPM; user decision). |
|
||||
| `git_monkey_act_runner` | 10.10.10.211 | x86_64, Debian 13 (trixie), 4 CPU, 4 GB RAM, 29 GB free on `/`, docker present, no gcc/rust/node, no `qemu-aarch64-static`, no binfmt entries listed. Candidate for disposable build containers **pending user approval**. |
|
||||
| `macbook` | 10.67.0.245 | Not probed (described as "macbook air", not the M1 Pro target). |
|
||||
|
||||
WSL on the dev machine cannot start (`HCS_E_HYPERV_NOT_INSTALLED`), so no local Linux toolchain exists.
|
||||
|
||||
Consequence: no Linux ELF (x64 or arm64) of TeamsPeach has been built or run yet; the
|
||||
Asahi ARM64 deliverable is unverified until a Linux build host is approved and the target is reachable.
|
||||
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 41 KiB |
@@ -0,0 +1,91 @@
|
||||
{
|
||||
"startedAt": "2026-10-24T00:09:03.606Z",
|
||||
"profile": "C:\\Users\\Admin\\AppData\\Local\\Temp\\teamspeach-smoke-IsAkHY",
|
||||
"steps": [
|
||||
{
|
||||
"name": "screenshot 01-first-launch-onboarding.png",
|
||||
"at": "2026-10-24T00:09:04.187Z"
|
||||
},
|
||||
{
|
||||
"name": "short nickname rejected",
|
||||
"at": "2026-10-24T00:09:04.212Z",
|
||||
"message": "Никнейм должен содержать от 3 до 30 символов."
|
||||
},
|
||||
{
|
||||
"name": "profile created",
|
||||
"at": "2026-10-24T00:09:04.856Z",
|
||||
"uid": "27312+ydLk3bXJHbBe8PTHQfa3M=",
|
||||
"nickname": "PeachSmoke"
|
||||
},
|
||||
{
|
||||
"name": "screenshot 02-after-onboarding.png",
|
||||
"at": "2026-10-24T00:09:05.208Z"
|
||||
},
|
||||
{
|
||||
"name": "restart keeps identity",
|
||||
"at": "2026-10-24T00:09:06.210Z",
|
||||
"uid": "27312+ydLk3bXJHbBe8PTHQfa3M=",
|
||||
"nickname": "PeachSmoke",
|
||||
"same": true
|
||||
},
|
||||
{
|
||||
"name": "renamed",
|
||||
"at": "2026-10-24T00:09:06.285Z",
|
||||
"uid": "27312+ydLk3bXJHbBe8PTHQfa3M=",
|
||||
"nickname": "PeachRenamed",
|
||||
"status": "Сохранено. UID не изменился.",
|
||||
"same": true
|
||||
},
|
||||
{
|
||||
"name": "screenshot 03-settings-renamed.png",
|
||||
"at": "2026-10-24T00:09:06.639Z"
|
||||
},
|
||||
{
|
||||
"name": "rename persisted",
|
||||
"at": "2026-10-24T00:09:07.606Z",
|
||||
"uid": "27312+ydLk3bXJHbBe8PTHQfa3M=",
|
||||
"nickname": "PeachRenamed",
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"name": "connected",
|
||||
"at": "2026-10-24T00:09:10.230Z",
|
||||
"server": "без негатива",
|
||||
"ownClientId": 23,
|
||||
"channel": "Welcome to the club buddy",
|
||||
"clients": 2,
|
||||
"videoCodecs": [
|
||||
"VP8",
|
||||
"VP9 profile-id=0",
|
||||
"VP9 profile-id=2",
|
||||
"VP9 profile-id=1",
|
||||
"VP9 profile-id=3",
|
||||
"H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f",
|
||||
"H264 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42001f",
|
||||
"H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",
|
||||
"H264 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42e01f",
|
||||
"H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=4d001f",
|
||||
"H264 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=4d001f",
|
||||
"H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=f4001f",
|
||||
"H264 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=f4001f",
|
||||
"AV1 level-idx=5;profile=0;tier=0",
|
||||
"AV1 level-idx=5;profile=1;tier=0",
|
||||
"H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=64001f",
|
||||
"H264 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=64001f",
|
||||
"H265 level-id=180;profile-id=1;tier-flag=0;tx-mode=SRST",
|
||||
"H265 level-id=180;profile-id=2;tier-flag=0;tx-mode=SRST"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "screenshot 04-connected.png",
|
||||
"at": "2026-10-24T00:09:10.592Z"
|
||||
},
|
||||
{
|
||||
"name": "disconnected",
|
||||
"at": "2026-10-24T00:09:10.613Z"
|
||||
}
|
||||
],
|
||||
"console": [],
|
||||
"finishedAt": "2026-10-24T00:09:10.697Z",
|
||||
"ok": true
|
||||
}
|
||||
|
After Width: | Height: | Size: 61 KiB |
@@ -0,0 +1,14 @@
|
||||
2026-10-24T00:11:53.819711Z WARN connection{addr=10.10.10.160:9987}:connection{local_addr=0.0.0.0:49571 remote_addr=10.10.10.160:9987}: tsproto::resend: Resend id=Command(0:1) tries=1 last=1.0154209s ago to="S" srtt=335.259449ms srtt_dev=247.571834ms rto=1s send_window=14
|
||||
2026-10-24T00:11:53.823542Z INFO connection{addr=10.10.10.160:9987}:connection{local_addr=0.0.0.0:49571 remote_addr=10.10.10.160:9987}: tsproto::resend: Resender: Changed state from=Connecting to=Connected
|
||||
2026-10-24T00:11:53.825949Z WARN connection{addr=10.10.10.160:9987}:parse_message: ts_bookkeeping::messages::s2c: Unknown argument command="InitServer" argument=Ok("virtualserver_address")
|
||||
2026-10-24T00:11:53.826174Z WARN connection{addr=10.10.10.160:9987}:parse_message: ts_bookkeeping::messages::s2c: Unknown argument command="InitServer" argument=Ok("virtualserver_version_sign")
|
||||
2026-10-24T00:11:53.826503Z WARN connection{addr=10.10.10.160:9987}:parse_message: ts_bookkeeping::messages::s2c: Unknown argument command="InitServer" argument=Ok("client_is_streaming")
|
||||
2026-10-24T00:11:53.830680Z WARN connection{addr=10.10.10.160:9987}:parse_message: ts_bookkeeping::messages::s2c: Unknown argument command="ClientEnterView" argument=Ok("client_is_streaming")
|
||||
2026-10-24T00:11:53.830912Z WARN connection{addr=10.10.10.160:9987}:parse_message: ts_bookkeeping::messages::s2c: Unknown argument command="ClientEnterView" argument=Ok("client_is_streaming")
|
||||
2026-10-24T00:11:53.834672Z WARN connection{addr=10.10.10.160:9987}:parse_message: ts_bookkeeping::messages::s2c: Unknown argument command="ClientEnterView" argument=Ok("client_is_streaming")
|
||||
2026-10-24T00:11:53.834739Z WARN connection{addr=10.10.10.160:9987}:parse_message: ts_bookkeeping::messages::s2c: Unknown argument command="ClientEnterView" argument=Ok("client_is_streaming")
|
||||
2026-10-24T00:11:53.834784Z WARN connection{addr=10.10.10.160:9987}:parse_message: ts_bookkeeping::messages::s2c: Unknown argument command="ClientEnterView" argument=Ok("client_is_streaming")
|
||||
2026-10-24T00:12:20.687490Z WARN connection{addr=10.10.10.160:9987}:parse_message: ts_bookkeeping::messages::s2c: Unknown argument command="ClientEnterView" argument=Ok("client_is_streaming")
|
||||
2026-10-24T00:12:21.765778Z WARN connection{addr=10.10.10.160:9987}:parse_message: ts_bookkeeping::messages::s2c: Unknown argument command="ClientEnterView" argument=Ok("client_is_streaming")
|
||||
2026-10-24T00:12:34.501446Z INFO connection{addr=10.10.10.160:9987}:connection{local_addr=0.0.0.0:49571 remote_addr=10.10.10.160:9987}: tsproto::resend: Resender: Changed state from=Connected to=Disconnecting
|
||||
2026-10-24T00:12:34.502188Z INFO connection{addr=10.10.10.160:9987}:connection{local_addr=0.0.0.0:49571 remote_addr=10.10.10.160:9987}: tsproto::resend: Resender: Changed state from=Disconnecting to=Disconnected
|
||||
@@ -0,0 +1,25 @@
|
||||
2026-10-24T00:11:52.763Z info state connecting → connecting
|
||||
2026-10-24T00:11:53.838Z info state connected → connected
|
||||
2026-10-24T00:11:54.185Z info stream event notifystreaminfo items=1 keys=return_code
|
||||
2026-10-24T00:11:54.185Z info stream event notifystreaminfo items=1 keys=accessibility,audio,bitrate,clid,id,mode,name,return_code,type,viewer,viewer_limit
|
||||
2026-10-24T00:11:54.186Z info stream event notifystreaminfo items=1 keys=return_code
|
||||
2026-10-24T00:11:54.209Z info watch: state requesting
|
||||
2026-10-24T00:11:54.221Z info watch: join sent id=c422f380-c3ad-474e-b505-eca620c5ae5b clid=16
|
||||
2026-10-24T00:11:54.264Z info stream event notifyrespondjoinstreamrequest items=1 keys=clid,decision,id,msg,offer
|
||||
2026-10-24T00:11:54.265Z info watch: join accepted, offer 3584 chars (clid field=16)
|
||||
2026-10-24T00:11:54.278Z info watch: state connecting
|
||||
2026-10-24T00:11:54.280Z info stream event notifystreamsignaling items=1 keys=clid,id,json
|
||||
2026-10-24T00:11:54.280Z info stream event notifystreamsignaling items=1 keys=clid,id,json
|
||||
2026-10-24T00:11:54.280Z info stream event notifystreamsignaling items=1 keys=clid,id,json
|
||||
2026-10-24T00:11:54.280Z info stream event notifystreamsignaling items=1 keys=clid,id,json
|
||||
2026-10-24T00:11:54.280Z info stream event notifystreamsignaling items=1 keys=clid,id,json
|
||||
2026-10-24T00:11:54.280Z info stream event notifystreamsignaling items=1 keys=clid,id,json
|
||||
2026-10-24T00:11:54.317Z info watch: answer sent for join (#1)
|
||||
2026-10-24T00:11:54.318Z info watch: connectionState=connecting
|
||||
2026-10-24T00:11:54.330Z info watch: connectionState=connected
|
||||
2026-10-24T00:11:54.330Z info watch: state live
|
||||
2026-10-24T00:11:55.714Z info watch: negotiated video/AV1 fmtp="level-idx=5;profile=0;tier=0" decoder=ExternalDecoder (D3D11VideoDecoder)
|
||||
2026-10-24T00:12:34.477Z info watch: state stopped
|
||||
2026-10-24T00:12:34.481Z info stream event notifystreamclientleft items=1 keys=clid,id,reason
|
||||
2026-10-24T00:12:34.501Z info state connected → disconnecting
|
||||
2026-10-24T00:12:34.505Z info state disconnecting → disconnected
|
||||
@@ -0,0 +1,551 @@
|
||||
{
|
||||
"startedAt": "2026-10-24T00:11:50.961Z",
|
||||
"server": "10.10.10.160:9987",
|
||||
"channelName": "cs",
|
||||
"profile": "C:\\Users\\Admin\\AppData\\Local\\Temp\\teamspeach-probe-OB9Dwe",
|
||||
"steps": [
|
||||
{
|
||||
"name": "muted before connect",
|
||||
"at": "2026-10-24T00:11:52.723Z",
|
||||
"profile": {
|
||||
"uid": "iIem4WcA1EBHBtBygFAHqPZBKU4=",
|
||||
"nickname": "TeamsPeach-Probe"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "connected",
|
||||
"at": "2026-10-24T00:11:53.846Z",
|
||||
"server": "без негатива",
|
||||
"ownClientId": 28,
|
||||
"channel": null,
|
||||
"audio": {
|
||||
"input_muted": true,
|
||||
"output_muted": false,
|
||||
"transmitting": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "joined channel",
|
||||
"at": "2026-10-24T00:11:53.947Z",
|
||||
"channel": "cs",
|
||||
"members": [
|
||||
"master",
|
||||
"maqrota",
|
||||
"Fiziro",
|
||||
"TeamsPeach-Probe"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "streams discovered",
|
||||
"at": "2026-10-24T00:11:54.191Z",
|
||||
"streams": [
|
||||
{
|
||||
"id": "c422f380-c3ad-474e-b505-eca620c5ae5b",
|
||||
"clientId": 16,
|
||||
"name": "Экран 1"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "watch clicked",
|
||||
"at": "2026-10-24T00:11:54.223Z",
|
||||
"streamId": "c422f380-c3ad-474e-b505-eca620c5ae5b",
|
||||
"clientId": 16
|
||||
},
|
||||
{
|
||||
"name": "first decoded frame",
|
||||
"at": "2026-10-24T00:11:56.226Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 52,
|
||||
"state": "live",
|
||||
"framesDecoded": 53,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 593,
|
||||
"videoBytes": 652421,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"name": "final watch stats",
|
||||
"at": "2026-10-24T00:12:34.459Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 59,
|
||||
"state": "live",
|
||||
"framesDecoded": 2298,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 10359,
|
||||
"videoBytes": 11075574,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"name": "stopped watching",
|
||||
"at": "2026-10-24T00:12:34.486Z"
|
||||
}
|
||||
],
|
||||
"samples": [
|
||||
{
|
||||
"at": "2026-10-24T00:11:56.226Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 52,
|
||||
"state": "live",
|
||||
"framesDecoded": 53,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 593,
|
||||
"videoBytes": 652421,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-24T00:11:58.287Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 61,
|
||||
"state": "live",
|
||||
"framesDecoded": 147,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 957,
|
||||
"videoBytes": 1036198,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-24T00:12:00.295Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 59,
|
||||
"state": "live",
|
||||
"framesDecoded": 326,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 1399,
|
||||
"videoBytes": 1442149,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-24T00:12:02.299Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 60,
|
||||
"state": "live",
|
||||
"framesDecoded": 417,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 1898,
|
||||
"videoBytes": 1969585,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-24T00:12:04.311Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 58,
|
||||
"state": "live",
|
||||
"framesDecoded": 506,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 2359,
|
||||
"videoBytes": 2456151,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-24T00:12:06.327Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 59,
|
||||
"state": "live",
|
||||
"framesDecoded": 684,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 3775,
|
||||
"videoBytes": 4015518,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-24T00:12:08.336Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 59,
|
||||
"state": "live",
|
||||
"framesDecoded": 773,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 4508,
|
||||
"videoBytes": 4827879,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-24T00:12:10.354Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 59,
|
||||
"state": "live",
|
||||
"framesDecoded": 861,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 5231,
|
||||
"videoBytes": 5627822,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-24T00:12:12.360Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 59,
|
||||
"state": "live",
|
||||
"framesDecoded": 1041,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 6232,
|
||||
"videoBytes": 6637773,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-24T00:12:14.365Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 59,
|
||||
"state": "live",
|
||||
"framesDecoded": 1131,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 6558,
|
||||
"videoBytes": 6957796,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-24T00:12:16.371Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 60,
|
||||
"state": "live",
|
||||
"framesDecoded": 1221,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 6851,
|
||||
"videoBytes": 7273417,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-24T00:12:18.389Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 59,
|
||||
"state": "live",
|
||||
"framesDecoded": 1400,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 7428,
|
||||
"videoBytes": 7906147,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-24T00:12:20.393Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 59,
|
||||
"state": "live",
|
||||
"framesDecoded": 1490,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 7716,
|
||||
"videoBytes": 8227599,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-24T00:12:22.397Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 59,
|
||||
"state": "live",
|
||||
"framesDecoded": 1580,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 8059,
|
||||
"videoBytes": 8585379,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-24T00:12:24.401Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 60,
|
||||
"state": "live",
|
||||
"framesDecoded": 1760,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 8706,
|
||||
"videoBytes": 9269133,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-24T00:12:26.412Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 59,
|
||||
"state": "live",
|
||||
"framesDecoded": 1849,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 8980,
|
||||
"videoBytes": 9575264,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-24T00:12:28.419Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 59,
|
||||
"state": "live",
|
||||
"framesDecoded": 1938,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 9274,
|
||||
"videoBytes": 9893588,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-24T00:12:30.434Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 60,
|
||||
"state": "live",
|
||||
"framesDecoded": 2118,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 9812,
|
||||
"videoBytes": 10482454,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-24T00:12:32.443Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 60,
|
||||
"state": "live",
|
||||
"framesDecoded": 2209,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 10089,
|
||||
"videoBytes": 10782562,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-24T00:12:34.457Z",
|
||||
"codec": "AV1",
|
||||
"width": 2560,
|
||||
"height": 1440,
|
||||
"fps": 59,
|
||||
"state": "live",
|
||||
"framesDecoded": 2298,
|
||||
"audio": true,
|
||||
"remoteCandidatesAdded": 6,
|
||||
"staleCandidates": 0,
|
||||
"candidateErrors": 0,
|
||||
"offersApplied": 1,
|
||||
"answersSent": 1,
|
||||
"pair": "host/udp → host",
|
||||
"videoPackets": 10359,
|
||||
"videoBytes": 11075574,
|
||||
"packetsLost": 0,
|
||||
"keyFrames": 2,
|
||||
"fmtp": "level-idx=5;profile=0;tier=0",
|
||||
"decoder": "ExternalDecoder (D3D11VideoDecoder)"
|
||||
}
|
||||
],
|
||||
"console": [],
|
||||
"finishedAt": "2026-10-24T00:12:35.478Z",
|
||||
"ok": true
|
||||
}
|
||||
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 43 KiB |
|
After Width: | Height: | Size: 55 KiB |
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 46 KiB |
@@ -0,0 +1,78 @@
|
||||
{
|
||||
"startedAt": "2026-10-24T00:16:08.472Z",
|
||||
"server": "10.10.10.160:9987",
|
||||
"steps": [
|
||||
{
|
||||
"name": "profiles created",
|
||||
"at": "2026-10-24T00:16:11.212Z",
|
||||
"a": {
|
||||
"uid": "RpuYw2vd6KW2pndcNgbtWrjHvGE=",
|
||||
"nickname": "PeachVoiceA"
|
||||
},
|
||||
"b": {
|
||||
"uid": "h+bYvyRwrZuG2GZMQZle/JYBiGM=",
|
||||
"nickname": "PeachVoiceB"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "both connected",
|
||||
"at": "2026-10-24T00:16:14.890Z",
|
||||
"aClid": 37,
|
||||
"aChannel": "Welcome to the club buddy",
|
||||
"bClid": 36,
|
||||
"bChannel": "Welcome to the club buddy"
|
||||
},
|
||||
{
|
||||
"name": "open mic received",
|
||||
"at": "2026-10-24T00:16:18.000Z",
|
||||
"aFramesSent": 153,
|
||||
"aTransmitting": true,
|
||||
"bTalking": [
|
||||
37
|
||||
],
|
||||
"bFramesPlayed": 151,
|
||||
"bPlayback": {
|
||||
"type": "stats",
|
||||
"framesIn": 151,
|
||||
"dropped": 0,
|
||||
"underruns": 0,
|
||||
"bufferedMs": 44
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "A muted, talking stopped on B",
|
||||
"at": "2026-10-24T00:16:18.972Z"
|
||||
},
|
||||
{
|
||||
"name": "PTT idle",
|
||||
"at": "2026-10-24T00:16:20.587Z",
|
||||
"bTalkingIncludesA": false
|
||||
},
|
||||
{
|
||||
"name": "PTT burst received",
|
||||
"at": "2026-10-24T00:16:22.203Z",
|
||||
"bFramesDuringBurst": 79
|
||||
},
|
||||
{
|
||||
"name": "reverse direction received",
|
||||
"at": "2026-10-24T00:16:24.291Z",
|
||||
"aFramesPlayed": 102,
|
||||
"aTalking": [
|
||||
36
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "channel chat",
|
||||
"at": "2026-10-24T00:16:24.379Z",
|
||||
"delivered": false,
|
||||
"error": "Сообщение не отправлено: Сервер отклонил действие: PermissionsClientInsufficient (TS 2568, не хватает права 224)"
|
||||
},
|
||||
{
|
||||
"name": "private chat delivered",
|
||||
"at": "2026-10-24T00:16:24.519Z"
|
||||
}
|
||||
],
|
||||
"console": [],
|
||||
"finishedAt": "2026-10-24T00:16:25.868Z",
|
||||
"ok": true
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
# Installed official TeamSpeak 6 client — read-only inspection (2026-10-24)
|
||||
|
||||
Purpose: interoperability reference for TeamsPeach screenshare viewing. Only installed program
|
||||
files were read (file versions, string tables). The user profile (`%APPDATA%\TeamSpeak\Default`:
|
||||
`settings.db`, `tschat_pc.db`) was **not opened**; the running official client (7 `TeamSpeak.exe`
|
||||
processes) was not touched. No credentials, tokens or identities were extracted.
|
||||
These are static strings, **not runtime proof** of what a given streamer negotiates.
|
||||
|
||||
## Install
|
||||
|
||||
- Path: `C:\Users\Admin\AppData\Local\Programs\TeamSpeak`
|
||||
- `TeamSpeak.exe`: FileVersionRaw **6.0.0.5163**, ProductVersion 6.0.0.0, TeamSpeak Systems GmbH, files dated 2026-10-15.
|
||||
(Registry `DisplayVersion 5.0.0` is the MSI wrapper, not the app.)
|
||||
- UI runtime: `libcef.dll` **151.3.15+g57a32ea+chromium-151.0.7922.76**; UI bundle `html/client_ui/main.js` (10.8 MB).
|
||||
- `html/client_ui/*.js` contains **no** `RTCPeerConnection` or stream verbs: screenshare WebRTC runs in native
|
||||
libwebrtc inside `TeamSpeak.dll`, not in Chromium's JS WebRTC.
|
||||
|
||||
## Codecs present in `TeamSpeak.dll` (strings)
|
||||
|
||||
libvpx (VP8/VP9), libaom + dav1d (AV1), OpenH264 2.6.0 fetched at runtime from
|
||||
`http://ciscobinary.openh264.org/openh264-2.6.0-win64.dll.bz2` ("Cisco H264 Encoder/Decoder (Software)"),
|
||||
FFmpeg `avcodec-62.dll` with hardware coders `h264_nvenc`, `h264_amf`, `h264_qsv`, `H264DecoderImpl`.
|
||||
Which codec/profile a particular streamer sends is decided at negotiation time; TeamsPeach shows the
|
||||
negotiated codec from `getStats()` while watching instead of assuming one.
|
||||
|
||||
## Screenshare signaling vocabulary
|
||||
|
||||
- Server notifications: `notifystreamstarted`, `notifystreamstopped`, `notifystreaminfo`, `notifystreamupdated`,
|
||||
`notifystreamclientjoined`, `notifystreamclientleft`, `notifystreamsignaling`, `notifystreamattendees`,
|
||||
`notifyjoinstreamrequest`, `notifyrespondjoinstreamrequest`, `notifysfuaccessinfo`.
|
||||
- Client commands: `setupstream`, `updatestream`, `requeststreaminfo`, `stopstream`, `removeclientfromstream`,
|
||||
`joinstreamrequest` (`is_remove`), `streamsignaling`, `respondjoinstreamrequest` (`decision`, `offer`),
|
||||
`requestsfuaccessinfo`; fields `accessibility`, `viewer_limit`, `sfu_endpoint`, `sfu_user_id`, `sfu_token`.
|
||||
- `streamsignaling` JSON commands: `answer`, `offer`, `reconnectOffer`, `reconnect`, `iceCandidate` (arg `mLine`), `callEnd` (calls).
|
||||
- Behaviour strings: `kOffer, is_reconnect:`; `pending candidate of a previous ICE generation, ufrag=` (stale-ufrag
|
||||
candidates are dropped); recovery "tier-1 ICE restart" / "tier-2 full reset";
|
||||
`OnRemoteSupportedCodecsChanged … realign` (the offer that follows our answer is a codec realignment);
|
||||
`kJoinResponse: decision=false or offer empty, not applying`.
|
||||
- Default STUN servers of the official client: `stun:turn.teamspeak.com:3478`, `stun:turn2.teamspeak.com:3478`.
|
||||
- An SFU path (mediasoup: `create-stream`, `transport-connect`, `consume-stream`) also exists. TeamsPeach implements
|
||||
only the P2P path and reports SFU streams as unsupported.
|
||||
|
||||
## Public protocol notes used
|
||||
|
||||
<https://raw.githubusercontent.com/phattbeats/plnt-android/main/STREAMING.md> (read for protocol knowledge only;
|
||||
no code copied): discover with `requeststreaminfo clid`, join with `joinstreamrequest id clid msg is_remove=0`,
|
||||
offer in `notifyrespondjoinstreamrequest decision=1 offer`, answer `{"cmd":"answer","args":{"answer":sdp}}`,
|
||||
trickle `{"cmd":"iceCandidate","args":{"mLine","mid","sdp"}}`, mandatory answer to the realign `offer`,
|
||||
leave with `is_remove=1`.
|
||||
@@ -0,0 +1,91 @@
|
||||
{
|
||||
"name": "teamspeach",
|
||||
"productName": "TeamsPeach",
|
||||
"version": "0.1.0",
|
||||
"description": "Desktop TeamSpeak 6 client: voice, chat and TS6 screenshare viewing",
|
||||
"main": "app/main/main.js",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"author": "TeamsPeach",
|
||||
"scripts": {
|
||||
"start": "electron .",
|
||||
"dev": "electron . --enable-logging",
|
||||
"test": "node --test \"test/*.test.*\"",
|
||||
"smoke": "node scripts/smoke-ui.mjs",
|
||||
"smoke:core": "node scripts/core-smoke.mjs core/target/release/teamspeach-core.exe",
|
||||
"dist:win-x64": "node scripts/dist.mjs --os win --arch x64",
|
||||
"dist:win-arm64": "node scripts/dist.mjs --os win --arch arm64",
|
||||
"dist:linux-x64": "node scripts/dist.mjs --os linux --arch x64",
|
||||
"dist:linux-arm64": "node scripts/dist.mjs --os linux --arch arm64",
|
||||
"dist:mac-x64": "node scripts/dist.mjs --os mac --arch x64",
|
||||
"dist:mac-arm64": "node scripts/dist.mjs --os mac --arch arm64"
|
||||
},
|
||||
"devDependencies": {
|
||||
"electron": "44.9.3",
|
||||
"electron-builder": "26.15.3",
|
||||
"playwright-core": "^1.56.0"
|
||||
},
|
||||
"build": {
|
||||
"appId": "dev.teamspeach.desktop",
|
||||
"productName": "TeamsPeach",
|
||||
"directories": {
|
||||
"output": "dist",
|
||||
"buildResources": "build"
|
||||
},
|
||||
"files": [
|
||||
"app/**/*",
|
||||
"package.json"
|
||||
],
|
||||
"extraResources": [
|
||||
{
|
||||
"from": "core-bin/${os}-${arch}/",
|
||||
"to": "core/",
|
||||
"filter": [
|
||||
"teamspeach-core",
|
||||
"teamspeach-core.exe"
|
||||
]
|
||||
},
|
||||
{
|
||||
"from": "core-bin/${os}-${arch}/THIRD_PARTY_NOTICES.md",
|
||||
"to": "licenses/teamspeach-core-THIRD_PARTY_NOTICES.md"
|
||||
},
|
||||
{
|
||||
"from": "LICENSES/",
|
||||
"to": "licenses/"
|
||||
}
|
||||
],
|
||||
"asar": true,
|
||||
"linux": {
|
||||
"target": [
|
||||
"AppImage",
|
||||
"tar.gz"
|
||||
],
|
||||
"category": "Network",
|
||||
"executableName": "teamspeach",
|
||||
"icon": "build/icon.png",
|
||||
"synopsis": "TeamSpeak 6 voice client"
|
||||
},
|
||||
"win": {
|
||||
"target": [
|
||||
"nsis",
|
||||
"zip"
|
||||
],
|
||||
"icon": "build/icon.png"
|
||||
},
|
||||
"nsis": {
|
||||
"oneClick": false,
|
||||
"allowToChangeInstallationDirectory": true
|
||||
},
|
||||
"mac": {
|
||||
"target": [
|
||||
"dmg",
|
||||
"zip"
|
||||
],
|
||||
"category": "public.app-category.social-networking",
|
||||
"icon": "build/icon.png",
|
||||
"extendInfo": {
|
||||
"NSMicrophoneUsageDescription": "TeamsPeach передаёт ваш голос на сервер TeamSpeak."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Reads the executable header and reports {format, arch}. Used to refuse packaging a core built for
|
||||
// another OS/CPU. node scripts/binary-arch.mjs <file> [--expect linux-arm64]
|
||||
import { openSync, readSync, closeSync } from 'node:fs';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
|
||||
const PE_MACHINES = { 0x8664: 'x64', 0xaa64: 'arm64', 0x014c: 'ia32' };
|
||||
const ELF_MACHINES = { 0x3e: 'x64', 0xb7: 'arm64', 0x03: 'ia32', 0x28: 'armv7l' };
|
||||
const MACHO_CPUS = { 0x01000007: 'x64', 0x0100000c: 'arm64' };
|
||||
|
||||
export function binaryArch(file) {
|
||||
const fd = openSync(file, 'r');
|
||||
try {
|
||||
const head = Buffer.alloc(4096);
|
||||
const n = readSync(fd, head, 0, head.length, 0);
|
||||
if (n >= 64 && head.readUInt16LE(0) === 0x5a4d) {
|
||||
const pe = head.readUInt32LE(0x3c);
|
||||
if (pe + 6 <= n && head.readUInt32LE(pe) === 0x00004550) {
|
||||
return { os: 'win', arch: PE_MACHINES[head.readUInt16LE(pe + 4)] ?? `pe-0x${head.readUInt16LE(pe + 4).toString(16)}` };
|
||||
}
|
||||
}
|
||||
if (n >= 20 && head.readUInt32BE(0) === 0x7f454c46) {
|
||||
const little = head[5] === 1;
|
||||
const machine = little ? head.readUInt16LE(18) : head.readUInt16BE(18);
|
||||
return { os: 'linux', arch: ELF_MACHINES[machine] ?? `elf-0x${machine.toString(16)}` };
|
||||
}
|
||||
if (n >= 8 && head.readUInt32LE(0) === 0xfeedfacf) {
|
||||
return { os: 'mac', arch: MACHO_CPUS[head.readUInt32LE(4)] ?? `macho-0x${head.readUInt32LE(4).toString(16)}` };
|
||||
}
|
||||
if (n >= 8 && head.readUInt32BE(0) === 0xcafebabe) return { os: 'mac', arch: 'universal' };
|
||||
return { os: 'unknown', arch: 'unknown' };
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
const file = process.argv[2];
|
||||
const expectIdx = process.argv.indexOf('--expect');
|
||||
const info = binaryArch(file);
|
||||
console.log(JSON.stringify({ file, ...info }));
|
||||
if (expectIdx > 0) {
|
||||
const want = process.argv[expectIdx + 1];
|
||||
if (`${info.os}-${info.arch}` !== want) {
|
||||
console.error(`expected ${want}, got ${info.os}-${info.arch}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// Offline smoke of a built core binary over its real stdio protocol (docs/bridge.md):
|
||||
// ready → profile_get (missing) → profile_create → rename → restart → same UID + persisted nickname.
|
||||
// No network, no server. Optional --wrapper runs the binary through an emulator (e.g. qemu-aarch64).
|
||||
//
|
||||
// node scripts/core-smoke.mjs <core-binary> [--wrapper "qemu-aarch64 -L /usr/aarch64-linux-gnu"]
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import readline from 'node:readline';
|
||||
|
||||
const binary = path.resolve(process.argv[2] ?? '');
|
||||
const wi = process.argv.indexOf('--wrapper');
|
||||
const wrapper = wi > 0 ? process.argv[wi + 1].split(' ').filter(Boolean) : [];
|
||||
const dataDir = mkdtempSync(path.join(tmpdir(), 'teamspeach-core-smoke-'));
|
||||
|
||||
function start() {
|
||||
const [cmd, ...pre] = wrapper.length ? wrapper : [binary];
|
||||
const args = wrapper.length ? [...pre, binary, '--data-dir', dataDir] : ['--data-dir', dataDir];
|
||||
const child = spawn(cmd, args, { stdio: ['pipe', 'pipe', 'inherit'] });
|
||||
const waiting = new Map();
|
||||
let ready;
|
||||
const readyP = new Promise((r) => { ready = r; });
|
||||
readline.createInterface({ input: child.stdout }).on('line', (line) => {
|
||||
const msg = JSON.parse(line);
|
||||
if (msg.event === 'ready') ready(msg);
|
||||
else if (msg.id && waiting.has(msg.id)) {
|
||||
waiting.get(msg.id)(msg);
|
||||
waiting.delete(msg.id);
|
||||
}
|
||||
});
|
||||
let n = 0;
|
||||
const request = (cmd, args) => new Promise((resolve, reject) => {
|
||||
const id = `s${++n}`;
|
||||
const timer = setTimeout(() => reject(new Error(`${cmd} timed out`)), 60000);
|
||||
waiting.set(id, (m) => {
|
||||
clearTimeout(timer);
|
||||
resolve(m);
|
||||
});
|
||||
child.stdin.write(`${JSON.stringify(args ? { id, cmd, args } : { id, cmd })}\n`);
|
||||
});
|
||||
const exited = new Promise((r) => child.on('exit', (code) => r(code)));
|
||||
return { child, request, readyP, exited };
|
||||
}
|
||||
|
||||
function check(cond, message) {
|
||||
if (!cond) throw new Error(message);
|
||||
console.log(`ok - ${message}`);
|
||||
}
|
||||
|
||||
let code = 0;
|
||||
try {
|
||||
let core = start();
|
||||
const ready = await Promise.race([core.readyP, new Promise((_, rej) => setTimeout(() => rej(new Error('no ready event')), 60000))]);
|
||||
check(ready.protocol === 1, `ready protocol 1 (core ${ready.core_version})`);
|
||||
let r = await core.request('profile_get');
|
||||
check(r.ok && r.result.exists === false, 'fresh data dir has no profile');
|
||||
r = await core.request('profile_create', { nickname: 'CI Probe' });
|
||||
check(r.ok && typeof r.result.uid === 'string' && r.result.uid.length > 10, `profile created uid=${r.ok ? r.result.uid : '-'}`);
|
||||
const uid = r.result.uid;
|
||||
r = await core.request('profile_create', { nickname: 'Again' });
|
||||
check(!r.ok && r.error.code === 'profile_exists', 'second profile_create refused');
|
||||
r = await core.request('rename', { nickname: 'CI Renamed' });
|
||||
check(r.ok && r.result.uid === uid && r.result.nickname === 'CI Renamed', 'rename keeps uid');
|
||||
r = await core.request('rename', { nickname: 'x' });
|
||||
check(!r.ok && r.error.code === 'invalid_nickname', 'short nickname rejected');
|
||||
await core.request('shutdown');
|
||||
check((await core.exited) === 0, 'clean shutdown exit 0');
|
||||
|
||||
core = start();
|
||||
await core.readyP;
|
||||
r = await core.request('profile_get');
|
||||
check(r.ok && r.result.uid === uid && r.result.nickname === 'CI Renamed', 'restart: same uid and persisted nickname');
|
||||
await core.request('shutdown');
|
||||
await core.exited;
|
||||
} catch (err) {
|
||||
console.error(`not ok - ${err.message}`);
|
||||
code = 1;
|
||||
} finally {
|
||||
rmSync(dataDir, { recursive: true, force: true });
|
||||
}
|
||||
process.exit(code);
|
||||
@@ -0,0 +1,77 @@
|
||||
// Packages TeamsPeach for one OS/arch. Refuses to package without a native core of exactly that
|
||||
// OS/arch (header check), and ships the core's third-party notices next to it.
|
||||
//
|
||||
// node scripts/dist.mjs --os win|linux|mac --arch x64|arm64 [--core <path>] [--targets "nsis zip"]
|
||||
//
|
||||
// Default core path: core/target/<rust-triple>/release/…, else core/target/release/… (host build).
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { copyFileSync, existsSync, mkdirSync, rmSync, readdirSync, statSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { binaryArch } from './binary-arch.mjs';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const argv = process.argv.slice(2);
|
||||
const opt = (n, d) => (argv.indexOf(`--${n}`) >= 0 ? argv[argv.indexOf(`--${n}`) + 1] : d);
|
||||
const os = opt('os');
|
||||
const arch = opt('arch');
|
||||
const TRIPLES = {
|
||||
'win-x64': 'x86_64-pc-windows-msvc',
|
||||
'win-arm64': 'aarch64-pc-windows-msvc',
|
||||
'linux-x64': 'x86_64-unknown-linux-gnu',
|
||||
'linux-arm64': 'aarch64-unknown-linux-gnu',
|
||||
'mac-x64': 'x86_64-apple-darwin',
|
||||
'mac-arm64': 'aarch64-apple-darwin',
|
||||
};
|
||||
const key = `${os}-${arch}`;
|
||||
if (!TRIPLES[key]) {
|
||||
console.error(`unsupported --os/--arch ${key}; one of ${Object.keys(TRIPLES).join(', ')}`);
|
||||
process.exit(2);
|
||||
}
|
||||
const exe = os === 'win' ? 'teamspeach-core.exe' : 'teamspeach-core';
|
||||
const candidates = [
|
||||
opt('core'),
|
||||
path.join(root, 'core', 'target', TRIPLES[key], 'release', exe),
|
||||
path.join(root, 'core', 'target', 'release', exe),
|
||||
].filter(Boolean);
|
||||
const core = candidates.find((c) => existsSync(c));
|
||||
if (!core) {
|
||||
console.error(`No core binary for ${key}. Looked at:\n ${candidates.join('\n ')}\nBuild it first: cargo build --release --locked --manifest-path core/Cargo.toml --target ${TRIPLES[key]}`);
|
||||
process.exit(1);
|
||||
}
|
||||
const info = binaryArch(core);
|
||||
if (info.os !== os || info.arch !== arch) {
|
||||
console.error(`Core ${core} is ${info.os}-${info.arch}, not ${key}. Refusing to package.`);
|
||||
process.exit(1);
|
||||
}
|
||||
const notices = path.join(root, 'core', 'THIRD_PARTY_NOTICES.md');
|
||||
if (!existsSync(notices)) {
|
||||
console.error('core/THIRD_PARTY_NOTICES.md is missing; it must ship with the binary.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const stage = path.join(root, 'core-bin', key);
|
||||
rmSync(stage, { recursive: true, force: true });
|
||||
mkdirSync(stage, { recursive: true });
|
||||
copyFileSync(core, path.join(stage, exe));
|
||||
copyFileSync(notices, path.join(stage, 'THIRD_PARTY_NOTICES.md'));
|
||||
console.log(`staged ${core} (${info.os}-${info.arch}, ${statSync(core).size} bytes) → ${stage}`);
|
||||
|
||||
const builderArgs = [`--${os}`, `--${arch}`, '--publish', 'never'];
|
||||
const targets = opt('targets');
|
||||
if (targets) builderArgs.splice(1, 0, ...targets.split(' '));
|
||||
const cli = path.join(root, 'node_modules', 'electron-builder', 'cli.js');
|
||||
const run = spawnSync(process.execPath, [cli, ...builderArgs], { cwd: root, stdio: 'inherit' });
|
||||
if (run.status !== 0) process.exit(run.status ?? 1);
|
||||
|
||||
// Verify the packaged app really contains the core for this target.
|
||||
const dist = path.join(root, 'dist');
|
||||
const unpacked = readdirSync(dist).filter((d) => d.endsWith('-unpacked') || d === 'mac' || d === 'mac-arm64').map((d) => path.join(dist, d));
|
||||
const packagedCore = unpacked
|
||||
.map((d) => (os === 'mac' ? path.join(d, 'TeamsPeach.app', 'Contents', 'Resources', 'core', exe) : path.join(d, 'resources', 'core', exe)))
|
||||
.find((p) => existsSync(p) && binaryArch(p).arch === arch);
|
||||
if (!packagedCore) {
|
||||
console.error('Packaged output does not contain resources/core for this target.');
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`packaged core verified: ${packagedCore} (${JSON.stringify(binaryArch(packagedCore))})`);
|
||||
@@ -0,0 +1,105 @@
|
||||
// Static check that ELF64 files can be mapped on kernels with large pages (Asahi Linux uses 16 KiB):
|
||||
// every PT_LOAD must have p_align >= PAGE and p_offset ≡ p_vaddr (mod PAGE).
|
||||
// Also lists DT_NEEDED libraries and the highest GLIBC_x.y symbol version referenced.
|
||||
//
|
||||
// node scripts/elf-pagesize.mjs <file-or-dir> [...] [--page 16384] [--json out.json]
|
||||
import { readFileSync, readdirSync, statSync, writeFileSync, openSync, readSync, closeSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const argv = process.argv.slice(2);
|
||||
const pi = argv.indexOf('--page');
|
||||
const PAGE = pi >= 0 ? Number(argv[pi + 1]) : 16384;
|
||||
const ji = argv.indexOf('--json');
|
||||
const valueIdx = new Set([pi, ji].filter((i) => i >= 0).map((i) => i + 1));
|
||||
const inputs = argv.filter((a, i) => !a.startsWith('--') && !valueIdx.has(i));
|
||||
|
||||
function isElf(file) {
|
||||
const fd = openSync(file, 'r');
|
||||
try {
|
||||
const b = Buffer.alloc(4);
|
||||
return readSync(fd, b, 0, 4, 0) === 4 && b.readUInt32BE(0) === 0x7f454c46;
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
function walk(p, out) {
|
||||
const st = statSync(p, { throwIfNoEntry: false });
|
||||
if (!st) return;
|
||||
if (st.isDirectory()) for (const e of readdirSync(p)) walk(path.join(p, e), out);
|
||||
else if (st.isFile() && st.size > 64 && isElf(p)) out.push(p);
|
||||
}
|
||||
|
||||
function inspect(file) {
|
||||
const b = readFileSync(file);
|
||||
if (b[4] !== 2 || b[5] !== 1) return { file, error: 'not ELF64 little-endian' };
|
||||
const machine = b.readUInt16LE(18);
|
||||
const phoff = Number(b.readBigUInt64LE(32));
|
||||
const phentsize = b.readUInt16LE(54);
|
||||
const phnum = b.readUInt16LE(56);
|
||||
const shoff = Number(b.readBigUInt64LE(40));
|
||||
const shentsize = b.readUInt16LE(58);
|
||||
const shnum = b.readUInt16LE(60);
|
||||
const loads = [];
|
||||
let dynamic = null;
|
||||
for (let i = 0; i < phnum; i += 1) {
|
||||
const o = phoff + i * phentsize;
|
||||
const type = b.readUInt32LE(o);
|
||||
const offset = b.readBigUInt64LE(o + 8);
|
||||
const vaddr = b.readBigUInt64LE(o + 16);
|
||||
const filesz = b.readBigUInt64LE(o + 32);
|
||||
const align = b.readBigUInt64LE(o + 48);
|
||||
if (type === 1) {
|
||||
const congruent = offset % BigInt(PAGE) === vaddr % BigInt(PAGE);
|
||||
loads.push({ align: Number(align), ok: align >= BigInt(PAGE) && congruent, congruent });
|
||||
} else if (type === 2) {
|
||||
dynamic = { offset: Number(offset), size: Number(filesz) };
|
||||
}
|
||||
}
|
||||
// DT_NEEDED via .dynamic + .dynstr (section headers), GLIBC versions via raw string scan.
|
||||
const needed = [];
|
||||
if (dynamic && shoff && shnum) {
|
||||
let dynstr = null;
|
||||
for (let i = 0; i < shnum; i += 1) {
|
||||
const o = shoff + i * shentsize;
|
||||
const type = b.readUInt32LE(o + 4);
|
||||
const link = b.readUInt32LE(o + 40);
|
||||
if (type === 6) {
|
||||
const lo = shoff + link * shentsize;
|
||||
dynstr = Number(b.readBigUInt64LE(lo + 24));
|
||||
}
|
||||
}
|
||||
if (dynstr !== null) {
|
||||
for (let o = dynamic.offset; o + 16 <= dynamic.offset + dynamic.size; o += 16) {
|
||||
const tag = b.readBigInt64LE(o);
|
||||
if (tag === 0n) break;
|
||||
if (tag === 1n) {
|
||||
const start = dynstr + Number(b.readBigUInt64LE(o + 8));
|
||||
needed.push(b.toString('latin1', start, b.indexOf(0, start)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const glibc = [...new Set(b.toString('latin1').match(/GLIBC_[0-9]+(\.[0-9]+)+/g) ?? [])]
|
||||
.sort((x, y) => x.slice(6).split('.').map(Number).reduce((acc, n, i) => acc || n - (y.slice(6).split('.').map(Number)[i] ?? 0), 0));
|
||||
return {
|
||||
file,
|
||||
machine: machine === 0xb7 ? 'aarch64' : machine === 0x3e ? 'x86-64' : `0x${machine.toString(16)}`,
|
||||
minLoadAlign: loads.length ? Math.min(...loads.map((l) => l.align)) : null,
|
||||
pageOk: loads.every((l) => l.ok),
|
||||
needed,
|
||||
maxGlibc: glibc.at(-1) ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
const files = [];
|
||||
for (const input of inputs) walk(path.resolve(input), files);
|
||||
const results = files.map(inspect);
|
||||
let bad = 0;
|
||||
for (const r of results) {
|
||||
if (r.error || !r.pageOk) bad += 1;
|
||||
console.log(`${r.pageOk ? 'ok ' : 'FAIL'} ${r.machine ?? ''} align=${r.minLoadAlign} glibc=${r.maxGlibc ?? '-'} ${path.relative(process.cwd(), r.file)}${r.needed?.length ? ` needs ${r.needed.join(',')}` : ''}${r.error ? ` (${r.error})` : ''}`);
|
||||
}
|
||||
console.log(`${results.length} ELF files, ${bad} incompatible with ${PAGE}-byte pages`);
|
||||
if (jsonOut) writeFileSync(jsonOut, JSON.stringify({ page: PAGE, results }, null, 2));
|
||||
process.exit(bad ? 1 : 0);
|
||||
@@ -0,0 +1,195 @@
|
||||
// Browser-pipeline check of the viewer's media lifecycle inside the real Electron renderer.
|
||||
// A throwaway RTCPeerConnection in the same page plays the streamer: it sends a canvas video and a
|
||||
// generated 440 Hz tone, trickles ICE before its offer is delivered, and sends a realign offer.
|
||||
// The real viewer code (watch.js + StreamViewerSession) receives it through an injected transport.
|
||||
//
|
||||
// This proves Chromium-side behaviour (track attach, playback, output-device routing, stop/switch
|
||||
// while callbacks are pending). It is NOT TeamSpeak interoperability: see scripts/probe-stream.mjs.
|
||||
//
|
||||
// node scripts/loopback-stream.mjs --out docs/evidence/runtime/<name>
|
||||
import { _electron as electron } from 'playwright-core';
|
||||
import { mkdirSync, writeFileSync, mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { createRequire } from 'node:module';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const require = createRequire(import.meta.url);
|
||||
const electronPath = require('electron');
|
||||
const argv = process.argv.slice(2);
|
||||
const out = path.resolve(root, argv[argv.indexOf('--out') + 1] ?? 'loopback-out');
|
||||
mkdirSync(out, { recursive: true });
|
||||
const profile = mkdtempSync(path.join(tmpdir(), 'teamspeach-loopback-'));
|
||||
const result = { startedAt: new Date().toISOString(), steps: [], console: [] };
|
||||
const step = (name, data = {}) => {
|
||||
result.steps.push({ name, ...data });
|
||||
console.log(`[loopback] ${name}`, JSON.stringify(data));
|
||||
};
|
||||
|
||||
// Runs in the page: builds a fake streamer bound to stream id `id`.
|
||||
const installStreamer = () => {
|
||||
window.__loop = {
|
||||
async make(id) {
|
||||
const watch = await import('/js/watch.js');
|
||||
const ctx = new AudioContext();
|
||||
const osc = ctx.createOscillator();
|
||||
osc.frequency.value = 440;
|
||||
const gain = ctx.createGain();
|
||||
gain.gain.value = 0.2;
|
||||
const dest = ctx.createMediaStreamDestination();
|
||||
osc.connect(gain).connect(dest);
|
||||
osc.start();
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = 640;
|
||||
canvas.height = 360;
|
||||
const g = canvas.getContext('2d');
|
||||
let n = 0;
|
||||
const timer = setInterval(() => {
|
||||
g.fillStyle = `hsl(${(n += 7) % 360} 60% 50%)`;
|
||||
g.fillRect(0, 0, 640, 360);
|
||||
}, 33);
|
||||
const ms = new MediaStream([canvas.captureStream(30).getVideoTracks()[0], dest.stream.getAudioTracks()[0]]);
|
||||
const pc = new RTCPeerConnection();
|
||||
for (const t of ms.getTracks()) pc.addTrack(t, ms);
|
||||
const emit = (name, item) => watch.onStreamEvent({ event: 'stream', name, items: [{ id, clid: '999', ...item }] });
|
||||
pc.onicecandidate = (e) => {
|
||||
if (e.candidate) emit('notifystreamsignaling', { json: JSON.stringify({ cmd: 'iceCandidate', args: { mLine: e.candidate.sdpMLineIndex, mid: e.candidate.sdpMid, sdp: e.candidate.candidate } }) });
|
||||
};
|
||||
let answers = 0;
|
||||
const transport = {
|
||||
join: async () => {
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
// Deliver the offer a little later so trickled candidates arrive first (buffering path).
|
||||
setTimeout(() => emit('notifyrespondjoinstreamrequest', { decision: '1', offer: pc.localDescription.sdp, msg: '' }), 150);
|
||||
},
|
||||
send: async (_id, _clid, json) => {
|
||||
if (json.cmd === 'answer') {
|
||||
await pc.setRemoteDescription({ type: 'answer', sdp: json.args.answer });
|
||||
answers += 1;
|
||||
if (answers === 1) {
|
||||
// Realign offer, as a TS6 streamer does after the first answer.
|
||||
setTimeout(async () => {
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
emit('notifystreamsignaling', { json: JSON.stringify({ cmd: 'offer', args: { offer: pc.localDescription.sdp } }) });
|
||||
}, 200);
|
||||
}
|
||||
} else if (json.cmd === 'iceCandidate') {
|
||||
await pc.addIceCandidate({ candidate: json.args.sdp, sdpMid: json.args.mid, sdpMLineIndex: json.args.mLine });
|
||||
}
|
||||
},
|
||||
leave: async () => {
|
||||
clearInterval(timer);
|
||||
pc.close();
|
||||
ctx.close();
|
||||
},
|
||||
};
|
||||
return { transport, pc };
|
||||
},
|
||||
async start(id) {
|
||||
const watch = await import('/js/watch.js');
|
||||
const { transport } = await this.make(id);
|
||||
watch.startWatching({ id, clientId: 999, name: `loop ${id}`, nickname: 'loopback', fields: { audio: '1' } }, transport);
|
||||
},
|
||||
async stop() {
|
||||
const watch = await import('/js/watch.js');
|
||||
watch.stopWatching();
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
let app;
|
||||
let page;
|
||||
let failed = null;
|
||||
try {
|
||||
// Synthetic capture device only: getUserMedia permission unlocks real output-device enumeration.
|
||||
app = await electron.launch({ executablePath: electronPath, args: [root, '--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream'], env: { ...process.env, TEAMSPEACH_PROFILE_DIR: profile } });
|
||||
page = await app.firstWindow();
|
||||
page.on('console', (m) => result.console.push(`${m.type()}: ${m.text()}`));
|
||||
page.on('pageerror', (e) => result.console.push(`pageerror: ${e.message}`));
|
||||
await page.waitForSelector('#view-onboarding', { state: 'visible', timeout: 20000 });
|
||||
await page.fill('#onboarding-nick', 'LoopbackTest');
|
||||
await page.click('#onboarding-submit');
|
||||
await page.waitForSelector('#view-app', { state: 'visible', timeout: 20000 });
|
||||
// Not connected to any server: show the session area so the viewer panel is laid out.
|
||||
await page.evaluate(() => {
|
||||
document.querySelector('#connect-view').hidden = true;
|
||||
document.querySelector('#session-view').hidden = false;
|
||||
});
|
||||
await page.evaluate(installStreamer);
|
||||
await page.$eval('#stream-volume', (el) => {
|
||||
el.value = '5';
|
||||
el.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
});
|
||||
|
||||
const stats = () => page.evaluate(() => window.teamspeachDiagnostics.snapshot().watch);
|
||||
const errorToasts = () => page.$$eval('.toast[data-kind="error"]', (els) => els.map((e) => e.textContent));
|
||||
|
||||
// 1. Switch while the first session's track-attach callback is pending, then stop/start rapidly.
|
||||
await page.evaluate(async () => {
|
||||
await window.__loop.start('A');
|
||||
await window.__loop.stop();
|
||||
await window.__loop.start('B');
|
||||
});
|
||||
await page.waitForFunction(() => window.teamspeachDiagnostics.snapshot().watch.framesDecoded > 30, null, { timeout: 20000 });
|
||||
await page.waitForTimeout(2000);
|
||||
let s = await stats();
|
||||
const srcIsCurrent = await page.evaluate(() => document.querySelector('#stream-video').srcObject?.getTracks().length ?? 0);
|
||||
step('switch while pending', { state: s.state, framesDecoded: s.framesDecoded, offersApplied: s.offersApplied, answersSent: s.answersSent, inboundAudioPackets: s.inboundAudioPackets, tracksOnElement: srcIsCurrent, errors: await errorToasts() });
|
||||
if (s.offersApplied < 2) throw new Error('realign offer was not answered');
|
||||
if (!(s.inboundAudioPackets > 0)) throw new Error('no inbound audio packets');
|
||||
|
||||
// 2. Default output: no setSinkId call is needed and no error may appear.
|
||||
step('default sink', { sinkId: s.sinkId, sinkError: s.sinkError, errors: await errorToasts() });
|
||||
|
||||
// 3. Select a concrete output device through the real settings UI while the stream plays.
|
||||
await page.click('#btn-settings');
|
||||
await page.waitForSelector('#settings-view', { state: 'visible' });
|
||||
await page.click('#mic-test');
|
||||
await page.waitForTimeout(1200);
|
||||
await page.click('#mic-test');
|
||||
await page.waitForTimeout(300);
|
||||
const options = await page.$$eval('#output-device option', (os) => os.map((o) => ({ value: o.value, label: o.textContent })));
|
||||
const device = options.find((o) => o.value);
|
||||
if (device) {
|
||||
await page.selectOption('#output-device', device.value);
|
||||
await page.waitForTimeout(1500);
|
||||
s = await stats();
|
||||
const elementSink = await page.evaluate(() => document.querySelector('#stream-video').sinkId);
|
||||
step('selected sink', { device: device.label, elementSinkMatches: elementSink === device.value, sinkError: s.sinkError, errors: await errorToasts() });
|
||||
if (elementSink !== device.value) throw new Error('stream element not routed to selected device');
|
||||
// Restart viewing with the device already selected: applied on `playing`.
|
||||
await page.click('#settings-back');
|
||||
await page.evaluate(() => {
|
||||
document.querySelector('#connect-view').hidden = true;
|
||||
document.querySelector('#session-view').hidden = false;
|
||||
});
|
||||
await page.evaluate(async () => {
|
||||
await window.__loop.stop();
|
||||
await window.__loop.start('C');
|
||||
});
|
||||
await page.waitForFunction(() => window.teamspeachDiagnostics.snapshot().watch.inboundAudioPackets > 50, null, { timeout: 20000 });
|
||||
s = await stats();
|
||||
step('restart with selected sink', { sinkId: s.sinkId === device.value, sinkError: s.sinkError, framesDecoded: s.framesDecoded, inboundAudioPackets: s.inboundAudioPackets, errors: await errorToasts() });
|
||||
await page.selectOption('#output-device', '').catch(() => {});
|
||||
} else {
|
||||
step('selected sink skipped', { reason: 'no non-default output device enumerated' });
|
||||
}
|
||||
await page.evaluate(() => { document.querySelector('#stream-video').style.visibility = 'hidden'; });
|
||||
await page.screenshot({ path: path.join(out, '30-loopback-viewer-redacted.png') });
|
||||
await page.evaluate(() => window.__loop.stop());
|
||||
const errs = await errorToasts();
|
||||
step('final', { errors: errs });
|
||||
if (errs.length) throw new Error(`error toasts: ${errs.join(' | ')}`);
|
||||
} catch (err) {
|
||||
failed = err;
|
||||
step('FAILED', { error: String(err.stack || err) });
|
||||
} finally {
|
||||
if (app) await app.close().catch(() => {});
|
||||
rmSync(profile, { recursive: true, force: true });
|
||||
}
|
||||
result.ok = !failed;
|
||||
result.note = 'Loopback inside Chromium: validates the browser media pipeline only, not TS6 interoperability.';
|
||||
writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2));
|
||||
console.log(`[loopback] ${result.ok ? 'OK' : 'FAILED'} → ${out}`);
|
||||
process.exit(result.ok ? 0 : 1);
|
||||
@@ -0,0 +1,131 @@
|
||||
// Watches a real TS6 screenshare with the real TeamsPeach UI and records protocol/media evidence.
|
||||
// Microphone is muted before connecting and push-to-talk is never pressed: nothing is transmitted.
|
||||
// No video pixels are saved: the video element is hidden for the UI screenshot.
|
||||
//
|
||||
// node scripts/probe-stream.mjs --server 10.10.10.160:9987 --channel cs --out docs/evidence/runtime/<name> [--seconds 40]
|
||||
import { _electron as electron } from 'playwright-core';
|
||||
import { mkdirSync, writeFileSync, mkdtempSync, readFileSync, existsSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { createRequire } from 'node:module';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const require = createRequire(import.meta.url);
|
||||
const electronPath = require('electron');
|
||||
const argv = process.argv.slice(2);
|
||||
const opt = (n, d) => (argv.indexOf(`--${n}`) >= 0 ? argv[argv.indexOf(`--${n}`) + 1] : d);
|
||||
const server = opt('server');
|
||||
const channelName = opt('channel', 'cs');
|
||||
const seconds = Number(opt('seconds', '40'));
|
||||
const nickname = opt('nick', 'TeamsPeach-Probe');
|
||||
const out = path.resolve(root, opt('out', 'probe-stream-out'));
|
||||
const profile = opt('profile') ? path.resolve(opt('profile')) : mkdtempSync(path.join(tmpdir(), 'teamspeach-probe-'));
|
||||
mkdirSync(out, { recursive: true });
|
||||
|
||||
const result = { startedAt: new Date().toISOString(), server, channelName, profile, steps: [], samples: [], console: [] };
|
||||
const step = (name, data = {}) => {
|
||||
result.steps.push({ name, at: new Date().toISOString(), ...data });
|
||||
console.log(`[probe] ${name}`, JSON.stringify(data));
|
||||
};
|
||||
const diag = (page) => page.evaluate(() => window.teamspeachDiagnostics.snapshot());
|
||||
|
||||
let app;
|
||||
let page;
|
||||
let failed = null;
|
||||
try {
|
||||
app = await electron.launch({ executablePath: electronPath, args: [root], env: { ...process.env, TEAMSPEACH_PROFILE_DIR: profile } });
|
||||
page = await app.firstWindow();
|
||||
page.on('console', (m) => result.console.push(`${m.type()}: ${m.text()}`));
|
||||
page.on('pageerror', (e) => result.console.push(`pageerror: ${e.message}`));
|
||||
await page.setViewportSize({ width: 1280, height: 800 }).catch(() => {});
|
||||
const onboarding = await page.waitForSelector('#view-onboarding, #view-app', { state: 'visible', timeout: 20000 });
|
||||
if ((await onboarding.getAttribute('id')) === 'view-onboarding') {
|
||||
await page.fill('#onboarding-nick', nickname);
|
||||
await page.click('#onboarding-submit');
|
||||
await page.waitForSelector('#view-app', { state: 'visible', timeout: 20000 });
|
||||
}
|
||||
// Mute before connecting (applied by the core at connect).
|
||||
await page.click('#btn-mute');
|
||||
await page.waitForFunction(() => window.teamspeachDiagnostics.snapshot().audio.input_muted === true, null, { timeout: 10000 });
|
||||
step('muted before connect', { profile: (await diag(page)).profile });
|
||||
|
||||
await page.fill('#connect-address', server);
|
||||
await page.click('#connect-submit');
|
||||
await page.waitForFunction(() => window.teamspeachDiagnostics.snapshot().conn === 'connected', null, { timeout: 60000 });
|
||||
let d = await diag(page);
|
||||
step('connected', { server: d.server, ownClientId: d.ownClientId, channel: d.ownChannel, audio: d.audio });
|
||||
const findRow = (name) => Array.from(document.querySelectorAll('#tree .channel-row')).some((r) => r.querySelector('.row-label')?.textContent.trim().toLowerCase() === name.toLowerCase());
|
||||
await page.waitForFunction(findRow, channelName, { timeout: 20000 }).catch(() => {});
|
||||
const joined = await page.evaluate((name) => {
|
||||
const rows = Array.from(document.querySelectorAll('#tree .channel-row'));
|
||||
const row = rows.find((r) => r.querySelector('.row-label')?.textContent.trim().toLowerCase() === name.toLowerCase());
|
||||
if (!row) return false;
|
||||
row.querySelector('.row-btn').click();
|
||||
return true;
|
||||
}, channelName);
|
||||
if (!joined) throw new Error(`channel "${channelName}" not found`);
|
||||
await page.waitForFunction((name) => (window.teamspeachDiagnostics.snapshot().ownChannel ?? '').toLowerCase() === name.toLowerCase(), channelName, { timeout: 15000 });
|
||||
d = await diag(page);
|
||||
step('joined channel', { channel: d.ownChannel, members: d.clients.filter((c) => c.channel === d.clients.find((x) => x.id === d.ownClientId).channel).map((c) => c.nickname) });
|
||||
|
||||
await page.waitForFunction(() => window.teamspeachDiagnostics.snapshot().streams.length > 0, null, { timeout: 25000 });
|
||||
d = await diag(page);
|
||||
step('streams discovered', { streams: d.streams });
|
||||
const stream = d.streams[0];
|
||||
await page.click(`#tree [data-key="u:${stream.clientId}"] .watch-btn`);
|
||||
step('watch clicked', { streamId: stream.id, clientId: stream.clientId });
|
||||
|
||||
const deadline = Date.now() + seconds * 1000;
|
||||
let firstFrameAt = null;
|
||||
while (Date.now() < deadline) {
|
||||
await page.waitForTimeout(2000);
|
||||
d = await diag(page);
|
||||
result.samples.push({ at: new Date().toISOString(), ...d.watch });
|
||||
if (!firstFrameAt && d.watch.framesDecoded > 0) {
|
||||
firstFrameAt = new Date().toISOString();
|
||||
step('first decoded frame', { ...d.watch });
|
||||
await page.evaluate(() => { document.querySelector('#stream-video').style.visibility = 'hidden'; });
|
||||
await page.screenshot({ path: path.join(out, '20-watching-video-redacted.png') });
|
||||
await page.evaluate(() => { document.querySelector('#stream-video').style.visibility = ''; });
|
||||
}
|
||||
if (['failed', 'declined', 'ended', 'removed', 'unsupported'].includes(d.watch.state)) {
|
||||
step('session ended early', { ...d.watch, overlay: await page.textContent('#stream-overlay') });
|
||||
await page.screenshot({ path: path.join(out, '21-watch-ended.png') });
|
||||
break;
|
||||
}
|
||||
}
|
||||
d = await diag(page);
|
||||
step('final watch stats', { ...d.watch });
|
||||
if (!(d.watch.framesDecoded > 0)) throw new Error('no video frames decoded');
|
||||
|
||||
await page.click('#stream-stop');
|
||||
await page.waitForFunction(() => window.teamspeachDiagnostics.snapshot().watch.state === 'idle', null, { timeout: 10000 });
|
||||
step('stopped watching');
|
||||
} catch (err) {
|
||||
failed = err;
|
||||
step('FAILED', { error: String(err.stack || err) });
|
||||
if (page) {
|
||||
await page.evaluate(() => { const v = document.querySelector('#stream-video'); if (v) v.style.visibility = 'hidden'; }).catch(() => {});
|
||||
await page.screenshot({ path: path.join(out, 'fail.png') }).catch(() => {});
|
||||
}
|
||||
} finally {
|
||||
if (page) {
|
||||
await page.click('#btn-disconnect').catch(() => {});
|
||||
await page.waitForTimeout(800);
|
||||
}
|
||||
if (app) await app.close().catch(() => {});
|
||||
}
|
||||
|
||||
for (const name of ['renderer.log', 'core.log']) {
|
||||
const file = path.join(profile, 'logs', name);
|
||||
if (existsSync(file)) {
|
||||
const lines = readFileSync(file, 'utf8').split(/\r?\n/).filter((l) => /watch|stream|state|error|warn/i.test(l));
|
||||
writeFileSync(path.join(out, `${name}.filtered.txt`), lines.join('\n'));
|
||||
}
|
||||
}
|
||||
result.finishedAt = new Date().toISOString();
|
||||
result.ok = !failed;
|
||||
writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2));
|
||||
console.log(`[probe] ${result.ok ? 'OK' : 'FAILED'} → ${out}`);
|
||||
process.exit(result.ok ? 0 : 1);
|
||||
@@ -0,0 +1,31 @@
|
||||
// Rasterizes build/icon.svg to build/icon.png (512×512, transparent) and app/renderer/assets/icon.png
|
||||
// with Electron's own renderer, so no extra image tooling is needed.
|
||||
// npx electron scripts/render-icon.cjs
|
||||
const { app, BrowserWindow } = require('electron');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const root = path.resolve(__dirname, '..');
|
||||
const svg = fs.readFileSync(path.join(root, 'build', 'icon.svg'), 'utf8');
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
const win = new BrowserWindow({
|
||||
width: 512,
|
||||
height: 512,
|
||||
show: false,
|
||||
transparent: true,
|
||||
frame: false,
|
||||
webPreferences: { offscreen: true },
|
||||
});
|
||||
win.webContents.setFrameRate(1);
|
||||
const html = `<!doctype html><html><body style="margin:0;background:transparent">${svg.replace('<svg ', '<svg width="512" height="512" ')}</body></html>`;
|
||||
await win.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(html)}`);
|
||||
await new Promise((r) => setTimeout(r, 300));
|
||||
const image = await win.webContents.capturePage({ x: 0, y: 0, width: 512, height: 512 });
|
||||
const png = image.resize({ width: 512, height: 512 }).toPNG();
|
||||
fs.writeFileSync(path.join(root, 'build', 'icon.png'), png);
|
||||
fs.mkdirSync(path.join(root, 'app', 'renderer', 'assets'), { recursive: true });
|
||||
fs.writeFileSync(path.join(root, 'app', 'renderer', 'assets', 'icon.png'), image.resize({ width: 256, height: 256 }).toPNG());
|
||||
console.log('icon written');
|
||||
app.quit();
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
// Real Electron UI smoke run (no mocks): first launch → onboarding → restart persistence → rename,
|
||||
// optional live server connect. Uses a disposable profile directory so the user's profile is untouched.
|
||||
//
|
||||
// node scripts/smoke-ui.mjs --out docs/evidence/runtime/<name> [--server 10.10.10.160:9987] [--profile DIR]
|
||||
//
|
||||
// Writes screenshots and result.json (UIDs are public identifiers; no private key ever leaves the core).
|
||||
import { _electron as electron } from 'playwright-core';
|
||||
import { mkdirSync, writeFileSync, mkdtempSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { createRequire } from 'node:module';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const require = createRequire(import.meta.url);
|
||||
const electronPath = require('electron');
|
||||
|
||||
const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => {
|
||||
if (a.startsWith('--')) acc.push([a.slice(2), all[i + 1] && !all[i + 1].startsWith('--') ? all[i + 1] : 'true']);
|
||||
return acc;
|
||||
}, []));
|
||||
const out = path.resolve(root, args.out ?? 'smoke-out');
|
||||
const profile = args.profile ? path.resolve(args.profile) : mkdtempSync(path.join(tmpdir(), 'teamspeach-smoke-'));
|
||||
mkdirSync(out, { recursive: true });
|
||||
|
||||
const result = { startedAt: new Date().toISOString(), profile, steps: [], console: [] };
|
||||
const step = (name, data = {}) => {
|
||||
result.steps.push({ name, at: new Date().toISOString(), ...data });
|
||||
console.log(`[smoke] ${name}`, JSON.stringify(data));
|
||||
};
|
||||
|
||||
async function launch(label) {
|
||||
const app = await electron.launch({
|
||||
executablePath: electronPath,
|
||||
env: { ...process.env, TEAMSPEACH_PROFILE_DIR: profile },
|
||||
args: [root, ...(process.env.TEAMSPEACH_SMOKE_EXTRA_ARGS ?? '').split(' ').filter(Boolean), ...(args.fakemic ? ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream'] : [])],
|
||||
});
|
||||
const page = await app.firstWindow();
|
||||
page.on('console', (msg) => result.console.push(`${label} ${msg.type()}: ${msg.text()}`));
|
||||
page.on('pageerror', (err) => result.console.push(`${label} pageerror: ${err.message}`));
|
||||
await page.setViewportSize({ width: 1280, height: 800 }).catch(() => {});
|
||||
return { app, page };
|
||||
}
|
||||
|
||||
const diag = (page) => page.evaluate(() => window.teamspeachDiagnostics.snapshot());
|
||||
const visible = (page, sel) => page.waitForSelector(sel, { state: 'visible', timeout: 20000 });
|
||||
const shot = async (page, name) => {
|
||||
await page.waitForTimeout(300);
|
||||
await page.screenshot({ path: path.join(out, name) });
|
||||
step(`screenshot ${name}`);
|
||||
};
|
||||
|
||||
let failed = null;
|
||||
try {
|
||||
// 1. First launch: onboarding must ask for a nickname once.
|
||||
let { app, page } = await launch('run1');
|
||||
await visible(page, '#view-onboarding');
|
||||
await shot(page, '01-first-launch-onboarding.png');
|
||||
await page.fill('#onboarding-nick', 'ab');
|
||||
await page.click('#onboarding-submit');
|
||||
const validation = await page.textContent('#onboarding-error');
|
||||
step('short nickname rejected', { message: validation });
|
||||
await page.fill('#onboarding-nick', 'PeachSmoke');
|
||||
await page.click('#onboarding-submit');
|
||||
await visible(page, '#view-app');
|
||||
let d = await diag(page);
|
||||
const uid1 = d.profile.uid;
|
||||
step('profile created', { uid: uid1, nickname: d.profile.nickname });
|
||||
await shot(page, '02-after-onboarding.png');
|
||||
await app.close();
|
||||
|
||||
// 2. Restart: same identity, no onboarding.
|
||||
({ app, page } = await launch('run2'));
|
||||
await visible(page, '#view-app');
|
||||
d = await diag(page);
|
||||
step('restart keeps identity', { uid: d.profile.uid, nickname: d.profile.nickname, same: d.profile.uid === uid1 });
|
||||
if (d.profile.uid !== uid1) throw new Error('UID changed after restart');
|
||||
|
||||
// 3. Rename in settings: UID must not change.
|
||||
await page.click('#btn-settings');
|
||||
await visible(page, '#settings-view');
|
||||
await page.fill('#rename-input', 'PeachRenamed');
|
||||
await page.click('#rename-submit');
|
||||
await page.waitForFunction(() => window.teamspeachDiagnostics.snapshot().profile.nickname === 'PeachRenamed', null, { timeout: 15000 });
|
||||
d = await diag(page);
|
||||
step('renamed', { uid: d.profile.uid, nickname: d.profile.nickname, status: await page.textContent('#rename-status'), same: d.profile.uid === uid1 });
|
||||
if (d.profile.uid !== uid1) throw new Error('UID changed after rename');
|
||||
await shot(page, '03-settings-renamed.png');
|
||||
await app.close();
|
||||
|
||||
// 4. Restart again: rename persisted.
|
||||
({ app, page } = await launch('run3'));
|
||||
await visible(page, '#view-app');
|
||||
d = await diag(page);
|
||||
step('rename persisted', { uid: d.profile.uid, nickname: d.profile.nickname, ok: d.profile.uid === uid1 && d.profile.nickname === 'PeachRenamed' });
|
||||
if (d.profile.nickname !== 'PeachRenamed') throw new Error('rename not persisted');
|
||||
|
||||
// 5. Optional live server connection.
|
||||
if (args.server) {
|
||||
await page.fill('#connect-address', args.server);
|
||||
await page.click('#connect-submit');
|
||||
await page.waitForFunction(() => window.teamspeachDiagnostics.snapshot().conn === 'connected', null, { timeout: 60000 });
|
||||
await page.waitForTimeout(1500);
|
||||
d = await diag(page);
|
||||
step('connected', { server: d.server, ownClientId: d.ownClientId, channel: d.ownChannel, clients: d.clients.length, videoCodecs: d.videoCodecs });
|
||||
await shot(page, '04-connected.png');
|
||||
await page.click('#btn-disconnect');
|
||||
await page.waitForFunction(() => window.teamspeachDiagnostics.snapshot().conn === 'disconnected', null, { timeout: 15000 });
|
||||
step('disconnected');
|
||||
}
|
||||
await app.close();
|
||||
} catch (err) {
|
||||
failed = err;
|
||||
step('FAILED', { error: String(err.stack || err) });
|
||||
}
|
||||
|
||||
result.finishedAt = new Date().toISOString();
|
||||
result.ok = !failed;
|
||||
writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2));
|
||||
console.log(`[smoke] ${result.ok ? 'OK' : 'FAILED'} → ${out}`);
|
||||
process.exit(result.ok ? 0 : 1);
|
||||
@@ -0,0 +1,210 @@
|
||||
// Two real TeamsPeach instances (separate disposable profiles) on a live server:
|
||||
// A transmits Chromium's synthetic microphone (open mic, then push-to-talk), B must receive
|
||||
// talking events and decoded audio frames from the core; plus channel and private chat both ways.
|
||||
//
|
||||
// node scripts/smoke-voice.mjs --server 10.10.10.160:9987 --out docs/evidence/runtime/<name>
|
||||
//
|
||||
// The synthetic microphone (--use-fake-device-for-media-stream) replaces only the capture device;
|
||||
// everything after getUserMedia (worklet, IPC, core Opus, server, decode, mix, playback) is the real path.
|
||||
import { _electron as electron } from 'playwright-core';
|
||||
import { mkdirSync, writeFileSync, mkdtempSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { createRequire } from 'node:module';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const require = createRequire(import.meta.url);
|
||||
const electronPath = require('electron');
|
||||
|
||||
const argv = process.argv.slice(2);
|
||||
const opt = (name, fallback) => {
|
||||
const i = argv.indexOf(`--${name}`);
|
||||
return i >= 0 ? argv[i + 1] : fallback;
|
||||
};
|
||||
const server = opt('server');
|
||||
if (!server) {
|
||||
console.error('--server is required');
|
||||
process.exit(2);
|
||||
}
|
||||
const out = path.resolve(root, opt('out', 'smoke-voice-out'));
|
||||
mkdirSync(out, { recursive: true });
|
||||
const result = { startedAt: new Date().toISOString(), server, steps: [], console: [] };
|
||||
const step = (name, data = {}) => {
|
||||
result.steps.push({ name, at: new Date().toISOString(), ...data });
|
||||
console.log(`[voice] ${name}`, JSON.stringify(data));
|
||||
};
|
||||
|
||||
async function launch(label, nickname) {
|
||||
const profile = mkdtempSync(path.join(tmpdir(), `teamspeach-${label}-`));
|
||||
const app = await electron.launch({
|
||||
executablePath: electronPath,
|
||||
args: [root, '--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream'],
|
||||
env: { ...process.env, TEAMSPEACH_PROFILE_DIR: profile },
|
||||
});
|
||||
const page = await app.firstWindow();
|
||||
page.on('console', (m) => result.console.push(`${label} ${m.type()}: ${m.text()}`));
|
||||
page.on('pageerror', (e) => result.console.push(`${label} pageerror: ${e.message}`));
|
||||
await page.waitForSelector('#view-onboarding', { state: 'visible', timeout: 20000 });
|
||||
await page.fill('#onboarding-nick', nickname);
|
||||
await page.click('#onboarding-submit');
|
||||
await page.waitForSelector('#view-app', { state: 'visible', timeout: 20000 });
|
||||
return { app, page, profile };
|
||||
}
|
||||
|
||||
const diag = (page) => page.evaluate(() => window.teamspeachDiagnostics.snapshot());
|
||||
const waitDiag = (page, fn, arg, timeout = 20000) => page.waitForFunction(fn, arg, { timeout });
|
||||
|
||||
async function setRange(page, selector, value) {
|
||||
await page.$eval(selector, (el, v) => {
|
||||
el.value = String(v);
|
||||
el.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
el.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
}, value);
|
||||
}
|
||||
|
||||
async function connect(page) {
|
||||
await page.fill('#connect-address', server);
|
||||
await page.click('#connect-submit');
|
||||
await waitDiag(page, () => window.teamspeachDiagnostics.snapshot().conn === 'connected', null, 60000);
|
||||
}
|
||||
|
||||
let a;
|
||||
let b;
|
||||
let failed = null;
|
||||
try {
|
||||
a = await launch('A', 'PeachVoiceA');
|
||||
b = await launch('B', 'PeachVoiceB');
|
||||
step('profiles created', { a: (await diag(a.page)).profile, b: (await diag(b.page)).profile });
|
||||
|
||||
// B listens at zero playback gain so the test does not play tones on the speakers; frames still flow.
|
||||
await b.page.click('#btn-settings');
|
||||
await setRange(b.page, '#voice-volume', 0);
|
||||
await b.page.click('#settings-back');
|
||||
|
||||
// Both connect in push-to-talk mode (nothing is sent until a key is held).
|
||||
await connect(b.page);
|
||||
await connect(a.page);
|
||||
await a.page.waitForTimeout(1500);
|
||||
const da = await diag(a.page);
|
||||
const db = await diag(b.page);
|
||||
step('both connected', { aClid: da.ownClientId, aChannel: da.ownChannel, bClid: db.ownClientId, bChannel: db.ownChannel });
|
||||
if (da.ownChannel !== db.ownChannel) throw new Error('clients landed in different channels');
|
||||
const ownCid = (s) => s.clients.find((c) => c.id === s.ownClientId)?.channel;
|
||||
const others = db.clients.filter((c) => c.type !== 'query' && c.channel === ownCid(db) && c.id !== da.ownClientId && c.id !== db.ownClientId);
|
||||
if (others.length > 0) throw new Error(`refusing to transmit test tones: channel occupied by ${others.map((c) => c.nickname).join(', ')}`);
|
||||
|
||||
// A: open microphone.
|
||||
await a.page.click('#btn-settings');
|
||||
await a.page.check('input[name="transmit"][value="open"]');
|
||||
await a.page.click('#settings-back');
|
||||
|
||||
// Open mic: B must see A talking and receive audio frames.
|
||||
await waitDiag(b.page, (clid) => window.teamspeachDiagnostics.snapshot().talking.includes(clid), da.ownClientId, 20000);
|
||||
await b.page.waitForTimeout(3000);
|
||||
let sa = await diag(a.page);
|
||||
let sb = await diag(b.page);
|
||||
const playback = await b.page.evaluate(() => window.teamspeachDiagnostics.playback());
|
||||
step('open mic received', { aFramesSent: sa.voice.framesSent, aTransmitting: sa.audio.transmitting, bTalking: sb.talking, bFramesPlayed: sb.voice.framesPlayed, bPlayback: playback });
|
||||
if (sb.voice.framesPlayed < 50) throw new Error('B received too few audio frames');
|
||||
await b.page.screenshot({ path: path.join(out, '10-b-sees-a-talking.png') });
|
||||
await a.page.screenshot({ path: path.join(out, '11-a-open-mic.png') });
|
||||
|
||||
// Mute A: talking must stop on B and the mute flag must be visible.
|
||||
await a.page.click('#btn-mute');
|
||||
await waitDiag(b.page, (clid) => !window.teamspeachDiagnostics.snapshot().talking.includes(clid), da.ownClientId, 10000);
|
||||
await b.page.waitForTimeout(800);
|
||||
step('A muted, talking stopped on B');
|
||||
await b.page.screenshot({ path: path.join(out, '12-b-sees-a-muted.png') });
|
||||
await a.page.click('#btn-mute');
|
||||
|
||||
// Push-to-talk: switch A to PTT (default key F8), hold the key, release.
|
||||
await a.page.click('#btn-settings');
|
||||
await a.page.check('input[name="transmit"][value="ptt"]');
|
||||
await a.page.click('#settings-back');
|
||||
await a.page.waitForTimeout(1500);
|
||||
sb = await diag(b.page);
|
||||
step('PTT idle', { bTalkingIncludesA: sb.talking.includes(da.ownClientId) });
|
||||
const before = (await diag(b.page)).voice.framesPlayed;
|
||||
await a.page.keyboard.down('F8');
|
||||
await waitDiag(b.page, (clid) => window.teamspeachDiagnostics.snapshot().talking.includes(clid), da.ownClientId, 10000);
|
||||
await a.page.waitForTimeout(1500);
|
||||
await a.page.screenshot({ path: path.join(out, '13-a-ptt-held.png') });
|
||||
await a.page.keyboard.up('F8');
|
||||
await waitDiag(b.page, (clid) => !window.teamspeachDiagnostics.snapshot().talking.includes(clid), da.ownClientId, 10000);
|
||||
step('PTT burst received', { bFramesDuringBurst: (await diag(b.page)).voice.framesPlayed - before });
|
||||
|
||||
// Reverse direction: B talks to A.
|
||||
await b.page.click('#btn-settings');
|
||||
await b.page.check('input[name="transmit"][value="open"]');
|
||||
await b.page.click('#settings-back');
|
||||
await waitDiag(a.page, (clid) => window.teamspeachDiagnostics.snapshot().talking.includes(clid), db.ownClientId, 20000);
|
||||
await a.page.waitForTimeout(2000);
|
||||
sa = await diag(a.page);
|
||||
step('reverse direction received', { aFramesPlayed: sa.voice.framesPlayed, aTalking: sa.talking });
|
||||
|
||||
// Deafen B while both have open mics: B must stop receiving (RX) and stop sending (TX); undeafen resumes both.
|
||||
await a.page.click('#btn-settings');
|
||||
await a.page.check('input[name="transmit"][value="open"]');
|
||||
await a.page.click('#settings-back');
|
||||
await waitDiag(b.page, (clid) => window.teamspeachDiagnostics.snapshot().talking.includes(clid), da.ownClientId, 10000);
|
||||
await b.page.click('#btn-deafen');
|
||||
await waitDiag(b.page, () => window.teamspeachDiagnostics.snapshot().audio.output_muted === true, null, 10000);
|
||||
await waitDiag(a.page, (clid) => !window.teamspeachDiagnostics.snapshot().talking.includes(clid), db.ownClientId, 10000);
|
||||
await b.page.waitForTimeout(1000);
|
||||
const rx0 = (await diag(b.page)).voice.framesPlayed;
|
||||
const txA0 = (await diag(a.page)).voice.framesPlayed;
|
||||
await b.page.waitForTimeout(2500);
|
||||
const deaf = { bRxDelta: (await diag(b.page)).voice.framesPlayed - rx0, aRxFromBDelta: (await diag(a.page)).voice.framesPlayed - txA0, aSeesBTalking: (await diag(a.page)).talking.includes(db.ownClientId) };
|
||||
await b.page.screenshot({ path: path.join(out, '17-b-deafened.png') });
|
||||
step('B deafened', deaf);
|
||||
if (deaf.bRxDelta !== 0 || deaf.aRxFromBDelta !== 0 || deaf.aSeesBTalking) throw new Error('deafen did not stop RX/TX');
|
||||
await b.page.click('#btn-deafen');
|
||||
await waitDiag(a.page, (clid) => window.teamspeachDiagnostics.snapshot().talking.includes(clid), db.ownClientId, 10000);
|
||||
const rx1 = (await diag(b.page)).voice.framesPlayed;
|
||||
await b.page.waitForTimeout(2000);
|
||||
step('B undeafened', { bRxDelta: (await diag(b.page)).voice.framesPlayed - rx1, aSeesBTalking: (await diag(a.page)).talking.includes(db.ownClientId) });
|
||||
for (const p of [a.page, b.page]) {
|
||||
await p.click('#btn-settings');
|
||||
await p.check('input[name="transmit"][value="ptt"]');
|
||||
await p.click('#settings-back');
|
||||
}
|
||||
|
||||
// Chat: channel message A → B (the server may deny guests channel text: that error must be shown),
|
||||
// private message B → A.
|
||||
await a.page.fill('#chat-input', 'TeamsPeach smoke: channel message');
|
||||
await a.page.press('#chat-input', 'Enter');
|
||||
const channelOutcome = await Promise.race([
|
||||
b.page.waitForSelector('text=TeamsPeach smoke: channel message', { timeout: 10000 }).then(() => ({ delivered: true })),
|
||||
a.page.waitForSelector('.toast[data-kind="error"]', { timeout: 10000 }).then(async (el) => ({ delivered: false, error: await el.textContent() })),
|
||||
]);
|
||||
step('channel chat', channelOutcome);
|
||||
await a.page.screenshot({ path: path.join(out, '14-a-channel-chat-result.png') });
|
||||
await b.page.click(`#tree [data-key="u:${da.ownClientId}"] .row-btn`);
|
||||
await b.page.fill('#chat-input', 'TeamsPeach smoke: private message');
|
||||
await b.page.press('#chat-input', 'Enter');
|
||||
await a.page.waitForSelector('#chat-tabs .chat-tab:has-text("PeachVoiceB")', { timeout: 10000 });
|
||||
await a.page.click('#chat-tabs .chat-tab:has-text("PeachVoiceB")');
|
||||
await a.page.waitForSelector('text=TeamsPeach smoke: private message', { timeout: 10000 });
|
||||
step('private chat delivered');
|
||||
await a.page.screenshot({ path: path.join(out, '15-a-private-chat.png') });
|
||||
await b.page.screenshot({ path: path.join(out, '16-b-private-chat.png') });
|
||||
} catch (err) {
|
||||
failed = err;
|
||||
step('FAILED', { error: String(err.stack || err) });
|
||||
if (a) await a.page.screenshot({ path: path.join(out, 'fail-a.png') }).catch(() => {});
|
||||
if (b) await b.page.screenshot({ path: path.join(out, 'fail-b.png') }).catch(() => {});
|
||||
} finally {
|
||||
for (const inst of [a, b]) {
|
||||
if (!inst) continue;
|
||||
await inst.page.click('#btn-disconnect').catch(() => {});
|
||||
await inst.page.waitForTimeout(500);
|
||||
await inst.app.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
result.finishedAt = new Date().toISOString();
|
||||
result.ok = !failed;
|
||||
writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2));
|
||||
console.log(`[voice] ${result.ok ? 'OK' : 'FAILED'} → ${out}`);
|
||||
process.exit(result.ok ? 0 : 1);
|
||||
@@ -0,0 +1,37 @@
|
||||
'use strict';
|
||||
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { validateRequest, RENDERER_COMMANDS } = require('../app/main/ipc-validate');
|
||||
|
||||
test('renderer allowlist excludes main-owned commands', () => {
|
||||
for (const cmd of ['shutdown', 'audio_frame', 'audio_end', 'eval', '__proto__', 'constructor']) {
|
||||
assert.throws(() => validateRequest(cmd, {}), (err) => err.code === 'unknown_command', cmd);
|
||||
}
|
||||
assert.ok(RENDERER_COMMANDS.includes('stream_signal'));
|
||||
});
|
||||
|
||||
test('unknown argument keys and wrong types are rejected', () => {
|
||||
assert.throws(() => validateRequest('connect', { address: 'h', path: '/etc/passwd' }));
|
||||
assert.throws(() => validateRequest('connect', { address: 5 }));
|
||||
assert.throws(() => validateRequest('connect', { address: 'a\nb' }));
|
||||
assert.throws(() => validateRequest('join_channel', { channel_id: -1 }));
|
||||
assert.throws(() => validateRequest('set_audio', { input_muted: 'yes' }));
|
||||
assert.deepEqual(validateRequest('connect', { address: '10.10.10.160:9987' }), { address: '10.10.10.160:9987' });
|
||||
});
|
||||
|
||||
test('send_text requires client_id exactly for private messages', () => {
|
||||
assert.throws(() => validateRequest('send_text', { target: 'client', message: 'hi' }));
|
||||
assert.throws(() => validateRequest('send_text', { target: 'channel', client_id: 3, message: 'hi' }));
|
||||
assert.deepEqual(validateRequest('send_text', { target: 'client', client_id: 3, message: 'hi\nthere' }), { target: 'client', client_id: 3, message: 'hi\nthere' });
|
||||
assert.throws(() => validateRequest('send_text', { target: 'server', message: 'x'.repeat(8193) }));
|
||||
});
|
||||
|
||||
test('stream_signal only carries answers and ICE candidates', () => {
|
||||
const base = { stream_id: 'c4', client_id: 16 };
|
||||
assert.ok(validateRequest('stream_signal', { ...base, json: { cmd: 'answer', args: { answer: 'v=0\r\n' } } }));
|
||||
assert.ok(validateRequest('stream_signal', { ...base, json: { cmd: 'iceCandidate', args: { mLine: 0, mid: '0', sdp: 'candidate:1' } } }));
|
||||
assert.throws(() => validateRequest('stream_signal', { ...base, json: { cmd: 'offer', args: { offer: 'x' } } }));
|
||||
assert.throws(() => validateRequest('stream_signal', { ...base, json: { cmd: 'answer', args: { answer: 'x', extra: 1 } } }));
|
||||
assert.throws(() => validateRequest('stream_signal', { ...base, json: { cmd: 'answer', args: { answer: 'x'.repeat(61 * 1024) } } }));
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { StreamDirectory } from '../app/renderer/js/stream/directory.js';
|
||||
|
||||
test('notifystreaminfo with id registers a stream; return_code-only replies are ignored', () => {
|
||||
const d = new StreamDirectory();
|
||||
assert.equal(d.handle('notifystreaminfo', [{ return_code: '1' }]), false);
|
||||
assert.equal(d.handle('notifystreaminfo', [{ id: 'c4', clid: '16', name: 'Экран 1', audio: '0', mode: '1', return_code: '2' }]), true);
|
||||
assert.equal(d.byClient(16).name, 'Экран 1');
|
||||
assert.equal(d.get('c4').fields.audio, '0');
|
||||
});
|
||||
|
||||
test('updates merge fields, stop removes, prune drops absent clients', () => {
|
||||
const d = new StreamDirectory();
|
||||
d.handle('notifystreamstarted', [{ id: 'a', clid: '5', name: 'one' }, { id: 'b', clid: '6', name: 'two' }]);
|
||||
d.handle('notifystreamupdated', [{ id: 'a', name: 'renamed' }]);
|
||||
assert.equal(d.get('a').name, 'renamed');
|
||||
assert.equal(d.get('a').clientId, 5);
|
||||
assert.equal(d.handle('notifystreamupdated', [{ id: 'zzz', name: 'x' }]), false, 'updates never create');
|
||||
d.handle('notifystreamstopped', [{ id: 'a' }]);
|
||||
assert.equal(d.get('a'), null);
|
||||
assert.equal(d.prune(new Set([1, 2])), true);
|
||||
assert.equal(d.streams.size, 0);
|
||||
});
|
||||
|
||||
test('stop by clid only (requeststreaminfo error) removes that client stream', () => {
|
||||
const d = new StreamDirectory();
|
||||
d.handle('notifystreaminfo', [{ id: 'a', clid: '5' }]);
|
||||
assert.equal(d.handle('notifystreamstopped', [{ clid: '5' }]), true);
|
||||
assert.equal(d.byClient(5), null);
|
||||
});
|
||||
|
||||
test('SFU notification is remembered', () => {
|
||||
const d = new StreamDirectory();
|
||||
assert.equal(d.handle('notifysfuaccessinfo', [{}]), true);
|
||||
assert.equal(d.sfuSeen, true);
|
||||
});
|
||||
@@ -0,0 +1,223 @@
|
||||
// Behaviour of the TS6 viewer session against a scripted peer connection: ordering of answers and
|
||||
// candidates, realign offers, stale ICE generations, filters and cancellation during negotiation.
|
||||
// This exercises session logic only; TS6 interoperability is proven by scripts/probe-stream.mjs.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { StreamViewerSession, candidateUfrag, remoteUfrags } from '../app/renderer/js/stream/session.js';
|
||||
|
||||
const OFFER = (ufrag) => `v=0\r\na=group:BUNDLE 0 1\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=mid:0\r\na=ice-ufrag:${ufrag}\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:1\r\na=ice-ufrag:${ufrag}\r\n`;
|
||||
const CAND = (ufrag, n = 1) => `candidate:${n} 1 udp 2122260223 10.10.10.5 5${n}000 typ host generation 0 ufrag ${ufrag} network-id 1`;
|
||||
|
||||
class FakePC {
|
||||
constructor() {
|
||||
this.signalingState = 'stable';
|
||||
this.remoteDescription = null;
|
||||
this.localDescription = null;
|
||||
this.added = [];
|
||||
this.closed = false;
|
||||
this.gates = {};
|
||||
this.rejectNextCandidate = null;
|
||||
}
|
||||
async setRemoteDescription(d) {
|
||||
if (d.type === 'rollback') {
|
||||
this.signalingState = 'stable';
|
||||
return;
|
||||
}
|
||||
if (this.gates.setRemote) await this.gates.setRemote;
|
||||
this.remoteDescription = d;
|
||||
this.signalingState = 'have-remote-offer';
|
||||
}
|
||||
async createAnswer() {
|
||||
return { type: 'answer', sdp: `answer-for-${this.remoteDescription.sdp.length}` };
|
||||
}
|
||||
async setLocalDescription(d) {
|
||||
if (this.gates.setLocal) await this.gates.setLocal;
|
||||
this.localDescription = d;
|
||||
this.signalingState = 'stable';
|
||||
}
|
||||
async addIceCandidate(c) {
|
||||
if (this.rejectNextCandidate) {
|
||||
const err = this.rejectNextCandidate;
|
||||
this.rejectNextCandidate = null;
|
||||
throw err;
|
||||
}
|
||||
this.added.push(c);
|
||||
}
|
||||
emitLocalCandidate(candidate, mLine = 0, mid = '0') {
|
||||
this.onicecandidate?.({ candidate: { candidate, sdpMLineIndex: mLine, sdpMid: mid } });
|
||||
}
|
||||
close() {
|
||||
this.closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
function harness(extra = {}) {
|
||||
const wire = [];
|
||||
const states = [];
|
||||
const timers = [];
|
||||
let pc = null;
|
||||
const session = new StreamViewerSession({
|
||||
streamId: 'S1',
|
||||
clientId: 16,
|
||||
ownClientId: 28,
|
||||
message: 'Probe',
|
||||
signal: {
|
||||
join: async (id, clid, msg) => wire.push({ op: 'join', id, clid, msg }),
|
||||
send: async (id, clid, json) => wire.push({ op: 'send', id, clid, json }),
|
||||
leave: async (id, clid) => wire.push({ op: 'leave', id, clid }),
|
||||
},
|
||||
createPeerConnection: () => {
|
||||
pc = new FakePC();
|
||||
return pc;
|
||||
},
|
||||
onState: (s, d) => states.push(d ? `${s}:${d}` : s),
|
||||
setTimer: (fn, ms) => {
|
||||
timers.push({ fn, ms });
|
||||
return timers.length;
|
||||
},
|
||||
clearTimer: () => {},
|
||||
...extra,
|
||||
});
|
||||
return { session, wire, states, timers, pc: () => pc };
|
||||
}
|
||||
|
||||
const settle = () => new Promise((r) => setTimeout(r, 0));
|
||||
const signal = (json, id = 'S1', clid = '16') => ({ id, clid, json: JSON.stringify(json) });
|
||||
|
||||
test('candidates that arrive before the offer is applied are buffered, then added', async () => {
|
||||
const h = harness();
|
||||
await h.session.start();
|
||||
h.session.handle('notifystreamsignaling', signal({ cmd: 'iceCandidate', args: { mLine: 0, mid: '0', sdp: CAND('u1', 1) } }));
|
||||
h.session.handle('notifyrespondjoinstreamrequest', { id: 'S1', clid: '16', decision: '1', offer: OFFER('u1'), msg: '' });
|
||||
h.session.handle('notifystreamsignaling', signal({ cmd: 'iceCandidate', args: { mLine: 1, mid: '1', sdp: CAND('u1', 2) } }));
|
||||
await settle();
|
||||
await h.session.queue;
|
||||
assert.equal(h.pc().added.length, 2);
|
||||
assert.deepEqual(h.pc().added.map((c) => c.sdpMid), ['0', '1']);
|
||||
const answers = h.wire.filter((w) => w.op === 'send' && w.json.cmd === 'answer');
|
||||
assert.equal(answers.length, 1);
|
||||
assert.equal(typeof answers[0].json.args.answer, 'string');
|
||||
assert.equal(h.session.state, 'connecting');
|
||||
});
|
||||
|
||||
test('local candidates gathered before the answer is sent follow it, in order', async () => {
|
||||
const h = harness();
|
||||
await h.session.start();
|
||||
let release;
|
||||
h.session.handle('notifyrespondjoinstreamrequest', { id: 'S1', clid: '16', decision: '1', offer: OFFER('u1') });
|
||||
await settle();
|
||||
h.pc().gates.setLocal = new Promise((r) => {
|
||||
release = r;
|
||||
});
|
||||
h.pc().emitLocalCandidate('candidate:9 1 udp 1 192.168.1.2 4000 typ host');
|
||||
release();
|
||||
await h.session.queue;
|
||||
const sends = h.wire.filter((w) => w.op === 'send').map((w) => w.json.cmd);
|
||||
assert.deepEqual(sends, ['answer', 'iceCandidate']);
|
||||
const cand = h.wire.find((w) => w.op === 'send' && w.json.cmd === 'iceCandidate').json.args;
|
||||
assert.deepEqual(Object.keys(cand).sort(), ['mLine', 'mid', 'sdp']);
|
||||
});
|
||||
|
||||
test('a realign offer after the first answer is answered again', async () => {
|
||||
const h = harness();
|
||||
await h.session.start();
|
||||
h.session.handle('notifyrespondjoinstreamrequest', { id: 'S1', clid: '16', decision: '1', offer: OFFER('u1') });
|
||||
h.session.handle('notifystreamsignaling', signal({ cmd: 'offer', args: { offer: `${OFFER('u1')}a=x-realign\r\n` } }));
|
||||
await settle();
|
||||
await h.session.queue;
|
||||
assert.equal(h.session.offersApplied, 2);
|
||||
assert.equal(h.wire.filter((w) => w.op === 'send' && w.json.cmd === 'answer').length, 2);
|
||||
});
|
||||
|
||||
test('candidates of a replaced ICE generation are skipped; current-generation failures are counted', async () => {
|
||||
const h = harness();
|
||||
await h.session.start();
|
||||
h.session.handle('notifyrespondjoinstreamrequest', { id: 'S1', clid: '16', decision: '1', offer: OFFER('old') });
|
||||
h.session.handle('notifystreamsignaling', signal({ cmd: 'reconnectOffer', args: { offer: OFFER('new') } }));
|
||||
h.session.handle('notifystreamsignaling', signal({ cmd: 'iceCandidate', args: { mLine: 0, mid: '0', sdp: CAND('old', 1) } }));
|
||||
await settle();
|
||||
await h.session.queue;
|
||||
assert.equal(h.session.staleCandidates, 1);
|
||||
assert.equal(h.pc().added.length, 0);
|
||||
h.pc().rejectNextCandidate = new Error('malformed');
|
||||
h.session.handle('notifystreamsignaling', signal({ cmd: 'iceCandidate', args: { mLine: 0, mid: '0', sdp: CAND('new', 2) } }));
|
||||
await settle();
|
||||
await h.session.queue;
|
||||
assert.equal(h.session.candidateErrors, 1);
|
||||
assert.equal(h.session.state, 'connecting');
|
||||
});
|
||||
|
||||
test('stop during negotiation: leave is sent once and nothing follows it', async () => {
|
||||
const h = harness();
|
||||
await h.session.start();
|
||||
let release;
|
||||
h.session.handle('notifyrespondjoinstreamrequest', { id: 'S1', clid: '16', decision: '1', offer: OFFER('u1') });
|
||||
await settle();
|
||||
h.pc().gates.setLocal = new Promise((r) => {
|
||||
release = r;
|
||||
});
|
||||
h.session.handle('notifystreamsignaling', signal({ cmd: 'offer', args: { offer: OFFER('u1') } }));
|
||||
await settle();
|
||||
h.session.stop();
|
||||
h.pc().emitLocalCandidate('candidate:9 1 udp 1 192.168.1.2 4000 typ host');
|
||||
release();
|
||||
await h.session.queue;
|
||||
await settle();
|
||||
const leaveAt = h.wire.findIndex((w) => w.op === 'leave');
|
||||
assert.ok(leaveAt >= 0, 'leave sent');
|
||||
assert.equal(h.wire.filter((w) => w.op === 'leave').length, 1);
|
||||
assert.deepEqual(h.wire.slice(leaveAt + 1), [], 'no signaling after leave');
|
||||
assert.equal(h.session.state, 'stopped');
|
||||
assert.equal(h.pc().closed, true);
|
||||
});
|
||||
|
||||
test('notifications for other streams or other clients are ignored', async () => {
|
||||
const h = harness();
|
||||
await h.session.start();
|
||||
assert.equal(h.session.handle('notifyrespondjoinstreamrequest', { id: 'OTHER', clid: '16', decision: '1', offer: OFFER('x') }), false);
|
||||
assert.equal(h.session.handle('notifystreamsignaling', signal({ cmd: 'offer', args: { offer: OFFER('x') } }, 'S1', '99')), false);
|
||||
assert.equal(h.session.handle('notifystreamstopped', { id: 'OTHER' }), false);
|
||||
await settle();
|
||||
assert.equal(h.pc(), null);
|
||||
assert.equal(h.session.state, 'requesting');
|
||||
});
|
||||
|
||||
test('declined join ends without a leave; stopped stream ends without a leave', async () => {
|
||||
const a = harness();
|
||||
await a.session.start();
|
||||
a.session.handle('notifyrespondjoinstreamrequest', { id: 'S1', clid: '16', decision: '0', msg: 'nope' });
|
||||
assert.equal(a.session.state, 'declined');
|
||||
assert.equal(a.wire.some((w) => w.op === 'leave'), false);
|
||||
|
||||
const b = harness();
|
||||
await b.session.start();
|
||||
b.session.handle('notifyrespondjoinstreamrequest', { id: 'S1', clid: '16', decision: '1', offer: OFFER('u1') });
|
||||
await settle();
|
||||
b.session.handle('notifystreamstopped', { id: 'S1', clid: '16' });
|
||||
assert.equal(b.session.state, 'ended');
|
||||
assert.equal(b.wire.some((w) => w.op === 'leave'), false);
|
||||
});
|
||||
|
||||
test('SFU access info while requesting is reported as unsupported and leaves', async () => {
|
||||
const h = harness();
|
||||
await h.session.start();
|
||||
h.session.handle('notifysfuaccessinfo', { sfu_endpoint: 'x' });
|
||||
assert.equal(h.session.state, 'unsupported');
|
||||
assert.equal(h.wire.filter((w) => w.op === 'leave').length, 1);
|
||||
});
|
||||
|
||||
test('no answer to the join request times out and leaves', async () => {
|
||||
const h = harness();
|
||||
await h.session.start();
|
||||
assert.equal(h.timers.length, 1);
|
||||
h.timers[0].fn();
|
||||
assert.equal(h.session.state, 'failed');
|
||||
assert.equal(h.session.detail, 'no_response');
|
||||
assert.equal(h.wire.filter((w) => w.op === 'leave').length, 1);
|
||||
});
|
||||
|
||||
test('ufrag helpers', () => {
|
||||
assert.equal(candidateUfrag(CAND('abc')), 'abc');
|
||||
assert.equal(candidateUfrag('candidate:1 1 udp 1 1.2.3.4 5 typ host'), null);
|
||||
assert.deepEqual([...remoteUfrags(OFFER('zz'))], ['zz']);
|
||||
});
|
||||