Updater from public releases, English UI by default with Russian selectable, cancelable capture, English technical messages, language-independent smoke hooks
This commit is contained in:
1 parent
ba4c7ec2af
commit
1142c9f60d
53 files changed
+3999
-543
No files matched your search
@@ -62,6 +62,9 @@ jobs:
|
||||
TEAMSPEACH_SMOKE_EXTRA_ARGS: --no-sandbox
|
||||
run: xvfb-run -a node scripts/smoke-ui.mjs --out smoke-out
|
||||
|
||||
- name: Updater engine behaviour (Xvfb, emulated release host)
|
||||
run: xvfb-run -a node --test test/update-engine.test.mjs
|
||||
|
||||
- name: Upload smoke evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v3
|
||||
|
||||
@@ -63,9 +63,15 @@ jobs:
|
||||
TEAMSPEACH_SMOKE_EXTRA_ARGS: --no-sandbox
|
||||
run: xvfb-run -a node scripts/smoke-ui.mjs --out smoke-out
|
||||
|
||||
- name: Updater engine behaviour (Xvfb, real electron-updater, emulated release server)
|
||||
run: xvfb-run -a node --test test/update-engine.test.mjs
|
||||
|
||||
- name: Package
|
||||
run: node scripts/dist.mjs --os linux --arch x64
|
||||
|
||||
- name: Update feed matches the packages (name, size, sha512, version)
|
||||
run: node scripts/update-feed-check.mjs --version "$(node -p "require('./package.json').version")" dist/*-linux.yml
|
||||
|
||||
- name: Package report (ELF layout of every packaged binary incl. the AppImage runtime)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -75,7 +81,7 @@ jobs:
|
||||
git rev-parse HEAD >> "$report"
|
||||
node scripts/elf-pagesize.mjs dist/linux-unpacked dist/TeamsPeach-*.AppImage --page 4096 --json dist/elf-report-linux-x64.json > elf.txt
|
||||
cat elf.txt >> "$report"
|
||||
sha256sum dist/*.AppImage dist/*.tar.gz >> "$report"
|
||||
sha256sum dist/*.AppImage dist/*.tar.gz dist/*-linux.yml >> "$report"
|
||||
cat "$report"
|
||||
|
||||
- uses: actions/upload-artifact@v3
|
||||
@@ -86,6 +92,7 @@ jobs:
|
||||
dist/*.tar.gz
|
||||
dist/build-info-linux-x64.txt
|
||||
dist/elf-report-linux-x64.json
|
||||
dist/*-linux.yml
|
||||
if-no-files-found: error
|
||||
|
||||
linux-arm64:
|
||||
@@ -131,6 +138,7 @@ jobs:
|
||||
set -euo pipefail
|
||||
npm ci
|
||||
node scripts/dist.mjs --os linux --arch arm64
|
||||
node scripts/update-feed-check.mjs --version "$(node -p "require('./package.json').version")" dist/*-linux-arm64.yml
|
||||
|
||||
- name: 16 KiB page check of every packaged ELF incl. the AppImage runtime (Asahi)
|
||||
run: |
|
||||
@@ -140,7 +148,7 @@ jobs:
|
||||
git rev-parse HEAD >> "$report"
|
||||
node scripts/elf-pagesize.mjs dist/linux-arm64-unpacked dist/TeamsPeach-*-arm64.AppImage --page 16384 --json dist/elf-report-linux-arm64.json > elf.txt
|
||||
cat elf.txt >> "$report"
|
||||
sha256sum dist/*.AppImage dist/*.tar.gz >> "$report"
|
||||
sha256sum dist/*.AppImage dist/*.tar.gz dist/*-linux-arm64.yml >> "$report"
|
||||
cat "$report"
|
||||
|
||||
- uses: actions/upload-artifact@v3
|
||||
@@ -151,6 +159,7 @@ jobs:
|
||||
dist/*.tar.gz
|
||||
dist/build-info-linux-arm64.txt
|
||||
dist/elf-report-linux-arm64.json
|
||||
dist/*-linux-arm64.yml
|
||||
if-no-files-found: error
|
||||
|
||||
# The AppImage runtime must start on a stock system: run it in a slim container without development
|
||||
@@ -208,10 +217,13 @@ jobs:
|
||||
set -euo pipefail
|
||||
node scripts/check-version.mjs
|
||||
cat > notes.md <<'EOF'
|
||||
Linux x64 и Linux ARM64 (aarch64) собраны в CI: тесты, офлайн-проверка ядра, проверка выравнивания ELF
|
||||
(для ARM64 — страницы 16 КиБ, включая загрузчик AppImage), см. build-info-*.txt.
|
||||
ARM64 проверен статически и под qemu, не на Apple Silicon. Пакеты не подписаны.
|
||||
Сборка Windows x64 собирается на машине разработчика из того же коммита и прикладывается отдельно
|
||||
с пометкой local.
|
||||
Linux x64 and Linux ARM64 (aarch64) are built in CI: tests, offline core check, ELF alignment check
|
||||
(16 KiB pages for ARM64, including the AppImage runtime), see build-info-*.txt.
|
||||
ARM64 is checked statically and under qemu, not on Apple Silicon. Packages are not signed.
|
||||
Windows x64 is built on the developer machine from the same commit and attached separately
|
||||
(provenance in *-win-x64-local-build-info.txt).
|
||||
Automatic updates (from the first updater-capable version on): Windows x64 NSIS installation and
|
||||
Linux AppImage install from this release's latest*.yml / <channel>*.yml feeds after user confirmation;
|
||||
zip and tar.gz users are notified and replace files manually.
|
||||
EOF
|
||||
node scripts/publish-release.mjs artifacts notes.md
|
||||
@@ -0,0 +1,68 @@
|
||||
# Manual end-to-end proof of the AppImage self-update between two PUBLISHED releases (Linux x64).
|
||||
# Downloads the older release's AppImage anonymously, runs it in a disposable profile under Xvfb with
|
||||
# APPIMAGE_EXTRACT_AND_RUN, lets it update itself from git.eeee.moe and checks version + identity afterwards.
|
||||
# Uses no secrets; never runs on pull requests.
|
||||
name: update-e2e
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
from_tag:
|
||||
description: Older updater-capable release tag (e.g. v0.1.2-rc.1)
|
||||
required: true
|
||||
to_tag:
|
||||
description: Newer release tag the old one must update to (e.g. v0.1.2-rc.2)
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
|
||||
jobs:
|
||||
appimage-x64:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: node:22-bookworm
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: System packages (container only)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends ca-certificates curl 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: Test driver (playwright-core)
|
||||
run: npm ci
|
||||
|
||||
- name: Download the older published AppImage (anonymous)
|
||||
env:
|
||||
FROM_TAG: ${{ inputs.from_tag }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
[[ "$FROM_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || { echo "bad tag $FROM_TAG"; exit 2; }
|
||||
mkdir -p old
|
||||
curl -fsSL -o "old/TeamsPeach-${FROM_TAG#v}.AppImage" \
|
||||
"https://git.eeee.moe/TeamsPeach/client/releases/download/${FROM_TAG}/TeamsPeach-${FROM_TAG#v}.AppImage"
|
||||
sha256sum old/*.AppImage
|
||||
|
||||
- name: Self-update end to end
|
||||
env:
|
||||
FROM_TAG: ${{ inputs.from_tag }}
|
||||
TO_TAG: ${{ inputs.to_tag }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
[[ "$TO_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || { echo "bad tag $TO_TAG"; exit 2; }
|
||||
xvfb-run -a node scripts/update-e2e.mjs --from "old/TeamsPeach-${FROM_TAG#v}.AppImage" --to-tag "$TO_TAG" --out update-e2e-out
|
||||
cat update-e2e-out/result.json
|
||||
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: always()
|
||||
with:
|
||||
name: update-e2e
|
||||
path: update-e2e-out/
|
||||
+14
-14
@@ -57,7 +57,7 @@ class CoreProcess extends EventEmitter {
|
||||
});
|
||||
} catch (err) {
|
||||
log.end();
|
||||
this._setStatus('failed', { message: err.message });
|
||||
this._setStatus('failed', { reason: 'spawn', message: err.message });
|
||||
return;
|
||||
}
|
||||
this.child = child;
|
||||
@@ -72,7 +72,7 @@ class CoreProcess extends EventEmitter {
|
||||
const readyTimer = setTimeout(() => {
|
||||
if (this.status === 'starting') {
|
||||
log.write('[main] core did not report ready in time, terminating\n');
|
||||
this._setStatus('failed', { message: 'Ядро не ответило за 15 секунд' });
|
||||
this._setStatus('failed', { reason: 'ready_timeout', message: 'The core did not report ready within 15 seconds' });
|
||||
child.kill();
|
||||
}
|
||||
}, READY_TIMEOUT_MS);
|
||||
@@ -80,7 +80,7 @@ class CoreProcess extends EventEmitter {
|
||||
child.on('error', (err) => {
|
||||
clearTimeout(readyTimer);
|
||||
log.write(`[main] spawn error: ${err.message}\n`);
|
||||
this._setStatus('failed', { message: err.message });
|
||||
this._setStatus('failed', { reason: 'spawn', message: err.message });
|
||||
});
|
||||
|
||||
child.on('exit', (code, signal) => {
|
||||
@@ -91,7 +91,7 @@ class CoreProcess extends EventEmitter {
|
||||
this.child = null;
|
||||
for (const [, entry] of this.pending) {
|
||||
clearTimeout(entry.timer);
|
||||
entry.resolve({ ok: false, error: { code: 'core_exited', message: 'Ядро завершило работу' } });
|
||||
entry.resolve({ ok: false, error: { code: 'core_exited', message: 'The core exited' } });
|
||||
}
|
||||
this.pending.clear();
|
||||
const expected = this.stopping;
|
||||
@@ -123,7 +123,7 @@ class CoreProcess extends EventEmitter {
|
||||
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._setStatus('failed', { reason: 'protocol', protocol: msg.protocol, message: `Unsupported core protocol version: ${msg.protocol}` });
|
||||
this.child?.kill();
|
||||
return;
|
||||
}
|
||||
@@ -145,19 +145,19 @@ class CoreProcess extends EventEmitter {
|
||||
|
||||
request(cmd, args) {
|
||||
if (!this.child || this.status !== 'ready') {
|
||||
return Promise.resolve({ ok: false, error: { code: 'core_unavailable', message: 'Ядро не запущено' } });
|
||||
return Promise.resolve({ ok: false, error: { code: 'core_unavailable', message: 'The core is not running' } });
|
||||
}
|
||||
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 Promise.resolve({ ok: false, error: { code: 'bad_request', message: 'Request too large' } });
|
||||
}
|
||||
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)} с` } });
|
||||
resolve({ ok: false, error: { code: 'timeout', message: `The core did not answer "${cmd}" within ${Math.round(timeoutMs / 1000)} s` } });
|
||||
}, timeoutMs);
|
||||
this.pending.set(id, { resolve, timer });
|
||||
this.child.stdin.write(line);
|
||||
@@ -194,7 +194,7 @@ class CoreProcess extends EventEmitter {
|
||||
}
|
||||
|
||||
function normalizeError(error) {
|
||||
if (!error || typeof error !== 'object') return { code: 'internal', message: 'Пустой ответ об ошибке' };
|
||||
if (!error || typeof error !== 'object') return { code: 'internal', message: 'Empty error response' };
|
||||
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;
|
||||
@@ -203,11 +203,11 @@ function normalizeError(error) {
|
||||
|
||||
function exitMessage(code) {
|
||||
switch (code) {
|
||||
case 0: return 'Ядро завершило работу';
|
||||
case 2: return 'Ядро отклонило аргументы запуска';
|
||||
case 3: return 'Профиль уже используется другим экземпляром TeamsPeach или каталог данных недоступен';
|
||||
case 1: return 'Внутренняя ошибка ядра (подробности в журнале core.log)';
|
||||
default: return `Ядро завершилось с кодом ${code}`;
|
||||
case 0: return 'The core exited';
|
||||
case 2: return 'The core rejected its start arguments';
|
||||
case 3: return 'The profile is in use by another TeamsPeach instance or the data directory is unavailable';
|
||||
case 1: return 'Internal core error (details in core.log)';
|
||||
default: return `The core exited with code ${code}`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+18
-18
@@ -16,27 +16,27 @@ class ValidationError extends Error {
|
||||
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 (typeof value !== 'string') throw new ValidationError(`${key}: expected a string`);
|
||||
if (value.length < min || value.length > max) throw new ValidationError(`${key}: invalid length`);
|
||||
if (maxBytes !== undefined && Buffer.byteLength(value, 'utf8') > maxBytes) throw new ValidationError(`${key}: too long`);
|
||||
if (multiline ? CONTROL_CHARS.test(value) : /[\u0000-\u001f\u007f]/.test(value)) {
|
||||
throw new ValidationError(`${key}: недопустимые управляющие символы`);
|
||||
throw new ValidationError(`${key}: control characters are not allowed`);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
const posInt = (value, key) => {
|
||||
if (!Number.isSafeInteger(value) || value < 0) throw new ValidationError(`${key}: ожидалось целое число`);
|
||||
if (!Number.isSafeInteger(value) || value < 0) throw new ValidationError(`${key}: expected a non-negative integer`);
|
||||
return value;
|
||||
};
|
||||
|
||||
const bool = (value, key) => {
|
||||
if (typeof value !== 'boolean') throw new ValidationError(`${key}: ожидалось true/false`);
|
||||
if (typeof value !== 'boolean') throw new ValidationError(`${key}: expected true/false`);
|
||||
return value;
|
||||
};
|
||||
|
||||
const oneOf = (...allowed) => (value, key) => {
|
||||
if (!allowed.includes(value)) throw new ValidationError(`${key}: недопустимое значение`);
|
||||
if (!allowed.includes(value)) throw new ValidationError(`${key}: value not allowed`);
|
||||
return value;
|
||||
};
|
||||
|
||||
@@ -53,15 +53,15 @@ function isPlainObject(value) {
|
||||
function shape(spec) {
|
||||
return (args) => {
|
||||
if (args === undefined || args === null) args = {};
|
||||
if (!isPlainObject(args)) throw new ValidationError('args: ожидался объект');
|
||||
if (!isPlainObject(args)) throw new ValidationError('args: expected an object');
|
||||
for (const key of Object.keys(args)) {
|
||||
if (!Object.prototype.hasOwnProperty.call(spec, key)) throw new ValidationError(`${key}: неизвестный аргумент`);
|
||||
if (!Object.prototype.hasOwnProperty.call(spec, key)) throw new ValidationError(`${key}: unknown argument`);
|
||||
}
|
||||
const out = {};
|
||||
for (const [key, check] of Object.entries(spec)) {
|
||||
const value = args[key];
|
||||
if (value === undefined) {
|
||||
if (!check.optional) throw new ValidationError(`${key}: обязательный аргумент`);
|
||||
if (!check.optional) throw new ValidationError(`${key}: required argument`);
|
||||
continue;
|
||||
}
|
||||
out[key] = check(value, key);
|
||||
@@ -74,12 +74,12 @@ const streamId = str(1, 256);
|
||||
const SIGNAL_COMMANDS = new Set(['answer', 'iceCandidate']);
|
||||
|
||||
function signalJson(value) {
|
||||
if (!isPlainObject(value)) throw new ValidationError('json: ожидался объект');
|
||||
if (!isPlainObject(value)) throw new ValidationError('json: expected an object');
|
||||
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: недопустимая команда сигнализации');
|
||||
if (keys.length !== 2 || !keys.includes('cmd') || !keys.includes('args')) throw new ValidationError('json: expected exactly the fields cmd and args');
|
||||
if (!SIGNAL_COMMANDS.has(value.cmd)) throw new ValidationError('json.cmd: signalling command not allowed');
|
||||
const args = value.args;
|
||||
if (!isPlainObject(args)) throw new ValidationError('json.args: ожидался объект');
|
||||
if (!isPlainObject(args)) throw new ValidationError('json.args: expected an object');
|
||||
if (value.cmd === 'answer') {
|
||||
shape({ answer: str(1, 60000, { multiline: true }) })(args);
|
||||
} else {
|
||||
@@ -90,7 +90,7 @@ function signalJson(value) {
|
||||
})(args);
|
||||
}
|
||||
const serialized = JSON.stringify(value);
|
||||
if (Buffer.byteLength(serialized, 'utf8') > 60 * 1024) throw new ValidationError('json: больше 60 КиБ');
|
||||
if (Buffer.byteLength(serialized, 'utf8') > 60 * 1024) throw new ValidationError('json: larger than 60 KiB');
|
||||
return JSON.parse(serialized);
|
||||
}
|
||||
|
||||
@@ -113,7 +113,7 @@ const COMMANDS = {
|
||||
message: str(1, 8192, { multiline: true, maxBytes: 8192 }),
|
||||
})(args);
|
||||
if ((out.target === 'client') !== (out.client_id !== undefined)) {
|
||||
throw new ValidationError('client_id: обязателен только для личных сообщений');
|
||||
throw new ValidationError('client_id: required for private messages only');
|
||||
}
|
||||
return out;
|
||||
},
|
||||
@@ -124,7 +124,7 @@ const COMMANDS = {
|
||||
stream_leave: shape({ stream_id: streamId, client_id: posInt }),
|
||||
fetch_icon: shape({
|
||||
icon_id: (v, k) => {
|
||||
if (!Number.isSafeInteger(v) || v <= 0 || v > 0xffffffff) throw new ValidationError(`${k}: ожидался идентификатор иконки`);
|
||||
if (!Number.isSafeInteger(v) || v <= 0 || v > 0xffffffff) throw new ValidationError(`${k}: expected an icon id`);
|
||||
return v;
|
||||
},
|
||||
}),
|
||||
@@ -136,7 +136,7 @@ const COMMANDS = {
|
||||
/** Returns sanitized args or throws ValidationError. */
|
||||
function validateRequest(cmd, args) {
|
||||
if (typeof cmd !== 'string' || !Object.prototype.hasOwnProperty.call(COMMANDS, cmd)) {
|
||||
const err = new ValidationError('Команда не разрешена');
|
||||
const err = new ValidationError('Command not allowed');
|
||||
err.code = 'unknown_command';
|
||||
throw err;
|
||||
}
|
||||
|
||||
+33
-17
@@ -24,6 +24,8 @@ const { permissionCheckAllowed, permissionRequestAllowed } = require('./permissi
|
||||
// Same switch the core uses for its own verbosity (see docs/bridge.md).
|
||||
const RENDERER_DEBUG_LOG = /\b(debug|trace)\b/.test(process.env.TEAMSPEACH_LOG ?? '');
|
||||
const { Prefs } = require('./prefs');
|
||||
const { createUpdateService } = require('./updates');
|
||||
const i18n = require('../renderer/shared/i18n.js');
|
||||
|
||||
const APP_SCHEME = 'app';
|
||||
const APP_HOST = 'teamspeach';
|
||||
@@ -86,6 +88,7 @@ if (!gotInstanceLock) {
|
||||
|
||||
let coreStatus = { status: 'starting' };
|
||||
let connectionState = 'disconnected';
|
||||
let updates = null;
|
||||
let quitting = false;
|
||||
let rendererLog = null;
|
||||
let rendererLogBudget = { windowStart: 0, count: 0 };
|
||||
@@ -156,7 +159,7 @@ async function restartCore() {
|
||||
|
||||
function runCoreCli(args) {
|
||||
const binary = resolveCoreBinary();
|
||||
if (!binary.path) return Promise.resolve({ ok: false, error: { code: 'core_missing', message: 'Исполняемый файл ядра не найден' } });
|
||||
if (!binary.path) return Promise.resolve({ ok: false, error: { code: 'core_missing', message: 'Core executable not found' } });
|
||||
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);
|
||||
@@ -168,10 +171,10 @@ function runCoreCli(args) {
|
||||
parsed = null;
|
||||
}
|
||||
if (parsed && typeof parsed === 'object') {
|
||||
resolve(parsed.ok ? { ok: true, uid: parsed.uid } : { ok: false, error: parsed.error || { code: 'internal', message: 'Неизвестная ошибка' } });
|
||||
resolve(parsed.ok ? { ok: true, uid: parsed.uid } : { ok: false, error: parsed.error || { code: 'internal', message: 'Unknown error' } });
|
||||
return;
|
||||
}
|
||||
resolve({ ok: false, error: { code: 'internal', message: err ? err.message : 'Ядро не вернуло результат' } });
|
||||
resolve({ ok: false, error: { code: 'internal', message: err ? err.message : 'The core returned no result' } });
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -215,7 +218,7 @@ function sniffImage(b) {
|
||||
|
||||
async function fetchExternalMedia(url) {
|
||||
if (typeof url !== 'string' || !externalMedia.has(url)) {
|
||||
return { ok: false, error: { code: 'forbidden', message: 'Адрес не был объявлен сервером' } };
|
||||
return { ok: false, error: { code: 'forbidden', message: 'The server did not announce this address' } };
|
||||
}
|
||||
if (!mediaSession) mediaSession = session.fromPartition('teamspeach-media', { cache: true });
|
||||
const controller = new AbortController();
|
||||
@@ -234,17 +237,17 @@ async function fetchExternalMedia(url) {
|
||||
size += value.byteLength;
|
||||
if (size > EXTERNAL_MEDIA_LIMIT) {
|
||||
controller.abort();
|
||||
return { ok: false, error: { code: 'media_too_large', message: 'Изображение больше 4 МиБ' } };
|
||||
return { ok: false, error: { code: 'media_too_large', message: 'Image larger than 4 MiB' } };
|
||||
}
|
||||
chunks.push(Buffer.from(value));
|
||||
}
|
||||
const bytes = Buffer.concat(chunks);
|
||||
// Servers mislabel images (e.g. text/plain); trust only the bytes.
|
||||
const mime = sniffImage(bytes);
|
||||
if (!mime) return { ok: false, error: { code: 'media_unsupported', message: 'Не изображение' } };
|
||||
if (!mime) return { ok: false, error: { code: 'media_unsupported', message: 'Not an image' } };
|
||||
return { ok: true, result: { mime, bytes: bytes.length, data: bytes.toString('base64') } };
|
||||
} catch (err) {
|
||||
return { ok: false, error: { code: 'io', message: err.name === 'AbortError' ? 'Истекло время загрузки' : err.message } };
|
||||
return { ok: false, error: { code: 'io', message: err.name === 'AbortError' ? 'Download timed out' : err.message } };
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
@@ -252,11 +255,16 @@ async function fetchExternalMedia(url) {
|
||||
|
||||
// ---------- identity backup (main-only, native dialogs) ----------
|
||||
|
||||
/** Native dialog text in the user's interface language. */
|
||||
function tr(key, params) {
|
||||
return i18n.t(key, params, prefs.get().language);
|
||||
}
|
||||
|
||||
async function exportIdentity() {
|
||||
const result = await dialog.showSaveDialog(mainWindow, {
|
||||
title: 'Экспорт идентичности TeamsPeach',
|
||||
title: tr('native.identityExport.title'),
|
||||
defaultPath: path.join(app.getPath('documents'), 'teamspeach-identity.ini'),
|
||||
filters: [{ name: 'Идентичность TeamSpeak', extensions: ['ini'] }],
|
||||
filters: [{ name: tr('native.identity.filter'), extensions: ['ini'] }],
|
||||
properties: ['showOverwriteConfirmation', 'createDirectory'],
|
||||
});
|
||||
if (result.canceled || !result.filePath) return { ok: false, canceled: true };
|
||||
@@ -273,16 +281,16 @@ async function exportIdentity() {
|
||||
|
||||
async function importIdentity() {
|
||||
if (connectionState !== 'disconnected') {
|
||||
return { ok: false, error: { code: 'connected', message: 'Сначала отключитесь от сервера' } };
|
||||
return { ok: false, error: { code: 'connected', message: 'Disconnect from the server first' } };
|
||||
}
|
||||
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: ['Отмена', 'Выбрать файл и заменить'],
|
||||
title: tr('native.identityReplace.title'),
|
||||
message: tr('native.identityReplace.message'),
|
||||
detail: tr('native.identityReplace.detail'),
|
||||
buttons: [tr('native.identityReplace.cancel'), tr('native.identityReplace.confirm')],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
@@ -290,8 +298,8 @@ async function importIdentity() {
|
||||
if (confirm.response !== 1) return { ok: false, canceled: true };
|
||||
}
|
||||
const pick = await dialog.showOpenDialog(mainWindow, {
|
||||
title: 'Импорт идентичности',
|
||||
filters: [{ name: 'Идентичность TeamSpeak', extensions: ['ini'] }, { name: 'Все файлы', extensions: ['*'] }],
|
||||
title: tr('native.identityImport.title'),
|
||||
filters: [{ name: tr('native.identity.filter'), extensions: ['ini'] }, { name: tr('native.allFiles'), extensions: ['*'] }],
|
||||
properties: ['openFile'],
|
||||
});
|
||||
if (pick.canceled || pick.filePaths.length !== 1) return { ok: false, canceled: true };
|
||||
@@ -407,7 +415,7 @@ function registerIpc() {
|
||||
} catch (err) {
|
||||
return { ok: false, error: { code: err.code || 'bad_request', message: err.message } };
|
||||
}
|
||||
if (!core) return { ok: false, error: { code: 'core_unavailable', message: 'Ядро не запущено' } };
|
||||
if (!core) return { ok: false, error: { code: 'core_unavailable', message: 'The core is not running' } };
|
||||
const hasArgs = Object.keys(clean).length > 0;
|
||||
const response = await core.request(cmd, hasArgs ? clean : undefined);
|
||||
if (!response.ok && response.error.code === 'external_media' && response.error.detail) {
|
||||
@@ -523,6 +531,14 @@ app.whenReady().then(() => {
|
||||
registerIpc();
|
||||
createWindow();
|
||||
startCore();
|
||||
// Updates come only from published releases of the public repo; nothing installs without a click.
|
||||
updates = createUpdateService({
|
||||
prefs,
|
||||
isSessionActive: () => connectionState !== 'disconnected',
|
||||
send: (state) => sendToRenderer('update:state', state),
|
||||
});
|
||||
updates.registerIpc(ipcMain, trustedSender);
|
||||
updates.start();
|
||||
});
|
||||
|
||||
app.on('window-all-closed', () => app.quit());
|
||||
|
||||
+5
-3
@@ -24,6 +24,8 @@ const SCHEMA = {
|
||||
theme: { default: 'dark', check: (v) => v === 'system' || v === 'dark' || v === 'light' },
|
||||
// Updater: 'preview' accepts prereleases (all TeamsPeach releases so far), 'stable' only full releases.
|
||||
updateChannel: { default: 'preview', check: (v) => v === 'preview' || v === 'stable' },
|
||||
// Interface language: English for new profiles (owner's request); a stored valid choice is kept.
|
||||
language: { default: 'en', check: (v) => v === 'en' || v === 'ru' },
|
||||
// Quick-access servers: name + address only. Passwords are never stored.
|
||||
savedServers: { default: [], check: validServers },
|
||||
};
|
||||
@@ -67,12 +69,12 @@ class Prefs {
|
||||
|
||||
/** 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: ожидался объект');
|
||||
if (!partial || typeof partial !== 'object' || Array.isArray(partial)) throw new Error('prefs: expected an object');
|
||||
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}`);
|
||||
if (!spec) throw new Error(`prefs: unknown key ${key}`);
|
||||
if (!spec.check(value)) throw new Error(`prefs: invalid value for ${key}`);
|
||||
next[key] = value;
|
||||
}
|
||||
this.values = next;
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
'use strict';
|
||||
|
||||
// Where updates come from and which published release this installation may move to.
|
||||
// Pure Node (no Electron): the complete Gitea release list is fetched anonymously from one fixed HTTPS host,
|
||||
// releases are filtered by channel, version (semver) and platform, and only complete releases are offered.
|
||||
// electron-updater then reads the feed of the chosen release and verifies size and sha512.
|
||||
|
||||
const path = require('node:path');
|
||||
const semver = require('semver');
|
||||
|
||||
const FORGE_ORIGIN = 'https://git.eeee.moe';
|
||||
const OWNER = 'TeamsPeach';
|
||||
const REPO = 'client';
|
||||
const RELEASES_API = `${FORGE_ORIGIN}/api/v1/repos/${OWNER}/${REPO}/releases`;
|
||||
const PAGE_SIZE = 50;
|
||||
const MAX_PAGES = 20;
|
||||
const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
|
||||
const PRODUCT = 'TeamsPeach';
|
||||
const LINUX_EXECUTABLE = 'teamspeach';
|
||||
|
||||
const ASSET_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
|
||||
const SHA512_BASE64 = /^[A-Za-z0-9+/]{86}==$/;
|
||||
|
||||
/**
|
||||
* Failure with a stable machine code and parameters; the renderer shows the localized text for `code`.
|
||||
* `message` is English technical text for logs only.
|
||||
*/
|
||||
class UpdateError extends Error {
|
||||
constructor(code, params = {}, message = code) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
this.params = params;
|
||||
}
|
||||
}
|
||||
|
||||
/** Strict SemVer 2.0 without build metadata (`0.1.2`, `0.1.2-rc.1`); null otherwise (`01.1.1`, `0.1`, `1.0.0+x`). */
|
||||
function cleanVersion(text) {
|
||||
if (typeof text !== 'string' || text.includes('+')) return null;
|
||||
return semver.valid(text) === text ? text : null;
|
||||
}
|
||||
|
||||
/** Release tag `v<version>`; returns the version or null. */
|
||||
function tagVersion(tag) {
|
||||
return typeof tag === 'string' && tag.startsWith('v') ? cleanVersion(tag.slice(1)) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What this installation is and how it can be updated.
|
||||
* mode 'auto': electron-updater installs (NSIS-installed Windows x64, Linux AppImage).
|
||||
* mode 'manual': user is told and replaces files himself (Windows zip, Linux tar.gz).
|
||||
* mode 'none': dev run or a platform that has no published build.
|
||||
*/
|
||||
function detectTarget({ platform, arch, packaged, env, execPath, exists }) {
|
||||
const none = (id, disabledCode) => ({ id, platform, arch, mode: 'none', kind: null, disabledCode });
|
||||
if (!packaged) return none(`${platform}-${arch}-dev`, 'dev-build');
|
||||
if (platform === 'win32') {
|
||||
if (arch !== 'x64') return none(`win-${arch}`, 'unsupported-platform');
|
||||
// The NSIS installer leaves its uninstaller next to the executable; the portable zip does not.
|
||||
if (exists(path.join(path.dirname(execPath), `Uninstall ${PRODUCT}.exe`))) {
|
||||
return { id: 'win-x64-nsis', platform, arch, mode: 'auto', kind: 'nsis', disabledCode: null };
|
||||
}
|
||||
return { id: 'win-x64-zip', platform, arch, mode: 'manual', kind: 'zip', disabledCode: null };
|
||||
}
|
||||
if (platform === 'linux') {
|
||||
if (arch !== 'x64' && arch !== 'arm64') return none(`linux-${arch}`, 'unsupported-platform');
|
||||
if (env.APPIMAGE) return { id: `linux-${arch}-appimage`, platform, arch, mode: 'auto', kind: 'appimage', disabledCode: null };
|
||||
return { id: `linux-${arch}-tar.gz`, platform, arch, mode: 'manual', kind: 'tar.gz', disabledCode: null };
|
||||
}
|
||||
if (platform === 'darwin') return none(`mac-${arch}`, 'unsupported-platform');
|
||||
return none(`${platform}-${arch}`, 'unsupported-platform');
|
||||
}
|
||||
|
||||
/** electron-builder names the feed after the version's first prerelease identifier, else "latest". */
|
||||
function feedChannel(version) {
|
||||
const pre = semver.prerelease(version);
|
||||
return pre && pre.length > 0 ? String(pre[0]) : 'latest';
|
||||
}
|
||||
|
||||
/** Exact feed file electron-builder writes for this target (app-builder-lib getUpdateInfoFileName). */
|
||||
function feedFileName(target, version) {
|
||||
const channel = feedChannel(version);
|
||||
if (target.kind === 'nsis') return `${channel}.yml`;
|
||||
if (target.kind === 'appimage') return target.arch === 'x64' ? `${channel}-linux.yml` : `${channel}-linux-${target.arch}.yml`;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exact installer electron-builder produces for this target (package.json build config: AppImage default
|
||||
* name, nsis.artifactName "${productName}-${version}-win-${arch}-setup.${ext}").
|
||||
*/
|
||||
function packageFileName(target, version) {
|
||||
if (target.kind === 'appimage') return target.arch === 'x64' ? `${PRODUCT}-${version}.AppImage` : `${PRODUCT}-${version}-${target.arch}.AppImage`;
|
||||
if (target.kind === 'nsis') return `${PRODUCT}-${version}-win-${target.arch}-setup.exe`;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Package names a manual-mode user downloads (builder defaults, plus the historical "-local" Windows zip). */
|
||||
function manualAssetNames(target, version) {
|
||||
if (target.kind === 'tar.gz') return [target.arch === 'x64' ? `${LINUX_EXECUTABLE}-${version}.tar.gz` : `${LINUX_EXECUTABLE}-${version}-${target.arch}.tar.gz`];
|
||||
if (target.kind === 'zip') return [`${PRODUCT}-${version}-win-x64.zip`, `${PRODUCT}-${version}-win.zip`, `${PRODUCT}-${version}-win-x64-local.zip`];
|
||||
return [];
|
||||
}
|
||||
|
||||
function releaseDownloadBase(tag) {
|
||||
return `${FORGE_ORIGIN}/${OWNER}/${REPO}/releases/download/${tag}/`;
|
||||
}
|
||||
|
||||
function releasePageUrl(tag) {
|
||||
return `${FORGE_ORIGIN}/${OWNER}/${REPO}/releases/tag/${tag}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks the releases this installation may update to, newest first.
|
||||
* Every published, non-draft release with a valid tag is considered. A release is "preview" when Gitea
|
||||
* marks it prerelease or its version has a prerelease part; the stable channel never sees previews.
|
||||
* Same or older versions are never offered. A release counts only when it carries this target's feed and
|
||||
* installer (auto) or package (manual); newer releases without one are reported in `withoutBuild`.
|
||||
*/
|
||||
function selectReleases(releases, { currentVersion, channel, target }) {
|
||||
const current = cleanVersion(currentVersion);
|
||||
if (!current) throw new UpdateError('bad-version', { version: String(currentVersion) }, `app version ${currentVersion} is not semver`);
|
||||
if (channel !== 'preview' && channel !== 'stable') throw new UpdateError('bad-channel', { channel: String(channel) }, `unknown channel ${channel}`);
|
||||
if (!Array.isArray(releases)) throw new UpdateError('bad-response', { detail: 'release list is not an array' }, 'release list is not an array');
|
||||
const candidates = [];
|
||||
const withoutBuild = [];
|
||||
const previews = [];
|
||||
for (const release of releases) {
|
||||
if (!release || typeof release !== 'object' || release.draft !== false) continue;
|
||||
const version = tagVersion(release.tag_name);
|
||||
if (!version || !semver.gt(version, current)) continue;
|
||||
const preview = release.prerelease !== false || semver.prerelease(version) !== null;
|
||||
if (channel === 'stable' && preview) {
|
||||
previews.push(version);
|
||||
continue;
|
||||
}
|
||||
const assets = new Map();
|
||||
for (const asset of Array.isArray(release.assets) ? release.assets : []) {
|
||||
if (asset && typeof asset.name === 'string' && ASSET_NAME.test(asset.name) && Number.isSafeInteger(asset.size) && asset.size > 0) {
|
||||
assets.set(asset.name, asset.size);
|
||||
}
|
||||
}
|
||||
const tag = release.tag_name;
|
||||
const entry = {
|
||||
tag,
|
||||
version,
|
||||
preview,
|
||||
publishedAt: typeof release.published_at === 'string' ? release.published_at : null,
|
||||
assets,
|
||||
downloadBase: releaseDownloadBase(tag),
|
||||
releaseUrl: releasePageUrl(tag),
|
||||
feedChannel: feedChannel(version),
|
||||
feedFile: null,
|
||||
packageFile: null,
|
||||
manualAsset: null,
|
||||
};
|
||||
if (target.mode === 'auto') {
|
||||
const feed = feedFileName(target, version);
|
||||
const pkg = packageFileName(target, version);
|
||||
if (!assets.has(feed) || !assets.has(pkg)) {
|
||||
const missing = assets.has(feed) ? pkg : feed;
|
||||
withoutBuild.push({ version, code: assets.has(feed) ? 'no-package' : 'no-feed', params: { version, file: missing, target: target.id } });
|
||||
continue;
|
||||
}
|
||||
entry.feedFile = feed;
|
||||
entry.packageFile = pkg;
|
||||
} else if (target.mode === 'manual') {
|
||||
const name = manualAssetNames(target, version).find((n) => assets.has(n));
|
||||
if (!name) {
|
||||
withoutBuild.push({ version, code: 'no-package', params: { version, file: manualAssetNames(target, version)[0], target: target.id } });
|
||||
continue;
|
||||
}
|
||||
entry.manualAsset = name;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
candidates.push(entry);
|
||||
}
|
||||
candidates.sort((a, b) => semver.rcompare(a.version, b.version));
|
||||
withoutBuild.sort((a, b) => semver.rcompare(a.version, b.version));
|
||||
previews.sort(semver.rcompare);
|
||||
return { candidates, withoutBuild, newestPreview: previews.length > 0 ? previews[0] : null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the feed electron-updater parsed against the release it was taken from: same version, and exactly
|
||||
* one package — this target's installer by its exact builder name (so an arm64 feed pointing at the x64
|
||||
* AppImage, or a renamed/foreign file, is refused) — present in THIS release with the declared size and a sha512.
|
||||
*/
|
||||
function verifyFeed(candidate, target, updateInfo) {
|
||||
const mismatch = (detail) => new UpdateError('feed-mismatch', { tag: candidate.tag, detail }, `${candidate.tag}: ${detail}`);
|
||||
if (!updateInfo || typeof updateInfo !== 'object') throw mismatch('feed is empty');
|
||||
if (cleanVersion(updateInfo.version) !== candidate.version) throw mismatch(`feed describes version ${String(updateInfo.version)}`);
|
||||
const expected = packageFileName(target, candidate.version);
|
||||
const files = Array.isArray(updateInfo.files) ? updateInfo.files : [];
|
||||
if (files.length !== 1 || !files[0] || files[0].url !== expected) {
|
||||
const listed = files.map((f) => (f && typeof f.url === 'string' ? f.url : '?')).join(', ') || 'nothing';
|
||||
throw mismatch(`feed for ${target.id} must list only ${expected}, lists: ${listed}`);
|
||||
}
|
||||
if (updateInfo.path !== undefined && updateInfo.path !== expected) throw mismatch(`feed path ${String(updateInfo.path)} is not ${expected}`);
|
||||
const file = files[0];
|
||||
if (typeof file.sha512 !== 'string' || !SHA512_BASE64.test(file.sha512)) throw mismatch(`no sha512 for ${expected}`);
|
||||
if (!candidate.assets.has(expected)) {
|
||||
throw new UpdateError('incomplete-release', { tag: candidate.tag, file: expected }, `${candidate.tag} has no asset ${expected}`);
|
||||
}
|
||||
if (file.size !== candidate.assets.get(expected)) {
|
||||
throw new UpdateError('incomplete-release', { tag: candidate.tag, file: expected }, `${candidate.tag}: size of ${expected} differs from the feed`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Anonymous GET of EVERY published release (paged; Gitea reports the total in X-Total-Count).
|
||||
* `fetchImpl` is Electron's net.fetch in the app. Network failure, timeout (whole listing), HTTP errors,
|
||||
* malformed bodies and a listing that cannot be completed within MAX_PAGES all throw UpdateError —
|
||||
* never a partial list that could hide a newer release.
|
||||
*/
|
||||
async function fetchReleases({ fetchImpl, timeoutMs = 20000 }) {
|
||||
const badResponse = (detail) => new UpdateError('bad-response', { detail }, `release list: ${detail}`);
|
||||
const signal = AbortSignal.timeout(timeoutMs);
|
||||
const all = [];
|
||||
let total = null;
|
||||
for (let page = 1; page <= MAX_PAGES; page += 1) {
|
||||
const url = `${RELEASES_API}?draft=false&limit=${PAGE_SIZE}&page=${page}`;
|
||||
let text;
|
||||
let headerTotal;
|
||||
try {
|
||||
const res = await fetchImpl(url, { signal, redirect: 'error', cache: 'no-store', headers: { Accept: 'application/json' } });
|
||||
if (!res.ok) throw new UpdateError('http', { status: res.status }, `release list: HTTP ${res.status}`);
|
||||
if (Number(res.headers.get('content-length')) > MAX_RESPONSE_BYTES) throw badResponse('response too large');
|
||||
headerTotal = res.headers.get('x-total-count');
|
||||
text = await res.text();
|
||||
} catch (err) {
|
||||
if (err instanceof UpdateError) throw err;
|
||||
const seconds = Math.round(timeoutMs / 1000);
|
||||
if (signal.aborted) throw new UpdateError('timeout', { seconds }, `release list: no answer in ${seconds} s`);
|
||||
const detail = err && err.cause && err.cause.message ? `${err.message}: ${err.cause.message}` : String(err && err.message ? err.message : err);
|
||||
throw new UpdateError('network', { detail }, `release list: ${detail}`);
|
||||
}
|
||||
if (text.length > MAX_RESPONSE_BYTES) throw badResponse('response too large');
|
||||
let items;
|
||||
try {
|
||||
items = JSON.parse(text);
|
||||
} catch {
|
||||
throw badResponse('not JSON');
|
||||
}
|
||||
if (!Array.isArray(items)) throw badResponse('not a release list');
|
||||
if (headerTotal !== null) {
|
||||
if (!/^\d+$/.test(headerTotal)) throw badResponse('invalid X-Total-Count');
|
||||
total = Number(headerTotal);
|
||||
}
|
||||
all.push(...items);
|
||||
// Done when the server's total is reached, or (no total reported) when a page comes back empty.
|
||||
if (total !== null ? all.length >= total || items.length === 0 : items.length === 0) {
|
||||
if (total !== null && all.length < total) {
|
||||
throw new UpdateError('incomplete-list', { fetched: all.length, total }, `release list: got ${all.length} of ${total}`);
|
||||
}
|
||||
return all;
|
||||
}
|
||||
}
|
||||
throw new UpdateError('incomplete-list', { fetched: all.length, total }, `release list longer than ${MAX_PAGES} pages`);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
FORGE_ORIGIN,
|
||||
RELEASES_API,
|
||||
PAGE_SIZE,
|
||||
UpdateError,
|
||||
cleanVersion,
|
||||
detectTarget,
|
||||
feedFileName,
|
||||
packageFileName,
|
||||
manualAssetNames,
|
||||
releaseDownloadBase,
|
||||
releasePageUrl,
|
||||
selectReleases,
|
||||
verifyFeed,
|
||||
fetchReleases,
|
||||
};
|
||||
@@ -0,0 +1,454 @@
|
||||
'use strict';
|
||||
|
||||
// Update service of the main process. Finds the newest eligible published release (update-source.js),
|
||||
// lets electron-updater read that release's feed, download and verify the package, and installs ONLY after
|
||||
// an explicit user action. It never quits or restarts the app on its own.
|
||||
//
|
||||
// Every check uses a NEW electron-updater instance. electron-updater keeps the last checked feed inside the
|
||||
// instance and cannot cancel a running check, so a check that timed out (or a check for another channel) can
|
||||
// still finish later; with one instance per check, such a late result can only touch an abandoned instance.
|
||||
// Download and install always use the exact instance that checked the offered release.
|
||||
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { app, net, shell } = require('electron');
|
||||
const source = require('./update-source');
|
||||
const { logsDir } = require('./paths');
|
||||
|
||||
const STARTUP_DELAY_MS = 15 * 1000;
|
||||
const CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000;
|
||||
const DEFERRED_POLL_MS = 60 * 1000;
|
||||
const FEED_TIMEOUT_MS = 60 * 1000;
|
||||
const LOG_LIMIT_BYTES = 1024 * 1024;
|
||||
const CHANNELS = ['preview', 'stable'];
|
||||
|
||||
function fileLogger(file) {
|
||||
const write = (level, parts) => {
|
||||
const line = `${new Date().toISOString()} ${level} ${parts.map((p) => (p instanceof Error ? p.stack || p.message : String(p))).join(' ')}`;
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
try {
|
||||
if (fs.statSync(file).size > LOG_LIMIT_BYTES) fs.renameSync(file, `${file}.1`);
|
||||
} catch {
|
||||
// no log yet
|
||||
}
|
||||
fs.appendFileSync(file, `${line.replace(/[\r\n]+/g, ' ')}\n`);
|
||||
} catch {
|
||||
// logging must never break updating
|
||||
}
|
||||
};
|
||||
return {
|
||||
info: (...p) => write('info', p),
|
||||
warn: (...p) => write('warn', p),
|
||||
error: (...p) => write('error', p),
|
||||
debug: () => {},
|
||||
};
|
||||
}
|
||||
|
||||
/** electron-updater instance for this target, configured so that nothing happens without our call. */
|
||||
function defaultCreateUpdater(target, logger, channel) {
|
||||
const { NsisUpdater, AppImageUpdater } = require('electron-updater');
|
||||
const instance = target.kind === 'nsis' ? new NsisUpdater() : new AppImageUpdater();
|
||||
instance.logger = logger;
|
||||
instance.autoDownload = false;
|
||||
instance.autoInstallOnAppQuit = false;
|
||||
instance.allowDowngrade = false;
|
||||
// Only the GitHub providers read allowPrerelease; with the generic provider the channel policy is applied
|
||||
// by update-source before a feed is chosen. Kept consistent with the selected channel anyway.
|
||||
instance.allowPrerelease = channel === 'preview';
|
||||
instance.disableWebInstaller = true;
|
||||
return instance;
|
||||
}
|
||||
|
||||
const CHECKSUM_FAILURE = /checksum mismatch/i;
|
||||
const NETWORK_FAILURE = /net::ERR_|ENOTFOUND|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|socket hang up/i;
|
||||
|
||||
/** Maps electron-updater / network failures to stable codes; `detail` keeps the technical text. */
|
||||
function classify(err, fallback, tag) {
|
||||
if (err instanceof source.UpdateError) return err;
|
||||
const detail = (err && err.message ? err.message : String(err)).split('\n')[0].slice(0, 300);
|
||||
const code = err && err.code;
|
||||
if (code === 'ERR_CHECKSUM_MISMATCH' || CHECKSUM_FAILURE.test(detail)) return new source.UpdateError('checksum', { tag, detail }, detail);
|
||||
if (code === 'ERR_UPDATER_CHANNEL_FILE_NOT_FOUND' || (err && err.statusCode === 404)) {
|
||||
return new source.UpdateError('incomplete-release', { tag, file: null, detail }, detail);
|
||||
}
|
||||
if (err && Number.isInteger(err.statusCode)) return new source.UpdateError('http', { status: err.statusCode }, detail);
|
||||
if (NETWORK_FAILURE.test(detail)) {
|
||||
return new source.UpdateError('network', { detail }, detail);
|
||||
}
|
||||
return new source.UpdateError(fallback, { tag, detail }, detail);
|
||||
}
|
||||
|
||||
function withTimeout(promise, ms, tag) {
|
||||
let timer;
|
||||
const seconds = Math.round(ms / 1000);
|
||||
return Promise.race([
|
||||
promise,
|
||||
new Promise((_, reject) => {
|
||||
timer = setTimeout(() => reject(new source.UpdateError('timeout', { seconds, tag }, `feed of ${tag}: no answer in ${seconds} s`)), ms);
|
||||
}),
|
||||
]).finally(() => clearTimeout(timer));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} o
|
||||
* @param {{ get(): object, set(partial: object): object }} o.prefs holds `updateChannel`
|
||||
* @param {() => boolean} o.isSessionActive true while connected to a server (voice / stream viewing)
|
||||
* @param {(state: object) => void} o.send pushes the state to the renderer
|
||||
* Remaining options exist for the Electron behaviour harness; the release host is not configurable.
|
||||
*/
|
||||
function createUpdateService({
|
||||
prefs,
|
||||
isSessionActive,
|
||||
send,
|
||||
electronApp = app,
|
||||
fetchImpl = (url, init) => net.fetch(url, init),
|
||||
target = source.detectTarget({
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
packaged: electronApp.isPackaged,
|
||||
env: process.env,
|
||||
execPath: process.execPath,
|
||||
exists: fs.existsSync,
|
||||
}),
|
||||
createUpdater = defaultCreateUpdater,
|
||||
openExternal = (url) => shell.openExternal(url),
|
||||
logger = fileLogger(path.join(logsDir(), 'updater.log')),
|
||||
appImagePath = () => process.env.APPIMAGE,
|
||||
argv = process.argv,
|
||||
feedTimeoutMs = FEED_TIMEOUT_MS,
|
||||
}) {
|
||||
const currentVersion = electronApp.getVersion();
|
||||
let offered = null; // { candidate, updater } — release in state.available and the instance that checked it
|
||||
let downloaded = null; // { candidate, updater } — verified package ready to install
|
||||
let downloading = null; // { updater, token }
|
||||
let busy = null; // in-flight check/download promise
|
||||
let timers = [];
|
||||
let deferredTimer = null;
|
||||
let lastProgressSent = 0;
|
||||
|
||||
const state = {
|
||||
currentVersion,
|
||||
channel: 'preview',
|
||||
mode: target.mode,
|
||||
target: target.id,
|
||||
phase: target.mode === 'none' ? 'disabled' : 'idle',
|
||||
lastCheckedAt: null,
|
||||
available: null,
|
||||
progress: null,
|
||||
newerWithoutBuild: [],
|
||||
newerPreview: null,
|
||||
error: null, // { code, params } — localized by the renderer; params.detail is technical text
|
||||
disabledCode: target.disabledCode,
|
||||
disabledParams: target.mode === 'none' ? { platform: target.platform, arch: target.arch } : null,
|
||||
};
|
||||
|
||||
logger.info(`updater: version ${currentVersion} pid ${process.pid} target ${target.id} mode ${target.mode}`);
|
||||
|
||||
function channel() {
|
||||
const value = prefs.get().updateChannel;
|
||||
return CHANNELS.includes(value) ? value : 'preview';
|
||||
}
|
||||
|
||||
function snapshot() {
|
||||
return {
|
||||
...state,
|
||||
channel: channel(),
|
||||
available: state.available ? { ...state.available } : null,
|
||||
progress: state.progress ? { ...state.progress } : null,
|
||||
newerWithoutBuild: state.newerWithoutBuild.map((x) => ({ ...x, params: { ...x.params } })),
|
||||
error: state.error ? { code: state.error.code, params: { ...state.error.params } } : null,
|
||||
disabledParams: state.disabledParams ? { ...state.disabledParams } : null,
|
||||
sessionActive: Boolean(isSessionActive()),
|
||||
};
|
||||
}
|
||||
|
||||
function emit() {
|
||||
try {
|
||||
send(snapshot());
|
||||
} catch (err) {
|
||||
logger.warn('updater: state push failed', err);
|
||||
}
|
||||
}
|
||||
|
||||
function setPhase(phase, extra = {}) {
|
||||
Object.assign(state, { phase }, extra);
|
||||
emit();
|
||||
}
|
||||
|
||||
function fail(err, fallback, tag) {
|
||||
const e = classify(err, fallback, tag);
|
||||
logger.error(`updater: ${e.code}: ${e.message}`);
|
||||
setPhase('error', { error: { code: e.code, params: e.params || {} }, progress: null });
|
||||
return e;
|
||||
}
|
||||
|
||||
function newUpdater(selectedChannel) {
|
||||
const u = createUpdater(target, logger, selectedChannel);
|
||||
// Failures are handled where the promises reject; the listener keeps EventEmitter from throwing.
|
||||
u.on('error', (err) => logger.warn('updater: electron-updater error event', err));
|
||||
u.on('download-progress', (p) => {
|
||||
if (!downloading || downloading.updater !== u) return;
|
||||
state.progress = { percent: Math.max(0, Math.min(100, Number(p.percent) || 0)), transferred: p.transferred, total: p.total };
|
||||
const now = Date.now();
|
||||
if (now - lastProgressSent >= 250) {
|
||||
lastProgressSent = now;
|
||||
emit();
|
||||
}
|
||||
});
|
||||
return u;
|
||||
}
|
||||
|
||||
/** Reads the candidate's feed through electron-updater and checks it against the release assets. */
|
||||
async function readFeed(u, candidate) {
|
||||
u.setFeedURL({ provider: 'generic', url: candidate.downloadBase, channel: candidate.feedChannel });
|
||||
const result = await withTimeout(u.checkForUpdates(), feedTimeoutMs, candidate.tag);
|
||||
if (!result) throw new source.UpdateError('feed-mismatch', { tag: candidate.tag, detail: 'updater inactive' }, 'electron-updater inactive');
|
||||
source.verifyFeed(candidate, target, result.updateInfo);
|
||||
if (!result.isUpdateAvailable) {
|
||||
const detail = 'electron-updater: not applicable to this system';
|
||||
throw new source.UpdateError('feed-mismatch', { tag: candidate.tag, detail }, detail);
|
||||
}
|
||||
}
|
||||
|
||||
async function runCheck() {
|
||||
const selectedChannel = channel();
|
||||
setPhase('checking', { error: null });
|
||||
let selection;
|
||||
try {
|
||||
const releases = await source.fetchReleases({ fetchImpl });
|
||||
selection = source.selectReleases(releases, { currentVersion, channel: selectedChannel, target });
|
||||
} catch (err) {
|
||||
fail(err, 'bad-response');
|
||||
return;
|
||||
}
|
||||
const skipped = [...selection.withoutBuild];
|
||||
let chosen = null;
|
||||
if (target.mode === 'manual') {
|
||||
if (selection.candidates[0]) chosen = { candidate: selection.candidates[0], updater: null };
|
||||
} else {
|
||||
for (const candidate of selection.candidates) {
|
||||
const u = newUpdater(selectedChannel);
|
||||
try {
|
||||
await readFeed(u, candidate);
|
||||
chosen = { candidate, updater: u };
|
||||
break;
|
||||
} catch (err) {
|
||||
const e = classify(err, 'feed-mismatch', candidate.tag);
|
||||
// A broken or incomplete release is skipped in favour of an older complete one; a network failure or
|
||||
// timeout ends the check with an error, so "no update" is never reported without a full answer.
|
||||
if (e.code !== 'feed-mismatch' && e.code !== 'incomplete-release') {
|
||||
fail(e, 'network');
|
||||
return;
|
||||
}
|
||||
logger.warn(`updater: skip ${candidate.tag}: ${e.message}`);
|
||||
skipped.push({ version: candidate.version, code: e.code, params: { version: candidate.version, ...e.params } });
|
||||
}
|
||||
}
|
||||
}
|
||||
offered = chosen;
|
||||
state.lastCheckedAt = new Date().toISOString();
|
||||
state.newerWithoutBuild = skipped;
|
||||
state.newerPreview = selection.newestPreview;
|
||||
if (!chosen) {
|
||||
downloaded = null;
|
||||
logger.info(`updater: up to date (${selectedChannel}), ${skipped.length} newer release(s) without a usable build`);
|
||||
setPhase('up-to-date', { available: null, progress: null, error: null });
|
||||
return;
|
||||
}
|
||||
const c = chosen.candidate;
|
||||
logger.info(`updater: ${c.tag} available (${selectedChannel})`);
|
||||
const available = { version: c.version, tag: c.tag, preview: c.preview, publishedAt: c.publishedAt, assetName: c.manualAsset || c.packageFile };
|
||||
if (downloaded && downloaded.candidate.tag === c.tag) {
|
||||
offered = downloaded;
|
||||
setPhase('downloaded', { available, error: null });
|
||||
return;
|
||||
}
|
||||
downloaded = null;
|
||||
setPhase('available', { available, progress: null, error: null });
|
||||
}
|
||||
|
||||
async function runDownload() {
|
||||
const job = offered;
|
||||
const { CancellationToken } = require('electron-updater');
|
||||
downloading = { updater: job.updater, token: new CancellationToken() };
|
||||
const { token } = downloading;
|
||||
setPhase('downloading', { progress: { percent: 0, transferred: 0, total: 0 }, error: null });
|
||||
try {
|
||||
await job.updater.downloadUpdate(token);
|
||||
if (offered !== job) {
|
||||
logger.info(`updater: ${job.candidate.tag} downloaded but no longer offered`);
|
||||
return;
|
||||
}
|
||||
downloaded = job;
|
||||
logger.info(`updater: ${job.candidate.tag} downloaded and verified`);
|
||||
setPhase('downloaded', { progress: null });
|
||||
} catch (err) {
|
||||
if (token.cancelled) {
|
||||
logger.info('updater: download cancelled');
|
||||
if (offered === job) setPhase('available', { progress: null });
|
||||
} else {
|
||||
fail(err, 'download', job.candidate.tag);
|
||||
}
|
||||
} finally {
|
||||
downloading = null;
|
||||
}
|
||||
}
|
||||
|
||||
function exclusive(fn) {
|
||||
if (busy) return busy.then(snapshot);
|
||||
busy = fn().finally(() => {
|
||||
busy = null;
|
||||
});
|
||||
return busy.then(snapshot);
|
||||
}
|
||||
|
||||
function scheduleDeferredPoll() {
|
||||
if (deferredTimer) return;
|
||||
deferredTimer = setInterval(() => {
|
||||
if (state.phase !== 'deferred') {
|
||||
clearInterval(deferredTimer);
|
||||
deferredTimer = null;
|
||||
} else if (!isSessionActive()) {
|
||||
download({ manual: false });
|
||||
}
|
||||
}, DEFERRED_POLL_MS);
|
||||
}
|
||||
|
||||
/** Background downloads wait while the user is connected; a manual request downloads now. */
|
||||
function download({ manual }) {
|
||||
if (busy) return busy.then(snapshot);
|
||||
if (target.mode !== 'auto' || !offered || (state.phase !== 'available' && state.phase !== 'deferred')) return Promise.resolve(snapshot());
|
||||
if (!manual && isSessionActive()) {
|
||||
if (state.phase !== 'deferred') {
|
||||
logger.info('updater: download deferred until the session ends');
|
||||
setPhase('deferred');
|
||||
}
|
||||
scheduleDeferredPoll();
|
||||
return Promise.resolve(snapshot());
|
||||
}
|
||||
return exclusive(runDownload);
|
||||
}
|
||||
|
||||
function check({ manual }) {
|
||||
if (target.mode === 'none' || state.phase === 'installing') return Promise.resolve(snapshot());
|
||||
return exclusive(runCheck)
|
||||
.then((s) => (s.phase === 'available' && target.mode === 'auto' ? download({ manual: false }) : s))
|
||||
.then((s) => {
|
||||
if (manual) logger.info(`updater: manual check → ${s.phase}`);
|
||||
return s;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs the downloaded, verified package after an explicit user action. Uses electron-updater's
|
||||
* quitAndInstall; its install step is synchronous and reports failures through the 'error' event.
|
||||
* NSIS: silent update of the existing installation, the installer starts the new version. Whether the
|
||||
* installer then succeeds happens after this process quits and is not claimed here.
|
||||
* AppImage: the file is replaced, then app.relaunch() starts the new AppImage only after this process
|
||||
* has exited (the single-instance lock and the core's data-dir lock are free by then).
|
||||
*/
|
||||
function install(options) {
|
||||
const confirmInterrupt = Boolean(options && options.confirmInterrupt === true);
|
||||
if (target.mode !== 'auto' || state.phase !== 'downloaded' || !downloaded || offered !== downloaded) {
|
||||
return { ok: false, code: 'not-ready' };
|
||||
}
|
||||
if (isSessionActive() && !confirmInterrupt) return { ok: false, code: 'session-active' };
|
||||
const u = downloaded.updater;
|
||||
const tag = downloaded.candidate.tag;
|
||||
setPhase('installing');
|
||||
let installError = null;
|
||||
let destination = appImagePath();
|
||||
const onError = (err) => {
|
||||
installError = err;
|
||||
};
|
||||
const onRename = (file) => {
|
||||
destination = file;
|
||||
};
|
||||
u.on('error', onError);
|
||||
u.on('appimage-filename-updated', onRename);
|
||||
try {
|
||||
if (target.kind === 'appimage') u.quitAndInstall(true, false);
|
||||
else u.quitAndInstall(true, true);
|
||||
} catch (err) {
|
||||
installError = err;
|
||||
} finally {
|
||||
u.removeListener('error', onError);
|
||||
u.removeListener('appimage-filename-updated', onRename);
|
||||
}
|
||||
if (installError) {
|
||||
const e = fail(installError, 'install', tag);
|
||||
return { ok: false, code: 'install-failed', params: e.params };
|
||||
}
|
||||
if (target.kind === 'appimage') {
|
||||
// quitAndInstall quits on the next tick; the relaunch is registered before that.
|
||||
electronApp.relaunch({ execPath: destination, args: argv.slice(1) });
|
||||
logger.info(`updater: AppImage replaced by ${tag} at ${destination}; relaunch after exit`);
|
||||
} else {
|
||||
logger.info(`updater: NSIS installer for ${tag} started; app quits`);
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
async function setChannel(value) {
|
||||
if (!CHANNELS.includes(value)) return snapshot();
|
||||
if (value !== channel()) {
|
||||
prefs.set({ updateChannel: value });
|
||||
logger.info(`updater: channel → ${value}`);
|
||||
if (downloading) downloading.token.cancel();
|
||||
if (busy) await busy;
|
||||
offered = null;
|
||||
downloaded = null;
|
||||
Object.assign(state, { available: null, progress: null, newerWithoutBuild: [], newerPreview: null });
|
||||
if (state.phase !== 'disabled') setPhase('idle');
|
||||
}
|
||||
return check({ manual: true });
|
||||
}
|
||||
|
||||
async function openRelease() {
|
||||
if (!offered) return { ok: false };
|
||||
try {
|
||||
await openExternal(source.releasePageUrl(offered.candidate.tag));
|
||||
return { ok: true };
|
||||
} catch (err) {
|
||||
logger.warn('updater: cannot open release page', err);
|
||||
return { ok: false };
|
||||
}
|
||||
}
|
||||
|
||||
function start() {
|
||||
if (target.mode === 'none') {
|
||||
logger.info(`updater: disabled: ${target.disabledCode}`);
|
||||
return;
|
||||
}
|
||||
timers.push(setTimeout(() => check({ manual: false }), STARTUP_DELAY_MS));
|
||||
timers.push(setInterval(() => check({ manual: false }), CHECK_INTERVAL_MS));
|
||||
}
|
||||
|
||||
function stop() {
|
||||
for (const t of timers) clearTimeout(t);
|
||||
timers = [];
|
||||
clearInterval(deferredTimer);
|
||||
deferredTimer = null;
|
||||
if (downloading) downloading.token.cancel();
|
||||
}
|
||||
|
||||
function registerIpc(ipcMain, trustedSender) {
|
||||
ipcMain.handle('update:get-state', (event) => (trustedSender(event) ? snapshot() : null));
|
||||
ipcMain.handle('update:check', (event) => (trustedSender(event) ? check({ manual: true }) : null));
|
||||
ipcMain.handle('update:download', (event) => (trustedSender(event) ? download({ manual: true }) : null));
|
||||
ipcMain.handle('update:install', (event, options) => {
|
||||
if (!trustedSender(event)) return { ok: false, code: 'forbidden' };
|
||||
if (options !== undefined && (options === null || typeof options !== 'object' || Array.isArray(options))) {
|
||||
return { ok: false, code: 'bad-request' };
|
||||
}
|
||||
return install(options);
|
||||
});
|
||||
ipcMain.handle('update:open-release', (event) => (trustedSender(event) ? openRelease() : { ok: false }));
|
||||
ipcMain.handle('update:set-channel', (event, value) => (trustedSender(event) && typeof value === 'string' ? setChannel(value) : null));
|
||||
}
|
||||
|
||||
return { start, stop, check, download, install, setChannel, openRelease, getState: snapshot, registerIpc };
|
||||
}
|
||||
|
||||
module.exports = { createUpdateService, createElectronUpdater: defaultCreateUpdater };
|
||||
@@ -29,5 +29,12 @@ contextBridge.exposeInMainWorld('teamspeach', {
|
||||
fetchExternalMedia: (url) => ipcRenderer.invoke('media:external', url),
|
||||
getVideoStatus: () => ipcRenderer.invoke('app:video-status'),
|
||||
relaunch: () => ipcRenderer.invoke('app:relaunch'),
|
||||
getUpdateState: () => ipcRenderer.invoke('update:get-state'),
|
||||
checkForUpdates: () => ipcRenderer.invoke('update:check'),
|
||||
downloadUpdate: () => ipcRenderer.invoke('update:download'),
|
||||
installUpdate: (confirmInterrupt) => ipcRenderer.invoke('update:install', { confirmInterrupt: confirmInterrupt === true }),
|
||||
openUpdateRelease: () => ipcRenderer.invoke('update:open-release'),
|
||||
setUpdateChannel: (channel) => ipcRenderer.invoke('update:set-channel', channel),
|
||||
onUpdateState: (callback) => subscribe('update:state', callback),
|
||||
log: (level, message) => ipcRenderer.send('app:log', level, String(message)),
|
||||
});
|
||||
+151
-119
@@ -1,5 +1,5 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<html lang="en">
|
||||
<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: blob:; 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'">
|
||||
@@ -42,19 +42,19 @@
|
||||
|
||||
<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>
|
||||
<p id="boot-text" data-i18n="ui.starting.core">Starting core…</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>
|
||||
<h1 id="fatal-title" data-i18n="ui.core.unavailable">Core unavailable</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>
|
||||
<button id="fatal-retry" class="btn btn-primary" type="button" data-i18n="ui.restart.core">Restart core</button>
|
||||
<button id="fatal-import" class="btn" type="button" hidden data-i18n="ui.import.backup">Import backup…</button>
|
||||
<button id="fatal-logs" class="btn" type="button" data-i18n="ui.open.logs">Open logs</button>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
@@ -62,63 +62,63 @@
|
||||
<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>
|
||||
<h1 data-i18n="ui.what.should.we.call.you">What should we call you?</h1>
|
||||
<p class="lede" data-i18n="ui.everyone.on.the.server.sees.your.nickname">Everyone on the server sees your nickname. You can change it later without changing your permanent identifier (UID).</p>
|
||||
<label class="field">
|
||||
<span class="field-label">Никнейм</span>
|
||||
<span class="field-label" data-i18n="ui.nickname">Nickname</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-hint" class="hint" data-i18n="ui.3.30.characters">3–30 characters.</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>
|
||||
<button id="onboarding-submit" class="btn btn-primary btn-wide" type="submit" data-i18n="ui.continue">Continue</button>
|
||||
<p class="hint" data-i18n="ui.teamspeach.will.create.a.cryptographic.identity.on">TeamsPeach will create a cryptographic identity on this computer. No registration required.</p>
|
||||
<button id="onboarding-import" class="btn btn-ghost" type="button" data-i18n="ui.restore.from.backup">Restore from backup…</button>
|
||||
</form>
|
||||
</main>
|
||||
|
||||
<div id="view-app" class="shell" hidden>
|
||||
<aside class="sidebar" aria-label="Сервер">
|
||||
<aside class="sidebar" aria-label="Server" data-i18n-aria-label="ui.server">
|
||||
<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>
|
||||
<span id="server-name" class="server-name" data-i18n="ui.not.connected">Not connected</span>
|
||||
<span id="conn-badge" class="conn-badge" data-state="disconnected" data-i18n="ui.not.connected2">not connected</span>
|
||||
</div>
|
||||
<button id="btn-servers" class="icon-btn" type="button" aria-expanded="false" aria-controls="servers-panel" aria-label="Сохранённые серверы" title="Сохранённые серверы">
|
||||
<button id="btn-servers" class="icon-btn" type="button" aria-expanded="false" aria-controls="servers-panel" aria-label="Saved servers" data-i18n-aria-label="ui.saved.servers" title="Saved servers" data-i18n-title="ui.saved.servers">
|
||||
<svg class="icon" aria-hidden="true"><use href="#i-bookmark"/></svg>
|
||||
</button>
|
||||
<button id="btn-disconnect" class="icon-btn" type="button" aria-label="Отключиться от сервера" title="Отключиться" hidden>
|
||||
<button id="btn-disconnect" class="icon-btn" type="button" aria-label="Disconnect from server" data-i18n-aria-label="ui.disconnect.from.server" title="Disconnect" data-i18n-title="ui.disconnect" hidden>
|
||||
<svg class="icon" aria-hidden="true"><use href="#i-logout"/></svg>
|
||||
</button>
|
||||
</header>
|
||||
<div id="room-side" class="room-side">
|
||||
<section id="servers-panel" class="servers-panel" aria-labelledby="servers-title" hidden>
|
||||
<div class="servers-head">
|
||||
<h2 id="servers-title" class="servers-title">Сохранённые серверы</h2>
|
||||
<button id="servers-save-current" class="btn btn-ghost btn-small" type="button" hidden>Сохранить текущий</button>
|
||||
<h2 id="servers-title" class="servers-title" data-i18n="ui.saved.servers">Saved servers</h2>
|
||||
<button id="servers-save-current" class="btn btn-ghost btn-small" type="button" hidden data-i18n="ui.save.current.server">Save current server</button>
|
||||
</div>
|
||||
<ul id="servers-list" class="servers-list"></ul>
|
||||
<p id="servers-empty" class="servers-empty">Сохранённых серверов нет. Введите адрес в форме подключения и нажмите «Сохранить».</p>
|
||||
<p id="servers-empty" class="servers-empty" data-i18n="ui.no.saved.servers.enter.an.address.in">No saved servers. Enter an address in the connection form and select Save.</p>
|
||||
</section>
|
||||
<p id="tree-empty" class="tree-empty">Каналы появятся после подключения к серверу.</p>
|
||||
<p id="tree-empty" class="tree-empty" data-i18n="ui.channels.will.appear.after.you.connect.to">Channels will appear after you connect to a server.</p>
|
||||
<img id="host-banner" class="host-banner" alt="" hidden>
|
||||
<ul id="tree" class="tree" aria-label="Каналы и участники"></ul>
|
||||
<ul id="tree" class="tree" aria-label="Channels and members" data-i18n-aria-label="ui.channels.and.members"></ul>
|
||||
</div>
|
||||
<nav id="settings-nav" class="settings-nav" aria-label="Разделы настроек" hidden>
|
||||
<nav id="settings-nav" class="settings-nav" aria-label="Settings categories" data-i18n-aria-label="ui.settings.categories" hidden>
|
||||
<button id="settings-back" class="settings-back" type="button">
|
||||
<svg class="icon" aria-hidden="true"><use href="#i-back"/></svg>Назад к серверу
|
||||
<svg class="icon" aria-hidden="true"><use href="#i-back"/></svg><span data-i18n="ui.back.to.server">Back to server</span>
|
||||
</button>
|
||||
<div class="settings-nav-title"><svg class="icon" aria-hidden="true"><use href="#i-sliders"/></svg>Настройки</div>
|
||||
<div class="nav-group-label">Пользователь</div>
|
||||
<button class="nav-item" type="button" data-panel="identity"><svg class="icon" aria-hidden="true"><use href="#i-user"/></svg>Идентичность</button>
|
||||
<button class="nav-item" type="button" data-panel="servers"><svg class="icon" aria-hidden="true"><use href="#i-bookmark"/></svg>Серверы</button>
|
||||
<div class="nav-group-label">Приложение</div>
|
||||
<button class="nav-item" type="button" data-panel="appearance"><svg class="icon" aria-hidden="true"><use href="#i-palette"/></svg>Внешний вид</button>
|
||||
<button class="nav-item" type="button" data-panel="audio"><svg class="icon" aria-hidden="true"><use href="#i-speaker"/></svg>Звук</button>
|
||||
<button class="nav-item" type="button" data-panel="video"><svg class="icon" aria-hidden="true"><use href="#i-monitor"/></svg>Видео</button>
|
||||
<button class="nav-item" type="button" data-panel="keys"><svg class="icon" aria-hidden="true"><use href="#i-keyboard"/></svg>Клавиши</button>
|
||||
<div class="nav-group-label">Информация</div>
|
||||
<button class="nav-item" type="button" data-panel="about"><svg class="icon" aria-hidden="true"><use href="#i-info"/></svg>Информация</button>
|
||||
<div class="settings-nav-title"><svg class="icon" aria-hidden="true"><use href="#i-sliders"/></svg><span data-i18n="ui.settings">Settings</span></div>
|
||||
<div class="nav-group-label" data-i18n="ui.user">User</div>
|
||||
<button class="nav-item" type="button" data-panel="identity"><svg class="icon" aria-hidden="true"><use href="#i-user"/></svg><span data-i18n="ui.identity">Identity</span></button>
|
||||
<button class="nav-item" type="button" data-panel="servers"><svg class="icon" aria-hidden="true"><use href="#i-bookmark"/></svg><span data-i18n="ui.servers">Servers</span></button>
|
||||
<div class="nav-group-label" data-i18n="ui.application">Application</div>
|
||||
<button class="nav-item" type="button" data-panel="appearance"><svg class="icon" aria-hidden="true"><use href="#i-palette"/></svg><span data-i18n="ui.appearance">Appearance</span></button>
|
||||
<button class="nav-item" type="button" data-panel="audio"><svg class="icon" aria-hidden="true"><use href="#i-speaker"/></svg><span data-i18n="ui.audio">Audio</span></button>
|
||||
<button class="nav-item" type="button" data-panel="video"><svg class="icon" aria-hidden="true"><use href="#i-monitor"/></svg><span data-i18n="ui.video">Video</span></button>
|
||||
<button class="nav-item" type="button" data-panel="keys"><svg class="icon" aria-hidden="true"><use href="#i-keyboard"/></svg><span data-i18n="ui.keyboard">Keyboard</span></button>
|
||||
<div class="nav-group-label" data-i18n="ui.information">Information</div>
|
||||
<button class="nav-item" type="button" data-panel="about"><svg class="icon" aria-hidden="true"><use href="#i-info"/></svg><span data-i18n="ui.information">Information</span></button>
|
||||
</nav>
|
||||
<footer class="self">
|
||||
<div class="self-id">
|
||||
@@ -129,13 +129,13 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="self-actions">
|
||||
<button id="btn-mute" class="icon-btn" type="button" aria-pressed="false" aria-label="Микрофон" title="Выключить микрофон">
|
||||
<button id="btn-mute" class="icon-btn" type="button" aria-pressed="false" aria-label="Microphone" data-i18n-aria-label="ui.microphone" title="Mute microphone" data-i18n-title="ui.mute.microphone">
|
||||
<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="Выключить звук">
|
||||
<button id="btn-deafen" class="icon-btn" type="button" aria-pressed="false" aria-label="Audio" data-i18n-aria-label="ui.audio" title="Mute audio" data-i18n-title="ui.mute.audio">
|
||||
<svg class="icon" aria-hidden="true"><use href="#i-headphones"/></svg>
|
||||
</button>
|
||||
<button id="btn-settings" class="icon-btn" type="button" aria-label="Настройки" title="Настройки">
|
||||
<button id="btn-settings" class="icon-btn" type="button" aria-label="Settings" data-i18n-aria-label="ui.settings" title="Settings" data-i18n-title="ui.settings">
|
||||
<svg class="icon" aria-hidden="true"><use href="#i-sliders"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
@@ -145,20 +145,20 @@
|
||||
<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>
|
||||
<h1 id="connect-title" data-i18n="ui.connect.to.a.server">Connect to a server</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>
|
||||
<span class="field-label" data-i18n="ui.server.address">Server address</span>
|
||||
<input id="connect-address" name="address" type="text" autocomplete="off" spellcheck="false" placeholder="address or address:9987" data-i18n-placeholder="ui.address.or.address.9987" required>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Пароль сервера <span class="optional">необязательно</span></span>
|
||||
<span class="field-label"><span data-i18n="ui.server.password">Server password</span> <span class="optional" data-i18n="ui.optional">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>
|
||||
<button id="connect-save" class="btn" type="button">Сохранить</button>
|
||||
<button id="connect-submit" class="btn btn-primary" type="submit" data-i18n="ui.connect">Connect</button>
|
||||
<button id="connect-save" class="btn" type="button" data-i18n="ui.save">Save</button>
|
||||
<span id="connect-status" class="form-status" role="status"></span>
|
||||
</div>
|
||||
</form>
|
||||
@@ -172,12 +172,12 @@
|
||||
</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>
|
||||
<button id="btn-ptt" class="btn btn-ptt" type="button" aria-pressed="false" data-i18n="ui.hold.to.talk">Hold to talk</button>
|
||||
</div>
|
||||
</header>
|
||||
<p id="session-notice" class="notice" role="status" hidden></p>
|
||||
|
||||
<section id="stream-view" class="stream-view" aria-label="Трансляция" hidden>
|
||||
<section id="stream-view" class="stream-view" aria-label="Stream" data-i18n-aria-label="ui.stream" hidden>
|
||||
<div class="stream-stage">
|
||||
<video id="stream-video" autoplay playsinline></video>
|
||||
<div id="stream-overlay" class="stream-overlay" role="status"></div>
|
||||
@@ -188,178 +188,210 @@
|
||||
<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="Выключить звук трансляции">
|
||||
<button id="stream-mute" class="icon-btn" type="button" aria-pressed="false" aria-label="Stream audio" data-i18n-aria-label="ui.stream.audio" title="Mute stream" data-i18n-title="ui.mute.stream">
|
||||
<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="Громкость трансляции">
|
||||
<input id="stream-volume" class="range" type="range" min="0" max="100" step="1" aria-label="Stream volume" data-i18n-aria-label="ui.stream.volume">
|
||||
<output id="stream-volume-value" class="range-value" for="stream-volume"></output>
|
||||
<button id="stream-fullscreen" class="icon-btn" type="button" aria-label="Во весь экран" title="Во весь экран">
|
||||
<button id="stream-fullscreen" class="icon-btn" type="button" aria-label="Full screen" data-i18n-aria-label="ui.full.screen" title="Full screen" data-i18n-title="ui.full.screen">
|
||||
<svg class="icon" aria-hidden="true"><use href="#i-fullscreen"/></svg>
|
||||
</button>
|
||||
<button id="stream-stop" class="btn" type="button">Прекратить просмотр</button>
|
||||
<button id="stream-stop" class="btn" type="button" data-i18n="ui.stop.watching">Stop watching</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="chat" aria-label="Чат">
|
||||
<div id="chat-tabs" class="chat-tabs" role="tablist" aria-label="Чаты"></div>
|
||||
<section class="chat" aria-label="Chat" data-i18n-aria-label="ui.chat">
|
||||
<div id="chat-tabs" class="chat-tabs" role="tablist" aria-label="Chats" data-i18n-aria-label="ui.chats"></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)">
|
||||
<textarea id="chat-input" rows="1" aria-label="Message" data-i18n-aria-label="ui.message" placeholder="Message" data-i18n-placeholder="ui.message"></textarea>
|
||||
<button id="chat-send" class="icon-btn icon-btn-accent" type="submit" aria-label="Send" data-i18n-aria-label="ui.send" title="Send (Enter)" data-i18n-title="ui.send.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-label="Настройки">
|
||||
<section id="settings-view" class="settings-view" hidden aria-label="Settings" data-i18n-aria-label="ui.settings">
|
||||
<div class="settings-scroll">
|
||||
<div class="settings-panel" data-panel="identity" hidden>
|
||||
<h1 id="settings-title" class="panel-title">Идентичность</h1>
|
||||
<h1 id="settings-title" class="panel-title" data-i18n="ui.identity">Identity</h1>
|
||||
<section class="card" aria-labelledby="card-identity">
|
||||
<h2 id="card-identity" class="card-title">Идентичность</h2>
|
||||
<h2 id="card-identity" class="card-title" data-i18n="ui.identity">Identity</h2>
|
||||
<div class="card-row">
|
||||
<span class="row-name">Уникальный идентификатор</span>
|
||||
<span class="row-name" data-i18n="ui.unique.identifier">Unique identifier</span>
|
||||
<code id="uid-value" class="uid-value"></code>
|
||||
<button id="uid-copy" class="btn btn-ghost btn-small" type="button"><svg class="icon" aria-hidden="true"><use href="#i-copy"/></svg>Копировать</button>
|
||||
<button id="uid-copy" class="btn btn-ghost btn-small" type="button"><svg class="icon" aria-hidden="true"><use href="#i-copy"/></svg><span data-i18n="ui.copy">Copy</span></button>
|
||||
</div>
|
||||
<p class="hint">UID — отпечаток вашего открытого ключа. Серверы TeamSpeak по нему узнают вас и выдают права; смена ника его не меняет.</p>
|
||||
<p class="hint" data-i18n="ui.your.uid.is.your.public.key.fingerprint">Your UID is your public key fingerprint. TeamSpeak servers use it to recognize you and assign permissions; changing your nickname does not change it.</p>
|
||||
<p id="security-level" class="hint"></p>
|
||||
<div class="card-divider"></div>
|
||||
<div class="form-actions">
|
||||
<button id="identity-export" class="btn" type="button">Экспортировать в файл…</button>
|
||||
<button id="identity-import" class="btn" type="button">Импортировать из файла…</button>
|
||||
<button id="identity-export" class="btn" type="button" data-i18n="ui.export.to.file">Export to file…</button>
|
||||
<button id="identity-import" class="btn" type="button" data-i18n="ui.import.from.file">Import from file…</button>
|
||||
</div>
|
||||
<p class="hint">Файл содержит закрытый ключ. Храните его как пароль: тот, у кого он есть, может выдавать себя за вас.</p>
|
||||
<p class="hint" data-i18n="ui.the.file.contains.your.private.key.protect">The file contains your private key. Protect it like a password: anyone with it can impersonate you.</p>
|
||||
<p id="identity-status" class="form-status" role="status"></p>
|
||||
</section>
|
||||
<section class="card" aria-labelledby="card-details">
|
||||
<h2 id="card-details" class="card-title">Подробнее</h2>
|
||||
<h2 id="card-details" class="card-title" data-i18n="ui.details">Details</h2>
|
||||
<form id="rename-form" class="inline-form" novalidate>
|
||||
<label class="inline-label" for="rename-input">Ник</label>
|
||||
<label class="inline-label" for="rename-input" data-i18n="ui.nickname2">Nickname</label>
|
||||
<input id="rename-input" type="text" autocomplete="off" spellcheck="false" maxlength="30">
|
||||
<button id="rename-submit" class="btn btn-primary btn-small" type="submit">Сохранить</button>
|
||||
<button id="rename-submit" class="btn btn-primary btn-small" type="submit" data-i18n="ui.save">Save</button>
|
||||
</form>
|
||||
<p class="hint">Ваш ник видят другие пользователи на сервере TeamSpeak. От 3 до 30 символов.</p>
|
||||
<p class="hint" data-i18n="ui.other.users.on.the.teamspeak.server.see">Other users on the TeamSpeak server see your nickname. 3–30 characters.</p>
|
||||
<p id="rename-status" class="form-status" role="status"></p>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="settings-panel" data-panel="servers" hidden>
|
||||
<h1 class="panel-title">Серверы</h1>
|
||||
<h1 class="panel-title" data-i18n="ui.servers">Servers</h1>
|
||||
<section class="card" aria-labelledby="card-saved">
|
||||
<h2 id="card-saved" class="card-title">Сохранённые серверы</h2>
|
||||
<h2 id="card-saved" class="card-title" data-i18n="ui.saved.servers">Saved servers</h2>
|
||||
<ul id="servers-manage" class="servers-list servers-manage"></ul>
|
||||
<p id="servers-manage-empty" class="hint">Сохранённых серверов нет.</p>
|
||||
<p id="servers-manage-empty" class="hint" data-i18n="ui.no.saved.servers">No saved servers.</p>
|
||||
</section>
|
||||
<section class="card" aria-labelledby="card-add-server">
|
||||
<h2 id="card-add-server" class="card-title">Добавить сервер</h2>
|
||||
<h2 id="card-add-server" class="card-title" data-i18n="ui.add.server">Add server</h2>
|
||||
<form id="server-add-form" class="stack-form" novalidate>
|
||||
<label class="field"><span class="field-label">Название</span><input id="server-add-name" type="text" maxlength="64" autocomplete="off"></label>
|
||||
<label class="field"><span class="field-label">Адрес</span><input id="server-add-address" type="text" maxlength="255" autocomplete="off" spellcheck="false" placeholder="адрес или адрес:9987"></label>
|
||||
<div class="form-actions"><button class="btn btn-primary btn-small" type="submit">Добавить</button><span id="server-add-status" class="form-status" role="status"></span></div>
|
||||
<label class="field"><span class="field-label" data-i18n="ui.name">Name</span><input id="server-add-name" type="text" maxlength="64" autocomplete="off"></label>
|
||||
<label class="field"><span class="field-label" data-i18n="ui.address">Address</span><input id="server-add-address" type="text" maxlength="255" autocomplete="off" spellcheck="false" placeholder="address or address:9987" data-i18n-placeholder="ui.address.or.address.9987"></label>
|
||||
<div class="form-actions"><button class="btn btn-primary btn-small" type="submit" data-i18n="ui.add">Add</button><span id="server-add-status" class="form-status" role="status"></span></div>
|
||||
</form>
|
||||
<p class="hint">Сохраняются только название и адрес. Пароль сервера не сохраняется — его спросят при подключении. Для всех серверов используется одна и та же ваша идентичность.</p>
|
||||
<p class="hint" data-i18n="ui.only.the.name.and.address.are.saved">Only the name and address are saved. Server passwords are not stored; you will be asked when connecting. The same identity is used for every server.</p>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="settings-panel" data-panel="appearance" hidden>
|
||||
<h1 class="panel-title">Внешний вид</h1>
|
||||
<h1 class="panel-title" data-i18n="ui.appearance">Appearance</h1>
|
||||
<section class="card" aria-labelledby="card-theme">
|
||||
<h2 id="card-theme" class="card-title">Тема</h2>
|
||||
<h2 id="card-theme" class="card-title" data-i18n="ui.theme">Theme</h2>
|
||||
<fieldset class="fieldset">
|
||||
<legend class="visually-hidden">Тема оформления</legend>
|
||||
<label class="choice"><input type="radio" name="theme" value="system"> Как в системе</label>
|
||||
<label class="choice"><input type="radio" name="theme" value="dark"> Тёмная</label>
|
||||
<label class="choice"><input type="radio" name="theme" value="light"> Светлая</label>
|
||||
<legend class="visually-hidden" data-i18n="ui.color.theme">Color theme</legend>
|
||||
<label class="choice"><input type="radio" name="theme" value="system"> <span data-i18n="ui.system">System</span></label>
|
||||
<label class="choice"><input type="radio" name="theme" value="dark"> <span data-i18n="ui.dark">Dark</span></label>
|
||||
<label class="choice"><input type="radio" name="theme" value="light"> <span data-i18n="ui.light">Light</span></label>
|
||||
</fieldset>
|
||||
</section>
|
||||
<section class="card" aria-labelledby="card-language">
|
||||
<h2 id="card-language" class="card-title" data-i18n="language.label">Language</h2>
|
||||
<label class="field"><span class="field-label" data-i18n="language.label">Language</span>
|
||||
<select id="language-select"><option value="en" lang="en">English</option><option value="ru" lang="ru" data-i18n="language.russian">Russian</option></select>
|
||||
</label>
|
||||
<p class="hint" data-i18n="language.note">Changes apply immediately. Your identity, connection and audio are unchanged.</p>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="settings-panel" data-panel="audio" hidden>
|
||||
<h1 class="panel-title">Звук</h1>
|
||||
<h1 class="panel-title" data-i18n="ui.audio">Audio</h1>
|
||||
<section class="card" aria-labelledby="card-devices">
|
||||
<h2 id="card-devices" class="card-title">Устройства</h2>
|
||||
<label class="field"><span class="field-label">Микрофон</span><select id="input-device"></select></label>
|
||||
<h2 id="card-devices" class="card-title" data-i18n="ui.devices">Devices</h2>
|
||||
<label class="field"><span class="field-label" data-i18n="ui.microphone">Microphone</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 btn-small" type="button" aria-pressed="false">Проверить микрофон</button>
|
||||
<button id="mic-test" class="btn btn-ghost btn-small" type="button" aria-pressed="false" data-i18n="ui.test.microphone">Test microphone</button>
|
||||
</div>
|
||||
<label class="field"><span class="field-label">Устройство вывода</span><select id="output-device"></select></label>
|
||||
<label class="field"><span class="field-label" data-i18n="ui.output.device">Output device</span><select id="output-device"></select></label>
|
||||
<p id="device-status" class="hint" role="status"></p>
|
||||
</section>
|
||||
<section class="card" aria-labelledby="card-volume">
|
||||
<h2 id="card-volume" class="card-title">Громкость</h2>
|
||||
<label class="field"><span class="field-label">Громкость голосов <output id="voice-volume-value" for="voice-volume"></output></span>
|
||||
<h2 id="card-volume" class="card-title" data-i18n="ui.volume">Volume</h2>
|
||||
<label class="field"><span class="field-label"><span data-i18n="ui.voice.volume">Voice volume</span> <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>
|
||||
</section>
|
||||
<section class="card" aria-labelledby="card-processing">
|
||||
<h2 id="card-processing" class="card-title">Обработка микрофона</h2>
|
||||
<h2 id="card-processing" class="card-title" data-i18n="ui.microphone.processing">Microphone processing</h2>
|
||||
<fieldset class="fieldset">
|
||||
<legend class="visually-hidden">Обработка микрофона</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>
|
||||
<legend class="visually-hidden" data-i18n="ui.microphone.processing">Microphone processing</legend>
|
||||
<label class="choice"><input id="opt-ns" type="checkbox"> <span data-i18n="ui.noise.suppression">Noise suppression</span></label>
|
||||
<label class="choice"><input id="opt-ec" type="checkbox"> <span data-i18n="ui.echo.cancellation">Echo cancellation</span></label>
|
||||
<label class="choice"><input id="opt-agc" type="checkbox"> <span data-i18n="ui.automatic.gain.control">Automatic gain control</span></label>
|
||||
</fieldset>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="settings-panel" data-panel="video" hidden>
|
||||
<h1 class="panel-title">Видео</h1>
|
||||
<h1 class="panel-title" data-i18n="ui.video">Video</h1>
|
||||
<section class="card" aria-labelledby="card-decode">
|
||||
<h2 id="card-decode" class="card-title">Аппаратное ускорение</h2>
|
||||
<label class="choice"><input id="opt-hwdec" type="checkbox"> Разрешить аппаратное декодирование видео</label>
|
||||
<p class="hint">Движок может использовать видеокарту для декодирования трансляций. Применяется после перезапуска.</p>
|
||||
<h2 id="card-decode" class="card-title" data-i18n="ui.hardware.acceleration">Hardware acceleration</h2>
|
||||
<label class="choice"><input id="opt-hwdec" type="checkbox"> <span data-i18n="ui.allow.hardware.video.decoding">Allow hardware video decoding</span></label>
|
||||
<p class="hint" data-i18n="ui.the.engine.may.use.your.gpu.to">The engine may use your GPU to decode streams. Applies after restarting.</p>
|
||||
<div id="hwdec-restart" class="form-actions" hidden>
|
||||
<span class="form-status">Изменение вступит в силу после перезапуска TeamsPeach.</span>
|
||||
<button id="hwdec-relaunch" class="btn btn-small" type="button">Перезапустить сейчас</button>
|
||||
<span class="form-status" data-i18n="ui.this.change.takes.effect.after.restarting.teamspeach">This change takes effect after restarting TeamsPeach.</span>
|
||||
<button id="hwdec-relaunch" class="btn btn-small" type="button" data-i18n="ui.restart.now">Restart now</button>
|
||||
</div>
|
||||
<div class="card-divider"></div>
|
||||
<div class="card-row">
|
||||
<span class="row-name">Бэкенд декодирования</span>
|
||||
<span class="row-value">Автоматически (выбирает Chromium)</span>
|
||||
<span class="row-name" data-i18n="ui.decoding.backend">Decoding backend</span>
|
||||
<span class="row-value" data-i18n="ui.automatic.chosen.by.chromium">Automatic (chosen by Chromium)</span>
|
||||
</div>
|
||||
<details class="card-details">
|
||||
<summary>Подробности: состояние, кодеки и бэкенды</summary>
|
||||
<summary data-i18n="ui.details.status.codecs.and.backends">Details: status, codecs and backends</summary>
|
||||
<dl class="diag-list">
|
||||
<dt>Политика</dt><dd id="hwdec-status"></dd>
|
||||
<dt>Текущий приём</dt><dd id="decoder-last"></dd>
|
||||
<dt data-i18n="ui.policy">Policy</dt><dd id="hwdec-status"></dd>
|
||||
<dt data-i18n="ui.current.reception">Current reception</dt><dd id="decoder-last"></dd>
|
||||
</dl>
|
||||
<h3 class="details-title">Кодеки приёма, объявленные движком</h3>
|
||||
<h3 class="details-title" data-i18n="ui.receive.codecs.reported.by.the.engine">Receive codecs reported by the engine</h3>
|
||||
<ul id="codec-list" class="codec-list"></ul>
|
||||
<h3 class="details-title">Недоступные настройки</h3>
|
||||
<p class="hint">Переключателя Cisco OpenH264 и ручного выбора аппаратных бэкендов (NVENC, AMF, QSV и др.), как в TeamSpeak 6, здесь нет: TeamsPeach принимает видео через WebRTC движка Chromium, у которого нет API выбора декодера. H.264 Chromium декодирует через FFmpeg — OpenH264 в нём служит только кодировщиком, а кодирование (отправка своего экрана) в TeamsPeach не реализовано.</p>
|
||||
<h3 class="details-title" data-i18n="ui.unavailable.settings">Unavailable settings</h3>
|
||||
<p class="hint" data-i18n="ui.unlike.teamspeak.6.there.is.no.cisco">Unlike TeamSpeak 6, there is no Cisco OpenH264 toggle or manual hardware backend selection (NVENC, AMF, QSV, etc.). TeamsPeach receives video through Chromium WebRTC, which has no decoder-selection API. Chromium decodes H.264 through FFmpeg; OpenH264 is only an encoder, and sending your own screen is not implemented in TeamsPeach.</p>
|
||||
</details>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="settings-panel" data-panel="keys" hidden>
|
||||
<h1 class="panel-title">Клавиши</h1>
|
||||
<h1 class="panel-title" data-i18n="ui.keyboard">Keyboard</h1>
|
||||
<section class="card" aria-labelledby="card-transmit">
|
||||
<h2 id="card-transmit" class="card-title">Передача голоса</h2>
|
||||
<h2 id="card-transmit" class="card-title" data-i18n="ui.voice.transmission">Voice transmission</h2>
|
||||
<fieldset class="fieldset">
|
||||
<legend class="visually-hidden">Режим передачи</legend>
|
||||
<label class="choice"><input type="radio" name="transmit" value="ptt"> Нажми и говори</label>
|
||||
<label class="choice"><input type="radio" name="transmit" value="open"> Открытый микрофон</label>
|
||||
<legend class="visually-hidden" data-i18n="ui.transmission.mode">Transmission mode</legend>
|
||||
<label class="choice"><input type="radio" name="transmit" value="ptt"> <span data-i18n="ui.push.to.talk">Push to talk</span></label>
|
||||
<label class="choice"><input type="radio" name="transmit" value="open"> <span data-i18n="ui.open.microphone">Open microphone</span></label>
|
||||
</fieldset>
|
||||
<div class="card-divider"></div>
|
||||
<div class="ptt-row">
|
||||
<span class="row-name">Клавиша «нажми и говори»</span>
|
||||
<span class="row-name" data-i18n="ui.push.to.talk.key">Push-to-talk key</span>
|
||||
<kbd id="ptt-key" class="kbd"></kbd>
|
||||
<button id="ptt-assign" class="btn btn-ghost btn-small" type="button">Назначить</button>
|
||||
<button id="ptt-assign" class="btn btn-ghost btn-small" type="button" data-i18n="ui.assign">Assign</button>
|
||||
</div>
|
||||
<p id="ptt-hint" class="hint">Клавиша работает, пока окно TeamsPeach активно. Буквенные клавиши не срабатывают во время набора текста. Esc отменяет назначение.</p>
|
||||
<p id="ptt-hint" class="hint" data-i18n="ui.the.key.works.while.teamspeach.is.focused">The key works while TeamsPeach is focused. Letter keys do not trigger while typing. Press Esc to cancel assignment.</p>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="settings-panel" data-panel="about" hidden>
|
||||
<h1 class="panel-title">Информация</h1>
|
||||
<h1 class="panel-title" data-i18n="ui.information">Information</h1>
|
||||
<section class="card" aria-labelledby="card-about">
|
||||
<h2 id="card-about" class="card-title">О программе</h2>
|
||||
<h2 id="card-about" class="card-title" data-i18n="ui.about">About</h2>
|
||||
<dl id="diag-list" class="diag-list"></dl>
|
||||
<div class="card-divider"></div>
|
||||
<div class="form-actions"><button id="open-logs" class="btn btn-small" type="button">Открыть журналы</button></div>
|
||||
<div class="form-actions"><button id="open-logs" class="btn btn-small" type="button" data-i18n="ui.open.logs">Open logs</button></div>
|
||||
</section>
|
||||
<section class="card" aria-labelledby="card-updates">
|
||||
<h2 id="card-updates" class="card-title" data-i18n="ui.updates">Updates</h2>
|
||||
<label class="field"><span class="field-label" data-i18n="ui.update.channel">Update channel</span>
|
||||
<select id="update-channel">
|
||||
<option value="preview" data-i18n="ui.preview.releases">Preview releases</option>
|
||||
<option value="stable" data-i18n="ui.stable.only">Stable only</option>
|
||||
</select>
|
||||
</label>
|
||||
<p class="hint" data-i18n="update.channel.hint">Preview includes prereleases; Stable excludes them.</p>
|
||||
<p id="update-status" class="update-status" role="status"></p>
|
||||
<progress id="update-progress" class="update-progress" max="100" hidden></progress>
|
||||
<div id="update-confirm" class="update-confirm" hidden>
|
||||
<p class="hint" data-i18n="ui.installing.closes.teamspeach.and.interrupts.your.current">Installing closes TeamsPeach and interrupts your current call and stream.</p>
|
||||
<div class="form-actions">
|
||||
<button id="update-confirm-yes" class="btn btn-primary btn-small" type="button" data-i18n="ui.interrupt.and.install">Interrupt and install</button>
|
||||
<button id="update-confirm-no" class="btn btn-ghost btn-small" type="button" data-i18n="ui.cancel">Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-actions">
|
||||
<button id="update-check" class="btn btn-small" type="button" data-i18n="ui.check.for.updates">Check for updates</button>
|
||||
<button id="update-download" class="btn btn-small" type="button" hidden data-i18n="ui.download">Download</button>
|
||||
<button id="update-install" class="btn btn-primary btn-small" type="button" hidden data-i18n="ui.install.and.restart">Install and restart</button>
|
||||
<button id="update-open" class="btn btn-small" type="button" hidden data-i18n="ui.open.release.page">Open release page</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+75
-54
@@ -1,3 +1,4 @@
|
||||
import { t, setLanguage, onLanguageChange } from './i18n.js';
|
||||
// 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';
|
||||
@@ -12,6 +13,7 @@ import * as settings from './settings.js';
|
||||
import { serverBannerUrl, clearMedia } from './media.js';
|
||||
import * as servers from './servers.js';
|
||||
import { initDeviceMenus } from './device-menu.js';
|
||||
import { initUpdates } from './updates-ui.js';
|
||||
|
||||
let hostBannerKey = null;
|
||||
|
||||
@@ -28,7 +30,7 @@ function renderHostBanner() {
|
||||
serverBannerUrl(server).then((url) => {
|
||||
if (!url || hostBannerKey !== key) return;
|
||||
img.src = url;
|
||||
img.alt = server.hostbanner_url ? `Баннер сервера (${server.hostbanner_url})` : 'Баннер сервера';
|
||||
img.alt = server.hostbanner_url ? t('message.server.banner.p0', { p0: server.hostbanner_url }) : t('ui.server.banner');
|
||||
img.hidden = false;
|
||||
});
|
||||
}
|
||||
@@ -47,9 +49,11 @@ function showView(id) {
|
||||
async function savePrefs(partial) {
|
||||
const r = await tp.setPrefs(partial);
|
||||
if (r && r.ok) S.prefs = r.prefs;
|
||||
else toast(`Настройка не сохранена: ${r?.message ?? 'ошибка'}`, 'error');
|
||||
else toast(() => t('message.setting.not.saved.p0', { p0: r?.message ?? t('ui.error') }), 'error');
|
||||
if (!Object.hasOwn(partial, 'language')) {
|
||||
renderSessionHead();
|
||||
servers.renderServers();
|
||||
}
|
||||
return S.prefs;
|
||||
}
|
||||
|
||||
@@ -59,11 +63,11 @@ function onCoreStatus(status) {
|
||||
S.core = status;
|
||||
switch (status.status) {
|
||||
case 'starting':
|
||||
setText($('#boot-text'), 'Запуск ядра…');
|
||||
setText($('#boot-text'), () => t('ui.starting.core'));
|
||||
showView('#boot');
|
||||
break;
|
||||
case 'stopped':
|
||||
setText($('#boot-text'), 'Перезапуск ядра…');
|
||||
setText($('#boot-text'), () => t('ui.restarting.core'));
|
||||
showView('#boot');
|
||||
resetConnection(null);
|
||||
break;
|
||||
@@ -71,17 +75,25 @@ function onCoreStatus(status) {
|
||||
loadProfile();
|
||||
break;
|
||||
case 'missing':
|
||||
showFatal('Ядро TeamsPeach не найдено', 'Исполняемый файл ядра отсутствует. Соберите его (см. README) или переустановите приложение. Проверенные пути:', status.candidates ?? []);
|
||||
showFatal(t('ui.teamspeach.core.not.found'), t('ui.the.core.executable.is.missing.build.it'), status.candidates ?? []);
|
||||
break;
|
||||
default:
|
||||
resetConnection(null);
|
||||
showFatal('Ядро остановилось', status.message || `Код завершения ${status.code}`, []);
|
||||
showFatal(t('ui.the.core.stopped'), coreStatusText(status), []);
|
||||
}
|
||||
}
|
||||
|
||||
function coreStatusText(status) {
|
||||
if (status.reason === 'ready_timeout') return t('core.status.readyTimeout');
|
||||
if (status.reason === 'protocol') return t('core.status.protocol', { protocol: status.protocol });
|
||||
if (status.reason === 'spawn') return `${t('ui.the.core.stopped')}: ${status.message}`;
|
||||
const code = status.code ?? 'unknown';
|
||||
return [0, 1, 2, 3].includes(code) ? t(`core.exit.${code}`) : t('core.exit.other', { code });
|
||||
}
|
||||
|
||||
function showFatal(title, text, list, { allowImport = false } = {}) {
|
||||
setText($('#fatal-title'), title);
|
||||
setText($('#fatal-text'), text);
|
||||
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';
|
||||
@@ -93,9 +105,9 @@ async function loadProfile() {
|
||||
S.profile = await call('profile_get');
|
||||
} catch (err) {
|
||||
if (err.code === 'identity_corrupt' || err.code === 'profile_corrupt') {
|
||||
showFatal('Профиль повреждён', `${errorText(err)} TeamsPeach никогда не создаёт новую идентичность поверх повреждённой.`, [], { allowImport: true });
|
||||
showFatal(t('ui.profile.corrupted'), t('message.p0.teamspeach.never.replaces.a.corrupted', { p0: errorText(err) }), [], { allowImport: true });
|
||||
} else {
|
||||
showFatal('Не удалось прочитать профиль', errorText(err), []);
|
||||
showFatal(t('ui.could.not.read.profile'), errorText(err), []);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -108,7 +120,7 @@ async function loadProfile() {
|
||||
function showOnboarding() {
|
||||
const existing = $('#onboarding-existing');
|
||||
existing.hidden = !S.profile.exists;
|
||||
setText(existing, S.profile.exists ? `Идентичность уже есть (UID ${S.profile.uid}). Осталось выбрать никнейм.` : '');
|
||||
setText(existing, () => S.profile.exists ? t('message.an.identity.already.exists.uid.p0', { p0: S.profile.uid }) : '');
|
||||
showView('#view-onboarding');
|
||||
$('#onboarding-nick').focus();
|
||||
}
|
||||
@@ -121,24 +133,24 @@ async function submitOnboarding(e) {
|
||||
const len = [...nickname].length;
|
||||
if (len < 3 || len > 30) {
|
||||
input.setAttribute('aria-invalid', 'true');
|
||||
setText(error, 'Никнейм должен содержать от 3 до 30 символов.');
|
||||
setText(error, () => t('ui.nickname.must.contain.3.30.characters'));
|
||||
input.focus();
|
||||
return;
|
||||
}
|
||||
input.removeAttribute('aria-invalid');
|
||||
setText(error, '');
|
||||
setText(error, () => '');
|
||||
const submit = $('#onboarding-submit');
|
||||
submit.disabled = true;
|
||||
setText(submit, 'Создаём идентичность…');
|
||||
setText(submit, () => t('ui.creating.identity'));
|
||||
try {
|
||||
S.profile = S.profile.exists ? await call('rename', { nickname }) : await call('profile_create', { nickname });
|
||||
showApp();
|
||||
toast(`Профиль создан. Ваш UID: ${S.profile.uid}`);
|
||||
toast(() => t('message.profile.created.your.uid.p0', { p0: S.profile.uid }));
|
||||
} catch (err) {
|
||||
setText(error, errorText(err));
|
||||
setText(error, () => errorText(err));
|
||||
} finally {
|
||||
submit.disabled = false;
|
||||
setText(submit, 'Продолжить');
|
||||
setText(submit, () => t('ui.continue'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,9 +177,9 @@ 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 : 'Нет подключения');
|
||||
const labels = { connecting: 'ui.connecting', connected: 'ui.connected', disconnecting: 'ui.disconnecting', disconnected: 'ui.not.connected2' };
|
||||
setText(badge, () => labels[state] ? t(labels[state]) : state);
|
||||
setText($('#server-name'), () => isConnected() ? S.snap.server.name || S.conn.address : S.conn.address && state !== 'disconnected' ? S.conn.address : t('ui.not.connected'));
|
||||
$('#btn-disconnect').hidden = state === 'disconnected';
|
||||
|
||||
const inSettings = S.view === 'settings';
|
||||
@@ -180,50 +192,50 @@ function renderConnection() {
|
||||
|
||||
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)}` : '');
|
||||
setText($('#connect-status'), () => state === 'connecting' ? t('ui.connecting2') : '');
|
||||
setText($('#connect-identity'), () => S.profile ? t('message.you.will.join.as.p0.uid', { p0: S.profile.nickname, p1: 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 ?? '');
|
||||
setText($('#self-nick'), () => p.nickname ?? '');
|
||||
const ch = ownChannel();
|
||||
setText($('#self-sub'), isConnected() && ch ? ch.name : `UID ${shortUid(p.uid)}`);
|
||||
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 ? 'Микрофон выключен' : 'Микрофон включён');
|
||||
mute.title = S.audio.input_muted ? t('ui.unmute.microphone') : t('ui.mute.microphone');
|
||||
mute.setAttribute('aria-label', S.audio.input_muted ? t('ui.microphone.muted') : t('ui.microphone.unmuted'));
|
||||
|
||||
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 ? 'Звук выключен' : 'Звук включён');
|
||||
deafen.title = S.audio.output_muted ? t('ui.unmute.audio') : t('ui.mute.audio.and.microphone');
|
||||
deafen.setAttribute('aria-label', S.audio.output_muted ? t('ui.audio.muted') : t('ui.audio.unmuted'));
|
||||
}
|
||||
|
||||
function renderSessionHead() {
|
||||
if (!S.prefs) return;
|
||||
const ch = ownChannel();
|
||||
setText($('#channel-title'), ch ? ch.name : '');
|
||||
setText($('#channel-topic'), ch ? stripBBCode(ch.topic) : '');
|
||||
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());
|
||||
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 = 'Микрофон выключен.';
|
||||
if (codec) text = t('message.this.channel.uses.a.legacy.codec', { p0: codec });
|
||||
else if (S.audio.output_muted) text = t('ui.audio.is.muted.you.cannot.hear.others');
|
||||
else if (S.audio.input_muted) text = t('ui.microphone.is.muted');
|
||||
notice.hidden = !text;
|
||||
setText(notice, text);
|
||||
setText(notice, () => text);
|
||||
}
|
||||
|
||||
// ---------- connection ----------
|
||||
@@ -239,14 +251,14 @@ function isPasswordError(err) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects to `address`. When another server is active, the user chose "Переключиться": the current
|
||||
* Connects to `address`. When another server is active, the user chose "Switch": the current
|
||||
* session is closed cleanly first, so there is never more than one connection.
|
||||
*/
|
||||
async function connectTo(address, { password = '', switching = false } = {}) {
|
||||
const error = $('#connect-error');
|
||||
setText(error, '');
|
||||
setText(error, () => '');
|
||||
if (!address) {
|
||||
setText(error, 'Укажите адрес сервера.');
|
||||
setText(error, () => t('ui.enter.a.server.address'));
|
||||
$('#connect-address').focus();
|
||||
return;
|
||||
}
|
||||
@@ -257,7 +269,7 @@ async function connectTo(address, { password = '', switching = false } = {}) {
|
||||
const deadline = Date.now() + 10000;
|
||||
while (S.conn.state !== 'disconnected' && Date.now() < deadline) await new Promise((r) => setTimeout(r, 100));
|
||||
if (S.conn.state !== 'disconnected') {
|
||||
toast('Не удалось отключиться от текущего сервера', 'error');
|
||||
toast(() => t('ui.could.not.disconnect.from.the.current.server'), 'error');
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -272,7 +284,7 @@ async function connectTo(address, { password = '', switching = false } = {}) {
|
||||
$('#connect-password').value = '';
|
||||
} catch (err) {
|
||||
if (err.code !== 'already_connected') {
|
||||
setText(error, isPasswordError(err) ? `${errorText(err)}. Введите пароль сервера и подключитесь снова.` : errorText(err));
|
||||
setText(error, () => isPasswordError(err) ? t('message.p0.enter.the.server.password.and', { p0: errorText(err) }) : errorText(err));
|
||||
if (S.conn.state === 'connecting') S.conn = { state: 'disconnected', address, reason: null };
|
||||
renderConnection();
|
||||
renderTree();
|
||||
@@ -285,7 +297,7 @@ async function disconnect() {
|
||||
try {
|
||||
await call('disconnect', {});
|
||||
} catch (err) {
|
||||
if (err.code !== 'not_connected') toast(`Отключение: ${errorText(err)}`, 'error');
|
||||
if (err.code !== 'not_connected') toast(() => t('message.disconnect.p0', { p0: errorText(err) }), 'error');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -304,9 +316,9 @@ function resetConnection(reason) {
|
||||
voice.setPtt(false);
|
||||
voice.syncCapture();
|
||||
if (wasConnected) {
|
||||
chat.addSystem('channel', reason ? `Отключено: ${errorText(reason)}` : 'Отключено от сервера');
|
||||
chat.addSystem('channel', () => reason ? t('message.disconnected.p0', { p0: errorText(reason) }) : t('ui.disconnected.from.server'));
|
||||
}
|
||||
if (reason) setText($('#connect-error'), errorText(reason));
|
||||
if (reason) setText($('#connect-error'), () => errorText(reason));
|
||||
}
|
||||
|
||||
function onStateEvent(evt) {
|
||||
@@ -315,9 +327,9 @@ function onStateEvent(evt) {
|
||||
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 === 'connecting' && prev === 'connected') chat.addSystem('channel', () => t('ui.connection.lost.reconnecting'));
|
||||
if (evt.state === 'connected') {
|
||||
setText($('#connect-error'), '');
|
||||
setText($('#connect-error'), () => '');
|
||||
voice.syncCapture();
|
||||
}
|
||||
}
|
||||
@@ -332,14 +344,14 @@ function onSnapshot(snap) {
|
||||
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})` : ''}`);
|
||||
chat.addSystem('server', () => t('message.connected.to.p0.p1', { p0: snap.server.name, p1: snap.server.version ? ` (${snap.server.version})` : '' }));
|
||||
const welcome = stripBBCode(snap.server.welcome_message).trim();
|
||||
if (welcome) chat.addSystem('server', welcome);
|
||||
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}»`);
|
||||
if (ch) chat.addSystem('channel', () => t('message.you.are.in.channel.p0', { p0: ch.name }));
|
||||
}
|
||||
watch.onSnapshot();
|
||||
renderHostBanner();
|
||||
@@ -361,7 +373,7 @@ function onAsyncError(error) {
|
||||
renderSessionHead();
|
||||
return;
|
||||
}
|
||||
toast(errorText(error), 'error');
|
||||
toast(() => errorText(error), 'error');
|
||||
}
|
||||
|
||||
function onCoreEvent(evt) {
|
||||
@@ -423,7 +435,7 @@ async function toggleAudio(key) {
|
||||
renderSelf();
|
||||
renderSessionHead();
|
||||
} catch (err) {
|
||||
toast(errorText(err), 'error');
|
||||
toast(() => errorText(err), 'error');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -468,6 +480,7 @@ Object.defineProperty(window, 'teamspeachDiagnostics', {
|
||||
|
||||
async function boot() {
|
||||
S.prefs = await tp.getPrefs();
|
||||
setLanguage(S.prefs.language);
|
||||
$('#stream-volume').value = String(S.prefs.streamVolume);
|
||||
|
||||
initTree({
|
||||
@@ -480,6 +493,7 @@ async function boot() {
|
||||
chat.initChat();
|
||||
servers.initServers({ savePrefs, connectTo });
|
||||
initDeviceMenus({ openAudioSettings: () => openSettings('audio') });
|
||||
initUpdates();
|
||||
watch.initWatch({ onChange: () => renderTree(), savePrefs });
|
||||
voice.initVoice({
|
||||
savePrefs,
|
||||
@@ -498,12 +512,19 @@ async function boot() {
|
||||
renderTree();
|
||||
},
|
||||
});
|
||||
onLanguageChange(() => {
|
||||
renderSelf();
|
||||
renderSessionHead();
|
||||
renderTree();
|
||||
chat.renderTabs();
|
||||
chat.renderLog();
|
||||
});
|
||||
|
||||
$('#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)}`);
|
||||
if (r.ok) toast(() => t('message.identity.restored.uid.p0', { p0: r.uid }));
|
||||
else if (!r.canceled) setText($('#onboarding-error'), () => t('message.restore.failed.p0', { p0: errorText(r.error) }));
|
||||
});
|
||||
$('#connect-form').addEventListener('submit', submitConnect);
|
||||
$('#btn-disconnect').addEventListener('click', disconnect);
|
||||
@@ -513,7 +534,7 @@ async function boot() {
|
||||
$('#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');
|
||||
if (!r.ok && !r.canceled) toast(() => t('message.import.failed.p0', { p0: errorText(r.error) }), 'error');
|
||||
});
|
||||
$('#fatal-logs').addEventListener('click', () => tp.openLogs());
|
||||
|
||||
@@ -525,5 +546,5 @@ async function boot() {
|
||||
|
||||
boot().catch((err) => {
|
||||
log('error', `boot failed: ${err.stack || err.message}`);
|
||||
showFatal('Ошибка запуска интерфейса', String(err.message || err), []);
|
||||
showFatal(t('ui.interface.startup.failed'), String(err.message || err), []);
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n.js';
|
||||
// Turns MediaDeviceInfo entries of one kind into select options. DOM-free for unit tests.
|
||||
//
|
||||
// Chromium adds aliases ("default", "communications") next to the physical endpoints and, without media
|
||||
@@ -20,15 +21,15 @@ function aliasTarget(label) {
|
||||
export function buildDeviceOptions(list, selected) {
|
||||
const defaultEntry = list.find((d) => d.deviceId === 'default');
|
||||
const defaultName = aliasTarget(defaultEntry?.label);
|
||||
const options = [{ value: '', label: defaultName ? `Системное по умолчанию (${defaultName})` : 'Системное устройство по умолчанию' }];
|
||||
const options = [{ value: '', label: defaultName ? t('message.system.default.p0', { p0: defaultName }) : t('ui.system.default.device') }];
|
||||
let physical = 0;
|
||||
for (const d of list) {
|
||||
if (!d.deviceId || ALIASES.has(d.deviceId)) continue;
|
||||
physical += 1;
|
||||
options.push({ value: d.deviceId, label: d.label || `Устройство без названия (${d.deviceId.slice(0, 8)})` });
|
||||
options.push({ value: d.deviceId, label: d.label || t('message.unnamed.device.p0', { p0: d.deviceId.slice(0, 8) }) });
|
||||
}
|
||||
if (selected && !options.some((o) => o.value === selected)) {
|
||||
options.push({ value: selected, label: 'Выбранное ранее устройство (сейчас не найдено)' });
|
||||
options.push({ value: selected, label: t('ui.previously.selected.device.currently.unavailable') });
|
||||
}
|
||||
// Entries exist but none carries an id: the engine withheld the list (no media permission).
|
||||
const redacted = physical === 0 && list.some((d) => !d.deviceId);
|
||||
|
||||
@@ -10,6 +10,8 @@ export class AudioEngine {
|
||||
this.playback = null;
|
||||
this.voiceGain = null;
|
||||
this.capture = null;
|
||||
this.captureGen = 0; // bumped by every start/stop; a pending start only completes if still current
|
||||
this.startingGen = null;
|
||||
this.ready = null;
|
||||
this.stats = { framesOut: 0 };
|
||||
this.statsWaiters = [];
|
||||
@@ -48,7 +50,7 @@ export class AudioEngine {
|
||||
|
||||
async setOutputDevice(deviceId) {
|
||||
await this.init();
|
||||
if (typeof this.ctx.setSinkId !== 'function') throw new Error('Выбор устройства вывода не поддерживается');
|
||||
if (typeof this.ctx.setSinkId !== 'function') throw new Error('Output device selection is not supported');
|
||||
await this.ctx.setSinkId(deviceId || '');
|
||||
}
|
||||
|
||||
@@ -76,9 +78,33 @@ export class AudioEngine {
|
||||
return this.capture !== null;
|
||||
}
|
||||
|
||||
/** True while a startCapture() call is still waiting for the engine or the microphone. */
|
||||
get captureStarting() {
|
||||
return this.startingGen !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the microphone. Every later startCapture() or stopCapture() supersedes a pending call: when
|
||||
* getUserMedia resolves for a superseded call its tracks are stopped at once and null is returned, so a
|
||||
* disconnect or a closed mic test during the permission/device wait never leaves a microphone open.
|
||||
*/
|
||||
async startCapture({ deviceId, echoCancellation, noiseSuppression, autoGainControl }) {
|
||||
const gen = ++this.captureGen;
|
||||
this.startingGen = gen;
|
||||
this.releaseCapture();
|
||||
try {
|
||||
return await this.openCapture(gen, { deviceId, echoCancellation, noiseSuppression, autoGainControl });
|
||||
} catch (err) {
|
||||
if (gen !== this.captureGen) return null; // superseded: the failure no longer matters
|
||||
throw err;
|
||||
} finally {
|
||||
if (this.startingGen === gen) this.startingGen = null;
|
||||
}
|
||||
}
|
||||
|
||||
async openCapture(gen, { deviceId, echoCancellation, noiseSuppression, autoGainControl }) {
|
||||
await this.init();
|
||||
this.stopCapture();
|
||||
if (gen !== this.captureGen) return null;
|
||||
const audio = {
|
||||
channelCount: 1,
|
||||
echoCancellation,
|
||||
@@ -87,17 +113,20 @@ export class AudioEngine {
|
||||
};
|
||||
if (deviceId) audio.deviceId = { exact: deviceId };
|
||||
let stream;
|
||||
let fellBack = false;
|
||||
try {
|
||||
stream = await navigator.mediaDevices.getUserMedia({ audio, video: false });
|
||||
} catch (err) {
|
||||
if (deviceId && err && err.name === 'OverconstrainedError') {
|
||||
if (!(deviceId && err && err.name === 'OverconstrainedError') || gen !== this.captureGen) throw err;
|
||||
delete audio.deviceId;
|
||||
stream = await navigator.mediaDevices.getUserMedia({ audio, video: false });
|
||||
this.onError({ code: 'device_fallback', message: 'Выбранный микрофон недоступен, используется микрофон по умолчанию' });
|
||||
} else {
|
||||
throw err;
|
||||
fellBack = true;
|
||||
}
|
||||
if (gen !== this.captureGen) {
|
||||
for (const t of stream.getTracks()) t.stop();
|
||||
return null;
|
||||
}
|
||||
if (fellBack) this.onError({ code: 'device_fallback', message: 'Selected microphone unavailable; using the default microphone' });
|
||||
const ctx = this.ctx;
|
||||
const source = ctx.createMediaStreamSource(stream);
|
||||
const node = new AudioWorkletNode(ctx, 'tp-capture', {
|
||||
@@ -120,7 +149,7 @@ export class AudioEngine {
|
||||
track.addEventListener('ended', () => {
|
||||
if (this.capture && this.capture.stream === stream) {
|
||||
this.stopCapture();
|
||||
this.onError({ code: 'device_lost', message: 'Микрофон отключён' });
|
||||
this.onError({ code: 'device_lost', message: 'Microphone disconnected' });
|
||||
}
|
||||
});
|
||||
this.capture = { stream, source, node, sink, label: track ? track.label : '' };
|
||||
@@ -132,7 +161,14 @@ export class AudioEngine {
|
||||
return this.capture.label;
|
||||
}
|
||||
|
||||
/** Stops the microphone and cancels a pending startCapture(). */
|
||||
stopCapture() {
|
||||
this.captureGen += 1;
|
||||
this.startingGen = null;
|
||||
this.releaseCapture();
|
||||
}
|
||||
|
||||
releaseCapture() {
|
||||
const c = this.capture;
|
||||
if (!c) return;
|
||||
this.capture = null;
|
||||
|
||||
+16
-15
@@ -1,3 +1,4 @@
|
||||
import { t } from './i18n.js';
|
||||
// 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';
|
||||
@@ -45,10 +46,10 @@ function autosize() {
|
||||
}
|
||||
|
||||
function tabTitle(chat) {
|
||||
if (chat.kind === 'channel') return ownChannel()?.name ?? 'Канал';
|
||||
if (chat.kind === 'server') return 'Сервер';
|
||||
if (chat.kind === 'channel') return ownChannel()?.name ?? t('ui.channel');
|
||||
if (chat.kind === 'server') return t('ui.server');
|
||||
const cl = clientById(chat.clientId);
|
||||
return cl ? cl.nickname : `${chat.nickname} (вышел)`;
|
||||
return cl ? cl.nickname : t('message.p0.left', { p0: chat.nickname });
|
||||
}
|
||||
|
||||
function targetOf(chat) {
|
||||
@@ -63,11 +64,11 @@ async function send() {
|
||||
const chat = chats.get(active);
|
||||
if (!chat) return;
|
||||
if (chat.kind === 'client' && !clientById(chat.clientId)) {
|
||||
toast('Собеседник покинул сервер', 'error');
|
||||
toast(() => t('ui.this.person.left.the.server'), 'error');
|
||||
return;
|
||||
}
|
||||
if (new TextEncoder().encode(text).length > 8192) {
|
||||
toast('Сообщение длиннее 8 КиБ', 'error');
|
||||
toast(() => t('ui.message.exceeds.8.kib'), 'error');
|
||||
return;
|
||||
}
|
||||
input.disabled = true;
|
||||
@@ -76,7 +77,7 @@ async function send() {
|
||||
input.value = '';
|
||||
autosize();
|
||||
} catch (err) {
|
||||
toast(`Сообщение не отправлено: ${errorText(err)}`, 'error');
|
||||
toast(() => t('message.message.not.sent.p0', { p0: errorText(err) }), 'error');
|
||||
} finally {
|
||||
input.disabled = false;
|
||||
input.focus();
|
||||
@@ -163,7 +164,7 @@ function createTab(chat) {
|
||||
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'));
|
||||
const close = h('button', { class: 'tab-close icon-btn', type: 'button', 'aria-label': t('ui.close.private.chat'), 'data-i18n-aria-label': 'ui.close.private.chat' }, icon('x'));
|
||||
close.addEventListener('click', () => closePrivate(chat.key));
|
||||
wrap.appendChild(close);
|
||||
}
|
||||
@@ -174,14 +175,14 @@ function updateTab(wrap, chat) {
|
||||
const tab = wrap.firstElementChild;
|
||||
const [label, unread] = tab.children;
|
||||
const title = tabTitle(chat);
|
||||
setText(label, chat.kind === 'client' ? `@ ${title}` : title);
|
||||
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}`;
|
||||
tab.title = chat.kind === 'channel' ? t('ui.current.channel.chat') : chat.kind === 'server' ? t('ui.server.wide.chat') : t('message.private.messages.p0', { p0: 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}` : ''}`);
|
||||
setText(unread, () => chat.unread > 99 ? '99+' : String(chat.unread));
|
||||
tab.setAttribute('aria-label', `${tab.title}${chat.unread ? t('message.unread.p0', { p0: chat.unread }) : ''}`);
|
||||
}
|
||||
|
||||
function onTabKey(e) {
|
||||
@@ -215,9 +216,9 @@ export function renderLog() {
|
||||
|
||||
function emptyText(chat) {
|
||||
if (!chat) return '';
|
||||
if (chat.kind === 'channel') return 'Сообщения в этом канале видят все, кто в нём находится.';
|
||||
if (chat.kind === 'server') return 'Сообщения сервера видят все подключённые.';
|
||||
return 'Личная переписка. Сообщения видит только собеседник.';
|
||||
if (chat.kind === 'channel') return t('ui.everyone.in.this.channel.can.see.its');
|
||||
if (chat.kind === 'server') return t('ui.everyone.connected.to.the.server.can.see');
|
||||
return t('ui.private.conversation.only.the.recipient.can.see');
|
||||
}
|
||||
|
||||
function rowFor(msg, prev) {
|
||||
@@ -250,7 +251,7 @@ export function updateComposer() {
|
||||
input.disabled = !enabled;
|
||||
sendBtn.disabled = !enabled;
|
||||
const title = chat ? tabTitle(chat) : '';
|
||||
input.placeholder = !isConnected() ? 'Нет подключения' : partnerGone ? 'Собеседник покинул сервер' : chat?.kind === 'client' ? `Сообщение для ${title}` : chat?.kind === 'server' ? 'Сообщение всему серверу' : `Сообщение в «${title}»`;
|
||||
input.placeholder = !isConnected() ? t('ui.not.connected') : partnerGone ? t('ui.this.person.left.the.server') : chat?.kind === 'client' ? t('message.message.p0', { p0: title }) : chat?.kind === 'server' ? t('ui.message.the.whole.server') : t('message.message.in.p0', { p0: title });
|
||||
}
|
||||
|
||||
/** Called when the connection ends: private chats keep their history but cannot be answered. */
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { t, onLanguageChange } from './i18n.js';
|
||||
// Context menus on the footer microphone/headphones buttons: pick the input or output device.
|
||||
// Uses the same discovery and selection path as Settings → Звук (voice.deviceChoices / choose*Device).
|
||||
// Uses the same discovery and selection path as Settings → Audio (voice.deviceChoices / choose*Device).
|
||||
// Opening never toggles mute or deafen; left click on the buttons keeps its own behaviour.
|
||||
import { $, h, icon } from './dom.js';
|
||||
import { S } from './state.js';
|
||||
@@ -12,6 +13,9 @@ export function initDeviceMenus(h0) {
|
||||
hooks = { ...hooks, ...h0 };
|
||||
bind($('#btn-mute'), 'input');
|
||||
bind($('#btn-deafen'), 'output');
|
||||
onLanguageChange(() => {
|
||||
if (open) show(open.anchor, open.kind, open.point);
|
||||
});
|
||||
}
|
||||
|
||||
function bind(button, kind) {
|
||||
@@ -48,8 +52,8 @@ let generation = 0;
|
||||
function show(anchor, kind, point) {
|
||||
close({ restoreFocus: false });
|
||||
const gen = ++generation;
|
||||
const title = kind === 'input' ? 'Микрофон' : 'Устройство вывода';
|
||||
const body = h('div', { class: 'menu-body' }, h('p', { class: 'menu-note', text: 'Получаем список устройств…' }));
|
||||
const title = kind === 'input' ? t('ui.microphone') : t('ui.output.device');
|
||||
const body = h('div', { class: 'menu-body' }, h('p', { class: 'menu-note', text: t('ui.loading.devices') }));
|
||||
const menu = h('div', { class: 'device-menu', role: 'menu', 'aria-label': title, 'aria-busy': 'true', tabindex: '-1' },
|
||||
h('div', { class: 'menu-title', text: title }),
|
||||
body);
|
||||
@@ -80,6 +84,8 @@ function show(anchor, kind, point) {
|
||||
gen,
|
||||
menu,
|
||||
anchor,
|
||||
kind,
|
||||
point,
|
||||
cleanup: () => {
|
||||
document.removeEventListener('pointerdown', onPointer, true);
|
||||
window.removeEventListener('resize', onDismiss);
|
||||
@@ -108,13 +114,13 @@ function show(anchor, kind, point) {
|
||||
});
|
||||
return item;
|
||||
});
|
||||
const settingsItem = h('button', { class: 'menu-item menu-item-secondary', type: 'button', role: 'menuitem', tabindex: '-1' }, h('span', { class: 'menu-check', 'aria-hidden': 'true' }), h('span', { class: 'menu-label', text: 'Настройки звука…' }));
|
||||
const settingsItem = h('button', { class: 'menu-item menu-item-secondary', type: 'button', role: 'menuitem', tabindex: '-1' }, h('span', { class: 'menu-check', 'aria-hidden': 'true' }), h('span', { class: 'menu-label', text: t('ui.audio.settings') }));
|
||||
settingsItem.addEventListener('click', () => {
|
||||
close({ restoreFocus: false });
|
||||
hooks.openAudioSettings();
|
||||
});
|
||||
const note = data.redacted || data.physical === 0
|
||||
? h('p', { class: 'menu-note', text: data.redacted ? 'Движок скрыл список устройств: доступно только системное устройство.' : kind === 'input' ? 'Микрофоны не найдены.' : 'Устройства вывода не найдены.' })
|
||||
? h('p', { class: 'menu-note', text: data.redacted ? t('ui.the.engine.hid.the.device.list.only') : kind === 'input' ? t('ui.no.microphones.found') : t('ui.no.output.devices.found') })
|
||||
: null;
|
||||
body.replaceChildren(...items, ...(note ? [note] : []), h('div', { class: 'menu-sep', role: 'separator' }), settingsItem);
|
||||
menu.removeAttribute('aria-busy');
|
||||
|
||||
+22
-3
@@ -1,3 +1,4 @@
|
||||
import { getLanguage, onLanguageChange } from './i18n.js';
|
||||
// DOM helpers. Server-provided text only ever reaches the page through textContent / attributes.
|
||||
|
||||
export function $(selector, root = document) {
|
||||
@@ -16,7 +17,7 @@ export function h(tag, props = {}, ...children) {
|
||||
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 === 'text') setText(el, 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));
|
||||
@@ -79,11 +80,29 @@ export function reconcile(container, items, keyOf, create, update) {
|
||||
for (const el of existing.values()) el.remove();
|
||||
}
|
||||
|
||||
const liveText = new WeakMap();
|
||||
|
||||
export function setText(el, text) {
|
||||
const value = text ?? '';
|
||||
if (typeof text === 'function') {
|
||||
liveText.set(el, text);
|
||||
el.dataset.liveText = '';
|
||||
} else {
|
||||
liveText.delete(el);
|
||||
delete el.dataset.liveText;
|
||||
}
|
||||
// A dynamic binding supersedes an initial HTML label.
|
||||
el.removeAttribute('data-i18n');
|
||||
const value = (typeof text === 'function' ? text() : text) ?? '';
|
||||
if (el.textContent !== value) el.textContent = value;
|
||||
}
|
||||
|
||||
onLanguageChange(() => {
|
||||
for (const el of document.querySelectorAll('[data-live-text]')) {
|
||||
const render = liveText.get(el);
|
||||
if (render) setText(el, render);
|
||||
}
|
||||
});
|
||||
|
||||
export function formatTime(date) {
|
||||
return date.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
|
||||
return date.toLocaleTimeString(getLanguage(), { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import '../shared/en.js';
|
||||
import '../shared/ru.js';
|
||||
import '../shared/i18n.js';
|
||||
|
||||
const shared = globalThis.TeamsPeachI18n;
|
||||
let language = 'en';
|
||||
const listeners = new Set();
|
||||
export const getLanguage = () => language;
|
||||
export const t = (key, params = {}) => shared.t(key, params, language);
|
||||
export const hasTranslation = (key) => Object.hasOwn(shared.catalogs.en, key);
|
||||
export function onLanguageChange(listener) {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
}
|
||||
export function translatePage(root = document) {
|
||||
for (const element of root.querySelectorAll('[data-i18n]')) element.textContent = t(element.dataset.i18n);
|
||||
for (const attribute of ['title', 'aria-label', 'placeholder']) {
|
||||
for (const element of root.querySelectorAll(`[data-i18n-${attribute}]`)) {
|
||||
element.setAttribute(attribute, t(element.getAttribute(`data-i18n-${attribute}`)));
|
||||
}
|
||||
}
|
||||
}
|
||||
export function setLanguage(value) {
|
||||
const next = shared.normalizeLanguage(value);
|
||||
const changed = next !== language;
|
||||
language = next;
|
||||
if (typeof document !== 'undefined') {
|
||||
document.documentElement.lang = language;
|
||||
translatePage();
|
||||
}
|
||||
if (changed) for (const listener of listeners) listener(language);
|
||||
return language;
|
||||
}
|
||||
+23
-18
@@ -1,5 +1,6 @@
|
||||
import { t, onLanguageChange } from './i18n.js';
|
||||
// Saved servers (name + address only; never passwords): quick access in the sidebar and management
|
||||
// in Settings → Серверы. Persisted through main's validated preferences.
|
||||
// in Settings → Servers. Persisted through main's validated preferences.
|
||||
import { $, h, icon, setText } from './dom.js';
|
||||
import { S, isConnected } from './state.js';
|
||||
import { toast } from './toast.js';
|
||||
@@ -12,6 +13,10 @@ let confirmTimer = null;
|
||||
|
||||
export function initServers(h0) {
|
||||
hooks = { ...hooks, ...h0 };
|
||||
onLanguageChange(() => {
|
||||
// Refresh quick actions only; never rebuild a bookmark form with an unsaved draft.
|
||||
$('#servers-list').replaceChildren(...servers().map(quickRow));
|
||||
});
|
||||
$('#btn-servers').addEventListener('click', () => {
|
||||
panelOpen = !isPanelOpen();
|
||||
renderServers();
|
||||
@@ -21,7 +26,7 @@ export function initServers(h0) {
|
||||
$('#connect-save').addEventListener('click', () => {
|
||||
const address = $('#connect-address').value.trim();
|
||||
if (!address) {
|
||||
setText($('#connect-error'), 'Укажите адрес сервера, чтобы сохранить его.');
|
||||
setText($('#connect-error'), () => t('ui.enter.a.server.address.to.save.it'));
|
||||
return;
|
||||
}
|
||||
saveAddress(address, address);
|
||||
@@ -31,13 +36,13 @@ export function initServers(h0) {
|
||||
const name = $('#server-add-name').value.trim();
|
||||
const address = $('#server-add-address').value.trim();
|
||||
if (!address) {
|
||||
setText($('#server-add-status'), 'Укажите адрес.');
|
||||
setText($('#server-add-status'), () => t('ui.enter.an.address'));
|
||||
return;
|
||||
}
|
||||
if (await saveAddress(name || address, address)) {
|
||||
$('#server-add-name').value = '';
|
||||
$('#server-add-address').value = '';
|
||||
setText($('#server-add-status'), 'Сервер добавлен.');
|
||||
setText($('#server-add-status'), () => t('ui.server.added'));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -66,15 +71,15 @@ async function persist(list) {
|
||||
async function saveAddress(name, address) {
|
||||
const trimmed = address.trim();
|
||||
if (servers().some((s) => sameAddress(s.address, trimmed))) {
|
||||
toast('Этот адрес уже сохранён');
|
||||
toast(() => t('ui.this.address.is.already.saved'));
|
||||
return false;
|
||||
}
|
||||
if (servers().length >= 50) {
|
||||
toast('Можно сохранить не больше 50 серверов', 'error');
|
||||
toast(() => t('ui.you.can.save.up.to.50.servers'), 'error');
|
||||
return false;
|
||||
}
|
||||
const ok = await persist([...servers(), { id: newId(), name: name.trim().slice(0, 64) || trimmed, address: trimmed }]);
|
||||
if (ok) toast(`Сервер «${name.trim() || trimmed}» сохранён`);
|
||||
if (ok) toast(() => t('message.server.p0.saved', { p0: name.trim() || trimmed }));
|
||||
return ok;
|
||||
}
|
||||
|
||||
@@ -102,13 +107,13 @@ export function renderServers() {
|
||||
function quickRow(server) {
|
||||
const current = connectedTo(server);
|
||||
const busy = S.conn.state === 'connecting' || S.conn.state === 'disconnecting';
|
||||
const label = current ? 'Подключено' : S.conn.state === 'disconnected' ? 'Подключиться' : 'Переключиться';
|
||||
const label = current ? t('ui.connected2') : S.conn.state === 'disconnected' ? t('ui.connect') : t('ui.switch');
|
||||
const btn = h('button', {
|
||||
class: 'server-item',
|
||||
type: 'button',
|
||||
disabled: current || busy,
|
||||
'aria-label': `${server.name}, ${server.address}. ${label}`,
|
||||
title: current ? 'Вы подключены к этому серверу' : S.conn.state === 'disconnected' ? 'Подключиться' : 'Отключиться от текущего сервера и подключиться к этому',
|
||||
title: current ? t('ui.you.are.connected.to.this.server') : S.conn.state === 'disconnected' ? t('ui.connect') : t('ui.disconnect.from.the.current.server.and.connect'),
|
||||
}, icon('bookmark'), h('span', { class: 'server-text' }, h('span', { class: 'server-item-name', text: server.name }), h('span', { class: 'server-item-address', text: server.address })), h('span', { class: 'server-item-action', text: label }));
|
||||
btn.addEventListener('click', () => hooks.connectTo(server.address, { switching: S.conn.state !== 'disconnected' }));
|
||||
return h('li', {}, btn);
|
||||
@@ -116,9 +121,9 @@ function quickRow(server) {
|
||||
|
||||
function manageRow(server) {
|
||||
if (editingId === server.id) return editRow(server);
|
||||
const edit = h('button', { class: 'btn btn-ghost btn-small', type: 'button' }, 'Изменить');
|
||||
const edit = h('button', { class: 'btn btn-ghost btn-small', type: 'button', 'data-action': 'edit', 'data-i18n': 'ui.edit' }, t('ui.edit'));
|
||||
const confirming = confirmDeleteId === server.id;
|
||||
const del = h('button', { class: `btn btn-ghost btn-small${confirming ? ' btn-danger' : ''}`, type: 'button' }, confirming ? 'Точно удалить?' : 'Удалить');
|
||||
const del = h('button', { class: `btn btn-ghost btn-small${confirming ? ' btn-danger' : ''}`, type: 'button', 'data-action': confirming ? 'confirm-delete' : 'delete', 'data-i18n': confirming ? 'ui.confirm.deletion' : 'ui.delete' }, confirming ? t('ui.confirm.deletion') : t('ui.delete'));
|
||||
edit.addEventListener('click', () => {
|
||||
editingId = server.id;
|
||||
renderServers();
|
||||
@@ -138,7 +143,7 @@ function manageRow(server) {
|
||||
}
|
||||
confirmDeleteId = null;
|
||||
await persist(servers().filter((s) => s.id !== server.id));
|
||||
toast(`Сервер «${server.name}» удалён`);
|
||||
toast(() => t('message.server.p0.deleted', { p0: server.name }));
|
||||
});
|
||||
return h('li', { class: 'manage-row', dataset: { row: server.id } },
|
||||
h('span', { class: 'server-text' }, h('span', { class: 'server-item-name', text: server.name }), h('span', { class: 'server-item-address', text: server.address })),
|
||||
@@ -146,10 +151,10 @@ function manageRow(server) {
|
||||
}
|
||||
|
||||
function editRow(server) {
|
||||
const name = h('input', { type: 'text', maxlength: '64', value: server.name, 'aria-label': 'Название сервера' });
|
||||
const address = h('input', { type: 'text', maxlength: '255', value: server.address, spellcheck: 'false', 'aria-label': 'Адрес сервера' });
|
||||
const cancel = h('button', { class: 'btn btn-ghost btn-small', type: 'button' }, 'Отмена');
|
||||
const form = h('form', { class: 'edit-row', novalidate: true, dataset: { edit: server.id } }, name, address, h('button', { class: 'btn btn-primary btn-small', type: 'submit' }, 'Сохранить'), cancel);
|
||||
const name = h('input', { type: 'text', maxlength: '64', value: server.name, 'data-field': 'name', 'aria-label': t('ui.server.name'), 'data-i18n-aria-label': 'ui.server.name' });
|
||||
const address = h('input', { type: 'text', maxlength: '255', value: server.address, spellcheck: 'false', 'aria-label': t('ui.server.address'), 'data-i18n-aria-label': 'ui.server.address' });
|
||||
const cancel = h('button', { class: 'btn btn-ghost btn-small', type: 'button', 'data-i18n': 'ui.cancel' }, t('ui.cancel'));
|
||||
const form = h('form', { class: 'edit-row', novalidate: true, dataset: { edit: server.id } }, name, address, h('button', { class: 'btn btn-primary btn-small', type: 'submit', 'data-action': 'save', 'data-i18n': 'ui.save' }, t('ui.save')), cancel);
|
||||
cancel.addEventListener('click', () => {
|
||||
editingId = null;
|
||||
renderServers();
|
||||
@@ -166,11 +171,11 @@ function editRow(server) {
|
||||
const n = name.value.trim();
|
||||
const a = address.value.trim();
|
||||
if (!n || !a) {
|
||||
toast('Название и адрес не могут быть пустыми', 'error');
|
||||
toast(() => t('ui.name.and.address.cannot.be.empty'), 'error');
|
||||
return;
|
||||
}
|
||||
if (servers().some((s) => s.id !== server.id && sameAddress(s.address, a))) {
|
||||
toast('Этот адрес уже сохранён под другим названием', 'error');
|
||||
toast(() => t('ui.this.address.is.already.saved.under.another'), 'error');
|
||||
return;
|
||||
}
|
||||
editingId = null;
|
||||
|
||||
+60
-40
@@ -1,3 +1,4 @@
|
||||
import { t, setLanguage, onLanguageChange } from './i18n.js';
|
||||
// Settings: profile (rename, UID, identity backup), audio devices/transmit mode, diagnostics.
|
||||
import { $, h, setText } from './dom.js';
|
||||
import { S, isConnected } from './state.js';
|
||||
@@ -11,6 +12,22 @@ let hooks = { savePrefs: async () => {}, close: () => {}, onProfile: () => {} };
|
||||
|
||||
export function initSettings(h0) {
|
||||
hooks = { ...hooks, ...h0 };
|
||||
$('#language-select').value = S.prefs.language;
|
||||
$('#language-select').addEventListener('change', async (event) => {
|
||||
const select = event.target;
|
||||
select.disabled = true;
|
||||
try {
|
||||
const prefs = await hooks.savePrefs({ language: select.value });
|
||||
select.value = setLanguage(prefs.language);
|
||||
} finally {
|
||||
select.disabled = false;
|
||||
}
|
||||
});
|
||||
onLanguageChange(() => {
|
||||
renderDiagnostics();
|
||||
renderVideo();
|
||||
voice.refreshDevices();
|
||||
});
|
||||
|
||||
$('#settings-back').addEventListener('click', () => hooks.close());
|
||||
for (const host of [$('#settings-view'), $('#settings-nav')]) {
|
||||
@@ -52,26 +69,26 @@ export function initSettings(h0) {
|
||||
const len = [...nickname].length;
|
||||
if (len < 3 || len > 30) {
|
||||
input.setAttribute('aria-invalid', 'true');
|
||||
setText(status, 'Никнейм должен содержать от 3 до 30 символов.');
|
||||
setText(status, () => t('ui.nickname.must.contain.3.30.characters'));
|
||||
return;
|
||||
}
|
||||
if (nickname === S.profile?.nickname) {
|
||||
setText(status, 'Это уже ваш никнейм.');
|
||||
setText(status, () => t('ui.this.is.already.your.nickname'));
|
||||
return;
|
||||
}
|
||||
input.removeAttribute('aria-invalid');
|
||||
$('#rename-submit').disabled = true;
|
||||
setText(status, 'Сохраняем…');
|
||||
setText(status, () => t('ui.saving'));
|
||||
const uidBefore = S.profile?.uid;
|
||||
try {
|
||||
const profile = await call('rename', { nickname });
|
||||
hooks.onProfile(profile);
|
||||
setText(status, profile.uid === uidBefore ? `Сохранено${isConnected() ? ' и применено на сервере' : ''}. UID не изменился.` : 'Сохранено.');
|
||||
setText(status, () => profile.uid === uidBefore ? t('message.saved.p0.uid.unchanged', { p0: isConnected() ? t('ui.and.applied.on.the.server') : '' }) : t('ui.saved'));
|
||||
} catch (err) {
|
||||
if (err.code === 'rename_not_persisted' && err.detail) {
|
||||
setText(status, `Сервер показал «${err.detail.server_nickname}», но на диске остался «${err.detail.saved_nickname}»${err.detail.reverted ? '; имя на сервере возвращено' : ''}.`);
|
||||
setText(status, () => t('message.the.server.showed.p0.but.p1', { p0: err.detail.server_nickname, p1: err.detail.saved_nickname, p2: err.detail.reverted ? t('ui.the.server.nickname.was.restored') : '' }));
|
||||
} else {
|
||||
setText(status, errorText(err));
|
||||
setText(status, () => errorText(err));
|
||||
}
|
||||
} finally {
|
||||
$('#rename-submit').disabled = false;
|
||||
@@ -79,26 +96,28 @@ export function initSettings(h0) {
|
||||
});
|
||||
|
||||
$('#uid-copy').addEventListener('click', async () => {
|
||||
if (S.profile?.uid && (await tp.copyText(S.profile.uid))) toast('UID скопирован');
|
||||
if (S.profile?.uid && (await tp.copyText(S.profile.uid))) toast(() => t('ui.uid.copied'));
|
||||
});
|
||||
|
||||
$('#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)}`);
|
||||
status.dataset.state = r.ok ? 'ok' : 'error';
|
||||
setText(status, () => r.ok ? t('message.saved.to.p0.uid.p1', { p0: r.file, p1: r.uid }) : t('message.export.failed.p0', { p0: errorText(r.error) }));
|
||||
});
|
||||
|
||||
$('#identity-import').addEventListener('click', async () => {
|
||||
const status = $('#identity-status');
|
||||
if (S.conn.state !== 'disconnected') {
|
||||
setText(status, 'Сначала отключитесь от сервера.');
|
||||
setText(status, () => t('ui.disconnect.from.the.server.first'));
|
||||
return;
|
||||
}
|
||||
const r = await tp.importIdentity();
|
||||
if (r.canceled) return;
|
||||
if (r.ok) toast(`Идентичность импортирована. UID ${r.uid}`);
|
||||
else setText(status, `Импорт не удался: ${errorText(r.error)}`);
|
||||
status.dataset.state = r.ok ? 'ok' : 'error';
|
||||
if (r.ok) toast(() => t('message.identity.imported.uid.p0', { p0: r.uid }));
|
||||
else setText(status, () => t('message.import.failed.p0', { p0: errorText(r.error) }));
|
||||
});
|
||||
|
||||
// Same selection path as the microphone/headphones context menus (voice.js).
|
||||
@@ -107,7 +126,7 @@ export function initSettings(h0) {
|
||||
$('#voice-volume').addEventListener('input', (e) => {
|
||||
const v = Number(e.target.value);
|
||||
voice.setVoiceVolume(v);
|
||||
setText($('#voice-volume-value'), `${v}%`);
|
||||
setText($('#voice-volume-value'), () => `${v}%`);
|
||||
});
|
||||
$('#voice-volume').addEventListener('change', (e) => hooks.savePrefs({ voiceVolume: Number(e.target.value) }));
|
||||
|
||||
@@ -123,7 +142,7 @@ export function initSettings(h0) {
|
||||
$('#ptt-assign').addEventListener('click', async () => {
|
||||
const btn = $('#ptt-assign');
|
||||
btn.disabled = true;
|
||||
setText($('#ptt-key'), 'нажмите клавишу…');
|
||||
setText($('#ptt-key'), () => t('ui.press.a.key'));
|
||||
const code = await voice.capturePttKey();
|
||||
btn.disabled = false;
|
||||
if (code) await hooks.savePrefs({ pttCode: code });
|
||||
@@ -143,7 +162,7 @@ export function initSettings(h0) {
|
||||
const btn = $('#mic-test');
|
||||
const on = btn.getAttribute('aria-pressed') !== 'true';
|
||||
btn.setAttribute('aria-pressed', String(on));
|
||||
setText(btn, on ? 'Остановить проверку' : 'Проверить микрофон');
|
||||
setText(btn, () => on ? t('ui.stop.test') : t('ui.test.microphone'));
|
||||
await voice.setMicTest(on);
|
||||
});
|
||||
|
||||
@@ -161,34 +180,34 @@ export function renderProfile() {
|
||||
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}` : '');
|
||||
setText($('#uid-value'), () => p.uid ?? '');
|
||||
setText($('#security-level'), () => p.security_level !== null && p.security_level !== undefined ? t('message.identity.security.level.p0', { p0: p.security_level }) : '');
|
||||
$('#identity-import').disabled = S.conn.state !== 'disconnected';
|
||||
$('#identity-import').title = S.conn.state !== 'disconnected' ? 'Доступно после отключения от сервера' : '';
|
||||
$('#identity-import').title = S.conn.state !== 'disconnected' ? t('ui.available.after.disconnecting.from.the.server') : '';
|
||||
}
|
||||
|
||||
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));
|
||||
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}%`);
|
||||
setText($('#voice-volume-value'), () => `${prefs.voiceVolume}%`);
|
||||
}
|
||||
|
||||
export async function renderDiagnostics() {
|
||||
const info = await tp.getAppInfo();
|
||||
const rows = [
|
||||
['TeamsPeach', info.appVersion],
|
||||
['Ядро', info.coreVersion ?? 'не запущено'],
|
||||
[t('ui.core'), info.coreVersion ?? t('ui.not.running')],
|
||||
['Electron', info.electron],
|
||||
['Chromium', info.chrome],
|
||||
['Платформа', `${info.platform} ${info.arch}`],
|
||||
['Исполняемый файл ядра', info.coreBinary ?? '—'],
|
||||
['Каталог данных', info.dataDir],
|
||||
[t('ui.platform'), `${info.platform} ${info.arch}`],
|
||||
[t('ui.core.executable'), info.coreBinary ?? '—'],
|
||||
[t('ui.data.folder'), 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 })));
|
||||
@@ -198,7 +217,7 @@ const IGNORED = new Set(['video/rtx', 'video/red', 'video/ulpfec', 'video/flexfe
|
||||
|
||||
export function videoCodecs() {
|
||||
const caps = typeof RTCRtpReceiver.getCapabilities === 'function' ? RTCRtpReceiver.getCapabilities('video') : null;
|
||||
if (!caps) return ['Возможности приёма недоступны'];
|
||||
if (!caps) return [t('ui.receive.capabilities.unavailable')];
|
||||
return caps.codecs.filter((c) => !IGNORED.has(c.mimeType.toLowerCase())).map((c) => `${c.mimeType.replace('video/', '')}${c.sdpFmtpLine ? ` ${c.sdpFmtpLine}` : ''}`);
|
||||
}
|
||||
|
||||
@@ -232,7 +251,7 @@ export async function close() {
|
||||
const btn = $('#mic-test');
|
||||
if (btn.getAttribute('aria-pressed') === 'true') {
|
||||
btn.setAttribute('aria-pressed', 'false');
|
||||
setText(btn, 'Проверить микрофон');
|
||||
setText(btn, () => t('ui.test.microphone'));
|
||||
await voice.setMicTest(false);
|
||||
}
|
||||
}
|
||||
@@ -240,15 +259,15 @@ export async function close() {
|
||||
// app.getGPUFeatureStatus().video_decode describes what the engine is allowed/able to use,
|
||||
// not which decoder is decoding right now; that comes only from a live RTCPeerConnection.
|
||||
const GPU_STATE = {
|
||||
enabled: 'аппаратное декодирование разрешено и доступно движку',
|
||||
enabled_on: 'аппаратное декодирование разрешено и доступно движку',
|
||||
enabled_force: 'аппаратное декодирование принудительно разрешено',
|
||||
disabled_software: 'аппаратное декодирование отключено, движок будет декодировать программно',
|
||||
disabled_off: 'аппаратное декодирование отключено',
|
||||
disabled_off_ok: 'аппаратное декодирование отключено',
|
||||
unavailable_software: 'аппаратное декодирование недоступно на этом устройстве, будет программное',
|
||||
unavailable_off: 'аппаратное декодирование недоступно',
|
||||
unavailable_off_ok: 'аппаратное декодирование недоступно',
|
||||
get enabled() { return t('ui.hardware.decoding.is.allowed.and.available.to'); },
|
||||
get enabled_on() { return t('ui.hardware.decoding.is.allowed.and.available.to'); },
|
||||
get enabled_force() { return t('ui.hardware.decoding.is.force.enabled'); },
|
||||
get disabled_software() { return t('ui.hardware.decoding.is.disabled.the.engine.will'); },
|
||||
get disabled_off() { return t('ui.hardware.decoding.is.disabled'); },
|
||||
get disabled_off_ok() { return t('ui.hardware.decoding.is.disabled'); },
|
||||
get unavailable_software() { return t('ui.hardware.decoding.is.unavailable.on.this.device'); },
|
||||
get unavailable_off() { return t('ui.hardware.decoding.is.unavailable'); },
|
||||
get unavailable_off_ok() { return t('ui.hardware.decoding.is.unavailable'); },
|
||||
};
|
||||
|
||||
/** Saved preference vs what this run was started with vs what the engine reports vs the live decoder. */
|
||||
@@ -258,13 +277,14 @@ export async function renderVideo() {
|
||||
$('#opt-hwdec').checked = saved;
|
||||
$('#hwdec-restart').hidden = !status || saved === status.hardwareDecodeAtLaunch;
|
||||
if (status) {
|
||||
const gpu = status.gpu?.video_decode ?? 'неизвестно';
|
||||
setText($('#hwdec-status'), `В этом запуске: ${status.hardwareDecodeAtLaunch ? 'разрешено' : 'запрещено (флаг disable-accelerated-video-decode)'}. Движок Chromium: ${GPU_STATE[gpu] ?? gpu}.`);
|
||||
$('#hwdec-status').dataset.policy = status.hardwareDecodeAtLaunch ? 'allowed' : 'forbidden';
|
||||
const gpu = status.gpu?.video_decode ?? t('ui.unknown');
|
||||
setText($('#hwdec-status'), () => t('message.this.run.p0.chromium.engine.p1', { p0: status.hardwareDecodeAtLaunch ? t('ui.allowed') : t('ui.disabled.disable.accelerated.video.decode.flag'), p1: GPU_STATE[gpu] ?? gpu }));
|
||||
}
|
||||
const d = watchStats.decoder;
|
||||
const live = watchStats.state === 'live' || watchStats.state === 'unstable';
|
||||
const efficiency = watchStats.powerEfficientDecoder === true ? ' (энергоэффективный)' : watchStats.powerEfficientDecoder === false ? ' (не энергоэффективный)' : '';
|
||||
setText($('#decoder-last'), d
|
||||
? `${live ? 'Текущая трансляция' : 'При последнем просмотре'}: ${watchStats.codec || '—'}, декодер «${d}»${efficiency}.`
|
||||
: 'Какой декодер реально работает, видно только во время просмотра трансляции.');
|
||||
const efficiency = watchStats.powerEfficientDecoder === true ? t('ui.power.efficient') : watchStats.powerEfficientDecoder === false ? t('ui.not.power.efficient') : '';
|
||||
setText($('#decoder-last'), () => d
|
||||
? t('message.p0.p1.decoder.p2.p3', { p0: live ? t('ui.current.stream') : t('ui.last.stream'), p1: watchStats.codec || '—', p2: d, p3: efficiency })
|
||||
: t('ui.the.actual.decoder.is.reported.only.while'));
|
||||
}
|
||||
+46
-47
@@ -1,45 +1,48 @@
|
||||
import { t } from './i18n.js';
|
||||
// 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: 'Действие запрещено',
|
||||
get bad_request() { return t('ui.invalid.request'); },
|
||||
get unknown_command() { return t('ui.command.not.supported'); },
|
||||
get profile_missing() { return t('ui.profile.not.created.yet'); },
|
||||
get profile_exists() { return t('ui.profile.already.exists'); },
|
||||
get identity_corrupt() { return t('ui.the.identity.file.is.corrupted.restore.a'); },
|
||||
get profile_corrupt() { return t('ui.profile.file.corrupted'); },
|
||||
get invalid_nickname() { return t('ui.nickname.must.contain.3.30.characters.with'); },
|
||||
get nickname_required() { return t('ui.set.a.nickname.first'); },
|
||||
get not_connected() { return t('ui.not.connected.to.a.server'); },
|
||||
get already_connected() { return t('ui.already.connected'); },
|
||||
get connect_failed() { return t('ui.could.not.connect'); },
|
||||
get server_error() { return t('ui.the.server.rejected.the.action'); },
|
||||
get audio_overflow() { return t('ui.microphone.queue.overflow.some.audio.was.dropped'); },
|
||||
get audio_muted() { return t('ui.microphone.or.audio.is.muted.voice.is'); },
|
||||
get audio_codec() { return t('ui.opus.codec.error'); },
|
||||
get audio_codec_unsupported() { return t('ui.this.channel.uses.a.legacy.codec.speex'); },
|
||||
get rename_not_persisted() { return t('ui.the.server.accepted.the.nickname.but.saving'); },
|
||||
get io() { return t('ui.could.not.access.the.data.folder'); },
|
||||
get internal() { return t('ui.internal.core.error'); },
|
||||
get timeout() { return t('ui.the.core.did.not.respond.in.time'); },
|
||||
get core_unavailable() { return t('ui.the.core.is.not.running'); },
|
||||
get core_exited() { return t('ui.the.core.stopped2'); },
|
||||
get core_missing() { return t('ui.core.executable.not.found'); },
|
||||
get connected() { return t('ui.disconnect.from.the.server.first2'); },
|
||||
get forbidden() { return t('ui.action.forbidden'); },
|
||||
get device_fallback() { return t('error.device_fallback'); },
|
||||
get device_lost() { return t('error.device_lost'); },
|
||||
get capture() { return t('error.capture'); },
|
||||
};
|
||||
|
||||
/** "Код: сообщение сервера" with the TeamSpeak error id when present. */
|
||||
/** Localized code explanation with untouched server/OS diagnostic detail. */
|
||||
export function errorText(error) {
|
||||
if (!error) return 'Неизвестная ошибка';
|
||||
const base = ERROR_TEXT[error.code] ?? error.message ?? error.code ?? 'Ошибка';
|
||||
if (!error) return t('ui.no.error.details.were.provided');
|
||||
const base = ERROR_TEXT[error.code] ?? t('ui.error2');
|
||||
const ts = error.ts_error;
|
||||
if (ts && (ts.message || ts.name)) {
|
||||
const perm = ts.missing_permission !== undefined && ts.missing_permission !== null ? `, не хватает права ${ts.missing_permission}` : '';
|
||||
const perm = ts.missing_permission !== undefined && ts.missing_permission !== null ? t('message.missing.permission.p0', { p0: 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;
|
||||
if (error.message && error.message !== base) return `${base}: ${error.message}`;
|
||||
return ERROR_TEXT[error.code] ?? t('error.detail', { code: error.code ?? 'no_code', detail: error.detail ?? error.message ?? t('ui.no.error.details.were.provided') });
|
||||
}
|
||||
|
||||
const BB_TAGS = /\[\/?(?:b|i|u|s|url(?:=[^\]]*)?|color(?:=[^\]]*)?|size(?:=[^\]]*)?|center|left|right|img|quote|code|list|\*|hr|table|tr|td|th)\]/gi;
|
||||
@@ -66,22 +69,22 @@ export function shortUid(uid) {
|
||||
}
|
||||
|
||||
const KEY_NAMES = {
|
||||
Space: 'Пробел',
|
||||
get Space() { return t('ui.space'); },
|
||||
Backquote: '`',
|
||||
ControlLeft: 'Левый Ctrl',
|
||||
ControlRight: 'Правый Ctrl',
|
||||
AltLeft: 'Левый Alt',
|
||||
AltRight: 'Правый Alt',
|
||||
ShiftLeft: 'Левый Shift',
|
||||
ShiftRight: 'Правый Shift',
|
||||
MetaLeft: 'Левый Super',
|
||||
MetaRight: 'Правый Super',
|
||||
get ControlLeft() { return t('ui.left.ctrl'); },
|
||||
get ControlRight() { return t('ui.right.ctrl'); },
|
||||
get AltLeft() { return t('ui.left.alt'); },
|
||||
get AltRight() { return t('ui.right.alt'); },
|
||||
get ShiftLeft() { return t('ui.left.shift'); },
|
||||
get ShiftRight() { return t('ui.right.shift'); },
|
||||
get MetaLeft() { return t('ui.left.super'); },
|
||||
get MetaRight() { return t('ui.right.super'); },
|
||||
CapsLock: 'Caps Lock',
|
||||
Tab: 'Tab',
|
||||
};
|
||||
|
||||
export function keyLabel(code) {
|
||||
if (!code) return 'не назначена';
|
||||
if (!code) return t('ui.not.assigned');
|
||||
if (KEY_NAMES[code]) return KEY_NAMES[code];
|
||||
if (code.startsWith('Key')) return code.slice(3);
|
||||
if (code.startsWith('Digit')) return code.slice(5);
|
||||
@@ -90,9 +93,5 @@ export function keyLabel(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} участников`;
|
||||
return t('members.count', { count: n });
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from './i18n.js';
|
||||
import { $, h, icon } from './dom.js';
|
||||
|
||||
const MAX_TOASTS = 4;
|
||||
@@ -5,7 +6,7 @@ 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 close = h('button', { class: 'icon-btn', type: 'button', 'aria-label': t('ui.dismiss.notification'), 'data-i18n-aria-label': 'ui.dismiss.notification' }, 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);
|
||||
|
||||
+38
-36
@@ -1,3 +1,4 @@
|
||||
import { t, getLanguage } from './i18n.js';
|
||||
// Channel tree with members (TeamSpeak order): talking state, mute flags, server-configured group
|
||||
// labels and icons, channel icons/banners, avatars and stream badges — all from real server data.
|
||||
import { $, h, icon, reconcile, setText } from './dom.js';
|
||||
@@ -16,7 +17,7 @@ export function initTree(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' });
|
||||
return a.nickname.localeCompare(b.nickname, getLanguage(), { sensitivity: 'base' });
|
||||
}
|
||||
|
||||
export function renderTree() {
|
||||
@@ -25,7 +26,7 @@ export function renderTree() {
|
||||
if (!isConnected()) {
|
||||
list.replaceChildren();
|
||||
empty.hidden = false;
|
||||
setText(empty, S.conn.state === 'connecting' ? 'Подключение…' : 'Каналы появятся после подключения к серверу.');
|
||||
setText(empty, () => S.conn.state === 'connecting' ? t('ui.connecting2') : t('ui.channels.will.appear.after.you.connect.to'));
|
||||
pendingPasswordCid = null;
|
||||
return;
|
||||
}
|
||||
@@ -77,11 +78,12 @@ function updateRow(el, item) {
|
||||
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);
|
||||
setText(el, () => text);
|
||||
break;
|
||||
}
|
||||
case 'password':
|
||||
el.style.setProperty('--depth', String(item.ch.depth));
|
||||
el.querySelector('input').setAttribute('aria-label', t('message.password.for.channel.p0', { p0: item.ch.name }));
|
||||
break;
|
||||
case 'member':
|
||||
updateMemberRow(el, item.cl, item.depth);
|
||||
@@ -115,15 +117,15 @@ function updateChannelRow(li, ch, count) {
|
||||
const btn = li.firstElementChild;
|
||||
const [ic, label, chIcon, meta] = btn.children;
|
||||
ic.firstElementChild.setAttribute('href', ch.has_password ? '#i-lock' : '#i-channel');
|
||||
setText(label, ch.name);
|
||||
setText(label, () => ch.name);
|
||||
const max = ch.max_clients;
|
||||
setText(meta, max !== null && max !== undefined && max >= 0 && count > 0 ? `${count}/${max}` : max === 0 ? 'закрыт' : '');
|
||||
setText(meta, () => max !== null && max !== undefined && max >= 0 && count > 0 ? `${count}/${max}` : max === 0 ? t('ui.closed') : '');
|
||||
const parts = [ch.name];
|
||||
if (ch.has_password) parts.push('с паролем');
|
||||
if (ch.has_password) parts.push(t('ui.password.protected'));
|
||||
parts.push(pluralMembers(count));
|
||||
if (current) parts.push('вы здесь');
|
||||
if (current) parts.push(t('ui.you.are.here'));
|
||||
btn.setAttribute('aria-label', parts.join(', '));
|
||||
btn.title = ch.topic ? ch.topic : current ? 'Вы в этом канале' : 'Перейти в канал';
|
||||
btn.title = ch.topic ? ch.topic : current ? t('ui.you.are.in.this.channel') : t('ui.join.channel');
|
||||
if (current) btn.setAttribute('aria-current', 'location');
|
||||
else btn.removeAttribute('aria-current');
|
||||
|
||||
@@ -163,14 +165,14 @@ async function joinChannel(cid) {
|
||||
try {
|
||||
await call('join_channel', { channel_id: cid });
|
||||
} catch (err) {
|
||||
toast(`Не удалось перейти в «${ch.name}»: ${errorText(err)}`, 'error');
|
||||
toast(() => t('message.could.not.join.p0.p1', { p0: ch.name, p1: 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 input = h('input', { type: 'password', autocomplete: 'off', 'aria-label': t('message.password.for.channel.p0', { p0: ch.name }), placeholder: t('ui.channel.password'), 'data-i18n-placeholder': 'ui.channel.password' });
|
||||
const cancel = h('button', { class: 'btn btn-ghost', type: 'button', 'data-i18n': 'ui.cancel' }, t('ui.cancel'));
|
||||
const form = h('form', { novalidate: true }, input, h('button', { class: 'btn btn-primary', type: 'submit', 'data-i18n': 'ui.join' }, t('ui.join')), cancel);
|
||||
const li = h('li', { class: 'tree-row password-row' }, form);
|
||||
const close = () => {
|
||||
pendingPasswordCid = null;
|
||||
@@ -187,7 +189,7 @@ function createPasswordRow(ch) {
|
||||
close();
|
||||
} catch (err) {
|
||||
input.setAttribute('aria-invalid', 'true');
|
||||
toast(`Не удалось войти в «${ch.name}»: ${errorText(err)}`, 'error');
|
||||
toast(() => t('message.could.not.enter.p0.p1', { p0: ch.name, p1: errorText(err) }), 'error');
|
||||
input.select();
|
||||
}
|
||||
});
|
||||
@@ -233,41 +235,41 @@ function updateMemberRow(li, cl, depth) {
|
||||
li.dataset.talking = String(talking);
|
||||
const btn = li.firstElementChild;
|
||||
const [avatar, before, label, after, tag, flags, badges] = btn.children;
|
||||
setText(label, cl.nickname);
|
||||
setText(tag, cl.is_self ? 'вы' : '');
|
||||
setText(label, () => cl.nickname);
|
||||
setText(tag, () => cl.is_self ? t('ui.you') : '');
|
||||
|
||||
// Group names appear next to the nickname exactly where each group's name_mode puts them.
|
||||
const { server: groups, channel: cgroup } = groupsOf(cl);
|
||||
const named = cgroup ? [...groups, cgroup] : groups;
|
||||
const beforeText = named.filter((g) => g.name_mode === 'before').map((g) => g.name).join(' · ');
|
||||
const afterText = named.filter((g) => g.name_mode === 'after').map((g) => g.name).join(' · ');
|
||||
setText(before, beforeText);
|
||||
setText(before, () => beforeText);
|
||||
before.title = beforeText;
|
||||
before.hidden = !beforeText;
|
||||
setText(after, afterText);
|
||||
setText(after, () => afterText);
|
||||
after.title = afterText;
|
||||
after.hidden = !afterText;
|
||||
|
||||
const flagIcons = [];
|
||||
const states = [];
|
||||
if (cl.output_muted) {
|
||||
flagIcons.push(['headphones-off', 'flag-muted', 'Звук выключен']);
|
||||
states.push('звук выключен');
|
||||
flagIcons.push(['headphones-off', 'flag-muted', t('ui.audio.muted')]);
|
||||
states.push(t('ui.audio.muted2'));
|
||||
} else if (cl.input_muted) {
|
||||
flagIcons.push(['mic-off', 'flag-muted', 'Микрофон выключен']);
|
||||
states.push('микрофон выключен');
|
||||
flagIcons.push(['mic-off', 'flag-muted', t('ui.microphone.muted')]);
|
||||
states.push(t('ui.microphone.muted2'));
|
||||
}
|
||||
if (!cl.input_hardware && !cl.input_muted) {
|
||||
flagIcons.push(['mic-off', '', 'Нет микрофона']);
|
||||
states.push('нет микрофона');
|
||||
flagIcons.push(['mic-off', '', t('ui.no.microphone')]);
|
||||
states.push(t('ui.no.microphone2'));
|
||||
}
|
||||
if (cl.away) {
|
||||
flagIcons.push(['moon', '', cl.away_message ? `Отошёл: ${cl.away_message}` : 'Отошёл']);
|
||||
states.push(cl.away_message ? `отошёл: ${cl.away_message}` : 'отошёл');
|
||||
flagIcons.push(['moon', '', cl.away_message ? t('message.away.p0', { p0: cl.away_message }) : t('ui.away')]);
|
||||
states.push(cl.away_message ? t('message.away.p02', { p0: cl.away_message }) : t('ui.away2'));
|
||||
}
|
||||
if (cl.is_recording) {
|
||||
flagIcons.push(['record', 'flag-rec', 'Записывает разговор']);
|
||||
states.push('записывает');
|
||||
flagIcons.push(['record', 'flag-rec', t('ui.recording.the.conversation')]);
|
||||
states.push(t('ui.recording'));
|
||||
}
|
||||
const flagKey = flagIcons.map((f) => f.join(':')).join('|');
|
||||
if (flags.dataset.sig !== flagKey) {
|
||||
@@ -277,12 +279,12 @@ function updateMemberRow(li, cl, depth) {
|
||||
|
||||
// Group icons: custom files from the server; built-in ids have no file, shown as a neutral named badge.
|
||||
const iconGroups = named.filter((g) => g.icon_id);
|
||||
const badgeKey = `${iconGroups.map((g) => `${g.id}:${g.icon_id}`).join(',')}|${cl.country ?? ''}`;
|
||||
const badgeKey = `${getLanguage()}|${iconGroups.map((g) => `${g.id}:${g.icon_id}`).join(',')}|${cl.country ?? ''}`;
|
||||
if (badges.dataset.sig !== badgeKey) {
|
||||
badges.dataset.sig = badgeKey;
|
||||
badges.replaceChildren(
|
||||
...iconGroups.map((g) => groupBadge(g)),
|
||||
...(cl.country ? [h('span', { class: 'country', title: `Страна: ${cl.country}`, text: cl.country })] : []),
|
||||
...(cl.country ? [h('span', { class: 'country', title: t('message.country.p0', { p0: cl.country }), text: cl.country })] : []),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -298,16 +300,16 @@ function updateMemberRow(li, cl, depth) {
|
||||
});
|
||||
}
|
||||
|
||||
if (talking) states.unshift('говорит');
|
||||
if (talking) states.unshift(t('ui.talking'));
|
||||
const groupNames = groups.map((g) => g.name);
|
||||
btn.setAttribute('aria-label', `${cl.nickname}${cl.is_self ? ' (вы)' : ''}${groupNames.length ? `, группы: ${groupNames.join(', ')}` : ''}${states.length ? `, ${states.join(', ')}` : ''}${cl.is_self ? '. Открыть настройки профиля' : '. Написать личное сообщение'}`);
|
||||
btn.title = [cl.description ? `Описание: ${cl.description}` : '', groupNames.length ? `Группы: ${groupNames.join(', ')}` : '', cl.is_self ? 'Настройки профиля' : 'Написать личное сообщение'].filter(Boolean).join('\n');
|
||||
btn.setAttribute('aria-label', `${cl.nickname}${cl.is_self ? t('ui.you2') : ''}${groupNames.length ? t('message.groups.p0', { p0: groupNames.join(', ') }) : ''}${states.length ? `, ${states.join(', ')}` : ''}${cl.is_self ? t('ui.open.profile.settings') : t('ui.send.a.private.message')}`);
|
||||
btn.title = [cl.description ? t('message.description.p0', { p0: cl.description }) : '', groupNames.length ? t('message.groups.p02', { p0: groupNames.join(', ') }) : '', cl.is_self ? t('ui.profile.settings') : t('ui.send.a.private.message2')].filter(Boolean).join('\n');
|
||||
|
||||
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 = h('button', { class: 'watch-btn', type: 'button' }, icon('monitor'), h('span', { text: t('ui.watch') }));
|
||||
watch.addEventListener('click', () => {
|
||||
const s = hooks.streamOf(Number(li.dataset.clid));
|
||||
if (s) hooks.toggleWatch(s);
|
||||
@@ -316,9 +318,9 @@ function updateMemberRow(li, cl, depth) {
|
||||
}
|
||||
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 || 'Трансляция экрана';
|
||||
setText(watch.lastElementChild, () => watching ? t('ui.watching') : t('ui.watch'));
|
||||
watch.setAttribute('aria-label', t('message.p0.p1.p2', { p0: watching ? t('ui.stop.watching') : t('ui.watch'), p1: cl.nickname, p2: stream.name ? `: ${stream.name}` : '' }));
|
||||
watch.title = stream.name || t('ui.screen.share');
|
||||
} else if (watch) {
|
||||
watch.remove();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
// Settings → Information → Updates. The main-process update service owns every decision (source, channel,
|
||||
// platform, verification) and sends codes, never user text; this module only renders that state in the
|
||||
// current language and forwards explicit user actions.
|
||||
import { $, setText } from './dom.js';
|
||||
import { tp } from './core.js';
|
||||
import { toast } from './toast.js';
|
||||
import { t, getLanguage, hasTranslation, onLanguageChange } from './i18n.js';
|
||||
|
||||
let state = null;
|
||||
let announced = null; // version already announced by a toast in this run
|
||||
let initialized = false;
|
||||
|
||||
/** Localized text for an updater code (`update.<group>.<code>`); optional params default to empty. */
|
||||
function codeText(group, code, params) {
|
||||
const key = `update.${group}.${code}`;
|
||||
if (!code || !hasTranslation(key)) return String(code ?? '');
|
||||
try {
|
||||
return t(key, { tag: '', file: null, detail: '', target: '', ...params });
|
||||
} catch {
|
||||
return String(code);
|
||||
}
|
||||
}
|
||||
|
||||
const when = (iso) => new Date(iso).toLocaleString(getLanguage(), { dateStyle: 'short', timeStyle: 'short' });
|
||||
|
||||
function statusText(s) {
|
||||
const version = s.available?.version;
|
||||
switch (s.phase) {
|
||||
case 'disabled':
|
||||
return t('update.ui.status.disabled', { reason: codeText('disabled', s.disabledCode, s.disabledParams ?? {}) });
|
||||
case 'idle':
|
||||
return t('update.ui.status.idle');
|
||||
case 'checking':
|
||||
return t('update.ui.status.checking');
|
||||
case 'up-to-date': {
|
||||
const base = s.lastCheckedAt ? t('update.ui.status.upToDateChecked', { time: when(s.lastCheckedAt) }) : t('update.ui.status.upToDate');
|
||||
return s.newerPreview ? `${base} ${t('update.ui.status.newerPreview', { version: s.newerPreview })}` : base;
|
||||
}
|
||||
case 'available': {
|
||||
const base = t(s.available?.preview ? 'update.ui.status.availablePreview' : 'update.ui.status.available', { version });
|
||||
return s.mode === 'manual' ? `${base} ${t('update.ui.status.manual')}` : base;
|
||||
}
|
||||
case 'deferred':
|
||||
return t('update.ui.status.deferred', { version });
|
||||
case 'downloading':
|
||||
return t('update.ui.status.downloading', { version, percent: Math.round(s.progress?.percent ?? 0) });
|
||||
case 'downloaded':
|
||||
return t('update.ui.status.downloaded', { version });
|
||||
case 'installing':
|
||||
return t('update.ui.status.installing');
|
||||
case 'error':
|
||||
return t('update.ui.status.error', { message: codeText('error', s.error?.code, s.error?.params ?? {}) });
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function render() {
|
||||
if (!state) return;
|
||||
const s = state;
|
||||
$('#update-channel').value = s.channel;
|
||||
$('#update-channel').disabled = s.phase === 'disabled';
|
||||
let text = statusText(s);
|
||||
const skipped = s.newerWithoutBuild?.[0];
|
||||
if (skipped && s.phase !== 'disabled') {
|
||||
text += ` ${t('update.ui.status.skipped', { version: skipped.version, reason: codeText('skip', skipped.code, { version: skipped.version, ...skipped.params }) })}`;
|
||||
}
|
||||
setText($('#update-status'), text);
|
||||
const progress = $('#update-progress');
|
||||
progress.hidden = s.phase !== 'downloading';
|
||||
progress.value = Math.round(s.progress?.percent ?? 0);
|
||||
|
||||
const busy = s.phase === 'checking' || s.phase === 'downloading' || s.phase === 'installing';
|
||||
const check = $('#update-check');
|
||||
check.hidden = s.phase === 'disabled';
|
||||
check.disabled = busy;
|
||||
setText(check, t(s.phase === 'error' ? 'update.ui.retry' : 'update.ui.check'));
|
||||
const download = $('#update-download');
|
||||
download.hidden = !(s.mode === 'auto' && (s.phase === 'available' || s.phase === 'deferred'));
|
||||
setText(download, t(s.phase === 'deferred' ? 'update.ui.downloadNow' : 'update.ui.download'));
|
||||
$('#update-install').hidden = !(s.mode === 'auto' && s.phase === 'downloaded');
|
||||
$('#update-open').hidden = !s.available;
|
||||
if (s.phase !== 'downloaded') $('#update-confirm').hidden = true;
|
||||
|
||||
if (s.available && s.available.version !== announced && (s.phase === 'available' || s.phase === 'deferred' || s.phase === 'downloaded')) {
|
||||
const version = s.available.version;
|
||||
announced = version;
|
||||
toast(() => t('update.ui.toast.available', { version }));
|
||||
}
|
||||
}
|
||||
|
||||
function askToInterrupt() {
|
||||
$('#update-confirm').hidden = false;
|
||||
$('#update-confirm-yes').focus();
|
||||
}
|
||||
|
||||
async function install(confirmInterrupt) {
|
||||
const r = await tp.installUpdate(confirmInterrupt);
|
||||
if (!r || r.ok) return;
|
||||
if (r.code === 'session-active') askToInterrupt();
|
||||
else toast(() => (r.code ? codeText('install', r.code, r.params ?? {}) : t('update.ui.installFailed')), 'error');
|
||||
}
|
||||
|
||||
export async function initUpdates() {
|
||||
if (initialized) return;
|
||||
initialized = true;
|
||||
tp.onUpdateState((next) => {
|
||||
state = next;
|
||||
render();
|
||||
});
|
||||
onLanguageChange(render);
|
||||
$('#update-check').addEventListener('click', () => tp.checkForUpdates());
|
||||
$('#update-download').addEventListener('click', () => tp.downloadUpdate());
|
||||
$('#update-open').addEventListener('click', () => tp.openUpdateRelease());
|
||||
$('#update-install').addEventListener('click', () => (state?.sessionActive ? askToInterrupt() : install(false)));
|
||||
$('#update-confirm-yes').addEventListener('click', () => install(true));
|
||||
$('#update-confirm-no').addEventListener('click', () => {
|
||||
$('#update-confirm').hidden = true;
|
||||
$('#update-install').focus();
|
||||
});
|
||||
$('#update-channel').addEventListener('change', async (e) => {
|
||||
const next = await tp.setUpdateChannel(e.target.value);
|
||||
if (next) {
|
||||
state = next;
|
||||
render();
|
||||
}
|
||||
});
|
||||
const initial = await tp.getUpdateState();
|
||||
if (initial && !state) {
|
||||
state = initial;
|
||||
render();
|
||||
}
|
||||
}
|
||||
+44
-35
@@ -6,7 +6,8 @@ import { tp, log } from './core.js';
|
||||
import { AudioEngine } from './audio/engine.js';
|
||||
import { buildDeviceOptions } from './audio/devices.js';
|
||||
import { toast } from './toast.js';
|
||||
import { keyLabel } from './text.js';
|
||||
import { errorText, keyLabel } from './text.js';
|
||||
import { t } from './i18n.js';
|
||||
|
||||
export const voiceStats = { framesSent: 0, bursts: 0, framesPlayed: 0, level: 0 };
|
||||
|
||||
@@ -22,7 +23,7 @@ export function initVoice(h0) {
|
||||
hooks = { ...hooks, ...h0 };
|
||||
engine = new AudioEngine({
|
||||
onFrame,
|
||||
onError: (e) => toast(e.message, 'error'),
|
||||
onError: (e) => toast(() => errorText(e), 'error'),
|
||||
log,
|
||||
});
|
||||
tp.onAudio(({ pcm }) => {
|
||||
@@ -66,9 +67,9 @@ 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'));
|
||||
if (S.prefs.outputDeviceId) await engine.setOutputDevice(S.prefs.outputDeviceId).catch((err) => toast(() => t('message.output.device.unavailable.p0', { p0: err.message }), 'error'));
|
||||
} catch (err) {
|
||||
toast(`Звук недоступен: ${err.message}`, 'error');
|
||||
toast(() => t('message.audio.unavailable.p0', { p0: err.message }), 'error');
|
||||
log('error', `audio init failed: ${err.message}`);
|
||||
}
|
||||
}
|
||||
@@ -117,33 +118,37 @@ function drawMeter() {
|
||||
$('#mic-meter').style.width = `${pct.toFixed(0)}%`;
|
||||
}
|
||||
|
||||
/** Capture runs while connected (or during the settings mic test). */
|
||||
/**
|
||||
* Capture runs while connected (or during the settings mic test). Stopping also cancels a start that is
|
||||
* still waiting for the microphone, and a second call while one start is pending does not open another.
|
||||
*/
|
||||
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) {
|
||||
if (!want) {
|
||||
engine.stopCapture();
|
||||
if (sending) {
|
||||
tp.endAudio();
|
||||
sending = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (engine.capturing || engine.captureStarting) return;
|
||||
try {
|
||||
const label = await engine.startCapture({
|
||||
deviceId: S.prefs.inputDeviceId,
|
||||
echoCancellation: S.prefs.echoCancellation,
|
||||
noiseSuppression: S.prefs.noiseSuppression,
|
||||
autoGainControl: S.prefs.autoGainControl,
|
||||
});
|
||||
if (label !== null) refreshDevices();
|
||||
} catch (err) {
|
||||
toast(() => t('message.microphone.access.unavailable.p0', { p0: err.message || err.name }), 'error');
|
||||
log('error', `capture failed: ${err.name} ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function restartCapture() {
|
||||
if (!engine.capturing) return;
|
||||
if (!engine.capturing && !engine.captureStarting) return;
|
||||
engine.stopCapture();
|
||||
await syncCapture();
|
||||
}
|
||||
@@ -164,18 +169,22 @@ export function setVoiceVolume(pct) {
|
||||
|
||||
/** Saved input device for capture; used by Settings and by the microphone context menu. */
|
||||
export async function chooseInputDevice(deviceId) {
|
||||
await hooks.savePrefs({ inputDeviceId: deviceId });
|
||||
await restartCapture();
|
||||
const saved = await hooks.savePrefs({ inputDeviceId: deviceId });
|
||||
if (saved?.inputDeviceId === deviceId) await restartCapture(); // not saved: keep capturing from the stored device
|
||||
await refreshDevices();
|
||||
}
|
||||
|
||||
/** Saved output device for voice and stream audio; used by Settings and by the headphones menu. */
|
||||
export async function chooseOutputDevice(deviceId) {
|
||||
await hooks.savePrefs({ outputDeviceId: deviceId });
|
||||
const saved = await hooks.savePrefs({ outputDeviceId: deviceId });
|
||||
if (saved?.outputDeviceId !== deviceId) {
|
||||
await refreshDevices(); // not saved: audio stays on the stored device the UI shows
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await engine.setOutputDevice(deviceId);
|
||||
} catch (err) {
|
||||
toast(`Не удалось выбрать устройство вывода: ${err.message}`, 'error');
|
||||
toast(() => t('message.could.not.select.output.device.p0', { p0: err.message }), 'error');
|
||||
}
|
||||
hooks.onOutputChanged();
|
||||
await refreshDevices();
|
||||
@@ -201,7 +210,7 @@ export async function refreshDevices() {
|
||||
try {
|
||||
devices = await navigator.mediaDevices.enumerateDevices();
|
||||
} catch (err) {
|
||||
setText(status, `Не удалось получить список устройств: ${err.name}: ${err.message}`);
|
||||
setText(status, () => t('message.could.not.list.devices.p0.p1', { p0: err.name, p1: err.message }));
|
||||
log('warn', `enumerateDevices failed: ${err.name}`);
|
||||
return;
|
||||
}
|
||||
@@ -210,12 +219,12 @@ export async function refreshDevices() {
|
||||
fillSelect($('#input-device'), input.options, S.prefs.inputDeviceId);
|
||||
fillSelect($('#output-device'), output.options, S.prefs.outputDeviceId);
|
||||
let text;
|
||||
if (input.redacted || output.redacted) text = 'Движок скрыл список устройств (нет разрешения на доступ к звуковым устройствам). Доступно только системное устройство по умолчанию.';
|
||||
else if (input.physical === 0 && output.physical === 0) text = 'Звуковые устройства не найдены.';
|
||||
else if (input.physical === 0) text = `Микрофоны не найдены. Устройств вывода: ${output.physical}.`;
|
||||
else if (output.physical === 0) text = `Микрофонов: ${input.physical}. Устройства вывода не найдены.`;
|
||||
else text = `Найдено микрофонов: ${input.physical}, устройств вывода: ${output.physical}.`;
|
||||
setText(status, text);
|
||||
if (input.redacted || output.redacted) text = t('ui.the.engine.hid.the.device.list.audio');
|
||||
else if (input.physical === 0 && output.physical === 0) text = t('ui.no.audio.devices.found');
|
||||
else if (input.physical === 0) text = t('message.no.microphones.found.output.devices.p0', { p0: output.physical });
|
||||
else if (output.physical === 0) text = t('message.microphones.p0.no.output.devices.found', { p0: input.physical });
|
||||
else text = t('message.microphones.found.p0.output.devices.p1', { p0: input.physical, p1: output.physical });
|
||||
setText(status, () => text);
|
||||
lastChoices = { input, output, status: text };
|
||||
log('info', `devices: inputs=${input.physical} outputs=${output.physical} redacted=${input.redacted || output.redacted}`);
|
||||
}
|
||||
@@ -260,7 +269,7 @@ export function setPtt(down, source = 'key') {
|
||||
S.ptt = down;
|
||||
const btn = $('#btn-ptt');
|
||||
btn.setAttribute('aria-pressed', String(down));
|
||||
setText(btn, down ? 'Говорите…' : 'Удерживайте, чтобы говорить');
|
||||
setText(btn, () => down ? t('ui.talk.now') : t('ui.hold.to.talk'));
|
||||
if (S.prefs?.transmitMode === 'ptt') log('debug', `voice: ptt ${down ? 'down' : 'up'} source=${source} focused=${document.hasFocus()}`);
|
||||
hooks.onPtt(down);
|
||||
}
|
||||
@@ -274,10 +283,10 @@ export function capturePttKey() {
|
||||
|
||||
export function transmitHint() {
|
||||
if (!S.prefs) return '';
|
||||
if (S.prefs.transmitMode === 'open') return 'Открытый микрофон';
|
||||
if (S.prefs.transmitMode === 'open') return t('ui.open.microphone');
|
||||
// The key is read only from this window: say so whenever another window has the focus.
|
||||
if (!document.hasFocus()) return `Окно неактивно — ${keyLabel(S.prefs.pttCode)} не сработает`;
|
||||
return `Клавиша: ${keyLabel(S.prefs.pttCode)}`;
|
||||
if (!document.hasFocus()) return t('message.window.unfocused.p0.will.not.work', { p0: keyLabel(S.prefs.pttCode) });
|
||||
return t('message.key.p0', { p0: keyLabel(S.prefs.pttCode) });
|
||||
}
|
||||
|
||||
export function isCapturing() {
|
||||
|
||||
+41
-33
@@ -1,3 +1,4 @@
|
||||
import { t, onLanguageChange } from './i18n.js';
|
||||
// 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';
|
||||
@@ -39,6 +40,10 @@ export const watchStats = { state: 'idle', ...emptyStats() };
|
||||
|
||||
export function initWatch(h0) {
|
||||
hooks = { ...hooks, ...h0 };
|
||||
onLanguageChange(() => {
|
||||
applyVolume();
|
||||
updateStatsLine();
|
||||
});
|
||||
const video = $('#stream-video');
|
||||
const volume = $('#stream-volume');
|
||||
volume.addEventListener('input', () => applyVolume());
|
||||
@@ -51,7 +56,7 @@ export function initWatch(h0) {
|
||||
$('#stream-fullscreen').addEventListener('click', () => {
|
||||
const view = $('#stream-view');
|
||||
if (document.fullscreenElement) document.exitFullscreen();
|
||||
else view.requestFullscreen().catch((err) => toast(`Полноэкранный режим недоступен: ${err.message}`, 'error'));
|
||||
else view.requestFullscreen().catch((err) => toast(() => t('message.full.screen.unavailable.p0', { p0: err.message }), 'error'));
|
||||
});
|
||||
$('#stream-stop').addEventListener('click', () => stopWatching());
|
||||
video.addEventListener('resize', () => updateStatsLine());
|
||||
@@ -139,7 +144,7 @@ export function onStreamEvent(evt) {
|
||||
}
|
||||
if (name === 'notifysfuaccessinfo' && !sfuToastShown) {
|
||||
sfuToastShown = true;
|
||||
toast('Сервер передаёт трансляции через SFU. TeamsPeach поддерживает только прямые (P2P) трансляции TeamSpeak 6.', 'error');
|
||||
toast(() => t('ui.the.server.routes.streams.through.an.sfu'), 'error');
|
||||
}
|
||||
if (directory.handle(name, items)) hooks.onChange();
|
||||
}
|
||||
@@ -177,8 +182,9 @@ export function startWatching(stream, transport = coreTransport) {
|
||||
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 streamTitle = { ...current };
|
||||
setText($('#stream-title'), () => streamTitle.name ? `${streamTitle.nickname} — ${streamTitle.name}` : t('message.stream.from.p0', { p0: streamTitle.nickname }));
|
||||
setText($('#stream-stats'), () => '');
|
||||
|
||||
const own = new StreamViewerSession({
|
||||
streamId: stream.id,
|
||||
@@ -238,29 +244,29 @@ function teardownMedia() {
|
||||
}
|
||||
|
||||
const STATE_TEXT = {
|
||||
requesting: 'Запрос отправлен. Ждём ответа стримера…',
|
||||
connecting: 'Соединение со стримером…',
|
||||
get requesting() { return t('ui.request.sent.waiting.for.the.streamer'); },
|
||||
get connecting() { return t('ui.connecting.to.the.streamer'); },
|
||||
live: '',
|
||||
unstable: 'Связь со стримером прервалась, ждём восстановления…',
|
||||
declined: 'Стример отклонил запрос на просмотр.',
|
||||
removed: 'Стример убрал вас из зрителей.',
|
||||
get unstable() { return t('ui.the.stream.connection.was.interrupted.waiting.to'); },
|
||||
get declined() { return t('ui.the.streamer.declined.your.request.to.watch'); },
|
||||
get removed() { return t('ui.the.streamer.removed.you.from.the.viewers'); },
|
||||
stopped: '',
|
||||
};
|
||||
|
||||
function failureText(detail) {
|
||||
switch (detail) {
|
||||
case 'no_response': return 'Стример не ответил на запрос за 90 секунд.';
|
||||
case 'ice_failed': return 'Не удалось установить прямое соединение со стримером. Для просмотра нужен прямой сетевой доступ к его компьютеру (через STUN, без TURN).';
|
||||
default: return `Ошибка трансляции: ${detail}`;
|
||||
case 'no_response': return t('ui.the.streamer.did.not.respond.within.90');
|
||||
case 'ice_failed': return t('ui.could.not.connect.directly.to.the.streamer');
|
||||
default: return t('message.stream.error.p0', { p0: detail });
|
||||
}
|
||||
}
|
||||
|
||||
function endedText(detail) {
|
||||
switch (detail) {
|
||||
case 'stream_stopped': return 'Трансляция завершена.';
|
||||
case 'streamer_left': return 'Стример покинул сервер.';
|
||||
case 'disconnected': return 'Соединение с сервером потеряно.';
|
||||
default: return 'Трансляция завершена.';
|
||||
case 'stream_stopped': return t('ui.the.stream.ended');
|
||||
case 'streamer_left': return t('ui.the.streamer.left.the.server');
|
||||
case 'disconnected': return t('ui.connection.to.the.server.was.lost');
|
||||
default: return t('ui.the.stream.ended');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -268,15 +274,17 @@ 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 text = () => {
|
||||
if (state === 'failed') return failureText(detail);
|
||||
if (state === 'ended') return endedText(detail);
|
||||
if (state === 'unsupported') return t('ui.this.stream.uses.a.teamspeak.sfu.server');
|
||||
if (state === 'declined' && detail) return `${STATE_TEXT.declined} ${detail}`;
|
||||
if (state === 'live' && watchStats.framesDecoded === 0) return t('ui.connected.waiting.for.the.first.frame');
|
||||
return STATE_TEXT[state] ?? '';
|
||||
};
|
||||
setText($('#stream-overlay'), text);
|
||||
const terminal = ['declined', 'ended', 'removed', 'failed', 'unsupported'].includes(state);
|
||||
setText($('#stream-stop'), terminal ? 'Закрыть' : state === 'requesting' ? 'Отменить' : 'Прекратить просмотр');
|
||||
setText($('#stream-stop'), () => terminal ? t('ui.close') : state === 'requesting' ? t('ui.cancel2') : t('ui.stop.watching'));
|
||||
if (terminal) {
|
||||
teardownMedia();
|
||||
if (state !== 'ended' || detail !== 'disconnected') toast(text, state === 'ended' ? 'info' : 'error');
|
||||
@@ -337,7 +345,7 @@ async function pollStats() {
|
||||
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'), '');
|
||||
if (firstFrame && own.state === 'live') setText($('#stream-overlay'), () => '');
|
||||
const sig = `${watchStats.codec} ${watchStats.fmtp}`;
|
||||
if (codec && sig !== lastCodecLogged) {
|
||||
lastCodecLogged = sig;
|
||||
@@ -351,12 +359,12 @@ function updateStatsLine() {
|
||||
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 (watchStats.fps) parts.push(t('message.p0.fps', { p0: watchStats.fps }));
|
||||
if (session.state === 'live') {
|
||||
if (watchStats.streamAdvertisesAudio === false) parts.push('стример не передаёт звук');
|
||||
else if (watchStats.inboundAudioPackets > 0) parts.push('со звуком');
|
||||
if (watchStats.streamAdvertisesAudio === false) parts.push(t('ui.streamer.is.not.sending.audio'));
|
||||
else if (watchStats.inboundAudioPackets > 0) parts.push(t('ui.with.audio'));
|
||||
}
|
||||
setText($('#stream-stats'), parts.join(' · '));
|
||||
setText($('#stream-stats'), () => parts.join(' · '));
|
||||
}
|
||||
|
||||
export function applyVolume() {
|
||||
@@ -365,9 +373,9 @@ export function applyVolume() {
|
||||
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}%`);
|
||||
setText($('#stream-volume-value'), () => `${volume.value}%`);
|
||||
setIcon($('#stream-mute').firstElementChild, muted ? 'speaker-off' : 'speaker');
|
||||
$('#stream-mute').title = muted ? 'Включить звук трансляции' : 'Выключить звук трансляции';
|
||||
$('#stream-mute').title = muted ? t('ui.unmute.stream') : t('ui.mute.stream');
|
||||
}
|
||||
|
||||
let sinkChain = Promise.resolve();
|
||||
@@ -397,8 +405,8 @@ export function applySink() {
|
||||
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');
|
||||
const label = Array.from($('#output-device').options).find((o) => o.value === target)?.textContent || t('ui.selected.device');
|
||||
toast(() => t('message.could.not.route.stream.audio.to', { p0: label, p1: err.name }), 'error');
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
// TeamsPeach en message catalog. Keep keys and placeholders aligned across languages.
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const messages = Object.freeze({
|
||||
"ui.starting.core": "Starting core…",
|
||||
"ui.restarting.core": "Restarting core…",
|
||||
"ui.core.unavailable": "Core unavailable",
|
||||
"ui.restart.core": "Restart core",
|
||||
"ui.import.backup": "Import backup…",
|
||||
"ui.open.logs": "Open logs",
|
||||
"ui.what.should.we.call.you": "What should we call you?",
|
||||
"ui.everyone.on.the.server.sees.your.nickname": "Everyone on the server sees your nickname. You can change it later without changing your permanent identifier (UID).",
|
||||
"ui.nickname": "Nickname",
|
||||
"ui.3.30.characters": "3–30 characters.",
|
||||
"ui.continue": "Continue",
|
||||
"ui.teamspeach.will.create.a.cryptographic.identity.on": "TeamsPeach will create a cryptographic identity on this computer. No registration required.",
|
||||
"ui.restore.from.backup": "Restore from backup…",
|
||||
"ui.server": "Server",
|
||||
"ui.not.connected": "Not connected",
|
||||
"ui.not.connected2": "not connected",
|
||||
"ui.connecting": "connecting…",
|
||||
"ui.connected": "connected",
|
||||
"ui.disconnecting": "disconnecting…",
|
||||
"ui.saved.servers": "Saved servers",
|
||||
"ui.disconnect.from.server": "Disconnect from server",
|
||||
"ui.disconnect": "Disconnect",
|
||||
"ui.save.current.server": "Save current server",
|
||||
"ui.no.saved.servers.enter.an.address.in": "No saved servers. Enter an address in the connection form and select Save.",
|
||||
"ui.channels.will.appear.after.you.connect.to": "Channels will appear after you connect to a server.",
|
||||
"ui.channels.and.members": "Channels and members",
|
||||
"ui.settings.categories": "Settings categories",
|
||||
"ui.back.to.server": "Back to server",
|
||||
"ui.settings": "Settings",
|
||||
"ui.user": "User",
|
||||
"ui.identity": "Identity",
|
||||
"ui.servers": "Servers",
|
||||
"ui.application": "Application",
|
||||
"ui.appearance": "Appearance",
|
||||
"ui.audio": "Audio",
|
||||
"ui.video": "Video",
|
||||
"ui.keyboard": "Keyboard",
|
||||
"ui.information": "Information",
|
||||
"ui.microphone": "Microphone",
|
||||
"ui.mute.microphone": "Mute microphone",
|
||||
"ui.mute.audio": "Mute audio",
|
||||
"ui.connect.to.a.server": "Connect to a server",
|
||||
"ui.server.address": "Server address",
|
||||
"ui.address.or.address.9987": "address or address:9987",
|
||||
"ui.server.password": "Server password",
|
||||
"ui.optional": "optional",
|
||||
"ui.connect": "Connect",
|
||||
"ui.save": "Save",
|
||||
"ui.hold.to.talk": "Hold to talk",
|
||||
"ui.stream": "Stream",
|
||||
"ui.stream.audio": "Stream audio",
|
||||
"ui.mute.stream": "Mute stream",
|
||||
"ui.stream.volume": "Stream volume",
|
||||
"ui.full.screen": "Full screen",
|
||||
"ui.stop.watching": "Stop watching",
|
||||
"ui.chat": "Chat",
|
||||
"ui.chats": "Chats",
|
||||
"ui.message": "Message",
|
||||
"ui.send": "Send",
|
||||
"ui.send.enter": "Send (Enter)",
|
||||
"ui.unique.identifier": "Unique identifier",
|
||||
"ui.copy": "Copy",
|
||||
"ui.your.uid.is.your.public.key.fingerprint": "Your UID is your public key fingerprint. TeamSpeak servers use it to recognize you and assign permissions; changing your nickname does not change it.",
|
||||
"ui.export.to.file": "Export to file…",
|
||||
"ui.import.from.file": "Import from file…",
|
||||
"ui.the.file.contains.your.private.key.protect": "The file contains your private key. Protect it like a password: anyone with it can impersonate you.",
|
||||
"ui.details": "Details",
|
||||
"ui.nickname2": "Nickname",
|
||||
"ui.other.users.on.the.teamspeak.server.see": "Other users on the TeamSpeak server see your nickname. 3–30 characters.",
|
||||
"ui.no.saved.servers": "No saved servers.",
|
||||
"ui.add.server": "Add server",
|
||||
"ui.name": "Name",
|
||||
"ui.address": "Address",
|
||||
"ui.add": "Add",
|
||||
"ui.only.the.name.and.address.are.saved": "Only the name and address are saved. Server passwords are not stored; you will be asked when connecting. The same identity is used for every server.",
|
||||
"ui.theme": "Theme",
|
||||
"ui.color.theme": "Color theme",
|
||||
"ui.system": "System",
|
||||
"ui.dark": "Dark",
|
||||
"ui.light": "Light",
|
||||
"ui.devices": "Devices",
|
||||
"ui.test.microphone": "Test microphone",
|
||||
"ui.output.device": "Output device",
|
||||
"ui.volume": "Volume",
|
||||
"ui.voice.volume": "Voice volume",
|
||||
"ui.microphone.processing": "Microphone processing",
|
||||
"ui.noise.suppression": "Noise suppression",
|
||||
"ui.echo.cancellation": "Echo cancellation",
|
||||
"ui.automatic.gain.control": "Automatic gain control",
|
||||
"ui.hardware.acceleration": "Hardware acceleration",
|
||||
"ui.allow.hardware.video.decoding": "Allow hardware video decoding",
|
||||
"ui.the.engine.may.use.your.gpu.to": "The engine may use your GPU to decode streams. Applies after restarting.",
|
||||
"ui.this.change.takes.effect.after.restarting.teamspeach": "This change takes effect after restarting TeamsPeach.",
|
||||
"ui.restart.now": "Restart now",
|
||||
"ui.decoding.backend": "Decoding backend",
|
||||
"ui.automatic.chosen.by.chromium": "Automatic (chosen by Chromium)",
|
||||
"ui.details.status.codecs.and.backends": "Details: status, codecs and backends",
|
||||
"ui.policy": "Policy",
|
||||
"ui.current.reception": "Current reception",
|
||||
"ui.receive.codecs.reported.by.the.engine": "Receive codecs reported by the engine",
|
||||
"ui.unavailable.settings": "Unavailable settings",
|
||||
"ui.unlike.teamspeak.6.there.is.no.cisco": "Unlike TeamSpeak 6, there is no Cisco OpenH264 toggle or manual hardware backend selection (NVENC, AMF, QSV, etc.). TeamsPeach receives video through Chromium WebRTC, which has no decoder-selection API. Chromium decodes H.264 through FFmpeg; OpenH264 is only an encoder, and sending your own screen is not implemented in TeamsPeach.",
|
||||
"ui.voice.transmission": "Voice transmission",
|
||||
"ui.transmission.mode": "Transmission mode",
|
||||
"ui.push.to.talk": "Push to talk",
|
||||
"ui.open.microphone": "Open microphone",
|
||||
"ui.push.to.talk.key": "Push-to-talk key",
|
||||
"ui.assign": "Assign",
|
||||
"ui.the.key.works.while.teamspeach.is.focused": "The key works while TeamsPeach is focused. Letter keys do not trigger while typing. Press Esc to cancel assignment.",
|
||||
"ui.about": "About",
|
||||
"ui.updates": "Updates",
|
||||
"ui.update.channel": "Update channel",
|
||||
"ui.preview.releases": "Preview releases",
|
||||
"ui.stable.only": "Stable only",
|
||||
"ui.all.teamspeach.releases.are.currently.previews.the": "All TeamsPeach releases are currently previews. The Stable only channel will not offer them.",
|
||||
"ui.installing.closes.teamspeach.and.interrupts.your.current": "Installing closes TeamsPeach and interrupts your current call and stream.",
|
||||
"ui.interrupt.and.install": "Interrupt and install",
|
||||
"ui.cancel": "Cancel",
|
||||
"ui.check.for.updates": "Check for updates",
|
||||
"ui.download": "Download",
|
||||
"ui.install.and.restart": "Install and restart",
|
||||
"ui.open.release.page": "Open release page",
|
||||
"ui.server.banner": "Server banner",
|
||||
"ui.error": "error",
|
||||
"ui.teamspeach.core.not.found": "TeamsPeach core not found",
|
||||
"ui.the.core.executable.is.missing.build.it": "The core executable is missing. Build it (see README) or reinstall the app. Searched paths:",
|
||||
"ui.the.core.stopped": "The core stopped",
|
||||
"ui.profile.corrupted": "Profile corrupted",
|
||||
"ui.could.not.read.profile": "Could not read profile",
|
||||
"ui.nickname.must.contain.3.30.characters": "Nickname must contain 3–30 characters.",
|
||||
"ui.creating.identity": "Creating identity…",
|
||||
"ui.connecting2": "Connecting…",
|
||||
"ui.unmute.microphone": "Unmute microphone",
|
||||
"ui.microphone.muted": "Microphone muted",
|
||||
"ui.microphone.unmuted": "Microphone unmuted",
|
||||
"ui.unmute.audio": "Unmute audio",
|
||||
"ui.mute.audio.and.microphone": "Mute audio (and microphone)",
|
||||
"ui.audio.muted": "Audio muted",
|
||||
"ui.audio.unmuted": "Audio unmuted",
|
||||
"ui.audio.is.muted.you.cannot.hear.others": "Audio is muted: you cannot hear others or transmit voice.",
|
||||
"ui.microphone.is.muted": "Microphone is muted.",
|
||||
"ui.enter.a.server.address": "Enter a server address.",
|
||||
"ui.could.not.disconnect.from.the.current.server": "Could not disconnect from the current server",
|
||||
"ui.disconnected.from.server": "Disconnected from server",
|
||||
"ui.connection.lost.reconnecting": "Connection lost, reconnecting…",
|
||||
"ui.interface.startup.failed": "Interface startup failed",
|
||||
"ui.channel": "Channel",
|
||||
"ui.this.person.left.the.server": "This person left the server",
|
||||
"ui.message.exceeds.8.kib": "Message exceeds 8 KiB",
|
||||
"ui.close.private.chat": "Close private chat",
|
||||
"ui.current.channel.chat": "Current channel chat",
|
||||
"ui.server.wide.chat": "Server-wide chat",
|
||||
"ui.everyone.in.this.channel.can.see.its": "Everyone in this channel can see its messages.",
|
||||
"ui.everyone.connected.to.the.server.can.see": "Everyone connected to the server can see server messages.",
|
||||
"ui.private.conversation.only.the.recipient.can.see": "Private conversation. Only the recipient can see your messages.",
|
||||
"ui.message.the.whole.server": "Message the whole server",
|
||||
"ui.loading.devices": "Loading devices…",
|
||||
"ui.audio.settings": "Audio settings…",
|
||||
"ui.the.engine.hid.the.device.list.only": "The engine hid the device list: only the system device is available.",
|
||||
"ui.no.microphones.found": "No microphones found.",
|
||||
"ui.no.output.devices.found": "No output devices found.",
|
||||
"ui.enter.a.server.address.to.save.it": "Enter a server address to save it.",
|
||||
"ui.enter.an.address": "Enter an address.",
|
||||
"ui.server.added": "Server added.",
|
||||
"ui.this.address.is.already.saved": "This address is already saved",
|
||||
"ui.you.can.save.up.to.50.servers": "You can save up to 50 servers",
|
||||
"ui.connected2": "Connected",
|
||||
"ui.switch": "Switch",
|
||||
"ui.you.are.connected.to.this.server": "You are connected to this server",
|
||||
"ui.disconnect.from.the.current.server.and.connect": "Disconnect from the current server and connect to this one",
|
||||
"ui.edit": "Edit",
|
||||
"ui.confirm.deletion": "Confirm deletion?",
|
||||
"ui.delete": "Delete",
|
||||
"ui.server.name": "Server name",
|
||||
"ui.name.and.address.cannot.be.empty": "Name and address cannot be empty",
|
||||
"ui.this.address.is.already.saved.under.another": "This address is already saved under another name",
|
||||
"ui.this.is.already.your.nickname": "This is already your nickname.",
|
||||
"ui.saving": "Saving…",
|
||||
"ui.and.applied.on.the.server": " and applied on the server",
|
||||
"ui.saved": "Saved.",
|
||||
"ui.the.server.nickname.was.restored": "; the server nickname was restored",
|
||||
"ui.uid.copied": "UID copied",
|
||||
"ui.disconnect.from.the.server.first": "Disconnect from the server first.",
|
||||
"ui.press.a.key": "press a key…",
|
||||
"ui.stop.test": "Stop test",
|
||||
"ui.available.after.disconnecting.from.the.server": "Available after disconnecting from the server",
|
||||
"ui.core": "Core",
|
||||
"ui.not.running": "not running",
|
||||
"ui.platform": "Platform",
|
||||
"ui.core.executable": "Core executable",
|
||||
"ui.data.folder": "Data folder",
|
||||
"ui.receive.capabilities.unavailable": "Receive capabilities unavailable",
|
||||
"ui.hardware.decoding.is.allowed.and.available.to": "hardware decoding is allowed and available to the engine",
|
||||
"ui.hardware.decoding.is.force.enabled": "hardware decoding is force-enabled",
|
||||
"ui.hardware.decoding.is.disabled.the.engine.will": "hardware decoding is disabled; the engine will use software decoding",
|
||||
"ui.hardware.decoding.is.disabled": "hardware decoding is disabled",
|
||||
"ui.hardware.decoding.is.unavailable.on.this.device": "hardware decoding is unavailable on this device; software decoding will be used",
|
||||
"ui.hardware.decoding.is.unavailable": "hardware decoding is unavailable",
|
||||
"ui.unknown": "unknown",
|
||||
"ui.allowed": "allowed",
|
||||
"ui.disabled.disable.accelerated.video.decode.flag": "disabled (disable-accelerated-video-decode flag)",
|
||||
"ui.power.efficient": " (power-efficient)",
|
||||
"ui.not.power.efficient": " (not power-efficient)",
|
||||
"ui.current.stream": "Current stream",
|
||||
"ui.last.stream": "Last stream",
|
||||
"ui.the.actual.decoder.is.reported.only.while": "The actual decoder is reported only while watching a stream.",
|
||||
"ui.dismiss.notification": "Dismiss notification",
|
||||
"ui.closed": "closed",
|
||||
"ui.password.protected": "password protected",
|
||||
"ui.you.are.here": "you are here",
|
||||
"ui.you.are.in.this.channel": "You are in this channel",
|
||||
"ui.join.channel": "Join channel",
|
||||
"ui.channel.password": "Channel password",
|
||||
"ui.join": "Join",
|
||||
"ui.you": "you",
|
||||
"ui.audio.muted2": "audio muted",
|
||||
"ui.microphone.muted2": "microphone muted",
|
||||
"ui.no.microphone": "No microphone",
|
||||
"ui.no.microphone2": "no microphone",
|
||||
"ui.away": "Away",
|
||||
"ui.away2": "away",
|
||||
"ui.recording.the.conversation": "Recording the conversation",
|
||||
"ui.recording": "recording",
|
||||
"ui.talking": "talking",
|
||||
"ui.you2": " (you)",
|
||||
"ui.open.profile.settings": ". Open profile settings",
|
||||
"ui.send.a.private.message": ". Send a private message",
|
||||
"ui.profile.settings": "Profile settings",
|
||||
"ui.send.a.private.message2": "Send a private message",
|
||||
"ui.watch": "Watch",
|
||||
"ui.watching": "Watching",
|
||||
"ui.screen.share": "Screen share",
|
||||
"ui.the.engine.hid.the.device.list.audio": "The engine hid the device list (audio device permission is unavailable). Only the system default device is available.",
|
||||
"ui.no.audio.devices.found": "No audio devices found.",
|
||||
"ui.talk.now": "Talk now…",
|
||||
"ui.the.server.routes.streams.through.an.sfu": "The server routes streams through an SFU. TeamsPeach supports only direct (P2P) TeamSpeak 6 streams.",
|
||||
"ui.request.sent.waiting.for.the.streamer": "Request sent. Waiting for the streamer…",
|
||||
"ui.connecting.to.the.streamer": "Connecting to the streamer…",
|
||||
"ui.the.stream.connection.was.interrupted.waiting.to": "The stream connection was interrupted. Waiting to reconnect…",
|
||||
"ui.the.streamer.declined.your.request.to.watch": "The streamer declined your request to watch.",
|
||||
"ui.the.streamer.removed.you.from.the.viewers": "The streamer removed you from the viewers.",
|
||||
"ui.the.streamer.did.not.respond.within.90": "The streamer did not respond within 90 seconds.",
|
||||
"ui.could.not.connect.directly.to.the.streamer": "Could not connect directly to the streamer. Watching requires direct network access to their computer (via STUN, without TURN).",
|
||||
"ui.the.stream.ended": "The stream ended.",
|
||||
"ui.the.streamer.left.the.server": "The streamer left the server.",
|
||||
"ui.connection.to.the.server.was.lost": "Connection to the server was lost.",
|
||||
"ui.this.stream.uses.a.teamspeak.sfu.server": "This stream uses a TeamSpeak SFU server. TeamsPeach supports only direct (P2P) streams.",
|
||||
"ui.connected.waiting.for.the.first.frame": "Connected. Waiting for the first frame…",
|
||||
"ui.close": "Close",
|
||||
"ui.cancel2": "Cancel",
|
||||
"ui.streamer.is.not.sending.audio": "streamer is not sending audio",
|
||||
"ui.with.audio": "with audio",
|
||||
"ui.unmute.stream": "Unmute stream",
|
||||
"ui.selected.device": "selected device",
|
||||
"ui.system.default.device": "System default device",
|
||||
"ui.previously.selected.device.currently.unavailable": "Previously selected device (currently unavailable)",
|
||||
"ui.output.device.selection.is.not.supported": "Output device selection is not supported",
|
||||
"ui.selected.microphone.unavailable.using.the.default.microphone": "Selected microphone unavailable; using the default microphone",
|
||||
"ui.microphone.disconnected": "Microphone disconnected",
|
||||
"ui.invalid.request": "Invalid request",
|
||||
"ui.command.not.supported": "Command not supported",
|
||||
"ui.profile.not.created.yet": "Profile not created yet",
|
||||
"ui.profile.already.exists": "Profile already exists",
|
||||
"ui.the.identity.file.is.corrupted.restore.a": "The identity file is corrupted. Restore a backup in Settings → Identity → Import.",
|
||||
"ui.profile.file.corrupted": "Profile file corrupted",
|
||||
"ui.nickname.must.contain.3.30.characters.with": "Nickname must contain 3–30 characters with no control characters",
|
||||
"ui.set.a.nickname.first": "Set a nickname first",
|
||||
"ui.not.connected.to.a.server": "Not connected to a server",
|
||||
"ui.already.connected": "Already connected",
|
||||
"ui.could.not.connect": "Could not connect",
|
||||
"ui.the.server.rejected.the.action": "The server rejected the action",
|
||||
"ui.microphone.queue.overflow.some.audio.was.dropped": "Microphone queue overflow; some audio was dropped",
|
||||
"ui.microphone.or.audio.is.muted.voice.is": "Microphone or audio is muted; voice is not transmitted",
|
||||
"ui.opus.codec.error": "Opus codec error",
|
||||
"ui.this.channel.uses.a.legacy.codec.speex": "This channel uses a legacy codec (Speex/CELT); voice transmission is unavailable",
|
||||
"ui.the.server.accepted.the.nickname.but.saving": "The server accepted the nickname, but saving it to disk failed",
|
||||
"ui.could.not.access.the.data.folder": "Could not access the data folder",
|
||||
"ui.internal.core.error": "Internal core error",
|
||||
"ui.the.core.did.not.respond.in.time": "The core did not respond in time",
|
||||
"ui.the.core.is.not.running": "The core is not running",
|
||||
"ui.the.core.stopped2": "The core stopped",
|
||||
"ui.core.executable.not.found": "Core executable not found",
|
||||
"ui.disconnect.from.the.server.first2": "Disconnect from the server first",
|
||||
"ui.action.forbidden": "Action forbidden",
|
||||
"ui.no.error.details.were.provided": "No error details were provided",
|
||||
"ui.error2": "Error",
|
||||
"ui.space": "Space",
|
||||
"ui.left.ctrl": "Left Ctrl",
|
||||
"ui.right.ctrl": "Right Ctrl",
|
||||
"ui.left.alt": "Left Alt",
|
||||
"ui.right.alt": "Right Alt",
|
||||
"ui.left.shift": "Left Shift",
|
||||
"ui.right.shift": "Right Shift",
|
||||
"ui.left.super": "Left Super",
|
||||
"ui.right.super": "Right Super",
|
||||
"ui.not.assigned": "not assigned",
|
||||
"message.server.banner.p0": "Server banner ({p0})",
|
||||
"message.setting.not.saved.p0": "Setting not saved: {p0}",
|
||||
"message.exit.code.p0": "Exit code {p0}",
|
||||
"message.p0.teamspeach.never.replaces.a.corrupted": "{p0} TeamsPeach never replaces a corrupted identity with a new one.",
|
||||
"message.an.identity.already.exists.uid.p0": "An identity already exists (UID {p0}). Choose a nickname to continue.",
|
||||
"message.profile.created.your.uid.p0": "Profile created. Your UID: {p0}",
|
||||
"message.you.will.join.as.p0.uid": "You will join as {p0} · UID {p1}",
|
||||
"message.this.channel.uses.a.legacy.codec": "This channel uses a legacy codec ({p0}). TeamsPeach only sends and receives Opus; voice is unavailable here.",
|
||||
"message.p0.enter.the.server.password.and": "{p0}. Enter the server password and reconnect.",
|
||||
"message.disconnect.p0": "Disconnect: {p0}",
|
||||
"message.disconnected.p0": "Disconnected: {p0}",
|
||||
"message.connected.to.p0.p1": "Connected to “{p0}”{p1}",
|
||||
"message.you.are.in.channel.p0": "You are in channel “{p0}”",
|
||||
"message.identity.restored.uid.p0": "Identity restored. UID {p0}",
|
||||
"message.restore.failed.p0": "Restore failed: {p0}",
|
||||
"message.import.failed.p0": "Import failed: {p0}",
|
||||
"message.p0.left": "{p0} (left)",
|
||||
"message.message.not.sent.p0": "Message not sent: {p0}",
|
||||
"message.private.messages.p0": "Private messages: {p0}",
|
||||
"message.unread.p0": ", unread: {p0}",
|
||||
"message.message.p0": "Message {p0}",
|
||||
"message.message.in.p0": "Message in “{p0}”",
|
||||
"message.server.p0.saved": "Server “{p0}” saved",
|
||||
"message.server.p0.deleted": "Server “{p0}” deleted",
|
||||
"message.saved.p0.uid.unchanged": "Saved{p0}. UID unchanged.",
|
||||
"message.the.server.showed.p0.but.p1": "The server showed “{p0}”, but “{p1}” remains on disk{p2}.",
|
||||
"message.saved.to.p0.uid.p1": "Saved to “{p0}”. UID {p1}.",
|
||||
"message.export.failed.p0": "Export failed: {p0}",
|
||||
"message.identity.imported.uid.p0": "Identity imported. UID {p0}",
|
||||
"message.identity.security.level.p0": "Identity security level: {p0}",
|
||||
"message.this.run.p0.chromium.engine.p1": "This run: {p0}. Chromium engine: {p1}.",
|
||||
"message.p0.p1.decoder.p2.p3": "{p0}: {p1}, decoder “{p2}”{p3}.",
|
||||
"message.missing.permission.p0": ", missing permission {p0}",
|
||||
"message.could.not.join.p0.p1": "Could not join “{p0}”: {p1}",
|
||||
"message.password.for.channel.p0": "Password for channel {p0}",
|
||||
"message.could.not.enter.p0.p1": "Could not enter “{p0}”: {p1}",
|
||||
"message.away.p0": "Away: {p0}",
|
||||
"message.away.p02": "away: {p0}",
|
||||
"message.country.p0": "Country: {p0}",
|
||||
"message.groups.p0": ", groups: {p0}",
|
||||
"message.description.p0": "Description: {p0}",
|
||||
"message.groups.p02": "Groups: {p0}",
|
||||
"message.p0.p1.p2": "{p0}: {p1}{p2}",
|
||||
"message.output.device.unavailable.p0": "Output device unavailable: {p0}",
|
||||
"message.audio.unavailable.p0": "Audio unavailable: {p0}",
|
||||
"message.microphone.access.unavailable.p0": "Microphone access unavailable: {p0}",
|
||||
"message.could.not.select.output.device.p0": "Could not select output device: {p0}",
|
||||
"message.could.not.list.devices.p0.p1": "Could not list devices: {p0}: {p1}",
|
||||
"message.no.microphones.found.output.devices.p0": "No microphones found. Output devices: {p0}.",
|
||||
"message.microphones.p0.no.output.devices.found": "Microphones: {p0}. No output devices found.",
|
||||
"message.microphones.found.p0.output.devices.p1": "Microphones found: {p0}; output devices: {p1}.",
|
||||
"message.window.unfocused.p0.will.not.work": "Window unfocused — {p0} will not work",
|
||||
"message.key.p0": "Key: {p0}",
|
||||
"message.full.screen.unavailable.p0": "Full screen unavailable: {p0}",
|
||||
"message.stream.from.p0": "Stream from {p0}",
|
||||
"message.stream.error.p0": "Stream error: {p0}",
|
||||
"message.p0.fps": "{p0} fps",
|
||||
"message.could.not.route.stream.audio.to": "Could not route stream audio to “{p0}” ({p1}). It continues playing through the current device; choose another in Settings → Audio.",
|
||||
"message.system.default.p0": "System default ({p0})",
|
||||
"message.unnamed.device.p0": "Unnamed device ({p0})",
|
||||
"native.identityExport.title": "Export TeamsPeach identity",
|
||||
"native.identity.filter": "TeamSpeak identity",
|
||||
"native.allFiles": "All files",
|
||||
"native.identityImport.title": "Import identity",
|
||||
"native.identityReplace.title": "Replace identity?",
|
||||
"native.identityReplace.message": "Importing replaces the current identity.",
|
||||
"native.identityReplace.detail": "The current UID is lost unless you have a backup of it. Server permissions and groups are bound to the UID.",
|
||||
"native.identityReplace.cancel": "Cancel",
|
||||
"native.identityReplace.confirm": "Choose file and replace",
|
||||
"native.error.connected": "Disconnect from the server first",
|
||||
"native.error.coreMissing": "Core executable not found",
|
||||
"native.error.coreNoResult": "The core returned no result",
|
||||
"native.error.unknown": "Unknown error",
|
||||
"native.error.coreUnavailable": "The core is not running",
|
||||
"native.error.mediaNotAnnounced": "The server did not announce this address",
|
||||
"native.error.mediaTooLarge": "Image larger than 4 MiB",
|
||||
"native.error.mediaUnsupported": "Not an image",
|
||||
"native.error.mediaTimeout": "Download timed out",
|
||||
"core.status.readyTimeout": "The core did not respond within 15 seconds",
|
||||
"core.status.protocol": "Unsupported core protocol version: {protocol}",
|
||||
"core.error.exited": "The core has stopped",
|
||||
"core.error.requestTooLarge": "Request too large",
|
||||
"core.error.timeout": "The core did not answer “{cmd}” within {seconds} s",
|
||||
"core.error.emptyError": "Empty error response",
|
||||
"core.exit.0": "The core has stopped",
|
||||
"core.exit.2": "The core rejected its start arguments",
|
||||
"core.exit.3": "The profile is in use by another TeamsPeach instance or the data folder is unavailable",
|
||||
"core.exit.1": "Internal core error (details in core.log)",
|
||||
"core.exit.other": "The core exited with code {code}",
|
||||
"update.ui.title": "Updates",
|
||||
"update.ui.channel.label": "Update channel",
|
||||
"update.ui.channel.preview": "Preview releases",
|
||||
"update.ui.channel.stable": "Stable only",
|
||||
"update.ui.channel.note": "All TeamsPeach releases are previews for now: the “Stable only” channel will receive no updates.",
|
||||
"update.ui.confirm.text": "Installing closes TeamsPeach: the current call and stream viewing will be interrupted.",
|
||||
"update.ui.confirm.yes": "Interrupt and install",
|
||||
"update.ui.confirm.no": "Cancel",
|
||||
"update.ui.check": "Check for updates",
|
||||
"update.ui.retry": "Retry",
|
||||
"update.ui.download": "Download",
|
||||
"update.ui.downloadNow": "Download now",
|
||||
"update.ui.install": "Install and restart",
|
||||
"update.ui.openRelease": "Open release page",
|
||||
"update.ui.status.disabled": "Automatic updates are unavailable: {reason}.",
|
||||
"update.ui.status.idle": "Not checked yet.",
|
||||
"update.ui.status.checking": "Checking for updates…",
|
||||
"update.ui.status.upToDate": "You have the latest version.",
|
||||
"update.ui.status.upToDateChecked": "You have the latest version (checked {time}).",
|
||||
"update.ui.status.newerPreview": "Preview version {version} is available in the “Preview releases” channel.",
|
||||
"update.ui.status.available": "Version {version} is available.",
|
||||
"update.ui.status.availablePreview": "Preview version {version} is available.",
|
||||
"update.ui.status.manual": "This build is updated manually: download the archive from the release page and replace the files.",
|
||||
"update.ui.status.deferred": "Version {version} found. The download starts after the call ends.",
|
||||
"update.ui.status.downloading": "Downloading version {version}: {percent}%.",
|
||||
"update.ui.status.downloaded": "Version {version} is downloaded and verified. Installing restarts TeamsPeach.",
|
||||
"update.ui.status.installing": "Installing the update, TeamsPeach will restart…",
|
||||
"update.ui.status.error": "Update failed: {message}",
|
||||
"update.ui.status.skipped": "Version {version} skipped: {reason}.",
|
||||
"update.ui.toast.available": "TeamsPeach {version} is available — Settings → Information.",
|
||||
"update.ui.installFailed": "Could not install the update",
|
||||
"language.label": "Language",
|
||||
"language.note": "Changes apply immediately. Your identity, connection and audio are unchanged.",
|
||||
"members.count": {
|
||||
"one": "{count} member",
|
||||
"other": "{count} members"
|
||||
},
|
||||
"error.detail": "Error ({code}): {detail}",
|
||||
"error.device_fallback": "Selected microphone unavailable; using the system default.",
|
||||
"error.device_lost": "The microphone was disconnected. Choose an available device in Settings → Audio.",
|
||||
"update.disabled.dev-build": "This development build does not install updates",
|
||||
"update.disabled.unsupported-platform": "Updates are not supported on {platform} {arch}",
|
||||
"update.error.network": "Network request failed: {detail}",
|
||||
"update.error.timeout": "The request timed out after {seconds} seconds",
|
||||
"update.error.http": "Update server returned HTTP {status}",
|
||||
"update.error.bad-response": "Invalid update response: {detail}",
|
||||
"update.error.incomplete-list": "Incomplete release list: received {fetched} of {total}",
|
||||
"update.error.incomplete-release": "Release {tag} is incomplete. File: {file}. {detail}",
|
||||
"update.error.checksum": "Release {tag} failed integrity verification: {detail}",
|
||||
"update.error.download": "Could not download release {tag}: {detail}",
|
||||
"update.error.install": "Could not install release {tag}: {detail}",
|
||||
"update.error.bad-version": "Invalid release version: {version}",
|
||||
"update.skip.no-feed": "No update feed {file} for {target}",
|
||||
"update.skip.no-package": "No installation package {file} for {target}",
|
||||
"update.skip.feed-mismatch": "Update feed does not match release {tag}: {detail}",
|
||||
"update.skip.incomplete-release": "Release {tag} is incomplete. File: {file}. {detail}",
|
||||
"update.install.session-active": "End the current call or confirm interrupting it to install.",
|
||||
"update.install.not-ready": "No verified update is ready to install.",
|
||||
"update.install.install-failed": "Could not install release {tag}: {detail}",
|
||||
"language.russian": "Russian",
|
||||
"update.channel.hint": "Preview includes prereleases; Stable excludes them.",
|
||||
"error.capture": "Microphone processing failed."
|
||||
});
|
||||
if (typeof module === 'object' && module.exports) module.exports = messages;
|
||||
root.TeamsPeachCatalogs = root.TeamsPeachCatalogs || {};
|
||||
root.TeamsPeachCatalogs.en = messages;
|
||||
})(globalThis);
|
||||
@@ -0,0 +1,26 @@
|
||||
// Shared browser/CommonJS translator. Language is explicit, never inferred from the OS.
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const catalogs = typeof module === 'object' && module.exports
|
||||
? { en: require('./en.js'), ru: require('./ru.js') }
|
||||
: root.TeamsPeachCatalogs;
|
||||
const languages = Object.freeze(['en', 'ru']);
|
||||
const normalizeLanguage = (language) => languages.includes(language) ? language : 'en';
|
||||
const plurals = { en: new Intl.PluralRules('en'), ru: new Intl.PluralRules('ru') };
|
||||
const numbers = { en: new Intl.NumberFormat('en'), ru: new Intl.NumberFormat('ru') };
|
||||
function t(key, params = {}, language = 'en') {
|
||||
const locale = normalizeLanguage(language);
|
||||
if (!Object.hasOwn(catalogs[locale], key)) throw new Error(`Missing translation key: ${key}`);
|
||||
let message = catalogs[locale][key];
|
||||
if (typeof message === 'object') message = message[plurals[locale].select(Number(params.count))] ?? message.other;
|
||||
return message.replace(/\{([A-Za-z][A-Za-z0-9]*)\}/g, (_, name) => {
|
||||
const value = params[name];
|
||||
// Optional technical fields may be null, but missing required parameters are a programming error.
|
||||
if (!Object.hasOwn(params, name)) throw new Error(`Missing translation parameter ${name} for ${key}`);
|
||||
return value == null ? '' : typeof value === 'number' ? numbers[locale].format(value) : String(value);
|
||||
});
|
||||
}
|
||||
const api = Object.freeze({ t, normalizeLanguage, languages, catalogs });
|
||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||
root.TeamsPeachI18n = api;
|
||||
})(globalThis);
|
||||
@@ -0,0 +1,458 @@
|
||||
// TeamsPeach ru message catalog. Keep keys and placeholders aligned across languages.
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const messages = Object.freeze({
|
||||
"ui.starting.core": "Запуск ядра…",
|
||||
"ui.restarting.core": "Перезапуск ядра…",
|
||||
"ui.core.unavailable": "Ядро недоступно",
|
||||
"ui.restart.core": "Перезапустить ядро",
|
||||
"ui.import.backup": "Импортировать резервную копию…",
|
||||
"ui.open.logs": "Открыть журналы",
|
||||
"ui.what.should.we.call.you": "Как вас называть?",
|
||||
"ui.everyone.on.the.server.sees.your.nickname": "Никнейм видят все на сервере. Его можно сменить позже — ваш постоянный идентификатор (UID) при этом не меняется.",
|
||||
"ui.nickname": "Никнейм",
|
||||
"ui.3.30.characters": "От 3 до 30 символов.",
|
||||
"ui.continue": "Продолжить",
|
||||
"ui.teamspeach.will.create.a.cryptographic.identity.on": "TeamsPeach создаст на этом компьютере криптографическую идентичность. Регистрация не нужна.",
|
||||
"ui.restore.from.backup": "Восстановить из резервной копии…",
|
||||
"ui.server": "Сервер",
|
||||
"ui.not.connected": "Нет подключения",
|
||||
"ui.not.connected2": "не подключено",
|
||||
"ui.connecting": "подключение…",
|
||||
"ui.connected": "подключено",
|
||||
"ui.disconnecting": "отключение…",
|
||||
"ui.saved.servers": "Сохранённые серверы",
|
||||
"ui.disconnect.from.server": "Отключиться от сервера",
|
||||
"ui.disconnect": "Отключиться",
|
||||
"ui.save.current.server": "Сохранить текущий",
|
||||
"ui.no.saved.servers.enter.an.address.in": "Сохранённых серверов нет. Введите адрес в форме подключения и нажмите «Сохранить».",
|
||||
"ui.channels.will.appear.after.you.connect.to": "Каналы появятся после подключения к серверу.",
|
||||
"ui.channels.and.members": "Каналы и участники",
|
||||
"ui.settings.categories": "Разделы настроек",
|
||||
"ui.back.to.server": "Назад к серверу",
|
||||
"ui.settings": "Настройки",
|
||||
"ui.user": "Пользователь",
|
||||
"ui.identity": "Идентичность",
|
||||
"ui.servers": "Серверы",
|
||||
"ui.application": "Приложение",
|
||||
"ui.appearance": "Внешний вид",
|
||||
"ui.audio": "Звук",
|
||||
"ui.video": "Видео",
|
||||
"ui.keyboard": "Клавиши",
|
||||
"ui.information": "Информация",
|
||||
"ui.microphone": "Микрофон",
|
||||
"ui.mute.microphone": "Выключить микрофон",
|
||||
"ui.mute.audio": "Выключить звук",
|
||||
"ui.connect.to.a.server": "Подключение к серверу",
|
||||
"ui.server.address": "Адрес сервера",
|
||||
"ui.address.or.address.9987": "адрес или адрес:9987",
|
||||
"ui.server.password": "Пароль сервера",
|
||||
"ui.optional": "необязательно",
|
||||
"ui.connect": "Подключиться",
|
||||
"ui.save": "Сохранить",
|
||||
"ui.hold.to.talk": "Удерживайте, чтобы говорить",
|
||||
"ui.stream": "Трансляция",
|
||||
"ui.stream.audio": "Звук трансляции",
|
||||
"ui.mute.stream": "Выключить звук трансляции",
|
||||
"ui.stream.volume": "Громкость трансляции",
|
||||
"ui.full.screen": "Во весь экран",
|
||||
"ui.stop.watching": "Прекратить просмотр",
|
||||
"ui.chat": "Чат",
|
||||
"ui.chats": "Чаты",
|
||||
"ui.message": "Сообщение",
|
||||
"ui.send": "Отправить",
|
||||
"ui.send.enter": "Отправить (Enter)",
|
||||
"ui.unique.identifier": "Уникальный идентификатор",
|
||||
"ui.copy": "Копировать",
|
||||
"ui.your.uid.is.your.public.key.fingerprint": "UID — отпечаток вашего открытого ключа. Серверы TeamSpeak по нему узнают вас и выдают права; смена ника его не меняет.",
|
||||
"ui.export.to.file": "Экспортировать в файл…",
|
||||
"ui.import.from.file": "Импортировать из файла…",
|
||||
"ui.the.file.contains.your.private.key.protect": "Файл содержит закрытый ключ. Храните его как пароль: тот, у кого он есть, может выдавать себя за вас.",
|
||||
"ui.details": "Подробнее",
|
||||
"ui.nickname2": "Ник",
|
||||
"ui.other.users.on.the.teamspeak.server.see": "Ваш ник видят другие пользователи на сервере TeamSpeak. От 3 до 30 символов.",
|
||||
"ui.no.saved.servers": "Сохранённых серверов нет.",
|
||||
"ui.add.server": "Добавить сервер",
|
||||
"ui.name": "Название",
|
||||
"ui.address": "Адрес",
|
||||
"ui.add": "Добавить",
|
||||
"ui.only.the.name.and.address.are.saved": "Сохраняются только название и адрес. Пароль сервера не сохраняется — его спросят при подключении. Для всех серверов используется одна и та же ваша идентичность.",
|
||||
"ui.theme": "Тема",
|
||||
"ui.color.theme": "Тема оформления",
|
||||
"ui.system": "Как в системе",
|
||||
"ui.dark": "Тёмная",
|
||||
"ui.light": "Светлая",
|
||||
"ui.devices": "Устройства",
|
||||
"ui.test.microphone": "Проверить микрофон",
|
||||
"ui.output.device": "Устройство вывода",
|
||||
"ui.volume": "Громкость",
|
||||
"ui.voice.volume": "Громкость голосов",
|
||||
"ui.microphone.processing": "Обработка микрофона",
|
||||
"ui.noise.suppression": "Шумоподавление",
|
||||
"ui.echo.cancellation": "Эхоподавление",
|
||||
"ui.automatic.gain.control": "Автоматическая громкость",
|
||||
"ui.hardware.acceleration": "Аппаратное ускорение",
|
||||
"ui.allow.hardware.video.decoding": "Разрешить аппаратное декодирование видео",
|
||||
"ui.the.engine.may.use.your.gpu.to": "Движок может использовать видеокарту для декодирования трансляций. Применяется после перезапуска.",
|
||||
"ui.this.change.takes.effect.after.restarting.teamspeach": "Изменение вступит в силу после перезапуска TeamsPeach.",
|
||||
"ui.restart.now": "Перезапустить сейчас",
|
||||
"ui.decoding.backend": "Бэкенд декодирования",
|
||||
"ui.automatic.chosen.by.chromium": "Автоматически (выбирает Chromium)",
|
||||
"ui.details.status.codecs.and.backends": "Подробности: состояние, кодеки и бэкенды",
|
||||
"ui.policy": "Политика",
|
||||
"ui.current.reception": "Текущий приём",
|
||||
"ui.receive.codecs.reported.by.the.engine": "Кодеки приёма, объявленные движком",
|
||||
"ui.unavailable.settings": "Недоступные настройки",
|
||||
"ui.unlike.teamspeak.6.there.is.no.cisco": "Переключателя Cisco OpenH264 и ручного выбора аппаратных бэкендов (NVENC, AMF, QSV и др.), как в TeamSpeak 6, здесь нет: TeamsPeach принимает видео через WebRTC движка Chromium, у которого нет API выбора декодера. H.264 Chromium декодирует через FFmpeg — OpenH264 в нём служит только кодировщиком, а кодирование (отправка своего экрана) в TeamsPeach не реализовано.",
|
||||
"ui.voice.transmission": "Передача голоса",
|
||||
"ui.transmission.mode": "Режим передачи",
|
||||
"ui.push.to.talk": "Нажми и говори",
|
||||
"ui.open.microphone": "Открытый микрофон",
|
||||
"ui.push.to.talk.key": "Клавиша «нажми и говори»",
|
||||
"ui.assign": "Назначить",
|
||||
"ui.the.key.works.while.teamspeach.is.focused": "Клавиша работает, пока окно TeamsPeach активно. Буквенные клавиши не срабатывают во время набора текста. Esc отменяет назначение.",
|
||||
"ui.about": "О программе",
|
||||
"ui.updates": "Обновления",
|
||||
"ui.update.channel": "Канал обновлений",
|
||||
"ui.preview.releases": "Предварительные версии (preview)",
|
||||
"ui.stable.only": "Только стабильные",
|
||||
"ui.all.teamspeach.releases.are.currently.previews.the": "Сейчас все релизы TeamsPeach предварительные: в канале «Только стабильные» обновлений не будет.",
|
||||
"ui.installing.closes.teamspeach.and.interrupts.your.current": "Установка закроет TeamsPeach: текущий разговор и просмотр трансляции прервутся.",
|
||||
"ui.interrupt.and.install": "Прервать и установить",
|
||||
"ui.cancel": "Отмена",
|
||||
"ui.check.for.updates": "Проверить обновления",
|
||||
"ui.download": "Скачать",
|
||||
"ui.install.and.restart": "Установить и перезапустить",
|
||||
"ui.open.release.page": "Открыть страницу релиза",
|
||||
"ui.server.banner": "Баннер сервера",
|
||||
"ui.error": "ошибка",
|
||||
"ui.teamspeach.core.not.found": "Ядро TeamsPeach не найдено",
|
||||
"ui.the.core.executable.is.missing.build.it": "Исполняемый файл ядра отсутствует. Соберите его (см. README) или переустановите приложение. Проверенные пути:",
|
||||
"ui.the.core.stopped": "Ядро остановилось",
|
||||
"ui.profile.corrupted": "Профиль повреждён",
|
||||
"ui.could.not.read.profile": "Не удалось прочитать профиль",
|
||||
"ui.nickname.must.contain.3.30.characters": "Никнейм должен содержать от 3 до 30 символов.",
|
||||
"ui.creating.identity": "Создаём идентичность…",
|
||||
"ui.connecting2": "Подключение…",
|
||||
"ui.unmute.microphone": "Включить микрофон",
|
||||
"ui.microphone.muted": "Микрофон выключен",
|
||||
"ui.microphone.unmuted": "Микрофон включён",
|
||||
"ui.unmute.audio": "Включить звук",
|
||||
"ui.mute.audio.and.microphone": "Выключить звук (и микрофон)",
|
||||
"ui.audio.muted": "Звук выключен",
|
||||
"ui.audio.unmuted": "Звук включён",
|
||||
"ui.audio.is.muted.you.cannot.hear.others": "Звук выключен: вы не слышите других и не передаёте голос.",
|
||||
"ui.microphone.is.muted": "Микрофон выключен.",
|
||||
"ui.enter.a.server.address": "Укажите адрес сервера.",
|
||||
"ui.could.not.disconnect.from.the.current.server": "Не удалось отключиться от текущего сервера",
|
||||
"ui.disconnected.from.server": "Отключено от сервера",
|
||||
"ui.connection.lost.reconnecting": "Связь потеряна, переподключение…",
|
||||
"ui.interface.startup.failed": "Ошибка запуска интерфейса",
|
||||
"ui.channel": "Канал",
|
||||
"ui.this.person.left.the.server": "Собеседник покинул сервер",
|
||||
"ui.message.exceeds.8.kib": "Сообщение длиннее 8 КиБ",
|
||||
"ui.close.private.chat": "Закрыть личный чат",
|
||||
"ui.current.channel.chat": "Чат текущего канала",
|
||||
"ui.server.wide.chat": "Чат всего сервера",
|
||||
"ui.everyone.in.this.channel.can.see.its": "Сообщения в этом канале видят все, кто в нём находится.",
|
||||
"ui.everyone.connected.to.the.server.can.see": "Сообщения сервера видят все подключённые.",
|
||||
"ui.private.conversation.only.the.recipient.can.see": "Личная переписка. Сообщения видит только собеседник.",
|
||||
"ui.message.the.whole.server": "Сообщение всему серверу",
|
||||
"ui.loading.devices": "Получаем список устройств…",
|
||||
"ui.audio.settings": "Настройки звука…",
|
||||
"ui.the.engine.hid.the.device.list.only": "Движок скрыл список устройств: доступно только системное устройство.",
|
||||
"ui.no.microphones.found": "Микрофоны не найдены.",
|
||||
"ui.no.output.devices.found": "Устройства вывода не найдены.",
|
||||
"ui.enter.a.server.address.to.save.it": "Укажите адрес сервера, чтобы сохранить его.",
|
||||
"ui.enter.an.address": "Укажите адрес.",
|
||||
"ui.server.added": "Сервер добавлен.",
|
||||
"ui.this.address.is.already.saved": "Этот адрес уже сохранён",
|
||||
"ui.you.can.save.up.to.50.servers": "Можно сохранить не больше 50 серверов",
|
||||
"ui.connected2": "Подключено",
|
||||
"ui.switch": "Переключиться",
|
||||
"ui.you.are.connected.to.this.server": "Вы подключены к этому серверу",
|
||||
"ui.disconnect.from.the.current.server.and.connect": "Отключиться от текущего сервера и подключиться к этому",
|
||||
"ui.edit": "Изменить",
|
||||
"ui.confirm.deletion": "Точно удалить?",
|
||||
"ui.delete": "Удалить",
|
||||
"ui.server.name": "Название сервера",
|
||||
"ui.name.and.address.cannot.be.empty": "Название и адрес не могут быть пустыми",
|
||||
"ui.this.address.is.already.saved.under.another": "Этот адрес уже сохранён под другим названием",
|
||||
"ui.this.is.already.your.nickname": "Это уже ваш никнейм.",
|
||||
"ui.saving": "Сохраняем…",
|
||||
"ui.and.applied.on.the.server": " и применено на сервере",
|
||||
"ui.saved": "Сохранено.",
|
||||
"ui.the.server.nickname.was.restored": "; имя на сервере возвращено",
|
||||
"ui.uid.copied": "UID скопирован",
|
||||
"ui.disconnect.from.the.server.first": "Сначала отключитесь от сервера.",
|
||||
"ui.press.a.key": "нажмите клавишу…",
|
||||
"ui.stop.test": "Остановить проверку",
|
||||
"ui.available.after.disconnecting.from.the.server": "Доступно после отключения от сервера",
|
||||
"ui.core": "Ядро",
|
||||
"ui.not.running": "не запущено",
|
||||
"ui.platform": "Платформа",
|
||||
"ui.core.executable": "Исполняемый файл ядра",
|
||||
"ui.data.folder": "Каталог данных",
|
||||
"ui.receive.capabilities.unavailable": "Возможности приёма недоступны",
|
||||
"ui.hardware.decoding.is.allowed.and.available.to": "аппаратное декодирование разрешено и доступно движку",
|
||||
"ui.hardware.decoding.is.force.enabled": "аппаратное декодирование принудительно разрешено",
|
||||
"ui.hardware.decoding.is.disabled.the.engine.will": "аппаратное декодирование отключено, движок будет декодировать программно",
|
||||
"ui.hardware.decoding.is.disabled": "аппаратное декодирование отключено",
|
||||
"ui.hardware.decoding.is.unavailable.on.this.device": "аппаратное декодирование недоступно на этом устройстве, будет программное",
|
||||
"ui.hardware.decoding.is.unavailable": "аппаратное декодирование недоступно",
|
||||
"ui.unknown": "неизвестно",
|
||||
"ui.allowed": "разрешено",
|
||||
"ui.disabled.disable.accelerated.video.decode.flag": "запрещено (флаг disable-accelerated-video-decode)",
|
||||
"ui.power.efficient": " (энергоэффективный)",
|
||||
"ui.not.power.efficient": " (не энергоэффективный)",
|
||||
"ui.current.stream": "Текущая трансляция",
|
||||
"ui.last.stream": "При последнем просмотре",
|
||||
"ui.the.actual.decoder.is.reported.only.while": "Какой декодер реально работает, видно только во время просмотра трансляции.",
|
||||
"ui.dismiss.notification": "Закрыть уведомление",
|
||||
"ui.closed": "закрыт",
|
||||
"ui.password.protected": "с паролем",
|
||||
"ui.you.are.here": "вы здесь",
|
||||
"ui.you.are.in.this.channel": "Вы в этом канале",
|
||||
"ui.join.channel": "Перейти в канал",
|
||||
"ui.channel.password": "Пароль канала",
|
||||
"ui.join": "Войти",
|
||||
"ui.you": "вы",
|
||||
"ui.audio.muted2": "звук выключен",
|
||||
"ui.microphone.muted2": "микрофон выключен",
|
||||
"ui.no.microphone": "Нет микрофона",
|
||||
"ui.no.microphone2": "нет микрофона",
|
||||
"ui.away": "Отошёл",
|
||||
"ui.away2": "отошёл",
|
||||
"ui.recording.the.conversation": "Записывает разговор",
|
||||
"ui.recording": "записывает",
|
||||
"ui.talking": "говорит",
|
||||
"ui.you2": " (вы)",
|
||||
"ui.open.profile.settings": ". Открыть настройки профиля",
|
||||
"ui.send.a.private.message": ". Написать личное сообщение",
|
||||
"ui.profile.settings": "Настройки профиля",
|
||||
"ui.send.a.private.message2": "Написать личное сообщение",
|
||||
"ui.watch": "Смотреть",
|
||||
"ui.watching": "Смотрите",
|
||||
"ui.screen.share": "Трансляция экрана",
|
||||
"ui.the.engine.hid.the.device.list.audio": "Движок скрыл список устройств (нет разрешения на доступ к звуковым устройствам). Доступно только системное устройство по умолчанию.",
|
||||
"ui.no.audio.devices.found": "Звуковые устройства не найдены.",
|
||||
"ui.talk.now": "Говорите…",
|
||||
"ui.the.server.routes.streams.through.an.sfu": "Сервер передаёт трансляции через SFU. TeamsPeach поддерживает только прямые (P2P) трансляции TeamSpeak 6.",
|
||||
"ui.request.sent.waiting.for.the.streamer": "Запрос отправлен. Ждём ответа стримера…",
|
||||
"ui.connecting.to.the.streamer": "Соединение со стримером…",
|
||||
"ui.the.stream.connection.was.interrupted.waiting.to": "Связь со стримером прервалась, ждём восстановления…",
|
||||
"ui.the.streamer.declined.your.request.to.watch": "Стример отклонил запрос на просмотр.",
|
||||
"ui.the.streamer.removed.you.from.the.viewers": "Стример убрал вас из зрителей.",
|
||||
"ui.the.streamer.did.not.respond.within.90": "Стример не ответил на запрос за 90 секунд.",
|
||||
"ui.could.not.connect.directly.to.the.streamer": "Не удалось установить прямое соединение со стримером. Для просмотра нужен прямой сетевой доступ к его компьютеру (через STUN, без TURN).",
|
||||
"ui.the.stream.ended": "Трансляция завершена.",
|
||||
"ui.the.streamer.left.the.server": "Стример покинул сервер.",
|
||||
"ui.connection.to.the.server.was.lost": "Соединение с сервером потеряно.",
|
||||
"ui.this.stream.uses.a.teamspeak.sfu.server": "Эта трансляция идёт через SFU-сервер TeamSpeak. TeamsPeach поддерживает только прямые (P2P) трансляции.",
|
||||
"ui.connected.waiting.for.the.first.frame": "Соединение установлено, ждём первый кадр…",
|
||||
"ui.close": "Закрыть",
|
||||
"ui.cancel2": "Отменить",
|
||||
"ui.streamer.is.not.sending.audio": "стример не передаёт звук",
|
||||
"ui.with.audio": "со звуком",
|
||||
"ui.unmute.stream": "Включить звук трансляции",
|
||||
"ui.selected.device": "выбранное устройство",
|
||||
"ui.system.default.device": "Системное устройство по умолчанию",
|
||||
"ui.previously.selected.device.currently.unavailable": "Выбранное ранее устройство (сейчас не найдено)",
|
||||
"ui.output.device.selection.is.not.supported": "Выбор устройства вывода не поддерживается",
|
||||
"ui.selected.microphone.unavailable.using.the.default.microphone": "Выбранный микрофон недоступен, используется микрофон по умолчанию",
|
||||
"ui.microphone.disconnected": "Микрофон отключён",
|
||||
"ui.invalid.request": "Некорректный запрос",
|
||||
"ui.command.not.supported": "Команда не поддерживается",
|
||||
"ui.profile.not.created.yet": "Профиль ещё не создан",
|
||||
"ui.profile.already.exists": "Профиль уже существует",
|
||||
"ui.the.identity.file.is.corrupted.restore.a": "Файл идентичности повреждён. Восстановите его из резервной копии (Настройки → Импорт).",
|
||||
"ui.profile.file.corrupted": "Файл профиля повреждён",
|
||||
"ui.nickname.must.contain.3.30.characters.with": "Никнейм должен содержать от 3 до 30 символов без управляющих символов",
|
||||
"ui.set.a.nickname.first": "Сначала задайте никнейм",
|
||||
"ui.not.connected.to.a.server": "Нет подключения к серверу",
|
||||
"ui.already.connected": "Уже подключено",
|
||||
"ui.could.not.connect": "Не удалось подключиться",
|
||||
"ui.the.server.rejected.the.action": "Сервер отклонил действие",
|
||||
"ui.microphone.queue.overflow.some.audio.was.dropped": "Очередь микрофона переполнена, часть звука пропущена",
|
||||
"ui.microphone.or.audio.is.muted.voice.is": "Микрофон или звук выключены — передача не идёт",
|
||||
"ui.opus.codec.error": "Ошибка кодека Opus",
|
||||
"ui.this.channel.uses.a.legacy.codec.speex": "Канал использует устаревший кодек (Speex/CELT): передача голоса невозможна",
|
||||
"ui.the.server.accepted.the.nickname.but.saving": "Сервер принял никнейм, но сохранить его на диск не удалось",
|
||||
"ui.could.not.access.the.data.folder": "Ошибка доступа к каталогу данных",
|
||||
"ui.internal.core.error": "Внутренняя ошибка ядра",
|
||||
"ui.the.core.did.not.respond.in.time": "Ядро не ответило вовремя",
|
||||
"ui.the.core.is.not.running": "Ядро не запущено",
|
||||
"ui.the.core.stopped2": "Ядро завершило работу",
|
||||
"ui.core.executable.not.found": "Исполняемый файл ядра не найден",
|
||||
"ui.disconnect.from.the.server.first2": "Сначала отключитесь от сервера",
|
||||
"ui.action.forbidden": "Действие запрещено",
|
||||
"ui.no.error.details.were.provided": "Неизвестная ошибка",
|
||||
"ui.error2": "Ошибка",
|
||||
"ui.space": "Пробел",
|
||||
"ui.left.ctrl": "Левый Ctrl",
|
||||
"ui.right.ctrl": "Правый Ctrl",
|
||||
"ui.left.alt": "Левый Alt",
|
||||
"ui.right.alt": "Правый Alt",
|
||||
"ui.left.shift": "Левый Shift",
|
||||
"ui.right.shift": "Правый Shift",
|
||||
"ui.left.super": "Левый Super",
|
||||
"ui.right.super": "Правый Super",
|
||||
"ui.not.assigned": "не назначена",
|
||||
"message.server.banner.p0": "Баннер сервера ({p0})",
|
||||
"message.setting.not.saved.p0": "Настройка не сохранена: {p0}",
|
||||
"message.exit.code.p0": "Код завершения {p0}",
|
||||
"message.p0.teamspeach.never.replaces.a.corrupted": "{p0} TeamsPeach никогда не создаёт новую идентичность поверх повреждённой.",
|
||||
"message.an.identity.already.exists.uid.p0": "Идентичность уже есть (UID {p0}). Осталось выбрать никнейм.",
|
||||
"message.profile.created.your.uid.p0": "Профиль создан. Ваш UID: {p0}",
|
||||
"message.you.will.join.as.p0.uid": "Вы войдёте как {p0} · UID {p1}",
|
||||
"message.this.channel.uses.a.legacy.codec": "Канал использует устаревший кодек ({p0}). TeamsPeach передаёт и принимает только Opus — говорить здесь не получится.",
|
||||
"message.p0.enter.the.server.password.and": "{p0}. Введите пароль сервера и подключитесь снова.",
|
||||
"message.disconnect.p0": "Отключение: {p0}",
|
||||
"message.disconnected.p0": "Отключено: {p0}",
|
||||
"message.connected.to.p0.p1": "Подключено к «{p0}»{p1}",
|
||||
"message.you.are.in.channel.p0": "Вы в канале «{p0}»",
|
||||
"message.identity.restored.uid.p0": "Идентичность восстановлена. UID {p0}",
|
||||
"message.restore.failed.p0": "Восстановление не удалось: {p0}",
|
||||
"message.import.failed.p0": "Импорт не удался: {p0}",
|
||||
"message.p0.left": "{p0} (вышел)",
|
||||
"message.message.not.sent.p0": "Сообщение не отправлено: {p0}",
|
||||
"message.private.messages.p0": "Личные сообщения: {p0}",
|
||||
"message.unread.p0": ", непрочитанных: {p0}",
|
||||
"message.message.p0": "Сообщение для {p0}",
|
||||
"message.message.in.p0": "Сообщение в «{p0}»",
|
||||
"message.server.p0.saved": "Сервер «{p0}» сохранён",
|
||||
"message.server.p0.deleted": "Сервер «{p0}» удалён",
|
||||
"message.saved.p0.uid.unchanged": "Сохранено{p0}. UID не изменился.",
|
||||
"message.the.server.showed.p0.but.p1": "Сервер показал «{p0}», но на диске остался «{p1}»{p2}.",
|
||||
"message.saved.to.p0.uid.p1": "Сохранено в «{p0}». UID {p1}.",
|
||||
"message.export.failed.p0": "Экспорт не удался: {p0}",
|
||||
"message.identity.imported.uid.p0": "Идентичность импортирована. UID {p0}",
|
||||
"message.identity.security.level.p0": "Уровень безопасности идентичности: {p0}",
|
||||
"message.this.run.p0.chromium.engine.p1": "В этом запуске: {p0}. Движок Chromium: {p1}.",
|
||||
"message.p0.p1.decoder.p2.p3": "{p0}: {p1}, декодер «{p2}»{p3}.",
|
||||
"message.missing.permission.p0": ", не хватает права {p0}",
|
||||
"message.could.not.join.p0.p1": "Не удалось перейти в «{p0}»: {p1}",
|
||||
"message.password.for.channel.p0": "Пароль канала {p0}",
|
||||
"message.could.not.enter.p0.p1": "Не удалось войти в «{p0}»: {p1}",
|
||||
"message.away.p0": "Отошёл: {p0}",
|
||||
"message.away.p02": "отошёл: {p0}",
|
||||
"message.country.p0": "Страна: {p0}",
|
||||
"message.groups.p0": ", группы: {p0}",
|
||||
"message.description.p0": "Описание: {p0}",
|
||||
"message.groups.p02": "Группы: {p0}",
|
||||
"message.p0.p1.p2": "{p0} трансляцию {p1}{p2}",
|
||||
"message.output.device.unavailable.p0": "Устройство вывода недоступно: {p0}",
|
||||
"message.audio.unavailable.p0": "Звук недоступен: {p0}",
|
||||
"message.microphone.access.unavailable.p0": "Нет доступа к микрофону: {p0}",
|
||||
"message.could.not.select.output.device.p0": "Не удалось выбрать устройство вывода: {p0}",
|
||||
"message.could.not.list.devices.p0.p1": "Не удалось получить список устройств: {p0}: {p1}",
|
||||
"message.no.microphones.found.output.devices.p0": "Микрофоны не найдены. Устройств вывода: {p0}.",
|
||||
"message.microphones.p0.no.output.devices.found": "Микрофонов: {p0}. Устройства вывода не найдены.",
|
||||
"message.microphones.found.p0.output.devices.p1": "Найдено микрофонов: {p0}, устройств вывода: {p1}.",
|
||||
"message.window.unfocused.p0.will.not.work": "Окно неактивно — {p0} не сработает",
|
||||
"message.key.p0": "Клавиша: {p0}",
|
||||
"message.full.screen.unavailable.p0": "Полноэкранный режим недоступен: {p0}",
|
||||
"message.stream.from.p0": "Трансляция {p0}",
|
||||
"message.stream.error.p0": "Ошибка трансляции: {p0}",
|
||||
"message.p0.fps": "{p0} к/с",
|
||||
"message.could.not.route.stream.audio.to": "Звук трансляции не удалось направить на «{p0}» ({p1}). Он продолжает играть через текущее устройство; выберите другое в Настройки → Звук.",
|
||||
"message.system.default.p0": "Системное по умолчанию ({p0})",
|
||||
"message.unnamed.device.p0": "Устройство без названия ({p0})",
|
||||
"native.identityExport.title": "Экспорт идентичности TeamsPeach",
|
||||
"native.identity.filter": "Идентичность TeamSpeak",
|
||||
"native.allFiles": "Все файлы",
|
||||
"native.identityImport.title": "Импорт идентичности",
|
||||
"native.identityReplace.title": "Заменить идентичность?",
|
||||
"native.identityReplace.message": "Импорт заменит текущую идентичность.",
|
||||
"native.identityReplace.detail": "Текущий UID будет потерян, если у вас нет его резервной копии. Серверные права и группы привязаны к UID.",
|
||||
"native.identityReplace.cancel": "Отмена",
|
||||
"native.identityReplace.confirm": "Выбрать файл и заменить",
|
||||
"native.error.connected": "Сначала отключитесь от сервера",
|
||||
"native.error.coreMissing": "Исполняемый файл ядра не найден",
|
||||
"native.error.coreNoResult": "Ядро не вернуло результат",
|
||||
"native.error.unknown": "Неизвестная ошибка",
|
||||
"native.error.coreUnavailable": "Ядро не запущено",
|
||||
"native.error.mediaNotAnnounced": "Адрес не был объявлен сервером",
|
||||
"native.error.mediaTooLarge": "Изображение больше 4 МиБ",
|
||||
"native.error.mediaUnsupported": "Не изображение",
|
||||
"native.error.mediaTimeout": "Истекло время загрузки",
|
||||
"core.status.readyTimeout": "Ядро не ответило за 15 секунд",
|
||||
"core.status.protocol": "Неподдерживаемая версия протокола ядра: {protocol}",
|
||||
"core.error.exited": "Ядро завершило работу",
|
||||
"core.error.requestTooLarge": "Запрос слишком большой",
|
||||
"core.error.timeout": "Ядро не ответило на «{cmd}» за {seconds} с",
|
||||
"core.error.emptyError": "Пустой ответ об ошибке",
|
||||
"core.exit.0": "Ядро завершило работу",
|
||||
"core.exit.2": "Ядро отклонило аргументы запуска",
|
||||
"core.exit.3": "Профиль уже используется другим экземпляром TeamsPeach или каталог данных недоступен",
|
||||
"core.exit.1": "Внутренняя ошибка ядра (подробности в журнале core.log)",
|
||||
"core.exit.other": "Ядро завершилось с кодом {code}",
|
||||
"update.ui.title": "Обновления",
|
||||
"update.ui.channel.label": "Канал обновлений",
|
||||
"update.ui.channel.preview": "Предварительные версии (preview)",
|
||||
"update.ui.channel.stable": "Только стабильные",
|
||||
"update.ui.channel.note": "Сейчас все релизы TeamsPeach предварительные: в канале «Только стабильные» обновлений не будет.",
|
||||
"update.ui.confirm.text": "Установка закроет TeamsPeach: текущий разговор и просмотр трансляции прервутся.",
|
||||
"update.ui.confirm.yes": "Прервать и установить",
|
||||
"update.ui.confirm.no": "Отмена",
|
||||
"update.ui.check": "Проверить обновления",
|
||||
"update.ui.retry": "Повторить",
|
||||
"update.ui.download": "Скачать",
|
||||
"update.ui.downloadNow": "Скачать сейчас",
|
||||
"update.ui.install": "Установить и перезапустить",
|
||||
"update.ui.openRelease": "Открыть страницу релиза",
|
||||
"update.ui.status.disabled": "Автообновление недоступно: {reason}.",
|
||||
"update.ui.status.idle": "Проверка ещё не выполнялась.",
|
||||
"update.ui.status.checking": "Проверяем обновления…",
|
||||
"update.ui.status.upToDate": "Установлена последняя версия.",
|
||||
"update.ui.status.upToDateChecked": "Установлена последняя версия (проверено {time}).",
|
||||
"update.ui.status.newerPreview": "Есть предварительная версия {version} — она доступна в канале «Предварительные версии».",
|
||||
"update.ui.status.available": "Доступна версия {version}.",
|
||||
"update.ui.status.availablePreview": "Доступна предварительная версия {version}.",
|
||||
"update.ui.status.manual": "Эта сборка обновляется вручную: скачайте архив на странице релиза и замените файлы.",
|
||||
"update.ui.status.deferred": "Найдена версия {version}. Скачивание начнётся после окончания разговора.",
|
||||
"update.ui.status.downloading": "Скачивается версия {version}: {percent}%.",
|
||||
"update.ui.status.downloaded": "Версия {version} скачана и проверена. Установка перезапустит TeamsPeach.",
|
||||
"update.ui.status.installing": "Устанавливаем обновление, TeamsPeach перезапустится…",
|
||||
"update.ui.status.error": "Не удалось обновить: {message}",
|
||||
"update.ui.status.skipped": "Версия {version} пропущена: {reason}.",
|
||||
"update.ui.toast.available": "Доступна версия TeamsPeach {version} — «Настройки → Информация».",
|
||||
"update.ui.installFailed": "Не удалось установить обновление",
|
||||
"language.label": "Язык",
|
||||
"language.note": "Изменения применяются сразу. Идентичность, подключение и звук сохраняются.",
|
||||
"members.count": {
|
||||
"one": "{count} участник",
|
||||
"few": "{count} участника",
|
||||
"many": "{count} участников",
|
||||
"other": "{count} участника"
|
||||
},
|
||||
"error.detail": "Ошибка ({code}): {detail}",
|
||||
"error.device_fallback": "Выбранный микрофон недоступен; используется системный по умолчанию.",
|
||||
"error.device_lost": "Микрофон отключён. Выберите доступное устройство в Настройки → Звук.",
|
||||
"update.disabled.dev-build": "Эта сборка для разработки не устанавливает обновления",
|
||||
"update.disabled.unsupported-platform": "Обновления не поддерживаются на {platform} {arch}",
|
||||
"update.error.network": "Ошибка сетевого запроса: {detail}",
|
||||
"update.error.timeout": "Время ожидания запроса истекло через {seconds} с",
|
||||
"update.error.http": "Сервер обновлений вернул HTTP {status}",
|
||||
"update.error.bad-response": "Некорректный ответ обновления: {detail}",
|
||||
"update.error.incomplete-list": "Неполный список релизов: получено {fetched} из {total}",
|
||||
"update.error.incomplete-release": "Релиз {tag} неполный. Файл: {file}. {detail}",
|
||||
"update.error.checksum": "Релиз {tag} не прошёл проверку целостности: {detail}",
|
||||
"update.error.download": "Не удалось скачать релиз {tag}: {detail}",
|
||||
"update.error.install": "Не удалось установить релиз {tag}: {detail}",
|
||||
"update.error.bad-version": "Некорректная версия релиза: {version}",
|
||||
"update.skip.no-feed": "Нет файла обновлений {file} для {target}",
|
||||
"update.skip.no-package": "Нет установочного пакета {file} для {target}",
|
||||
"update.skip.feed-mismatch": "Файл обновлений не соответствует релизу {tag}: {detail}",
|
||||
"update.skip.incomplete-release": "Релиз {tag} неполный. Файл: {file}. {detail}",
|
||||
"update.install.session-active": "Завершите разговор или подтвердите его прерывание для установки.",
|
||||
"update.install.not-ready": "Проверенное обновление ещё не готово к установке.",
|
||||
"update.install.install-failed": "Не удалось установить релиз {tag}: {detail}",
|
||||
"language.russian": "Русский",
|
||||
"update.channel.hint": "Предварительный канал включает предварительные версии; стабильный исключает их.",
|
||||
"error.capture": "Ошибка обработки микрофона."
|
||||
});
|
||||
if (typeof module === 'object' && module.exports) module.exports = messages;
|
||||
root.TeamsPeachCatalogs = root.TeamsPeachCatalogs || {};
|
||||
root.TeamsPeachCatalogs.ru = messages;
|
||||
})(globalThis);
|
||||
@@ -716,3 +716,9 @@ input[type="checkbox"], input[type="radio"] { accent-color: var(--accent); width
|
||||
.menu-label { flex: 1; min-width: 0; overflow-wrap: anywhere; }
|
||||
.menu-note { margin: 4px 10px; font-size: 12px; color: var(--text-3); }
|
||||
.menu-sep { height: 1px; margin: 5px 4px; background: var(--border); }
|
||||
|
||||
/* ---------- updates card (Settings → Information) ---------- */
|
||||
.update-status { margin: 10px 0 0; font-size: 13px; color: var(--text); overflow-wrap: anywhere; }
|
||||
.update-progress { display: block; width: 100%; height: 6px; margin-top: 8px; accent-color: var(--accent); }
|
||||
.update-confirm { margin-top: 10px; padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--radius-sm); background: var(--surface-2, var(--surface)); }
|
||||
.update-confirm .hint { margin-top: 0; }
|
||||
+2
-2
@@ -303,7 +303,7 @@ pub mod tests {
|
||||
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"] {
|
||||
for name in ["Second Name", "\u{0422}\u{0440}\u{0435}\u{0442}\u{0438}\u{0439} \u{043d}\u{0438}\u{043a}", "Final-Name"] {
|
||||
store.save_nickname(name).unwrap();
|
||||
// "Restart": a fresh store instance reads everything from disk.
|
||||
let reopened = Store::new(&dir.0);
|
||||
@@ -370,7 +370,7 @@ pub mod tests {
|
||||
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);
|
||||
assert_eq!(validate_nickname(&"\u{0436}".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(_))));
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
# 0.1.2 audio devices: root cause, fix and evidence
|
||||
|
||||
## Reported symptom
|
||||
Settings → Audio listed only "System default device" for both microphone and output (user report,
|
||||
Windows 11, TeamsPeach 0.1.1).
|
||||
|
||||
## Root cause (observed, real Electron, no fake-media flags, no capture)
|
||||
Electron 44 calls the session permission *check* handler during `enumerateDevices()` with:
|
||||
|
||||
```
|
||||
{ permission: "media", requestingOrigin: "app://teamspeach/", mediaType: "audio" | "video", securityOrigin: "app://teamspeach/" }
|
||||
{ permission: "speaker-selection", requestingOrigin: "app://teamspeach/" }
|
||||
```
|
||||
|
||||
The 0.1.1 handler compared `requestingOrigin` with `"app://teamspeach"` (no trailing slash), so every check
|
||||
was denied. Chromium then redacts the device list to one entry per kind with empty `deviceId`/`label`, and
|
||||
the renderer dropped entries with empty ids, leaving only the default option.
|
||||
|
||||
## Fix
|
||||
- `app/main/permissions.js`: origins are parsed with WHATWG `URL` and rebuilt as `protocol//host` (the
|
||||
WHATWG origin of a non-special scheme is `"null"`); inputs with credentials, backslashes or no host never
|
||||
match. Checks allow `media` only for `mediaType === "audio"` and `speaker-selection`, for the app origin
|
||||
only; requests allow audio-only `getUserMedia`. Camera stays denied. Tests: `test/permissions.test.js`
|
||||
(observed arguments, lookalike origins `app://teamspeach@evil/`, `app://teamspeach.evil/`,
|
||||
`app://teamspeach\@evil/`, `app://user:pass@teamspeach/`, `apps://teamspeach/`, `app:teamspeach`).
|
||||
- `app/renderer/js/audio/devices.js`: default/communications aliases fold into one "system default (<name>)"
|
||||
entry; an unnamed device keeps its real id with an honest label; a saved but absent device stays
|
||||
selectable and is marked missing. Tests: `test/devices.test.mjs`.
|
||||
- Settings and the new right-click menus on the footer microphone/headphones buttons share one path
|
||||
(`voice.deviceChoices`, `chooseInputDevice`, `chooseOutputDevice`). A choice is applied only after it was
|
||||
saved.
|
||||
|
||||
## OS inventory (read-only, same machine)
|
||||
6 capture endpoints (MiniFuse 4 Mic/Line/Inst 1-2 = default, Loopback Mix, Line 3-4, Oculus headset mic,
|
||||
DroidCam, Virtual Desktop) and 6 render endpoints (MiniFuse Main L/R = default, Virtual L/R, Aux L/R, Realtek
|
||||
Digital Output, LG ULTRAGEAR, Oculus).
|
||||
|
||||
## Runtime evidence (`runtime/2026-10-24-audio-devices/`)
|
||||
Real devices, no fake-media flags, disposable profiles, never connected, microphone never opened.
|
||||
|
||||
| Run | Result |
|
||||
|---|---|
|
||||
| `result-settings.json`, `60`/`61` png (dev tree) | 6 inputs + 6 outputs with names; `capturing=false`, `framesSent=0`, disconnected; a non-default input and output persist across restart; no error toasts |
|
||||
| `result-menus.json`, `62`/`63` png (dev tree) | right-click on the microphone opens the input menu without muting; the choice shows in Settings; Shift+F10 + arrows + Escape on headphones restores focus without deafening; left click still mutes; choices persist across restart; with enumeration slowed to 600 ms, rapid microphone → headphones requests leave exactly one (output) menu, and a dismissal before the result leaves no menu and does not steal focus |
|
||||
| `packaged-41e90fb/` (packaged `dist/win-unpacked/TeamsPeach.exe`, core 0.1.2) | same settings and menu results as above |
|
||||
|
||||
The UI strings in these captures are the Russian UI of that build and are kept as recorded.
|
||||
|
||||
## Capture lifecycle
|
||||
`AudioEngine.startCapture` is cancelable: a stop or a newer start while `getUserMedia` is pending stops the
|
||||
late stream's tracks immediately; `voice.syncCapture` always cancels when capture is not wanted.
|
||||
Tests: `test/audio-engine.test.mjs`.
|
||||
|
||||
## Voice diagnostics (no behaviour change)
|
||||
Default log level records one line per capture start (device label, sample rate, channel count, EC/NS/AGC,
|
||||
track muted) and OS mute/unmute of the track. With `TEAMSPEACH_LOG=debug`, push-to-talk presses (source,
|
||||
window focus), each transmission burst (frames, peak dBFS) and the core's `transmitting` state are logged.
|
||||
The push-to-talk hint states when the window is unfocused (the key is read only in the focused window).
|
||||
|
||||
## Not proven
|
||||
That the official TeamSpeak 6 client hears TeamsPeach voice is **not verified**. The user's 0.1.1-era
|
||||
logs show a connection and an opened microphone, but no burst logging existed then. The pending check is
|
||||
user-controlled: hold the in-window push-to-talk button (or F8 with TeamsPeach focused) while the official
|
||||
client listens. Synthetic two-TeamsPeach voice tests (fake capture, empty channel) pass and are not
|
||||
hardware proof.
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
# Updates
|
||||
|
||||
TeamsPeach updates itself only from **published releases** of the public Gitea repository
|
||||
<https://git.eeee.moe/TeamsPeach/client>. Branches, commits, Actions artifacts and draft releases are never
|
||||
used. The client needs no credentials; the release host, owner and repository are constants in the main
|
||||
process and the renderer cannot pass URLs.
|
||||
|
||||
## How a check works
|
||||
|
||||
1. `app/main/update-source.js` reads the complete release list anonymously
|
||||
(`GET /api/v1/repos/TeamsPeach/client/releases?draft=false`, every page, `X-Total-Count` checked, 20 s
|
||||
budget). A network failure, timeout, HTTP error, malformed body or incomplete listing is an **error**,
|
||||
never "up to date".
|
||||
2. Releases are filtered:
|
||||
- drafts and tags that are not `v` + strict SemVer (no build metadata, no leading zeros) are ignored;
|
||||
- only versions **greater** than the running one (SemVer precedence via `semver`, `0.1.2-rc.1 < 0.1.2`)
|
||||
are considered — never the same version, never a downgrade;
|
||||
- channel policy (see below);
|
||||
- the release must contain this installation's feed **and** its exact installer name, otherwise it is
|
||||
listed in `newerWithoutBuild` (with a reason code) and an older complete release may be offered instead.
|
||||
3. For auto-update targets, a fresh `electron-updater` 6.8.11 instance (generic provider) reads the feed of the
|
||||
chosen release from `https://git.eeee.moe/TeamsPeach/client/releases/download/<tag>/`. The feed must
|
||||
describe the same version and list exactly one file: this target's installer by its exact builder name,
|
||||
present in the release with the same size and with a sha512. An arm64 feed pointing at the x64 AppImage,
|
||||
a renamed installer or a foreign path is refused. A feed that times out (60 s) ends the check with an error;
|
||||
the abandoned updater instance cannot influence later checks or downloads.
|
||||
4. electron-updater downloads the package and verifies its sha512 (a mismatch is reported as `checksum`
|
||||
and nothing becomes installable).
|
||||
|
||||
Checks run 15 s after start and every 6 hours, and on demand from Settings → Information.
|
||||
|
||||
## Channels
|
||||
|
||||
| Channel | Accepts |
|
||||
|---|---|
|
||||
| `preview` (default) | every published release, including prereleases |
|
||||
| `stable` | only releases that Gitea does not mark as prerelease **and** whose version has no prerelease part |
|
||||
|
||||
A release counts as preview if either the Gitea flag or the SemVer prerelease part says so. The default is
|
||||
`preview` because the distribution currently ships prereleases; the setting is visible in Settings →
|
||||
Information (pref `updateChannel`). In the stable channel the state field `newerPreview` names the newest
|
||||
preview that the channel hides.
|
||||
|
||||
## Platforms
|
||||
|
||||
| Installation | Detection | Behaviour |
|
||||
|---|---|---|
|
||||
| Windows x64, NSIS installer | `Uninstall TeamsPeach.exe` next to the executable | download, then silent NSIS update after the user confirms; the installer starts the new version |
|
||||
| Linux x64 / arm64 AppImage | `APPIMAGE` environment variable | download, then the AppImage file is replaced and the app relaunches after the user confirms |
|
||||
| Windows x64 zip, Linux tar.gz | otherwise | notification only; "open release page"; the user replaces files manually |
|
||||
| macOS, Windows ARM64, development runs | — | updates disabled (`disabledCode`) — no builds are published for them |
|
||||
|
||||
AppImage install uses `quitAndInstall(isSilent=true, isForceRunAfter=false)`: electron-updater swaps the file
|
||||
(a versioned file name such as `TeamsPeach-0.1.2.AppImage` becomes the new versioned name in the same
|
||||
directory, so shortcuts to the old name must be updated), then `app.relaunch({ execPath })` starts the new
|
||||
AppImage only after the old process has exited, so the single-instance lock and the core's `core.lock` are
|
||||
free. NSIS uses `quitAndInstall(true, true)`; whether the installer then succeeds happens after the app quit
|
||||
and is not reported by the app.
|
||||
|
||||
The first updater-capable version must be installed manually: 0.1.1 and older have no updater.
|
||||
|
||||
## User confirmation and active sessions
|
||||
|
||||
Nothing is installed or restarted automatically (`autoInstallOnAppQuit` is off). While the app is connected
|
||||
to a server (voice or stream viewing) background downloads wait (`deferred`) and `update:install` returns
|
||||
`session-active` unless the user explicitly confirms the interruption. User data (`identity.json`,
|
||||
`profile.json`, `prefs.json`: UID, nickname, bookmarks, devices) lives in the profile directory and is not
|
||||
touched by updates.
|
||||
|
||||
## IPC and state
|
||||
|
||||
Invoke-only channels: `update:get-state`, `update:check`, `update:download`,
|
||||
`update:install({ confirmInterrupt })`, `update:open-release`, `update:set-channel`; push channel
|
||||
`update:state`. All check the trusted sender. The state carries stable codes and parameters only
|
||||
(`error: { code, params }`, `newerWithoutBuild[]: { version, code, params }`, `disabledCode`); the renderer
|
||||
localizes them through the shared catalog (`update.*` keys). `params.detail` is raw technical text.
|
||||
The service log is `logs/updater.log` in the profile directory (English).
|
||||
|
||||
## Release requirements
|
||||
|
||||
- `package.json` `build.publish` (generic provider) makes electron-builder write the feeds: `latest.yml`
|
||||
(Windows), `latest-linux.yml`, `latest-linux-arm64.yml`; for a prerelease version `X.Y.Z-rc.N` they are
|
||||
`rc.yml`, `rc-linux.yml`, `rc-linux-arm64.yml`.
|
||||
- Package names must stay exactly as built: `TeamsPeach-<v>.AppImage`, `TeamsPeach-<v>-arm64.AppImage`,
|
||||
`TeamsPeach-<v>-win-x64-setup.exe` (+ `.blockmap`). Renaming breaks the feed.
|
||||
- `scripts/update-feed-check.mjs` verifies feed version, file names, sizes and sha512 against the files next
|
||||
to it; the release workflow runs it after packaging, and `scripts/publish-release.mjs` runs it before
|
||||
uploading and uploads feeds after all packages.
|
||||
- Windows assets built locally are appended to the published release with
|
||||
`TOKEN=… API=… TAG=<tag> node scripts/publish-release.mjs --append <dir>` (dir: setup exe, blockmap,
|
||||
feed, zip, build-info). It refuses to overwrite existing assets. Until the Windows feed is attached, Windows
|
||||
clients simply see no newer build.
|
||||
- Releases are created as prereleases unless `PRERELEASE=false` is set and the tag has no prerelease part.
|
||||
|
||||
## Verification
|
||||
|
||||
- `test/update-source.test.js`: selection, SemVer order (RC → final, no RC after final), drafts, channels,
|
||||
wrong architecture, missing assets, exact feed check, full paging, timeout / HTTP / garbage / redirect /
|
||||
refused connection. `TEAMSPEACH_LIVE_UPDATE_TEST=1` adds a read of the live public release list.
|
||||
- `test/update-engine.test.mjs`: the real service and real electron-updater inside Electron against an emulated
|
||||
release server at the protocol layer — download and sha512 verification, corrupt checksum, wrong-arch feed,
|
||||
missing feed file, feed timeout followed by a late answer that must not contaminate the next download,
|
||||
unreachable server, stable channel, deferred download and install confirmation during a session. Needs a
|
||||
display on Linux (`xvfb-run`). Never installs.
|
||||
- `.gitea/workflows/update-e2e.yml` (manual): downloads an older published AppImage, runs it in a disposable
|
||||
profile under Xvfb with `APPIMAGE_EXTRACT_AND_RUN=1`, lets it update itself from the real release server,
|
||||
and checks the relaunched version, the installed file against the feed sha512, and that UID, nickname,
|
||||
bookmark and device preference are unchanged (`scripts/update-e2e.mjs`).
|
||||
Generated
+42
-28
@@ -8,6 +8,10 @@
|
||||
"name": "teamspeach",
|
||||
"version": "0.1.2",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"electron-updater": "6.8.11",
|
||||
"semver": "7.7.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"electron": "44.9.3",
|
||||
"electron-builder": "26.15.3",
|
||||
@@ -768,19 +772,6 @@
|
||||
"graceful-fs": "^4.1.6"
|
||||
}
|
||||
},
|
||||
"node_modules/app-builder-lib/node_modules/semver": {
|
||||
"version": "7.7.4",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
|
||||
"integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
"semver": "bin/semver.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/app-builder-lib/node_modules/universalify": {
|
||||
"version": "0.1.2",
|
||||
"resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",
|
||||
@@ -795,7 +786,6 @@
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
|
||||
"integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
|
||||
"dev": true,
|
||||
"license": "Python-2.0"
|
||||
},
|
||||
"node_modules/asn1js": {
|
||||
@@ -951,7 +941,6 @@
|
||||
"version": "9.7.0",
|
||||
"resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.7.0.tgz",
|
||||
"integrity": "sha512-g/kR520giAFYkSXTzcmF3kqQq7wi8F6N6SzeDgZrqTBN+VHdmgWOyTdD1yD7AATDId/yXLvuP34CxW46/BwCdw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"debug": "^4.3.4",
|
||||
@@ -1209,7 +1198,6 @@
|
||||
"version": "4.4.3",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
|
||||
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ms": "^2.1.3"
|
||||
@@ -1520,6 +1508,22 @@
|
||||
"mime": "^2.5.2"
|
||||
}
|
||||
},
|
||||
"node_modules/electron-updater": {
|
||||
"version": "6.8.11",
|
||||
"resolved": "https://registry.npmjs.org/electron-updater/-/electron-updater-6.8.11.tgz",
|
||||
"integrity": "sha512-12U/mbzaIKQS3Q543aQ7DjyAZMXeVJy1Wpu0qdq5ne4RXpIQDpWYm25zRjgXngAoo6swMrm4C4owGyiIipelsg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"builder-util-runtime": "9.7.0",
|
||||
"fs-extra": "^10.1.0",
|
||||
"js-yaml": "^4.1.0",
|
||||
"lazy-val": "^1.0.5",
|
||||
"lodash.escaperegexp": "^4.1.2",
|
||||
"lodash.isequal": "^4.5.0",
|
||||
"semver": "~7.7.3",
|
||||
"tiny-typed-emitter": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/electron-winstaller": {
|
||||
"version": "5.4.0",
|
||||
"resolved": "https://registry.npmjs.org/electron-winstaller/-/electron-winstaller-5.4.0.tgz",
|
||||
@@ -1804,7 +1808,6 @@
|
||||
"version": "10.1.0",
|
||||
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
|
||||
"integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"graceful-fs": "^4.2.0",
|
||||
@@ -2030,7 +2033,6 @@
|
||||
"version": "4.2.11",
|
||||
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
|
||||
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/has-flag": {
|
||||
@@ -2252,7 +2254,6 @@
|
||||
"version": "4.3.2",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz",
|
||||
"integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -2310,7 +2311,6 @@
|
||||
"version": "6.2.1",
|
||||
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
|
||||
"integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"universalify": "^2.0.0"
|
||||
@@ -2333,7 +2333,6 @@
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/lazy-val/-/lazy-val-1.0.5.tgz",
|
||||
"integrity": "sha512-0/BnGCCfyUMkBpeDgWihanIAF9JmZhHBgUhEqzvf+adhNGLoP6TaiI5oF8oyb3I45P+PcnrqihSf01M0l0G5+Q==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash": {
|
||||
@@ -2343,6 +2342,19 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.escaperegexp": {
|
||||
"version": "4.1.2",
|
||||
"resolved": "https://registry.npmjs.org/lodash.escaperegexp/-/lodash.escaperegexp-4.1.2.tgz",
|
||||
"integrity": "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isequal": {
|
||||
"version": "4.5.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz",
|
||||
"integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==",
|
||||
"deprecated": "This package is deprecated. Use require('node:util').isDeepStrictEqual instead.",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lowercase-keys": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz",
|
||||
@@ -2502,7 +2514,6 @@
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/node-abi": {
|
||||
@@ -3076,17 +3087,15 @@
|
||||
"version": "1.6.1",
|
||||
"resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz",
|
||||
"integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"engines": {
|
||||
"node": ">=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/semver": {
|
||||
"version": "7.8.5",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
|
||||
"integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
|
||||
"dev": true,
|
||||
"version": "7.7.4",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
|
||||
"integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
"semver": "bin/semver.js"
|
||||
@@ -3338,6 +3347,12 @@
|
||||
"semver": "bin/semver"
|
||||
}
|
||||
},
|
||||
"node_modules/tiny-typed-emitter": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/tiny-typed-emitter/-/tiny-typed-emitter-2.1.0.tgz",
|
||||
"integrity": "sha512-qVtvMxeXbVej0cQWKqVSSAHmKZEHAvxdF8HEUBFWts8h+xEo5m/lEiPakuyZ3BnCBjOD8i24kzNOiOLLgsSxhA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tinyglobby": {
|
||||
"version": "0.2.17",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
|
||||
@@ -3428,7 +3443,6 @@
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
|
||||
"integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 10.0.0"
|
||||
|
||||
+13
-2
@@ -74,7 +74,8 @@
|
||||
},
|
||||
"nsis": {
|
||||
"oneClick": false,
|
||||
"allowToChangeInstallationDirectory": true
|
||||
"allowToChangeInstallationDirectory": true,
|
||||
"artifactName": "${productName}-${version}-win-${arch}-setup.${ext}"
|
||||
},
|
||||
"mac": {
|
||||
"target": [
|
||||
@@ -84,11 +85,21 @@
|
||||
"category": "public.app-category.social-networking",
|
||||
"icon": "build/icon.png",
|
||||
"extendInfo": {
|
||||
"NSMicrophoneUsageDescription": "TeamsPeach передаёт ваш голос на сервер TeamSpeak."
|
||||
"NSMicrophoneUsageDescription": "TeamsPeach sends your voice to the TeamSpeak server you join."
|
||||
}
|
||||
},
|
||||
"toolsets": {
|
||||
"appimage": "1.0.3"
|
||||
},
|
||||
"publish": [
|
||||
{
|
||||
"provider": "generic",
|
||||
"url": "https://git.eeee.moe/TeamsPeach/client/releases/download/v${version}"
|
||||
}
|
||||
]
|
||||
},
|
||||
"dependencies": {
|
||||
"electron-updater": "6.8.11",
|
||||
"semver": "7.7.4"
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
// On a tag build, refuses to continue unless the tag equals v<package.json version> and the core's
|
||||
// Cargo package version is the same. Branch/manual builds pass through.
|
||||
// Cargo package version is the same. A release candidate (package.json 0.1.2-rc.1) ships the core of
|
||||
// its target version (0.1.2), so for prerelease app versions the core must equal the version without
|
||||
// the prerelease part. Branch/manual builds pass through.
|
||||
// GITHUB_REF=refs/tags/v0.1.0 node scripts/check-version.mjs
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
@@ -10,7 +12,8 @@ const app = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')).ve
|
||||
const cargo = /^\[package\][\s\S]*?^version\s*=\s*"([^"]+)"/m.exec(readFileSync(path.join(root, 'core', 'Cargo.toml'), 'utf8'))?.[1];
|
||||
const ref = process.env.GITHUB_REF ?? '';
|
||||
console.log(`package.json ${app}, core Cargo.toml ${cargo}, ref ${ref || '(none)'}`);
|
||||
if (app !== cargo) {
|
||||
const rc = /^(\d+\.\d+\.\d+)-rc\.\d+$/.exec(app);
|
||||
if (app !== cargo && !(rc && rc[1] === cargo)) {
|
||||
console.error('package.json and core/Cargo.toml versions differ');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
+58
-11
@@ -3,18 +3,33 @@
|
||||
// The token is read only from the environment (TOKEN) and never printed or passed as an argument.
|
||||
//
|
||||
// TOKEN=… API=https://host/api/v1/repos/owner/repo TAG=v0.1.0 node scripts/publish-release.mjs <asset-dir> [notes-file]
|
||||
// TOKEN=… API=… TAG=v0.1.2 node scripts/publish-release.mjs --append <asset-dir>
|
||||
//
|
||||
// --append adds assets (e.g. the locally built Windows packages) to the already published release of TAG;
|
||||
// it refuses to replace an existing asset name.
|
||||
//
|
||||
// Update feeds (*.yml) are checked before anything is uploaded: every package a feed references must be in
|
||||
// the same directory with the exact name, size and sha512 the feed declares, and the feed version must equal
|
||||
// the tag. Feeds are uploaded after all packages, so clients never see a feed whose package is not there yet.
|
||||
// The release is marked prerelease unless PRERELEASE=false is set and the tag has no prerelease part.
|
||||
import { readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { checkFeed } from './update-feed-check.mjs';
|
||||
|
||||
const { TOKEN, API, TAG } = process.env;
|
||||
const assetDir = process.argv[2];
|
||||
const notesFile = process.argv[3];
|
||||
const args = process.argv.slice(2);
|
||||
const append = args[0] === '--append';
|
||||
if (append) args.shift();
|
||||
const assetDir = args[0];
|
||||
const notesFile = args[1];
|
||||
for (const [name, value] of Object.entries({ TOKEN, API, TAG, assetDir })) {
|
||||
if (!value) {
|
||||
console.error(`missing ${name}`);
|
||||
process.exit(2);
|
||||
}
|
||||
}
|
||||
const version = TAG.replace(/^v/, '');
|
||||
const prerelease = process.env.PRERELEASE !== 'false' || version.includes('-');
|
||||
|
||||
function collect(dir) {
|
||||
const files = [];
|
||||
@@ -33,7 +48,9 @@ async function request(method, url, body, headers = {}) {
|
||||
return text ? JSON.parse(text) : null;
|
||||
}
|
||||
|
||||
const files = collect(assetDir);
|
||||
const isFeed = (f) => f.endsWith('.yml');
|
||||
// Packages first, feeds last.
|
||||
const files = collect(assetDir).sort((a, b) => isFeed(a) - isFeed(b));
|
||||
if (files.length === 0) {
|
||||
console.error(`no assets in ${assetDir}`);
|
||||
process.exit(1);
|
||||
@@ -47,18 +64,48 @@ for (const f of files) {
|
||||
}
|
||||
names.add(n);
|
||||
}
|
||||
for (const feed of files.filter(isFeed)) {
|
||||
try {
|
||||
const referenced = await checkFeed(feed, { version });
|
||||
console.log(`feed ${path.basename(feed)} ok: ${referenced.join(', ')}`);
|
||||
} catch (err) {
|
||||
console.error(`feed check failed: ${err.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
async function upload(releaseId, file) {
|
||||
const form = new FormData();
|
||||
form.append('attachment', new Blob([readFileSync(file)]), path.basename(file));
|
||||
const asset = await request('POST', `${API}/releases/${releaseId}/assets?name=${encodeURIComponent(path.basename(file))}`, form);
|
||||
if (asset.name !== path.basename(file) || asset.size !== statSync(file).size) {
|
||||
throw new Error(`server stored ${asset.name} (${asset.size} bytes) for ${path.basename(file)} (${statSync(file).size} bytes)`);
|
||||
}
|
||||
console.log(`uploaded ${asset.name} (${asset.size} bytes)`);
|
||||
}
|
||||
|
||||
if (append) {
|
||||
try {
|
||||
const release = await request('GET', `${API}/releases/tags/${encodeURIComponent(TAG)}`);
|
||||
if (release.draft) throw new Error(`release ${TAG} is a draft; publish it first`);
|
||||
const existing = new Set((release.assets || []).map((a) => a.name));
|
||||
const clash = files.map((f) => path.basename(f)).filter((n) => existing.has(n));
|
||||
if (clash.length > 0) throw new Error(`release ${TAG} already has ${clash.join(', ')}`);
|
||||
for (const file of files) await upload(release.id, file);
|
||||
console.log(`appended ${files.length} assets to ${TAG}`);
|
||||
} catch (err) {
|
||||
console.error(`append failed: ${err.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const body = notesFile ? readFileSync(notesFile, 'utf8') : '';
|
||||
let release = null;
|
||||
try {
|
||||
release = await request('POST', `${API}/releases`, JSON.stringify({ tag_name: TAG, name: `TeamsPeach ${TAG}`, body, draft: true, prerelease: true }), { 'Content-Type': 'application/json' });
|
||||
console.log(`draft release ${release.id} created for ${TAG}`);
|
||||
for (const file of files) {
|
||||
const form = new FormData();
|
||||
form.append('attachment', new Blob([readFileSync(file)]), path.basename(file));
|
||||
const asset = await request('POST', `${API}/releases/${release.id}/assets?name=${encodeURIComponent(path.basename(file))}`, form);
|
||||
console.log(`uploaded ${asset.name} (${asset.size} bytes)`);
|
||||
}
|
||||
release = await request('POST', `${API}/releases`, JSON.stringify({ tag_name: TAG, name: `TeamsPeach ${TAG}`, body, draft: true, prerelease }), { 'Content-Type': 'application/json' });
|
||||
console.log(`draft release ${release.id} created for ${TAG} (prerelease: ${prerelease})`);
|
||||
for (const file of files) await upload(release.id, file);
|
||||
await request('PATCH', `${API}/releases/${release.id}`, JSON.stringify({ draft: false }), { 'Content-Type': 'application/json' });
|
||||
console.log(`release ${TAG} published with ${files.length} assets`);
|
||||
} catch (err) {
|
||||
|
||||
@@ -105,11 +105,12 @@ try {
|
||||
await page.waitForTimeout(1500);
|
||||
const afterSwitch = await page.evaluate(() => ({
|
||||
menus: document.querySelectorAll('.device-menu').length,
|
||||
label: document.querySelector('.device-menu')?.getAttribute('aria-label'),
|
||||
outputExpanded: document.querySelector('#btn-deafen').getAttribute('aria-expanded'),
|
||||
inputExpanded: document.querySelector('#btn-mute').getAttribute('aria-expanded'),
|
||||
items: document.querySelectorAll('.device-menu [role="menuitemradio"]').length,
|
||||
}));
|
||||
step('rapid mic → headphones while enumeration pending', afterSwitch);
|
||||
if (afterSwitch.menus !== 1 || afterSwitch.label !== 'Устройство вывода' || afterSwitch.items < 2) throw new Error('stale or duplicate menu');
|
||||
if (afterSwitch.menus !== 1 || afterSwitch.outputExpanded !== 'true' || afterSwitch.inputExpanded !== 'false' || afterSwitch.items < 2) throw new Error('stale or duplicate menu');
|
||||
await page.keyboard.press('Escape');
|
||||
await page.click('#btn-mute', { button: 'right' });
|
||||
await page.click('#connect-address');
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Real audio devices in Settings → Звук (NO fake-media flags): lists what the engine exposes without any
|
||||
// Real audio devices in Settings → Audio (NO fake-media flags): lists what the engine exposes without any
|
||||
// capture, selects a non-default microphone and output, restarts and checks the choice persisted.
|
||||
// Never connects to a server, never starts the microphone, plays nothing.
|
||||
// node scripts/smoke-devices.mjs --out docs/evidence/runtime/<name> [--exe packaged.exe]
|
||||
|
||||
@@ -56,22 +56,22 @@ try {
|
||||
await page.click('#settings-back');
|
||||
}
|
||||
|
||||
// Save from the connect form, then manage it in Settings → Серверы.
|
||||
// Save from the connect form, then manage it in Settings → Servers.
|
||||
await page.fill('#connect-address', server);
|
||||
await page.click('#connect-save');
|
||||
await page.waitForSelector('#servers-list .server-item', { timeout: 5000 });
|
||||
await page.click('#btn-settings');
|
||||
await page.click('#settings-nav .nav-item[data-panel="servers"]');
|
||||
await page.fill('#server-add-name', 'Недоступный тест');
|
||||
await page.fill('#server-add-name', 'Unreachable test');
|
||||
await page.fill('#server-add-address', '127.0.0.1:9');
|
||||
await page.click('#server-add-form button[type="submit"]');
|
||||
await page.waitForFunction(() => document.querySelectorAll('#servers-manage .manage-row').length === 2);
|
||||
await page.click('#servers-manage .manage-row:first-child button:has-text("Изменить")');
|
||||
await page.fill('#servers-manage .edit-row input[aria-label="Название сервера"]', 'Без негатива');
|
||||
await page.click('#servers-manage .manage-row:first-child button[data-action="edit"]');
|
||||
await page.fill('#servers-manage .edit-row input[data-field="name"]', 'Renamed server');
|
||||
await page.click('#servers-manage .edit-row button[type="submit"]');
|
||||
const del = page.locator('#servers-manage .manage-row', { hasText: 'Недоступный тест' }).locator('button', { hasText: 'Удалить' });
|
||||
const del = page.locator('#servers-manage .manage-row', { hasText: 'Unreachable test' }).locator('button[data-action="delete"]');
|
||||
await del.click();
|
||||
await page.locator('#servers-manage .manage-row', { hasText: 'Недоступный тест' }).locator('button', { hasText: 'Точно удалить?' }).click();
|
||||
await page.locator('#servers-manage .manage-row', { hasText: 'Unreachable test' }).locator('button[data-action="confirm-delete"]').click();
|
||||
await page.waitForFunction(() => document.querySelectorAll('#servers-manage .manage-row').length === 1);
|
||||
await page.screenshot({ path: path.join(out, '50-settings-servers.png') });
|
||||
step('saved, edited, deleted', { rows: await page.$$eval('#servers-manage .manage-row', (r) => r.map((x) => x.textContent.trim())) });
|
||||
|
||||
@@ -118,7 +118,7 @@ try {
|
||||
}, exportFile);
|
||||
await page.click('#btn-settings');
|
||||
await page.click('#identity-export');
|
||||
await page.waitForFunction(() => /UID|не удался/.test(document.querySelector('#identity-status').textContent), null, { timeout: 20000 });
|
||||
await page.waitForFunction(() => Boolean(document.querySelector('#identity-status').dataset.state), null, { timeout: 20000 });
|
||||
const exportStatus = await page.textContent('#identity-status');
|
||||
const { readFileSync, rmSync } = await import('node:fs');
|
||||
const exported = readFileSync(exportFile, 'utf8');
|
||||
@@ -137,7 +137,7 @@ try {
|
||||
await page.click('#btn-settings');
|
||||
await page.click('#settings-nav .nav-item[data-panel="video"]');
|
||||
await page.click('.settings-panel[data-panel="video"] summary');
|
||||
await page.waitForFunction(() => /запрещено/.test(document.querySelector('#hwdec-status').textContent), null, { timeout: 10000 });
|
||||
await page.waitForFunction(() => document.querySelector('#hwdec-status').dataset.policy === 'forbidden', null, { timeout: 10000 });
|
||||
step('after restart', { status: await page.textContent('#hwdec-status'), restartHint: await page.isVisible('#hwdec-restart') });
|
||||
await shot(page, '05-video-decode-disabled.png');
|
||||
await page.check('#opt-hwdec');
|
||||
|
||||
@@ -63,7 +63,7 @@ async function setRange(page, selector, value) {
|
||||
}, value);
|
||||
}
|
||||
|
||||
/** Transmit mode lives in Settings → Клавиши. */
|
||||
/** Transmit mode lives in Settings → Keys. */
|
||||
async function setTransmit(page, mode) {
|
||||
await page.click('#btn-settings');
|
||||
await page.click('#settings-nav .nav-item[data-panel="keys"]');
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
// End-to-end self-update of a real, published Linux AppImage (no mocks, no credentials):
|
||||
// 1. start the OLD published AppImage with a disposable profile and create an identity, bookmark, device pref;
|
||||
// 2. let its updater find, download and verify the NEWER published release from git.eeee.moe;
|
||||
// 3. confirm install: the AppImage file is replaced and the app relaunches by itself after exiting;
|
||||
// 4. the relaunched process reports the new version; its file matches the release feed's sha512;
|
||||
// 5. start the new AppImage again: version, UID, nickname, bookmark and device pref are unchanged.
|
||||
//
|
||||
// xvfb-run -a node scripts/update-e2e.mjs --from <old.AppImage> --to-tag v0.1.2-rc.2 --out update-e2e-out
|
||||
//
|
||||
// Runs AppImages with APPIMAGE_EXTRACT_AND_RUN=1 (no FUSE needed). Everything lives in a temp directory:
|
||||
// profile, updater cache, the "installed" AppImage. The user's own installation is never touched.
|
||||
import { _electron as electron } from 'playwright-core';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { parseFeed } from './update-feed-check.mjs';
|
||||
|
||||
const argv = process.argv.slice(2);
|
||||
const opt = (n) => (argv.indexOf(`--${n}`) >= 0 ? argv[argv.indexOf(`--${n}`) + 1] : undefined);
|
||||
const fromImage = opt('from');
|
||||
const toTag = opt('to-tag');
|
||||
const out = path.resolve(opt('out') ?? 'update-e2e-out');
|
||||
if (!fromImage || !toTag || process.platform !== 'linux') {
|
||||
console.error('usage (Linux): update-e2e.mjs --from <old.AppImage> --to-tag <vX> [--out dir]');
|
||||
process.exit(2);
|
||||
}
|
||||
const toVersion = toTag.slice(1);
|
||||
const RELEASE = 'https://git.eeee.moe/TeamsPeach/client/releases/download';
|
||||
mkdirSync(out, { recursive: true });
|
||||
|
||||
const work = mkdtempSync(path.join(tmpdir(), 'teamspeach-update-e2e-'));
|
||||
const apps = path.join(work, 'apps');
|
||||
const profile = path.join(work, 'profile');
|
||||
mkdirSync(apps);
|
||||
const installed = path.join(apps, path.basename(fromImage));
|
||||
copyFileSync(fromImage, installed);
|
||||
chmodSync(installed, 0o755);
|
||||
const env = {
|
||||
...process.env,
|
||||
TEAMSPEACH_PROFILE_DIR: profile,
|
||||
XDG_CACHE_HOME: path.join(work, 'cache'),
|
||||
APPIMAGE_EXTRACT_AND_RUN: '1',
|
||||
};
|
||||
|
||||
const result = { startedAt: new Date().toISOString(), fromImage: path.basename(fromImage), toTag, steps: [] };
|
||||
const step = (name, data = {}) => {
|
||||
result.steps.push({ name, at: new Date().toISOString(), ...data });
|
||||
console.log(`[update-e2e] ${name} ${JSON.stringify(data)}`);
|
||||
};
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
const sha512 = (file) => createHash('sha512').update(readFileSync(file)).digest('base64');
|
||||
const updaterLog = () => {
|
||||
const file = path.join(profile, 'logs', 'updater.log');
|
||||
return existsSync(file) ? readFileSync(file, 'utf8') : '';
|
||||
};
|
||||
|
||||
async function launch(image, label) {
|
||||
const app = await electron.launch({ executablePath: image, args: ['--no-sandbox'], env, timeout: 120000 });
|
||||
const page = await app.firstWindow({ timeout: 120000 });
|
||||
page.on('console', (m) => m.type() === 'error' && step(`${label} console error`, { text: m.text().slice(0, 300) }));
|
||||
return { app, page };
|
||||
}
|
||||
const diag = (page) => page.evaluate(() => window.teamspeachDiagnostics.snapshot());
|
||||
|
||||
async function waitFor(fn, ms, what) {
|
||||
const end = Date.now() + ms;
|
||||
for (;;) {
|
||||
const v = await fn();
|
||||
if (v) return v;
|
||||
if (Date.now() > end) throw new Error(`timed out waiting for ${what}`);
|
||||
await sleep(1000);
|
||||
}
|
||||
}
|
||||
|
||||
let failed = null;
|
||||
try {
|
||||
// 1. Old version, fresh profile.
|
||||
let { app, page } = await launch(installed, 'old');
|
||||
await page.waitForSelector('#view-onboarding', { state: 'visible', timeout: 60000 });
|
||||
await page.fill('#onboarding-nick', 'UpdateProof');
|
||||
await page.click('#onboarding-submit');
|
||||
await page.waitForSelector('#view-app', { state: 'visible', timeout: 60000 });
|
||||
const before = await diag(page);
|
||||
const oldInfo = await page.evaluate(() => window.teamspeach.getAppInfo());
|
||||
const bookmark = { id: 'upd0001', name: 'Update proof', address: '192.0.2.10:9987' };
|
||||
await page.evaluate((b) => window.teamspeach.setPrefs({ savedServers: [b], inputDeviceId: 'update-proof-device' }), bookmark);
|
||||
step('old version running', { version: oldInfo.appVersion, uid: before.profile.uid, nickname: before.profile.nickname });
|
||||
|
||||
// 2. Real check + download from the public release server.
|
||||
const checked = await page.evaluate(() => window.teamspeach.checkForUpdates());
|
||||
step('check', { phase: checked.phase, available: checked.available, error: checked.error, skipped: checked.newerWithoutBuild });
|
||||
const ready = await waitFor(async () => {
|
||||
const s = await page.evaluate(() => window.teamspeach.getUpdateState());
|
||||
if (s.phase === 'error') throw new Error(`updater error ${JSON.stringify(s.error)}`);
|
||||
return s.phase === 'downloaded' && s;
|
||||
}, 600000, 'download');
|
||||
step('downloaded and verified by electron-updater', { available: ready.available, target: ready.target });
|
||||
if (ready.available.version !== toVersion) throw new Error(`offered ${ready.available.version}, expected ${toVersion}`);
|
||||
|
||||
// 3. User confirms install (also confirming interruption, as the UI would).
|
||||
const exited = new Promise((r) => app.process().once('exit', (code, signal) => r({ code, signal })));
|
||||
const install = await page.evaluate(() => window.teamspeach.installUpdate(true)).catch((e) => ({ evaluateEnded: e.message.slice(0, 200) }));
|
||||
step('install requested', { install });
|
||||
step('old process exited', await Promise.race([exited, sleep(180000).then(() => ({ timeout: true }))]));
|
||||
|
||||
// 4. Relaunch happened by itself: the new version logs its start with its pid.
|
||||
const started = await waitFor(() => {
|
||||
const m = new RegExp(`updater: version ${toVersion.replace(/\./g, '\\.')} pid (\\d+) target (\\S+)`).exec(updaterLog());
|
||||
return m && { pid: Number(m[1]), target: m[2] };
|
||||
}, 180000, 'relaunched new version');
|
||||
step('new version relaunched automatically', started);
|
||||
const files = readdirSync(apps);
|
||||
const newImage = path.join(apps, files.find((f) => f.endsWith('.AppImage')));
|
||||
const feedName = `${toVersion.includes('-') ? toVersion.split('-')[1].split('.')[0] : 'latest'}-linux.yml`;
|
||||
const feedRes = await fetch(`${RELEASE}/${toTag}/${feedName}`);
|
||||
if (!feedRes.ok) throw new Error(`feed ${feedName}: HTTP ${feedRes.status}`);
|
||||
const feed = parseFeed(await feedRes.text());
|
||||
const fileSha = sha512(newImage);
|
||||
step('installed file', { files, sha512MatchesFeed: fileSha === feed.files[0].sha512, feedFile: feed.files[0].url });
|
||||
if (files.length !== 1 || path.basename(newImage) !== feed.files[0].url || fileSha !== feed.files[0].sha512) {
|
||||
throw new Error('installed AppImage does not match the release feed');
|
||||
}
|
||||
process.kill(started.pid, 'SIGTERM');
|
||||
await waitFor(() => !existsSync(`/proc/${started.pid}`), 60000, 'relaunched app to exit');
|
||||
await sleep(2000);
|
||||
|
||||
// 5. Start the new AppImage again: same identity and preferences, new version.
|
||||
({ app, page } = await launch(newImage, 'new'));
|
||||
await page.waitForSelector('#view-app', { state: 'visible', timeout: 60000 });
|
||||
const after = await diag(page);
|
||||
const newInfo = await page.evaluate(() => window.teamspeach.getAppInfo());
|
||||
const prefs = await page.evaluate(() => window.teamspeach.getPrefs());
|
||||
const state = await page.evaluate(() => window.teamspeach.getUpdateState());
|
||||
await page.screenshot({ path: path.join(out, 'after-update.png') });
|
||||
await app.close();
|
||||
const kept = {
|
||||
version: newInfo.appVersion,
|
||||
uidSame: after.profile.uid === before.profile.uid,
|
||||
nicknameSame: after.profile.nickname === before.profile.nickname,
|
||||
bookmarkSame: JSON.stringify(prefs.savedServers) === JSON.stringify([bookmark]),
|
||||
deviceSame: prefs.inputDeviceId === 'update-proof-device',
|
||||
updater: { phase: state.phase, target: state.target, mode: state.mode },
|
||||
};
|
||||
step('after update', kept);
|
||||
if (kept.version !== toVersion || !kept.uidSame || !kept.nicknameSame || !kept.bookmarkSame || !kept.deviceSame) {
|
||||
throw new Error('state after update is wrong');
|
||||
}
|
||||
} catch (err) {
|
||||
failed = err;
|
||||
step('FAILED', { error: err.message });
|
||||
}
|
||||
result.updaterLog = updaterLog().split('\n').filter((l) => / updater: /.test(l));
|
||||
result.ok = !failed;
|
||||
writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2));
|
||||
process.exit(failed ? 1 : 0);
|
||||
@@ -0,0 +1,102 @@
|
||||
// Release gate for electron-updater feeds (latest.yml, latest-linux.yml, rc-linux-arm64.yml, …).
|
||||
// Every file a feed references must sit next to it under exactly that name, with the declared size and
|
||||
// sha512, and the feed version must be the expected one. A renamed or rebuilt package fails here instead
|
||||
// of failing on users' machines.
|
||||
//
|
||||
// node scripts/update-feed-check.mjs [--version 0.1.2-rc.1] <feed.yml> [...]
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createReadStream, readFileSync, statSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
export const FEED_NAME = /^[0-9A-Za-z][0-9A-Za-z-]*\.yml$/;
|
||||
|
||||
/** Parses the subset of YAML electron-builder writes for update info. Throws on anything else. */
|
||||
export function parseFeed(text) {
|
||||
const feed = { version: null, files: [] };
|
||||
let current = null;
|
||||
let inFiles = false;
|
||||
for (const raw of text.split(/\r?\n/)) {
|
||||
if (raw.trim() === '') continue;
|
||||
const top = /^([A-Za-z][A-Za-z0-9]*):\s*(.*)$/.exec(raw);
|
||||
if (top) {
|
||||
inFiles = top[1] === 'files' && top[2] === '';
|
||||
current = null;
|
||||
if (top[1] === 'version') feed.version = unquote(top[2]);
|
||||
continue;
|
||||
}
|
||||
const item = /^ {2}- ([A-Za-z][A-Za-z0-9]*):\s*(.*)$/.exec(raw);
|
||||
const field = /^ {4}([A-Za-z][A-Za-z0-9]*):\s*(.*)$/.exec(raw);
|
||||
if (inFiles && item) {
|
||||
current = {};
|
||||
feed.files.push(current);
|
||||
current[item[1]] = unquote(item[2]);
|
||||
} else if (inFiles && field && current) {
|
||||
current[field[1]] = unquote(field[2]);
|
||||
} else {
|
||||
throw new Error(`unexpected feed line: ${raw.slice(0, 80)}`);
|
||||
}
|
||||
}
|
||||
if (!feed.version) throw new Error('feed has no version');
|
||||
if (feed.files.length === 0) throw new Error('feed lists no files');
|
||||
for (const f of feed.files) {
|
||||
if (!f.url || !f.sha512 || !/^\d+$/.test(f.size ?? '')) throw new Error(`feed entry without url/sha512/size: ${JSON.stringify(f)}`);
|
||||
f.size = Number(f.size);
|
||||
}
|
||||
return feed;
|
||||
}
|
||||
|
||||
function unquote(v) {
|
||||
const s = v.trim();
|
||||
return /^'.*'$/.test(s) || /^".*"$/.test(s) ? s.slice(1, -1) : s;
|
||||
}
|
||||
|
||||
function sha512(file) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const hash = createHash('sha512');
|
||||
createReadStream(file).on('error', reject).on('data', (d) => hash.update(d)).on('end', () => resolve(hash.digest('base64')));
|
||||
});
|
||||
}
|
||||
|
||||
/** Returns the referenced file names; throws with a precise message when the feed and files disagree. */
|
||||
export async function checkFeed(feedFile, { version } = {}) {
|
||||
const name = path.basename(feedFile);
|
||||
if (!FEED_NAME.test(name)) throw new Error(`${name}: not an electron-updater feed name`);
|
||||
const feed = parseFeed(readFileSync(feedFile, 'utf8'));
|
||||
if (version && feed.version !== version) throw new Error(`${name}: version ${feed.version}, expected ${version}`);
|
||||
const dir = path.dirname(feedFile);
|
||||
for (const f of feed.files) {
|
||||
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(f.url)) throw new Error(`${name}: file name ${f.url} contains a path or characters a release asset cannot keep`);
|
||||
const file = path.join(dir, f.url);
|
||||
let size;
|
||||
try {
|
||||
size = statSync(file).size;
|
||||
} catch {
|
||||
throw new Error(`${name}: references ${f.url}, which is missing next to the feed (renamed?)`);
|
||||
}
|
||||
if (size !== f.size) throw new Error(`${name}: ${f.url} is ${size} bytes, feed says ${f.size}`);
|
||||
if ((await sha512(file)) !== f.sha512) throw new Error(`${name}: sha512 of ${f.url} differs from the feed`);
|
||||
}
|
||||
return feed.files.map((f) => f.url);
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const args = process.argv.slice(2);
|
||||
const vi = args.indexOf('--version');
|
||||
const version = vi >= 0 ? args.splice(vi, 2)[1] : undefined;
|
||||
if (args.length === 0) {
|
||||
console.error('usage: update-feed-check.mjs [--version X] <feed.yml> [...]');
|
||||
process.exit(2);
|
||||
}
|
||||
let failed = false;
|
||||
for (const feed of args) {
|
||||
try {
|
||||
const files = await checkFeed(feed, { version });
|
||||
console.log(`${path.basename(feed)}: ok (${files.join(', ')})`);
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
failed = true;
|
||||
}
|
||||
}
|
||||
process.exit(failed ? 1 : 0);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// Capture lifecycle of the AudioEngine with stubbed Web Audio / getUserMedia: a stop or a newer start
|
||||
// while the microphone request is pending must never leave a microphone open.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { AudioEngine } from '../app/renderer/js/audio/engine.js';
|
||||
|
||||
function fakeStream(name) {
|
||||
const track = {
|
||||
label: name,
|
||||
muted: false,
|
||||
stopped: false,
|
||||
stop() { this.stopped = true; },
|
||||
addEventListener() {},
|
||||
getSettings: () => ({ sampleRate: 48000, channelCount: 1 }),
|
||||
};
|
||||
return { name, track, getTracks: () => [track], getAudioTracks: () => [track] };
|
||||
}
|
||||
|
||||
const node = () => ({ connect(next) { return next ?? this; }, disconnect() {}, port: {}, gain: { value: 1 } });
|
||||
|
||||
/** Engine whose getUserMedia calls stay pending until the test resolves them in order. */
|
||||
function setup() {
|
||||
const pending = [];
|
||||
Object.defineProperty(globalThis, 'navigator', {
|
||||
configurable: true,
|
||||
value: { mediaDevices: { getUserMedia: () => new Promise((resolve, reject) => pending.push({ resolve, reject })) } },
|
||||
});
|
||||
globalThis.AudioWorkletNode = class { constructor() { Object.assign(this, node()); } };
|
||||
const engine = new AudioEngine({ onFrame() {}, log() {} });
|
||||
engine.init = async () => {};
|
||||
engine.ctx = { createMediaStreamSource: () => node(), createGain: node, destination: {} };
|
||||
return { engine, pending, flush: () => new Promise((r) => setTimeout(r, 0)) };
|
||||
}
|
||||
|
||||
test('stop while the microphone request is pending closes the late stream', async () => {
|
||||
const { engine, pending, flush } = setup();
|
||||
const started = engine.startCapture({});
|
||||
await flush();
|
||||
assert.equal(engine.captureStarting, true);
|
||||
engine.stopCapture();
|
||||
assert.equal(engine.captureStarting, false);
|
||||
const stream = fakeStream('late');
|
||||
pending[0].resolve(stream);
|
||||
assert.equal(await started, null);
|
||||
assert.equal(stream.track.stopped, true);
|
||||
assert.equal(engine.capturing, false);
|
||||
});
|
||||
|
||||
test('a newer start supersedes a pending one; only the newest stream stays open', async () => {
|
||||
const { engine, pending, flush } = setup();
|
||||
const first = engine.startCapture({});
|
||||
await flush();
|
||||
const second = engine.startCapture({});
|
||||
await flush();
|
||||
const a = fakeStream('first');
|
||||
const b = fakeStream('second');
|
||||
pending[1].resolve(b);
|
||||
assert.equal(await second, 'second');
|
||||
pending[0].resolve(a);
|
||||
assert.equal(await first, null);
|
||||
assert.equal(a.track.stopped, true);
|
||||
assert.equal(b.track.stopped, false);
|
||||
assert.equal(engine.capture.stream, b);
|
||||
engine.stopCapture();
|
||||
assert.equal(b.track.stopped, true);
|
||||
assert.equal(engine.capturing, false);
|
||||
});
|
||||
|
||||
test('a failure of a superseded start is ignored; a current failure is reported', async () => {
|
||||
const { engine, pending, flush } = setup();
|
||||
const stale = engine.startCapture({});
|
||||
await flush();
|
||||
engine.stopCapture();
|
||||
pending[0].reject(Object.assign(new Error('denied'), { name: 'NotAllowedError' }));
|
||||
assert.equal(await stale, null);
|
||||
const current = engine.startCapture({});
|
||||
await flush();
|
||||
pending[1].reject(Object.assign(new Error('denied'), { name: 'NotAllowedError' }));
|
||||
await assert.rejects(current, { name: 'NotAllowedError' });
|
||||
assert.equal(engine.captureStarting, false);
|
||||
});
|
||||
@@ -11,26 +11,28 @@ test('without media permission Chromium returns one anonymous entry: reported as
|
||||
|
||||
test('aliases are folded into the default option, physical endpoints listed with real ids', () => {
|
||||
const list = [
|
||||
{ deviceId: 'default', label: 'По умолчанию - Mic/Line/Inst 1-2 (MiniFuse 4)' },
|
||||
{ deviceId: 'communications', label: 'Связь - Mic/Line/Inst 1-2 (MiniFuse 4)' },
|
||||
{ deviceId: 'default', label: '\u041f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e - Mic/Line/Inst 1-2 (MiniFuse 4)' },
|
||||
{ deviceId: 'communications', label: '\u0421\u0432\u044f\u0437\u044c - Mic/Line/Inst 1-2 (MiniFuse 4)' },
|
||||
{ deviceId: 'a1b2c3d4e5', label: 'Mic/Line/Inst 1-2 (MiniFuse 4)' },
|
||||
{ deviceId: 'f6g7h8i9j0', label: 'Микрофон (DroidCam Audio)' },
|
||||
{ deviceId: 'f6g7h8i9j0', label: '\u041c\u0438\u043a\u0440\u043e\u0444\u043e\u043d (DroidCam Audio)' },
|
||||
];
|
||||
const r = buildDeviceOptions(list, '');
|
||||
assert.equal(r.redacted, false);
|
||||
assert.equal(r.physical, 2);
|
||||
assert.equal(r.options[0].label, 'Системное по умолчанию (Mic/Line/Inst 1-2 (MiniFuse 4))');
|
||||
assert.ok(r.options[0].label.includes(list[2].label));
|
||||
assert.equal(r.options[2].label, list[3].label);
|
||||
assert.deepEqual(r.options.slice(1).map((o) => o.value), ['a1b2c3d4e5', 'f6g7h8i9j0']);
|
||||
});
|
||||
|
||||
test('an unnamed physical device keeps its real id and an honest label', () => {
|
||||
const r = buildDeviceOptions([{ deviceId: 'zz99yy88xx77', label: '' }], '');
|
||||
assert.equal(r.options[1].value, 'zz99yy88xx77');
|
||||
assert.equal(r.options[1].label, 'Устройство без названия (zz99yy88)');
|
||||
assert.ok(r.options[1].label.includes('zz99yy88'));
|
||||
});
|
||||
|
||||
test('a saved device that is currently absent stays selectable and is labelled as missing', () => {
|
||||
const r = buildDeviceOptions([{ deviceId: 'a1', label: 'A' }], 'gone-device');
|
||||
assert.equal(r.options.at(-1).value, 'gone-device');
|
||||
assert.match(r.options.at(-1).label, /не найдено/);
|
||||
assert.ok(r.options.at(-1).label.length > 0);
|
||||
assert.equal(r.options.length, 3);
|
||||
});
|
||||
Vendored
+210
@@ -0,0 +1,210 @@
|
||||
'use strict';
|
||||
|
||||
// Electron main-process harness for test/update-engine.test.mjs. Runs the real update service with the real
|
||||
// electron-updater (NSIS updater on Windows, AppImage updater on Linux) against a release server emulated at
|
||||
// the protocol layer of BOTH sessions involved (default session: release list; "electron-updater": feeds and
|
||||
// packages), so HTTP handling, sha512 verification and the download cache are the library's own.
|
||||
// Never installs anything. Prints one JSON line with the scenario results and exits.
|
||||
|
||||
const crypto = require('node:crypto');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { app, session } = require('electron');
|
||||
|
||||
const repo = process.env.UPDATE_HARNESS_REPO;
|
||||
const tmp = process.env.UPDATE_HARNESS_TMP;
|
||||
app.setPath('userData', path.join(tmp, 'userData'));
|
||||
|
||||
const source = require(path.join(repo, 'app/main/update-source.js'));
|
||||
const { createUpdateService, createElectronUpdater } = require(path.join(repo, 'app/main/updates.js'));
|
||||
|
||||
const TARGET = process.platform === 'win32'
|
||||
? { id: 'win-x64-nsis', platform: 'win32', arch: 'x64', mode: 'auto', kind: 'nsis', disabledCode: null }
|
||||
: { id: `linux-${process.arch}-appimage`, platform: 'linux', arch: process.arch, mode: 'auto', kind: 'appimage', disabledCode: null };
|
||||
const OTHER_ARCH = TARGET.kind === 'nsis' ? { ...TARGET, arch: 'arm64' } : { ...TARGET, arch: TARGET.arch === 'x64' ? 'arm64' : 'x64' };
|
||||
|
||||
const sha512 = (b) => crypto.createHash('sha512').update(b).digest('base64');
|
||||
|
||||
// ---------- emulated release server ----------
|
||||
let releases = [];
|
||||
const files = new Map(); // "<tag>/<name>" → { bytes } | { status } | { gate: Promise<Buffer> }
|
||||
const requests = [];
|
||||
|
||||
function feedYaml(version, name, bytes, shaOf = bytes) {
|
||||
return Buffer.from(
|
||||
`version: ${version}\nfiles:\n - url: ${name}\n sha512: ${sha512(shaOf)}\n size: ${bytes.length}\npath: ${name}\nsha512: ${sha512(shaOf)}\nreleaseDate: '2026-10-24T00:00:00.000Z'\n`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Adds a release; options shape its feed: corrupt sha, other-arch package, missing feed file, gated feed. */
|
||||
function addRelease(tag, { prerelease = true, draft = false, corrupt = false, otherArch = false, feedStatus = null, gate = null } = {}) {
|
||||
const version = tag.slice(1);
|
||||
const bytes = crypto.randomBytes(200 * 1024);
|
||||
const pkg = source.packageFileName(TARGET, version);
|
||||
const otherPkg = source.packageFileName(OTHER_ARCH, version);
|
||||
const feed = source.feedFileName(TARGET, version);
|
||||
const assets = new Map([[pkg, bytes], [otherPkg, bytes]]);
|
||||
const feedName = otherArch ? otherPkg : pkg;
|
||||
const feedBytes = feedYaml(version, feedName, bytes, corrupt ? crypto.randomBytes(bytes.length) : bytes);
|
||||
assets.set(feed, feedBytes);
|
||||
for (const [name, b] of assets) files.set(`${tag}/${name}`, { bytes: b });
|
||||
if (feedStatus) files.set(`${tag}/${feed}`, { status: feedStatus });
|
||||
if (gate) files.set(`${tag}/${feed}`, { gate: gate.then(() => feedBytes) });
|
||||
releases.push({ tag_name: tag, draft, prerelease, published_at: '2026-10-24T00:00:00Z', assets: [...assets].map(([name, b]) => ({ name, size: b.length })) });
|
||||
return { bytes, pkg };
|
||||
}
|
||||
|
||||
async function handle(req) {
|
||||
const url = new URL(req.url);
|
||||
requests.push({ url: req.url, auth: req.headers.get('authorization') });
|
||||
if (url.host !== 'git.eeee.moe') return new Response('unexpected host', { status: 599 });
|
||||
if (url.pathname === '/api/v1/repos/TeamsPeach/client/releases') {
|
||||
if (releases === 'network-error') return Response.error();
|
||||
const page = Number(url.searchParams.get('page'));
|
||||
const body = page === 1 ? releases : [];
|
||||
return new Response(JSON.stringify(body), { headers: { 'content-type': 'application/json', 'x-total-count': String(releases.length) } });
|
||||
}
|
||||
const m = /^\/TeamsPeach\/client\/releases\/download\/([^/]+)\/([^/]+)$/.exec(url.pathname);
|
||||
const entry = m && files.get(`${m[1]}/${decodeURIComponent(m[2])}`);
|
||||
if (!entry) return new Response('not found', { status: 404 });
|
||||
if (entry.status) return new Response('x', { status: entry.status });
|
||||
const bytes = entry.gate ? await entry.gate : entry.bytes;
|
||||
return new Response(bytes, { headers: { 'content-length': String(bytes.length) } });
|
||||
}
|
||||
|
||||
// ---------- scenarios ----------
|
||||
const cacheDirName = `teamspeach-updater-harness-${process.pid}`;
|
||||
const updateConfig = path.join(tmp, 'app-update.yml');
|
||||
fs.writeFileSync(updateConfig, `provider: generic\nurl: https://git.eeee.moe/\nupdaterCacheDirName: ${cacheDirName}\n`);
|
||||
|
||||
function service({ channel = 'preview', sessionActive = false, feedTimeoutMs } = {}) {
|
||||
const prefsValues = { updateChannel: channel };
|
||||
const session = { active: sessionActive };
|
||||
const svc = createUpdateService({
|
||||
prefs: { get: () => ({ ...prefsValues }), set: (p) => Object.assign(prefsValues, p) },
|
||||
isSessionActive: () => session.active,
|
||||
send: () => {},
|
||||
target: TARGET,
|
||||
feedTimeoutMs,
|
||||
createUpdater: (t, logger, ch) => {
|
||||
const u = createElectronUpdater(t, logger, ch);
|
||||
u.forceDevUpdateConfig = true;
|
||||
u.updateConfigPath = updateConfig;
|
||||
return u;
|
||||
},
|
||||
});
|
||||
return { svc, session };
|
||||
}
|
||||
|
||||
function reset() {
|
||||
releases = [];
|
||||
files.clear();
|
||||
requests.length = 0;
|
||||
}
|
||||
|
||||
const pick = (s) => ({ phase: s.phase, available: s.available && s.available.version, error: s.error, newerWithoutBuild: s.newerWithoutBuild, newerPreview: s.newerPreview, lastCheckedAt: s.lastCheckedAt });
|
||||
|
||||
function cachedPackageSha() {
|
||||
const dir = path.join(process.env.LOCALAPPDATA || process.env.XDG_CACHE_HOME, cacheDirName, 'pending');
|
||||
const name = fs.existsSync(dir) ? fs.readdirSync(dir).find((n) => n !== 'update-info.json' && !n.startsWith('temp')) : null;
|
||||
return name ? sha512(fs.readFileSync(path.join(dir, name))) : null;
|
||||
}
|
||||
|
||||
const scenarios = {
|
||||
async happy() {
|
||||
addRelease('v0.1.1');
|
||||
const good = addRelease('v0.1.2-rc.2');
|
||||
addRelease('v0.1.3', { draft: true });
|
||||
const { svc } = service();
|
||||
const s = await svc.check({ manual: true });
|
||||
return {
|
||||
...pick(s),
|
||||
cachedShaMatches: cachedPackageSha() === sha512(good.bytes),
|
||||
draftFetched: requests.some((r) => r.url.includes('/v0.1.3/')),
|
||||
anyAuth: requests.some((r) => r.auth),
|
||||
};
|
||||
},
|
||||
async sessionGate() {
|
||||
addRelease('v0.1.2-rc.2');
|
||||
const { svc } = service({ sessionActive: true });
|
||||
const deferred = await svc.check({ manual: false });
|
||||
const packageRequestedWhileDeferred = requests.some((r) => /\.(exe|AppImage)(\?|$)/.test(r.url));
|
||||
const downloaded = await svc.download({ manual: true });
|
||||
const install = svc.install({});
|
||||
return { deferred: deferred.phase, packageRequestedWhileDeferred, downloaded: downloaded.phase, install, stillDownloaded: svc.getState().phase };
|
||||
},
|
||||
async checksum() {
|
||||
addRelease('v0.1.2-rc.2', { corrupt: true });
|
||||
const { svc } = service();
|
||||
const s = await svc.check({ manual: true });
|
||||
return { ...pick(s), install: svc.install({ confirmInterrupt: true }) };
|
||||
},
|
||||
async wrongArch() {
|
||||
addRelease('v0.1.3', { otherArch: true });
|
||||
addRelease('v0.1.2-rc.2');
|
||||
const { svc } = service();
|
||||
return pick(await svc.check({ manual: true }));
|
||||
},
|
||||
async missingFeedFile() {
|
||||
addRelease('v0.1.3', { feedStatus: 404 });
|
||||
const { svc } = service();
|
||||
return pick(await svc.check({ manual: true }));
|
||||
},
|
||||
async timeoutThenLateResult() {
|
||||
let open;
|
||||
const gate = new Promise((r) => {
|
||||
open = r;
|
||||
});
|
||||
addRelease('v0.1.3', { gate });
|
||||
const { svc, session } = service({ feedTimeoutMs: 1500 });
|
||||
const timedOut = pick(await svc.check({ manual: true }));
|
||||
reset();
|
||||
addRelease('v0.1.2-rc.2');
|
||||
const second = pick(await svc.check({ manual: true }));
|
||||
open();
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
session.active = true;
|
||||
return { timedOut, second, afterLate: pick(svc.getState()), install: svc.install({}) };
|
||||
},
|
||||
async networkDown() {
|
||||
releases = 'network-error';
|
||||
const { svc } = service();
|
||||
return pick(await svc.check({ manual: true }));
|
||||
},
|
||||
async stableChannel() {
|
||||
addRelease('v0.1.2-rc.2');
|
||||
addRelease('v0.1.3', { prerelease: true });
|
||||
const { svc } = service({ channel: 'stable' });
|
||||
return pick(await svc.check({ manual: true }));
|
||||
},
|
||||
async sameAndOlder() {
|
||||
addRelease('v0.1.2-rc.1');
|
||||
addRelease('v0.1.1');
|
||||
addRelease('v0.1.2-beta.9');
|
||||
const { svc } = service();
|
||||
const s = pick(await svc.check({ manual: true }));
|
||||
return { ...s, feedRequests: requests.filter((r) => r.url.endsWith('.yml') || r.url.includes('.yml?')).length };
|
||||
},
|
||||
};
|
||||
|
||||
async function run() {
|
||||
for (const ses of [session.defaultSession, session.fromPartition('electron-updater', { cache: false })]) ses.protocol.handle('https', handle);
|
||||
const results = { version: app.getVersion(), target: TARGET.id };
|
||||
for (const [name, fn] of Object.entries(scenarios)) {
|
||||
reset();
|
||||
try {
|
||||
results[name] = await fn();
|
||||
} catch (err) {
|
||||
results[name] = { thrown: err && err.stack ? err.stack : String(err) };
|
||||
}
|
||||
}
|
||||
process.stdout.write(`UPDATE_HARNESS_RESULT ${JSON.stringify(results)}\n`);
|
||||
}
|
||||
|
||||
app.whenReady().then(run).then(
|
||||
() => app.exit(0),
|
||||
(err) => {
|
||||
process.stdout.write(`UPDATE_HARNESS_FATAL ${err && err.stack}\n`);
|
||||
app.exit(1);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,64 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import shared from '../app/renderer/shared/i18n.js';
|
||||
import { setLanguage, getLanguage, t, onLanguageChange } from '../app/renderer/js/i18n.js';
|
||||
import { errorText, pluralMembers, keyLabel } from '../app/renderer/js/text.js';
|
||||
import { buildDeviceOptions } from '../app/renderer/js/audio/devices.js';
|
||||
|
||||
const placeholders = (value) => [...new Set(Object.values(typeof value === 'string' ? { value } : value).flatMap((text) => [...text.matchAll(/\{(\w+)\}/g)].map((match) => match[1])))].sort();
|
||||
|
||||
test('catalogs have identical keys and parameters and every message can be formatted', () => {
|
||||
assert.deepEqual(Object.keys(shared.catalogs.en).sort(), Object.keys(shared.catalogs.ru).sort());
|
||||
for (const key of Object.keys(shared.catalogs.en)) {
|
||||
assert.deepEqual(placeholders(shared.catalogs.en[key]), placeholders(shared.catalogs.ru[key]), key);
|
||||
const params = Object.fromEntries(placeholders(shared.catalogs.en[key]).map((name) => [name, name === 'count' ? 5 : `<${name}>`]));
|
||||
for (const language of shared.languages) {
|
||||
const value = shared.t(key, params, language);
|
||||
assert.equal(typeof value, 'string', key);
|
||||
assert.ok(value.length > 0, key);
|
||||
assert.ok(!/\{\w+\}/.test(value), key);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('English is the explicit default; missing keys and parameters are programming errors', () => {
|
||||
assert.equal(shared.normalizeLanguage(undefined), 'en');
|
||||
assert.equal(shared.normalizeLanguage('ru-RU'), 'en');
|
||||
assert.equal(shared.t('language.label'), shared.catalogs.en['language.label']);
|
||||
assert.throws(() => shared.t('missing.key'), /Missing translation key/);
|
||||
assert.throws(() => shared.t('members.count'), /Missing translation parameter/);
|
||||
});
|
||||
|
||||
test('English and Russian plural categories and number formatting use Intl', () => {
|
||||
for (const language of shared.languages) {
|
||||
setLanguage(language);
|
||||
for (const count of [0, 1, 2, 5, 11, 21, 22, 25, 101, 1000, 1.5]) {
|
||||
const category = new Intl.PluralRules(language).select(count);
|
||||
const forms = shared.catalogs[language]['members.count'];
|
||||
assert.equal(pluralMembers(count), (forms[category] ?? forms.other).replace('{count}', new Intl.NumberFormat(language).format(count)));
|
||||
}
|
||||
}
|
||||
setLanguage('en');
|
||||
});
|
||||
|
||||
test('switching changes presentation only, preserves raw data and notifies once per change', () => {
|
||||
setLanguage('en');
|
||||
const raw = '<script>user supplied & text</script>';
|
||||
const device = { deviceId: 'device-42', label: raw };
|
||||
let notifications = 0;
|
||||
const unsubscribe = onLanguageChange(() => notifications++);
|
||||
const englishKey = keyLabel('Space');
|
||||
const englishError = errorText({ code: 'device_lost', message: raw });
|
||||
setLanguage('ru');
|
||||
assert.equal(getLanguage(), 'ru');
|
||||
assert.notEqual(keyLabel('Space'), englishKey);
|
||||
assert.notEqual(errorText({ code: 'device_lost', message: raw }), englishError);
|
||||
assert.ok(errorText({ code: 'unrecognized', message: raw }).includes(raw));
|
||||
assert.equal(buildDeviceOptions([device], device.deviceId).options[1].label, raw);
|
||||
assert.ok(t('message.server.p0.saved', { p0: raw }).includes(raw));
|
||||
setLanguage('ru');
|
||||
assert.equal(notifications, 1);
|
||||
setLanguage('en');
|
||||
assert.equal(notifications, 2);
|
||||
unsubscribe();
|
||||
});
|
||||
+23
-3
@@ -17,13 +17,13 @@ test('saved servers: add, edit, remove persist across instances', () => {
|
||||
try {
|
||||
let p = new Prefs(file);
|
||||
assert.deepEqual(p.get().savedServers, []);
|
||||
p.set({ savedServers: [{ id: 'abc123', name: 'Дом', address: '10.10.10.160:9987' }, { id: 'def456', name: 'Test', address: 'example.org' }] });
|
||||
p.set({ savedServers: [{ id: 'abc123', name: '\u0414\u043e\u043c', address: '10.10.10.160:9987' }, { id: 'def456', name: 'Test', address: 'example.org' }] });
|
||||
p = new Prefs(file);
|
||||
assert.equal(p.get().savedServers.length, 2);
|
||||
p.set({ savedServers: p.get().savedServers.map((s) => (s.id === 'abc123' ? { ...s, name: 'Без негатива' } : s)) });
|
||||
p.set({ savedServers: p.get().savedServers.map((s) => (s.id === 'abc123' ? { ...s, name: '\u0411\u0435\u0437 \u043d\u0435\u0433\u0430\u0442\u0438\u0432\u0430' } : s)) });
|
||||
p.set({ savedServers: p.get().savedServers.filter((s) => s.id !== 'def456') });
|
||||
p = new Prefs(file);
|
||||
assert.deepEqual(p.get().savedServers, [{ id: 'abc123', name: 'Без негатива', address: '10.10.10.160:9987' }]);
|
||||
assert.deepEqual(p.get().savedServers, [{ id: 'abc123', name: '\u0411\u0435\u0437 \u043d\u0435\u0433\u0430\u0442\u0438\u0432\u0430', address: '10.10.10.160:9987' }]);
|
||||
} finally {
|
||||
cleanup();
|
||||
}
|
||||
@@ -90,3 +90,23 @@ test('theme: stored choices survive an update and are never rewritten', () => {
|
||||
cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('language: English by default, a stored choice is kept and independent of the theme', () => {
|
||||
const { file, cleanup } = tempFile();
|
||||
try {
|
||||
assert.equal(new Prefs(file).get().language, 'en');
|
||||
fs.writeFileSync(file, JSON.stringify({ theme: 'light' }));
|
||||
assert.deepEqual([new Prefs(file).get().language, new Prefs(file).get().theme], ['en', 'light']);
|
||||
fs.writeFileSync(file, JSON.stringify({ language: 'ru' }));
|
||||
let p = new Prefs(file);
|
||||
assert.deepEqual([p.get().language, p.get().theme], ['ru', 'dark']);
|
||||
fs.writeFileSync(file, JSON.stringify({ language: 'de' }));
|
||||
assert.equal(new Prefs(file).get().language, 'en', 'unknown language falls back to the default');
|
||||
p = new Prefs(file);
|
||||
assert.throws(() => p.set({ language: 'fr' }));
|
||||
p.set({ language: 'ru' });
|
||||
assert.equal(new Prefs(file).get().language, 'ru');
|
||||
} finally {
|
||||
cleanup();
|
||||
}
|
||||
});
|
||||
@@ -5,8 +5,8 @@ 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.handle('notifystreaminfo', [{ id: 'c4', clid: '16', name: '\u042d\u043a\u0440\u0430\u043d 1', audio: '0', mode: '1', return_code: '2' }]), true);
|
||||
assert.equal(d.byClient(16).name, '\u042d\u043a\u0440\u0430\u043d 1');
|
||||
assert.equal(d.get('c4').fields.audio, '0');
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
// Behaviour of the update service with the real electron-updater inside Electron (see
|
||||
// test/fixtures/update-harness.cjs). Needs a display on Linux (CI runs it under xvfb-run).
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const noDisplay = process.platform === 'linux' && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY;
|
||||
|
||||
async function runHarness() {
|
||||
const tmp = mkdtempSync(path.join(os.tmpdir(), 'teamspeach-update-'));
|
||||
try {
|
||||
const appDir = path.join(tmp, 'app');
|
||||
const cache = path.join(tmp, 'cache');
|
||||
for (const d of [appDir, cache]) mkdirSync(d, { recursive: true });
|
||||
// The running version comes from this package.json (app.getVersion()).
|
||||
writeFileSync(path.join(appDir, 'package.json'), JSON.stringify({ name: 'teamspeach-update-harness', version: '0.1.2-rc.1', main: 'main.js' }));
|
||||
writeFileSync(path.join(appDir, 'main.js'), `require(${JSON.stringify(path.join(repo, 'test', 'fixtures', 'update-harness.cjs'))});\n`);
|
||||
const oldAppImage = path.join(tmp, 'TeamsPeach-0.1.2-rc.1.AppImage');
|
||||
writeFileSync(oldAppImage, 'old');
|
||||
const args = [appDir];
|
||||
if (process.platform === 'linux') args.push('--no-sandbox');
|
||||
const env = {
|
||||
...process.env,
|
||||
UPDATE_HARNESS_REPO: repo,
|
||||
UPDATE_HARNESS_TMP: tmp,
|
||||
// electron-updater's download cache lives under these; keep it inside the temp dir.
|
||||
LOCALAPPDATA: cache,
|
||||
XDG_CACHE_HOME: cache,
|
||||
APPIMAGE: oldAppImage,
|
||||
ELECTRON_ENABLE_LOGGING: '',
|
||||
};
|
||||
delete env.ELECTRON_RUN_AS_NODE;
|
||||
const child = spawn(require('electron'), args, { env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
let out = '';
|
||||
let err = '';
|
||||
child.stdout.on('data', (d) => (out += d));
|
||||
child.stderr.on('data', (d) => (err += d));
|
||||
const timer = setTimeout(() => child.kill(), 120000);
|
||||
const code = await new Promise((r) => child.on('exit', r));
|
||||
clearTimeout(timer);
|
||||
const line = out.split('\n').find((l) => l.startsWith('UPDATE_HARNESS_RESULT '));
|
||||
if (!line) throw new Error(`harness failed (exit ${code}):\n${out}\n${err.slice(-4000)}`);
|
||||
return JSON.parse(line.slice('UPDATE_HARNESS_RESULT '.length));
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
test('update service + electron-updater behaviour against an emulated Gitea release server', { skip: noDisplay && 'no display (run under xvfb-run)', timeout: 180000 }, async (t) => {
|
||||
const r = await runHarness();
|
||||
for (const [name, v] of Object.entries(r)) if (v && v.thrown) assert.fail(`${name}: ${v.thrown}`);
|
||||
assert.equal(r.version, '0.1.2-rc.1');
|
||||
|
||||
await t.test('newest eligible release is found, downloaded and sha512-verified; drafts untouched; no credentials', () => {
|
||||
assert.equal(r.happy.phase, 'downloaded');
|
||||
assert.equal(r.happy.available, '0.1.2-rc.2');
|
||||
assert.equal(r.happy.cachedShaMatches, true);
|
||||
assert.equal(r.happy.draftFetched, false);
|
||||
assert.equal(r.happy.anyAuth, false);
|
||||
});
|
||||
|
||||
await t.test('in a call: background download waits, install needs explicit confirmation', () => {
|
||||
assert.equal(r.sessionGate.deferred, 'deferred');
|
||||
assert.equal(r.sessionGate.packageRequestedWhileDeferred, false);
|
||||
assert.equal(r.sessionGate.downloaded, 'downloaded');
|
||||
assert.deepEqual(r.sessionGate.install, { ok: false, code: 'session-active' });
|
||||
assert.equal(r.sessionGate.stillDownloaded, 'downloaded');
|
||||
});
|
||||
|
||||
await t.test('corrupt package: checksum error, nothing installable', () => {
|
||||
assert.equal(r.checksum.phase, 'error');
|
||||
assert.equal(r.checksum.error.code, 'checksum');
|
||||
assert.equal(r.checksum.install.code, 'not-ready');
|
||||
});
|
||||
|
||||
await t.test('feed pointing at the other architecture is skipped in favour of an older complete release', () => {
|
||||
assert.equal(r.wrongArch.phase, 'downloaded');
|
||||
assert.equal(r.wrongArch.available, '0.1.2-rc.2');
|
||||
assert.deepEqual(r.wrongArch.newerWithoutBuild.map((x) => [x.version, x.code]), [['0.1.3', 'feed-mismatch']]);
|
||||
});
|
||||
|
||||
await t.test('feed listed but not downloadable: skipped, reported, up to date otherwise', () => {
|
||||
assert.equal(r.missingFeedFile.phase, 'up-to-date');
|
||||
assert.deepEqual(r.missingFeedFile.newerWithoutBuild.map((x) => [x.version, x.code]), [['0.1.3', 'incomplete-release']]);
|
||||
});
|
||||
|
||||
await t.test('feed timeout is an error; its late answer cannot change the next offer or download', () => {
|
||||
assert.equal(r.timeoutThenLateResult.timedOut.phase, 'error');
|
||||
assert.equal(r.timeoutThenLateResult.timedOut.error.code, 'timeout');
|
||||
assert.equal(r.timeoutThenLateResult.timedOut.lastCheckedAt, null);
|
||||
assert.equal(r.timeoutThenLateResult.second.phase, 'downloaded');
|
||||
assert.equal(r.timeoutThenLateResult.second.available, '0.1.2-rc.2');
|
||||
assert.equal(r.timeoutThenLateResult.afterLate.phase, 'downloaded');
|
||||
assert.equal(r.timeoutThenLateResult.afterLate.available, '0.1.2-rc.2');
|
||||
assert.deepEqual(r.timeoutThenLateResult.install, { ok: false, code: 'session-active' });
|
||||
});
|
||||
|
||||
await t.test('release server unreachable: error, never "up to date"', () => {
|
||||
assert.equal(r.networkDown.phase, 'error');
|
||||
assert.equal(r.networkDown.error.code, 'network');
|
||||
assert.equal(r.networkDown.lastCheckedAt, null);
|
||||
});
|
||||
|
||||
await t.test('stable channel ignores previews and says which one exists', () => {
|
||||
assert.equal(r.stableChannel.phase, 'up-to-date');
|
||||
assert.equal(r.stableChannel.newerPreview, '0.1.3');
|
||||
});
|
||||
|
||||
await t.test('same version, older versions and older prereleases are not even fetched', () => {
|
||||
assert.equal(r.sameAndOlder.phase, 'up-to-date');
|
||||
assert.equal(r.sameAndOlder.feedRequests, 0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
// Release gate for electron-updater feeds, on a feed serialized exactly like electron-builder does.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { checkFeed } from '../scripts/update-feed-check.mjs';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { serializeToYaml } = require('builder-util/out/util.js');
|
||||
|
||||
function fixture() {
|
||||
const dir = mkdtempSync(path.join(os.tmpdir(), 'teamspeach-feed-'));
|
||||
const name = 'TeamsPeach-0.1.2-rc.1-arm64.AppImage';
|
||||
const bytes = randomBytes(4096);
|
||||
writeFileSync(path.join(dir, name), bytes);
|
||||
const sha512 = createHash('sha512').update(bytes).digest('base64');
|
||||
const feed = path.join(dir, 'rc-linux-arm64.yml');
|
||||
writeFileSync(feed, serializeToYaml({ version: '0.1.2-rc.1', files: [{ url: name, sha512, size: bytes.length, blockMapSize: 100 }], path: name, sha512, releaseDate: new Date().toISOString() }, false, true));
|
||||
return { dir, name, feed, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
|
||||
}
|
||||
|
||||
test('a builder feed next to its unchanged package passes', async () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
assert.deepEqual(await checkFeed(f.feed, { version: '0.1.2-rc.1' }), [f.name]);
|
||||
} finally {
|
||||
f.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('renamed package, changed bytes or wrong version fail the release', async () => {
|
||||
let f = fixture();
|
||||
try {
|
||||
await assert.rejects(checkFeed(f.feed, { version: '0.1.2' }), /version 0\.1\.2-rc\.1, expected 0\.1\.2/);
|
||||
renameSync(path.join(f.dir, f.name), path.join(f.dir, 'TeamsPeach-0.1.2-rc.1-linux-arm64-local.AppImage'));
|
||||
await assert.rejects(checkFeed(f.feed), /missing next to the feed/);
|
||||
} finally {
|
||||
f.cleanup();
|
||||
}
|
||||
f = fixture();
|
||||
try {
|
||||
writeFileSync(path.join(f.dir, f.name), randomBytes(4096));
|
||||
await assert.rejects(checkFeed(f.feed), /sha512 of .* differs/);
|
||||
writeFileSync(path.join(f.dir, f.name), randomBytes(10));
|
||||
await assert.rejects(checkFeed(f.feed), /is 10 bytes/);
|
||||
} finally {
|
||||
f.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,289 @@
|
||||
'use strict';
|
||||
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const http = require('node:http');
|
||||
const {
|
||||
RELEASES_API,
|
||||
UpdateError,
|
||||
cleanVersion,
|
||||
packageFileName,
|
||||
detectTarget,
|
||||
selectReleases,
|
||||
verifyFeed,
|
||||
fetchReleases,
|
||||
} = require('../app/main/update-source');
|
||||
|
||||
const SHA = `${'A'.repeat(86)}==`;
|
||||
const APPIMAGE_X64 = { id: 'linux-x64-appimage', platform: 'linux', arch: 'x64', mode: 'auto', kind: 'appimage' };
|
||||
const APPIMAGE_ARM = { id: 'linux-arm64-appimage', platform: 'linux', arch: 'arm64', mode: 'auto', kind: 'appimage' };
|
||||
const NSIS = { id: 'win-x64-nsis', platform: 'win32', arch: 'x64', mode: 'auto', kind: 'nsis' };
|
||||
const TARGZ_ARM = { id: 'linux-arm64-tar.gz', platform: 'linux', arch: 'arm64', mode: 'manual', kind: 'tar.gz' };
|
||||
const ZIP = { id: 'win-x64-zip', platform: 'win32', arch: 'x64', mode: 'manual', kind: 'zip' };
|
||||
|
||||
/** A release shaped like Gitea's API answer, with the assets electron-builder + the release flow produce. */
|
||||
function release(tag, { prerelease = true, draft = false, platforms = ['linux-x64', 'linux-arm64', 'win-x64'] } = {}) {
|
||||
const v = tag.slice(1);
|
||||
const ch = v.includes('-') ? v.split('-')[1].split('.')[0] : 'latest';
|
||||
const assets = [{ name: `build-info-linux-x64.txt`, size: 100 }];
|
||||
if (platforms.includes('linux-x64')) {
|
||||
assets.push({ name: `TeamsPeach-${v}.AppImage`, size: 1000 }, { name: `teamspeach-${v}.tar.gz`, size: 900 }, { name: `${ch}-linux.yml`, size: 400 });
|
||||
}
|
||||
if (platforms.includes('linux-arm64')) {
|
||||
assets.push({ name: `TeamsPeach-${v}-arm64.AppImage`, size: 1001 }, { name: `teamspeach-${v}-arm64.tar.gz`, size: 901 }, { name: `${ch}-linux-arm64.yml`, size: 401 });
|
||||
}
|
||||
if (platforms.includes('win-x64')) {
|
||||
assets.push(
|
||||
{ name: `TeamsPeach-${v}-win-x64-setup.exe`, size: 2000 },
|
||||
{ name: `TeamsPeach-${v}-win-x64-setup.exe.blockmap`, size: 20 },
|
||||
{ name: `TeamsPeach-${v}-win-x64-local.zip`, size: 3000 },
|
||||
{ name: `${ch}.yml`, size: 300 },
|
||||
);
|
||||
}
|
||||
return { tag_name: tag, draft, prerelease, published_at: '2026-10-24T00:00:00Z', assets };
|
||||
}
|
||||
|
||||
const versions = (sel) => sel.candidates.map((c) => c.version);
|
||||
|
||||
test('release ordering follows SemVer 2.0 (prerelease < release, numeric < alphanumeric)', () => {
|
||||
const order = ['0.1.2-alpha', '0.1.2-alpha.1', '0.1.2-alpha.beta', '0.1.2-beta', '0.1.2-beta.2', '0.1.2-beta.11', '0.1.2-rc.1', '0.1.2', '0.1.10', '0.2.0', '1.0.0'];
|
||||
const shuffled = [...order].reverse().concat(order.slice(3, 6)).map((v) => release(`v${v}`));
|
||||
const sel = selectReleases([...new Map(shuffled.map((r) => [r.tag_name, r])).values()], { currentVersion: '0.1.1', channel: 'preview', target: NSIS });
|
||||
assert.deepEqual(versions(sel), [...order].reverse());
|
||||
for (const bad of ['01.1.1', '0.01.1', '0.1', '0.1.1-', '0.1.1-01', 'v0.1.1', '', '1.2.3.4', ' 0.1.1', '0.1.1+build']) assert.equal(cleanVersion(bad), null, bad);
|
||||
assert.equal(cleanVersion('0.1.2-rc.1'), '0.1.2-rc.1');
|
||||
});
|
||||
|
||||
test('same-core RC → final: the final release is newer than its candidates, never the reverse', () => {
|
||||
const list = [release('v0.1.2-rc.1'), release('v0.1.2-rc.2'), release('v0.1.2', { prerelease: false })];
|
||||
assert.deepEqual(versions(selectReleases(list, { currentVersion: '0.1.2-rc.2', channel: 'preview', target: APPIMAGE_X64 })), ['0.1.2']);
|
||||
assert.deepEqual(versions(selectReleases(list, { currentVersion: '0.1.2-rc.1', channel: 'preview', target: APPIMAGE_X64 })), ['0.1.2', '0.1.2-rc.2']);
|
||||
// A stable install never moves back to a release candidate of the same version.
|
||||
assert.deepEqual(versions(selectReleases(list, { currentVersion: '0.1.2', channel: 'preview', target: APPIMAGE_X64 })), []);
|
||||
assert.deepEqual(versions(selectReleases(list, { currentVersion: '0.1.2-rc.2', channel: 'stable', target: APPIMAGE_X64 })), ['0.1.2']);
|
||||
});
|
||||
|
||||
test('only published releases newer than the running version are offered, newest first', () => {
|
||||
const list = [release('v0.1.0'), release('v0.1.2-rc.1'), release('v0.1.1'), release('v0.1.2-rc.2'), release('v0.1.3', { draft: true })];
|
||||
const sel = selectReleases(list, { currentVersion: '0.1.1', channel: 'preview', target: APPIMAGE_X64 });
|
||||
assert.deepEqual(versions(sel), ['0.1.2-rc.2', '0.1.2-rc.1']);
|
||||
assert.equal(sel.candidates[0].feedFile, 'rc-linux.yml');
|
||||
assert.equal(sel.candidates[0].downloadBase, 'https://git.eeee.moe/TeamsPeach/client/releases/download/v0.1.2-rc.2/');
|
||||
});
|
||||
|
||||
test('drafts are never offered, even when they are the newest', () => {
|
||||
const sel = selectReleases([release('v0.9.0', { draft: true }), { ...release('v0.8.0'), draft: undefined }], { currentVersion: '0.1.1', channel: 'preview', target: APPIMAGE_X64 });
|
||||
assert.deepEqual(versions(sel), []);
|
||||
});
|
||||
|
||||
test('same version and downgrades are refused', () => {
|
||||
const list = [release('v0.1.2'), release('v0.1.1'), release('v0.1.2-rc.9')];
|
||||
assert.deepEqual(versions(selectReleases(list, { currentVersion: '0.1.2', channel: 'preview', target: NSIS })), []);
|
||||
// A final release is newer than its own release candidates.
|
||||
assert.deepEqual(versions(selectReleases(list, { currentVersion: '0.1.2-rc.2', channel: 'preview', target: NSIS })), ['0.1.2', '0.1.2-rc.9']);
|
||||
});
|
||||
|
||||
test('stable channel never treats a preview as stable (Gitea flag or semver prerelease)', () => {
|
||||
const list = [release('v0.3.0', { prerelease: true }), release('v0.2.1-rc.1', { prerelease: false }), release('v0.2.0', { prerelease: false })];
|
||||
const stable = selectReleases(list, { currentVersion: '0.1.1', channel: 'stable', target: APPIMAGE_X64 });
|
||||
assert.deepEqual(versions(stable), ['0.2.0']);
|
||||
assert.equal(stable.newestPreview, '0.3.0');
|
||||
assert.equal(stable.candidates[0].preview, false);
|
||||
const preview = selectReleases(list, { currentVersion: '0.1.1', channel: 'preview', target: APPIMAGE_X64 });
|
||||
assert.deepEqual(versions(preview), ['0.3.0', '0.2.1-rc.1', '0.2.0']);
|
||||
assert.equal(preview.candidates[1].preview, true);
|
||||
// Today every published release is a preview: the stable channel has nothing, and says what it hides.
|
||||
const today = selectReleases([release('v0.1.2-rc.1')], { currentVersion: '0.1.1', channel: 'stable', target: NSIS });
|
||||
assert.deepEqual(versions(today), []);
|
||||
assert.equal(today.newestPreview, '0.1.2-rc.1');
|
||||
});
|
||||
|
||||
test('wrong architecture or a missing platform build is not offered and is reported', () => {
|
||||
const list = [release('v0.1.3', { platforms: ['linux-x64'] }), release('v0.1.2', { platforms: ['linux-x64', 'linux-arm64', 'win-x64'] })];
|
||||
const arm = selectReleases(list, { currentVersion: '0.1.1', channel: 'preview', target: APPIMAGE_ARM });
|
||||
assert.deepEqual(versions(arm), ['0.1.2']);
|
||||
assert.equal(arm.candidates[0].feedFile, 'latest-linux-arm64.yml');
|
||||
assert.deepEqual(arm.withoutBuild.map((x) => [x.version, x.code, x.params.file]), [['0.1.3', 'no-feed', 'latest-linux-arm64.yml']]);
|
||||
const win = selectReleases(list, { currentVersion: '0.1.1', channel: 'preview', target: NSIS });
|
||||
assert.deepEqual(versions(win), ['0.1.2']);
|
||||
assert.equal(win.candidates[0].feedFile, 'latest.yml');
|
||||
// Linux-only release published before the Windows assets are appended: Windows sees nothing new.
|
||||
assert.deepEqual(versions(selectReleases([release('v0.1.2', { platforms: ['linux-x64', 'linux-arm64'] })], { currentVersion: '0.1.1', channel: 'preview', target: NSIS })), []);
|
||||
});
|
||||
|
||||
test('manual targets need their own package; the historical 0.1.1 release has no feeds at all', () => {
|
||||
const v011 = { ...release('v0.1.1'), assets: release('v0.1.1').assets.filter((a) => !a.name.endsWith('.yml')) };
|
||||
assert.deepEqual(versions(selectReleases([v011], { currentVersion: '0.1.0', channel: 'preview', target: APPIMAGE_X64 })), []);
|
||||
const tar = selectReleases([v011], { currentVersion: '0.1.0', channel: 'preview', target: TARGZ_ARM });
|
||||
assert.equal(tar.candidates[0].manualAsset, 'teamspeach-0.1.1-arm64.tar.gz');
|
||||
assert.equal(selectReleases([v011], { currentVersion: '0.1.0', channel: 'preview', target: ZIP }).candidates[0].manualAsset, 'TeamsPeach-0.1.1-win-x64-local.zip');
|
||||
});
|
||||
|
||||
test('malformed tags, assets and inputs are ignored or rejected', () => {
|
||||
const evil = release('v0.2.0', { platforms: [] });
|
||||
evil.assets.push({ name: '../latest-linux.yml', size: 5 }, { name: 'latest-linux.yml', size: 0 });
|
||||
const list = [{ ...release('v9.9.9'), tag_name: 'nightly' }, { ...release('v9.9.8'), tag_name: 'v9.9.8+build' }, evil, null, 'x'];
|
||||
assert.deepEqual(versions(selectReleases(list, { currentVersion: '0.1.1', channel: 'preview', target: APPIMAGE_X64 })), []);
|
||||
assert.throws(() => selectReleases([], { currentVersion: 'dev', channel: 'preview', target: NSIS }), (e) => e.code === 'bad-version');
|
||||
assert.throws(() => selectReleases([], { currentVersion: '0.1.1', channel: 'beta', target: NSIS }), (e) => e.code === 'bad-channel');
|
||||
assert.throws(() => selectReleases({}, { currentVersion: '0.1.1', channel: 'preview', target: NSIS }), (e) => e.code === 'bad-response');
|
||||
});
|
||||
|
||||
test('detectTarget: auto only for NSIS installs and AppImages; no promises for unbuilt platforms', () => {
|
||||
const base = { packaged: true, env: {}, execPath: 'C:\\Apps\\TeamsPeach\\TeamsPeach.exe', exists: () => false };
|
||||
assert.equal(detectTarget({ ...base, platform: 'win32', arch: 'x64', exists: (p) => p.endsWith('Uninstall TeamsPeach.exe') }).id, 'win-x64-nsis');
|
||||
assert.equal(detectTarget({ ...base, platform: 'win32', arch: 'x64' }).mode, 'manual');
|
||||
assert.equal(detectTarget({ ...base, platform: 'win32', arch: 'arm64' }).mode, 'none');
|
||||
assert.equal(detectTarget({ ...base, platform: 'linux', arch: 'arm64', env: { APPIMAGE: '/home/u/TeamsPeach.AppImage' } }).id, 'linux-arm64-appimage');
|
||||
assert.equal(detectTarget({ ...base, platform: 'linux', arch: 'x64' }).id, 'linux-x64-tar.gz');
|
||||
assert.equal(detectTarget({ ...base, platform: 'darwin', arch: 'arm64' }).mode, 'none');
|
||||
assert.equal(detectTarget({ ...base, packaged: false, platform: 'linux', arch: 'x64' }).mode, 'none');
|
||||
});
|
||||
|
||||
test('verifyFeed: feed must match the release version and its assets exactly', () => {
|
||||
const [cand] = selectReleases([release('v0.1.2-rc.2')], { currentVersion: '0.1.1', channel: 'preview', target: NSIS }).candidates;
|
||||
const good = { version: '0.1.2-rc.2', files: [{ url: 'TeamsPeach-0.1.2-rc.2-win-x64-setup.exe', sha512: SHA, size: 2000 }] };
|
||||
verifyFeed(cand, NSIS, good);
|
||||
const code = (info) => {
|
||||
try {
|
||||
verifyFeed(cand, NSIS, info);
|
||||
return 'ok';
|
||||
} catch (e) {
|
||||
assert.ok(e instanceof UpdateError);
|
||||
return e.code;
|
||||
}
|
||||
};
|
||||
assert.equal(code({ ...good, version: '0.1.2-rc.1' }), 'feed-mismatch');
|
||||
// Installer renamed after building (spaces, or the builder default name): not the exact expected name.
|
||||
assert.equal(code({ ...good, files: [{ ...good.files[0], url: 'TeamsPeach Setup 0.1.2-rc.2.exe' }] }), 'feed-mismatch');
|
||||
assert.equal(code({ ...good, files: [{ ...good.files[0], url: 'TeamsPeach-Setup-0.1.2-rc.2.exe' }] }), 'feed-mismatch');
|
||||
assert.equal(code({ ...good, files: [{ ...good.files[0], size: 1999 }] }), 'incomplete-release');
|
||||
assert.equal(code({ ...good, files: [{ ...good.files[0], sha512: undefined }] }), 'feed-mismatch');
|
||||
assert.equal(code({ ...good, files: [{ ...good.files[0], url: 'https://evil.example/x.exe' }] }), 'feed-mismatch');
|
||||
assert.equal(code({ ...good, files: [] }), 'feed-mismatch');
|
||||
assert.equal(code({ ...good, files: [good.files[0], { url: 'TeamsPeach-0.1.2-rc.2-win-arm64-setup.exe', sha512: SHA, size: 2000 }] }), 'feed-mismatch');
|
||||
assert.equal(code({ ...good, path: 'other.exe' }), 'feed-mismatch');
|
||||
// A Windows feed that only lists the zip cannot be installed by NSIS.
|
||||
assert.equal(code({ ...good, files: [{ url: 'TeamsPeach-0.1.2-rc.2-win-x64-local.zip', sha512: SHA, size: 3000 }] }), 'feed-mismatch');
|
||||
// Feed is right but the package vanished from the release after selection.
|
||||
const gone = { ...cand, assets: new Map([...cand.assets].filter(([n]) => !n.endsWith('.exe'))) };
|
||||
assert.throws(() => verifyFeed(gone, NSIS, good), (e) => e.code === 'incomplete-release' && e.params.file === 'TeamsPeach-0.1.2-rc.2-win-x64-setup.exe');
|
||||
});
|
||||
|
||||
test('verifyFeed: an arm64 feed pointing at the x64 AppImage is refused although both assets exist', () => {
|
||||
const [arm] = selectReleases([release('v0.1.2')], { currentVersion: '0.1.1', channel: 'preview', target: APPIMAGE_ARM }).candidates;
|
||||
assert.equal(packageFileName(APPIMAGE_ARM, '0.1.2'), 'TeamsPeach-0.1.2-arm64.AppImage');
|
||||
verifyFeed(arm, APPIMAGE_ARM, { version: '0.1.2', files: [{ url: 'TeamsPeach-0.1.2-arm64.AppImage', sha512: SHA, size: 1001 }] });
|
||||
assert.throws(
|
||||
() => verifyFeed(arm, APPIMAGE_ARM, { version: '0.1.2', files: [{ url: 'TeamsPeach-0.1.2.AppImage', sha512: SHA, size: 1000 }] }),
|
||||
(e) => e.code === 'feed-mismatch',
|
||||
);
|
||||
const [x64] = selectReleases([release('v0.1.2')], { currentVersion: '0.1.1', channel: 'preview', target: APPIMAGE_X64 }).candidates;
|
||||
assert.throws(
|
||||
() => verifyFeed(x64, APPIMAGE_X64, { version: '0.1.2', files: [{ url: 'TeamsPeach-0.1.2-arm64.AppImage', sha512: SHA, size: 1001 }] }),
|
||||
(e) => e.code === 'feed-mismatch',
|
||||
);
|
||||
});
|
||||
|
||||
/** Real HTTP server; only the fixed HTTPS origin is swapped for it, everything else is the production fetch path. */
|
||||
async function withServer(handler, fn) {
|
||||
const server = http.createServer(handler);
|
||||
await new Promise((r) => server.listen(0, '127.0.0.1', r));
|
||||
const base = `http://127.0.0.1:${server.address().port}`;
|
||||
let seenUrl = null;
|
||||
const fetchImpl = (url, init) => {
|
||||
seenUrl = url;
|
||||
return fetch(url.replace('https://git.eeee.moe', base), init);
|
||||
};
|
||||
try {
|
||||
return await fn(fetchImpl, () => seenUrl);
|
||||
} finally {
|
||||
server.closeAllConnections();
|
||||
await new Promise((r) => server.close(r));
|
||||
}
|
||||
}
|
||||
|
||||
/** Gitea-like paging: newest-created first, `limit` capped by the server, X-Total-Count header. */
|
||||
function giteaPages(all, { cap = 50, sendTotal = true, lieTotal = null } = {}) {
|
||||
return (req, res) => {
|
||||
assert.equal(req.headers.authorization, undefined);
|
||||
const u = new URL(req.url, 'http://x');
|
||||
assert.equal(u.pathname, '/api/v1/repos/TeamsPeach/client/releases');
|
||||
assert.equal(u.searchParams.get('draft'), 'false');
|
||||
const limit = Math.min(Number(u.searchParams.get('limit')), cap);
|
||||
const page = Number(u.searchParams.get('page'));
|
||||
const headers = { 'Content-Type': 'application/json' };
|
||||
if (sendTotal) headers['X-Total-Count'] = String(lieTotal ?? all.length);
|
||||
res.writeHead(200, headers);
|
||||
res.end(JSON.stringify(all.slice((page - 1) * limit, page * limit)));
|
||||
};
|
||||
}
|
||||
|
||||
test('fetchReleases reads every page of the fixed public API without credentials', async () => {
|
||||
// 120 releases; the newest version was created early, so it sits on the last page.
|
||||
const all = [];
|
||||
for (let i = 0; i < 119; i += 1) all.push(release(`v0.0.${i}`));
|
||||
all.push(release('v0.5.0'));
|
||||
for (const opts of [{}, { cap: 30 }, { sendTotal: false }]) {
|
||||
await withServer(giteaPages(all, opts), async (fetchImpl, seen) => {
|
||||
const list = await fetchReleases({ fetchImpl });
|
||||
assert.equal(list.length, 120, JSON.stringify(opts));
|
||||
assert.ok(seen().startsWith(`${RELEASES_API}?draft=false&limit=50&page=`));
|
||||
assert.deepEqual(versions(selectReleases(list, { currentVersion: '0.1.1', channel: 'preview', target: APPIMAGE_X64 })), ['0.5.0']);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('fetchReleases: an incomplete or endless listing is an error, not "up to date"', async () => {
|
||||
const all = Array.from({ length: 50 }, (_, i) => release(`v0.0.${i}`));
|
||||
await withServer(giteaPages(all, { lieTotal: 60 }), async (fetchImpl) => {
|
||||
await assert.rejects(fetchReleases({ fetchImpl }), (e) => e.code === 'incomplete-list' && e.params.fetched === 50 && e.params.total === 60);
|
||||
});
|
||||
await withServer((req, res) => res.end(JSON.stringify(all)), async (fetchImpl) => {
|
||||
await assert.rejects(fetchReleases({ fetchImpl }), (e) => e.code === 'incomplete-list');
|
||||
});
|
||||
});
|
||||
|
||||
test('fetchReleases: timeout, HTTP error and garbage are errors, never an empty list', async () => {
|
||||
await withServer(() => {}, async (fetchImpl) => {
|
||||
await assert.rejects(fetchReleases({ fetchImpl, timeoutMs: 300 }), (e) => e.code === 'timeout');
|
||||
});
|
||||
await withServer((req, res) => {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.write('[');
|
||||
// headers sent, body stalls
|
||||
}, async (fetchImpl) => {
|
||||
await assert.rejects(fetchReleases({ fetchImpl, timeoutMs: 300 }), (e) => e.code === 'timeout');
|
||||
});
|
||||
await withServer((req, res) => {
|
||||
res.writeHead(502);
|
||||
res.end('bad gateway');
|
||||
}, async (fetchImpl) => {
|
||||
await assert.rejects(fetchReleases({ fetchImpl }), (e) => e.code === 'http' && /502/.test(e.message));
|
||||
});
|
||||
await withServer((req, res) => res.end('<html>login</html>'), async (fetchImpl) => {
|
||||
await assert.rejects(fetchReleases({ fetchImpl }), (e) => e.code === 'bad-response');
|
||||
});
|
||||
await withServer((req, res) => res.end('{"message":"x"}'), async (fetchImpl) => {
|
||||
await assert.rejects(fetchReleases({ fetchImpl }), (e) => e.code === 'bad-response');
|
||||
});
|
||||
await withServer((req, res) => {
|
||||
res.writeHead(302, { Location: 'https://evil.example/' });
|
||||
res.end();
|
||||
}, async (fetchImpl) => {
|
||||
await assert.rejects(fetchReleases({ fetchImpl }), (e) => e.code === 'network');
|
||||
});
|
||||
const refused = (url, init) => fetch(url.replace('https://git.eeee.moe', 'http://127.0.0.1:9'), init);
|
||||
await assert.rejects(fetchReleases({ fetchImpl: refused }), (e) => e.code === 'network');
|
||||
});
|
||||
|
||||
test('the live public release list parses and selects without credentials', { skip: process.env.TEAMSPEACH_LIVE_UPDATE_TEST !== '1' && 'set TEAMSPEACH_LIVE_UPDATE_TEST=1' }, async () => {
|
||||
const list = await fetchReleases({ fetchImpl: fetch });
|
||||
assert.ok(list.some((r) => r.tag_name === 'v0.1.1' && r.draft === false));
|
||||
// 0.1.1 shipped no feeds: nothing installs automatically from it, but tar.gz users are told.
|
||||
const auto = selectReleases(list, { currentVersion: '0.1.0', channel: 'preview', target: APPIMAGE_X64 });
|
||||
assert.ok(!auto.candidates.some((c) => c.version === '0.1.1'));
|
||||
const manual = selectReleases(list, { currentVersion: '0.1.0', channel: 'preview', target: TARGZ_ARM });
|
||||
assert.ok(manual.candidates.some((c) => c.version === '0.1.1'));
|
||||
assert.deepEqual(versions(selectReleases(list, { currentVersion: '0.1.1', channel: 'stable', target: NSIS })), []);
|
||||
});
|
||||
Reference in new issue
Block a user