21 Commits
Author SHA1 Message Date
omar a924d792b4 VAD docs: startup buffer latency stated precisely; smoke-voice-vad --exe
ci / linux-arm64-cross (push) Successful in 2m48s
ci / linux-x64 (push) Successful in 2m53s
release / linux-arm64 (push) Successful in 4m15s
release / linux-x64 (push) Successful in 4m38s
release / appimage-startup (push) Successful in 15s
release / publish (push) Failing after 9s
2026-10-24 09:31:27 +03:00
omar b7951e0693 Voice activation (core voice detector, set_transmit handshake), transmission mode in Settings → Audio, atomic prefs commit, ARM64 unit tests under qemu; version 0.1.3
ci / linux-x64 (push) Successful in 2m50s
ci / linux-arm64-cross (push) Successful in 2m50s
2026-10-24 09:29:46 +03:00
omar 8439fe062e Evidence: v0.1.2 release, packaged 0.1.2 smokes, updater E2E logs (rc.1→rc.2, rc.2→0.1.2)
ci / linux-arm64-cross (push) Successful in 2m19s
ci / linux-x64 (push) Successful in 2m41s
2026-10-24 07:41:41 +03:00
omar 9e7483601b Updater harness: hash the pending update file; updater RC proof notes
ci / linux-arm64-cross (push) Successful in 2m18s
ci / linux-x64 (push) Successful in 3m20s
release / linux-arm64 (push) Successful in 4m12s
release / linux-x64 (push) Successful in 4m30s
release / appimage-startup (push) Successful in 14s
release / publish (push) Successful in 19s
2026-10-24 07:30:23 +03:00
omar f97a651c87 TeamsPeach 0.1.2
ci / linux-arm64-cross (push) Successful in 2m51s
ci / linux-x64 (push) Successful in 3m9s
2026-10-24 07:28:47 +03:00
omar 2cf63f5d88 Evidence: packaged 0.1.2-rc.2 (ed2e123) smokes
ci / linux-x64 (push) Successful in 3m3s
ci / linux-arm64-cross (push) Successful in 2m34s
2026-10-24 07:15:35 +03:00
omar ed2e123404 Release candidate 0.1.2-rc.2
ci / linux-x64 (push) Successful in 3m45s
ci / linux-arm64-cross (push) Successful in 2m50s
release / linux-arm64 (push) Successful in 4m8s
release / linux-x64 (push) Successful in 4m36s
release / appimage-startup (push) Successful in 13s
release / publish (push) Successful in 19s
2026-10-24 07:13:20 +03:00
omar 6b8994f1cb Use the application icon asset as the in-app brand mark; drop the old inline peach; smoke checks the decoded image
ci / linux-arm64-cross (push) Successful in 2m53s
ci / linux-x64 (push) Successful in 4m54s
2026-10-24 07:12:44 +03:00
omar d505890c74 Evidence: packaged 0.1.2-rc.1 (2a71d63) real-device, menu, theme and UI smokes
ci / linux-arm64-cross (push) Successful in 2m25s
ci / linux-x64 (push) Successful in 2m40s
release / linux-arm64 (push) Successful in 5m47s
release / linux-x64 (push) Successful in 6m57s
release / appimage-startup (push) Successful in 17s
release / publish (push) Successful in 20s
2026-10-24 07:09:08 +03:00
omar 2a71d63b7b Fail closed on a missing microphone, release partial capture setup, menus show enumeration failures; deterministic packaged smoke launch; NSIS custom-profile update guard 2026-10-24 07:07:05 +03:00
omar 7afce5ab20 Release candidate 0.1.2-rc.1
ci / linux-arm64-cross (push) Successful in 3m13s
ci / linux-x64 (push) Successful in 4m14s
2026-10-24 06:40:25 +03:00
omar 5f5d30d3ed i18n: final sweep, i18n smoke and evidence, docs/i18n.md
ci / linux-arm64-cross (push) Successful in 3m51s
ci / linux-x64 (push) Successful in 4m22s
2026-10-24 06:40:15 +03:00
omar 0fffb27166 Docs: English authored prose; 0.1.2 changelog (devices, menus, theme, language, updater, icon, identity fix)
ci / linux-arm64-cross (push) Successful in 1m52s
ci / linux-x64 (push) Successful in 2m43s
2026-10-24 06:36:56 +03:00
omar 1142c9f60d Updater from public releases, English UI by default with Russian selectable, cancelable capture, English technical messages, language-independent smoke hooks
ci / linux-arm64-cross (push) Successful in 1m54s
ci / linux-x64 (push) Successful in 2m45s
2026-10-24 06:34:33 +03:00
omar ba4c7ec2af core: decode stored keys with upstream's simple_asn1 shape plus scalar left-padding; deterministic and malformed-input tests 2026-10-24 06:18:41 +03:00
omar 456041bfde Dark theme by default (stored choices kept); updateChannel pref; new peach icon (transparent); packaged device evidence
ci / linux-arm64-cross (push) Successful in 2m29s
ci / linux-x64 (push) Successful in 3m11s
2026-10-24 06:13:08 +03:00
omar 41e90fb5e8 Device menus: loading shell, stale enumeration dropped; strict origin parsing; no automatic silence warning; core transmit state at debug
ci / linux-arm64-cross (push) Successful in 1m51s
ci / linux-x64 (push) Failing after 5m39s
2026-10-24 06:09:48 +03:00
omar 401c331aa4 Core 0.1.2 (zero-leading private key load fix); capture state in diagnostics; changelog
ci / linux-arm64-cross (push) Successful in 2m0s
ci / linux-x64 (push) Successful in 2m47s
2026-10-24 06:06:49 +03:00
omar 7ad5ee8572 Voice burst and PTT diagnostics only at TEAMSPEACH_LOG=debug 2026-10-24 06:06:20 +03:00
omar a3185229ee Audio devices: fix permission origin (app://teamspeach/), real device lists, right-click device menus, voice TX diagnostics; version 0.1.2 2026-10-24 06:05:46 +03:00
omar 8153e9b88b Evidence: v0.1.1 release (static AppImage runtime), v0.1.0 marked superseded
ci / linux-arm64-cross (push) Successful in 2m13s
ci / linux-x64 (push) Successful in 2m34s
2026-10-24 05:01:13 +03:00
191 changed files with 10938 additions and 865 deletions

No files matched your search

+11
View File
@@ -62,6 +62,9 @@ jobs:
TEAMSPEACH_SMOKE_EXTRA_ARGS: --no-sandbox TEAMSPEACH_SMOKE_EXTRA_ARGS: --no-sandbox
run: xvfb-run -a node scripts/smoke-ui.mjs --out smoke-out 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 - name: Upload smoke evidence
if: always() if: always()
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@v3
@@ -109,3 +112,11 @@ jobs:
- name: Core identity smoke under qemu-aarch64 (emulated, not native hardware) - name: Core identity smoke under qemu-aarch64 (emulated, not native hardware)
run: node scripts/core-smoke.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --wrapper "qemu-aarch64 -L /usr/aarch64-linux-gnu" run: node scripts/core-smoke.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --wrapper "qemu-aarch64 -L /usr/aarch64-linux-gnu"
# The unit tests (voice detector, resampler, identity keys, codecs, protocol) built for aarch64 and run
# under user-mode qemu. Emulated, not native hardware; the bridge smoke tests spawn the core binary and
# are left to the host build above.
- name: Core unit tests under qemu-aarch64 (emulated, not native hardware)
env:
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_RUNNER: qemu-aarch64 -L /usr/aarch64-linux-gnu
run: cargo test --manifest-path core/Cargo.toml --locked --target aarch64-unknown-linux-gnu --bin teamspeach-core
+19 -7
View File
@@ -63,9 +63,15 @@ jobs:
TEAMSPEACH_SMOKE_EXTRA_ARGS: --no-sandbox TEAMSPEACH_SMOKE_EXTRA_ARGS: --no-sandbox
run: xvfb-run -a node scripts/smoke-ui.mjs --out smoke-out 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 - name: Package
run: node scripts/dist.mjs --os linux --arch x64 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) - name: Package report (ELF layout of every packaged binary incl. the AppImage runtime)
run: | run: |
set -euo pipefail set -euo pipefail
@@ -75,7 +81,7 @@ jobs:
git rev-parse HEAD >> "$report" 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 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" cat elf.txt >> "$report"
sha256sum dist/*.AppImage dist/*.tar.gz >> "$report" sha256sum dist/*.AppImage dist/*.tar.gz dist/*-linux.yml >> "$report"
cat "$report" cat "$report"
- uses: actions/upload-artifact@v3 - uses: actions/upload-artifact@v3
@@ -86,6 +92,7 @@ jobs:
dist/*.tar.gz dist/*.tar.gz
dist/build-info-linux-x64.txt dist/build-info-linux-x64.txt
dist/elf-report-linux-x64.json dist/elf-report-linux-x64.json
dist/*-linux.yml
if-no-files-found: error if-no-files-found: error
linux-arm64: linux-arm64:
@@ -131,6 +138,7 @@ jobs:
set -euo pipefail set -euo pipefail
npm ci npm ci
node scripts/dist.mjs --os linux --arch arm64 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) - name: 16 KiB page check of every packaged ELF incl. the AppImage runtime (Asahi)
run: | run: |
@@ -140,7 +148,7 @@ jobs:
git rev-parse HEAD >> "$report" 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 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" cat elf.txt >> "$report"
sha256sum dist/*.AppImage dist/*.tar.gz >> "$report" sha256sum dist/*.AppImage dist/*.tar.gz dist/*-linux-arm64.yml >> "$report"
cat "$report" cat "$report"
- uses: actions/upload-artifact@v3 - uses: actions/upload-artifact@v3
@@ -151,6 +159,7 @@ jobs:
dist/*.tar.gz dist/*.tar.gz
dist/build-info-linux-arm64.txt dist/build-info-linux-arm64.txt
dist/elf-report-linux-arm64.json dist/elf-report-linux-arm64.json
dist/*-linux-arm64.yml
if-no-files-found: error if-no-files-found: error
# The AppImage runtime must start on a stock system: run it in a slim container without development # 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 set -euo pipefail
node scripts/check-version.mjs node scripts/check-version.mjs
cat > notes.md <<'EOF' cat > notes.md <<'EOF'
Linux x64 и Linux ARM64 (aarch64) собраны в CI: тесты, офлайн-проверка ядра, проверка выравнивания ELF Linux x64 and Linux ARM64 (aarch64) are built in CI: tests, offline core check, ELF alignment check
(для ARM64 — страницы 16 КиБ, включая загрузчик AppImage), см. build-info-*.txt. (16 KiB pages for ARM64, including the AppImage runtime), see build-info-*.txt.
ARM64 проверен статически и под qemu, не на Apple Silicon. Пакеты не подписаны. ARM64 is checked statically and under qemu, not on Apple Silicon. Packages are not signed.
Сборка Windows x64 собирается на машине разработчика из того же коммита и прикладывается отдельно Windows x64 is built on the developer machine from the same commit and attached separately
с пометкой local. (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 EOF
node scripts/publish-release.mjs artifacts notes.md node scripts/publish-release.mjs artifacts notes.md
+78
View File
@@ -0,0 +1,78 @@
# 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
new_prefs:
description: Optional JSON of settings that exist only in the new version, applied after the update and checked after a restart
required: false
default: ''
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 }}
NEW_PREFS: ${{ inputs.new_prefs }}
run: |
set -euo pipefail
[[ "$TO_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || { echo "bad tag $TO_TAG"; exit 2; }
if [ -n "$NEW_PREFS" ]; then
node -e 'const p = JSON.parse(process.argv[1]); if (!p || typeof p !== "object" || Array.isArray(p)) process.exit(2)' "$NEW_PREFS"
xvfb-run -a node scripts/update-e2e.mjs --from "old/TeamsPeach-${FROM_TAG#v}.AppImage" --to-tag "$TO_TAG" --out update-e2e-out --new-prefs "$NEW_PREFS"
else
xvfb-run -a node scripts/update-e2e.mjs --from "old/TeamsPeach-${FROM_TAG#v}.AppImage" --to-tag "$TO_TAG" --out update-e2e-out
fi
cat update-e2e-out/result.json
- uses: actions/upload-artifact@v3
if: always()
with:
name: update-e2e
path: update-e2e-out/
+58
View File
@@ -1,5 +1,63 @@
# Changelog # Changelog
## 0.1.3 — unreleased
- Added voice activation as a third transmission mode next to push to talk and the open microphone
(Settings → Audio → Voice transmission, sensitivity High / Normal / Low). The core decides locally with
the earshot voice detector (a small embedded neural network, no cloud service, no speech recognition) on
audio that has already passed the microphone processing (noise suppression, echo cancellation, gain
control). It sends from about 100 ms before a detected onset until about 400 ms after the last detected
speech. After connecting, unmuting or changing the mode the gate cannot open for 200 ms, but every frame
since then is kept (up to 300 ms) and sent with the first spurt, so the first word is complete; that first
spurt therefore starts up to 300 ms late (later spurts carry the normal 100 ms). Muting, deafening, disconnecting, a channel or codec change and
a server talk denial discard what the detector heard. Push to talk and the open microphone are unchanged;
stored settings keep their mode, and new profiles still start with push to talk.
- The transmission mode moved from Settings → Keyboard to Settings → Audio; the push-to-talk key stays in
Keyboard. The microphone test explains that it only shows the input level and never transmits.
- The renderer forwards microphone audio only after the core has confirmed the selected mode; a failed
mode change is shown and nothing is sent until it is applied.
- Fixed: a preference write failure no longer changes the in-memory value the app keeps using.
- ARM64 CI runs the core unit tests (voice detector, resampler, identity, codecs) under qemu-aarch64
(emulated, not native hardware).
## 0.1.2 — 2026-10-24
- Fixed: Settings → Audio listed only the system default device. Electron reports the app origin as
`app://teamspeach/` and the permission check compared it with `app://teamspeach`, so Chromium withheld
device ids and names. The audio-only permission policy now normalises origins (camera stays denied);
real inputs and outputs are listed without starting the microphone, and the default entry names the
device it points to.
- The default theme is now dark, independent of the OS; Light or System can be chosen in
Settings → Appearance and persists. A theme already saved by an earlier version is kept as is.
- Right-click (or Shift+F10 / Menu key) on the microphone and headphones buttons opens an input / output
device menu sharing the Settings selection; left click still mutes/deafens.
- Voice diagnostics: the local log records the capture device and track state; with
`TEAMSPEACH_LOG=debug` it also records push-to-talk presses with window focus and each transmission burst
(frames, peak level).
- The push-to-talk hint says when the window is not focused (the key is read only there).
- Fixed: ~1/256 newly created or imported identities could not be loaded again (private key with a leading
zero byte). Storage format unchanged.
- Replaced the application icon assets with an original peach silhouette on a transparent background,
including PNG assets and a seven-size Windows ICO. The reproducible Electron export now renders the
SVG directly to an alpha-enabled canvas instead of capturing a window, avoiding captured scrollbars.
The start, error and onboarding screens show the same icon asset instead of a separate inline drawing.
- Added an English-default interface with selectable Russian, backed by shared catalogs for the renderer
and native identity dialogs. Repository-authored documentation and technical diagnostics are English;
historical captures and server-provided content remain unchanged.
- Added update checks against published public Gitea releases, Preview and Stable channels, verified
downloads for Windows x64 NSIS and Linux x64/ARM64 AppImage installations, and manual-update guidance
for zip/tar.gz distributions. Installation requires confirmation; active sessions defer background
downloads. Version 0.1.1 and older require a first manual installation of an updater-capable version.
- Fixed capture cancellation during pending microphone acquisition and prevented device changes from
being applied when saving the selected device fails.
- A saved microphone that is no longer available is reported as unavailable; TeamsPeach no longer opens
a different microphone in its place. Choosing an available device restores capture while connected or
during the microphone test, and opens nothing otherwise. A failure while building the capture chain
releases the microphone.
- The microphone and headphones menus show a failed device enumeration instead of an earlier list.
- Windows installations started with a custom profile (`TEAMSPEACH_PROFILE_DIR`) only offer manual
updates, because the installer would restart TeamsPeach on the default profile.
## 0.1.1 — 2026-10-24 ## 0.1.1 — 2026-10-24
- Linux AppImages use the static AppImage runtime (electron-builder toolset `appimage` 1.0.3, - Linux AppImages use the static AppImage runtime (electron-builder toolset `appimage` 1.0.3,
+14 -7
View File
@@ -12,13 +12,13 @@ owner-pinned visual reference is the TeamSpeak 6 settings screenshot that the se
- Tree rows: channels with `#`/lock glyph, server channel icon at the right, server banner as a row - Tree rows: channels with `#`/lock glyph, server channel icon at the right, server banner as a row
background fading from the sidebar colour; members indented under channels with avatar/status dot, background fading from the sidebar colour; members indented under channels with avatar/status dot,
nickname (never truncated before group labels), server-configured group labels, mute/away/recording nickname (never truncated before group labels), server-configured group labels, mute/away/recording
flags, group icons and country code, and a pill "Смотреть" button for streamers. flags, group icons and country code, and a pill-shaped Watch button for streamers.
- Settings follow the owner's pinned reference: the sidebar's room area is replaced by category navigation - Settings follow the owner's pinned reference: the sidebar's room area is replaced by category navigation
(Назад к серверу, groups Пользователь / Приложение / Информация, active item with an accent bar and tint), (Back to server, User / Application / Information groups, active item with an accent bar and tint),
the workspace shows the selected category as titled cards (`.card`, 12 px radius) with an expandable the workspace shows the selected category as titled cards (`.card`, 12 px radius) with an expandable
"Подробности" area for advanced video information. The connection, voice footer and any stream keep running. Details area for advanced video information. The connection, voice footer and any stream keep running.
- Saved servers sit above the tree as a compact list (name, address, action: Подключиться / Переключиться / - Saved servers sit above the tree as a compact list (name, address, action: Connect / Switch /
Подключено); a bookmark button in the server header shows or hides it. Connected); a bookmark button in the server header shows or hides it.
- Stream viewer: black stage with the video contained, dark control bar (title, codec · resolution · fps, - Stream viewer: black stage with the video contained, dark control bar (title, codec · resolution · fps,
mute, volume 0–100 %, fullscreen, stop). Overlay text explains every non-live state. mute, volume 0–100 %, fullscreen, stop). Overlay text explains every non-live state.
@@ -39,8 +39,9 @@ Restrained strategy: warm neutrals plus one accent; state colours only where the
| `--talk` | `#1f8a5a` | `#4fcf8e` | talking indicator, PTT held | | `--talk` | `#1f8a5a` | `#4fcf8e` | talking indicator, PTT held |
| `--danger` | `#b3261e` | `#f08b82` | mute/deafen active, errors | | `--danger` | `#b3261e` | `#f08b82` | mute/deafen active, errors |
Theme follows the choice in Settings → Внешний вид (system by default, implemented through Electron Theme follows the choice in Settings → Appearance (dark by default for new profiles, independent of the OS;
`nativeTheme.themeSource`, so `prefers-color-scheme` stays the single switch). The dark palette uses the Light and System are selectable; implemented through Electron
`nativeTheme.themeSource`, applied before the window is created, so `prefers-color-scheme` stays the single switch). The dark palette uses the
blue-gray surfaces of the owner's reference (`--bg #1b2029`, `--surface #242b37`, `--sidebar #1e242e`). blue-gray surfaces of the owner's reference (`--bg #1b2029`, `--surface #242b37`, `--sidebar #1e242e`).
Selection, caret, scrollbars and focus rings use the palette. Selection, caret, scrollbars and focus rings use the palette.
@@ -56,6 +57,12 @@ Buttons (primary, default, ghost), 34 px icon buttons with `aria-pressed` states
radio/checkbox choices with accent colour, range sliders, chat tabs with unread counters, toasts in a polite radio/checkbox choices with accent colour, range sliders, chat tabs with unread counters, toasts in a polite
live region (errors 10 s, others 5 s). Icons are an inline SVG sprite drawn in one 1.8 stroke style. live region (errors 10 s, others 5 s). Icons are an inline SVG sprite drawn in one 1.8 stroke style.
The application icon is an original peach silhouette with a small stem and leaf on a transparent
background, without a plate, font or emoji dependency. `build/icon.svg` is the source for the 512 px
build PNG, 256 px runtime PNG and Windows ICO sizes 16, 24, 32, 48, 64, 128 and 256 px. Raster export uses
an alpha-enabled canvas in Electron, not a window screenshot. Asset-level alpha and small-size visual
checks do not establish that a particular packaged release contains or displays these assets.
## Motion ## Motion
Only colour transitions (120 ms) and the toast entrance (180 ms, exponential ease-out); everything is Only colour transitions (120 ms) and the toast entrance (180 ms, exponential ease-out); everything is
+8 -7
View File
@@ -9,21 +9,22 @@ UI, evidence path given; **implemented** = code + unit/loopback tests, no live p
| First-run nickname, P-256 identity, public UID, restart persistence, rename keeps UID | proven | `docs/evidence/runtime/2026-10-24-identity/` | | First-run nickname, P-256 identity, public UID, restart persistence, rename keeps UID | proven | `docs/evidence/runtime/2026-10-24-identity/` |
| Connect / disconnect by address | proven | identity run `04-connected.png` | | Connect / disconnect by address | proven | identity run `04-connected.png` |
| Saved servers (name + address, no passwords): save, edit, delete, restart persistence, one-click connect, clean switch | proven | `docs/evidence/runtime/2026-10-24-servers-settings/` (connect with same UID, mic muted) + `test/prefs.test.js` | | Saved servers (name + address, no passwords): save, edit, delete, restart persistence, one-click connect, clean switch | proven | `docs/evidence/runtime/2026-10-24-servers-settings/` (connect with same UID, mic muted) + `test/prefs.test.js` |
| Sectioned settings (Идентичность, Серверы, Внешний вид, Звук, Видео, Клавиши, Информация) without dropping the connection | proven | servers-settings run: all 7 panels visited while connected, keyboard Home/arrows, Escape returns | | Sectioned settings (Identity, Servers, Appearance, Audio, Video, Keys, Information) without dropping the connection | proven | servers-settings run: all 7 panels visited while connected, keyboard Home/arrows, Escape returns |
| Theme: system / dark / light | implemented | dark captured in servers-settings screenshots | | Theme: system / dark / light | implemented | dark captured in servers-settings screenshots |
| Server password on connect | implemented, not exercised | the test server has no password | | Server password on connect | implemented, not exercised | the test server has no password |
| Channel tree, join channel, password channels (inline prompt) | proven (join), implemented (password) | probe joined `cs`; no password test performed | | Channel tree, join channel, password channels (inline prompt) | proven (join), implemented (password) | probe joined `cs`; no password test performed |
| Voice TX/RX (Opus via core), talking indicators, mute, deafen RX+TX block/restore, PTT, open mic | proven | `docs/evidence/runtime/2026-10-24-voice-chat/` (synthetic capture device, real path after it) | | Voice TX/RX (Opus via core), talking indicators, mute, deafen RX+TX block/restore, PTT, open mic | proven between two TeamsPeach clients with synthetic capture | `docs/evidence/runtime/2026-10-24-voice-chat/`; the path after capture is real. Live microphone voice with the official TS6 client and Asahi hardware operation are not proven |
| Voice activation (local voice detector in the core, sensitivity High/Normal/Low, 100 ms preroll, 400 ms hangover) | proven between two TeamsPeach clients with a real speech recording as file-fed capture; detector unit tests on real speech and synthetic noise | `docs/evidence/runtime/2026-10-24-vad-dev/`, `docs/evidence/vad-0.1.3.md`: speech opens and silence closes the gate, mute/deafen/push-to-talk-not-held/disconnected send nothing, setting persists. A live microphone, an official TS6 receiver and native ARM64 hardware are not proven (ARM64 unit tests run under qemu) |
| Private chat | proven | voice-chat run `15/16-*.png` | | Private chat | proven | voice-chat run `15/16-*.png` |
| Channel chat | proven error path | server denies guests: TS 2568, permission 224, shown in UI | | Channel chat | proven error path | server denies guests: TS 2568, permission 224, shown in UI |
| Server chat | implemented | not exercised live | | Server chat | implemented | not exercised live |
| Mic/output device selection | implemented; output routing proven in loopback | `2026-10-24-loopback-browser-pipeline/` | | Mic/output device selection (Settings and right-click menus on the footer buttons) | proven on real hardware (Windows) | `2026-10-24-audio-devices/`: 6 inputs + 6 outputs listed without capture (matches the OS endpoint inventory), choice persists across restart, menus do not toggle mute/deafen; output routing also proven in loopback |
| TS6 screenshare viewing (P2P): discovery, join, answer, ICE buffering, stop | proven | `2026-10-24-ts6-stream-view/`: AV1 2560×1440 ~59 fps, 2298 frames, D3D11 decoder | | TS6 screenshare viewing (P2P): discovery, join, answer, ICE buffering, stop | proven | `2026-10-24-ts6-stream-view/`: AV1 2560×1440 ~59 fps, 2298 frames, D3D11 decoder |
| Realign / reconnect offer renegotiation | implemented | unit tests + loopback (2 offers/2 answers); no realign seen live | | Realign / reconnect offer renegotiation | implemented | unit tests + loopback (2 offers/2 answers); no realign seen live |
| Stream audio | implemented | live stream advertised `audio=0`; loopback 139 inbound audio packets | | Stream audio | implemented | live stream advertised `audio=0`; loopback 139 inbound audio packets |
| SFU streams | blocked | P2P only; `notifysfuaccessinfo` → "не поддерживается" | | SFU streams | blocked | P2P only; `notifysfuaccessinfo` is reported as unsupported |
| Sending own screenshare | blocked | not implemented | | Sending own screenshare | blocked | not implemented |
| Server/channel group labels (`name_mode`), custom group icons, country | proven | `2026-10-24-tree-metadata/`: labels «куколд», «бля ща», 6 custom icons, RU | | Server/channel group labels (`name_mode`), custom group icons, country | proven | `2026-10-24-tree-metadata/`: two server-supplied group labels retained verbatim in the raw capture, 6 custom icons, RU country code |
| Built-in group icons (ids 100, 200, 300, 500, 600) | partial | server has no file (core: `not_found`, `builtin:true`); neutral badge named after the group | | Built-in group icons (ids 100, 200, 300, 500, 600) | partial | server has no file (core: `not_found`, `builtin:true`); neutral badge named after the group |
| Channel icons and channel banners | proven | tree-metadata run: 11/11 channel icons and 11/11 banners from the server's file transfer | | Channel icons and channel banners | proven | tree-metadata run: 11/11 channel icons and 11/11 banners from the server's file transfer |
| Host banner | proven | tree-metadata run: server GIF rendered above the tree | | Host banner | proven | tree-metadata run: server GIF rendered above the tree |
@@ -35,8 +36,8 @@ UI, evidence path given; **implemented** = code + unit/loopback tests, no live p
| Identity import / restore from backup | implemented, not exercised | uses the same core CLI; import of a file produced by the official TeamSpeak client not verified | | Identity import / restore from backup | implemented, not exercised | uses the same core CLI; import of a file produced by the official TeamSpeak client not verified |
| Hardware video decode on/off | proven (policy) | packaged run: saved off → restart → launched with `disable-accelerated-video-decode`, engine reports `disabled_software`. Separately, the live TS6 stream decoded AV1 with `D3D11VideoDecoder` while allowed; no claim for other codecs | | Hardware video decode on/off | proven (policy) | packaged run: saved off → restart → launched with `disable-accelerated-video-decode`, engine reports `disabled_software`. Separately, the live TS6 stream decoded AV1 with `D3D11VideoDecoder` while allowed; no claim for other codecs |
| Cisco OpenH264 toggle / per-codec backend choice | not possible in this engine | Chromium WebRTC decodes H.264 with FFmpeg (OpenH264 only encodes) and exposes no decoder selection; stated in settings | | Cisco OpenH264 toggle / per-codec backend choice | not possible in this engine | Chromium WebRTC decodes H.264 with FFmpeg (OpenH264 only encodes) and exposes no decoder selection; stated in settings |
| Linux x64 / arm64 packages | released (pre-release v0.1.0), built in CI | release run #11 on `674cae8`: tests, core smoke (arm64 under qemu), every packaged arm64 ELF incl. the AppImage runtime 16 KiB-compatible; see `docs/evidence/release-v0.1.0.md`. Not run on Asahi hardware (target unreachable) | | Linux x64 / arm64 packages | released (pre-release v0.1.1), built in CI | release run #18 on `71300ff`: tests, core smoke (arm64 under qemu), every packaged arm64 ELF 16 KiB-compatible, static AppImage runtime starts in a slim container (arm64 under qemu); `docs/evidence/release-v0.1.1.md`. v0.1.0 ARM64 AppImage is broken (needs `libz.so`). Not run on Asahi hardware (target unreachable) |
| Windows x64 package | released (pre-release v0.1.0), local build | built on the developer PC from `674cae8`, static CRT core, provenance file attached; packaged smoke in `docs/evidence/runtime/2026-10-24-windows-package*/`; not tested on a pristine Windows | | Windows x64 package | released (pre-release v0.1.1), local build | built on the developer PC from `71300ff`, static CRT core, provenance file attached; packaged smoke in `docs/evidence/runtime/2026-10-24-windows-package*/`; not tested on a pristine Windows |
| macOS, Windows ARM64 | blocked | no macOS host; Windows ARM64 needs the VS "MSVC ARM64 build tools" component (not installed) | | macOS, Windows ARM64 | blocked | no macOS host; Windows ARM64 needs the VS "MSVC ARM64 build tools" component (not installed) |
| Server/channel group (role) and permission management | not implemented | groups are displayed read-only; no assignment or permission editing | | Server/channel group (role) and permission management | not implemented | groups are displayed read-only; no assignment or permission editing |
| General file browser / file transfer | not implemented | file transfer is used internally only to download icons, banners and avatars | | General file browser / file transfer | not implemented | file transfer is used internally only to download icons, banners and avatars |
+2
View File
@@ -6,5 +6,7 @@
(`LICENSE`, `LICENSES.chromium.html`), as placed there by electron-builder. (`LICENSE`, `LICENSES.chromium.html`), as placed there by electron-builder.
- The native core (`teamspeach-core`, built on ReSpeak tsclientlib, libopus and other Rust crates) - The native core (`teamspeach-core`, built on ReSpeak tsclientlib, libopus and other Rust crates)
ships its complete third-party notices in `teamspeach-core-THIRD_PARTY_NOTICES.md` in this folder. ships its complete third-party notices in `teamspeach-core-THIRD_PARTY_NOTICES.md` in this folder.
This includes the earshot voice detector (MIT OR Apache-2.0), whose crate embeds the small neural network
it runs (`weights.bin`) under the same license.
- TeamSpeak is a trademark of TeamSpeak Systems GmbH. TeamsPeach is an independent client and is not - TeamSpeak is a trademark of TeamSpeak Systems GmbH. TeamsPeach is an independent client and is not
affiliated with or endorsed by TeamSpeak Systems GmbH. affiliated with or endorsed by TeamSpeak Systems GmbH.
+8 -5
View File
@@ -33,8 +33,9 @@ working voice and can watch a friend's stream.
## Positioning ## Positioning
An independent, account-free TeamSpeak 6 client that interoperates with the official client's voice and P2P An independent, account-free TeamSpeak 6 client targeting interoperability with the official client's voice
screenshare protocol, built for platforms the official client does not serve. and P2P screenshare protocol on platforms the official client does not serve. This is a product goal, not
a claim of complete interoperability; the evidence matrix records the demonstrated scope.
## Operating Context ## Operating Context
@@ -53,7 +54,8 @@ from this client).
## Brand Commitments ## Brand Commitments
Name "TeamsPeach"; restrained peach accent (*inferred* from the name and brief); Russian interface language. Name "TeamsPeach"; restrained peach accent (*inferred* from the name and brief); English as the default
interface language, with Russian selectable through the shared translation catalog.
The owner pinned a visual reference for settings (TeamSpeak 6 style: category navigation on the left, The owner pinned a visual reference for settings (TeamSpeak 6 style: category navigation on the left,
titled card sections on the right, dark blue-gray surfaces); settings follow it. titled card sections on the right, dark blue-gray surfaces); settings follow it.
The owner explicitly asked for a straightforward, familiar chat UI rather than a branding exercise. The owner explicitly asked for a straightforward, familiar chat UI rather than a branding exercise.
@@ -73,5 +75,6 @@ benchmarks exist and none may be invented.
## Accessibility & Inclusion ## Accessibility & Inclusion
Keyboard-operable controls with visible focus, screen-reader names for icon buttons and tree rows, light and Keyboard-operable controls with visible focus, screen-reader names for icon buttons and tree rows, light
dark themes following the OS, readable system fonts (*inferred* from the brief). and dark themes with an optional System mode, and readable system fonts. New profiles default to dark;
an existing saved theme choice is preserved.
+136 -78
View File
@@ -1,109 +1,167 @@
# TeamsPeach # TeamsPeach
Настольный клиент для серверов **TeamSpeak 6** без учётной записи myTeamSpeak: голос, чат, дерево A desktop client for **TeamSpeak 6** servers without a myTeamSpeak account: voice, chat, a channel tree
каналов с группами/иконками/баннерами сервера и **просмотр трансляций экрана TS6**. with server groups, icons and banners, and **TS6 screenshare viewing**.
Интерфейс — Electron (обычные JS-модули, HTML/CSS), протокол — нативное ядро на Rust The interface uses Electron (plain JavaScript modules and HTML/CSS); a native Rust core handles the
(`core/`, ReSpeak tsclientlib) через приватный stdio (контракт: [`docs/bridge.md`](docs/bridge.md)). protocol (`core/`, ReSpeak tsclientlib) over private stdio. See the [bridge contract](docs/bridge.md).
Подробная карта возможностей и доказательств: [`FEATURE_COMPATIBILITY.md`](FEATURE_COMPATIBILITY.md). See [`FEATURE_COMPATIBILITY.md`](FEATURE_COMPATIBILITY.md) for feature status and evidence. This is not a
claim of full TeamSpeak 6 parity: official-client voice interoperability and Asahi hardware operation
have not been proven.
## Запуск для разработки (Windows / Linux) ## Development (Windows / Linux)
``` ```
npm ci npm ci
cargo build --release --locked --manifest-path core/Cargo.toml # нужен Rust ≥ 1.89, CMake, C-компилятор cargo build --release --locked --manifest-path core/Cargo.toml # requires Rust ≥ 1.89, CMake and a C compiler
npm start npm start
``` ```
Electron ищет ядро в `core/target/release` и `core/target/debug` (берётся более свежий файл). Electron looks for the core in `core/target/release` and `core/target/debug`, choosing the newer binary.
На Windows cargo установлен rustup'ом без изменения PATH — запускайте `%USERPROFILE%\.cargo\bin\cargo.exe` If rustup installed Cargo without adding it to PATH on Windows, run
или откройте «Developer PowerShell for VS». При нехватке памяти линковки используйте `-j 2`. `%USERPROFILE%\.cargo\bin\cargo.exe` or open Developer PowerShell for VS. Use `-j 2` if linking runs out
of memory.
Отдельный профиль (не трогает основной): `TEAMSPEACH_PROFILE_DIR=<абсолютный путь> npm start`. Use a separate profile without touching the main one: `TEAMSPEACH_PROFILE_DIR=<absolute-path> npm start`.
## Сборка пакетов ## Packaging
``` ```
npm run dist:win-x64 # NSIS + zip npm run dist:win-x64 # NSIS + zip
npm run dist:linux-x64 # AppImage + tar.gz npm run dist:linux-x64 # AppImage + tar.gz
npm run dist:linux-arm64 # AppImage + tar.gz (ядро aarch64 собирается отдельно) npm run dist:linux-arm64 # AppImage + tar.gz (build the aarch64 core separately)
``` ```
`scripts/dist.mjs` **отказывается** собирать пакет без ядра нужной ОС/архитектуры (проверка `scripts/dist.mjs` **refuses** to package without a core for the target OS and architecture (checked via
заголовка PE/ELF/Mach-O), кладёт `THIRD_PARTY_NOTICES.md` ядра в `resources/licenses/` и проверяет, its PE/ELF/Mach-O header), copies the core's `THIRD_PARTY_NOTICES.md` into `resources/licenses/`, and
что ядро действительно попало в пакет. Для Asahi (страницы 16 КиБ) есть checks that the package actually contains the core. For Asahi's 16 KiB pages, use
`node scripts/elf-pagesize.mjs <файл|папка>` — проверка выравнивания PT_LOAD, glibc и зависимостей. `node scripts/elf-pagesize.mjs <file-or-directory>` to check PT_LOAD alignment, glibc and dependencies.
CI: `.gitea/workflows/ci.yml` (Gitea Actions, контейнеры на Linux x64): тесты, сборка ядра, CI: `.gitea/workflows/ci.yml` (Gitea Actions, Linux x64 containers) runs tests, builds the core, checks
офлайн-проверка идентичности через stdio, Electron-смоук под Xvfb, кросс-сборка ядра aarch64 с identity invariants offline over stdio, runs Electron smoke checks under Xvfb, and cross-compiles the
проверкой 16 КиБ и запуском под `qemu-aarch64` (эмуляция, не железо Apple). Запускается только на push в aarch64 core with 16 KiB checks and execution under `qemu-aarch64` (emulation, not Apple hardware).
`main` и вручную: автоматического запуска для pull request нет — репозиторий публичный, а раннер стоит It runs on pushes to `main` and manual dispatch only. Pull requests do not run automatically: this is a
во внутренней сети, поэтому чужие изменения сначала просматривает мейнтейнер. public repository with a runner on a private network, so a maintainer reviews external changes first.
Релизы: `.gitea/workflows/release.yml` по тегу `v*` (тег должен совпадать с версией в `package.json` и Releases: `.gitea/workflows/release.yml` runs for `v*` tags. The tag must match `package.json` and
`core/Cargo.toml`) собирает Linux x64 и ARM64, проверяет ELF и публикует релиз (черновик → все файлы → `core/Cargo.toml`. It builds Linux x64 and ARM64, checks ELF files, and publishes the release only after
публикация). Сборка Windows x64 делается на машине разработчика из того же коммита и прикладывается с uploading all files to a draft. Windows x64 is built on the developer's machine from the same commit and
пометкой `local` и файлом происхождения `*-build-info.txt`. attached with a `local` designation and a `*-build-info.txt` provenance file.
## Использование ## Usage
1. Первый запуск: один раз ввести никнейм — создаётся криптографическая идентичность (P-256), 1. On first launch, enter a nickname to create a cryptographic identity (P-256). The public UID is shown
публичный UID виден в «Настройки → Идентичность». Никнейм меняется без смены UID. in Settings → Identity. Changing your nickname does not change your UID.
2. Ввести адрес сервера (и пароль, если нужен) → «Подключиться». Кнопка «Сохранить» добавляет адрес в 2. Enter a server address and, if required, its password, then select Connect. Save adds the address to
сохранённые серверы: они видны слева над деревом (значок закладки в шапке), подключение — в один клик; saved servers above the tree; the bookmark button in the header toggles that list. Connect with one
если вы уже на другом сервере, кнопка называется «Переключиться» и сначала корректно отключает текущий. click. If already connected elsewhere, Switch first disconnects from the current server cleanly.
Название, адрес и удаление — в «Настройки → Серверы». Пароли серверов не сохраняются; для всех серверов Edit names and addresses or remove entries in Settings → Servers. Server passwords are not saved;
используется одна и та же идентичность. all servers use the same identity.
3. Клик по каналу — переход (для каналов с паролем откроется поле ввода). 3. Click a channel to join it. Password-protected channels show a password field.
4. Голос: «Нажми и говори» (по умолчанию F8 или кнопка в шапке) либо «Открытый микрофон»; 4. Choose how your voice is sent in Settings → Audio → Voice transmission:
кнопки микрофона и звука внизу слева видны серверу. - **Push to talk** (default): hold F8 (change it in Settings → Keyboard) or the button in the channel
5. Трансляции: у стримящего участника появится кнопка «Смотреть». Громкость, отключение звука, header. The key works **only while the TeamsPeach window is focused**; the header hint says so.
полный экран, «Прекратить просмотр» — на панели под видео. В строке статуса — реально - **Voice activation**: a small voice detector built into TeamsPeach decides on this computer when you
согласованный кодек, разрешение и частота кадров. are speaking and sends only then, from about 0.1 s before a detected word until about 0.4 s after the
last detected speech (the first spurt after connecting, unmuting or changing the mode carries up to
0.3 s of held audio and so starts up to 0.3 s late). Sensitivity: High (quieter speech), Normal, Low (noisier surroundings). It runs
after the microphone processing in the same panel (noise suppression, echo cancellation, gain
control). It is not speech recognition and saves nothing; loud speech-like sound (TV, other voices)
can also trigger it.
- **Open microphone**: continuous transmission.
The microphone test only shows the input level and never transmits. The microphone and audio buttons at
the bottom left update your server-visible mute state; muting or deafening stops transmission in every
mode. Right-click these buttons, or press Shift+F10 while focused, to select an input or output device
using the same selection as Settings → Audio. Left-click still mutes or deafens.
5. A streaming member has a Watch button. Volume, mute, fullscreen and Stop watching are below the video.
The status line shows the negotiated codec, resolution and frame rate.
## Резервная копия идентичности ## Language
«Настройки → Профиль → Экспортировать…» сохраняет файл в формате TeamSpeak (`.ini`) через системный The interface defaults to English, independently of the operating-system language. Select Russian in
диалог. **Файл содержит закрытый ключ** — храните как пароль. Восстановление: «Импортировать…» Settings → Appearance; the saved choice applies to the interface and native identity dialogs. Language
(после отключения от сервера; текущая идентичность заменяется только после подтверждения) или changes do not translate server names, chat messages or operating-system device names.
кнопка «Восстановить из резервной копии…» на экране первого запуска. Ядро никогда не создаёт новую
идентичность поверх повреждённой.
Данные: `%APPDATA%\TeamsPeach` (Windows), `~/.config/TeamsPeach` (Linux): `core/identity.json`, ## Updates
`core/profile.json`, `prefs.json`, `logs/`.
## Ограничения (честно) Check for updates in Settings → Information. The first updater-capable version must be installed
manually: version 0.1.1 and older cannot update themselves. Updates come only from published releases
of the public [TeamsPeach/client repository](https://git.eeee.moe/TeamsPeach/client), without credentials.
- Трансляции только P2P (как у официального клиента по умолчанию). SFU-трансляции сервер Windows x64 NSIS installations and Linux x64/ARM64 AppImages can download a verified package and install
обозначает уведомлением — TeamsPeach пишет «не поддерживается». TURN нет: нужен прямой путь it after confirmation. Windows zip and Linux tar.gz distributions notify you and open the release page;
до компьютера стримера (STUN `turn.teamspeak.com`, как у официального клиента). replace those files manually. Development runs and unsupported platforms do not self-update. The
- Показ своего экрана (отправка трансляции) не реализован. default Preview channel includes prereleases; choose Stable to exclude them. Installation never starts
- Клавиша PTT в TeamsPeach работает только пока окно активно: глобальная клавиша с удержанием automatically, and interrupting an active server session requires explicit confirmation.
(например, через портал GlobalShortcuts на Wayland) не реализована.
- Цвет ника: официальный клиент подсвечивает собственный ник и ники контактов myTeamSpeak (локальные
связи, а не данные сервера). Без учётной записи контактов нет, поэтому TeamsPeach выделяет только свой ник.
- Аватары: показываются серверные и myTeamSpeak-аватары (публичные https-ссылки, байты проверяются по
сигнатуре). Встроенные иконки групп TeamSpeak (id 100, 200, 300, 500, 600) — нейтральный значок с
названием группы: у сервера нет этих файлов.
- Управление «Cisco OpenH264» и выбор аппаратных бэкендов из TS6 в движке Chromium недоступны;
декодирование выбирает Chromium (на Windows подтверждён аппаратный D3D11 для AV1).
- Сборки macOS и Windows ARM64 не выпускаются: нет сборочных машин. Linux ARM64 собирается
кроссом; запуск на Asahi M1 Pro не проверен — машина недоступна по SSH.
- Пакеты не подписаны: Windows SmartScreen и macOS Gatekeeper будут предупреждать.
## Продукт и дизайн For platform details, release requirements and verification scope, see [Updates](docs/updates.md).
Implementation and service-level tests do not by themselves prove a successful installed upgrade;
published-release end-to-end evidence must identify the source and destination versions.
Рабочий инструмент: привычная раскладка голосового чата (сервер и дерево слева, канал/чат справа), ## Identity backups
настройки — разделы слева (Идентичность, Серверы, Внешний вид, Звук, Видео, Клавиши, Информация) и
карточки справа, как на образце владельца; тема — «как в системе», тёмная или светлая.
Системные шрифты, единственный акцент — персиковый; зелёный —
только «говорит». Всё содержимое сервера выводится как текст (`textContent`), изображения — только
байты, проверенные по сигнатуре. Renderer изолирован (contextIsolation, sandbox, строгая CSP,
список разрешённых команд в main); пути к файлам выбирает только main через системные диалоги.
## Проверки Settings → Identity → Export saves a TeamSpeak-format `.ini` file through a native dialog.
**This file contains your private key: protect it like a password.** Restore it with Import after
disconnecting from the server; replacing the current identity requires confirmation. You can also use
Restore from backup on the first-run screen. The core never silently replaces a corrupt identity.
- `npm test` — модульные тесты (валидация IPC, сессия просмотра, каталог трансляций). Data locations: `%APPDATA%\TeamsPeach` (Windows), `~/.config/TeamsPeach` (Linux). Files include
- `node scripts/core-smoke.mjs <ядро>` — офлайн-инварианты идентичности. `core/identity.json`, `core/profile.json`, `prefs.json` and `logs/`.
- `node scripts/smoke-ui.mjs`, `smoke-voice.mjs`, `probe-stream.mjs`, `loopback-stream.mjs`,
`smoke-tree.mjs` — реальный UI; результаты прогонов лежат в `docs/evidence/runtime/`. ## Limitations
- Screenshares use P2P only, as the official client does by default. SFU notifications are reported as
unsupported. There is no TURN relay: the viewer needs a direct network path to the streaming computer
(STUN uses `turn.teamspeak.com`, as in the official client).
- Sending your own screenshare is not implemented.
- Push-to-talk only works while the window is focused. A global hold-to-talk shortcut, such as one using
the Wayland GlobalShortcuts portal, is not implemented.
- The official client highlights your own nickname and myTeamSpeak contacts using local relationships,
not server data. Without an account there are no contacts, so TeamsPeach highlights only your own name.
- Server-stored avatars, icons and banners use TeamSpeak file transfer. myTeamSpeak avatars use public
HTTPS URLs announced by the server; downloaded image bytes are checked by signature. A myTeamSpeak
avatar was observed in the live run; server-stored avatar support is implemented but was not exercised
live because no client on the test server advertised one.
Built-in TeamSpeak group icons (IDs 100, 200, 300, 500, 600) use a neutral badge with the group name,
because the server does not supply these files.
- Chromium does not expose the official client's Cisco OpenH264 switch or per-codec hardware backend
selection. Chromium chooses the decoder; AV1 hardware decoding with D3D11 was demonstrated on Windows.
- macOS and Windows ARM64 builds are not published because build hosts are unavailable. Linux ARM64 is
cross-compiled; execution on Asahi M1 Pro hardware has not been checked because the target was
unreachable over SSH.
- Packages are unsigned. Windows SmartScreen warns about unsigned builds; macOS Gatekeeper would also
require attention for a future macOS build.
- The recorded two-way voice run used synthetic capture between two TeamsPeach clients. It does not
prove live microphone interoperability with the official TS6 client or operation on Asahi hardware.
## Product and design
A familiar voice-chat layout: server and channel tree on the left, channel and chat on the right.
Settings use category navigation (Identity, Servers, Appearance, Audio, Video, Keys, Information) on the
left and cards on the right, following the supplied reference. New profiles default to a dark theme,
independent of the OS. Choose Light or System in Settings → Appearance; the choice persists, and an
existing saved choice is preserved across upgrades.
System fonts and a restrained peach accent keep the interface readable; green indicates a speaker.
Server text is rendered with `textContent`; image bytes are checked by signature. The renderer uses
context isolation, a sandbox, a strict CSP and allowlisted main-process commands. Only the main process
selects file paths through native dialogs.
## Repository language and evidence
Repository-authored documentation, comments, logs, diagnostics, scripts and release notes are in
English. Localized UI text belongs in the shared translation catalog; technical error details stay in
English and may be shown after a localized explanation. Server content, operating-system device names
and user messages are data, not translation resources.
Historical JSON captures and screenshots in `docs/evidence/runtime/` retain the exact UI text, server
names and device names observed during each run, including Russian text. They are not translated or
rewritten to resemble the current interface. Unicode test fixtures retain their original values.
## Checks
- `npm test` runs unit tests for contracts such as IPC validation, viewer sessions and stream discovery.
- `node scripts/core-smoke.mjs <core-binary>` checks identity invariants offline.
- `node scripts/smoke-ui.mjs`, `smoke-voice.mjs`, `probe-stream.mjs`, `loopback-stream.mjs` and
`smoke-tree.mjs` exercise the real UI. Recorded results are in `docs/evidence/runtime/`; each run's
scope and limitations apply.
+14 -14
View File
@@ -57,7 +57,7 @@ class CoreProcess extends EventEmitter {
}); });
} catch (err) { } catch (err) {
log.end(); log.end();
this._setStatus('failed', { message: err.message }); this._setStatus('failed', { reason: 'spawn', message: err.message });
return; return;
} }
this.child = child; this.child = child;
@@ -72,7 +72,7 @@ class CoreProcess extends EventEmitter {
const readyTimer = setTimeout(() => { const readyTimer = setTimeout(() => {
if (this.status === 'starting') { if (this.status === 'starting') {
log.write('[main] core did not report ready in time, terminating\n'); 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(); child.kill();
} }
}, READY_TIMEOUT_MS); }, READY_TIMEOUT_MS);
@@ -80,7 +80,7 @@ class CoreProcess extends EventEmitter {
child.on('error', (err) => { child.on('error', (err) => {
clearTimeout(readyTimer); clearTimeout(readyTimer);
log.write(`[main] spawn error: ${err.message}\n`); 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) => { child.on('exit', (code, signal) => {
@@ -91,7 +91,7 @@ class CoreProcess extends EventEmitter {
this.child = null; this.child = null;
for (const [, entry] of this.pending) { for (const [, entry] of this.pending) {
clearTimeout(entry.timer); 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(); this.pending.clear();
const expected = this.stopping; const expected = this.stopping;
@@ -123,7 +123,7 @@ class CoreProcess extends EventEmitter {
this.coreVersion = typeof msg.core_version === 'string' ? msg.core_version : null; this.coreVersion = typeof msg.core_version === 'string' ? msg.core_version : null;
if (msg.protocol !== 1) { if (msg.protocol !== 1) {
log.write(`[main] unsupported core protocol ${msg.protocol}\n`); 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(); this.child?.kill();
return; return;
} }
@@ -145,19 +145,19 @@ class CoreProcess extends EventEmitter {
request(cmd, args) { request(cmd, args) {
if (!this.child || this.status !== 'ready') { 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 id = `m${this.nextId++}`;
const payload = args === undefined ? { id, cmd } : { id, cmd, args }; const payload = args === undefined ? { id, cmd } : { id, cmd, args };
const line = JSON.stringify(payload) + '\n'; const line = JSON.stringify(payload) + '\n';
if (Buffer.byteLength(line) > MAX_LINE_BYTES) { 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) => { return new Promise((resolve) => {
const timeoutMs = TIMEOUTS[cmd] ?? TIMEOUTS.default; const timeoutMs = TIMEOUTS[cmd] ?? TIMEOUTS.default;
const timer = setTimeout(() => { const timer = setTimeout(() => {
this.pending.delete(id); 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); }, timeoutMs);
this.pending.set(id, { resolve, timer }); this.pending.set(id, { resolve, timer });
this.child.stdin.write(line); this.child.stdin.write(line);
@@ -194,7 +194,7 @@ class CoreProcess extends EventEmitter {
} }
function normalizeError(error) { 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 ?? '') }; 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.ts_error && typeof error.ts_error === 'object') out.ts_error = error.ts_error;
if (error.detail && typeof error.detail === 'object') out.detail = error.detail; if (error.detail && typeof error.detail === 'object') out.detail = error.detail;
@@ -203,11 +203,11 @@ function normalizeError(error) {
function exitMessage(code) { function exitMessage(code) {
switch (code) { switch (code) {
case 0: return 'Ядро завершило работу'; case 0: return 'The core exited';
case 2: return 'Ядро отклонило аргументы запуска'; case 2: return 'The core rejected its start arguments';
case 3: return 'Профиль уже используется другим экземпляром TeamsPeach или каталог данных недоступен'; case 3: return 'The profile is in use by another TeamsPeach instance or the data directory is unavailable';
case 1: return 'Внутренняя ошибка ядра (подробности в журнале core.log)'; case 1: return 'Internal core error (details in core.log)';
default: return `Ядро завершилось с кодом ${code}`; default: return `The core exited with code ${code}`;
} }
} }
+19 -18
View File
@@ -16,27 +16,27 @@ class ValidationError extends Error {
const CONTROL_CHARS = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/; const CONTROL_CHARS = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
const str = (min, max, { multiline = false, maxBytes } = {}) => (value, key) => { const str = (min, max, { multiline = false, maxBytes } = {}) => (value, key) => {
if (typeof value !== 'string') 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}: недопустимая длина`); 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}: слишком длинно`); 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)) { 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; return value;
}; };
const posInt = (value, key) => { 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; return value;
}; };
const bool = (value, key) => { 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; return value;
}; };
const oneOf = (...allowed) => (value, key) => { 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; return value;
}; };
@@ -53,15 +53,15 @@ function isPlainObject(value) {
function shape(spec) { function shape(spec) {
return (args) => { return (args) => {
if (args === undefined || args === null) 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)) { 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 = {}; const out = {};
for (const [key, check] of Object.entries(spec)) { for (const [key, check] of Object.entries(spec)) {
const value = args[key]; const value = args[key];
if (value === undefined) { if (value === undefined) {
if (!check.optional) throw new ValidationError(`${key}: обязательный аргумент`); if (!check.optional) throw new ValidationError(`${key}: required argument`);
continue; continue;
} }
out[key] = check(value, key); out[key] = check(value, key);
@@ -74,12 +74,12 @@ const streamId = str(1, 256);
const SIGNAL_COMMANDS = new Set(['answer', 'iceCandidate']); const SIGNAL_COMMANDS = new Set(['answer', 'iceCandidate']);
function signalJson(value) { 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); const keys = Object.keys(value);
if (keys.length !== 2 || !keys.includes('cmd') || !keys.includes('args')) throw new ValidationError('json: ожидались поля cmd и args'); 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: недопустимая команда сигнализации'); if (!SIGNAL_COMMANDS.has(value.cmd)) throw new ValidationError('json.cmd: signalling command not allowed');
const args = value.args; 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') { if (value.cmd === 'answer') {
shape({ answer: str(1, 60000, { multiline: true }) })(args); shape({ answer: str(1, 60000, { multiline: true }) })(args);
} else { } else {
@@ -90,7 +90,7 @@ function signalJson(value) {
})(args); })(args);
} }
const serialized = JSON.stringify(value); 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); return JSON.parse(serialized);
} }
@@ -113,18 +113,19 @@ const COMMANDS = {
message: str(1, 8192, { multiline: true, maxBytes: 8192 }), message: str(1, 8192, { multiline: true, maxBytes: 8192 }),
})(args); })(args);
if ((out.target === 'client') !== (out.client_id !== undefined)) { 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; return out;
}, },
set_audio: shape({ input_muted: optional(bool), output_muted: optional(bool) }), set_audio: shape({ input_muted: optional(bool), output_muted: optional(bool) }),
set_transmit: shape({ mode: oneOf('direct', 'vad'), sensitivity: optional(oneOf('high', 'normal', 'low')) }),
stream_list: shape({ client_id: optional(posInt) }), stream_list: shape({ client_id: optional(posInt) }),
stream_join: shape({ stream_id: streamId, client_id: posInt, message: optional(str(0, 200)) }), stream_join: shape({ stream_id: streamId, client_id: posInt, message: optional(str(0, 200)) }),
stream_signal: shape({ stream_id: streamId, client_id: posInt, json: signalJson }), stream_signal: shape({ stream_id: streamId, client_id: posInt, json: signalJson }),
stream_leave: shape({ stream_id: streamId, client_id: posInt }), stream_leave: shape({ stream_id: streamId, client_id: posInt }),
fetch_icon: shape({ fetch_icon: shape({
icon_id: (v, k) => { 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; return v;
}, },
}), }),
@@ -136,7 +137,7 @@ const COMMANDS = {
/** Returns sanitized args or throws ValidationError. */ /** Returns sanitized args or throws ValidationError. */
function validateRequest(cmd, args) { function validateRequest(cmd, args) {
if (typeof cmd !== 'string' || !Object.prototype.hasOwnProperty.call(COMMANDS, cmd)) { 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'; err.code = 'unknown_command';
throw err; throw err;
} }
+53 -23
View File
@@ -20,7 +20,12 @@ if (profileOverride) {
const { RENDERER_DIR, resolveCoreBinary, dataDir, logsDir, prefsFile } = require('./paths'); const { RENDERER_DIR, resolveCoreBinary, dataDir, logsDir, prefsFile } = require('./paths');
const { CoreProcess } = require('./core-process'); const { CoreProcess } = require('./core-process');
const { validateRequest } = require('./ipc-validate'); const { validateRequest } = require('./ipc-validate');
const { permissionCheckAllowed, permissionRequestAllowed } = require('./permissions');
// 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 { Prefs } = require('./prefs');
const { createUpdateService } = require('./updates');
const i18n = require('../renderer/shared/i18n.js');
const APP_SCHEME = 'app'; const APP_SCHEME = 'app';
const APP_HOST = 'teamspeach'; const APP_HOST = 'teamspeach';
@@ -83,6 +88,7 @@ if (!gotInstanceLock) {
let coreStatus = { status: 'starting' }; let coreStatus = { status: 'starting' };
let connectionState = 'disconnected'; let connectionState = 'disconnected';
let updates = null;
let quitting = false; let quitting = false;
let rendererLog = null; let rendererLog = null;
let rendererLogBudget = { windowStart: 0, count: 0 }; let rendererLogBudget = { windowStart: 0, count: 0 };
@@ -153,7 +159,7 @@ async function restartCore() {
function runCoreCli(args) { function runCoreCli(args) {
const binary = resolveCoreBinary(); 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) => { return new Promise((resolve) => {
execFile(binary.path, args, { windowsHide: true, timeout: 30000, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => { execFile(binary.path, args, { windowsHide: true, timeout: 30000, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
if (stderr) appendLog('core-cli.log', stderr); if (stderr) appendLog('core-cli.log', stderr);
@@ -165,10 +171,10 @@ function runCoreCli(args) {
parsed = null; parsed = null;
} }
if (parsed && typeof parsed === 'object') { 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; 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' } });
}); });
}); });
} }
@@ -212,7 +218,7 @@ function sniffImage(b) {
async function fetchExternalMedia(url) { async function fetchExternalMedia(url) {
if (typeof url !== 'string' || !externalMedia.has(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 }); if (!mediaSession) mediaSession = session.fromPartition('teamspeach-media', { cache: true });
const controller = new AbortController(); const controller = new AbortController();
@@ -231,17 +237,17 @@ async function fetchExternalMedia(url) {
size += value.byteLength; size += value.byteLength;
if (size > EXTERNAL_MEDIA_LIMIT) { if (size > EXTERNAL_MEDIA_LIMIT) {
controller.abort(); 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)); chunks.push(Buffer.from(value));
} }
const bytes = Buffer.concat(chunks); const bytes = Buffer.concat(chunks);
// Servers mislabel images (e.g. text/plain); trust only the bytes. // Servers mislabel images (e.g. text/plain); trust only the bytes.
const mime = sniffImage(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') } }; return { ok: true, result: { mime, bytes: bytes.length, data: bytes.toString('base64') } };
} catch (err) { } 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 { } finally {
clearTimeout(timer); clearTimeout(timer);
} }
@@ -249,11 +255,16 @@ async function fetchExternalMedia(url) {
// ---------- identity backup (main-only, native dialogs) ---------- // ---------- 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() { async function exportIdentity() {
const result = await dialog.showSaveDialog(mainWindow, { const result = await dialog.showSaveDialog(mainWindow, {
title: 'Экспорт идентичности TeamsPeach', title: tr('native.identityExport.title'),
defaultPath: path.join(app.getPath('documents'), 'teamspeach-identity.ini'), 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'], properties: ['showOverwriteConfirmation', 'createDirectory'],
}); });
if (result.canceled || !result.filePath) return { ok: false, canceled: true }; if (result.canceled || !result.filePath) return { ok: false, canceled: true };
@@ -270,16 +281,16 @@ async function exportIdentity() {
async function importIdentity() { async function importIdentity() {
if (connectionState !== 'disconnected') { 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')); const identityExists = fs.existsSync(path.join(dataDir(), 'identity.json'));
if (identityExists) { if (identityExists) {
const confirm = await dialog.showMessageBox(mainWindow, { const confirm = await dialog.showMessageBox(mainWindow, {
type: 'warning', type: 'warning',
title: 'Заменить идентичность?', title: tr('native.identityReplace.title'),
message: 'Импорт заменит текущую идентичность.', message: tr('native.identityReplace.message'),
detail: 'Текущий UID будет потерян, если у вас нет его резервной копии. Серверные права и группы привязаны к UID.', detail: tr('native.identityReplace.detail'),
buttons: ['Отмена', 'Выбрать файл и заменить'], buttons: [tr('native.identityReplace.cancel'), tr('native.identityReplace.confirm')],
defaultId: 0, defaultId: 0,
cancelId: 0, cancelId: 0,
noLink: true, noLink: true,
@@ -287,8 +298,8 @@ async function importIdentity() {
if (confirm.response !== 1) return { ok: false, canceled: true }; if (confirm.response !== 1) return { ok: false, canceled: true };
} }
const pick = await dialog.showOpenDialog(mainWindow, { const pick = await dialog.showOpenDialog(mainWindow, {
title: 'Импорт идентичности', title: tr('native.identityImport.title'),
filters: [{ name: 'Идентичность TeamSpeak', extensions: ['ini'] }, { name: 'Все файлы', extensions: ['*'] }], filters: [{ name: tr('native.identity.filter'), extensions: ['ini'] }, { name: tr('native.allFiles'), extensions: ['*'] }],
properties: ['openFile'], properties: ['openFile'],
}); });
if (pick.canceled || pick.filePaths.length !== 1) return { ok: false, canceled: true }; if (pick.canceled || pick.filePaths.length !== 1) return { ok: false, canceled: true };
@@ -372,13 +383,12 @@ function registerProtocol() {
function hardenSession() { function hardenSession() {
const ses = session.defaultSession; const ses = session.defaultSession;
// Electron passes origins as "app://teamspeach/"; the policy normalises them (see permissions.js).
ses.setPermissionRequestHandler((_wc, permission, callback, details) => { ses.setPermissionRequestHandler((_wc, permission, callback, details) => {
const mediaTypes = details && Array.isArray(details.mediaTypes) ? details.mediaTypes : []; callback(permissionRequestAllowed(permission, details, APP_ORIGIN));
const audioOnly = mediaTypes.length > 0 && mediaTypes.every((t) => t === 'audio');
callback(permission === 'media' && audioOnly && isAppUrl(details.requestingUrl));
}); });
ses.setPermissionCheckHandler((_wc, permission, requestingOrigin) => { ses.setPermissionCheckHandler((_wc, permission, requestingOrigin, details) => {
return (permission === 'media' || permission === 'speaker-selection') && requestingOrigin === APP_ORIGIN; return permissionCheckAllowed(permission, requestingOrigin, details, APP_ORIGIN);
}); });
ses.setDisplayMediaRequestHandler((_request, callback) => callback({})); ses.setDisplayMediaRequestHandler((_request, callback) => callback({}));
} }
@@ -405,7 +415,7 @@ function registerIpc() {
} catch (err) { } catch (err) {
return { ok: false, error: { code: err.code || 'bad_request', message: err.message } }; 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 hasArgs = Object.keys(clean).length > 0;
const response = await core.request(cmd, hasArgs ? clean : undefined); const response = await core.request(cmd, hasArgs ? clean : undefined);
if (!response.ok && response.error.code === 'external_media' && response.error.detail) { if (!response.ok && response.error.code === 'external_media' && response.error.detail) {
@@ -498,6 +508,8 @@ function registerIpc() {
if (now - rendererLogBudget.windowStart > 1000) rendererLogBudget = { windowStart: now, count: 0 }; if (now - rendererLogBudget.windowStart > 1000) rendererLogBudget = { windowStart: now, count: 0 };
if (++rendererLogBudget.count > 40) return; if (++rendererLogBudget.count > 40) return;
const lvl = ['debug', 'info', 'warn', 'error'].includes(level) ? level : 'info'; const lvl = ['debug', 'info', 'warn', 'error'].includes(level) ? level : 'info';
// Per-burst voice diagnostics are debug level: written only when started with TEAMSPEACH_LOG=debug|trace.
if (lvl === 'debug' && !RENDERER_DEBUG_LOG) return;
if (!rendererLog) { if (!rendererLog) {
fs.mkdirSync(logsDir(), { recursive: true }); fs.mkdirSync(logsDir(), { recursive: true });
rendererLog = fs.createWriteStream(path.join(logsDir(), 'renderer.log'), { flags: 'a' }); rendererLog = fs.createWriteStream(path.join(logsDir(), 'renderer.log'), { flags: 'a' });
@@ -517,8 +529,26 @@ app.whenReady().then(() => {
registerProtocol(); registerProtocol();
hardenSession(); hardenSession();
registerIpc(); registerIpc();
createWindow(); if (process.env.TEAMSPEACH_TEST_HOLD_WINDOW === '1') {
// Test harness only (scripts/lib/electron-app.mjs with --exe): Playwright cannot inject its startup loader
// into a packaged app, and attaching while the first page commits loses its utility world, so the harness
// attaches first and then creates the window through this hook.
globalThis.__teamspeachCreateWindow = () => {
delete globalThis.__teamspeachCreateWindow;
createWindow();
};
} else {
createWindow();
}
startCore(); 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()); app.on('window-all-closed', () => app.quit());
+44
View File
@@ -0,0 +1,44 @@
'use strict';
/**
* Media permission policy for the app's own origin. Electron reports origins as a URL spec with a
* trailing slash ("app://teamspeach/"), so origins are compared after normalisation. Only audio is
* ever allowed: microphone capture on request, device enumeration and output selection on check.
* Camera, screen capture and every other permission stay denied.
*/
// WHATWG URL reports "null" as the origin of non-special schemes such as app:, so the origin is rebuilt from
// the parsed protocol and host. Inputs with credentials or backslashes (lookalikes such as
// "app://teamspeach\@evil" or "app://teamspeach@evil") never match.
function normalizeOrigin(origin) {
if (typeof origin !== 'string' || origin.includes('\\')) return '';
let url;
try {
url = new URL(origin);
} catch {
return '';
}
if (url.username || url.password || !url.host) return '';
return `${url.protocol}//${url.host}`.toLowerCase();
}
function isAppOrigin(origin, appOrigin) {
return normalizeOrigin(origin) === appOrigin;
}
/** setPermissionCheckHandler: enumerateDevices labels/ids and setSinkId depend on this. */
function permissionCheckAllowed(permission, requestingOrigin, details, appOrigin) {
if (!isAppOrigin(requestingOrigin, appOrigin)) return false;
if (permission === 'media') return Boolean(details) && details.mediaType === 'audio';
return permission === 'speaker-selection';
}
/** setPermissionRequestHandler: getUserMedia for audio only, from a page of the app. */
function permissionRequestAllowed(permission, details, appOrigin) {
if (permission !== 'media' || !details) return false;
if (!isAppOrigin(details.requestingUrl, appOrigin)) return false;
const types = Array.isArray(details.mediaTypes) ? details.mediaTypes : [];
return types.length > 0 && types.every((t) => t === 'audio');
}
module.exports = { normalizeOrigin, permissionCheckAllowed, permissionRequestAllowed };
+15 -6
View File
@@ -9,7 +9,9 @@ const path = require('node:path');
*/ */
const SCHEMA = { const SCHEMA = {
lastAddress: { default: '', check: (v) => typeof v === 'string' && v.length <= 255 && !/[\u0000-\u001f]/.test(v) }, lastAddress: { default: '', check: (v) => typeof v === 'string' && v.length <= 255 && !/[\u0000-\u001f]/.test(v) },
transmitMode: { default: 'ptt', check: (v) => v === 'ptt' || v === 'open' }, // 'ptt' push-to-talk, 'open' continuous open microphone, 'vad' voice activation (the core's detector).
transmitMode: { default: 'ptt', check: (v) => v === 'ptt' || v === 'open' || v === 'vad' },
vadSensitivity: { default: 'normal', check: (v) => v === 'high' || v === 'normal' || v === 'low' },
pttCode: { default: 'F8', check: (v) => typeof v === 'string' && /^[A-Za-z0-9]{1,32}$/.test(v) }, pttCode: { default: 'F8', check: (v) => typeof v === 'string' && /^[A-Za-z0-9]{1,32}$/.test(v) },
inputDeviceId: { default: '', check: (v) => typeof v === 'string' && v.length <= 512 }, inputDeviceId: { default: '', check: (v) => typeof v === 'string' && v.length <= 512 },
outputDeviceId: { default: '', check: (v) => typeof v === 'string' && v.length <= 512 }, outputDeviceId: { default: '', check: (v) => typeof v === 'string' && v.length <= 512 },
@@ -19,7 +21,13 @@ const SCHEMA = {
voiceVolume: { default: 100, check: (v) => Number.isInteger(v) && v >= 0 && v <= 200 }, voiceVolume: { default: 100, check: (v) => Number.isInteger(v) && v >= 0 && v <= 200 },
hardwareVideoDecode: { default: true, check: (v) => typeof v === 'boolean' }, hardwareVideoDecode: { default: true, check: (v) => typeof v === 'boolean' },
streamVolume: { default: 100, check: (v) => Number.isInteger(v) && v >= 0 && v <= 100 }, streamVolume: { default: 100, check: (v) => Number.isInteger(v) && v >= 0 && v <= 100 },
theme: { default: 'system', check: (v) => v === 'system' || v === 'dark' || v === 'light' }, // Dark by default for new profiles regardless of the OS (owner's request); a stored valid choice —
// including 'system' or 'light' — is always kept.
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. // Quick-access servers: name + address only. Passwords are never stored.
savedServers: { default: [], check: validServers }, savedServers: { default: [], check: validServers },
}; };
@@ -63,19 +71,20 @@ class Prefs {
/** Applies a validated partial update; returns the full prefs or throws. */ /** Applies a validated partial update; returns the full prefs or throws. */
set(partial) { 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 }; const next = { ...this.values };
for (const [key, value] of Object.entries(partial)) { for (const [key, value] of Object.entries(partial)) {
const spec = SCHEMA[key]; const spec = SCHEMA[key];
if (!spec) throw new Error(`prefs: неизвестный ключ ${key}`); if (!spec) throw new Error(`prefs: unknown key ${key}`);
if (!spec.check(value)) throw new Error(`prefs: недопустимое значение ${key}`); if (!spec.check(value)) throw new Error(`prefs: invalid value for ${key}`);
next[key] = value; next[key] = value;
} }
this.values = next; // Persist first: if writing fails, neither the file nor the in-memory values change.
fs.mkdirSync(path.dirname(this.file), { recursive: true }); fs.mkdirSync(path.dirname(this.file), { recursive: true });
const tmp = `${this.file}.tmp`; const tmp = `${this.file}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(next, null, 2)); fs.writeFileSync(tmp, JSON.stringify(next, null, 2));
fs.renameSync(tmp, this.file); fs.renameSync(tmp, this.file);
this.values = next;
return this.get(); return this.get();
} }
} }
+277
View File
@@ -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,
};
+463
View File
@@ -0,0 +1,463 @@
'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,
profileOverride = process.env.TEAMSPEACH_PROFILE_DIR,
}) {
const currentVersion = electronApp.getVersion();
// The NSIS installer restarts the app through Explorer (StdUtils.ExecShellAsUser), which does not pass this
// process's environment on: an app running on a TEAMSPEACH_PROFILE_DIR profile would come back on the
// default profile. Such a run is offered the release page (manual install) instead of an automatic install.
// AppImage relaunch (app.relaunch) keeps the environment and is not affected.
const installBlock = target.kind === 'nsis' && profileOverride ? 'custom-profile' : null;
const autoInstall = target.mode === 'auto' && !installBlock;
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: installBlock ? 'manual' : target.mode,
manualReason: installBlock, // null | 'custom-profile'
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 ${state.mode}${installBlock ? ` (${installBlock})` : ''}`);
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 (!autoInstall || !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' && autoInstall ? 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 (installBlock) return { ok: false, code: installBlock };
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 };
+7
View File
@@ -29,5 +29,12 @@ contextBridge.exposeInMainWorld('teamspeach', {
fetchExternalMedia: (url) => ipcRenderer.invoke('media:external', url), fetchExternalMedia: (url) => ipcRenderer.invoke('media:external', url),
getVideoStatus: () => ipcRenderer.invoke('app:video-status'), getVideoStatus: () => ipcRenderer.invoke('app:video-status'),
relaunch: () => ipcRenderer.invoke('app:relaunch'), 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)), log: (level, message) => ipcRenderer.send('app:log', level, String(message)),
}); });
Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 37 KiB

+175 -128
View File
@@ -1,5 +1,5 @@
<!doctype html> <!doctype html>
<html lang="ru"> <html lang="en">
<head> <head>
<meta charset="utf-8"> <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'"> <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'">
@@ -29,7 +29,6 @@
<symbol id="i-back" viewBox="0 0 24 24"><path d="M14.5 5.5L8 12l6.5 6.5"/></symbol> <symbol id="i-back" viewBox="0 0 24 24"><path d="M14.5 5.5L8 12l6.5 6.5"/></symbol>
<symbol id="i-moon" viewBox="0 0 24 24"><path d="M19.5 14.6A7.8 7.8 0 1 1 9.4 4.5a6.2 6.2 0 0 0 10.1 10.1z"/></symbol> <symbol id="i-moon" viewBox="0 0 24 24"><path d="M19.5 14.6A7.8 7.8 0 1 1 9.4 4.5a6.2 6.2 0 0 0 10.1 10.1z"/></symbol>
<symbol id="i-message" viewBox="0 0 24 24"><path d="M4.5 5.5h15v10.5h-9.5l-5.5 4z"/></symbol> <symbol id="i-message" viewBox="0 0 24 24"><path d="M4.5 5.5h15v10.5h-9.5l-5.5 4z"/></symbol>
<symbol id="i-peach" viewBox="0 0 24 24"><path class="peach-body" d="M12 7.2c-4.6-1.6-8 1.6-8 6 0 4.6 3.6 8.3 8 8.3s8-3.7 8-8.3c0-4.4-3.4-7.6-8-6z"/><path class="peach-crease" d="M12 7.6c-1.8 2.6-2 8.6 0 13.6"/><path class="peach-leaf" d="M12.2 6.8c.2-2.6 2-4.2 5-4.3-.3 2.7-2.1 4.2-5 4.3z"/></symbol>
<symbol id="i-shield" viewBox="0 0 24 24"><path d="M12 3.5l7 2.6v5.4c0 4.3-2.9 7.6-7 9-4.1-1.4-7-4.7-7-9V6.1z"/></symbol> <symbol id="i-shield" viewBox="0 0 24 24"><path d="M12 3.5l7 2.6v5.4c0 4.3-2.9 7.6-7 9-4.1-1.4-7-4.7-7-9V6.1z"/></symbol>
<symbol id="i-record" viewBox="0 0 24 24"><circle cx="12" cy="12" r="6.5"/><circle cx="12" cy="12" r="2.5"/></symbol> <symbol id="i-record" viewBox="0 0 24 24"><circle cx="12" cy="12" r="6.5"/><circle cx="12" cy="12" r="2.5"/></symbol>
<symbol id="i-bookmark" viewBox="0 0 24 24"><path d="M7 4.5h10v15l-5-3.6-5 3.6z"/></symbol> <symbol id="i-bookmark" viewBox="0 0 24 24"><path d="M7 4.5h10v15l-5-3.6-5 3.6z"/></symbol>
@@ -37,87 +36,88 @@
<symbol id="i-palette" viewBox="0 0 24 24"><path d="M12 4a8 8 0 0 0 0 16c1.2 0 1.8-.8 1.8-1.7 0-1.3-1-1.6-1-2.6 0-1 .8-1.7 1.8-1.7H17a3 3 0 0 0 3-3C20 7.3 16.4 4 12 4z"/><circle cx="8" cy="11" r="1"/><circle cx="11" cy="7.8" r="1"/><circle cx="15" cy="8.3" r="1"/></symbol> <symbol id="i-palette" viewBox="0 0 24 24"><path d="M12 4a8 8 0 0 0 0 16c1.2 0 1.8-.8 1.8-1.7 0-1.3-1-1.6-1-2.6 0-1 .8-1.7 1.8-1.7H17a3 3 0 0 0 3-3C20 7.3 16.4 4 12 4z"/><circle cx="8" cy="11" r="1"/><circle cx="11" cy="7.8" r="1"/><circle cx="15" cy="8.3" r="1"/></symbol>
<symbol id="i-keyboard" viewBox="0 0 24 24"><rect x="3" y="6.5" width="18" height="11" rx="2"/><path d="M7 10h.01M10.5 10h.01M14 10h.01M17 10h.01M8 14h8"/></symbol> <symbol id="i-keyboard" viewBox="0 0 24 24"><rect x="3" y="6.5" width="18" height="11" rx="2"/><path d="M7 10h.01M10.5 10h.01M14 10h.01M17 10h.01M8 14h8"/></symbol>
<symbol id="i-info" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M12 11v5.5M12 7.8v.01"/></symbol> <symbol id="i-info" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M12 11v5.5M12 7.8v.01"/></symbol>
<symbol id="i-check" viewBox="0 0 24 24"><path d="M5.5 12.5l4.2 4.2 8.8-9.2"/></symbol>
</svg> </svg>
<div id="boot" class="boot" role="status"> <div id="boot" class="boot" role="status">
<svg class="icon brand-mark" aria-hidden="true"><use href="#i-peach"/></svg> <img class="brand-mark" src="assets/icon.png" width="40" height="40" alt="" aria-hidden="true">
<p id="boot-text">Запуск ядра…</p> <p id="boot-text" data-i18n="ui.starting.core">Starting core…</p>
</div> </div>
<main id="view-fatal" class="fatal" hidden> <main id="view-fatal" class="fatal" hidden>
<div class="fatal-inner"> <div class="fatal-inner">
<svg class="icon brand-mark" aria-hidden="true"><use href="#i-peach"/></svg> <img class="brand-mark" src="assets/icon.png" width="40" height="40" alt="" aria-hidden="true">
<h1 id="fatal-title">Ядро недоступно</h1> <h1 id="fatal-title" data-i18n="ui.core.unavailable">Core unavailable</h1>
<p id="fatal-text"></p> <p id="fatal-text"></p>
<ul id="fatal-list" class="fatal-list"></ul> <ul id="fatal-list" class="fatal-list"></ul>
<div class="fatal-actions"> <div class="fatal-actions">
<button id="fatal-retry" class="btn btn-primary" 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>Импортировать резервную копию…</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">Открыть журналы</button> <button id="fatal-logs" class="btn" type="button" data-i18n="ui.open.logs">Open logs</button>
</div> </div>
</div> </div>
</main> </main>
<main id="view-onboarding" class="onboarding" hidden> <main id="view-onboarding" class="onboarding" hidden>
<form id="onboarding-form" class="onboarding-form" novalidate> <form id="onboarding-form" class="onboarding-form" novalidate>
<svg class="icon brand-mark brand-mark-large" aria-hidden="true"><use href="#i-peach"/></svg> <img class="brand-mark brand-mark-large" src="assets/icon.png" width="56" height="56" alt="" aria-hidden="true">
<h1>Как вас называть?</h1> <h1 data-i18n="ui.what.should.we.call.you">What should we call you?</h1>
<p class="lede">Никнейм видят все на сервере. Его можно сменить позже — ваш постоянный идентификатор (UID) при этом не меняется.</p> <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"> <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"> <input id="onboarding-nick" name="nickname" type="text" autocomplete="off" spellcheck="false" maxlength="30" required aria-describedby="onboarding-hint onboarding-error">
</label> </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-existing" class="hint" hidden></p>
<p id="onboarding-error" class="form-error" role="alert"></p> <p id="onboarding-error" class="form-error" role="alert"></p>
<button id="onboarding-submit" class="btn btn-primary btn-wide" type="submit">Продолжить</button> <button id="onboarding-submit" class="btn btn-primary btn-wide" type="submit" data-i18n="ui.continue">Continue</button>
<p class="hint">TeamsPeach создаст на этом компьютере криптографическую идентичность. Регистрация не нужна.</p> <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">Восстановить из резервной копии…</button> <button id="onboarding-import" class="btn btn-ghost" type="button" data-i18n="ui.restore.from.backup">Restore from backup…</button>
</form> </form>
</main> </main>
<div id="view-app" class="shell" hidden> <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"> <header class="server-head">
<div class="server-title"> <div class="server-title">
<span id="server-name" class="server-name">Нет подключения</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">не подключено</span> <span id="conn-badge" class="conn-badge" data-state="disconnected" data-i18n="ui.not.connected2">not connected</span>
</div> </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> <svg class="icon" aria-hidden="true"><use href="#i-bookmark"/></svg>
</button> </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> <svg class="icon" aria-hidden="true"><use href="#i-logout"/></svg>
</button> </button>
</header> </header>
<div id="room-side" class="room-side"> <div id="room-side" class="room-side">
<section id="servers-panel" class="servers-panel" aria-labelledby="servers-title" hidden> <section id="servers-panel" class="servers-panel" aria-labelledby="servers-title" hidden>
<div class="servers-head"> <div class="servers-head">
<h2 id="servers-title" class="servers-title">Сохранённые серверы</h2> <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>Сохранить текущий</button> <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> </div>
<ul id="servers-list" class="servers-list"></ul> <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> </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> <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> </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"> <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> </button>
<div class="settings-nav-title"><svg class="icon" aria-hidden="true"><use href="#i-sliders"/></svg>Настройки</div> <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">Пользователь</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>Идентичность</button> <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>Серверы</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">Приложение</div> <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>Внешний вид</button> <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>Звук</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>Видео</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>Клавиши</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">Информация</div> <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>Информация</button> <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> </nav>
<footer class="self"> <footer class="self">
<div class="self-id"> <div class="self-id">
@@ -128,13 +128,13 @@
</div> </div>
</div> </div>
<div class="self-actions"> <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> <svg class="icon" aria-hidden="true"><use href="#i-mic"/></svg>
</button> </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> <svg class="icon" aria-hidden="true"><use href="#i-headphones"/></svg>
</button> </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> <svg class="icon" aria-hidden="true"><use href="#i-sliders"/></svg>
</button> </button>
</div> </div>
@@ -144,20 +144,20 @@
<main class="workspace"> <main class="workspace">
<section id="connect-view" class="connect-view" aria-labelledby="connect-title"> <section id="connect-view" class="connect-view" aria-labelledby="connect-title">
<form id="connect-form" class="connect-form" novalidate> <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> <p id="connect-identity" class="lede"></p>
<label class="field"> <label class="field">
<span class="field-label">Адрес сервера</span> <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="адрес или адрес:9987" required> <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>
<label class="field"> <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"> <input id="connect-password" name="password" type="password" autocomplete="off">
</label> </label>
<p id="connect-error" class="form-error" role="alert"></p> <p id="connect-error" class="form-error" role="alert"></p>
<div class="form-actions"> <div class="form-actions">
<button id="connect-submit" class="btn btn-primary" type="submit">Подключиться</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">Сохранить</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> <span id="connect-status" class="form-status" role="status"></span>
</div> </div>
</form> </form>
@@ -171,12 +171,12 @@
</div> </div>
<div class="transmit"> <div class="transmit">
<span id="transmit-hint" class="transmit-hint"></span> <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> </div>
</header> </header>
<p id="session-notice" class="notice" role="status" hidden></p> <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"> <div class="stream-stage">
<video id="stream-video" autoplay playsinline></video> <video id="stream-video" autoplay playsinline></video>
<div id="stream-overlay" class="stream-overlay" role="status"></div> <div id="stream-overlay" class="stream-overlay" role="status"></div>
@@ -187,177 +187,224 @@
<span id="stream-stats" class="stream-stats"></span> <span id="stream-stats" class="stream-stats"></span>
</div> </div>
<div class="stream-controls"> <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> <svg class="icon" aria-hidden="true"><use href="#i-speaker"/></svg>
</button> </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> <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> <svg class="icon" aria-hidden="true"><use href="#i-fullscreen"/></svg>
</button> </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>
</div> </div>
</section> </section>
<section class="chat" aria-label="Чат"> <section class="chat" aria-label="Chat" data-i18n-aria-label="ui.chat">
<div id="chat-tabs" class="chat-tabs" role="tablist" aria-label="Чаты"></div> <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> <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> <form id="chat-form" class="composer" novalidate>
<textarea id="chat-input" rows="1" aria-label="Сообщение" placeholder="Сообщение"></textarea> <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="Отправить" title="Отправить (Enter)"> <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> <svg class="icon" aria-hidden="true"><use href="#i-send"/></svg>
</button> </button>
</form> </form>
</section> </section>
</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-scroll">
<div class="settings-panel" data-panel="identity" hidden> <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"> <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"> <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> <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> </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> <p id="security-level" class="hint"></p>
<div class="card-divider"></div> <div class="card-divider"></div>
<div class="form-actions"> <div class="form-actions">
<button id="identity-export" 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">Импортировать из файла…</button> <button id="identity-import" class="btn" type="button" data-i18n="ui.import.from.file">Import from file…</button>
</div> </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> <p id="identity-status" class="form-status" role="status"></p>
</section> </section>
<section class="card" aria-labelledby="card-details"> <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> <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"> <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> </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> <p id="rename-status" class="form-status" role="status"></p>
</section> </section>
</div> </div>
<div class="settings-panel" data-panel="servers" hidden> <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"> <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> <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>
<section class="card" aria-labelledby="card-add-server"> <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> <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" 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">Адрес</span><input id="server-add-address" type="text" maxlength="255" autocomplete="off" spellcheck="false" placeholder="адрес или адрес:9987"></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">Добавить</button><span id="server-add-status" class="form-status" role="status"></span></div> <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> </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> </section>
</div> </div>
<div class="settings-panel" data-panel="appearance" hidden> <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"> <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"> <fieldset class="fieldset">
<legend class="visually-hidden">Тема оформления</legend> <legend class="visually-hidden" data-i18n="ui.color.theme">Color theme</legend>
<label class="choice"><input type="radio" name="theme" value="system"> Как в системе</label> <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"> Тёмная</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"> Светлая</label> <label class="choice"><input type="radio" name="theme" value="light"> <span data-i18n="ui.light">Light</span></label>
</fieldset> </fieldset>
</section> </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>
<div class="settings-panel" data-panel="audio" hidden> <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"> <section class="card" aria-labelledby="card-devices">
<h2 id="card-devices" class="card-title">Устройства</h2> <h2 id="card-devices" class="card-title" data-i18n="ui.devices">Devices</h2>
<label class="field"><span class="field-label">Микрофон</span><select id="input-device"></select></label> <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-row">
<div class="meter" aria-hidden="true"><div id="mic-meter" class="meter-fill"></div></div> <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> </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>
<section class="card" aria-labelledby="card-volume"> <section class="card" aria-labelledby="card-volume">
<h2 id="card-volume" class="card-title">Громкость</h2> <h2 id="card-volume" class="card-title" data-i18n="ui.volume">Volume</h2>
<label class="field"><span class="field-label">Громкость голосов <output id="voice-volume-value" for="voice-volume"></output></span> <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> <input id="voice-volume" class="range" type="range" min="0" max="200" step="5"></label>
</section> </section>
<section class="card" aria-labelledby="card-processing"> <section class="card" aria-labelledby="card-transmit">
<h2 id="card-processing" class="card-title">Обработка микрофона</h2> <h2 id="card-transmit" class="card-title" data-i18n="ui.voice.transmission">Voice transmission</h2>
<fieldset class="fieldset"> <fieldset class="fieldset">
<legend class="visually-hidden">Обработка микрофона</legend> <legend class="visually-hidden" data-i18n="ui.transmission.mode">Transmission mode</legend>
<label class="choice"><input id="opt-ns" type="checkbox"> Шумоподавление</label> <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 id="opt-ec" type="checkbox"> Эхоподавление</label> <label class="choice"><input type="radio" name="transmit" value="vad"> <span data-i18n="transmit.mode.vad">Voice activation</span></label>
<label class="choice"><input id="opt-agc" type="checkbox"> Автоматическая громкость</label> <label class="choice"><input type="radio" name="transmit" value="open"> <span data-i18n="transmit.mode.open">Open microphone (continuous transmission)</span></label>
</fieldset>
<div id="vad-options" hidden>
<label class="field"><span class="field-label" data-i18n="transmit.vad.sensitivity">Voice activation sensitivity</span>
<select id="vad-sensitivity">
<option value="high" data-i18n="transmit.vad.high">High: quieter speech</option>
<option value="normal" data-i18n="transmit.vad.normal">Normal</option>
<option value="low" data-i18n="transmit.vad.low">Low: noisier surroundings</option>
</select>
</label>
<p class="hint" data-i18n="transmit.vad.hint">Voice detection runs locally on this computer, not in the cloud. It detects speech rather than just sound level; audio is only held briefly in memory to decide, and nothing is saved as a recording or transcribed into words. Transmission starts when speech is detected and ends about 0.4 s after the last detected speech. Noise suppression can help, but a TV, other voices, or noise may still trigger transmission or keep it open.</p>
</div>
<p class="hint" data-i18n="transmit.mic.test.hint">The microphone test shows the input level, not whether speech is detected. The test itself never sends audio. In a channel, the selected transmission mode and mute controls determine when others hear you.</p>
</section>
<section class="card" aria-labelledby="card-processing">
<h2 id="card-processing" class="card-title" data-i18n="ui.microphone.processing">Microphone processing</h2>
<fieldset class="fieldset">
<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> </fieldset>
</section> </section>
</div> </div>
<div class="settings-panel" data-panel="video" hidden> <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"> <section class="card" aria-labelledby="card-decode">
<h2 id="card-decode" class="card-title">Аппаратное ускорение</h2> <h2 id="card-decode" class="card-title" data-i18n="ui.hardware.acceleration">Hardware acceleration</h2>
<label class="choice"><input id="opt-hwdec" type="checkbox"> Разрешить аппаратное декодирование видео</label> <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">Движок может использовать видеокарту для декодирования трансляций. Применяется после перезапуска.</p> <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> <div id="hwdec-restart" class="form-actions" hidden>
<span class="form-status">Изменение вступит в силу после перезапуска TeamsPeach.</span> <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">Перезапустить сейчас</button> <button id="hwdec-relaunch" class="btn btn-small" type="button" data-i18n="ui.restart.now">Restart now</button>
</div> </div>
<div class="card-divider"></div> <div class="card-divider"></div>
<div class="card-row"> <div class="card-row">
<span class="row-name">Бэкенд декодирования</span> <span class="row-name" data-i18n="ui.decoding.backend">Decoding backend</span>
<span class="row-value">Автоматически (выбирает Chromium)</span> <span class="row-value" data-i18n="ui.automatic.chosen.by.chromium">Automatic (chosen by Chromium)</span>
</div> </div>
<details class="card-details"> <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"> <dl class="diag-list">
<dt>Политика</dt><dd id="hwdec-status"></dd> <dt data-i18n="ui.policy">Policy</dt><dd id="hwdec-status"></dd>
<dt>Текущий приём</dt><dd id="decoder-last"></dd> <dt data-i18n="ui.current.reception">Current reception</dt><dd id="decoder-last"></dd>
</dl> </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> <ul id="codec-list" class="codec-list"></ul>
<h3 class="details-title">Недоступные настройки</h3> <h3 class="details-title" data-i18n="ui.unavailable.settings">Unavailable settings</h3>
<p class="hint">Переключателя Cisco OpenH264 и ручного выбора аппаратных бэкендов (NVENC, AMF, QSV и др.), как в TeamSpeak 6, здесь нет: TeamsPeach принимает видео через WebRTC движка Chromium, у которого нет API выбора декодера. H.264 Chromium декодирует через FFmpeg — OpenH264 в нём служит только кодировщиком, а кодирование (отправка своего экрана) в TeamsPeach не реализовано.</p> <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> </details>
</section> </section>
</div> </div>
<div class="settings-panel" data-panel="keys" hidden> <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"> <section class="card" aria-labelledby="card-ptt">
<h2 id="card-transmit" class="card-title">Передача голоса</h2> <h2 id="card-ptt" class="card-title" data-i18n="ui.push.to.talk">Push to talk</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>
</fieldset>
<div class="card-divider"></div>
<div class="ptt-row"> <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> <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> </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> </section>
</div> </div>
<div class="settings-panel" data-panel="about" hidden> <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"> <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> <dl id="diag-list" class="diag-list"></dl>
<div class="card-divider"></div> <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> </section>
</div> </div>
</div> </div>
+95 -57
View File
@@ -1,3 +1,4 @@
import { t, setLanguage, onLanguageChange } from './i18n.js';
// TeamsPeach renderer entry: core lifecycle, onboarding, connection, self controls and view routing. // TeamsPeach renderer entry: core lifecycle, onboarding, connection, self controls and view routing.
import { $, h, setIcon, setText } from './dom.js'; import { $, h, setIcon, setText } from './dom.js';
import { S, emit, isConnected, ownChannel } from './state.js'; import { S, emit, isConnected, ownChannel } from './state.js';
@@ -11,6 +12,8 @@ import * as voice from './voice.js';
import * as settings from './settings.js'; import * as settings from './settings.js';
import { serverBannerUrl, clearMedia } from './media.js'; import { serverBannerUrl, clearMedia } from './media.js';
import * as servers from './servers.js'; import * as servers from './servers.js';
import { initDeviceMenus } from './device-menu.js';
import { initUpdates } from './updates-ui.js';
let hostBannerKey = null; let hostBannerKey = null;
@@ -27,7 +30,7 @@ function renderHostBanner() {
serverBannerUrl(server).then((url) => { serverBannerUrl(server).then((url) => {
if (!url || hostBannerKey !== key) return; if (!url || hostBannerKey !== key) return;
img.src = url; 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; img.hidden = false;
}); });
} }
@@ -46,9 +49,11 @@ function showView(id) {
async function savePrefs(partial) { async function savePrefs(partial) {
const r = await tp.setPrefs(partial); const r = await tp.setPrefs(partial);
if (r && r.ok) S.prefs = r.prefs; 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');
renderSessionHead(); if (!Object.hasOwn(partial, 'language')) {
servers.renderServers(); renderSessionHead();
servers.renderServers();
}
return S.prefs; return S.prefs;
} }
@@ -58,29 +63,42 @@ function onCoreStatus(status) {
S.core = status; S.core = status;
switch (status.status) { switch (status.status) {
case 'starting': case 'starting':
setText($('#boot-text'), 'Запуск ядра…'); setText($('#boot-text'), () => t('ui.starting.core'));
showView('#boot'); showView('#boot');
break; break;
case 'stopped': case 'stopped':
setText($('#boot-text'), 'Перезапуск ядра…'); voice.forgetCoreTransmitMode();
setText($('#boot-text'), () => t('ui.restarting.core'));
showView('#boot'); showView('#boot');
resetConnection(null); resetConnection(null);
break; break;
case 'ready': case 'ready':
// A (re)started core transmits directly until told otherwise: apply the chosen mode first.
voice.forgetCoreTransmitMode();
voice.applyTransmitMode();
loadProfile(); loadProfile();
break; break;
case 'missing': 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; break;
default: default:
voice.forgetCoreTransmitMode();
resetConnection(null); 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 } = {}) { function showFatal(title, text, list, { allowImport = false } = {}) {
setText($('#fatal-title'), title); setText($('#fatal-title'), () => title);
setText($('#fatal-text'), text); setText($('#fatal-text'), () => text);
$('#fatal-list').replaceChildren(...list.map((item) => h('li', { text: item }))); $('#fatal-list').replaceChildren(...list.map((item) => h('li', { text: item })));
$('#fatal-import').hidden = !allowImport; $('#fatal-import').hidden = !allowImport;
$('#fatal-retry').hidden = S.core.status === 'missing'; $('#fatal-retry').hidden = S.core.status === 'missing';
@@ -92,9 +110,9 @@ async function loadProfile() {
S.profile = await call('profile_get'); S.profile = await call('profile_get');
} catch (err) { } catch (err) {
if (err.code === 'identity_corrupt' || err.code === 'profile_corrupt') { 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 { } else {
showFatal('Не удалось прочитать профиль', errorText(err), []); showFatal(t('ui.could.not.read.profile'), errorText(err), []);
} }
return; return;
} }
@@ -107,7 +125,7 @@ async function loadProfile() {
function showOnboarding() { function showOnboarding() {
const existing = $('#onboarding-existing'); const existing = $('#onboarding-existing');
existing.hidden = !S.profile.exists; 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'); showView('#view-onboarding');
$('#onboarding-nick').focus(); $('#onboarding-nick').focus();
} }
@@ -120,24 +138,24 @@ async function submitOnboarding(e) {
const len = [...nickname].length; const len = [...nickname].length;
if (len < 3 || len > 30) { if (len < 3 || len > 30) {
input.setAttribute('aria-invalid', 'true'); input.setAttribute('aria-invalid', 'true');
setText(error, 'Никнейм должен содержать от 3 до 30 символов.'); setText(error, () => t('ui.nickname.must.contain.3.30.characters'));
input.focus(); input.focus();
return; return;
} }
input.removeAttribute('aria-invalid'); input.removeAttribute('aria-invalid');
setText(error, ''); setText(error, () => '');
const submit = $('#onboarding-submit'); const submit = $('#onboarding-submit');
submit.disabled = true; submit.disabled = true;
setText(submit, 'Создаём идентичность…'); setText(submit, () => t('ui.creating.identity'));
try { try {
S.profile = S.profile.exists ? await call('rename', { nickname }) : await call('profile_create', { nickname }); S.profile = S.profile.exists ? await call('rename', { nickname }) : await call('profile_create', { nickname });
showApp(); showApp();
toast(`Профиль создан. Ваш UID: ${S.profile.uid}`); toast(() => t('message.profile.created.your.uid.p0', { p0: S.profile.uid }));
} catch (err) { } catch (err) {
setText(error, errorText(err)); setText(error, () => errorText(err));
} finally { } finally {
submit.disabled = false; submit.disabled = false;
setText(submit, 'Продолжить'); setText(submit, () => t('ui.continue'));
} }
} }
@@ -164,9 +182,9 @@ function renderConnection() {
const state = S.conn.state; const state = S.conn.state;
const badge = $('#conn-badge'); const badge = $('#conn-badge');
badge.dataset.state = state; badge.dataset.state = state;
const labels = { connecting: 'подключение…', connected: 'подключено', disconnecting: 'отключение…', disconnected: 'не подключено' }; const labels = { connecting: 'ui.connecting', connected: 'ui.connected', disconnecting: 'ui.disconnecting', disconnected: 'ui.not.connected2' };
setText(badge, labels[state] ?? state); 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 : 'Нет подключения'); 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'; $('#btn-disconnect').hidden = state === 'disconnected';
const inSettings = S.view === 'settings'; const inSettings = S.view === 'settings';
@@ -179,50 +197,50 @@ function renderConnection() {
const busy = state === 'connecting' || state === 'disconnecting'; const busy = state === 'connecting' || state === 'disconnecting';
$('#connect-submit').disabled = busy; $('#connect-submit').disabled = busy;
setText($('#connect-status'), state === 'connecting' ? 'Подключение…' : ''); setText($('#connect-status'), () => state === 'connecting' ? t('ui.connecting2') : '');
setText($('#connect-identity'), S.profile ? `Вы войдёте как ${S.profile.nickname} · UID ${shortUid(S.profile.uid)}` : ''); 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; if (!$('#connect-address').value && S.prefs.lastAddress) $('#connect-address').value = S.prefs.lastAddress;
} }
function renderSelf() { function renderSelf() {
const p = S.profile; const p = S.profile;
if (!p) return; if (!p) return;
setText($('#self-nick'), p.nickname ?? ''); setText($('#self-nick'), () => p.nickname ?? '');
const ch = ownChannel(); 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-sub').title = `UID ${p.uid}`;
$('#self-dot').dataset.talking = String(Boolean(S.audio.transmitting)); $('#self-dot').dataset.talking = String(Boolean(S.audio.transmitting));
const mute = $('#btn-mute'); const mute = $('#btn-mute');
mute.setAttribute('aria-pressed', String(S.audio.input_muted)); mute.setAttribute('aria-pressed', String(S.audio.input_muted));
setIcon(mute.firstElementChild, S.audio.input_muted ? 'mic-off' : 'mic'); setIcon(mute.firstElementChild, S.audio.input_muted ? 'mic-off' : 'mic');
mute.title = 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 ? 'Микрофон выключен' : 'Микрофон включён'); mute.setAttribute('aria-label', S.audio.input_muted ? t('ui.microphone.muted') : t('ui.microphone.unmuted'));
const deafen = $('#btn-deafen'); const deafen = $('#btn-deafen');
deafen.setAttribute('aria-pressed', String(S.audio.output_muted)); deafen.setAttribute('aria-pressed', String(S.audio.output_muted));
setIcon(deafen.firstElementChild, S.audio.output_muted ? 'headphones-off' : 'headphones'); setIcon(deafen.firstElementChild, S.audio.output_muted ? 'headphones-off' : 'headphones');
deafen.title = 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 ? 'Звук выключен' : 'Звук включён'); deafen.setAttribute('aria-label', S.audio.output_muted ? t('ui.audio.muted') : t('ui.audio.unmuted'));
} }
function renderSessionHead() { function renderSessionHead() {
if (!S.prefs) return; if (!S.prefs) return;
const ch = ownChannel(); const ch = ownChannel();
setText($('#channel-title'), ch ? ch.name : ''); setText($('#channel-title'), () => ch ? ch.name : '');
setText($('#channel-topic'), ch ? stripBBCode(ch.topic) : ''); setText($('#channel-topic'), () => ch ? stripBBCode(ch.topic) : '');
const ptt = S.prefs.transmitMode === 'ptt'; const ptt = S.prefs.transmitMode === 'ptt';
$('#btn-ptt').hidden = !ptt; $('#btn-ptt').hidden = !ptt;
setText($('#transmit-hint'), voice.transmitHint()); setText($('#transmit-hint'), () => voice.transmitHint());
const notice = $('#session-notice'); const notice = $('#session-notice');
const codec = voice.channelCodecProblem(); const codec = voice.channelCodecProblem();
let text = ''; let text = '';
if (codec) text = `Канал использует устаревший кодек (${codec}). TeamsPeach передаёт и принимает только Opus — говорить здесь не получится.`; if (codec) text = t('message.this.channel.uses.a.legacy.codec', { p0: codec });
else if (S.audio.output_muted) text = 'Звук выключен: вы не слышите других и не передаёте голос.'; else if (S.audio.output_muted) text = t('ui.audio.is.muted.you.cannot.hear.others');
else if (S.audio.input_muted) text = 'Микрофон выключен.'; else if (S.audio.input_muted) text = t('ui.microphone.is.muted');
notice.hidden = !text; notice.hidden = !text;
setText(notice, text); setText(notice, () => text);
} }
// ---------- connection ---------- // ---------- connection ----------
@@ -238,14 +256,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. * session is closed cleanly first, so there is never more than one connection.
*/ */
async function connectTo(address, { password = '', switching = false } = {}) { async function connectTo(address, { password = '', switching = false } = {}) {
const error = $('#connect-error'); const error = $('#connect-error');
setText(error, ''); setText(error, () => '');
if (!address) { if (!address) {
setText(error, 'Укажите адрес сервера.'); setText(error, () => t('ui.enter.a.server.address'));
$('#connect-address').focus(); $('#connect-address').focus();
return; return;
} }
@@ -256,7 +274,7 @@ async function connectTo(address, { password = '', switching = false } = {}) {
const deadline = Date.now() + 10000; const deadline = Date.now() + 10000;
while (S.conn.state !== 'disconnected' && Date.now() < deadline) await new Promise((r) => setTimeout(r, 100)); while (S.conn.state !== 'disconnected' && Date.now() < deadline) await new Promise((r) => setTimeout(r, 100));
if (S.conn.state !== 'disconnected') { if (S.conn.state !== 'disconnected') {
toast('Не удалось отключиться от текущего сервера', 'error'); toast(() => t('ui.could.not.disconnect.from.the.current.server'), 'error');
return; return;
} }
} }
@@ -271,7 +289,7 @@ async function connectTo(address, { password = '', switching = false } = {}) {
$('#connect-password').value = ''; $('#connect-password').value = '';
} catch (err) { } catch (err) {
if (err.code !== 'already_connected') { 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 }; if (S.conn.state === 'connecting') S.conn = { state: 'disconnected', address, reason: null };
renderConnection(); renderConnection();
renderTree(); renderTree();
@@ -284,7 +302,7 @@ async function disconnect() {
try { try {
await call('disconnect', {}); await call('disconnect', {});
} catch (err) { } 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');
} }
} }
@@ -303,9 +321,9 @@ function resetConnection(reason) {
voice.setPtt(false); voice.setPtt(false);
voice.syncCapture(); voice.syncCapture();
if (wasConnected) { 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) { function onStateEvent(evt) {
@@ -314,9 +332,9 @@ function onStateEvent(evt) {
resetConnection(evt.reason ?? null); resetConnection(evt.reason ?? null);
} else { } else {
S.conn = { state: evt.state, address: evt.address ?? S.conn.address, reason: null }; 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') { if (evt.state === 'connected') {
setText($('#connect-error'), ''); setText($('#connect-error'), () => '');
voice.syncCapture(); voice.syncCapture();
} }
} }
@@ -331,14 +349,14 @@ function onSnapshot(snap) {
for (const id of Array.from(S.talking)) if (!present.has(id)) S.talking.delete(id); for (const id of Array.from(S.talking)) if (!present.has(id)) S.talking.delete(id);
if (!welcomeShown) { if (!welcomeShown) {
welcomeShown = true; 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(); 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) { if (snap.own_channel_id !== lastOwnChannel) {
lastOwnChannel = snap.own_channel_id; lastOwnChannel = snap.own_channel_id;
const ch = ownChannel(); 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(); watch.onSnapshot();
renderHostBanner(); renderHostBanner();
@@ -360,7 +378,7 @@ function onAsyncError(error) {
renderSessionHead(); renderSessionHead();
return; return;
} }
toast(errorText(error), 'error'); toast(() => errorText(error), 'error');
} }
function onCoreEvent(evt) { function onCoreEvent(evt) {
@@ -373,7 +391,10 @@ function onCoreEvent(evt) {
break; break;
case 'audio_state': { case 'audio_state': {
const wasDeaf = S.audio.output_muted; const wasDeaf = S.audio.output_muted;
const wasTransmitting = S.audio.transmitting;
S.audio = { input_muted: Boolean(evt.input_muted), output_muted: Boolean(evt.output_muted), transmitting: Boolean(evt.transmitting) }; S.audio = { input_muted: Boolean(evt.input_muted), output_muted: Boolean(evt.output_muted), transmitting: Boolean(evt.transmitting) };
// Core-side confirmation that voice is going out (TEAMSPEACH_LOG=debug only).
if (S.audio.transmitting !== wasTransmitting) log('debug', `voice: core transmitting=${S.audio.transmitting}`);
if (S.audio.output_muted && !wasDeaf) voice.onOutputMuted(true); if (S.audio.output_muted && !wasDeaf) voice.onOutputMuted(true);
watch.applyVolume(); watch.applyVolume();
renderSelf(); renderSelf();
@@ -419,7 +440,7 @@ async function toggleAudio(key) {
renderSelf(); renderSelf();
renderSessionHead(); renderSessionHead();
} catch (err) { } catch (err) {
toast(errorText(err), 'error'); toast(() => errorText(err), 'error');
} }
} }
@@ -451,7 +472,7 @@ Object.defineProperty(window, 'teamspeachDiagnostics', {
clients: S.snap ? S.snap.clients.map((c) => ({ id: c.id, nickname: c.nickname, channel: c.channel_id, type: c.client_type, inputMuted: c.input_muted })) : [], clients: S.snap ? S.snap.clients.map((c) => ({ id: c.id, nickname: c.nickname, channel: c.channel_id, type: c.client_type, inputMuted: c.input_muted })) : [],
talking: Array.from(S.talking), talking: Array.from(S.talking),
audio: { ...S.audio }, audio: { ...S.audio },
voice: { ...voice.voiceStats, sending: voice.isSending() }, voice: { ...voice.voiceStats, sending: voice.isSending(), capturing: voice.isCapturing(), coreMode: voice.confirmedTransmitMode() },
streams: Array.from(watch.directory.streams.values()).map((s) => ({ id: s.id, clientId: s.clientId, name: s.name })), streams: Array.from(watch.directory.streams.values()).map((s) => ({ id: s.id, clientId: s.clientId, name: s.name })),
watch: { ...watch.watchStats }, watch: { ...watch.watchStats },
videoCodecs: settings.videoCodecs(), videoCodecs: settings.videoCodecs(),
@@ -464,6 +485,7 @@ Object.defineProperty(window, 'teamspeachDiagnostics', {
async function boot() { async function boot() {
S.prefs = await tp.getPrefs(); S.prefs = await tp.getPrefs();
setLanguage(S.prefs.language);
$('#stream-volume').value = String(S.prefs.streamVolume); $('#stream-volume').value = String(S.prefs.streamVolume);
initTree({ initTree({
@@ -475,8 +497,12 @@ async function boot() {
}); });
chat.initChat(); chat.initChat();
servers.initServers({ savePrefs, connectTo }); servers.initServers({ savePrefs, connectTo });
initDeviceMenus({ openAudioSettings: () => openSettings('audio') });
initUpdates();
watch.initWatch({ onChange: () => renderTree(), savePrefs }); watch.initWatch({ onChange: () => renderTree(), savePrefs });
voice.initVoice({ voice.initVoice({
savePrefs,
onOutputChanged: () => watch.applySink(),
onPtt: () => renderSessionHead(), onPtt: () => renderSessionHead(),
onTransmitChanged: () => {}, onTransmitChanged: () => {},
}); });
@@ -491,12 +517,24 @@ async function boot() {
renderTree(); renderTree();
}, },
}); });
onLanguageChange(() => {
renderSelf();
renderSessionHead();
renderTree();
chat.renderTabs();
const chatLog = $('#chat-log');
const scrollTop = chatLog.scrollTop;
chat.renderLog();
chatLog.scrollTop = scrollTop;
const banner = $('#host-banner');
if (!banner.hidden) banner.alt = S.snap?.server?.hostbanner_url ? t('message.server.banner.p0', { p0: S.snap.server.hostbanner_url }) : t('ui.server.banner');
});
$('#onboarding-form').addEventListener('submit', submitOnboarding); $('#onboarding-form').addEventListener('submit', submitOnboarding);
$('#onboarding-import').addEventListener('click', async () => { $('#onboarding-import').addEventListener('click', async () => {
const r = await tp.importIdentity(); const r = await tp.importIdentity();
if (r.ok) toast(`Идентичность восстановлена. UID ${r.uid}`); if (r.ok) toast(() => t('message.identity.restored.uid.p0', { p0: r.uid }));
else if (!r.canceled) setText($('#onboarding-error'), `Восстановление не удалось: ${errorText(r.error)}`); else if (!r.canceled) setText($('#onboarding-error'), () => t('message.restore.failed.p0', { p0: errorText(r.error) }));
}); });
$('#connect-form').addEventListener('submit', submitConnect); $('#connect-form').addEventListener('submit', submitConnect);
$('#btn-disconnect').addEventListener('click', disconnect); $('#btn-disconnect').addEventListener('click', disconnect);
@@ -506,7 +544,7 @@ async function boot() {
$('#fatal-retry').addEventListener('click', () => tp.restartCore()); $('#fatal-retry').addEventListener('click', () => tp.restartCore());
$('#fatal-import').addEventListener('click', async () => { $('#fatal-import').addEventListener('click', async () => {
const r = await tp.importIdentity(); 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()); $('#fatal-logs').addEventListener('click', () => tp.openLogs());
@@ -518,5 +556,5 @@ async function boot() {
boot().catch((err) => { boot().catch((err) => {
log('error', `boot failed: ${err.stack || err.message}`); log('error', `boot failed: ${err.stack || err.message}`);
showFatal('Ошибка запуска интерфейса', String(err.message || err), []); showFatal(t('ui.interface.startup.failed'), String(err.message || err), []);
}); });
+37
View File
@@ -0,0 +1,37 @@
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
// permission, returns one anonymous entry per kind (empty deviceId and label). Aliases are not offered as
// separate choices; the system-default option names the device the alias currently points to.
const ALIASES = new Set(['default', 'communications']);
/** Strips Chromium's localized "<Default> - " prefix from the alias label to get the device name. */
function aliasTarget(label) {
const m = /^[^-]+ - (.+)$/.exec(label || '');
return m ? m[1] : '';
}
/**
* @param {{deviceId:string,label:string}[]} list entries of one kind
* @param {string} selected saved deviceId ('' = system default)
* @returns {{options:{value:string,label:string}[], physical:number, redacted:boolean}}
*/
export function buildDeviceOptions(list, selected) {
const defaultEntry = list.find((d) => d.deviceId === 'default');
const defaultName = aliasTarget(defaultEntry?.label);
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 || t('message.unnamed.device.p0', { p0: d.deviceId.slice(0, 8) }) });
}
if (selected && !options.some((o) => o.value === selected)) {
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);
return { options, physical, redacted };
}
+83 -27
View File
@@ -10,6 +10,8 @@ export class AudioEngine {
this.playback = null; this.playback = null;
this.voiceGain = null; this.voiceGain = null;
this.capture = 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.ready = null;
this.stats = { framesOut: 0 }; this.stats = { framesOut: 0 };
this.statsWaiters = []; this.statsWaiters = [];
@@ -48,7 +50,7 @@ export class AudioEngine {
async setOutputDevice(deviceId) { async setOutputDevice(deviceId) {
await this.init(); 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 || ''); await this.ctx.setSinkId(deviceId || '');
} }
@@ -76,9 +78,33 @@ export class AudioEngine {
return this.capture !== null; 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 }) { 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(); await this.init();
this.stopCapture(); if (gen !== this.captureGen) return null;
const audio = { const audio = {
channelCount: 1, channelCount: 1,
echoCancellation, echoCancellation,
@@ -90,45 +116,75 @@ export class AudioEngine {
try { try {
stream = await navigator.mediaDevices.getUserMedia({ audio, video: false }); stream = await navigator.mediaDevices.getUserMedia({ audio, video: false });
} catch (err) { } catch (err) {
// A saved microphone that is gone is an error: never open a different microphone in its place.
if (deviceId && err && err.name === 'OverconstrainedError') { if (deviceId && err && err.name === 'OverconstrainedError') {
delete audio.deviceId; throw Object.assign(new Error('Selected microphone is not available'), { name: 'OverconstrainedError', code: 'device_unavailable' });
stream = await navigator.mediaDevices.getUserMedia({ audio, video: false });
this.onError({ code: 'device_fallback', message: 'Выбранный микрофон недоступен, используется микрофон по умолчанию' });
} else {
throw err;
} }
throw err;
}
if (gen !== this.captureGen) {
for (const t of stream.getTracks()) t.stop();
return null;
}
let source = null;
let node = null;
let sink = null;
try {
const ctx = this.ctx;
source = ctx.createMediaStreamSource(stream);
node = new AudioWorkletNode(ctx, 'tp-capture', {
numberOfInputs: 1,
numberOfOutputs: 1,
outputChannelCount: [1],
channelCount: 1,
channelCountMode: 'explicit',
channelInterpretation: 'speakers',
});
sink = ctx.createGain();
sink.gain.value = 0;
node.port.onmessage = (event) => {
const data = event.data;
if (data.type === 'frame') this.onFrame(data.pcm, data.rms, data.peak);
else if (data.type === 'error') this.onError({ code: 'capture', message: data.message });
};
source.connect(node).connect(sink).connect(ctx.destination);
} catch (err) {
// The microphone is already open: release it and whatever was built before rethrowing.
if (node) node.port.onmessage = null;
for (const part of [source, node, sink]) {
try {
part?.disconnect();
} catch {
// never connected
}
}
for (const t of stream.getTracks()) t.stop();
throw err;
} }
const ctx = this.ctx;
const source = ctx.createMediaStreamSource(stream);
const node = new AudioWorkletNode(ctx, 'tp-capture', {
numberOfInputs: 1,
numberOfOutputs: 1,
outputChannelCount: [1],
channelCount: 1,
channelCountMode: 'explicit',
channelInterpretation: 'speakers',
});
const sink = ctx.createGain();
sink.gain.value = 0;
node.port.onmessage = (event) => {
const data = event.data;
if (data.type === 'frame') this.onFrame(data.pcm, data.rms, data.peak);
else if (data.type === 'error') this.onError({ code: 'capture', message: data.message });
};
source.connect(node).connect(sink).connect(ctx.destination);
const track = stream.getAudioTracks()[0]; const track = stream.getAudioTracks()[0];
track.addEventListener('ended', () => { track.addEventListener('ended', () => {
if (this.capture && this.capture.stream === stream) { if (this.capture && this.capture.stream === stream) {
this.stopCapture(); 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 : '' }; this.capture = { stream, source, node, sink, label: track ? track.label : '' };
this.log('info', `audio: capture started (${track ? track.getSettings().sampleRate : '?'} Hz device)`); // The OS can mute a capture track (privacy switch, exclusive mode); record it for diagnosis.
track.addEventListener('mute', () => this.log('warn', 'audio: capture track muted by the system'));
track.addEventListener('unmute', () => this.log('info', 'audio: capture track unmuted'));
const settings = track ? track.getSettings() : {};
this.log('info', `audio: capture started "${track ? track.label : '?'}" ${settings.sampleRate ?? '?'} Hz, ${settings.channelCount ?? '?'} ch, muted=${track ? track.muted : '?'}, ec=${settings.echoCancellation} ns=${settings.noiseSuppression} agc=${settings.autoGainControl}`);
return this.capture.label; return this.capture.label;
} }
/** Stops the microphone and cancels a pending startCapture(). */
stopCapture() { stopCapture() {
this.captureGen += 1;
this.startingGen = null;
this.releaseCapture();
}
releaseCapture() {
const c = this.capture; const c = this.capture;
if (!c) return; if (!c) return;
this.capture = null; this.capture = null;
+16 -15
View File
@@ -1,3 +1,4 @@
import { t } from './i18n.js';
// Channel, server and private text chat. Message text is rendered as plain text only. // Channel, server and private text chat. Message text is rendered as plain text only.
import { $, h, icon, reconcile, setText, formatTime } from './dom.js'; import { $, h, icon, reconcile, setText, formatTime } from './dom.js';
import { S, isConnected, ownChannel, clientById } from './state.js'; import { S, isConnected, ownChannel, clientById } from './state.js';
@@ -45,10 +46,10 @@ function autosize() {
} }
function tabTitle(chat) { function tabTitle(chat) {
if (chat.kind === 'channel') return ownChannel()?.name ?? 'Канал'; if (chat.kind === 'channel') return ownChannel()?.name ?? t('ui.channel');
if (chat.kind === 'server') return 'Сервер'; if (chat.kind === 'server') return t('ui.server');
const cl = clientById(chat.clientId); 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) { function targetOf(chat) {
@@ -63,11 +64,11 @@ async function send() {
const chat = chats.get(active); const chat = chats.get(active);
if (!chat) return; if (!chat) return;
if (chat.kind === 'client' && !clientById(chat.clientId)) { if (chat.kind === 'client' && !clientById(chat.clientId)) {
toast('Собеседник покинул сервер', 'error'); toast(() => t('ui.this.person.left.the.server'), 'error');
return; return;
} }
if (new TextEncoder().encode(text).length > 8192) { if (new TextEncoder().encode(text).length > 8192) {
toast('Сообщение длиннее 8 КиБ', 'error'); toast(() => t('ui.message.exceeds.8.kib'), 'error');
return; return;
} }
input.disabled = true; input.disabled = true;
@@ -76,7 +77,7 @@ async function send() {
input.value = ''; input.value = '';
autosize(); autosize();
} catch (err) { } catch (err) {
toast(`Сообщение не отправлено: ${errorText(err)}`, 'error'); toast(() => t('message.message.not.sent.p0', { p0: errorText(err) }), 'error');
} finally { } finally {
input.disabled = false; input.disabled = false;
input.focus(); input.focus();
@@ -163,7 +164,7 @@ function createTab(chat) {
tab.addEventListener('click', () => select(chat.key)); tab.addEventListener('click', () => select(chat.key));
const wrap = h('div', { class: 'tab-wrap', role: 'presentation' }, tab); const wrap = h('div', { class: 'tab-wrap', role: 'presentation' }, tab);
if (chat.kind === 'client') { 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)); close.addEventListener('click', () => closePrivate(chat.key));
wrap.appendChild(close); wrap.appendChild(close);
} }
@@ -174,14 +175,14 @@ function updateTab(wrap, chat) {
const tab = wrap.firstElementChild; const tab = wrap.firstElementChild;
const [label, unread] = tab.children; const [label, unread] = tab.children;
const title = tabTitle(chat); const title = tabTitle(chat);
setText(label, chat.kind === 'client' ? `@ ${title}` : title); setText(label, () => chat.kind === 'client' ? `@ ${title}` : title);
const selected = chat.key === active; const selected = chat.key === active;
tab.setAttribute('aria-selected', String(selected)); tab.setAttribute('aria-selected', String(selected));
tab.tabIndex = selected ? 0 : -1; 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; unread.hidden = chat.unread === 0;
setText(unread, chat.unread > 99 ? '99+' : String(chat.unread)); setText(unread, () => chat.unread > 99 ? '99+' : String(chat.unread));
tab.setAttribute('aria-label', `${tab.title}${chat.unread ? `, непрочитанных: ${chat.unread}` : ''}`); tab.setAttribute('aria-label', `${tab.title}${chat.unread ? t('message.unread.p0', { p0: chat.unread }) : ''}`);
} }
function onTabKey(e) { function onTabKey(e) {
@@ -215,9 +216,9 @@ export function renderLog() {
function emptyText(chat) { function emptyText(chat) {
if (!chat) return ''; if (!chat) return '';
if (chat.kind === 'channel') return 'Сообщения в этом канале видят все, кто в нём находится.'; if (chat.kind === 'channel') return t('ui.everyone.in.this.channel.can.see.its');
if (chat.kind === 'server') return 'Сообщения сервера видят все подключённые.'; if (chat.kind === 'server') return t('ui.everyone.connected.to.the.server.can.see');
return 'Личная переписка. Сообщения видит только собеседник.'; return t('ui.private.conversation.only.the.recipient.can.see');
} }
function rowFor(msg, prev) { function rowFor(msg, prev) {
@@ -250,7 +251,7 @@ export function updateComposer() {
input.disabled = !enabled; input.disabled = !enabled;
sendBtn.disabled = !enabled; sendBtn.disabled = !enabled;
const title = chat ? tabTitle(chat) : ''; 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. */ /** Called when the connection ends: private chats keep their history but cannot be answered. */
+156
View File
@@ -0,0 +1,156 @@
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 → 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';
import * as voice from './voice.js';
let open = null; // { menu, anchor, cleanup }
let hooks = { openAudioSettings: () => {} };
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) {
button.setAttribute('aria-haspopup', 'menu');
button.addEventListener('contextmenu', (e) => {
e.preventDefault();
show(button, kind, { x: e.clientX, y: e.clientY });
});
button.addEventListener('keydown', (e) => {
if (e.key === 'ContextMenu' || (e.key === 'F10' && e.shiftKey)) {
e.preventDefault();
show(button, kind, null);
}
});
}
function close({ restoreFocus = true } = {}) {
if (!open) return;
const { menu, anchor, cleanup } = open;
open = null;
cleanup();
menu.remove();
anchor.setAttribute('aria-expanded', 'false');
if (restoreFocus) anchor.focus();
}
let generation = 0;
/**
* The menu element exists from the first moment (with a loading line), so every close path — Escape,
* outside click, window blur, another menu — applies while device enumeration is still pending. The
* enumeration result only fills the menu that is still open for this request; a stale result is dropped.
*/
function show(anchor, kind, point) {
close({ restoreFocus: false });
const gen = ++generation;
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);
document.body.appendChild(menu);
anchor.setAttribute('aria-expanded', 'true');
position(menu, anchor, point);
let focusables = [];
const focusAt = (i) => focusables.length && focusables[(i + focusables.length) % focusables.length].focus();
const onKey = (e) => {
const i = focusables.indexOf(document.activeElement);
if (e.key === 'ArrowDown') { e.preventDefault(); focusAt(i + 1); }
else if (e.key === 'ArrowUp') { e.preventDefault(); focusAt(i - 1); }
else if (e.key === 'Home') { e.preventDefault(); focusAt(0); }
else if (e.key === 'End') { e.preventDefault(); focusAt(focusables.length - 1); }
else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); close(); }
else if (e.key === 'Tab') { close({ restoreFocus: false }); }
};
const onPointer = (e) => {
if (!menu.contains(e.target) && e.target !== anchor) close({ restoreFocus: false });
};
const onDismiss = () => close({ restoreFocus: false });
menu.addEventListener('keydown', onKey);
document.addEventListener('pointerdown', onPointer, true);
window.addEventListener('resize', onDismiss);
window.addEventListener('blur', onDismiss);
open = {
gen,
menu,
anchor,
kind,
point,
cleanup: () => {
document.removeEventListener('pointerdown', onPointer, true);
window.removeEventListener('resize', onDismiss);
window.removeEventListener('blur', onDismiss);
},
};
menu.focus();
voice.deviceChoices().then((choices) => {
if (!open || open.gen !== gen || !choices) return; // closed or replaced meanwhile
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();
});
if (choices.error) {
// Enumeration failed now: show that instead of any earlier list.
body.replaceChildren(h('p', { class: 'menu-note', role: 'alert', text: t('message.could.not.list.devices.p0.p1', { p0: choices.error.name, p1: choices.error.message }) }), h('div', { class: 'menu-sep', role: 'separator' }), settingsItem);
menu.removeAttribute('aria-busy');
position(menu, anchor, point);
focusables = [settingsItem];
if (menu.contains(document.activeElement)) focusAt(0);
return;
}
const data = kind === 'input' ? choices.input : choices.output;
const selected = (kind === 'input' ? S.prefs.inputDeviceId : S.prefs.outputDeviceId) || '';
const items = data.options.map((o) => {
const item = h('button', {
class: 'menu-item',
type: 'button',
role: 'menuitemradio',
'aria-checked': String(o.value === selected),
tabindex: '-1',
}, h('span', { class: 'menu-check', 'aria-hidden': 'true' }, o.value === selected ? icon('check') : null), h('span', { class: 'menu-label', text: o.label }));
item.addEventListener('click', async () => {
close();
if (o.value === selected) return;
if (kind === 'input') await voice.chooseInputDevice(o.value);
else await voice.chooseOutputDevice(o.value);
});
return item;
});
const note = data.redacted || data.physical === 0
? 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');
position(menu, anchor, point);
focusables = [...items, settingsItem];
// Move focus into the list only if it is still inside the menu (the user may have clicked elsewhere).
if (menu.contains(document.activeElement)) focusAt(Math.max(0, items.findIndex((i) => i.getAttribute('aria-checked') === 'true')));
});
}
/** Above the button (the footer sits at the bottom), clamped inside the viewport. */
function position(menu, anchor, point) {
const rect = anchor.getBoundingClientRect();
const mw = menu.offsetWidth;
const mh = menu.offsetHeight;
const margin = 8;
let left = point ? point.x : rect.left;
let top = (point ? point.y : rect.top) - mh - 6;
if (top < margin) top = Math.min(rect.bottom + 6, window.innerHeight - mh - margin);
left = Math.max(margin, Math.min(left, window.innerWidth - mw - margin));
top = Math.max(margin, top);
menu.style.left = `${Math.round(left)}px`;
menu.style.top = `${Math.round(top)}px`;
}
+22 -3
View File
@@ -1,3 +1,4 @@
import { getLanguage, onLanguageChange } from './i18n.js';
// DOM helpers. Server-provided text only ever reaches the page through textContent / attributes. // DOM helpers. Server-provided text only ever reaches the page through textContent / attributes.
export function $(selector, root = document) { export function $(selector, root = document) {
@@ -16,7 +17,7 @@ export function h(tag, props = {}, ...children) {
if (value === undefined || value === null || value === false) continue; if (value === undefined || value === null || value === false) continue;
if (key === 'class') el.className = value; if (key === 'class') el.className = value;
else if (key === 'dataset') Object.assign(el.dataset, 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.startsWith('on') && typeof value === 'function') el.addEventListener(key.slice(2), value);
else if (key in el && typeof value !== 'string') el[key] = value; else if (key in el && typeof value !== 'string') el[key] = value;
else el.setAttribute(key, value === true ? '' : String(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(); for (const el of existing.values()) el.remove();
} }
const liveText = new WeakMap();
export function setText(el, text) { 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; 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) { 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' });
} }
+33
View File
@@ -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
View File
@@ -1,5 +1,6 @@
import { t, onLanguageChange } from './i18n.js';
// Saved servers (name + address only; never passwords): quick access in the sidebar and management // 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 { $, h, icon, setText } from './dom.js';
import { S, isConnected } from './state.js'; import { S, isConnected } from './state.js';
import { toast } from './toast.js'; import { toast } from './toast.js';
@@ -12,6 +13,10 @@ let confirmTimer = null;
export function initServers(h0) { export function initServers(h0) {
hooks = { ...hooks, ...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', () => { $('#btn-servers').addEventListener('click', () => {
panelOpen = !isPanelOpen(); panelOpen = !isPanelOpen();
renderServers(); renderServers();
@@ -21,7 +26,7 @@ export function initServers(h0) {
$('#connect-save').addEventListener('click', () => { $('#connect-save').addEventListener('click', () => {
const address = $('#connect-address').value.trim(); const address = $('#connect-address').value.trim();
if (!address) { if (!address) {
setText($('#connect-error'), 'Укажите адрес сервера, чтобы сохранить его.'); setText($('#connect-error'), () => t('ui.enter.a.server.address.to.save.it'));
return; return;
} }
saveAddress(address, address); saveAddress(address, address);
@@ -31,13 +36,13 @@ export function initServers(h0) {
const name = $('#server-add-name').value.trim(); const name = $('#server-add-name').value.trim();
const address = $('#server-add-address').value.trim(); const address = $('#server-add-address').value.trim();
if (!address) { if (!address) {
setText($('#server-add-status'), 'Укажите адрес.'); setText($('#server-add-status'), () => t('ui.enter.an.address'));
return; return;
} }
if (await saveAddress(name || address, address)) { if (await saveAddress(name || address, address)) {
$('#server-add-name').value = ''; $('#server-add-name').value = '';
$('#server-add-address').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) { async function saveAddress(name, address) {
const trimmed = address.trim(); const trimmed = address.trim();
if (servers().some((s) => sameAddress(s.address, trimmed))) { if (servers().some((s) => sameAddress(s.address, trimmed))) {
toast('Этот адрес уже сохранён'); toast(() => t('ui.this.address.is.already.saved'));
return false; return false;
} }
if (servers().length >= 50) { if (servers().length >= 50) {
toast('Можно сохранить не больше 50 серверов', 'error'); toast(() => t('ui.you.can.save.up.to.50.servers'), 'error');
return false; return false;
} }
const ok = await persist([...servers(), { id: newId(), name: name.trim().slice(0, 64) || trimmed, address: trimmed }]); 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; return ok;
} }
@@ -102,13 +107,13 @@ export function renderServers() {
function quickRow(server) { function quickRow(server) {
const current = connectedTo(server); const current = connectedTo(server);
const busy = S.conn.state === 'connecting' || S.conn.state === 'disconnecting'; 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', { const btn = h('button', {
class: 'server-item', class: 'server-item',
type: 'button', type: 'button',
disabled: current || busy, disabled: current || busy,
'aria-label': `${server.name}, ${server.address}. ${label}`, '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 })); }, 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' })); btn.addEventListener('click', () => hooks.connectTo(server.address, { switching: S.conn.state !== 'disconnected' }));
return h('li', {}, btn); return h('li', {}, btn);
@@ -116,9 +121,9 @@ function quickRow(server) {
function manageRow(server) { function manageRow(server) {
if (editingId === server.id) return editRow(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 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', () => { edit.addEventListener('click', () => {
editingId = server.id; editingId = server.id;
renderServers(); renderServers();
@@ -138,7 +143,7 @@ function manageRow(server) {
} }
confirmDeleteId = null; confirmDeleteId = null;
await persist(servers().filter((s) => s.id !== server.id)); 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 } }, 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 })), 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) { function editRow(server) {
const name = h('input', { type: 'text', maxlength: '64', value: server.name, 'aria-label': 'Название сервера' }); 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': 'Адрес сервера' }); 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' }, 'Отмена'); 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' }, 'Сохранить'), 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', () => { cancel.addEventListener('click', () => {
editingId = null; editingId = null;
renderServers(); renderServers();
@@ -166,11 +171,11 @@ function editRow(server) {
const n = name.value.trim(); const n = name.value.trim();
const a = address.value.trim(); const a = address.value.trim();
if (!n || !a) { if (!n || !a) {
toast('Название и адрес не могут быть пустыми', 'error'); toast(() => t('ui.name.and.address.cannot.be.empty'), 'error');
return; return;
} }
if (servers().some((s) => s.id !== server.id && sameAddress(s.address, a))) { 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; return;
} }
editingId = null; editingId = null;
+73 -54
View File
@@ -1,3 +1,4 @@
import { t, setLanguage, onLanguageChange } from './i18n.js';
// Settings: profile (rename, UID, identity backup), audio devices/transmit mode, diagnostics. // Settings: profile (rename, UID, identity backup), audio devices/transmit mode, diagnostics.
import { $, h, setText } from './dom.js'; import { $, h, setText } from './dom.js';
import { S, isConnected } from './state.js'; import { S, isConnected } from './state.js';
@@ -5,12 +6,28 @@ import { tp, call } from './core.js';
import { errorText, keyLabel } from './text.js'; import { errorText, keyLabel } from './text.js';
import { toast } from './toast.js'; import { toast } from './toast.js';
import * as voice from './voice.js'; import * as voice from './voice.js';
import { applySink, watchStats } from './watch.js'; import { watchStats } from './watch.js';
let hooks = { savePrefs: async () => {}, close: () => {}, onProfile: () => {} }; let hooks = { savePrefs: async () => {}, close: () => {}, onProfile: () => {} };
export function initSettings(h0) { export function initSettings(h0) {
hooks = { ...hooks, ...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()); $('#settings-back').addEventListener('click', () => hooks.close());
for (const host of [$('#settings-view'), $('#settings-nav')]) { for (const host of [$('#settings-view'), $('#settings-nav')]) {
@@ -52,26 +69,26 @@ export function initSettings(h0) {
const len = [...nickname].length; const len = [...nickname].length;
if (len < 3 || len > 30) { if (len < 3 || len > 30) {
input.setAttribute('aria-invalid', 'true'); input.setAttribute('aria-invalid', 'true');
setText(status, 'Никнейм должен содержать от 3 до 30 символов.'); setText(status, () => t('ui.nickname.must.contain.3.30.characters'));
return; return;
} }
if (nickname === S.profile?.nickname) { if (nickname === S.profile?.nickname) {
setText(status, 'Это уже ваш никнейм.'); setText(status, () => t('ui.this.is.already.your.nickname'));
return; return;
} }
input.removeAttribute('aria-invalid'); input.removeAttribute('aria-invalid');
$('#rename-submit').disabled = true; $('#rename-submit').disabled = true;
setText(status, 'Сохраняем…'); setText(status, () => t('ui.saving'));
const uidBefore = S.profile?.uid; const uidBefore = S.profile?.uid;
try { try {
const profile = await call('rename', { nickname }); const profile = await call('rename', { nickname });
hooks.onProfile(profile); 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) { } catch (err) {
if (err.code === 'rename_not_persisted' && err.detail) { 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 { } else {
setText(status, errorText(err)); setText(status, () => errorText(err));
} }
} finally { } finally {
$('#rename-submit').disabled = false; $('#rename-submit').disabled = false;
@@ -79,45 +96,37 @@ export function initSettings(h0) {
}); });
$('#uid-copy').addEventListener('click', async () => { $('#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 () => { $('#identity-export').addEventListener('click', async () => {
const status = $('#identity-status'); const status = $('#identity-status');
const r = await tp.exportIdentity(); const r = await tp.exportIdentity();
if (r.canceled) return; 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 () => { $('#identity-import').addEventListener('click', async () => {
const status = $('#identity-status'); const status = $('#identity-status');
if (S.conn.state !== 'disconnected') { if (S.conn.state !== 'disconnected') {
setText(status, 'Сначала отключитесь от сервера.'); setText(status, () => t('ui.disconnect.from.the.server.first'));
return; return;
} }
const r = await tp.importIdentity(); const r = await tp.importIdentity();
if (r.canceled) return; if (r.canceled) return;
if (r.ok) toast(`Идентичность импортирована. UID ${r.uid}`); status.dataset.state = r.ok ? 'ok' : 'error';
else setText(status, `Импорт не удался: ${errorText(r.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) }));
}); });
$('#input-device').addEventListener('change', async (e) => { // Same selection path as the microphone/headphones context menus (voice.js).
await hooks.savePrefs({ inputDeviceId: e.target.value }); $('#input-device').addEventListener('change', (e) => voice.chooseInputDevice(e.target.value));
await voice.restartCapture(); $('#output-device').addEventListener('change', (e) => voice.chooseOutputDevice(e.target.value));
});
$('#output-device').addEventListener('change', async (e) => {
await hooks.savePrefs({ outputDeviceId: e.target.value });
try {
await voice.setOutputDevice(e.target.value);
} catch (err) {
toast(`Не удалось выбрать устройство вывода: ${err.message}`, 'error');
}
applySink();
});
$('#voice-volume').addEventListener('input', (e) => { $('#voice-volume').addEventListener('input', (e) => {
const v = Number(e.target.value); const v = Number(e.target.value);
voice.setVoiceVolume(v); 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) })); $('#voice-volume').addEventListener('change', (e) => hooks.savePrefs({ voiceVolume: Number(e.target.value) }));
@@ -126,14 +135,21 @@ export function initSettings(h0) {
if (radio.checked) { if (radio.checked) {
await hooks.savePrefs({ transmitMode: radio.value }); await hooks.savePrefs({ transmitMode: radio.value });
renderAudio(); renderAudio();
await voice.applyTransmitMode();
} }
}); });
} }
$('#vad-sensitivity').addEventListener('change', async (e) => {
await hooks.savePrefs({ vadSensitivity: e.target.value });
renderAudio();
await voice.applyTransmitMode();
});
$('#ptt-assign').addEventListener('click', async () => { $('#ptt-assign').addEventListener('click', async () => {
const btn = $('#ptt-assign'); const btn = $('#ptt-assign');
btn.disabled = true; btn.disabled = true;
setText($('#ptt-key'), 'нажмите клавишу…'); setText($('#ptt-key'), () => t('ui.press.a.key'));
const code = await voice.capturePttKey(); const code = await voice.capturePttKey();
btn.disabled = false; btn.disabled = false;
if (code) await hooks.savePrefs({ pttCode: code }); if (code) await hooks.savePrefs({ pttCode: code });
@@ -153,7 +169,7 @@ export function initSettings(h0) {
const btn = $('#mic-test'); const btn = $('#mic-test');
const on = btn.getAttribute('aria-pressed') !== 'true'; const on = btn.getAttribute('aria-pressed') !== 'true';
btn.setAttribute('aria-pressed', String(on)); btn.setAttribute('aria-pressed', String(on));
setText(btn, on ? 'Остановить проверку' : 'Проверить микрофон'); setText(btn, () => on ? t('ui.stop.test') : t('ui.test.microphone'));
await voice.setMicTest(on); await voice.setMicTest(on);
}); });
@@ -171,34 +187,36 @@ export function renderProfile() {
if (!p) return; if (!p) return;
const input = $('#rename-input'); const input = $('#rename-input');
if (document.activeElement !== input) input.value = p.nickname ?? ''; if (document.activeElement !== input) input.value = p.nickname ?? '';
setText($('#uid-value'), p.uid ?? ''); setText($('#uid-value'), () => p.uid ?? '');
setText($('#security-level'), p.security_level !== null && p.security_level !== undefined ? `Уровень безопасности идентичности: ${p.security_level}` : ''); 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').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() { export function renderAudio() {
const prefs = S.prefs; const prefs = S.prefs;
for (const radio of document.querySelectorAll('input[name="transmit"]')) radio.checked = radio.value === prefs.transmitMode; for (const radio of document.querySelectorAll('input[name="transmit"]')) radio.checked = radio.value === prefs.transmitMode;
setText($('#ptt-key'), keyLabel(prefs.pttCode)); $('#vad-options').hidden = prefs.transmitMode !== 'vad';
$('#vad-sensitivity').value = prefs.vadSensitivity;
setText($('#ptt-key'), () => keyLabel(prefs.pttCode));
$('#ptt-assign').disabled = false; $('#ptt-assign').disabled = false;
$('#opt-ns').checked = prefs.noiseSuppression; $('#opt-ns').checked = prefs.noiseSuppression;
$('#opt-ec').checked = prefs.echoCancellation; $('#opt-ec').checked = prefs.echoCancellation;
$('#opt-agc').checked = prefs.autoGainControl; $('#opt-agc').checked = prefs.autoGainControl;
$('#voice-volume').value = String(prefs.voiceVolume); $('#voice-volume').value = String(prefs.voiceVolume);
setText($('#voice-volume-value'), `${prefs.voiceVolume}%`); setText($('#voice-volume-value'), () => `${prefs.voiceVolume}%`);
} }
export async function renderDiagnostics() { export async function renderDiagnostics() {
const info = await tp.getAppInfo(); const info = await tp.getAppInfo();
const rows = [ const rows = [
['TeamsPeach', info.appVersion], ['TeamsPeach', info.appVersion],
['Ядро', info.coreVersion ?? 'не запущено'], [t('ui.core'), info.coreVersion ?? t('ui.not.running')],
['Electron', info.electron], ['Electron', info.electron],
['Chromium', info.chrome], ['Chromium', info.chrome],
['Платформа', `${info.platform} ${info.arch}`], [t('ui.platform'), `${info.platform} ${info.arch}`],
['Исполняемый файл ядра', info.coreBinary ?? '—'], [t('ui.core.executable'), info.coreBinary ?? '—'],
['Каталог данных', info.dataDir], [t('ui.data.folder'), info.dataDir],
]; ];
$('#diag-list').replaceChildren(...rows.flatMap(([k, v]) => [h('dt', { text: k }), h('dd', { text: v })])); $('#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 }))); $('#codec-list').replaceChildren(...videoCodecs().map((line) => h('li', { text: line })));
@@ -208,7 +226,7 @@ const IGNORED = new Set(['video/rtx', 'video/red', 'video/ulpfec', 'video/flexfe
export function videoCodecs() { export function videoCodecs() {
const caps = typeof RTCRtpReceiver.getCapabilities === 'function' ? RTCRtpReceiver.getCapabilities('video') : null; 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}` : ''}`); return caps.codecs.filter((c) => !IGNORED.has(c.mimeType.toLowerCase())).map((c) => `${c.mimeType.replace('video/', '')}${c.sdpFmtpLine ? ` ${c.sdpFmtpLine}` : ''}`);
} }
@@ -242,7 +260,7 @@ export async function close() {
const btn = $('#mic-test'); const btn = $('#mic-test');
if (btn.getAttribute('aria-pressed') === 'true') { if (btn.getAttribute('aria-pressed') === 'true') {
btn.setAttribute('aria-pressed', 'false'); btn.setAttribute('aria-pressed', 'false');
setText(btn, 'Проверить микрофон'); setText(btn, () => t('ui.test.microphone'));
await voice.setMicTest(false); await voice.setMicTest(false);
} }
} }
@@ -250,15 +268,15 @@ export async function close() {
// app.getGPUFeatureStatus().video_decode describes what the engine is allowed/able to use, // 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. // not which decoder is decoding right now; that comes only from a live RTCPeerConnection.
const GPU_STATE = { const GPU_STATE = {
enabled: 'аппаратное декодирование разрешено и доступно движку', get enabled() { return t('ui.hardware.decoding.is.allowed.and.available.to'); },
enabled_on: 'аппаратное декодирование разрешено и доступно движку', get enabled_on() { return t('ui.hardware.decoding.is.allowed.and.available.to'); },
enabled_force: 'аппаратное декодирование принудительно разрешено', get enabled_force() { return t('ui.hardware.decoding.is.force.enabled'); },
disabled_software: 'аппаратное декодирование отключено, движок будет декодировать программно', get disabled_software() { return t('ui.hardware.decoding.is.disabled.the.engine.will'); },
disabled_off: 'аппаратное декодирование отключено', get disabled_off() { return t('ui.hardware.decoding.is.disabled'); },
disabled_off_ok: 'аппаратное декодирование отключено', get disabled_off_ok() { return t('ui.hardware.decoding.is.disabled'); },
unavailable_software: 'аппаратное декодирование недоступно на этом устройстве, будет программное', get unavailable_software() { return t('ui.hardware.decoding.is.unavailable.on.this.device'); },
unavailable_off: 'аппаратное декодирование недоступно', get unavailable_off() { return t('ui.hardware.decoding.is.unavailable'); },
unavailable_off_ok: 'аппаратное декодирование недоступно', 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. */ /** Saved preference vs what this run was started with vs what the engine reports vs the live decoder. */
@@ -268,13 +286,14 @@ export async function renderVideo() {
$('#opt-hwdec').checked = saved; $('#opt-hwdec').checked = saved;
$('#hwdec-restart').hidden = !status || saved === status.hardwareDecodeAtLaunch; $('#hwdec-restart').hidden = !status || saved === status.hardwareDecodeAtLaunch;
if (status) { if (status) {
const gpu = status.gpu?.video_decode ?? 'неизвестно'; $('#hwdec-status').dataset.policy = status.hardwareDecodeAtLaunch ? 'allowed' : 'forbidden';
setText($('#hwdec-status'), `В этом запуске: ${status.hardwareDecodeAtLaunch ? 'разрешено' : 'запрещено (флаг disable-accelerated-video-decode)'}. Движок Chromium: ${GPU_STATE[gpu] ?? gpu}.`); 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 d = watchStats.decoder;
const live = watchStats.state === 'live' || watchStats.state === 'unstable'; const live = watchStats.state === 'live' || watchStats.state === 'unstable';
const efficiency = watchStats.powerEfficientDecoder === true ? ' (энергоэффективный)' : watchStats.powerEfficientDecoder === false ? ' (не энергоэффективный)' : ''; const efficiency = watchStats.powerEfficientDecoder === true ? t('ui.power.efficient') : watchStats.powerEfficientDecoder === false ? t('ui.not.power.efficient') : '';
setText($('#decoder-last'), d setText($('#decoder-last'), () => d
? `${live ? 'Текущая трансляция' : 'При последнем просмотре'}: ${watchStats.codec || '—'}, декодер «${d}»${efficiency}.` ? 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
View File
@@ -1,45 +1,48 @@
import { t } from './i18n.js';
// User-facing wording for bridge errors and plain-text rendering of TeamSpeak BBCode. // User-facing wording for bridge errors and plain-text rendering of TeamSpeak BBCode.
const ERROR_TEXT = { const ERROR_TEXT = {
bad_request: 'Некорректный запрос', get bad_request() { return t('ui.invalid.request'); },
unknown_command: 'Команда не поддерживается', get unknown_command() { return t('ui.command.not.supported'); },
profile_missing: 'Профиль ещё не создан', get profile_missing() { return t('ui.profile.not.created.yet'); },
profile_exists: 'Профиль уже существует', get profile_exists() { return t('ui.profile.already.exists'); },
identity_corrupt: 'Файл идентичности повреждён. Восстановите его из резервной копии (Настройки → Импорт).', get identity_corrupt() { return t('ui.the.identity.file.is.corrupted.restore.a'); },
profile_corrupt: 'Файл профиля повреждён', get profile_corrupt() { return t('ui.profile.file.corrupted'); },
invalid_nickname: 'Никнейм должен содержать от 3 до 30 символов без управляющих символов', get invalid_nickname() { return t('ui.nickname.must.contain.3.30.characters.with'); },
nickname_required: 'Сначала задайте никнейм', get nickname_required() { return t('ui.set.a.nickname.first'); },
not_connected: 'Нет подключения к серверу', get not_connected() { return t('ui.not.connected.to.a.server'); },
already_connected: 'Уже подключено', get already_connected() { return t('ui.already.connected'); },
connect_failed: 'Не удалось подключиться', get connect_failed() { return t('ui.could.not.connect'); },
server_error: 'Сервер отклонил действие', get server_error() { return t('ui.the.server.rejected.the.action'); },
audio_overflow: 'Очередь микрофона переполнена, часть звука пропущена', get audio_overflow() { return t('ui.microphone.queue.overflow.some.audio.was.dropped'); },
audio_muted: 'Микрофон или звук выключены — передача не идёт', get audio_muted() { return t('ui.microphone.or.audio.is.muted.voice.is'); },
audio_codec: 'Ошибка кодека Opus', get audio_codec() { return t('ui.opus.codec.error'); },
audio_codec_unsupported: 'Канал использует устаревший кодек (Speex/CELT): передача голоса невозможна', get audio_codec_unsupported() { return t('ui.this.channel.uses.a.legacy.codec.speex'); },
rename_not_persisted: 'Сервер принял никнейм, но сохранить его на диск не удалось', get rename_not_persisted() { return t('ui.the.server.accepted.the.nickname.but.saving'); },
io: 'Ошибка доступа к каталогу данных', get io() { return t('ui.could.not.access.the.data.folder'); },
internal: 'Внутренняя ошибка ядра', get internal() { return t('ui.internal.core.error'); },
timeout: 'Ядро не ответило вовремя', get timeout() { return t('ui.the.core.did.not.respond.in.time'); },
core_unavailable: 'Ядро не запущено', get core_unavailable() { return t('ui.the.core.is.not.running'); },
core_exited: 'Ядро завершило работу', get core_exited() { return t('ui.the.core.stopped2'); },
core_missing: 'Исполняемый файл ядра не найден', get core_missing() { return t('ui.core.executable.not.found'); },
connected: 'Сначала отключитесь от сервера', get connected() { return t('ui.disconnect.from.the.server.first2'); },
forbidden: 'Действие запрещено', get forbidden() { return t('ui.action.forbidden'); },
get device_unavailable() { return t('error.device_unavailable'); },
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) { export function errorText(error) {
if (!error) return 'Неизвестная ошибка'; if (!error) return t('ui.no.error.details.were.provided');
const base = ERROR_TEXT[error.code] ?? error.message ?? error.code ?? 'Ошибка'; const base = ERROR_TEXT[error.code] ?? t('ui.error2');
const ts = error.ts_error; const ts = error.ts_error;
if (ts && (ts.message || ts.name)) { 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})`; return `${base}: ${ts.message || ts.name} (TS ${ts.id}${perm})`;
} }
if (error.code === 'connect_failed' && error.message) return `${base}: ${error.message}`; if (error.message && error.message !== base) return `${base}: ${error.message}`;
if (!ERROR_TEXT[error.code] && error.message) return 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') });
return base;
} }
const BB_TAGS = /\[\/?(?:b|i|u|s|url(?:=[^\]]*)?|color(?:=[^\]]*)?|size(?:=[^\]]*)?|center|left|right|img|quote|code|list|\*|hr|table|tr|td|th)\]/gi; 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 = { const KEY_NAMES = {
Space: 'Пробел', get Space() { return t('ui.space'); },
Backquote: '`', Backquote: '`',
ControlLeft: 'Левый Ctrl', get ControlLeft() { return t('ui.left.ctrl'); },
ControlRight: 'Правый Ctrl', get ControlRight() { return t('ui.right.ctrl'); },
AltLeft: 'Левый Alt', get AltLeft() { return t('ui.left.alt'); },
AltRight: 'Правый Alt', get AltRight() { return t('ui.right.alt'); },
ShiftLeft: 'Левый Shift', get ShiftLeft() { return t('ui.left.shift'); },
ShiftRight: 'Правый Shift', get ShiftRight() { return t('ui.right.shift'); },
MetaLeft: 'Левый Super', get MetaLeft() { return t('ui.left.super'); },
MetaRight: 'Правый Super', get MetaRight() { return t('ui.right.super'); },
CapsLock: 'Caps Lock', CapsLock: 'Caps Lock',
Tab: 'Tab', Tab: 'Tab',
}; };
export function keyLabel(code) { export function keyLabel(code) {
if (!code) return 'не назначена'; if (!code) return t('ui.not.assigned');
if (KEY_NAMES[code]) return KEY_NAMES[code]; if (KEY_NAMES[code]) return KEY_NAMES[code];
if (code.startsWith('Key')) return code.slice(3); if (code.startsWith('Key')) return code.slice(3);
if (code.startsWith('Digit')) return code.slice(5); if (code.startsWith('Digit')) return code.slice(5);
@@ -90,9 +93,5 @@ export function keyLabel(code) {
} }
export function pluralMembers(n) { export function pluralMembers(n) {
const mod10 = n % 10; return t('members.count', { count: n });
const mod100 = n % 100;
if (mod10 === 1 && mod100 !== 11) return `${n} участник`;
if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return `${n} участника`;
return `${n} участников`;
} }
+2 -1
View File
@@ -1,3 +1,4 @@
import { t } from './i18n.js';
import { $, h, icon } from './dom.js'; import { $, h, icon } from './dom.js';
const MAX_TOASTS = 4; const MAX_TOASTS = 4;
@@ -5,7 +6,7 @@ const MAX_TOASTS = 4;
/** Non-blocking notice in the polite live region. Errors stay longer. */ /** Non-blocking notice in the polite live region. Errors stay longer. */
export function toast(text, kind = 'info') { export function toast(text, kind = 'info') {
const host = $('#toasts'); 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 el = h('div', { class: 'toast', role: kind === 'error' ? 'alert' : 'status', dataset: { kind } }, h('span', { class: 'toast-text', text }), close);
const remove = () => el.remove(); const remove = () => el.remove();
close.addEventListener('click', remove); close.addEventListener('click', remove);
+38 -36
View File
@@ -1,3 +1,4 @@
import { t, getLanguage } from './i18n.js';
// Channel tree with members (TeamSpeak order): talking state, mute flags, server-configured group // 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. // labels and icons, channel icons/banners, avatars and stream badges — all from real server data.
import { $, h, icon, reconcile, setText } from './dom.js'; import { $, h, icon, reconcile, setText } from './dom.js';
@@ -16,7 +17,7 @@ export function initTree(h0) {
function sortClients(a, b) { function sortClients(a, b) {
if (b.talk_power !== a.talk_power) return b.talk_power - a.talk_power; 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() { export function renderTree() {
@@ -25,7 +26,7 @@ export function renderTree() {
if (!isConnected()) { if (!isConnected()) {
list.replaceChildren(); list.replaceChildren();
empty.hidden = false; 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; pendingPasswordCid = null;
return; return;
} }
@@ -77,11 +78,12 @@ function updateRow(el, item) {
el.style.setProperty('--depth', String(item.ch.depth)); el.style.setProperty('--depth', String(item.ch.depth));
el.dataset.kind = item.spacer.kind; 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; 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; break;
} }
case 'password': case 'password':
el.style.setProperty('--depth', String(item.ch.depth)); 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; break;
case 'member': case 'member':
updateMemberRow(el, item.cl, item.depth); updateMemberRow(el, item.cl, item.depth);
@@ -115,15 +117,15 @@ function updateChannelRow(li, ch, count) {
const btn = li.firstElementChild; const btn = li.firstElementChild;
const [ic, label, chIcon, meta] = btn.children; const [ic, label, chIcon, meta] = btn.children;
ic.firstElementChild.setAttribute('href', ch.has_password ? '#i-lock' : '#i-channel'); ic.firstElementChild.setAttribute('href', ch.has_password ? '#i-lock' : '#i-channel');
setText(label, ch.name); setText(label, () => ch.name);
const max = ch.max_clients; 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]; const parts = [ch.name];
if (ch.has_password) parts.push('с паролем'); if (ch.has_password) parts.push(t('ui.password.protected'));
parts.push(pluralMembers(count)); parts.push(pluralMembers(count));
if (current) parts.push('вы здесь'); if (current) parts.push(t('ui.you.are.here'));
btn.setAttribute('aria-label', parts.join(', ')); 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'); if (current) btn.setAttribute('aria-current', 'location');
else btn.removeAttribute('aria-current'); else btn.removeAttribute('aria-current');
@@ -163,14 +165,14 @@ async function joinChannel(cid) {
try { try {
await call('join_channel', { channel_id: cid }); await call('join_channel', { channel_id: cid });
} catch (err) { } 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) { function createPasswordRow(ch) {
const input = h('input', { type: 'password', autocomplete: 'off', 'aria-label': `Пароль канала ${ch.name}`, placeholder: 'Пароль канала' }); 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' }, 'Отмена'); 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' }, 'Войти'), 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 li = h('li', { class: 'tree-row password-row' }, form);
const close = () => { const close = () => {
pendingPasswordCid = null; pendingPasswordCid = null;
@@ -187,7 +189,7 @@ function createPasswordRow(ch) {
close(); close();
} catch (err) { } catch (err) {
input.setAttribute('aria-invalid', 'true'); 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(); input.select();
} }
}); });
@@ -233,41 +235,41 @@ function updateMemberRow(li, cl, depth) {
li.dataset.talking = String(talking); li.dataset.talking = String(talking);
const btn = li.firstElementChild; const btn = li.firstElementChild;
const [avatar, before, label, after, tag, flags, badges] = btn.children; const [avatar, before, label, after, tag, flags, badges] = btn.children;
setText(label, cl.nickname); setText(label, () => cl.nickname);
setText(tag, cl.is_self ? 'вы' : ''); setText(tag, () => cl.is_self ? t('ui.you') : '');
// Group names appear next to the nickname exactly where each group's name_mode puts them. // Group names appear next to the nickname exactly where each group's name_mode puts them.
const { server: groups, channel: cgroup } = groupsOf(cl); const { server: groups, channel: cgroup } = groupsOf(cl);
const named = cgroup ? [...groups, cgroup] : groups; const named = cgroup ? [...groups, cgroup] : groups;
const beforeText = named.filter((g) => g.name_mode === 'before').map((g) => g.name).join(' · '); 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(' · '); const afterText = named.filter((g) => g.name_mode === 'after').map((g) => g.name).join(' · ');
setText(before, beforeText); setText(before, () => beforeText);
before.title = beforeText; before.title = beforeText;
before.hidden = !beforeText; before.hidden = !beforeText;
setText(after, afterText); setText(after, () => afterText);
after.title = afterText; after.title = afterText;
after.hidden = !afterText; after.hidden = !afterText;
const flagIcons = []; const flagIcons = [];
const states = []; const states = [];
if (cl.output_muted) { if (cl.output_muted) {
flagIcons.push(['headphones-off', 'flag-muted', 'Звук выключен']); flagIcons.push(['headphones-off', 'flag-muted', t('ui.audio.muted')]);
states.push('звук выключен'); states.push(t('ui.audio.muted2'));
} else if (cl.input_muted) { } else if (cl.input_muted) {
flagIcons.push(['mic-off', 'flag-muted', 'Микрофон выключен']); flagIcons.push(['mic-off', 'flag-muted', t('ui.microphone.muted')]);
states.push('микрофон выключен'); states.push(t('ui.microphone.muted2'));
} }
if (!cl.input_hardware && !cl.input_muted) { if (!cl.input_hardware && !cl.input_muted) {
flagIcons.push(['mic-off', '', 'Нет микрофона']); flagIcons.push(['mic-off', '', t('ui.no.microphone')]);
states.push('нет микрофона'); states.push(t('ui.no.microphone2'));
} }
if (cl.away) { if (cl.away) {
flagIcons.push(['moon', '', 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 ? `отошёл: ${cl.away_message}` : 'отошёл'); states.push(cl.away_message ? t('message.away.p02', { p0: cl.away_message }) : t('ui.away2'));
} }
if (cl.is_recording) { if (cl.is_recording) {
flagIcons.push(['record', 'flag-rec', 'Записывает разговор']); flagIcons.push(['record', 'flag-rec', t('ui.recording.the.conversation')]);
states.push('записывает'); states.push(t('ui.recording'));
} }
const flagKey = flagIcons.map((f) => f.join(':')).join('|'); const flagKey = flagIcons.map((f) => f.join(':')).join('|');
if (flags.dataset.sig !== flagKey) { 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. // 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 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) { if (badges.dataset.sig !== badgeKey) {
badges.dataset.sig = badgeKey; badges.dataset.sig = badgeKey;
badges.replaceChildren( badges.replaceChildren(
...iconGroups.map((g) => groupBadge(g)), ...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); 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.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 ? `Описание: ${cl.description}` : '', groupNames.length ? `Группы: ${groupNames.join(', ')}` : '', cl.is_self ? 'Настройки профиля' : 'Написать личное сообщение'].filter(Boolean).join('\n'); 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); const stream = hooks.streamOf(cl.id);
let watch = li.querySelector('.watch-btn'); let watch = li.querySelector('.watch-btn');
if (stream && !cl.is_self) { if (stream && !cl.is_self) {
if (!watch) { 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', () => { watch.addEventListener('click', () => {
const s = hooks.streamOf(Number(li.dataset.clid)); const s = hooks.streamOf(Number(li.dataset.clid));
if (s) hooks.toggleWatch(s); if (s) hooks.toggleWatch(s);
@@ -316,9 +318,9 @@ function updateMemberRow(li, cl, depth) {
} }
const watching = hooks.watchingId() === stream.id; const watching = hooks.watchingId() === stream.id;
watch.setAttribute('aria-pressed', String(watching)); watch.setAttribute('aria-pressed', String(watching));
setText(watch.lastElementChild, watching ? 'Смотрите' : 'Смотреть'); setText(watch.lastElementChild, () => watching ? t('ui.watching') : t('ui.watch'));
watch.setAttribute('aria-label', `${watching ? 'Прекратить просмотр' : 'Смотреть'} трансляцию ${cl.nickname}${stream.name ? `: ${stream.name}` : ''}`); 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 || 'Трансляция экрана'; watch.title = stream.name || t('ui.screen.share');
} else if (watch) { } else if (watch) {
watch.remove(); watch.remove();
} }
+134
View File
@@ -0,0 +1,134 @@
// 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 });
if (s.mode !== 'manual') return base;
return `${base} ${s.manualReason ? codeText('manual', s.manualReason, {}) : t('update.ui.status.manual')}`;
}
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();
}
}
+190 -64
View File
@@ -2,25 +2,28 @@
// device selection and push-to-talk keys. // device selection and push-to-talk keys.
import { $, setText } from './dom.js'; import { $, setText } from './dom.js';
import { S, isConnected, ownChannel } from './state.js'; import { S, isConnected, ownChannel } from './state.js';
import { tp, log } from './core.js'; import { tp, log, call } from './core.js';
import { AudioEngine } from './audio/engine.js'; import { AudioEngine } from './audio/engine.js';
import { buildDeviceOptions } from './audio/devices.js';
import { toast } from './toast.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 }; export const voiceStats = { framesSent: 0, bursts: 0, framesPlayed: 0, level: 0 };
let engine = null; let engine = null;
let sending = false; let sending = false;
let burst = null;
let micTest = false; let micTest = false;
let meterRaf = 0; let meterRaf = 0;
let assigningPtt = null; let assigningPtt = null;
let hooks = { onPtt: () => {}, onPttAssigned: () => {}, onTransmitChanged: () => {} }; let hooks = { onPtt: () => {}, onPttAssigned: () => {}, onTransmitChanged: () => {}, savePrefs: async () => S.prefs, onOutputChanged: () => {} };
export function initVoice(h0) { export function initVoice(h0) {
hooks = { ...hooks, ...h0 }; hooks = { ...hooks, ...h0 };
engine = new AudioEngine({ engine = new AudioEngine({
onFrame, onFrame,
onError: (e) => toast(e.message, 'error'), onError: (e) => toast(() => errorText(e), 'error'),
log, log,
}); });
tp.onAudio(({ pcm }) => { tp.onAudio(({ pcm }) => {
@@ -29,22 +32,26 @@ export function initVoice(h0) {
}); });
window.addEventListener('keydown', onKeyDown, true); window.addEventListener('keydown', onKeyDown, true);
window.addEventListener('keyup', onKeyUp, true); window.addEventListener('keyup', onKeyUp, true);
window.addEventListener('blur', () => setPtt(false)); window.addEventListener('blur', () => {
setPtt(false, 'window-blur');
hooks.onPtt(false);
});
window.addEventListener('focus', () => hooks.onPtt(S.ptt));
navigator.mediaDevices.addEventListener('devicechange', () => refreshDevices()); navigator.mediaDevices.addEventListener('devicechange', () => refreshDevices());
const btn = $('#btn-ptt'); const btn = $('#btn-ptt');
btn.addEventListener('pointerdown', (e) => { btn.addEventListener('pointerdown', (e) => {
if (e.button !== 0) return; if (e.button !== 0) return;
btn.setPointerCapture(e.pointerId); btn.setPointerCapture(e.pointerId);
setPtt(true); setPtt(true, 'button');
}); });
const release = () => setPtt(false); const release = () => setPtt(false, 'button');
btn.addEventListener('pointerup', release); btn.addEventListener('pointerup', release);
btn.addEventListener('pointercancel', release); btn.addEventListener('pointercancel', release);
btn.addEventListener('lostpointercapture', release); btn.addEventListener('lostpointercapture', release);
btn.addEventListener('keydown', (e) => { btn.addEventListener('keydown', (e) => {
if ((e.key === ' ' || e.key === 'Enter') && !e.repeat) { if ((e.key === ' ' || e.key === 'Enter') && !e.repeat) {
e.preventDefault(); e.preventDefault();
setPtt(true); setPtt(true, 'button');
} }
}); });
btn.addEventListener('keyup', (e) => { btn.addEventListener('keyup', (e) => {
@@ -60,9 +67,9 @@ export async function startAudio() {
try { try {
await engine.init(); await engine.init();
engine.setVoiceVolume(S.prefs.voiceVolume); 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) { } catch (err) {
toast(`Звук недоступен: ${err.message}`, 'error'); toast(() => t('message.audio.unavailable.p0', { p0: err.message }), 'error');
log('error', `audio init failed: ${err.message}`); log('error', `audio init failed: ${err.message}`);
} }
} }
@@ -72,29 +79,94 @@ function channelCanTransmit() {
return !ch || ch.codec === null || ch.codec === undefined || ch.codec === 'opus_voice' || ch.codec === 'opus_music'; return !ch || ch.codec === null || ch.codec === undefined || ch.codec === 'opus_voice' || ch.codec === 'opus_music';
} }
export function shouldTransmit() { // Transmit mode confirmed by the core (`set_transmit`): null until acknowledged. Frames are forwarded only
return isConnected() // when it matches what the preferences ask for, so audio never reaches the core under the wrong mode.
&& !S.audio.input_muted // "direct": the core sends every forwarded frame (push to talk, open microphone). "vad": the core's voice
&& !S.audio.output_muted // detector decides, so frames are forwarded continuously and only speech is sent.
&& (S.prefs.transmitMode === 'open' || S.ptt) let coreTx = null;
&& channelCanTransmit(); let coreTxPending = null;
let coreTxFailed = false;
function wantedCoreTx() {
return S.prefs?.transmitMode === 'vad' ? { mode: 'vad', sensitivity: S.prefs.vadSensitivity } : { mode: 'direct' };
}
const txKey = (mode) => (mode ? `${mode.mode}:${mode.sensitivity ?? ''}` : '');
/** Stops forwarding at once and ends an open burst (the core ends its talk spurt on audio_end). */
function stopForwarding() {
if (!sending) return;
tp.endAudio();
sending = false;
log('debug', `voice: burst end frames=${burst.frames} peak=${burst.peakMax > 0 ? (20 * Math.log10(burst.peakMax)).toFixed(1) : '-inf'} dBFS`);
burst = null;
hooks.onTransmitChanged();
}
/**
* Asks the core to use the transmit mode the preferences select. Nothing is forwarded until the core has
* acknowledged it; a failure leaves the mode unapplied (nothing is sent) and is shown, never replaced by
* another mode.
*/
export async function applyTransmitMode() {
if (!S.prefs) return;
const want = wantedCoreTx();
const key = txKey(want);
if (txKey(coreTx) === key && !coreTxFailed) return;
coreTx = null;
stopForwarding();
coreTxPending = key;
try {
const result = await call('set_transmit', want);
if (coreTxPending !== key) return; // a newer change is on its way
coreTx = { mode: result.mode, sensitivity: result.sensitivity };
coreTxFailed = false;
log('info', `voice: transmit mode ${result.mode}${result.sensitivity ? ` (${result.sensitivity})` : ''}`);
} catch (err) {
if (coreTxPending !== key) return;
coreTxFailed = true;
log('error', `voice: set_transmit failed: ${err.code} ${err.message}`);
toast(() => t('error.transmit_mode', { detail: errorText(err) }), 'error');
} finally {
if (coreTxPending === key) coreTxPending = null;
hooks.onTransmitChanged();
}
}
/** The core stopped or restarted: its transmit mode is unknown until applied again. */
export function forgetCoreTransmitMode() {
coreTx = null;
coreTxPending = null;
sending = false;
burst = null;
}
/** Whether captured frames go to the core right now (not whether voice is sent: see S.audio.transmitting). */
export function shouldForward() {
if (!isConnected() || S.audio.input_muted || S.audio.output_muted || !channelCanTransmit()) return false;
const mode = S.prefs.transmitMode;
if (mode === 'vad') return coreTx?.mode === 'vad' && coreTx.sensitivity === S.prefs.vadSensitivity;
if (coreTx?.mode !== 'direct') return false;
return mode === 'open' || S.ptt;
} }
function onFrame(pcm, rms, peak) { function onFrame(pcm, rms, peak) {
voiceStats.level = peak; voiceStats.level = peak;
if (micTest && !meterRaf) meterRaf = requestAnimationFrame(drawMeter); if (micTest && !meterRaf) meterRaf = requestAnimationFrame(drawMeter);
if (shouldTransmit()) { if (shouldForward()) {
tp.sendAudioFrame(new Uint8Array(pcm)); tp.sendAudioFrame(new Uint8Array(pcm));
voiceStats.framesSent += 1; voiceStats.framesSent += 1;
if (!sending) { if (!sending) {
sending = true; sending = true;
voiceStats.bursts += 1; voiceStats.bursts += 1;
burst = { frames: 0, peakMax: 0, mode: S.prefs.transmitMode };
log('debug', `voice: burst start mode=${burst.mode} focused=${document.hasFocus()} capture=${engine.capturing}`);
hooks.onTransmitChanged(); hooks.onTransmitChanged();
} }
} else if (sending) { burst.frames += 1;
tp.endAudio(); if (peak > burst.peakMax) burst.peakMax = peak;
sending = false; } else {
hooks.onTransmitChanged(); stopForwarding();
} }
} }
@@ -105,34 +177,40 @@ function drawMeter() {
$('#mic-meter').style.width = `${pct.toFixed(0)}%`; $('#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() { export async function syncCapture() {
const want = isConnected() || micTest; const want = isConnected() || micTest;
if (want && !engine.capturing) { if (!want) {
try {
await engine.startCapture({
deviceId: S.prefs.inputDeviceId,
echoCancellation: S.prefs.echoCancellation,
noiseSuppression: S.prefs.noiseSuppression,
autoGainControl: S.prefs.autoGainControl,
});
refreshDevices();
} catch (err) {
toast(`Нет доступа к микрофону: ${err.message || err.name}`, 'error');
log('error', `capture failed: ${err.name} ${err.message}`);
}
} else if (!want && engine.capturing) {
engine.stopCapture(); engine.stopCapture();
if (sending) { stopForwarding();
tp.endAudio(); return;
sending = false; }
} 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) {
if (err.code === 'device_unavailable') toast(() => errorText(err), 'error');
else toast(() => t('message.microphone.access.unavailable.p0', { p0: err.message || err.name }), 'error');
log('error', `capture failed: ${err.name} ${err.message}`);
} }
} }
/**
* Re-opens the microphone with the current preferences. Also used after a failed start, so a newly chosen
* device recovers capture whenever capture is wanted (connected or mic test); otherwise nothing opens.
*/
export async function restartCapture() { export async function restartCapture() {
if (!engine.capturing) return;
engine.stopCapture(); engine.stopCapture();
stopForwarding();
await syncCapture(); await syncCapture();
} }
@@ -150,8 +228,27 @@ export function setVoiceVolume(pct) {
engine.setVoiceVolume(pct); engine.setVoiceVolume(pct);
} }
export async function setOutputDevice(id) { /** Saved input device for capture; used by Settings and by the microphone context menu. */
await engine.setOutputDevice(id); export async function chooseInputDevice(deviceId) {
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) {
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(() => t('message.could.not.select.output.device.p0', { p0: err.message }), 'error');
}
hooks.onOutputChanged();
await refreshDevices();
} }
export function playbackStats() { export function playbackStats() {
@@ -160,26 +257,42 @@ export function playbackStats() {
// ---------- devices ---------- // ---------- devices ----------
export async function refreshDevices() { let lastChoices = null;
let devices = [];
try { /** Last enumerated choices ({input, output} from buildDeviceOptions), shared by Settings and the menus. */
devices = await navigator.mediaDevices.enumerateDevices(); export async function deviceChoices() {
} catch { await refreshDevices();
return; return lastChoices;
}
fillSelect($('#input-device'), devices.filter((d) => d.kind === 'audioinput'), S.prefs.inputDeviceId, 'Микрофон');
fillSelect($('#output-device'), devices.filter((d) => d.kind === 'audiooutput'), S.prefs.outputDeviceId, 'Динамики');
} }
function fillSelect(select, list, selected, fallback) { export async function refreshDevices() {
const options = [{ value: '', label: 'Системное устройство по умолчанию' }]; const status = $('#device-status');
let n = 0; let devices;
for (const d of list) { try {
if (d.deviceId === 'default' || d.deviceId === 'communications' || d.deviceId === '') continue; devices = await navigator.mediaDevices.enumerateDevices();
n += 1; } catch (err) {
options.push({ value: d.deviceId, label: d.label || `${fallback} ${n}` }); // The menus must show this failure, not an earlier successful list.
lastChoices = { error: { name: err.name, message: 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;
} }
if (selected && !options.some((o) => o.value === selected)) options.push({ value: selected, label: 'Выбранное устройство (не подключено)' }); const input = buildDeviceOptions(devices.filter((d) => d.kind === 'audioinput'), S.prefs.inputDeviceId);
const output = buildDeviceOptions(devices.filter((d) => d.kind === 'audiooutput'), S.prefs.outputDeviceId);
fillSelect($('#input-device'), input.options, S.prefs.inputDeviceId);
fillSelect($('#output-device'), output.options, S.prefs.outputDeviceId);
let 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}`);
}
function fillSelect(select, options, selected) {
select.replaceChildren(...options.map((o) => { select.replaceChildren(...options.map((o) => {
const opt = document.createElement('option'); const opt = document.createElement('option');
opt.value = o.value; opt.value = o.value;
@@ -214,12 +327,13 @@ function onKeyUp(e) {
if (e.code === S.prefs?.pttCode) setPtt(false); if (e.code === S.prefs?.pttCode) setPtt(false);
} }
export function setPtt(down) { export function setPtt(down, source = 'key') {
if (S.ptt === down) return; if (S.ptt === down) return;
S.ptt = down; S.ptt = down;
const btn = $('#btn-ptt'); const btn = $('#btn-ptt');
btn.setAttribute('aria-pressed', String(down)); 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); hooks.onPtt(down);
} }
@@ -232,8 +346,20 @@ export function capturePttKey() {
export function transmitHint() { export function transmitHint() {
if (!S.prefs) return ''; if (!S.prefs) return '';
if (S.prefs.transmitMode === 'open') return 'Открытый микрофон'; if (S.prefs.transmitMode === 'open') return t('ui.open.microphone');
return `Клавиша: ${keyLabel(S.prefs.pttCode)}`; if (S.prefs.transmitMode === 'vad') return t('transmit.header.vad');
// The key is read only from this window: say so whenever another window has the focus.
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() {
return Boolean(engine && engine.capturing);
}
/** The transmit mode the core confirmed, or null (diagnostics). */
export function confirmedTransmitMode() {
return coreTx ? { ...coreTx } : null;
} }
export function isSending() { export function isSending() {
+41 -33
View File
@@ -1,3 +1,4 @@
import { t, onLanguageChange } from './i18n.js';
// TS6 screenshare: discovery (stream_list + notifications), one viewing session, the viewer panel. // TS6 screenshare: discovery (stream_list + notifications), one viewing session, the viewer panel.
import { $, setIcon, setText } from './dom.js'; import { $, setIcon, setText } from './dom.js';
import { S, isConnected, clientById } from './state.js'; import { S, isConnected, clientById } from './state.js';
@@ -39,6 +40,10 @@ export const watchStats = { state: 'idle', ...emptyStats() };
export function initWatch(h0) { export function initWatch(h0) {
hooks = { ...hooks, ...h0 }; hooks = { ...hooks, ...h0 };
onLanguageChange(() => {
applyVolume();
updateStatsLine();
});
const video = $('#stream-video'); const video = $('#stream-video');
const volume = $('#stream-volume'); const volume = $('#stream-volume');
volume.addEventListener('input', () => applyVolume()); volume.addEventListener('input', () => applyVolume());
@@ -51,7 +56,7 @@ export function initWatch(h0) {
$('#stream-fullscreen').addEventListener('click', () => { $('#stream-fullscreen').addEventListener('click', () => {
const view = $('#stream-view'); const view = $('#stream-view');
if (document.fullscreenElement) document.exitFullscreen(); 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()); $('#stream-stop').addEventListener('click', () => stopWatching());
video.addEventListener('resize', () => updateStatsLine()); video.addEventListener('resize', () => updateStatsLine());
@@ -139,7 +144,7 @@ export function onStreamEvent(evt) {
} }
if (name === 'notifysfuaccessinfo' && !sfuToastShown) { if (name === 'notifysfuaccessinfo' && !sfuToastShown) {
sfuToastShown = true; 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(); if (directory.handle(name, items)) hooks.onChange();
} }
@@ -177,8 +182,9 @@ export function startWatching(stream, transport = coreTransport) {
Object.assign(watchStats, emptyStats()); Object.assign(watchStats, emptyStats());
watchStats.streamAdvertisesAudio = stream.fields?.audio === '1' ? true : stream.fields?.audio === '0' ? false : null; watchStats.streamAdvertisesAudio = stream.fields?.audio === '1' ? true : stream.fields?.audio === '0' ? false : null;
$('#stream-view').hidden = false; $('#stream-view').hidden = false;
setText($('#stream-title'), current.name ? `${current.nickname} — ${current.name}` : `Трансляция ${current.nickname}`); const streamTitle = { ...current };
setText($('#stream-stats'), ''); setText($('#stream-title'), () => streamTitle.name ? `${streamTitle.nickname} — ${streamTitle.name}` : t('message.stream.from.p0', { p0: streamTitle.nickname }));
setText($('#stream-stats'), () => '');
const own = new StreamViewerSession({ const own = new StreamViewerSession({
streamId: stream.id, streamId: stream.id,
@@ -238,29 +244,29 @@ function teardownMedia() {
} }
const STATE_TEXT = { const STATE_TEXT = {
requesting: 'Запрос отправлен. Ждём ответа стримера…', get requesting() { return t('ui.request.sent.waiting.for.the.streamer'); },
connecting: 'Соединение со стримером…', get connecting() { return t('ui.connecting.to.the.streamer'); },
live: '', live: '',
unstable: 'Связь со стримером прервалась, ждём восстановления…', get unstable() { return t('ui.the.stream.connection.was.interrupted.waiting.to'); },
declined: 'Стример отклонил запрос на просмотр.', get declined() { return t('ui.the.streamer.declined.your.request.to.watch'); },
removed: 'Стример убрал вас из зрителей.', get removed() { return t('ui.the.streamer.removed.you.from.the.viewers'); },
stopped: '', stopped: '',
}; };
function failureText(detail) { function failureText(detail) {
switch (detail) { switch (detail) {
case 'no_response': return 'Стример не ответил на запрос за 90 секунд.'; case 'no_response': return t('ui.the.streamer.did.not.respond.within.90');
case 'ice_failed': return 'Не удалось установить прямое соединение со стримером. Для просмотра нужен прямой сетевой доступ к его компьютеру (через STUN, без TURN).'; case 'ice_failed': return t('ui.could.not.connect.directly.to.the.streamer');
default: return `Ошибка трансляции: ${detail}`; default: return t('message.stream.error.p0', { p0: detail });
} }
} }
function endedText(detail) { function endedText(detail) {
switch (detail) { switch (detail) {
case 'stream_stopped': return 'Трансляция завершена.'; case 'stream_stopped': return t('ui.the.stream.ended');
case 'streamer_left': return 'Стример покинул сервер.'; case 'streamer_left': return t('ui.the.streamer.left.the.server');
case 'disconnected': return 'Соединение с сервером потеряно.'; case 'disconnected': return t('ui.connection.to.the.server.was.lost');
default: return 'Трансляция завершена.'; default: return t('ui.the.stream.ended');
} }
} }
@@ -268,15 +274,17 @@ function onSessionState(state, detail) {
watchStats.state = state; watchStats.state = state;
log('info', `watch: state ${state}${detail ? ` (${detail})` : ''}`); log('info', `watch: state ${state}${detail ? ` (${detail})` : ''}`);
if (state === 'stopped') return; if (state === 'stopped') return;
let text = STATE_TEXT[state]; const text = () => {
if (state === 'failed') text = failureText(detail); if (state === 'failed') return failureText(detail);
else if (state === 'ended') text = endedText(detail); if (state === 'ended') return endedText(detail);
else if (state === 'unsupported') text = 'Эта трансляция идёт через SFU-сервер TeamSpeak. TeamsPeach поддерживает только прямые (P2P) трансляции.'; if (state === 'unsupported') return t('ui.this.stream.uses.a.teamspeak.sfu.server');
else if (state === 'declined' && detail) text = `${STATE_TEXT.declined} ${detail}`; if (state === 'declined' && detail) return `${STATE_TEXT.declined} ${detail}`;
if (state === 'live' && watchStats.framesDecoded === 0) text = 'Соединение установлено, ждём первый кадр…'; if (state === 'live' && watchStats.framesDecoded === 0) return t('ui.connected.waiting.for.the.first.frame');
setText($('#stream-overlay'), text ?? ''); return STATE_TEXT[state] ?? '';
};
setText($('#stream-overlay'), text);
const terminal = ['declined', 'ended', 'removed', 'failed', 'unsupported'].includes(state); 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) { if (terminal) {
teardownMedia(); teardownMedia();
if (state !== 'ended' || detail !== 'disconnected') toast(text, state === 'ended' ? 'info' : 'error'); if (state !== 'ended' || detail !== 'disconnected') toast(text, state === 'ended' ? 'info' : 'error');
@@ -337,7 +345,7 @@ async function pollStats() {
watchStats.framesDecoded = inbound.framesDecoded ?? 0; watchStats.framesDecoded = inbound.framesDecoded ?? 0;
watchStats.decoder = inbound.decoderImplementation ?? ''; watchStats.decoder = inbound.decoderImplementation ?? '';
watchStats.powerEfficientDecoder = typeof inbound.powerEfficientDecoder === 'boolean' ? inbound.powerEfficientDecoder : null; 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}`; const sig = `${watchStats.codec} ${watchStats.fmtp}`;
if (codec && sig !== lastCodecLogged) { if (codec && sig !== lastCodecLogged) {
lastCodecLogged = sig; lastCodecLogged = sig;
@@ -351,12 +359,12 @@ function updateStatsLine() {
const parts = []; const parts = [];
if (watchStats.codec) parts.push(watchStats.codec); if (watchStats.codec) parts.push(watchStats.codec);
if (watchStats.width) parts.push(`${watchStats.width}×${watchStats.height}`); 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 (session.state === 'live') {
if (watchStats.streamAdvertisesAudio === false) parts.push('стример не передаёт звук'); if (watchStats.streamAdvertisesAudio === false) parts.push(t('ui.streamer.is.not.sending.audio'));
else if (watchStats.inboundAudioPackets > 0) parts.push('со звуком'); else if (watchStats.inboundAudioPackets > 0) parts.push(t('ui.with.audio'));
} }
setText($('#stream-stats'), parts.join(' · ')); setText($('#stream-stats'), () => parts.join(' · '));
} }
export function applyVolume() { export function applyVolume() {
@@ -365,9 +373,9 @@ export function applyVolume() {
const muted = $('#stream-mute').getAttribute('aria-pressed') === 'true'; const muted = $('#stream-mute').getAttribute('aria-pressed') === 'true';
video.volume = Number(volume.value) / 100; video.volume = Number(volume.value) / 100;
video.muted = muted || S.audio.output_muted; 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'); 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(); let sinkChain = Promise.resolve();
@@ -397,8 +405,8 @@ export function applySink() {
log('warn', `watch: setSinkId failed ${err.name}: ${err.message}`); log('warn', `watch: setSinkId failed ${err.name}: ${err.message}`);
if (session !== own) return; if (session !== own) return;
watchStats.sinkError = `${err.name}: ${err.message}`; watchStats.sinkError = `${err.name}: ${err.message}`;
const label = Array.from($('#output-device').options).find((o) => o.value === target)?.textContent || 'выбранное устройство'; const label = Array.from($('#output-device').options).find((o) => o.value === target)?.textContent || t('ui.selected.device');
toast(`Звук трансляции не удалось направить на «${label}» (${err.name}). Он продолжает играть через текущее устройство; выберите другое в Настройки → Звук.`, 'error'); toast(() => t('message.could.not.route.stream.audio.to', { p0: label, p1: err.name }), 'error');
} }
}); });
} }
+466
View File
@@ -0,0 +1,466 @@
// 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",
"transmit.mode.vad": "Voice activation",
"transmit.mode.open": "Open microphone (continuous transmission)",
"transmit.vad.sensitivity": "Voice activation sensitivity",
"transmit.vad.high": "High: quieter speech",
"transmit.vad.normal": "Normal",
"transmit.vad.low": "Low: noisier surroundings",
"transmit.vad.hint": "Voice detection runs locally on this computer, not in the cloud. It detects speech rather than just sound level; audio is only held briefly in memory to decide, and nothing is saved as a recording or transcribed into words. Transmission starts when speech is detected and ends about 0.4 s after the last detected speech. Noise suppression can help, but a TV, other voices, or noise may still trigger transmission or keep it open.",
"transmit.mic.test.hint": "The microphone test shows the input level, not whether speech is detected. The test itself never sends audio. In a channel, the selected transmission mode and mute controls determine when others hear you.",
"transmit.header.vad": "Voice activation",
"error.transmit_mode": "The transmission mode could not be applied ({detail}). Nothing is transmitted until it is applied.",
"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.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.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_unavailable": "The selected microphone is not available. Choose another device in Settings → Audio or by right-clicking the microphone button.",
"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.custom-profile": "Automatic install is off for a custom profile: the installer would restart TeamsPeach on the default profile. Install the update manually from the release page.",
"update.manual.custom-profile": "Automatic install is off for a custom profile: the installer would restart TeamsPeach on the default profile. Install the update manually from the release page.",
"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);
+26
View File
@@ -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);
+468
View File
@@ -0,0 +1,468 @@
// 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": "Открытый микрофон",
"transmit.mode.vad": "Активация голосом",
"transmit.mode.open": "Открытый микрофон (непрерывная передача)",
"transmit.vad.sensitivity": "Чувствительность активации голосом",
"transmit.vad.high": "Высокая: для тихой речи",
"transmit.vad.normal": "Обычная",
"transmit.vad.low": "Низкая: для шумной обстановки",
"transmit.vad.hint": "Детектор работает на этом компьютере, без облачных сервисов. Он определяет наличие речи, а не просто уровень звука; звук лишь кратко держится в памяти для решения, ничего не сохраняется как запись и не переводится в текст. Передача начинается при обнаружении речи и заканчивается примерно через 0,4 с после последней обнаруженной речи. Шумоподавление может помочь, но телевизор, чужие голоса или шум всё равно могут включить передачу или продлить её.",
"transmit.mic.test.hint": "Проверка микрофона показывает уровень входного сигнала, а не результат определения речи. Сама проверка не отправляет звук. В канале слышимость вашего голоса зависит от выбранного режима передачи и кнопок отключения микрофона и звука.",
"transmit.header.vad": "Активация голосом",
"error.transmit_mode": "Не удалось применить режим передачи ({detail}). Пока он не применён, ничего не передаётся.",
"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.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.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_unavailable": "Выбранный микрофон недоступен. Выберите другое устройство в Настройки → Звук или правым кликом по кнопке микрофона.",
"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.custom-profile": "Автоматическая установка отключена для отдельного профиля: установщик перезапустил бы TeamsPeach с профилем по умолчанию. Установите обновление вручную со страницы релиза.",
"update.manual.custom-profile": "Автоматическая установка отключена для отдельного профиля: установщик перезапустил бы TeamsPeach с профилем по умолчанию. Установите обновление вручную со страницы релиза.",
"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);
+34 -4
View File
@@ -109,11 +109,9 @@ p { margin: 0; }
stroke-linejoin: round; stroke-linejoin: round;
} }
.brand-mark { width: 40px; height: 40px; stroke: none; } /* Product mark: the application icon (assets/icon.png), the single brand master. */
.brand-mark { width: 40px; height: 40px; flex: none; object-fit: contain; }
.brand-mark-large { width: 56px; height: 56px; } .brand-mark-large { width: 56px; height: 56px; }
.brand-mark .peach-body, .peach-body { fill: var(--peach); stroke: none; }
.peach-crease { fill: none; stroke: rgba(120, 50, 20, 0.35); stroke-width: 1.2; }
.peach-leaf { fill: #5f9e5a; stroke: none; }
/* ---------- controls ---------- */ /* ---------- controls ---------- */
@@ -690,3 +688,35 @@ input[type="checkbox"], input[type="radio"] { accent-color: var(--accent); width
.card-details[open] > summary { margin-bottom: 10px; } .card-details[open] > summary { margin-bottom: 10px; }
.card-details .diag-list { margin-bottom: 12px; } .card-details .diag-list { margin-bottom: 12px; }
.details-title { font-size: 13px; font-weight: 600; color: var(--text-2); margin: 10px 0 6px; } .details-title { font-size: 13px; font-weight: 600; color: var(--text-2); margin: 10px 0 6px; }
/* ---------- device context menus (footer microphone / headphones) ---------- */
.device-menu {
position: fixed;
z-index: 20;
min-width: 240px;
max-width: min(420px, calc(100vw - 16px));
max-height: calc(100vh - 16px);
overflow-y: auto;
padding: 6px;
border: 1px solid var(--border);
border-radius: var(--radius);
background: var(--surface);
box-shadow: var(--shadow);
}
.menu-title { padding: 6px 10px 6px; font-size: 12px; font-weight: 600; color: var(--text-3); }
.menu-item { width: 100%; display: flex; align-items: center; gap: 8px; min-height: 32px; padding: 5px 10px 5px 6px; border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--text); font: inherit; font-size: 13px; text-align: left; cursor: pointer; }
.menu-item:hover, .menu-item:focus-visible { background: var(--hover); outline: none; }
.menu-item:focus-visible { box-shadow: inset 0 0 0 2px var(--focus); }
.menu-item[aria-checked="true"] { font-weight: 600; }
.menu-item-secondary { color: var(--text-2); }
.menu-check { width: 18px; flex: none; display: inline-grid; place-items: center; color: var(--accent); }
.menu-check .icon { width: 16px; height: 16px; }
.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; }
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 57 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 138 KiB

+15 -4
View File
@@ -1,6 +1,17 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<rect x="24" y="24" width="464" height="464" rx="104" fill="#2a2320"/> <defs>
<path d="M256 168c-86-30-150 30-150 112 0 86 67 156 150 156s150-70 150-156c0-82-64-142-150-112z" fill="#f3a37c"/> <linearGradient id="peach" x1="108" y1="142" x2="390" y2="432" gradientUnits="userSpaceOnUse">
<path d="M256 176c-30 47-37 160 0 254" fill="none" stroke="#b9653d" stroke-width="12" stroke-linecap="round"/> <stop stop-color="#ffc18c"/>
<path d="M261 160c4-50 39-80 96-82-6 52-40 81-96 82z" fill="#6aa864"/> <stop offset=".48" stop-color="#f3a37c"/>
<stop offset="1" stop-color="#ed776b"/>
</linearGradient>
<linearGradient id="leaf" x1="274" y1="109" x2="368" y2="44" gradientUnits="userSpaceOnUse">
<stop stop-color="#3e8053"/>
<stop offset="1" stop-color="#83b56b"/>
</linearGradient>
</defs>
<path d="M252 151c-7-35-3-68 11-94" fill="none" stroke="#80503b" stroke-width="21" stroke-linecap="round"/>
<path d="M264 119c3-53 43-84 116-78-10 58-47 92-116 78Z" fill="url(#leaf)"/>
<path d="M255 150c-35-26-72-35-106-24C79 148 47 201 53 267c7 85 73 150 167 195 23 11 37 21 44 21s20-12 40-23c96-54 152-120 156-196 4-65-31-119-92-137-43-13-82-4-113 23Z" fill="url(#peach)"/>
<path d="M255 150c-22 36-34 75-35 117-2 66 17 133 44 185" fill="none" stroke="#d97158" stroke-width="13" stroke-linecap="round"/>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 445 B

After

Width:  |  Height:  |  Size: 1.0 KiB

+10 -1
View File
@@ -411,6 +411,12 @@ dependencies = [
"syn 3.0.9", "syn 3.0.9",
] ]
[[package]]
name = "earshot"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "afea66474c4036a7e5fa4b072a3b0a09cd0b01f00134da3115d76b7cc5899f03"
[[package]] [[package]]
name = "eax" name = "eax"
version = "0.5.0" version = "0.5.0"
@@ -1869,14 +1875,17 @@ checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417"
[[package]] [[package]]
name = "teamspeach-core" name = "teamspeach-core"
version = "0.1.1" version = "0.1.3"
dependencies = [ dependencies = [
"audiopus", "audiopus",
"base64 0.22.1", "base64 0.22.1",
"earshot",
"futures", "futures",
"num-traits", "num-traits",
"serde", "serde",
"serde_json", "serde_json",
"sha-1",
"simple_asn1",
"thiserror 2.0.21", "thiserror 2.0.21",
"tokio", "tokio",
"tracing", "tracing",
+6 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "teamspeach-core" name = "teamspeach-core"
version = "0.1.1" version = "0.1.3"
edition = "2021" edition = "2021"
rust-version = "1.89" rust-version = "1.89"
description = "TeamsPeach native TeamSpeak protocol core (stdio JSON bridge)" description = "TeamsPeach native TeamSpeak protocol core (stdio JSON bridge)"
@@ -21,6 +21,11 @@ futures = "0.3"
num-traits = "0.2" num-traits = "0.2"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["raw_value", "preserve_order"] } serde_json = { version = "1", features = ["raw_value", "preserve_order"] }
sha-1 = "0.10"
# Same DER decoder tsproto-types uses for keys (already in the lock through it).
simple_asn1 = "0.6"
# Voice activation detector (pure Rust, embedded model; MIT OR Apache-2.0). Pinned: newer releases change the API.
earshot = "=1.2.2"
thiserror = "2" thiserror = "2"
tokio = { version = "1", features = ["rt", "macros", "io-std", "io-util", "sync", "time"] } tokio = { version = "1", features = ["rt", "macros", "io-std", "io-util", "sync", "time"] }
tracing = "0.1" tracing = "0.1"
+26 -1
View File
@@ -48,6 +48,7 @@ platform build links), followed by the license texts shipped with those crates.
| digest | 0.10.7 | MIT OR Apache-2.0 | registry+https://github.com/rust-lang/crates.io-index | | digest | 0.10.7 | MIT OR Apache-2.0 | registry+https://github.com/rust-lang/crates.io-index |
| digest | 0.9.0 | MIT OR Apache-2.0 | registry+https://github.com/rust-lang/crates.io-index | | digest | 0.9.0 | MIT OR Apache-2.0 | registry+https://github.com/rust-lang/crates.io-index |
| displaydoc | 0.2.7 | MIT OR Apache-2.0 | registry+https://github.com/rust-lang/crates.io-index | | displaydoc | 0.2.7 | MIT OR Apache-2.0 | registry+https://github.com/rust-lang/crates.io-index |
| earshot | 1.2.2 | MIT OR Apache-2.0 | registry+https://github.com/rust-lang/crates.io-index |
| eax | 0.5.0 | Apache-2.0 OR MIT | registry+https://github.com/rust-lang/crates.io-index | | eax | 0.5.0 | Apache-2.0 OR MIT | registry+https://github.com/rust-lang/crates.io-index |
| ecdsa | 0.16.9 | Apache-2.0 OR MIT | registry+https://github.com/rust-lang/crates.io-index | | ecdsa | 0.16.9 | Apache-2.0 OR MIT | registry+https://github.com/rust-lang/crates.io-index |
| either | 1.19.0 | MIT OR Apache-2.0 | registry+https://github.com/rust-lang/crates.io-index | | either | 1.19.0 | MIT OR Apache-2.0 | registry+https://github.com/rust-lang/crates.io-index |
@@ -253,7 +254,7 @@ platform build links), followed by the license texts shipped with those crates.
| zerovec-derive | 0.11.7 | Unicode-3.0 | registry+https://github.com/rust-lang/crates.io-index | | zerovec-derive | 0.11.7 | Unicode-3.0 | registry+https://github.com/rust-lang/crates.io-index |
| zmij | 1.0.23 | MIT | registry+https://github.com/rust-lang/crates.io-index | | zmij | 1.0.23 | MIT | registry+https://github.com/rust-lang/crates.io-index |
Crates whose package ships no license file (standard texts of their declared license are included below with the authors from their Cargo.toml): git-testament 0.2.6, git-testament-derive 0.2.1, jni 0.22.4, jni-macros 0.22.4, jni-sys-macros 0.4.1, ndk-context 0.1.1, quicklz 0.3.1, r-efi 6.0.0, valuable 0.1.1. Crates whose package ships no license file (standard texts of their declared license are included below with the authors from their Cargo.toml): earshot 1.2.2, git-testament 0.2.6, git-testament-derive 0.2.1, jni 0.22.4, jni-macros 0.22.4, jni-sys-macros 0.4.1, ndk-context 0.1.1, quicklz 0.3.1, r-efi 6.0.0, valuable 0.1.1.
## libopus (bundled in audiopus_sys, statically linked) ## libopus (bundled in audiopus_sys, statically linked)
@@ -2964,6 +2965,30 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
``` ```
### earshot 1.2.2 (no license file in package; standard MIT text, license MIT OR Apache-2.0)
```
Copyright (c) Carson M <carson@pyke.io>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
### eax 0.5.0 (LICENSE-MIT) ### eax 0.5.0 (LICENSE-MIT)
``` ```
+21
View File
@@ -84,6 +84,15 @@ impl AudioInQueue {
pub fn pop(&self) -> Option<AudioIn> { self.items.lock().expect("audio queue poisoned").pop_front() } pub fn pop(&self) -> Option<AudioIn> { self.items.lock().expect("audio queue poisoned").pop_front() }
/// Discards everything queued, e.g. frames captured under a previous transmit mode. Returns the number
/// of discarded frames (not counted as overflow drops).
pub fn clear(&self) -> usize {
let mut q = self.items.lock().expect("audio queue poisoned");
let frames = q.iter().filter(|i| matches!(i, AudioIn::Frame(_))).count();
q.clear();
frames
}
pub async fn notified(&self) { self.notify.notified().await } pub async fn notified(&self) { self.notify.notified().await }
/// Number of frames dropped since the last call. /// Number of frames dropped since the last call.
@@ -316,6 +325,18 @@ mod tests {
InAudioBuf::try_new(Direction::S2C, out.into_vec()).unwrap() InAudioBuf::try_new(Direction::S2C, out.into_vec()).unwrap()
} }
#[test]
fn clear_discards_queued_frames_without_counting_drops() {
let q = AudioInQueue::new();
for _ in 0..3 {
q.push(AudioIn::Frame(Box::new([1; FRAME_SAMPLES])));
}
q.push(AudioIn::End);
assert_eq!(q.clear(), 3);
assert!(q.pop().is_none());
assert_eq!(q.take_dropped(), 0);
}
#[test] #[test]
fn encode_decode_mix_roundtrip_both_codecs() { fn encode_decode_mix_roundtrip_both_codecs() {
for codec in [TxCodec::OpusVoice, TxCodec::OpusMusic] { for codec in [TxCodec::OpusVoice, TxCodec::OpusMusic] {
+175
View File
@@ -0,0 +1,175 @@
//! Decoding of stored TeamSpeak private keys that tolerates leading zero bytes.
//!
//! Upstream `tsproto_types::crypto::EccKeyPrivP256::from_tomcrypt` passes the DER integer's
//! minimal big-endian bytes to `from_short`, which requires exactly 32 bytes. A private scalar
//! whose top byte is 0x00 (about 1 key in 256) is therefore written fine by `to_ts` but can never
//! be read back. `private_key_from_tomcrypt` is upstream's decoder — the same `simple_asn1`
//! parser and the same block positions — with the single difference that the scalar is
//! left-padded to 32 bytes. The stored format is unchanged.
use base64::prelude::*;
use sha1::{Digest, Sha1};
use simple_asn1::{ASN1Block, BigInt};
use tsclientlib::Identity;
use tsproto_types::crypto::EccKeyPrivP256;
/// XOR mask TeamSpeak applies to identities in its settings/export files (same constant as
/// tsproto-types' `IDENTITY_OBFUSCATION`, MIT OR Apache-2.0).
const IDENTITY_OBFUSCATION: &[u8; 128] = b"b9dfaa7bee6ac57ac7b65f1094a1c155\
e747327bc2fe5d51c512023fe54a280201004e90ad1daaae1075d53b7d571c30e063b5a\
62a4a017bb394833aa0983e6e";
/// Private key from libtomcrypt DER: `SEQUENCE { BIT STRING flags, INTEGER size, INTEGER x,
/// INTEGER y, INTEGER priv }`, or the 2-bit variant `{ BIT STRING, INTEGER size, INTEGER priv }`.
pub fn private_key_from_tomcrypt(der: &[u8]) -> Result<EccKeyPrivP256, String> {
let blocks = simple_asn1::from_der(der).map_err(|e| format!("invalid DER: {e}"))?;
let [ASN1Block::Sequence(_, items)] = blocks.as_slice() else {
return Err("expected a single DER SEQUENCE".into());
};
let Some(ASN1Block::BitString(_, bit_count, flags)) = items.first() else {
return Err("expected BIT STRING".into());
};
if !flags.first().is_some_and(|f| f & 0x80 != 0) {
return Err("key has no private part".into());
}
let priv_index = match bit_count {
1 => 4,
2 => 2,
n => return Err(format!("unexpected flag bit count {n}")),
};
let Some(ASN1Block::Integer(_, scalar)) = items.get(priv_index) else {
return Err("missing private INTEGER".into());
};
if *scalar < BigInt::default() {
return Err("negative private scalar".into());
}
let (_, digits) = scalar.to_bytes_be();
if digits.len() > 32 {
return Err("private scalar longer than 32 bytes".into());
}
let mut short = [0u8; 32];
short[32 - digits.len()..].copy_from_slice(&digits);
EccKeyPrivP256::from_short(&short).map_err(|e| e.to_string())
}
/// Base64 libtomcrypt key as stored in `identity.json` (`EccKeyPrivP256::to_ts` output).
pub fn private_key_from_ts(b64: &str) -> Result<EccKeyPrivP256, String> {
let der = BASE64_STANDARD.decode(b64).map_err(|e| format!("not base64: {e}"))?;
private_key_from_tomcrypt(&der)
}
/// Reverse of `EccKeyPrivP256::to_ts_obfuscated`.
fn deobfuscate(b64: &str) -> Result<String, String> {
let mut data = BASE64_STANDARD.decode(b64).map_err(|e| format!("not base64: {e}"))?;
if data.len() < 20 {
return Err("obfuscated key too short".into());
}
let pos = data[20..].iter().position(|b| *b == 0).unwrap_or(data.len() - 20);
let hash = Sha1::digest(&data[20..20 + pos]);
for (d, h) in data.iter_mut().zip(hash.iter()).take(20) {
*d ^= h;
}
for (d, m) in data.iter_mut().zip(IDENTITY_OBFUSCATION.iter()).take(100) {
*d ^= m;
}
String::from_utf8(data).map_err(|_| "deobfuscated key is not text".into())
}
/// TeamSpeak identity string `<offset>V<key>` where `<key>` is the obfuscated form (TS client
/// exports) or plain base64 libtomcrypt DER.
pub fn identity_from_ts_str(value: &str) -> Result<Identity, String> {
let (counter, key) = value.split_once('V').ok_or("missing 'V' separator")?;
let counter: u64 = counter.parse().map_err(|_| "invalid key offset")?;
let key = private_key_from_ts(key)
.or_else(|plain_err| deobfuscate(key).and_then(|t| private_key_from_ts(&t)).map_err(|e| format!("{e} (as plain key: {plain_err})")))?;
Ok(Identity::new(key, counter))
}
#[cfg(test)]
pub mod tests {
use super::*;
use simple_asn1::{to_der, ASN1Block::*};
/// Valid P-256 scalars (non-zero, below the group order) covering every DER length case.
pub const ONE_LEADING_ZERO: [u8; 32] = scalar(1, 0x5a);
const THREE_LEADING_ZEROS: [u8; 32] = scalar(3, 0x5a);
/// Top bit set: DER needs a 0x00 sign byte (33 content bytes).
const SIGN_PADDED: [u8; 32] = scalar(0, 0x80);
/// Full width without sign byte (32 content bytes).
const FULL_WIDTH: [u8; 32] = scalar(0, 0x7f);
const fn scalar(zeros: usize, first: u8) -> [u8; 32] {
let mut s = [0x5au8; 32];
let mut i = 0;
while i < zeros {
s[i] = 0;
i += 1;
}
s[zeros] = first;
s
}
pub fn key(s: &[u8; 32]) -> EccKeyPrivP256 { EccKeyPrivP256::from_short(s).unwrap() }
#[test]
fn fixed_scalars_roundtrip_in_every_stored_form() {
for s in [ONE_LEADING_ZERO, THREE_LEADING_ZEROS, SIGN_PADDED, FULL_WIDTH] {
let k = key(&s);
let ts = k.to_ts();
assert_eq!(private_key_from_ts(&ts).unwrap().to_short().as_slice(), s.as_slice());
let id = identity_from_ts_str(&format!("42V{}", k.to_ts_obfuscated())).unwrap();
assert_eq!(id.key().to_short().as_slice(), s.as_slice());
assert_eq!(id.counter(), 42);
assert_eq!(identity_from_ts_str(&format!("7V{ts}")).unwrap().key().to_short().as_slice(), s.as_slice());
}
}
#[test]
fn upstream_test_vector_and_garbage() {
// Vector from tsproto's own tests (TS client identity), UID known.
const KEY: &str = "MG8DAgeAAgEgAiEA6rtKxDn/o/Bo50rNtAE5Ph3h2RKLHQ0gbFkvm2yA79kCIQCrfzAZts/vHP+3MOetKLjNnpZXt4c6U3UB4gWLKR4H9AIgYTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=";
let k = private_key_from_ts(KEY).unwrap();
assert_eq!(k.to_pub().get_uid(), "test/9PZ9vww/Bpf5vJxtJhpz80=");
for bad in ["", "AAAA", "MAA=", "not base64!"] {
assert!(private_key_from_ts(bad).is_err(), "{bad}");
}
assert!(identity_from_ts_str("xVabc").is_err());
assert!(identity_from_ts_str("1Vgarbage").is_err());
}
fn int(v: &[u8]) -> ASN1Block { Integer(0, BigInt::from_signed_bytes_be(v)) }
/// libtomcrypt layout with a 1-bit flag string; `priv_value` goes into the private slot.
fn der_with(flags: ASN1Block, priv_value: ASN1Block) -> Vec<u8> {
to_der(&Sequence(0, vec![flags, int(&[32]), int(&[1]), int(&[2]), priv_value])).unwrap()
}
#[test]
fn malformed_keys_are_errors_not_panics() {
let good = key(&ONE_LEADING_ZERO).to_tomcrypt();
assert!(private_key_from_tomcrypt(&good).is_ok());
let private_flag = || BitString(0, 1, vec![0x80]);
let mut cases: Vec<(&str, Vec<u8>)> = vec![
("truncated", good[..good.len() - 1].to_vec()),
("trailing block", [good.clone(), vec![0x05, 0x00]].concat()),
("not a sequence", to_der(&int(&[1])).unwrap()),
("empty sequence", to_der(&Sequence(0, vec![])).unwrap()),
("first item not a BIT STRING", to_der(&Sequence(0, vec![int(&[1]), int(&[1])])).unwrap()),
("public-only flag", der_with(BitString(0, 1, vec![0x00]), int(&ONE_LEADING_ZERO))),
("empty BIT STRING", der_with(BitString(0, 0, vec![]), int(&ONE_LEADING_ZERO))),
("3-bit flags", der_with(BitString(0, 3, vec![0x80]), int(&ONE_LEADING_ZERO))),
("private slot missing", to_der(&Sequence(0, vec![private_flag(), int(&[32])])).unwrap()),
("private slot not INTEGER", der_with(private_flag(), OctetString(0, ONE_LEADING_ZERO.to_vec()))),
("negative scalar", der_with(private_flag(), int(&[0xff]))),
("zero scalar", der_with(private_flag(), int(&[0]))),
("scalar above the group order", der_with(private_flag(), int(&[[0u8].as_slice(), &[0xff; 32]].concat()))),
("33-byte scalar", der_with(private_flag(), int(&[[0x01u8].as_slice(), &[0x5a; 32]].concat()))),
];
// Raw BIT STRING whose unused-bit count exceeds its length, and one with an empty INTEGER.
cases.push(("unused bits > length", vec![0x30, 0x04, 0x03, 0x02, 0x09, 0x80]));
cases.push(("empty INTEGER", vec![0x30, 0x0f, 0x03, 0x02, 0x07, 0x80, 0x02, 0x01, 0x20, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02, 0x02, 0x00]));
for (name, der) in cases {
assert!(private_key_from_tomcrypt(&der).is_err(), "{name}");
}
}
}
+2
View File
@@ -2,6 +2,7 @@
//! Contract: `docs/bridge.md`. //! Contract: `docs/bridge.md`.
mod audio; mod audio;
mod keyfmt;
mod media; mod media;
mod profile; mod profile;
mod protocol; mod protocol;
@@ -10,6 +11,7 @@ mod secure_fs;
mod session; mod session;
mod snapshot; mod snapshot;
mod stdio; mod stdio;
mod vad;
use std::fs::{File, OpenOptions, TryLockError}; use std::fs::{File, OpenOptions, TryLockError};
use std::io::{Read, Write}; use std::io::{Read, Write};
+21 -4
View File
@@ -132,7 +132,7 @@ impl Store {
if file.version != FORMAT_VERSION { if file.version != FORMAT_VERSION {
return Err(self.corrupt_identity(format!("unsupported version {}", file.version))); return Err(self.corrupt_identity(format!("unsupported version {}", file.version)));
} }
let key = EccKeyPrivP256::from_ts(&file.private_key) let key = crate::keyfmt::private_key_from_ts(&file.private_key)
.map_err(|e| self.corrupt_identity(format!("invalid private key: {e}")))?; .map_err(|e| self.corrupt_identity(format!("invalid private key: {e}")))?;
let uid = uid_of(&key); let uid = uid_of(&key);
if uid != file.uid { if uid != file.uid {
@@ -254,7 +254,7 @@ impl Store {
} }
} }
let value = identity_value.ok_or_else(|| StoreError::ImportInvalid("no identity= entry".into()))?; let value = identity_value.ok_or_else(|| StoreError::ImportInvalid("no identity= entry".into()))?;
let identity = Identity::new_from_ts_str(&value) let identity = crate::keyfmt::identity_from_ts_str(&value)
.map_err(|e| StoreError::ImportInvalid(format!("cannot decode identity: {e}")))?; .map_err(|e| StoreError::ImportInvalid(format!("cannot decode identity: {e}")))?;
let nickname = match nickname { let nickname = match nickname {
Some(n) => Some(validate_nickname(&n)?), Some(n) => Some(validate_nickname(&n)?),
@@ -303,7 +303,7 @@ pub mod tests {
assert!(created.security_level() >= NEW_IDENTITY_LEVEL); assert!(created.security_level() >= NEW_IDENTITY_LEVEL);
let identity_bytes = fs::read(dir.0.join(IDENTITY_FILE)).unwrap(); 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(); store.save_nickname(name).unwrap();
// "Restart": a fresh store instance reads everything from disk. // "Restart": a fresh store instance reads everything from disk.
let reopened = Store::new(&dir.0); let reopened = Store::new(&dir.0);
@@ -370,7 +370,7 @@ pub mod tests {
assert!(validate_nickname(" ab ").is_err()); assert!(validate_nickname(" ab ").is_err());
assert!(validate_nickname(&"x".repeat(31)).is_err()); assert!(validate_nickname(&"x".repeat(31)).is_err());
assert!(validate_nickname("bad\nname").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 dir = TempDir::new("nick");
let store = Store::new(&dir.0); let store = Store::new(&dir.0);
assert!(matches!(store.create("x"), Err(StoreError::InvalidNickname(_)))); assert!(matches!(store.create("x"), Err(StoreError::InvalidNickname(_))));
@@ -386,6 +386,23 @@ pub mod tests {
assert!(matches!(store.load_nickname(), Err(StoreError::ProfileCorrupt { .. }))); assert!(matches!(store.load_nickname(), Err(StoreError::ProfileCorrupt { .. })));
} }
#[test]
fn zero_leading_private_key_loads_and_imports() {
let dir = TempDir::new("zerolead");
let store = Store::new(&dir.0);
let key = crate::keyfmt::tests::key(&crate::keyfmt::tests::ONE_LEADING_ZERO);
let mut identity = Identity::new(key, 0);
identity.upgrade_level(NEW_IDENTITY_LEVEL);
let uid = store.write_identity(&identity).unwrap();
store.save_nickname("ZeroLead").unwrap();
let loaded = store.load_identity().unwrap().unwrap();
assert_eq!(loaded.uid, uid);
assert_eq!(loaded.identity.key().to_short(), identity.key().to_short());
let (ini, _) = store.export_ts_ini().unwrap();
let other = TempDir::new("zerolead-import");
assert_eq!(Store::new(&other.0).import_ts_ini(&ini, false).unwrap(), uid);
}
#[test] #[test]
fn upgraded_key_offset_keeps_uid() { fn upgraded_key_offset_keeps_uid() {
let dir = TempDir::new("upgrade"); let dir = TempDir::new("upgrade");
+41
View File
@@ -8,6 +8,8 @@ use serde::{Deserialize, Serialize};
use serde_json::value::RawValue; use serde_json::value::RawValue;
use serde_json::Value; use serde_json::Value;
use crate::vad::Sensitivity;
pub const PROTOCOL_VERSION: u32 = 1; pub const PROTOCOL_VERSION: u32 = 1;
/// Maximum accepted stdin line (bytes, without the newline). /// Maximum accepted stdin line (bytes, without the newline).
pub const MAX_LINE_BYTES: usize = 256 * 1024; pub const MAX_LINE_BYTES: usize = 256 * 1024;
@@ -108,6 +110,8 @@ pub enum Command {
JoinChannel { channel_id: u64, password: Option<String> }, JoinChannel { channel_id: u64, password: Option<String> },
SendText { target: TextTarget, client_id: Option<u16>, message: String }, SendText { target: TextTarget, client_id: Option<u16>, message: String },
SetAudio { input_muted: Option<bool>, output_muted: Option<bool> }, SetAudio { input_muted: Option<bool>, output_muted: Option<bool> },
/// `None` = direct transmission (push-to-talk / open microphone decided by the caller).
SetTransmit { vad: Option<Sensitivity> },
StreamList { client_id: Option<u16> }, StreamList { client_id: Option<u16> },
StreamJoin { stream_id: String, client_id: u16, message: Option<String> }, StreamJoin { stream_id: String, client_id: u16, message: Option<String> },
/// `json` is already compact-serialized and size checked. /// `json` is already compact-serialized and size checked.
@@ -131,6 +135,7 @@ impl Command {
Command::JoinChannel { .. } => "join_channel", Command::JoinChannel { .. } => "join_channel",
Command::SendText { .. } => "send_text", Command::SendText { .. } => "send_text",
Command::SetAudio { .. } => "set_audio", Command::SetAudio { .. } => "set_audio",
Command::SetTransmit { .. } => "set_transmit",
Command::StreamList { .. } => "stream_list", Command::StreamList { .. } => "stream_list",
Command::StreamJoin { .. } => "stream_join", Command::StreamJoin { .. } => "stream_join",
Command::StreamSignal { .. } => "stream_signal", Command::StreamSignal { .. } => "stream_signal",
@@ -211,6 +216,14 @@ struct SendTextArgs {
message: String, message: String,
} }
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SetTransmitArgs {
mode: String,
#[serde(default)]
sensitivity: Option<String>,
}
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
struct SetAudioArgs { struct SetAudioArgs {
@@ -425,6 +438,19 @@ fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result<Command, ErrorObj>
let a: SetAudioArgs = args_owned(raw)?; let a: SetAudioArgs = args_owned(raw)?;
Command::SetAudio { input_muted: a.input_muted, output_muted: a.output_muted } Command::SetAudio { input_muted: a.input_muted, output_muted: a.output_muted }
} }
"set_transmit" => {
let a: SetTransmitArgs = args_owned(raw)?;
let vad = match (a.mode.as_str(), a.sensitivity.as_deref()) {
("direct", None) => None,
("direct", Some(_)) => return Err(bad("set_transmit: sensitivity applies to mode 'vad' only")),
("vad", None | Some("normal")) => Some(Sensitivity::Normal),
("vad", Some("high")) => Some(Sensitivity::High),
("vad", Some("low")) => Some(Sensitivity::Low),
("vad", Some(_)) => return Err(bad("set_transmit: sensitivity must be 'high', 'normal' or 'low'")),
_ => return Err(bad("set_transmit: mode must be 'direct' or 'vad'")),
};
Command::SetTransmit { vad }
}
"stream_list" => Command::StreamList { client_id: args_owned::<StreamListArgs>(raw)?.client_id }, "stream_list" => Command::StreamList { client_id: args_owned::<StreamListArgs>(raw)?.client_id },
"stream_join" => { "stream_join" => {
let a: StreamJoinArgs = args_owned(raw)?; let a: StreamJoinArgs = args_owned(raw)?;
@@ -511,6 +537,21 @@ mod tests {
} }
} }
#[test]
fn set_transmit_modes_and_sensitivities() {
let parse = |args: &str| parse_line(&format!(r#"{{"id":"t","cmd":"set_transmit","args":{args}}}"#));
assert!(matches!(parse(r#"{"mode":"direct"}"#), Input::Request { cmd: Command::SetTransmit { vad: None }, .. }));
assert!(matches!(parse(r#"{"mode":"vad"}"#), Input::Request { cmd: Command::SetTransmit { vad: Some(Sensitivity::Normal) }, .. }));
assert!(matches!(parse(r#"{"mode":"vad","sensitivity":"high"}"#), Input::Request { cmd: Command::SetTransmit { vad: Some(Sensitivity::High) }, .. }));
assert!(matches!(parse(r#"{"mode":"vad","sensitivity":"low"}"#), Input::Request { cmd: Command::SetTransmit { vad: Some(Sensitivity::Low) }, .. }));
for bad in [r#"{"mode":"open"}"#, r#"{"mode":"direct","sensitivity":"low"}"#, r#"{"mode":"vad","sensitivity":"max"}"#, r#"{"mode":"vad","threshold":0.1}"#, r#"{}"#] {
match parse(bad) {
Input::Invalid { error, .. } => assert_eq!(error.code, ErrorCode::BadRequest, "{bad}"),
other => panic!("{bad}: {other:?}"),
}
}
}
#[test] #[test]
fn requests_need_valid_id_and_known_args() { fn requests_need_valid_id_and_known_args() {
assert!(matches!( assert!(matches!(
+139 -34
View File
@@ -20,6 +20,7 @@ use tsclientlib::messages::c2s::{OutInitDownloadMessage, OutInitDownloadPart};
use tsproto_packets::packets::OutCommand; use tsproto_packets::packets::OutCommand;
use crate::audio::{self, AudioIn, AudioInQueue, Receiver, RxEvent, TxCodec, TxEncoder}; use crate::audio::{self, AudioIn, AudioInQueue, Receiver, RxEvent, TxCodec, TxEncoder};
use crate::vad::{Decision, Sensitivity, VoiceGate, MAX_PREROLL_FRAMES};
use crate::media::{self, MediaKind}; use crate::media::{self, MediaKind};
use crate::profile::{validate_nickname, Store, StoreError, StoredIdentity}; use crate::profile::{validate_nickname, Store, StoreError, StoredIdentity};
use crate::protocol::{Command, ConnectArgs, ErrorCode, ErrorObj, Frame, Input, TextTarget, TsErrorInfo, FRAME_SAMPLES}; use crate::protocol::{Command, ConnectArgs, ErrorCode, ErrorObj, Frame, Input, TextTarget, TsErrorInfo, FRAME_SAMPLES};
@@ -156,11 +157,12 @@ struct FtJob {
impl Conn { impl Conn {
fn connected(&self) -> bool { matches!(self.phase, Phase::Connected) } fn connected(&self) -> bool { matches!(self.phase, Phase::Connected) }
fn own_channel_codec(&self) -> Option<(tsclientlib::Codec, u8)> { /// Own channel id, codec and codec quality.
fn own_channel_codec(&self) -> Option<(u64, tsclientlib::Codec, u8)> {
let book = self.con.get_state().ok()?; let book = self.con.get_state().ok()?;
let me = book.clients.get(&book.own_client)?; let me = book.clients.get(&book.own_client)?;
let ch = book.channels.get(&me.channel)?; let ch = book.channels.get(&me.channel)?;
Some((ch.codec, ch.codec_quality.unwrap_or(DEFAULT_CODEC_QUALITY))) Some((me.channel.0, ch.codec, ch.codec_quality.unwrap_or(DEFAULT_CODEC_QUALITY)))
} }
fn send(&mut self, cmd: impl OutCommandExt) -> Result<u16, tsclientlib::Error> { fn send(&mut self, cmd: impl OutCommandExt) -> Result<u16, tsclientlib::Error> {
@@ -178,6 +180,14 @@ struct Tx {
last_overflow_report: Option<Instant>, last_overflow_report: Option<Instant>,
} }
/// Voice activation state; present only in the "vad" transmit mode.
struct VadState {
gate: VoiceGate,
/// Channel and codec the gate's audio belongs to; a change resets the gate so nothing heard before
/// it is sent afterwards.
route: Option<(u64, TxCodec, u8)>,
}
enum Exit { enum Exit {
Running, Running,
Requested { req: Option<String> }, Requested { req: Option<String> },
@@ -191,6 +201,9 @@ pub struct Session {
flags: AudioFlags, flags: AudioFlags,
conn: Option<Conn>, conn: Option<Conn>,
tx: Tx, tx: Tx,
/// `None` = direct transmission: every frame the renderer forwards is sent.
vad: Option<Box<VadState>>,
preroll_buf: Box<[Frame; MAX_PREROLL_FRAMES]>,
pcm: Box<[i16; FRAME_SAMPLES]>, pcm: Box<[i16; FRAME_SAMPLES]>,
rev: u64, rev: u64,
exit: Exit, exit: Exit,
@@ -218,6 +231,8 @@ impl Session {
flags: AudioFlags::default(), flags: AudioFlags::default(),
conn: None, conn: None,
tx: Tx::default(), tx: Tx::default(),
vad: None,
preroll_buf: Box::new([[0; FRAME_SAMPLES]; MAX_PREROLL_FRAMES]),
pcm: Box::new([0; FRAME_SAMPLES]), pcm: Box::new([0; FRAME_SAMPLES]),
rev: 0, rev: 0,
exit: Exit::Running, exit: Exit::Running,
@@ -346,6 +361,7 @@ impl Session {
Command::JoinChannel { channel_id, password } => self.join_channel(&id, channel_id, password), Command::JoinChannel { channel_id, password } => self.join_channel(&id, channel_id, password),
Command::SendText { target, client_id, message } => self.send_text(&id, target, client_id, &message), Command::SendText { target, client_id, message } => self.send_text(&id, target, client_id, &message),
Command::SetAudio { input_muted, output_muted } => self.set_audio(&id, input_muted, output_muted).await, Command::SetAudio { input_muted, output_muted } => self.set_audio(&id, input_muted, output_muted).await,
Command::SetTransmit { vad } => self.set_transmit(vad).await.map(Some),
Command::StreamList { client_id } => self.stream_list(&id, client_id).await, Command::StreamList { client_id } => self.stream_list(&id, client_id).await,
Command::StreamJoin { stream_id, client_id, message } => { Command::StreamJoin { stream_id, client_id, message } => {
self.stream_join(&id, &stream_id, client_id, message) self.stream_join(&id, &stream_id, client_id, message)
@@ -1189,38 +1205,107 @@ impl Session {
} }
} }
/// Applies the transmit mode. Frames still queued from the previous mode are discarded and any open
/// burst is ended before the answer, so nothing captured under the old mode is sent under the new one.
async fn set_transmit(&mut self, vad: Option<Sensitivity>) -> Result<Value, ErrorObj> {
let discarded = self.audio_in.clear();
self.tx_end().await;
match (vad, self.vad.as_mut()) {
(None, _) => self.vad = None,
(Some(s), Some(state)) => state.gate.set_sensitivity(s),
(Some(s), None) => self.vad = Some(Box::new(VadState { gate: VoiceGate::new(s), route: None })),
}
let result = match vad {
None => json!({ "mode": "direct" }),
Some(s) => json!({ "mode": "vad", "sensitivity": s.name() }),
};
info!(mode = %result["mode"], sensitivity = %result["sensitivity"], discarded, "transmit mode applied");
Ok(result)
}
/// Checks every condition for sending voice right now and returns the own channel id, codec and
/// quality; reports the first failing condition once per burst.
async fn tx_route(&mut self) -> Option<(u64, TxCodec, u8)> {
let flags = self.flags;
let Some(c) = self.conn.as_mut().filter(|c| c.connected()) else {
self.report_once(ErrorObj::new(ErrorCode::NotConnected, "audio_frame while not connected; frames dropped")).await;
return None;
};
if flags.input_muted || flags.output_muted {
self.report_once(ErrorObj::new(ErrorCode::AudioMuted, "audio_frame while muted or deafened; frames dropped")).await;
return None;
}
let Some((channel, codec, quality)) = c.own_channel_codec() else {
self.report_once(ErrorObj::new(ErrorCode::Internal, "own channel is unknown")).await;
return None;
};
let Some(tx_codec) = TxCodec::for_channel(codec) else {
self.report_once(
ErrorObj::new(
ErrorCode::AudioCodecUnsupported,
format!("channel codec {} is not supported for sending (Opus only)", audio::codec_name(codec)),
)
.with_detail(json!({ "codec": audio::codec_name(codec) })),
)
.await;
return None;
};
if !c.con.can_send_audio() {
self.report_once(ErrorObj::new(
ErrorCode::AudioMuted,
"the server does not let this client talk here (talk power, away or server mute); frames dropped",
))
.await;
return None;
}
Some((channel, tx_codec, quality))
}
async fn tx_frame(&mut self, frame: &Frame) { async fn tx_frame(&mut self, frame: &Frame) {
self.tx.burst_open = true; self.tx.burst_open = true;
self.tx.last_frame = Some(Instant::now()); self.tx.last_frame = Some(Instant::now());
let flags = self.flags; let Some(route) = self.tx_route().await else {
let Some(c) = self.conn.as_mut().filter(|c| c.connected()) else { // Nothing may be sent now; forget what voice activation heard so it is never sent later.
return self.report_once(ErrorObj::new(ErrorCode::NotConnected, "audio_frame while not connected; frames dropped")).await; self.vad_reset();
self.end_spurt().await;
return;
}; };
if flags.input_muted || flags.output_muted { let (_, tx_codec, quality) = route;
return self.report_once(ErrorObj::new(ErrorCode::AudioMuted, "audio_frame while muted or deafened; frames dropped")).await; let Some(vad) = self.vad.as_mut() else {
self.tx_send(frame, tx_codec, quality).await;
return;
};
if vad.route != Some(route) {
vad.gate.reset();
vad.route = Some(route);
} }
let Some((codec, quality)) = c.own_channel_codec() else { let decision = vad.gate.push(frame);
return self.report_once(ErrorObj::new(ErrorCode::Internal, "own channel is unknown")).await; let held = if decision == Decision::Start { vad.gate.take_preroll(&mut self.preroll_buf) } else { 0 };
}; match decision {
let Some(tx_codec) = TxCodec::for_channel(codec) else { Decision::Hold => {}
return self Decision::Start => {
.report_once( for i in 0..held {
ErrorObj::new( let earlier = self.preroll_buf[i];
ErrorCode::AudioCodecUnsupported, if !self.tx_send(&earlier, tx_codec, quality).await {
format!("channel codec {} is not supported for sending (Opus only)", audio::codec_name(codec)), return;
) }
.with_detail(json!({ "codec": audio::codec_name(codec) })), }
) self.tx_send(frame, tx_codec, quality).await;
.await; }
}; Decision::Send => {
if !c.con.can_send_audio() { self.tx_send(frame, tx_codec, quality).await;
return self }
.report_once(ErrorObj::new( Decision::SendAndEnd => {
ErrorCode::AudioMuted, if self.tx_send(frame, tx_codec, quality).await {
"the server does not let this client talk here (talk power, away or server mute); frames dropped", self.end_spurt().await;
)) }
.await; }
} }
}
/// Encodes and sends one frame; returns false if it could not be sent (reported once per burst).
async fn tx_send(&mut self, frame: &Frame, tx_codec: TxCodec, quality: u8) -> bool {
let Some(c) = self.conn.as_mut().filter(|c| c.connected()) else { return false };
if !self.tx.encoder.as_ref().is_some_and(|e| e.matches(tx_codec, quality)) { if !self.tx.encoder.as_ref().is_some_and(|e| e.matches(tx_codec, quality)) {
if let (true, Some(old)) = (self.tx.transmitting, &self.tx.encoder) { if let (true, Some(old)) = (self.tx.transmitting, &self.tx.encoder) {
let _ = c.con.send_audio(audio::end_of_voice(old.codec())); let _ = c.con.send_audio(audio::end_of_voice(old.codec()));
@@ -1228,27 +1313,39 @@ impl Session {
match TxEncoder::new(tx_codec, quality) { match TxEncoder::new(tx_codec, quality) {
Ok(e) => self.tx.encoder = Some(e), Ok(e) => self.tx.encoder = Some(e),
Err(e) => { Err(e) => {
return self.report_once(ErrorObj::new(ErrorCode::AudioCodec, format!("creating Opus encoder: {e}"))).await; self.report_once(ErrorObj::new(ErrorCode::AudioCodec, format!("creating Opus encoder: {e}"))).await;
return false;
} }
} }
} }
let encoder = self.tx.encoder.as_mut().expect("set above"); let encoder = self.tx.encoder.as_mut().expect("set above");
let packet = match encoder.encode(frame) { let packet = match encoder.encode(frame) {
Ok(p) => p, Ok(p) => p,
Err(e) => return self.report_once(ErrorObj::new(ErrorCode::AudioCodec, format!("Opus encode failed: {e}"))).await, Err(e) => {
self.report_once(ErrorObj::new(ErrorCode::AudioCodec, format!("Opus encode failed: {e}"))).await;
return false;
}
}; };
if let Err(e) = c.con.send_audio(packet) { if let Err(e) = c.con.send_audio(packet) {
return self.report_once(lib_error(ErrorCode::Io, &e)).await; self.report_once(lib_error(ErrorCode::Io, &e)).await;
return false;
} }
if !self.tx.transmitting { if !self.tx.transmitting {
self.tx.transmitting = true; self.tx.transmitting = true;
self.emit_audio_state().await; self.emit_audio_state().await;
} }
true
} }
async fn tx_end(&mut self) { fn vad_reset(&mut self) {
self.tx.burst_open = false; if let Some(state) = self.vad.as_mut() {
self.tx.reported = false; state.gate.reset();
state.route = None;
}
}
/// Ends the current talk spurt (end-of-voice packet, `transmitting: false`) if one is open.
async fn end_spurt(&mut self) {
if !self.tx.transmitting { if !self.tx.transmitting {
return; return;
} }
@@ -1263,6 +1360,14 @@ impl Session {
self.emit_audio_state().await; self.emit_audio_state().await;
} }
/// The renderer stopped sending (audio_end, mute, deafen, disconnect, capture stopped, timeout).
async fn tx_end(&mut self) {
self.tx.burst_open = false;
self.tx.reported = false;
self.vad_reset();
self.end_spurt().await;
}
async fn on_tick(&mut self) { async fn on_tick(&mut self) {
let now = Instant::now(); let now = Instant::now();
if self.tx.burst_open && self.tx.last_frame.is_some_and(|t| now - t > BURST_TIMEOUT) { if self.tx.burst_open && self.tx.last_frame.is_some_and(|t| now - t > BURST_TIMEOUT) {
+644
View File
@@ -0,0 +1,644 @@
//! Voice activation: decides which captured 20 ms frames are sent when the user chose "voice activation".
//!
//! The detector is earshot (pure Rust, MIT OR Apache-2.0): a small embedded neural network that returns
//! a voice probability for every 16 ms window of 16 kHz mono audio. It is a statistical detector, not a
//! speech recogniser: loud speech-like noise can open the gate and quiet speech under heavy noise can be
//! missed. The input has already passed Chromium's WebRTC capture processing (noise suppression, echo
//! cancellation, gain control as configured by the user).
//!
//! All buffers are fixed-size and allocated once when the gate is created; processing a frame does not
//! allocate.
use earshot::Detector;
use crate::protocol::{Frame, FRAME_SAMPLES};
/// Frames kept from before the onset so the start of a word is not cut off (5 × 20 ms = 100 ms).
pub const PREROLL_FRAMES: usize = 5;
/// Frames sent after the last voiced frame so word endings and short pauses are kept (400 ms).
pub const HANGOVER_FRAMES: u32 = 20;
/// While a spurt is open, a window keeps it open at this much below the opening threshold.
pub const RELEASE_MARGIN: f32 = 0.15;
/// Consecutive voiced detector windows (16 ms each) needed to open the gate.
pub const ONSET_WINDOWS: u32 = 3;
/// Frames after a reset during which the gate cannot open: a freshly reset network scores the first
/// ~150 ms of any input (noise, clicks) higher than it settles to. Nothing heard in that time is lost:
/// every frame since the reset is kept (see [`MAX_PREROLL_FRAMES`]) and sent if speech opens the gate.
pub const WARMUP_FRAMES: u32 = 10;
/// Frames held at most: the whole warm-up plus the normal preroll (300 ms). The first spurt after a
/// reset sends everything since the reset; later spurts send the last [`PREROLL_FRAMES`].
pub const MAX_PREROLL_FRAMES: usize = WARMUP_FRAMES as usize + PREROLL_FRAMES;
/// Detector input: 16 ms at 16 kHz.
const WINDOW: usize = 256;
/// 48 kHz → 16 kHz.
const DECIMATION: usize = 3;
const OUT_PER_FRAME: usize = FRAME_SAMPLES / DECIMATION;
/// Anti-aliasing low-pass in front of the decimation (odd length, linear phase).
const TAPS: usize = 63;
const HISTORY: usize = TAPS - 1;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Sensitivity {
High,
Normal,
Low,
}
impl Sensitivity {
/// Voice probability a detector window needs to count as voiced.
pub fn threshold(self) -> f32 {
match self {
Sensitivity::High => 0.45,
Sensitivity::Normal => 0.6,
Sensitivity::Low => 0.75,
}
}
pub fn name(self) -> &'static str {
match self {
Sensitivity::High => "high",
Sensitivity::Normal => "normal",
Sensitivity::Low => "low",
}
}
}
/// What to do with the frame just pushed.
#[derive(Debug, PartialEq, Eq)]
pub enum Decision {
/// Not speech: keep it only as possible preroll.
Hold,
/// Speech starts: send the returned preroll frames (oldest first), then the current frame.
Start,
/// Inside a talk spurt: send the current frame.
Send,
/// Send the current frame, then end the talk spurt (hangover ran out).
SendAndEnd,
}
/// 48 kHz → 16 kHz decimator whose filter history carries over between 960-sample frames.
struct Decimator {
coeffs: [f32; TAPS],
/// The last `HISTORY` input samples of the previous frame, then the current frame.
buf: [f32; HISTORY + FRAME_SAMPLES],
}
impl Decimator {
fn new() -> Self {
// Windowed sinc (Blackman), cut-off 7 kHz at 48 kHz, unity gain at DC.
let fc = 7_000.0_f64 / 48_000.0;
let m = (TAPS - 1) as f64;
let mut c = [0.0_f64; TAPS];
for (i, v) in c.iter_mut().enumerate() {
let x = i as f64 - m / 2.0;
let sinc = if x == 0.0 { 2.0 * fc } else { (2.0 * std::f64::consts::PI * fc * x).sin() / (std::f64::consts::PI * x) };
let w = 0.42 - 0.5 * (2.0 * std::f64::consts::PI * i as f64 / m).cos() + 0.08 * (4.0 * std::f64::consts::PI * i as f64 / m).cos();
*v = sinc * w;
}
let sum: f64 = c.iter().sum();
let mut coeffs = [0.0_f32; TAPS];
for (o, v) in coeffs.iter_mut().zip(c) {
*o = (v / sum) as f32;
}
Self { coeffs, buf: [0.0; HISTORY + FRAME_SAMPLES] }
}
fn reset(&mut self) { self.buf = [0.0; HISTORY + FRAME_SAMPLES]; }
/// Decimates one 20 ms frame into `out` (320 samples). The low-pass can overshoot full-scale input
/// slightly (ringing), so outputs are clamped to [-1, 1], the range the detector expects.
fn process(&mut self, frame: &Frame, out: &mut [f32; OUT_PER_FRAME]) {
for (dst, s) in self.buf[HISTORY..].iter_mut().zip(frame.iter()) {
*dst = f32::from(*s) / 32_768.0;
}
// Output k uses the TAPS inputs ending at input sample 3k (+2 to stay causal within the frame).
for (k, o) in out.iter_mut().enumerate() {
let end = HISTORY + k * DECIMATION + (DECIMATION - 1);
let window = &self.buf[end + 1 - TAPS..=end];
let y: f32 = window.iter().zip(self.coeffs.iter()).map(|(x, c)| x * c).sum();
*o = y.clamp(-1.0, 1.0);
}
self.buf.copy_within(FRAME_SAMPLES.., 0);
}
}
pub struct VoiceGate {
detector: Box<Detector>,
decimator: Decimator,
threshold: f32,
sensitivity: Sensitivity,
/// 16 kHz samples waiting for a full detector window.
pending: [f32; WINDOW],
pending_len: usize,
resampled: [f32; OUT_PER_FRAME],
voiced_run: u32,
/// Frames left before the spurt ends; 0 = idle.
hangover: u32,
preroll: [Frame; MAX_PREROLL_FRAMES],
preroll_start: usize,
preroll_len: usize,
/// Frames left in the post-reset warm-up.
warmup: u32,
/// True from a reset until the first spurt opens: that spurt gets every frame held since the reset.
since_reset: bool,
}
impl VoiceGate {
pub fn new(sensitivity: Sensitivity) -> Self {
let mut gate = Self {
detector: Detector::default_boxed(),
decimator: Decimator::new(),
threshold: sensitivity.threshold(),
sensitivity,
pending: [0.0; WINDOW],
pending_len: 0,
resampled: [0.0; OUT_PER_FRAME],
voiced_run: 0,
hangover: 0,
preroll: [[0; FRAME_SAMPLES]; MAX_PREROLL_FRAMES],
preroll_start: 0,
preroll_len: 0,
warmup: WARMUP_FRAMES,
since_reset: true,
};
gate.reset();
gate
}
#[cfg(test)]
pub fn sensitivity(&self) -> Sensitivity { self.sensitivity }
pub fn set_sensitivity(&mut self, sensitivity: Sensitivity) {
self.sensitivity = sensitivity;
self.threshold = sensitivity.threshold();
}
#[cfg(test)]
pub fn is_active(&self) -> bool { self.hangover > 0 }
/// Forgets everything heard so far: detector state, filter history, preroll and any open spurt.
/// Called at privacy and routing boundaries only (mode change, mute/deafen, capture end, disconnect,
/// channel/codec/permission change), never at the natural end of a spurt.
pub fn reset(&mut self) {
self.detector.reset();
self.warmup = WARMUP_FRAMES;
self.since_reset = true;
self.decimator.reset();
self.pending_len = 0;
self.voiced_run = 0;
self.hangover = 0;
self.preroll_len = 0;
self.preroll_start = 0;
}
/// Runs the detector over one frame and returns whether any 16 ms window in it was voiced and
/// whether the onset condition is met. While a spurt is open, windows count as voiced down to
/// [`RELEASE_MARGIN`] below the threshold (hysteresis), so quieter syllables do not end it.
fn detect(&mut self, frame: &Frame) -> (bool, bool) {
self.decimator.process(frame, &mut self.resampled);
let keep = if self.hangover > 0 { self.threshold - RELEASE_MARGIN } else { self.threshold };
let mut voiced = false;
let mut onset = false;
let mut i = 0;
while i < OUT_PER_FRAME {
let take = (WINDOW - self.pending_len).min(OUT_PER_FRAME - i);
self.pending[self.pending_len..self.pending_len + take].copy_from_slice(&self.resampled[i..i + take]);
self.pending_len += take;
i += take;
if self.pending_len == WINDOW {
self.pending_len = 0;
let score = self.detector.predict_f32(&self.pending);
if score >= keep {
voiced = true;
}
if score >= self.threshold {
self.voiced_run = (self.voiced_run + 1).min(ONSET_WINDOWS);
if self.voiced_run >= ONSET_WINDOWS {
onset = true;
}
} else {
self.voiced_run = 0;
}
}
}
(voiced, onset)
}
/// Classifies `frame`. On [`Decision::Start`], the caller sends [`VoiceGate::take_preroll`] and then
/// `frame`; the current frame is never part of the preroll.
pub fn push(&mut self, frame: &Frame) -> Decision {
let (voiced, onset) = self.detect(frame);
if self.hangover > 0 {
if voiced {
self.hangover = HANGOVER_FRAMES;
return Decision::Send;
}
self.hangover -= 1;
return if self.hangover == 0 { Decision::SendAndEnd } else { Decision::Send };
}
if self.warmup > 0 {
self.warmup -= 1;
} else if onset {
self.hangover = HANGOVER_FRAMES;
return Decision::Start;
}
self.remember(frame);
Decision::Hold
}
fn remember(&mut self, frame: &Frame) {
let slot = (self.preroll_start + self.preroll_len) % MAX_PREROLL_FRAMES;
self.preroll[slot] = *frame;
if self.preroll_len < MAX_PREROLL_FRAMES {
self.preroll_len += 1;
} else {
self.preroll_start = (self.preroll_start + 1) % MAX_PREROLL_FRAMES;
}
}
/// Copies the frames to send before the current one into `out`, oldest first, and empties the
/// preroll: everything since the reset for the first spurt after it (at most 300 ms), otherwise the
/// last [`PREROLL_FRAMES`]. Returns how many were copied.
pub fn take_preroll(&mut self, out: &mut [Frame; MAX_PREROLL_FRAMES]) -> usize {
let keep = if self.since_reset { self.preroll_len } else { self.preroll_len.min(PREROLL_FRAMES) };
let skip = self.preroll_len - keep;
for (i, dst) in out.iter_mut().take(keep).enumerate() {
*dst = self.preroll[(self.preroll_start + skip + i) % MAX_PREROLL_FRAMES];
}
self.preroll_start = 0;
self.preroll_len = 0;
self.since_reset = false;
keep
}
}
#[cfg(test)]
pub mod tests {
use super::*;
/// Real speech: 4 s of a public-domain LibriVox reading (see tests/fixtures/README.md), 48 kHz mono s16le WAV.
pub fn speech_frames() -> Vec<Frame> {
let wav = include_bytes!("../tests/fixtures/speech-librivox-48k.wav");
let data = wav_data(wav);
data.chunks_exact(FRAME_SAMPLES * 2)
.map(|c| {
let mut f = [0i16; FRAME_SAMPLES];
for (s, b) in f.iter_mut().zip(c.chunks_exact(2)) {
*s = i16::from_le_bytes([b[0], b[1]]);
}
f
})
.collect()
}
fn wav_data(wav: &[u8]) -> &[u8] {
assert_eq!(&wav[0..4], b"RIFF");
assert_eq!(&wav[8..12], b"WAVE");
let mut i = 12;
while i + 8 <= wav.len() {
let id = &wav[i..i + 4];
let len = u32::from_le_bytes([wav[i + 4], wav[i + 5], wav[i + 6], wav[i + 7]]) as usize;
if id == b"fmt " {
let fmt = &wav[i + 8..i + 8 + len];
assert_eq!(u16::from_le_bytes([fmt[0], fmt[1]]), 1, "PCM");
assert_eq!(u16::from_le_bytes([fmt[2], fmt[3]]), 1, "mono");
assert_eq!(u32::from_le_bytes([fmt[4], fmt[5], fmt[6], fmt[7]]), 48_000, "48 kHz");
assert_eq!(u16::from_le_bytes([fmt[14], fmt[15]]), 16, "16 bit");
}
if id == b"data" {
return &wav[i + 8..i + 8 + len];
}
i += 8 + len + (len & 1);
}
panic!("no data chunk");
}
/// Deterministic pseudo-random generator (xorshift) for synthetic noise.
struct Rng(u32);
impl Rng {
fn next(&mut self) -> f32 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 17;
self.0 ^= self.0 << 5;
(self.0 as f32 / u32::MAX as f32) * 2.0 - 1.0
}
}
fn silence(n: usize) -> Vec<Frame> { vec![[0i16; FRAME_SAMPLES]; n] }
/// Synthetic steady broadband noise (fan/hiss-like) at roughly -30 dBFS RMS.
fn steady_noise(n: usize) -> Vec<Frame> {
let mut rng = Rng(0x1234_5678);
let mut low = 0.0_f32;
(0..n)
.map(|_| {
let mut f = [0i16; FRAME_SAMPLES];
for s in f.iter_mut() {
low = 0.97 * low + 0.03 * rng.next();
*s = ((rng.next() * 0.03 + low * 0.3) * 32_767.0) as i16;
}
f
})
.collect()
}
/// Synthetic transients: a 3 ms click (keyboard/mouse-like) every 200 ms over near-silence.
fn clicks(n: usize) -> Vec<Frame> {
let mut rng = Rng(0x0bad_cafe);
(0..n)
.map(|i| {
let mut f = [0i16; FRAME_SAMPLES];
if i % 10 == 0 {
for (j, s) in f.iter_mut().take(144).enumerate() {
let env = 1.0 - j as f32 / 144.0;
*s = (rng.next() * env * 0.6 * 32_767.0) as i16;
}
}
f
})
.collect()
}
/// Runs frames through a gate and returns, per frame, whether it would have been sent, plus the
/// total number of frames sent (preroll included).
fn run(gate: &mut VoiceGate, frames: &[Frame]) -> (Vec<bool>, usize) {
let mut sent = Vec::with_capacity(frames.len());
let mut total = 0;
for f in frames {
match gate.push(f) {
Decision::Hold => sent.push(false),
Decision::Start => {
let mut pre = [[0i16; FRAME_SAMPLES]; MAX_PREROLL_FRAMES];
total += gate.take_preroll(&mut pre) + 1;
sent.push(true);
}
Decision::Send | Decision::SendAndEnd => {
total += 1;
sent.push(true);
}
}
}
(sent, total)
}
#[test]
fn decimator_keeps_history_across_frames() {
// A 1 kHz tone split into frames must decimate exactly like one long block would: compare the
// frame-wise output with a direct convolution over the concatenated input.
let mut d = Decimator::new();
let input: Vec<i16> = (0..FRAME_SAMPLES * 3).map(|n| ((n as f32 * 2.0 * std::f32::consts::PI * 1_000.0 / 48_000.0).sin() * 10_000.0) as i16).collect();
let mut framewise = Vec::new();
for chunk in input.chunks_exact(FRAME_SAMPLES) {
let mut f = [0i16; FRAME_SAMPLES];
f.copy_from_slice(chunk);
let mut out = [0.0; OUT_PER_FRAME];
d.process(&f, &mut out);
framewise.extend_from_slice(&out);
}
let reference = Decimator::new();
let padded: Vec<f32> = std::iter::repeat_n(0.0, HISTORY).chain(input.iter().map(|s| f32::from(*s) / 32_768.0)).collect();
for (k, got) in framewise.iter().enumerate() {
let end = HISTORY + k * DECIMATION + (DECIMATION - 1);
let want: f32 = padded[end + 1 - TAPS..=end].iter().zip(reference.coeffs.iter()).map(|(x, c)| x * c).sum();
assert!((got - want).abs() < 1e-6, "sample {k}: {got} vs {want}");
}
// A 1 kHz tone passes, a 12 kHz tone (above the new Nyquist) is suppressed.
let rms = |hz: f32| {
let mut d = Decimator::new();
let mut acc = 0.0;
for i in 0..4 {
let mut f = [0i16; FRAME_SAMPLES];
for (n, s) in f.iter_mut().enumerate() {
let t = (i * FRAME_SAMPLES + n) as f32;
*s = ((t * 2.0 * std::f32::consts::PI * hz / 48_000.0).sin() * 16_000.0) as i16;
}
let mut out = [0.0; OUT_PER_FRAME];
d.process(&f, &mut out);
if i > 0 {
acc += out.iter().map(|x| x * x).sum::<f32>();
}
}
(acc / (3 * OUT_PER_FRAME) as f32).sqrt()
};
assert!(rms(1_000.0) > 0.3, "pass band {}", rms(1_000.0));
assert!(rms(12_000.0) < 0.003, "stop band {}", rms(12_000.0));
}
#[test]
fn detector_windows_cross_frame_boundaries() {
// 320 new samples per frame: the 5th frame completes the 6th 256-sample window, so frames carry
// one or two windows and none is lost or duplicated (1600 samples = 6 windows + 64 pending).
let mut gate = VoiceGate::new(Sensitivity::Normal);
for _ in 0..5 {
gate.detect(&[0i16; FRAME_SAMPLES]);
}
assert_eq!(gate.pending_len, 5 * OUT_PER_FRAME - 6 * WINDOW);
}
fn rms_dbfs(f: &Frame) -> f32 {
let p = f.iter().map(|s| (f32::from(*s) / 32_768.0).powi(2)).sum::<f32>() / FRAME_SAMPLES as f32;
10.0 * p.max(1e-18).log10()
}
/// Index of the first clearly voiced frame of the fixture. The recording's own noise floor is about
/// -30 dBFS; voiced speech is above -24 dBFS.
fn first_loud(frames: &[Frame]) -> usize { frames.iter().position(|f| rms_dbfs(f) >= -24.0).expect("loud frame") }
#[test]
fn speech_opens_the_gate_with_preroll_and_no_duplicate() {
let speech = speech_frames();
let lead = 10;
let mut frames = silence(lead);
frames.extend_from_slice(&speech);
frames.extend(silence(60));
let speech_start = lead + first_loud(&speech);
let mut gate = VoiceGate::new(Sensitivity::Normal);
let mut first_onset = None;
let mut first_held = 0;
let mut since_end = 0; // frames held since the last spurt ended
let mut open = false;
let mut ended_at = None;
for (i, f) in frames.iter().enumerate() {
match gate.push(f) {
Decision::Start => {
assert!(!open);
let mut buf = [[0i16; FRAME_SAMPLES]; MAX_PREROLL_FRAMES];
let n = gate.take_preroll(&mut buf);
// First spurt after the reset: everything held since it (bounded); later spurts: the
// normal preroll. Oldest first, never the current frame.
let expected = if first_onset.is_none() { i.min(MAX_PREROLL_FRAMES) } else { PREROLL_FRAMES.min(since_end) };
assert_eq!(n, expected, "spurt at {i}");
for (k, p) in buf[..n].iter().enumerate() {
assert_eq!(p, &frames[i - n + k]);
}
if first_onset.is_none() {
first_onset = Some(i);
first_held = n;
}
open = true;
}
Decision::Send => assert!(open),
Decision::SendAndEnd => {
assert!(open);
open = false;
since_end = 0;
if i >= lead + speech.len() {
ended_at.get_or_insert(i);
}
}
Decision::Hold => {
assert!(!open);
since_end += 1;
}
}
}
let onset = first_onset.expect("speech must open the gate");
// The gate decides within 3 frames (60 ms) of the first loud frame, and what it sends reaches back
// before it, so the onset is not clipped.
assert!(onset >= speech_start && onset <= speech_start + 3, "onset at {onset}, loud speech at {speech_start}");
assert!(onset - first_held <= speech_start, "first sent frame {} after the loud start {speech_start}", onset - first_held);
// The last spurt ends in the trailing silence: after at least the hangover, and not much later.
let speech_end = lead + speech.len();
let ended = ended_at.expect("the spurt must end in the trailing silence");
assert!(ended >= speech_end + HANGOVER_FRAMES as usize - 1 && ended <= speech_end + HANGOVER_FRAMES as usize + 15, "ended at {ended}, speech ended at {speech_end}");
}
/// First spurt of `frames` fed to `gate`: (index of the Start, frames sent before the current one).
fn first_spurt(gate: &mut VoiceGate, frames: &[Frame]) -> Option<(usize, usize)> {
for (i, f) in frames.iter().enumerate() {
if gate.push(f) == Decision::Start {
let mut buf = [[0i16; FRAME_SAMPLES]; MAX_PREROLL_FRAMES];
let n = gate.take_preroll(&mut buf);
for (k, p) in buf[..n].iter().enumerate() {
assert_eq!(p, &frames[i - n + k], "sent frames are the held ones, in order");
}
return Some((i, n));
}
}
None
}
#[test]
fn speech_from_the_first_frame_is_sent_in_full() {
// Loud speech starting at frame 0 of a fresh gate (connect, unmute, mode change while talking).
let speech = speech_frames();
let from_loud = &speech[first_loud(&speech)..];
for s in [Sensitivity::High, Sensitivity::Normal, Sensitivity::Low] {
let mut gate = VoiceGate::new(s);
let (onset, held) = first_spurt(&mut gate, from_loud).expect("speech must open the gate");
// The warm-up delays the decision (measured: at most 3 frames past it), but every frame from
// frame 0 is sent: nothing of the first word is lost, it just arrives up to ~260 ms later.
assert!(onset <= WARMUP_FRAMES as usize + 3, "{s:?}: opened at frame {onset}");
assert_eq!(held, onset, "{s:?}: frames 0..{onset} must all be sent before frame {onset}");
}
}
#[test]
fn speech_right_after_a_reset_is_sent_in_full() {
// Talking through an unmute: the gate is reset at the mute; the first frame after it must be sent.
let speech = speech_frames();
let mut gate = VoiceGate::new(Sensitivity::Normal);
run(&mut gate, &speech[..60]);
gate.reset();
let after = &speech[60..];
let (onset, held) = first_spurt(&mut gate, after).expect("speech must open the gate");
assert_eq!(held, onset, "frames since the reset are all sent");
assert!(onset <= WARMUP_FRAMES as usize + 3);
}
#[test]
fn the_natural_end_of_a_spurt_does_not_reset_the_detector() {
let speech = speech_frames();
let mut frames = speech.clone();
frames.extend(silence(HANGOVER_FRAMES as usize + 10));
frames.extend_from_slice(&speech);
let mut gate = VoiceGate::new(Sensitivity::Normal);
let mut starts = Vec::new();
for f in &frames {
if gate.push(f) == Decision::Start {
let mut buf = [[0i16; FRAME_SAMPLES]; MAX_PREROLL_FRAMES];
starts.push(gate.take_preroll(&mut buf));
}
}
assert!(starts.len() >= 2, "{starts:?}");
// Only the first spurt after the reset carries the startup buffer; later ones the normal preroll,
// and no warm-up was re-armed in between.
assert!(starts[1..].iter().all(|n| *n <= PREROLL_FRAMES), "{starts:?}");
assert_eq!(gate.warmup, 0);
}
#[test]
fn decimator_output_stays_in_the_detector_range() {
// Full-scale square wave: the low-pass rings above full scale; the detector input is clamped.
let mut d = Decimator::new();
let mut peak = 0.0f32;
for _ in 0..3 {
let mut f = [0i16; FRAME_SAMPLES];
for (n, s) in f.iter_mut().enumerate() {
*s = if (n / 48) % 2 == 0 { i16::MAX } else { i16::MIN };
}
let mut out = [0.0; OUT_PER_FRAME];
d.process(&f, &mut out);
peak = out.iter().fold(peak, |m, x| m.max(x.abs()));
}
assert!(peak <= 1.0 && peak > 0.9, "peak {peak}");
}
#[test]
fn silence_steady_noise_and_clicks_stay_closed() {
// Synthetic, deterministic noise (not recordings): the detector is statistical, so this checks the
// chosen thresholds keep these inputs closed, not that every real noise does.
for (name, frames) in [("silence", silence(250)), ("steady noise", steady_noise(250)), ("clicks", clicks(250))] {
for s in [Sensitivity::High, Sensitivity::Normal, Sensitivity::Low] {
let mut gate = VoiceGate::new(s);
let (_, total) = run(&mut gate, &frames);
assert_eq!(total, 0, "{name} opened the gate at {s:?}");
}
}
}
#[test]
fn hangover_keeps_short_pauses_and_ends_after_it() {
let speech = speech_frames();
// A continuously voiced stretch of the fixture, a 160 ms pause, the same stretch again, then silence.
let voiced = &speech[60..90];
let mut frames = voiced.to_vec();
frames.extend(silence(8));
frames.extend_from_slice(voiced);
let speech_end = frames.len();
frames.extend(silence(60));
let mut gate = VoiceGate::new(Sensitivity::Normal);
let (sent, _) = run(&mut gate, &frames);
let starts = sent.windows(2).filter(|w| !w[0] && w[1]).count() + usize::from(sent[0]);
assert_eq!(starts, 1, "a short pause must not split the spurt");
let last_sent = sent.iter().rposition(|s| *s).expect("sent");
assert!(last_sent >= speech_end + HANGOVER_FRAMES as usize - 1, "closed at {last_sent} before the hangover ran out");
assert!(!sent[sent.len() - 1], "gate must be closed after the hangover");
}
#[test]
fn reset_forgets_preroll_and_open_spurt() {
let speech = speech_frames();
let mut gate = VoiceGate::new(Sensitivity::Normal);
run(&mut gate, &speech[..40]);
assert!(gate.is_active());
gate.reset();
assert!(!gate.is_active());
let mut buf = [[0i16; FRAME_SAMPLES]; MAX_PREROLL_FRAMES];
assert_eq!(gate.take_preroll(&mut buf), 0);
// After a reset only new audio is considered: silence keeps it closed.
let (_, total) = run(&mut gate, &silence(30));
assert_eq!(total, 0);
}
#[test]
fn sensitivity_changes_the_probability_threshold() {
let mut gate = VoiceGate::new(Sensitivity::High);
assert!(gate.sensitivity().threshold() < Sensitivity::Normal.threshold());
gate.set_sensitivity(Sensitivity::Low);
assert_eq!(gate.threshold, Sensitivity::Low.threshold());
assert!(Sensitivity::Low.threshold() > Sensitivity::Normal.threshold());
}
}
+21
View File
@@ -0,0 +1,21 @@
# Test fixtures
## `speech-librivox-48k.wav`
Real human speech used to test the voice activation detector (`core/src/vad.rs`) and, looped with silence, as
the fake capture input of `scripts/smoke-voice-vad.mjs`. Test data only; not shipped in any package.
- Source: LibriVox, *Short Poetry Collection 001*, "Jenny Kissed Me" by Leigh Hunt, file
`jenny_hunt_py_64kb.mp3` from <https://archive.org/details/short_poetry_001_librivox>
(`https://archive.org/download/short_poetry_001_librivox/jenny_hunt_py_64kb.mp3`, SHA-256 of the downloaded
MP3 `9394cb36b156957c6770b50c77181ab17ecaf7d88ed2cb337a822fd8897b768a`).
- License: public domain. LibriVox recordings are dedicated to the public domain; the archive.org item states
<http://creativecommons.org/licenses/publicdomain/>.
- Content: 4.0 s starting at 2.0 s of the recording (the LibriVox introduction, read by a volunteer).
- Conversion (FFmpeg 7.1.1): `ffmpeg -ss 2.0 -t 4.0 -i jenny_hunt_py_64kb.mp3 -ac 1 -ar 48000 -c:a pcm_s16le
-map_metadata -1 -fflags +bitexact -flags:a +bitexact speech-librivox-48k.wav` → 48 kHz mono 16-bit PCM WAV,
384 044 bytes, SHA-256 `d0e63d939369a0d51bbb42aa36fb5fe185b19e4f4aa3070c10bef28df593ed38`.
- Character: the MP3's own noise floor is about -30 dBFS; voiced speech is above -24 dBFS (the tests use that
level to locate the first loud frame). Mean -25.4 dB, peak -5.6 dB.
The noise inputs of the tests (steady broadband noise, clicks) are generated in code and are synthetic.
Binary file not shown.
+42 -13
View File
@@ -73,6 +73,11 @@ error id and tsclientlib's name for it (live example: send_text to a channel wit
permission → `{"id":2568,"name":"PermissionsClientInsufficient","missing_permission":224}`). permission → `{"id":2568,"name":"PermissionsClientInsufficient","missing_permission":224}`).
`detail` carries structured extra state where stated (e.g. `rename`). `detail` carries structured extra state where stated (e.g. `rename`).
Repository-authored `message` text and stderr diagnostics are English technical details, not UI
translation keys. The renderer selects a localized explanation by stable `code` and may append the
technical detail. Do not translate protocol tokens, server-supplied text or user content, and do not
branch on human-readable message wording.
| code | meaning | | code | meaning |
|---|---| |---|---|
| `bad_request` | malformed JSON, missing/unknown/invalid argument, bad `id` | | `bad_request` | malformed JSON, missing/unknown/invalid argument, bad `id` |
@@ -94,7 +99,7 @@ permission → `{"id":2568,"name":"PermissionsClientInsufficient","missing_permi
| `audio_codec_unsupported` | current channel codec is not Opus (legacy Speex/CELT): we cannot transmit there (event, once per burst); received non-Opus voice is reported once per speaker | | `audio_codec_unsupported` | current channel codec is not Opus (legacy Speex/CELT): we cannot transmit there (event, once per burst); received non-Opus voice is reported once per speaker |
| `rename_not_persisted` | server accepted the new nickname but saving it failed; see §4.3 | | `rename_not_persisted` | server accepted the new nickname but saving it failed; see §4.3 |
| `not_found` | requested icon/avatar/banner does not exist (`detail.builtin:true` for built-in icon ids) | | `not_found` | requested icon/avatar/banner does not exist (`detail.builtin:true` for built-in icon ids) |
| `media_too_large` | file exceeds the size limit of its kind (§4.16) | | `media_too_large` | file exceeds the size limit of its kind (§4.17) |
| `media_unsupported` | file is not a recognized image, or a banner reference the core cannot fetch | | `media_unsupported` | file is not a recognized image, or a banner reference the core cannot fetch |
| `external_media` | banner or avatar lives at an `https://` URL (`detail.url` for banners, `detail.urls` for avatars); main may fetch it itself | | `external_media` | banner or avatar lives at an `https://` URL (`detail.url` for banners, `detail.urls` for avatars); main may fetch it itself |
| `io` | data dir I/O failure | | `io` | data dir I/O failure |
@@ -190,20 +195,44 @@ Initial state at process start: both `false`.
One 20 ms microphone frame: base64 (standard alphabet, padded) of **960 signed One 20 ms microphone frame: base64 (standard alphabet, padded) of **960 signed
16-bit little-endian mono samples at 48 kHz = 1920 bytes** (2560 base64 chars). 16-bit little-endian mono samples at 48 kHz = 1920 bytes** (2560 base64 chars).
The renderer gates push-to-talk / voice activation: it sends frames only while In transmit mode `direct` (see 4.11) the renderer decides: it sends frames only while
transmitting and `audio_end` when it stops. The core Opus-encodes 20 ms frames push-to-talk is held or the open microphone is on, and `audio_end` when it stops; the core
with the **current channel's codec**: Opus Voice (mono) or Opus Music (stereo — the sends every frame. In mode `vad` the renderer sends frames continuously while connected and
not muted, and the core's voice detector decides which are sent. The core Opus-encodes 20 ms
frames with the **current channel's codec**: Opus Voice (mono) or Opus Music (stereo — the
mono frame is duplicated to both channels). Legacy Speex/CELT channels → mono frame is duplicated to both channels). Legacy Speex/CELT channels →
`audio_codec_unsupported` event and nothing is sent. Outgoing queue bound: 10 frames `audio_codec_unsupported` event and nothing is sent. Outgoing queue bound: 10 frames
(200 ms); on overflow the oldest frames are dropped (`audio_overflow` event). (200 ms); on overflow the oldest frames are dropped (`audio_overflow` event).
If no frame arrives for 200 ms during a burst the core ends the burst itself. If no frame arrives for 200 ms during a burst the core ends the burst itself.
Not connected → frames dropped with one `not_connected` error event per burst. Not connected → frames dropped with one `not_connected` error event per burst. Muted,
deafened, or not allowed to talk by the server → frames dropped with one `audio_muted` event
per burst; in mode `vad` the detector state and preroll are discarded as well.
### 4.10 `audio_end` — no args (no `id`, no response) ### 4.10 `audio_end` — no args (no `id`, no response)
Ends the current transmission burst (core sends the TeamSpeak end-of-voice packet). Ends the current transmission burst (core sends the TeamSpeak end-of-voice packet). In mode
`vad` it also discards the detector state and preroll (capture stopped or the renderer stopped
forwarding).
### 4.11 `stream_list` — `{client_id?: number}` ### 4.11 `set_transmit` — `{mode: "direct"|"vad", sensitivity?: "high"|"normal"|"low"}`
Selects who decides when voice is sent. `direct` (initial state at process start): every
forwarded frame is sent. `vad`: voice activation in the core (`core/src/vad.rs`): frames are
decimated to 16 kHz and scored by the earshot voice detector (embedded model, 16 ms windows,
probability 0–1). The gate opens after 3 consecutive windows at or above the threshold
(`high` 0.45, `normal` 0.6 — default, `low` 0.75) and sends the 5 frames (100 ms) held before
the onset, then the current frame. While open, a window counts as voiced down to 0.15 below the
threshold; the gate closes 20 frames (400 ms) after the last voiced frame. It cannot open
during the first 10 frames after a reset; until the first spurt after a reset all frames since it are held
(at most 15 = 300 ms) and sent before the current one, later spurts send 5. Detector, filter history and preroll are reset on
every `set_transmit`, `audio_end`, mute/deafen, disconnect, channel or codec change and when
the server does not allow talking. `sensitivity` is accepted only with `vad`.
Before answering, the core discards frames still queued from the previous mode and ends any
open burst; the renderer forwards nothing until it has this answer.
Result `{"mode":"direct"}` or `{"mode":"vad","sensitivity":"normal"}`. `audio_state.transmitting`
is true only while voice packets are actually being sent.
### 4.12 `stream_list` — `{client_id?: number}`
TS6 screenshare discovery. Sends `requeststreaminfo clid=<id>` for `client_id`, or for TS6 screenshare discovery. Sends `requeststreaminfo clid=<id>` for `client_id`, or for
every other client in our current channel when omitted. Result: every other client in our current channel when omitted. Result:
@@ -218,28 +247,28 @@ Live behaviour (TS6 6.0.0-beta13.1): every `requeststreaminfo` is answered `ok`,
`viewer`, `viewer_limit`; for a non-streaming client the item has only `return_code`. `viewer`, `viewer_limit`; for a non-streaming client the item has only `return_code`.
So: "is streaming" ⇔ the `notifystreaminfo` item has `id`. So: "is streaming" ⇔ the `notifystreaminfo` item has `id`.
### 4.12 `stream_join` — `{stream_id: string, client_id: number, message?: string}` ### 4.13 `stream_join` — `{stream_id: string, client_id: number, message?: string}`
Sends `joinstreamrequest id=<stream_id> clid=<client_id> msg=<message|our nickname> is_remove=0`. Sends `joinstreamrequest id=<stream_id> clid=<client_id> msg=<message|our nickname> is_remove=0`.
Result `{}` (or `server_error`). The SDP offer arrives as `stream` event Result `{}` (or `server_error`). The SDP offer arrives as `stream` event
`notifyrespondjoinstreamrequest` (`decision=1`, `offer=<sdp>`). `notifyrespondjoinstreamrequest` (`decision=1`, `offer=<sdp>`).
### 4.13 `stream_signal` — `{stream_id: string, client_id: number, json: object}` ### 4.14 `stream_signal` — `{stream_id: string, client_id: number, json: object}`
Sends `streamsignaling id=<stream_id> clid=<client_id> json=<compact JSON of json>`. Sends `streamsignaling id=<stream_id> clid=<client_id> json=<compact JSON of json>`.
Examples of `json`: `{"cmd":"answer","args":{"answer":"<sdp>"}}`, Examples of `json`: `{"cmd":"answer","args":{"answer":"<sdp>"}}`,
`{"cmd":"iceCandidate","args":{"mLine":0,"mid":"0","sdp":"candidate:..."}}`. `{"cmd":"iceCandidate","args":{"mLine":0,"mid":"0","sdp":"candidate:..."}}`.
Max serialized `json` size 60 KiB (the whole stdin line is capped at 256 KiB). Result `{}` or `server_error`. Max serialized `json` size 60 KiB (the whole stdin line is capped at 256 KiB). Result `{}` or `server_error`.
### 4.14 `stream_leave` — `{stream_id: string, client_id: number}` ### 4.15 `stream_leave` — `{stream_id: string, client_id: number}`
Sends `joinstreamrequest id=… clid=… msg= is_remove=1`. Result `{}`. Sends `joinstreamrequest id=… clid=… msg= is_remove=1`. Result `{}`.
### 4.15 `shutdown` — no args ### 4.16 `shutdown` — no args
Disconnects cleanly if needed, responds `{}`, exits 0. Disconnects cleanly if needed, responds `{}`, exits 0.
### 4.16 Media: `fetch_icon`, `fetch_avatar`, `fetch_banner`, `fetch_server_banner` ### 4.17 Media: `fetch_icon`, `fetch_avatar`, `fetch_banner`, `fetch_server_banner`
Read-only downloads over TeamSpeak file transfer from the connected server. No paths Read-only downloads over TeamSpeak file transfer from the connected server. No paths
cross the bridge: the core derives the server file from ids it already knows. cross the bridge: the core derives the server file from ids it already knows.
@@ -323,7 +352,7 @@ Full replacement of the server view, emitted after connect and after every chang
`"speex_ultrawideband"`, `"celt_mono"` or `null` if unknown. Only Opus channels can `"speex_ultrawideband"`, `"celt_mono"` or `null` if unknown. Only Opus channels can
transmit; the UI should show the reason for others. transmit; the UI should show the reason for others.
- `client_type`: `"normal"` or `"query"`. `uid` may be `null` if not visible. - `client_type`: `"normal"` or `"query"`. `uid` may be `null` if not visible.
- `icon_id`: TeamSpeak icon id or `null` (0 = none). Fetch with `fetch_icon` (§4.16). - `icon_id`: TeamSpeak icon id or `null` (0 = none). Fetch with `fetch_icon` (§4.17).
- Groups: `server_groups`/`channel_groups` are the server's group catalogs (sent to every - Groups: `server_groups`/`channel_groups` are the server's group catalogs (sent to every
client on connect; sorted by `sort_id`, then `id`). A client's `server_groups` and client on connect; sorted by `sort_id`, then `id`). A client's `server_groups` and
`channel_group_id` reference them. `name_mode` (`none|before|after`) is TeamSpeak's `channel_group_id` reference them. `name_mode` (`none|before|after`) is TeamSpeak's
+91
View File
@@ -0,0 +1,91 @@
# 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.
## Packaged smoke harness: launch race (found and fixed)
`runtime/2026-10-24-packaged-launch-race/` keeps the first packaged run of 0.1.2-rc.1 (7afce5a): `theme` and
`menus` passed; `devices` and `ui` failed with `electron.launch: Timeout`. Cause: with `executablePath`
Playwright cannot inject its `-r loader.js` (which in a dev run holds `ready` until it has attached); when it
attaches to the packaged app while the first page is committing, it loses its utility world and the launch
never completes (6 of 6 isolated probes hung; passing `-r loader.js` to the packaged exe is ignored, 5 of 5
hung). CI run #21 failed the same way. Fix: dev runs use Playwright's own loader (no `executablePath`);
packaged runs start with `TEAMSPEACH_TEST_HOLD_WINDOW=1`, which defers window creation until the harness
calls the main-process hook (`scripts/lib/electron-app.mjs`). Without that variable the app starts as before.
## Device choice and capture safety (rc.1 additions)
- A saved microphone that no longer exists fails closed (`device_unavailable`): no second `getUserMedia`
without the device id, no default microphone, nothing sent. Choosing an available device restarts capture
only while connected or during the microphone test. Tests: `test/voice-capture.test.mjs`,
`test/audio-engine.test.mjs`.
- A failure while building the capture graph after the microphone opened stops its tracks and disconnects the
partial nodes before rethrowing.
- A failed `enumerateDevices()` replaces the cached choices, so the menus show the failure, not an older list.
## Packaged release candidates
- `runtime/2026-10-24-rc1-packaged/`: build of 2a71d63 (application tree of tag `v0.1.2-rc.1` at d505890).
- `runtime/2026-10-24-rc2-packaged/`: build of ed2e123 (tag `v0.1.2-rc.2`), the same build as the attached
Windows assets. Theme (fresh profile dark, onboarding mark = decoded `assets/icon.png` 256×256 shown at
56 px, light persists), 6 + 6 real devices without capture, menus incl. races, offline UI: all pass,
0 page errors.
+31
View File
@@ -100,3 +100,34 @@ are always off. `client_user_tag`, which carries a signed myTS token, is never l
Hardening item, not applied: vendored `tsclientlib/src/lib.rs` `warn!(message = ?msg, "Expected Hardening item, not applied: vendored `tsclientlib/src/lib.rs` `warn!(message = ?msg, "Expected
initserver, dropping command")` would Debug-print a whole command if one arrived before initserver, dropping command")` would Debug-print a whole command if one arrived before
`initserver` during connect (not observed live). Proposed fix: log only the command name. `initserver` during connect (not observed live). Proposed fix: log only the command name.
## 0.1.2: private keys with a leading zero byte (bug found and fixed)
- Found by running the unit tests concurrently (6×80): about 3% of runs failed with
`identity_corrupt: invalid private key: Failed to parse short private key` on freshly created
identities.
- Cause: upstream `EccKeyPrivP256::from_tomcrypt` (tsproto-types) passes the DER integer's
minimal bytes to `from_short`, which requires 32 bytes. A scalar starting with `0x00`
(~1 in 256 keys) is written by `to_ts` but cannot be read back. The same applies to
`Identity::new_from_ts_str` (ini import). Affected users would have had a permanently refused
identity (the core never regenerates).
- Fix (`core/src/keyfmt.rs`): upstream's own decoder shape — the same `simple_asn1::from_der`
(already in the lock through tsproto-types), the same SEQUENCE / BIT STRING / INTEGER positions —
with the single difference that the non-negative scalar is left-padded to 32 bytes. The import
path de-obfuscates (same constant as tsproto-types) and then parses the same way. The stored
format is unchanged, so already-written affected files now load; no identity is regenerated.
Malformed input returns an error, never panics. (A first hand-written TLV parser from the same
day was replaced by this after review.)
- Permanent tests are deterministic: fixed scalars with one and three leading zero bytes, a
sign-padded scalar (top bit set, 33-byte DER INTEGER) and a full-width one round-trip as plain
DER, obfuscated `…V…` and plain `…V…`; profile write → load → export → import with the
one-zero scalar; upstream test vector (known UID); malformed inputs (truncated, trailing block,
non-SEQUENCE, empty SEQUENCE, wrong first item, public-only flag, empty / 3-bit / unused-bits >
length BIT STRING, missing or non-INTEGER private slot, negative, zero, empty, ≥ group order and
33-byte scalars) are errors. `cargo test --locked`: 37 unit + 3 stdio smoke pass.
- Throwaway evidence (not kept as tests): upstream `from_ts` fails on the fixed one-zero scalar;
100 000 random keys all round-trip through the fix, 387 had a zero top byte and exactly those
387 fail upstream.
- Release `0.1.2` (root `.cargo/config.toml`, static CRT, `-j 2`): 8969216 bytes, SHA256
`6c04f1e6595740f50628374b23216d00b9e7a5bfa5c8c5cba18a8b053eb9bb57`; imports only system DLLs
(ADVAPI32, IPHLPAPI, KERNEL32, api-ms-win-core-synch, bcrypt, bcryptprimitives, ntdll, oleaut32,
ws2_32); `npm run smoke:core` passes (create → restart → same UID).
+1
View File
@@ -17,3 +17,4 @@
- 2026-10-24: at the owner's request the repository was made **public** after a secret audit - 2026-10-24: at the owner's request the repository was made **public** after a secret audit
(`docs/evidence/public-visibility.md`); CI no longer runs on pull requests. (`docs/evidence/public-visibility.md`); CI no longer runs on pull requests.
- Release `v0.1.0` (prerelease) published by the release workflow: `docs/evidence/release-v0.1.0.md`. - Release `v0.1.0` (prerelease) published by the release workflow: `docs/evidence/release-v0.1.0.md`.
- Release `v0.1.1` (prerelease) supersedes v0.1.0 (ARM64 AppImage runtime fix): `docs/evidence/release-v0.1.1.md`.
+1 -1
View File
@@ -1,6 +1,6 @@
# Making TeamsPeach/client public — audit (2026-10-24) # Making TeamsPeach/client public — audit (2026-10-24)
Requested by the owner ("репо пусть публичный будет"). Only counts and categories are recorded here. The owner requested a public repository. Only counts and categories are recorded here.
## Secret audit (before the visibility change) ## Secret audit (before the visibility change)
+67
View File
@@ -0,0 +1,67 @@
# Release v0.1.1 (pre-release) — 2026-10-24
Fixes a packaging defect of v0.1.0: the ARM64 AppImage used electron-builder's legacy AppImage runtime
(appimage-12.0.1), which has `PT_INTERP` and `DT_NEEDED libz.so` (unversioned, normally only in zlib
development packages).
## Reproduction of the defect (release dispatch run #14, commit `7c9616f`, legacy toolset)
In `node:22-bookworm-slim` (only `libz.so.1` present), the new `appimage-startup` gate:
```
qemu-aarch64 -L / TeamsPeach-0.1.0-arm64.AppImage --appimage-version
error while loading shared libraries: libz.so: cannot open shared object file: No such file or directory (exit 127)
```
The x64 legacy runtime started in the same container.
## Fix
`package.json` → `build.toolsets.appimage = "1.0.3"` (static type2 runtime 20251108). No application changes.
`package.json` and `core/Cargo.toml` → 0.1.1.
## Proof
- Commit `71300ff0610f592dd7a2d43795a946a42ab887e6`, tag `v0.1.1`.
- CI run #16 success; release dispatch run #17 success; tag release run #18: `linux-x64`, `linux-arm64`,
`appimage-startup`, `publish` all success.
- `appimage-startup` in `node:22-bookworm-slim` without zlib development files:
x64 native and arm64 under `qemu-aarch64 -L /` both print
`AppImage runtime version: https://github.com/AppImage/type2-runtime/commit/dd6cebe` (emulated for arm64).
- Runtime headers of the published AppImages (read anonymously from the release):
| AppImage | ELF type | PT_INTERP | DT_NEEDED | PT_LOAD align / offset≡vaddr (16 KiB) |
|---|---|---|---|---|
| TeamsPeach-0.1.1-arm64.AppImage | ET_DYN (static-pie) | none | none | 65536 / yes |
| TeamsPeach-0.1.1.AppImage | ET_DYN (static-pie) | none | none | 4096 / yes |
| v0.1.0 arm64 (for comparison) | ET_EXEC | present | `libz.so`, … | 65536 / yes |
- The package-wide 16 KiB check (`elf-report-linux-arm64.json`) passed for all 8 arm64 ELF files.
## Assets (downloaded back without credentials; size and SHA-256)
| Asset | Bytes | SHA-256 |
|---|---|---|
| TeamsPeach-0.1.1.AppImage | 120807031 | ff758081ce9ee95e2f0fb104099bfa1823b3493b4dfd9cde8eb8d2f1f60fe489 |
| teamspeach-0.1.1.tar.gz | 122885965 | 032ee915db881bc009c9f67267e7375d62ff4278495f1f176bd6fccde3c84823 |
| TeamsPeach-0.1.1-arm64.AppImage | 120884070 | 80c80d07ccd3fa6f100c2838ab0c561e2e064797d3325402e1b2d43392241c7b |
| teamspeach-0.1.1-arm64.tar.gz | 123741168 | a7015569d65c551c8e86c8199015f0bf8580a5ff4a47f34ae491b5984e565403 |
| build-info-linux-x64.txt | 1930 | 6af1f8875209f6ab80ba4eab2f6dae5fd0b9e6f635b2418b668d7278430702dd |
| build-info-linux-arm64.txt | 2016 | b9d7c74c04b38000db1985b5c5e0cb2b4468d8d1b1c70a6708d7b6a7685a3dd7 |
| elf-report-linux-x64.json | 3650 | f4c42badb3166ca563d5ee0afd8d8806169f388af6d2c2afb76083bd37b92f8c |
| elf-report-linux-arm64.json | 3727 | 6c5eb3689ca1a0f23d7eb4b81d4a7967fd7800b69aa8d0c11f05022a7a83bfb8 |
| TeamsPeach-0.1.1-win-x64-local-setup.exe | 114091919 | 1f551dcda1aa2b033059086e75392109fea3b332ea65f100c3814b508d223a27 |
| TeamsPeach-0.1.1-win-x64-local.zip | 156790297 | 5491acaa32a16155a443aefdc2932b4b4d4d1baf5b618fd04921e9c12895cab5 |
| TeamsPeach-0.1.1-win-x64-local-build-info.txt | 1095 | 2c0796b8e6ac52bd75b196671e68afa7d4887952380155522723f948386b3ba1 |
Windows x64: built on the developer PC from the clean tagged commit; core 0.1.1
`df2a8629b9fc9bf896a22f30b494eb819b0dcd6398794ccc82073444cfad8dab` (static CRT); packaged offline smoke of
this build passed (first launch, restart, rename, export, hardware-decode policy restart).
v0.1.0 release text now says it is superseded by v0.1.1 (assets and tag unchanged).
## Still unverified / blocked
Execution on Apple Silicon under Asahi Linux (target unreachable; arm64 checked statically and under qemu),
FUSE mounting of the AppImage on Fedora (only `--appimage-version` was run), macOS and Windows ARM64 builds,
code signing.
+53
View File
@@ -0,0 +1,53 @@
# Release v0.1.2 and its release candidates
All three are published prereleases (TeamsPeach releases are previews so far) at
https://git.eeee.moe/TeamsPeach/client/releases. Earlier tags were not moved; v0.1.1, v0.1.2-rc.1 and
v0.1.2-rc.2 only received a "superseded by v0.1.2" note in their release text (assets unchanged).
| Tag | Commit | Release run | Assets | Windows (built locally from the tag commit, appended) |
|---|---|---|---|---|
| `v0.1.2` | 9e74836 | #36 (id 4379): linux-x64, linux-arm64, appimage-startup, publish all green | 15 | setup, blockmap, `-local.zip`, build-info, `latest.yml` (uploaded last); anonymous download SHA-256 equal to the local build |
| `v0.1.2-rc.1` | d505890 | #29 (id 4372): all jobs green | 15 | same set with `rc.yml`; anonymous SHA-256 match |
| `v0.1.2-rc.2` | ed2e123 | #32 (id 4375): all jobs green | 15 | same set with `rc.yml`; anonymous SHA-256 match |
rc.1 is the tested functional baseline (device lists, menus, capture safety, updater, language, theme,
identity key fix). rc.2 changes only the in-app brand mark (now `assets/icon.png`). 0.1.2 adds no
application change over rc.2 (version, changelog date, updater test harness fix, evidence).
Core 0.1.2 in all three: Windows SHA-256 `21220483fd23fcc9e93da67aa2598197c54654cc63bbbfe1706d7dd435aaa221`.
## v0.1.2 Windows assets (local build of 9e74836, clean tree)
```
c4bfcebef4a40596e67777154e70954f41aeed74789a9c919b97701dd0d53084 TeamsPeach-0.1.2-win-x64-setup.exe (114535732 bytes)
a88bce3f8010619276a1dad14467cbbad32c32253c093f54631c3fd670213044 TeamsPeach-0.1.2-win-x64-setup.exe.blockmap (121106 bytes)
3d627e28084a43e7eb0c045e07ca456c8d9912c55235ab15b48149ea2b274e5b TeamsPeach-0.1.2-win-x64-local.zip (157330314 bytes)
7d626eaa76249473004c6088865d20efb3ee21265dc477c1501b977a571d942c latest.yml (365 bytes)
```
Linux assets (CI): `TeamsPeach-0.1.2.AppImage`, `TeamsPeach-0.1.2-arm64.AppImage`, `teamspeach-0.1.2.tar.gz`,
`teamspeach-0.1.2-arm64.tar.gz`, `latest-linux.yml`, `latest-linux-arm64.yml`, build-info and ELF reports.
## Updater end-to-end proofs (Linux x64 AppImage)
Workflow `update-e2e` (Linux x64 container, Xvfb, disposable profile, published releases on git.eeee.moe,
anonymous downloads). Full job logs: `runtime/2026-10-24-update-e2e/`.
| Run | Transition | Result |
|---|---|---|
| #33 (id 4376) | v0.1.2-rc.1 → v0.1.2-rc.2 (`rc-linux.yml`) | check found rc.2 (preview); electron-updater downloaded and verified it; explicit install → old process exit 0 → rc.2 relaunched automatically with the same UID; installed AppImage SHA-512 = feed; nickname, bookmark, selected device unchanged |
| #37 (id 4380) | v0.1.2-rc.2 → v0.1.2 (`latest-linux.yml`) | same sequence: prerelease → release precedence (`0.1.2-rc.2 < 0.1.2`) across the rc → latest feed names; version 0.1.2 after relaunch, same UID, SHA-512 = feed, preferences unchanged |
Not covered: Windows NSIS install/relaunch (needs a separate Windows account or VM — the NSIS relaunch would
use the default profile; a custom-profile run refuses automatic install), Linux ARM64 AppImage update,
macOS (no builds). 0.1.1 and older have no updater: 0.1.2 must be installed manually once.
## Packaged Windows smokes (real devices, no fake media flags, disposable profiles, never connected)
- `runtime/2026-10-24-0.1.2-packaged/`: the published 0.1.2 build. Fresh profile dark and English, onboarding
mark = decoded `assets/icon.png` (256×256 shown at 56 px), light persists across restart, stored theme kept;
6 inputs + 6 outputs without capture (`capturing=false`, `framesSent=0`), choices persist; device menus incl.
pending-enumeration races; offline UI smoke. 0 page errors.
- `runtime/2026-10-24-rc1-packaged/`, `runtime/2026-10-24-rc2-packaged/`: the same checks on the candidates.
- `runtime/2026-10-24-packaged-launch-race/`: the harness failure found on the first rc.1 run and its cause
(see `audio-devices-0.1.2.md`).
## Not verified
That the official TeamSpeak 6 client hears TeamsPeach voice (user report on 0.1.1). The synthetic
two-TeamsPeach voice test passes; the check with the official client is the user's (hold the in-window
push-to-talk button, or F8 while TeamsPeach is focused).
Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

@@ -0,0 +1,95 @@
{
"steps": [
{
"name": "mic right-click",
"menu": true,
"inputMuted": false,
"capturing": false,
"framesSent": 0,
"items": [
{
"label": "System default (Mic/Line/Inst 1-2 (MiniFuse 4))",
"checked": "true"
},
{
"label": "Loopback Mix Left/Right (MiniFuse 4)",
"checked": "false"
},
{
"label": "Headset Microphone (Oculus Virtual Audio Device)",
"checked": "false"
},
{
"label": "Line 3-4 (MiniFuse 4)",
"checked": "false"
},
{
"label": "Микрофон (DroidCam Audio)",
"checked": "false"
},
{
"label": "Микрофон (Virtual Desktop Audio)",
"checked": "false"
},
{
"label": "Mic/Line/Inst 1-2 (MiniFuse 4)",
"checked": "false"
}
],
"insideViewport": true,
"focused": "menu-item"
},
{
"name": "menu choice reflected in settings",
"pick": "Headset Microphone (Oculus Virtual Audio Device)",
"settingsInput": "Headset Microphone (Oculus Virtual Audio Device)",
"same": true
},
{
"name": "headphones Shift+F10",
"menu": true,
"outputMuted": false,
"items": [
"System default (Main Left/Right (MiniFuse 4))",
"Main Left/Right (MiniFuse 4)",
"Realtek Digital Output (Realtek(R) Audio)",
"Virtual Left/Right (MiniFuse 4)",
"LG ULTRAGEAR (NVIDIA High Definition Audio)",
"Наушники (Oculus Virtual Audio Device)",
"Aux Left/Right (MiniFuse 4)"
],
"insideViewport": true
},
{
"name": "escape",
"menuClosed": true,
"focusRestored": true,
"outputMuted": false
},
{
"name": "left click still toggles mute",
"inputMuted": true
},
{
"name": "rapid mic → headphones while enumeration pending",
"menus": 1,
"outputExpanded": "true",
"inputExpanded": "false",
"items": 7
},
{
"name": "dismissed before enumeration finished",
"menus": 0,
"focused": "connect-address",
"expanded": "false"
},
{
"name": "after restart",
"checkedIn": "Headset Microphone (Oculus Virtual Audio Device)",
"checkedOut": "Realtek Digital Output (Realtek(R) Audio)",
"persisted": true
}
],
"console": [],
"ok": true
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

@@ -0,0 +1,49 @@
{
"steps": [
{
"name": "listed without capture",
"inputs": 6,
"outputs": 6,
"inputLabels": [
"System default (Mic/Line/Inst 1-2 (MiniFuse 4))",
"Loopback Mix Left/Right (MiniFuse 4)",
"Headset Microphone (Oculus Virtual Audio Device)",
"Line 3-4 (MiniFuse 4)",
"Микрофон (DroidCam Audio)",
"Микрофон (Virtual Desktop Audio)",
"Mic/Line/Inst 1-2 (MiniFuse 4)"
],
"outputLabels": [
"System default (Main Left/Right (MiniFuse 4))",
"Main Left/Right (MiniFuse 4)",
"Realtek Digital Output (Realtek(R) Audio)",
"Virtual Left/Right (MiniFuse 4)",
"LG ULTRAGEAR (NVIDIA High Definition Audio)",
"Наушники (Oculus Virtual Audio Device)",
"Aux Left/Right (MiniFuse 4)"
],
"status": "Microphones found: 6; output devices: 6.",
"conn": "disconnected",
"framesSent": 0,
"capturing": false
},
{
"name": "selected",
"inputChoice": "Headset Microphone (Oculus Virtual Audio Device)",
"outputChoice": "Realtek Digital Output (Realtek(R) Audio)",
"toasts": [],
"framesSent": 0,
"capturing": false
},
{
"name": "after restart",
"inputNow": "Headset Microphone (Oculus Virtual Audio Device)",
"outputNow": "Realtek Digital Output (Realtek(R) Audio)",
"persisted": true,
"toasts": [],
"conn": "disconnected"
}
],
"console": [],
"ok": true
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

@@ -0,0 +1,50 @@
{
"steps": [
{
"name": "os app theme",
"appsUseTheme": "dark"
},
{
"name": "new profile: onboarding",
"themeSource": "dark",
"windowBackground": "#1A1817",
"prefersDark": true,
"bodyBackground": "rgb(27, 32, 41)",
"bg": "#1b2029"
},
{
"name": "onboarding brand mark",
"src": "/assets/icon.png",
"naturalWidth": 256,
"naturalHeight": 256,
"shownWidth": 56
},
{
"name": "settings shows dark selected",
"checked": "dark"
},
{
"name": "switched to light",
"themeSource": "light",
"windowBackground": "#1A1817",
"prefersDark": false,
"bodyBackground": "rgb(246, 243, 240)",
"bg": "#f6f3f0"
},
{
"name": "restart keeps light",
"themeSource": "light",
"windowBackground": "#F6F3F0",
"prefersDark": false,
"bodyBackground": "rgb(246, 243, 240)",
"bg": "#f6f3f0",
"stored": "light"
},
{
"name": "stored \"system\" kept",
"legacyStored": "system",
"prefersDark": true
}
],
"ok": true
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB

@@ -0,0 +1,77 @@
{
"startedAt": "2026-10-24T04:32:12.963Z",
"profile": "C:\\Users\\Admin\\AppData\\Local\\Temp\\teamspeach-smoke-WEcYS4",
"steps": [
{
"name": "screenshot 01-first-launch-onboarding.png",
"at": "2026-10-24T04:32:13.645Z"
},
{
"name": "short nickname rejected",
"at": "2026-10-24T04:32:13.675Z",
"message": "Nickname must contain 3–30 characters."
},
{
"name": "profile created",
"at": "2026-10-24T04:32:14.413Z",
"uid": "IS+EYqLp6wbT5w9mqFyxjaUcvbY=",
"nickname": "PeachSmoke"
},
{
"name": "screenshot 02-after-onboarding.png",
"at": "2026-10-24T04:32:14.769Z"
},
{
"name": "restart keeps identity",
"at": "2026-10-24T04:32:15.936Z",
"uid": "IS+EYqLp6wbT5w9mqFyxjaUcvbY=",
"nickname": "PeachSmoke",
"same": true
},
{
"name": "renamed",
"at": "2026-10-24T04:32:16.004Z",
"uid": "IS+EYqLp6wbT5w9mqFyxjaUcvbY=",
"nickname": "PeachRenamed",
"status": "Saved. UID unchanged.",
"same": true
},
{
"name": "screenshot 03-settings-renamed.png",
"at": "2026-10-24T04:32:16.357Z"
},
{
"name": "rename persisted",
"at": "2026-10-24T04:32:17.544Z",
"uid": "IS+EYqLp6wbT5w9mqFyxjaUcvbY=",
"nickname": "PeachRenamed",
"ok": true
},
{
"name": "identity exported",
"at": "2026-10-24T04:32:17.620Z",
"status": "Saved to “identity.ini”. UID IS+EYqLp6wbT5w9mqFyxjaUcvbY=.",
"statusHasUid": true,
"iniHeader": "[Identity]",
"containsIdentityKey": true
},
{
"name": "hardware decode disabled, restart required",
"at": "2026-10-24T04:32:17.667Z",
"status": "This run: allowed. Chromium engine: hardware decoding is allowed and available to the engine."
},
{
"name": "after restart",
"at": "2026-10-24T04:32:19.074Z",
"status": "This run: disabled (disable-accelerated-video-decode flag). Chromium engine: hardware decoding is disabled; the engine will use software decoding.",
"restartHint": false
},
{
"name": "screenshot 05-video-decode-disabled.png",
"at": "2026-10-24T04:32:19.452Z"
}
],
"console": [],
"finishedAt": "2026-10-24T04:32:19.574Z",
"ok": true
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

@@ -0,0 +1,94 @@
{
"steps": [
{
"name": "mic right-click",
"menu": true,
"inputMuted": false,
"capturing": false,
"framesSent": 0,
"items": [
{
"label": "Системное по умолчанию (Mic/Line/Inst 1-2 (MiniFuse 4))",
"checked": "true"
},
{
"label": "Loopback Mix Left/Right (MiniFuse 4)",
"checked": "false"
},
{
"label": "Headset Microphone (Oculus Virtual Audio Device)",
"checked": "false"
},
{
"label": "Line 3-4 (MiniFuse 4)",
"checked": "false"
},
{
"label": "Микрофон (DroidCam Audio)",
"checked": "false"
},
{
"label": "Микрофон (Virtual Desktop Audio)",
"checked": "false"
},
{
"label": "Mic/Line/Inst 1-2 (MiniFuse 4)",
"checked": "false"
}
],
"insideViewport": true,
"focused": "menu-item"
},
{
"name": "menu choice reflected in settings",
"pick": "Headset Microphone (Oculus Virtual Audio Device)",
"settingsInput": "Headset Microphone (Oculus Virtual Audio Device)",
"same": true
},
{
"name": "headphones Shift+F10",
"menu": true,
"outputMuted": false,
"items": [
"Системное по умолчанию (Main Left/Right (MiniFuse 4))",
"Main Left/Right (MiniFuse 4)",
"Realtek Digital Output (Realtek(R) Audio)",
"Virtual Left/Right (MiniFuse 4)",
"LG ULTRAGEAR (NVIDIA High Definition Audio)",
"Наушники (Oculus Virtual Audio Device)",
"Aux Left/Right (MiniFuse 4)"
],
"insideViewport": true
},
{
"name": "escape",
"menuClosed": true,
"focusRestored": true,
"outputMuted": false
},
{
"name": "left click still toggles mute",
"inputMuted": true
},
{
"name": "rapid mic → headphones while enumeration pending",
"menus": 1,
"label": "Устройство вывода",
"items": 7
},
{
"name": "dismissed before enumeration finished",
"menus": 0,
"focused": "connect-address",
"expanded": "false"
},
{
"name": "after restart",
"checkedIn": "Headset Microphone (Oculus Virtual Audio Device)",
"checkedOut": "Realtek Digital Output (Realtek(R) Audio)",
"persisted": true
}
],
"console": [],
"ok": true
}
@@ -0,0 +1,49 @@
{
"steps": [
{
"name": "listed without capture",
"inputs": 6,
"outputs": 6,
"inputLabels": [
"Системное по умолчанию (Mic/Line/Inst 1-2 (MiniFuse 4))",
"Loopback Mix Left/Right (MiniFuse 4)",
"Headset Microphone (Oculus Virtual Audio Device)",
"Line 3-4 (MiniFuse 4)",
"Микрофон (DroidCam Audio)",
"Микрофон (Virtual Desktop Audio)",
"Mic/Line/Inst 1-2 (MiniFuse 4)"
],
"outputLabels": [
"Системное по умолчанию (Main Left/Right (MiniFuse 4))",
"Main Left/Right (MiniFuse 4)",
"Realtek Digital Output (Realtek(R) Audio)",
"Virtual Left/Right (MiniFuse 4)",
"LG ULTRAGEAR (NVIDIA High Definition Audio)",
"Наушники (Oculus Virtual Audio Device)",
"Aux Left/Right (MiniFuse 4)"
],
"status": "Найдено микрофонов: 6, устройств вывода: 6.",
"conn": "disconnected",
"framesSent": 0,
"capturing": false
},
{
"name": "selected",
"inputChoice": "Headset Microphone (Oculus Virtual Audio Device)",
"outputChoice": "Realtek Digital Output (Realtek(R) Audio)",
"toasts": [],
"framesSent": 0,
"capturing": false
},
{
"name": "after restart",
"inputNow": "Headset Microphone (Oculus Virtual Audio Device)",
"outputNow": "Realtek Digital Output (Realtek(R) Audio)",
"persisted": true,
"toasts": [],
"conn": "disconnected"
}
],
"console": [],
"ok": true
}
@@ -0,0 +1,94 @@
{
"steps": [
{
"name": "mic right-click",
"menu": true,
"inputMuted": false,
"capturing": false,
"framesSent": 0,
"items": [
{
"label": "Системное по умолчанию (Mic/Line/Inst 1-2 (MiniFuse 4))",
"checked": "true"
},
{
"label": "Loopback Mix Left/Right (MiniFuse 4)",
"checked": "false"
},
{
"label": "Headset Microphone (Oculus Virtual Audio Device)",
"checked": "false"
},
{
"label": "Line 3-4 (MiniFuse 4)",
"checked": "false"
},
{
"label": "Микрофон (DroidCam Audio)",
"checked": "false"
},
{
"label": "Микрофон (Virtual Desktop Audio)",
"checked": "false"
},
{
"label": "Mic/Line/Inst 1-2 (MiniFuse 4)",
"checked": "false"
}
],
"insideViewport": true,
"focused": "menu-item"
},
{
"name": "menu choice reflected in settings",
"pick": "Headset Microphone (Oculus Virtual Audio Device)",
"settingsInput": "Headset Microphone (Oculus Virtual Audio Device)",
"same": true
},
{
"name": "headphones Shift+F10",
"menu": true,
"outputMuted": false,
"items": [
"Системное по умолчанию (Main Left/Right (MiniFuse 4))",
"Main Left/Right (MiniFuse 4)",
"Realtek Digital Output (Realtek(R) Audio)",
"Virtual Left/Right (MiniFuse 4)",
"LG ULTRAGEAR (NVIDIA High Definition Audio)",
"Наушники (Oculus Virtual Audio Device)",
"Aux Left/Right (MiniFuse 4)"
],
"insideViewport": true
},
{
"name": "escape",
"menuClosed": true,
"focusRestored": true,
"outputMuted": false
},
{
"name": "left click still toggles mute",
"inputMuted": true
},
{
"name": "rapid mic → headphones while enumeration pending",
"menus": 1,
"label": "Устройство вывода",
"items": 7
},
{
"name": "dismissed before enumeration finished",
"menus": 0,
"focused": "connect-address",
"expanded": "false"
},
{
"name": "after restart",
"checkedIn": "Headset Microphone (Oculus Virtual Audio Device)",
"checkedOut": "Realtek Digital Output (Realtek(R) Audio)",
"persisted": true
}
],
"console": [],
"ok": true
}
@@ -0,0 +1,49 @@
{
"steps": [
{
"name": "listed without capture",
"inputs": 6,
"outputs": 6,
"inputLabels": [
"Системное по умолчанию (Mic/Line/Inst 1-2 (MiniFuse 4))",
"Loopback Mix Left/Right (MiniFuse 4)",
"Headset Microphone (Oculus Virtual Audio Device)",
"Line 3-4 (MiniFuse 4)",
"Микрофон (DroidCam Audio)",
"Микрофон (Virtual Desktop Audio)",
"Mic/Line/Inst 1-2 (MiniFuse 4)"
],
"outputLabels": [
"Системное по умолчанию (Main Left/Right (MiniFuse 4))",
"Main Left/Right (MiniFuse 4)",
"Realtek Digital Output (Realtek(R) Audio)",
"Virtual Left/Right (MiniFuse 4)",
"LG ULTRAGEAR (NVIDIA High Definition Audio)",
"Наушники (Oculus Virtual Audio Device)",
"Aux Left/Right (MiniFuse 4)"
],
"status": "Найдено микрофонов: 6, устройств вывода: 6.",
"conn": "disconnected",
"framesSent": 0,
"capturing": false
},
{
"name": "selected",
"inputChoice": "Headset Microphone (Oculus Virtual Audio Device)",
"outputChoice": "Realtek Digital Output (Realtek(R) Audio)",
"toasts": [],
"framesSent": 0,
"capturing": false
},
{
"name": "after restart",
"inputNow": "Headset Microphone (Oculus Virtual Audio Device)",
"outputNow": "Realtek Digital Output (Realtek(R) Audio)",
"persisted": true,
"toasts": [],
"conn": "disconnected"
}
],
"console": [],
"ok": true
}
@@ -0,0 +1,10 @@
{
"steps": [
{
"name": "FAILED",
"error": "electron.launch: Timeout 180000ms exceeded.\nCall log:\n\u001b[2m - <launching> \"C:\\Users\\Admin\\Desktop\\projects\\TeamsPeach\\dist\\win-unpacked\\TeamsPeach.exe\" \"--inspect=0\" \"--remote-debugging-port=0\"\u001b[22m\n\u001b[2m - <launched> pid=4588\u001b[22m\n\u001b[2m - [pid=4588][out]\u001b[22m\n\u001b[2m - [pid=4588][err] Debugger listening on ws://127.0.0.1:63427/fe8be778-dfa5-4682-a04e-1fbfc456af8f\u001b[22m\n\u001b[2m - [pid=4588][err] For help, see: https://nodejs.org/learn/getting-started/debugging\u001b[22m\n\u001b[2m - <ws connecting> ws://127.0.0.1:63427/fe8be778-dfa5-4682-a04e-1fbfc456af8f\u001b[22m\n\u001b[2m - <ws connected> ws://127.0.0.1:63427/fe8be778-dfa5-4682-a04e-1fbfc456af8f\u001b[22m\n\u001b[2m - [pid=4588][err] Debugger attached.\u001b[22m\n\u001b[2m - [pid=4588][err]\u001b[22m\n\u001b[2m - [pid=4588][err] DevTools listening on ws://127.0.0.1:63429/devtools/browser/5f28a818-8da7-4cf7-a0ac-26a82d2ac4ef\u001b[22m\n\u001b[2m - <ws connecting> ws://127.0.0.1:63429/devtools/browser/5f28a818-8da7-4cf7-a0ac-26a82d2ac4ef\u001b[22m\n\u001b[2m - <ws connected> ws://127.0.0.1:63429/devtools/browser/5f28a818-8da7-4cf7-a0ac-26a82d2ac4ef\u001b[22m\n\n at async launch (C:\\Users\\Admin\\Desktop\\projects\\TeamsPeach\\scripts\\smoke-devices.mjs:27:15)\n at async file:///C:/Users/Admin/Desktop/projects/TeamsPeach/scripts/smoke-devices.mjs:59:20"
}
],
"console": [],
"ok": false
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

@@ -0,0 +1,95 @@
{
"steps": [
{
"name": "mic right-click",
"menu": true,
"inputMuted": false,
"capturing": false,
"framesSent": 0,
"items": [
{
"label": "System default (Mic/Line/Inst 1-2 (MiniFuse 4))",
"checked": "true"
},
{
"label": "Loopback Mix Left/Right (MiniFuse 4)",
"checked": "false"
},
{
"label": "Headset Microphone (Oculus Virtual Audio Device)",
"checked": "false"
},
{
"label": "Line 3-4 (MiniFuse 4)",
"checked": "false"
},
{
"label": "Микрофон (DroidCam Audio)",
"checked": "false"
},
{
"label": "Микрофон (Virtual Desktop Audio)",
"checked": "false"
},
{
"label": "Mic/Line/Inst 1-2 (MiniFuse 4)",
"checked": "false"
}
],
"insideViewport": true,
"focused": "menu-item"
},
{
"name": "menu choice reflected in settings",
"pick": "Headset Microphone (Oculus Virtual Audio Device)",
"settingsInput": "Headset Microphone (Oculus Virtual Audio Device)",
"same": true
},
{
"name": "headphones Shift+F10",
"menu": true,
"outputMuted": false,
"items": [
"System default (Main Left/Right (MiniFuse 4))",
"Main Left/Right (MiniFuse 4)",
"Realtek Digital Output (Realtek(R) Audio)",
"Virtual Left/Right (MiniFuse 4)",
"LG ULTRAGEAR (NVIDIA High Definition Audio)",
"Наушники (Oculus Virtual Audio Device)",
"Aux Left/Right (MiniFuse 4)"
],
"insideViewport": true
},
{
"name": "escape",
"menuClosed": true,
"focusRestored": true,
"outputMuted": false
},
{
"name": "left click still toggles mute",
"inputMuted": true
},
{
"name": "rapid mic → headphones while enumeration pending",
"menus": 1,
"outputExpanded": "true",
"inputExpanded": "false",
"items": 7
},
{
"name": "dismissed before enumeration finished",
"menus": 0,
"focused": "connect-address",
"expanded": "false"
},
{
"name": "after restart",
"checkedIn": "Headset Microphone (Oculus Virtual Audio Device)",
"checkedOut": "Realtek Digital Output (Realtek(R) Audio)",
"persisted": true
}
],
"console": [],
"ok": true
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

@@ -0,0 +1,43 @@
{
"steps": [
{
"name": "os app theme",
"appsUseTheme": "dark"
},
{
"name": "new profile: onboarding",
"themeSource": "dark",
"windowBackground": "#1A1817",
"prefersDark": true,
"bodyBackground": "rgb(27, 32, 41)",
"bg": "#1b2029"
},
{
"name": "settings shows dark selected",
"checked": "dark"
},
{
"name": "switched to light",
"themeSource": "light",
"windowBackground": "#1A1817",
"prefersDark": false,
"bodyBackground": "rgb(246, 243, 240)",
"bg": "#f6f3f0"
},
{
"name": "restart keeps light",
"themeSource": "light",
"windowBackground": "#F6F3F0",
"prefersDark": false,
"bodyBackground": "rgb(246, 243, 240)",
"bg": "#f6f3f0",
"stored": "light"
},
{
"name": "stored \"system\" kept",
"legacyStored": "system",
"prefersDark": true
}
],
"ok": true
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

@@ -0,0 +1,95 @@
{
"steps": [
{
"name": "mic right-click",
"menu": true,
"inputMuted": false,
"capturing": false,
"framesSent": 0,
"items": [
{
"label": "System default (Mic/Line/Inst 1-2 (MiniFuse 4))",
"checked": "true"
},
{
"label": "Loopback Mix Left/Right (MiniFuse 4)",
"checked": "false"
},
{
"label": "Headset Microphone (Oculus Virtual Audio Device)",
"checked": "false"
},
{
"label": "Line 3-4 (MiniFuse 4)",
"checked": "false"
},
{
"label": "Микрофон (DroidCam Audio)",
"checked": "false"
},
{
"label": "Микрофон (Virtual Desktop Audio)",
"checked": "false"
},
{
"label": "Mic/Line/Inst 1-2 (MiniFuse 4)",
"checked": "false"
}
],
"insideViewport": true,
"focused": "menu-item"
},
{
"name": "menu choice reflected in settings",
"pick": "Headset Microphone (Oculus Virtual Audio Device)",
"settingsInput": "Headset Microphone (Oculus Virtual Audio Device)",
"same": true
},
{
"name": "headphones Shift+F10",
"menu": true,
"outputMuted": false,
"items": [
"System default (Main Left/Right (MiniFuse 4))",
"Main Left/Right (MiniFuse 4)",
"Realtek Digital Output (Realtek(R) Audio)",
"Virtual Left/Right (MiniFuse 4)",
"LG ULTRAGEAR (NVIDIA High Definition Audio)",
"Наушники (Oculus Virtual Audio Device)",
"Aux Left/Right (MiniFuse 4)"
],
"insideViewport": true
},
{
"name": "escape",
"menuClosed": true,
"focusRestored": true,
"outputMuted": false
},
{
"name": "left click still toggles mute",
"inputMuted": true
},
{
"name": "rapid mic → headphones while enumeration pending",
"menus": 1,
"outputExpanded": "true",
"inputExpanded": "false",
"items": 7
},
{
"name": "dismissed before enumeration finished",
"menus": 0,
"focused": "connect-address",
"expanded": "false"
},
{
"name": "after restart",
"checkedIn": "Headset Microphone (Oculus Virtual Audio Device)",
"checkedOut": "Realtek Digital Output (Realtek(R) Audio)",
"persisted": true
}
],
"console": [],
"ok": true
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

@@ -0,0 +1,49 @@
{
"steps": [
{
"name": "listed without capture",
"inputs": 6,
"outputs": 6,
"inputLabels": [
"System default (Mic/Line/Inst 1-2 (MiniFuse 4))",
"Loopback Mix Left/Right (MiniFuse 4)",
"Headset Microphone (Oculus Virtual Audio Device)",
"Line 3-4 (MiniFuse 4)",
"Микрофон (DroidCam Audio)",
"Микрофон (Virtual Desktop Audio)",
"Mic/Line/Inst 1-2 (MiniFuse 4)"
],
"outputLabels": [
"System default (Main Left/Right (MiniFuse 4))",
"Main Left/Right (MiniFuse 4)",
"Realtek Digital Output (Realtek(R) Audio)",
"Virtual Left/Right (MiniFuse 4)",
"LG ULTRAGEAR (NVIDIA High Definition Audio)",
"Наушники (Oculus Virtual Audio Device)",
"Aux Left/Right (MiniFuse 4)"
],
"status": "Microphones found: 6; output devices: 6.",
"conn": "disconnected",
"framesSent": 0,
"capturing": false
},
{
"name": "selected",
"inputChoice": "Headset Microphone (Oculus Virtual Audio Device)",
"outputChoice": "Realtek Digital Output (Realtek(R) Audio)",
"toasts": [],
"framesSent": 0,
"capturing": false
},
{
"name": "after restart",
"inputNow": "Headset Microphone (Oculus Virtual Audio Device)",
"outputNow": "Realtek Digital Output (Realtek(R) Audio)",
"persisted": true,
"toasts": [],
"conn": "disconnected"
}
],
"console": [],
"ok": true
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

@@ -0,0 +1,43 @@
{
"steps": [
{
"name": "os app theme",
"appsUseTheme": "dark"
},
{
"name": "new profile: onboarding",
"themeSource": "dark",
"windowBackground": "#1A1817",
"prefersDark": true,
"bodyBackground": "rgb(27, 32, 41)",
"bg": "#1b2029"
},
{
"name": "settings shows dark selected",
"checked": "dark"
},
{
"name": "switched to light",
"themeSource": "light",
"windowBackground": "#1A1817",
"prefersDark": false,
"bodyBackground": "rgb(246, 243, 240)",
"bg": "#f6f3f0"
},
{
"name": "restart keeps light",
"themeSource": "light",
"windowBackground": "#F6F3F0",
"prefersDark": false,
"bodyBackground": "rgb(246, 243, 240)",
"bg": "#f6f3f0",
"stored": "light"
},
{
"name": "stored \"system\" kept",
"legacyStored": "system",
"prefersDark": true
}
],
"ok": true
}
Loaded 100 of 191 files, more files were not shown because too many files have changed in this diff. Show more