Release: cut over Echoion 2.0 components
Modular container CI / release-build (push) Has been cancelled

This commit is contained in:
faumaray committed 2026-07-29 20:35:27 +03:00
1 parent 1305d37fae
commit 458dde05a6
169 files changed
+3069 -32261

No files matched your search

+1
View File
@@ -4,4 +4,5 @@ dist
release
EchoionWeb/frontend/node_modules
EchoionWeb/frontend/web-dist
components
docs
+61 -46
View File
@@ -58,44 +58,50 @@ Enable Actions and add these repository secrets:
| Secret | Purpose |
| --- | --- |
| `RELEASE_CHECKOUT_SSH_KEY` | Read-only key used for the root checkout. |
| `RELEASE_BOT_TOKEN` | PAT owned by a dedicated bot. It needs read access to the component repositories plus release/tag and `release-feed` write access in this repository. |
| `RELEASE_CHECKOUT_SSH_KEY` | Read-only SSH key used for root, component, and `release-feed` checkouts. Grant it access to every private component repository before cutover. |
| `RELEASE_BOT_TOKEN` | PAT owned by a dedicated bot. It needs read access to every component repository plus release/tag and `release-feed` write access in this repository. |
| `RELEASE_TAG_ALLOWED_SIGNERS` | Complete OpenSSH `allowed_signers` lines for maintainers allowed to publish `v*` tags. |
| `RELEASE_FEED_ED25519_PRIVATE_KEY` | PEM private key matching `release-keys/echoion-release-2026-07.pub.pem`. Preserve its newlines. |
Component checkouts use the release PAT with `persist-credentials: false`, so
the credential is removed before repository scripts run. The feed signing key
must not be stored in Git, runner images, Actions variables, or release assets.
Component checkouts use SSH with `persist-credentials: false`. Release API
operations use the bot PAT, but Git fetches and pushes never rewrite remotes to
HTTPS. The feed signing key must not be stored in Git, runner images, Actions
variables, or release assets.
## Independent component repositories
Echoion does not use Git submodules. `components.lock.json` is the immutable
checkout manifest for `EchoionApi`, `EchoionCore`, and `EchoionDesktop`. CMake
uses a component already present beside the root checkout; otherwise it fetches
the locked revision. All three Gitea workflows check out those revisions as
ordinary repositories before entering Docker.
Echoion does not use Git submodules. `components.json` describes the nine
independent repositories: `EchoionApi`, `EchoionHost`, `EchoionCore`,
`EchoionWeb`, `EchoionStandalone`, `EchoionUpdater`, `EchoionDesktop`,
`EchoionPluginUrlShortenerInternal`, and
`EchoionPluginUrlShortenerExternal`. `components.lock.json` is the immutable
release checkout manifest. All Gitea workflows check out the locked revisions
as ordinary SSH repositories before entering Docker.
For a new developer checkout:
```bash
python3 scripts/sync-components.py
scripts/prepare-release.sh --workspace ..
```
After changing a component, commit and push that component first, then refresh
and commit the root lock:
For ordinary development CMake follows each component's `main` branch unless a
`CPM_<Component>_SOURCE` override is supplied. Release builds use the exact
lock. After changing a component, make a signed commit and push it over SSH
first, then refresh and commit the root lock:
```bash
python3 scripts/sync-components.py --record
scripts/prepare-release.sh --workspace ..
git add components.lock.json
git commit -S -m 'Release: lock Echoion 2.0.0 components'
```
`--record` refuses dirty component repositories, so a lock can never point at
uncommitted source. `--update` moves existing clean component checkouts to the
locked revisions. Product version changes are separate: edit only
The preparer refuses dirty, inaccessible, missing, non-fast-forward, or
version/tag-inconsistent component repositories, so a lock can never point at
unpublished source. Product version changes are separate: edit only
`project(Echoion VERSION ...)` in root `CMakeLists.txt`; orchestrated component
builds and release overrides inherit that value. A stable or beta release tag
must have the same numeric base as this CMake version, so `v1.2.3` and
`v1.2.3-rc.1` both require `project(Echoion VERSION 1.2.3 ...)`. The release
must have the same numeric base as this CMake version, so `v2.0.0` and
`v2.0.0-rc.1` both require `project(Echoion VERSION 2.0.0 ...)`. The release
workflow rejects mismatches before building.
Nightlies use the newer of the root CMake version and the next patch after the
@@ -114,17 +120,28 @@ Gitea uses the same allowlist for tag creation and later tag changes; when
immutable release tags are required, add a server-side pre-receive policy that
rejects updates and deletion after creation. Protect `main` in the normal way.
The updater feed URL is:
The updater source can use the feed base:
```text
https://<gitea>/<owner>/<repo>/raw/branch/release-feed/feeds/echoion-runtime.json
https://<gitea>/<owner>/<repo>/raw/branch/release-feed
```
The embedded updater trust configuration is represented by
`release-keys/official-update-keys.json`. `scripts/release.sh` validates and
or an exact channel catalog:
```text
https://<gitea>/<owner>/<repo>/raw/branch/release-feed/feeds/stable/catalog.json
```
The catalog resolves immutable component documents under
`feeds/<channel>/<component>/<version>.json` and plugin documents under
`feeds/<channel>/plugins/<plugin-id>/<version>.json`. The embedded updater
trust configuration is represented by
`.gitea/release-keys/official-update-keys.json`. `scripts/release.sh` validates and
embeds that JSON automatically. Release workflows also pass the HTTPS
`release-feed` branch URL through `--official-update-feed-url`, so a fresh
installation has a signed official source without operator-side duplication.
channel catalog through `--official-update-feed-url`, so a fresh installation
has a signed official source without operator-side duplication. The v1
`feeds/echoion-runtime.json` feed is not published at the 2.0 cutover; v1
operators must stop their service and run the signed v2 installer manually.
## Stable and beta releases
@@ -136,9 +153,9 @@ for the tag:
```bash
git config gpg.format ssh
git config user.signingkey ~/.ssh/echoion-release-maintainer
git tag -s -a v1.2.3 -m 'Echoion 1.2.3'
test "$(git cat-file -t refs/tags/v1.2.3)" = tag
git push origin v1.2.3
git tag -s -a v2.0.0 -m 'Echoion 2.0.0'
test "$(git cat-file -t refs/tags/v2.0.0)" = tag
git push origin v2.0.0
```
The private-key path works without an SSH agent. A `.pub` path may be used
@@ -155,8 +172,9 @@ The workflow creates or resumes a draft, replaces incomplete draft assets,
uploads every file in `dist/`, downloads every asset through Gitea, checks
its size and SHA-256, and only then publishes. A rerun against an already
published release is read-only and succeeds only when all remote assets still
match. The signed aggregate feed is committed after release publication; a
feed failure can therefore be retried without replacing a published release.
match. The signed catalog and all component feeds are committed together after
release publication; a feed failure can therefore be retried without replacing
a published release.
## Nightly releases
@@ -167,15 +185,16 @@ semantic release, nightlies use the root CMake
`project(Echoion VERSION x.y.z)` value without incrementing it. Drafts, failed
publications, and `nightly-*` releases do not affect the base. Nightlies use the
`nightly` channel, publish as prereleases, and keep the newest 14 Gitea
releases. The aggregate feed also keeps the newest 14 distinct nightly versions
while retaining stable and beta records. Gitea materializes a missing
releases. Channel catalogs remain separate, and nightly publication never
advances stable component state. Gitea materializes a missing
`nightly-*` Git tag only when the download-verified draft is published; the
publisher then verifies its commit immediately and never moves an existing tag
whose target differs. Stable and beta publishing require their signed tag to
exist before creating a draft. If `nightly-*` is protected separately, allow
the release bot to create and delete it.
Every aggregate envelope expires 45 days after generation. Scheduled
Every rolling catalog and `latest.json` envelope expires 45 days after
generation. Scheduled
nightlies normally refresh it daily. Alert when the feed branch has not
advanced for more than seven days, and treat 30 days without a successful
signing run as urgent.
@@ -204,17 +223,12 @@ openssl pkey -pubin -in echoion-release-YYYY-MM.pub.pem -outform DER |
printf '\n'
```
Add the new public key to official builds before signing any feed with it.
Keep the old public key embedded for at least one full update lifetime. During
the first signing run with the new key, pass each prior envelope key explicitly
to `aggregate_update_feed.py` as
`--trusted-existing-key OLD_KEY_ID=OLD_PUBLIC_KEY_PATH`; this permits only
verification of the old envelope and never selects the old key for signing.
Update the signing key id and public-key paths in both release workflows, add
the old-key verification argument while an old envelope may exist, and replace
the private-key secret. The merger verifies the newly generated signature
against the new committed public key before writing either output. Never print
the private key or pass it as a command-line argument.
Add the new public key to official builds before signing any feed with it and
keep the old public key embedded for at least one full update lifetime. Update
the signing key id in both release workflows and replace the private-key
secret only after the build containing both trust roots is installed broadly.
Immutable version feeds are never rewritten during rotation. Never print the
private key or pass it as a command-line argument.
## Recovery rules
@@ -227,5 +241,6 @@ the private key or pass it as a command-line argument.
- A failed feed push leaves the published release available but undiscoverable
to auto-update. Rerun the workflow; publication verification is idempotent
and the feed step will run again.
- Never edit `release-feed` manually. The merger verifies the existing
Ed25519 envelope before using any prior entries.
- Never edit `release-feed` manually. The publisher validates immutable
version feeds, replay sequences, and component state before committing the
complete transaction.
+39 -65
View File
@@ -1,4 +1,4 @@
name: Container CI
name: Modular container CI
on:
push:
@@ -22,7 +22,7 @@ jobs:
docker version
docker info
- name: Check out source
- name: Check out root over SSH
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
fetch-depth: 0
@@ -32,79 +32,53 @@ jobs:
git.faumaray.ru ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw==
persist-credentials: false
- name: Read locked component repositories
id: components
- name: Verify source-free root and resolve every lock over SSH
shell: bash
env:
ECHOION_COMPONENT_SSH_KEY: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }}
run: |
set -euo pipefail
python3 - "$GITHUB_OUTPUT" <<'PY'
import json
import pathlib
import sys
lock = json.loads(pathlib.Path("components.lock.json").read_text())
with pathlib.Path(sys.argv[1]).open("a") as output:
for component, key in (
("EchoionApi", "api"),
("EchoionCore", "core"),
("EchoionDesktop", "desktop"),
):
entry = lock["components"][component]
print(f"{key}_repository={entry['repository']}", file=output)
print(f"{key}_revision={entry['revision']}", file=output)
PY
- name: Check out EchoionApi
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
repository: ${{ steps.components.outputs.api_repository }}
ref: ${{ steps.components.outputs.api_revision }}
path: EchoionApi
fetch-depth: 1
token: ${{ secrets.RELEASE_BOT_TOKEN }}
persist-credentials: false
- name: Check out EchoionCore
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
repository: ${{ steps.components.outputs.core_repository }}
ref: ${{ steps.components.outputs.core_revision }}
path: EchoionCore
fetch-depth: 1
token: ${{ secrets.RELEASE_BOT_TOKEN }}
persist-credentials: false
- name: Check out EchoionDesktop
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
repository: ${{ steps.components.outputs.desktop_repository }}
ref: ${{ steps.components.outputs.desktop_revision }}
path: EchoionDesktop
fetch-depth: 1
token: ${{ secrets.RELEASE_BOT_TOKEN }}
persist-credentials: false
test ! -e .gitmodules
if git ls-files -s | awk '$1 == "160000" { found=1 } END { exit !found }'
then
echo "root release contains a gitlink" >&2
exit 1
fi
scripts/ci-checkout-components.sh \
"$PWD/components" \
"$PWD/dependencies"
scripts/prepare-release.sh \
--workspace "$PWD/components" \
--check
- name: Build, test, and package without starting Echoion
env:
CI_VERSION: 0.0.0-ci.${{ gitea.run_number }}.${{ gitea.run_attempt }}
CI_VERSION: 2.0.0-ci.${{ gitea.run_number }}.${{ gitea.run_attempt }}
run: |
set -eu
scripts/release.sh --version "$CI_VERSION"
set -euo pipefail
scripts/release.sh \
--version "$CI_VERSION" \
--component-workspace "$PWD/components" \
--void-source "$PWD/dependencies/VoidLibrary" \
--void-teamspeak-source "$PWD/dependencies/VoidTeamspeak" \
--update-channel beta \
--update-sequence "${{ gitea.run_number }}"
- name: Test release control-plane scripts
- name: Test release control-plane scripts offline
shell: bash
run: |
set -eu
set -euo pipefail
bash scripts/tests/test-gitea-tag-verification.sh
. scripts/lib/docker-daemon-path.sh
docker_workspace=$(docker_daemon_path "$PWD")
docker run --rm --network none \
--volume "$docker_workspace:/workspace:ro" \
--workdir /workspace \
echoion-release-builder:gcc-16.1.0 \
python3 scripts/tests/test_aggregate_update_feed.py
docker run --rm --network none \
--volume "$docker_workspace:/workspace:ro" \
--workdir /workspace \
echoion-release-builder:gcc-16.1.0 \
python3 scripts/tests/test_gitea_release.py
for test_script in \
scripts/tests/test_package_components.py \
scripts/tests/test_publish_component_feeds.py \
scripts/tests/test_gitea_release.py
do
docker run --rm --network none \
--volume "$docker_workspace:/workspace:ro" \
--workdir /workspace \
echoion-release-builder:gcc-16.1.0 \
python3 "$test_script"
done
+66 -113
View File
@@ -1,4 +1,4 @@
name: Nightly release
name: Nightly modular release
on:
schedule:
@@ -8,6 +8,10 @@ on:
permissions:
contents: read
concurrency:
group: echoion-release-feed
cancel-in-progress: false
jobs:
publish-nightly:
runs-on: ubuntu-24.04
@@ -21,7 +25,7 @@ jobs:
docker version
docker info
- name: Check out main
- name: Check out signed main over SSH
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
ref: main
@@ -32,59 +36,26 @@ jobs:
git.faumaray.ru ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw==
persist-credentials: false
- name: Read locked component repositories
id: components
- name: Verify root cutover and check out locked components over SSH
shell: bash
env:
ECHOION_COMPONENT_SSH_KEY: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }}
run: |
set -euo pipefail
python3 - "$GITHUB_OUTPUT" <<'PY'
import json
import pathlib
import sys
test ! -e .gitmodules
if git ls-files -s | awk '$1 == "160000" { found=1 } END { exit !found }'
then
echo "root release contains a gitlink" >&2
exit 1
fi
scripts/ci-checkout-components.sh \
"$PWD/components" \
"$PWD/dependencies"
scripts/prepare-release.sh \
--workspace "$PWD/components" \
--check
lock = json.loads(pathlib.Path("components.lock.json").read_text())
with pathlib.Path(sys.argv[1]).open("a") as output:
for component, key in (
("EchoionApi", "api"),
("EchoionCore", "core"),
("EchoionDesktop", "desktop"),
):
entry = lock["components"][component]
print(f"{key}_repository={entry['repository']}", file=output)
print(f"{key}_revision={entry['revision']}", file=output)
PY
- name: Check out EchoionApi
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
repository: ${{ steps.components.outputs.api_repository }}
ref: ${{ steps.components.outputs.api_revision }}
path: EchoionApi
fetch-depth: 1
token: ${{ secrets.RELEASE_BOT_TOKEN }}
persist-credentials: false
- name: Check out EchoionCore
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
repository: ${{ steps.components.outputs.core_repository }}
ref: ${{ steps.components.outputs.core_revision }}
path: EchoionCore
fetch-depth: 1
token: ${{ secrets.RELEASE_BOT_TOKEN }}
persist-credentials: false
- name: Check out EchoionDesktop
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
repository: ${{ steps.components.outputs.desktop_repository }}
ref: ${{ steps.components.outputs.desktop_revision }}
path: EchoionDesktop
fetch-depth: 1
token: ${{ secrets.RELEASE_BOT_TOKEN }}
persist-credentials: false
- name: Derive the nightly identity
- name: Derive nightly identity and URLs
shell: bash
env:
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }}
@@ -108,36 +79,37 @@ jobs:
--run-number "$RUN_NUMBER"
)
tag="nightly-${date_id}-${RUN_NUMBER}"
artifact="echoion-${version}-linux-x86_64.tar.zst"
url="${SERVER_URL}/${REPOSITORY}/releases/download/${tag}/${artifact}"
feed_url="${SERVER_URL}/${REPOSITORY}/raw/branch/release-feed/feeds/echoion-runtime.json"
python3 scripts/validate-semver.py "$version"
{
printf 'RELEASE_TAG=%s\n' "$tag"
printf 'RELEASE_VERSION=%s\n' "$version"
printf 'RELEASE_CHANNEL=nightly\n'
printf 'RELEASE_PRERELEASE=true\n'
printf 'RELEASE_ARTIFACT_URL=%s\n' "$url"
printf 'RELEASE_FEED_URL=%s\n' "$feed_url"
printf 'RELEASE_SEQUENCE=%s\n' "$RUN_NUMBER"
printf 'RELEASE_ARTIFACT_BASE_URL=%s\n' \
"${SERVER_URL}/${REPOSITORY}/releases/download/${tag}"
printf 'RELEASE_FEED_URL=%s\n' \
"${SERVER_URL}/${REPOSITORY}/raw/branch/release-feed/feeds/nightly/catalog.json"
printf 'RELEASE_TARGET=%s\n' "$(git rev-parse HEAD)"
} >>"$GITHUB_ENV"
- name: Build and test the dynamic nightly in Docker
- name: Build and test all locked repositories in Docker
shell: bash
run: |
set -euo pipefail
scripts/release.sh \
--version "$RELEASE_VERSION" \
--update-url "$RELEASE_ARTIFACT_URL" \
--component-workspace "$PWD/components" \
--void-source "$PWD/dependencies/VoidLibrary" \
--void-teamspeak-source "$PWD/dependencies/VoidTeamspeak" \
--official-update-feed-url "$RELEASE_FEED_URL" \
--update-channel nightly \
--update-valid-days 45
--update-sequence "$RELEASE_SEQUENCE"
{
printf 'Automated nightly from %s.\n\n' "$RELEASE_TARGET"
printf 'This prerelease is retained for fourteen nightly runs.\n'
} >"$RUNNER_TEMP/release-notes.md"
- name: Create draft, upload, download-verify, and publish
- name: Upload, download-verify, publish, and retain fourteen nightlies
shell: bash
env:
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }}
@@ -159,17 +131,6 @@ jobs:
--artifacts dist \
--allow-missing-draft-tag \
--prerelease
- name: Retain fourteen Gitea nightly releases
shell: bash
env:
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }}
API_URL: ${{ gitea.api_url }}
REPOSITORY: ${{ gitea.repository }}
run: |
set -euo pipefail
owner=${REPOSITORY%%/*}
repo=${REPOSITORY#*/}
python3 scripts/gitea_release.py \
--api-url "$API_URL" \
prune-nightlies \
@@ -179,63 +140,55 @@ jobs:
--keep 14 \
--protect-tag "$RELEASE_TAG"
- name: Check out the aggregate feed branch
- name: Check out release-feed over SSH
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
ref: release-feed
path: feed-state
token: ${{ secrets.RELEASE_BOT_TOKEN }}
fetch-depth: 1
fetch-depth: 0
ssh-key: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }}
ssh-user: gitea
ssh-known-hosts: >-
git.faumaray.ru ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw==
- name: Sign and push the aggregate feed last
- name: Sign and push the nightly feed transaction
shell: bash
env:
FEED_PRIVATE_KEY: ${{ secrets.RELEASE_FEED_ED25519_PRIVATE_KEY }}
FEED_COMMIT_SIGNING_KEY: ${{ secrets.RELEASE_FEED_GIT_SIGNING_KEY }}
run: |
set -euo pipefail
key="$RUNNER_TEMP/echoion-release-2026-07.pem"
payload="$RUNNER_TEMP/echoion-runtime.payload.json"
envelope="$RUNNER_TEMP/echoion-runtime.json"
trap 'rm -f -- "$key" "$payload" "$envelope"' EXIT
feed_key="$RUNNER_TEMP/echoion-feed-ed25519.pem"
commit_key="$RUNNER_TEMP/echoion-feed-commit-key"
trap 'rm -f -- "$feed_key" "$commit_key"' EXIT
umask 077
printf '%s\n' "$FEED_PRIVATE_KEY" >"$key"
chmod 0600 "$key"
openssl pkey -in "$key" -noout
mkdir -p feed-state/feeds
existing=()
if [[ -s feed-state/feeds/echoion-runtime.json ]]; then
existing+=(
--existing-envelope feed-state/feeds/echoion-runtime.json
)
fi
python3 scripts/aggregate_update_feed.py \
--new-payload \
"dist/echoion-${RELEASE_VERSION}-linux-x86_64.update-payload.json" \
--new-payload \
"dist/echoion-core-${RELEASE_VERSION}-linux-x86_64.update-payload.json" \
--new-payload \
"dist/url-shortener-internal-${RELEASE_VERSION}-linux-x86_64.update-payload.json" \
--new-payload \
"dist/url-shortener-external-${RELEASE_VERSION}-linux-x86_64.update-payload.json" \
"${existing[@]}" \
--public-key \
.gitea/release-keys/echoion-release-2026-07.pub.pem \
--private-key "$key" \
--key-id echoion-release-2026-07 \
printf '%s\n' "$FEED_PRIVATE_KEY" >"$feed_key"
printf '%s\n' "$FEED_COMMIT_SIGNING_KEY" >"$commit_key"
chmod 0600 "$feed_key" "$commit_key"
python3 scripts/publish-component-feeds.py \
--registry components.json \
--lock components.lock.json \
--artifacts dist/components \
--feed-root feed-state \
--base-url \
"${{ gitea.server_url }}/${{ gitea.repository }}/raw/branch/release-feed" \
--artifact-base-url "$RELEASE_ARTIFACT_BASE_URL" \
--channel nightly \
--sequence "$RELEASE_SEQUENCE" \
--valid-days 45 \
--nightly-retention 14 \
--output-payload "$payload" \
--output-envelope "$envelope"
install -m 0644 "$payload" \
feed-state/feeds/echoion-runtime.payload.json
install -m 0644 "$envelope" feed-state/feeds/echoion-runtime.json
--key-id echoion-release-2026-07 \
--private-key "$feed_key"
git -C feed-state config user.name 'Echoion Release Bot'
git -C feed-state config user.email 'release-bot@echoion.invalid'
git -C feed-state add \
feeds/echoion-runtime.json feeds/echoion-runtime.payload.json
git -C feed-state config gpg.format ssh
git -C feed-state config user.signingkey "$commit_key"
git -C feed-state config commit.gpgsign true
git -C feed-state add feeds/nightly state
if git -C feed-state diff --cached --quiet; then
exit 0
fi
git -C feed-state commit -m \
git -C feed-state commit -S -m \
"Feed: nightly ${RELEASE_VERSION}"
git -C feed-state cat-file commit HEAD |
grep -q '^gpgsig '
git -C feed-state push origin HEAD:release-feed
+79 -101
View File
@@ -1,4 +1,4 @@
name: Signed release
name: Signed modular release
on:
push:
@@ -8,6 +8,10 @@ on:
permissions:
contents: read
concurrency:
group: echoion-release-feed
cancel-in-progress: false
jobs:
publish:
runs-on: ubuntu-24.04
@@ -21,7 +25,7 @@ jobs:
docker version
docker info
- name: Check out the signed tag
- name: Check out the signed root tag over SSH
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
ref: ${{ gitea.ref }}
@@ -32,59 +36,38 @@ jobs:
git.faumaray.ru ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw==
persist-credentials: false
- name: Read locked component repositories
id: components
- name: Reject embedded component sources and gitlinks
shell: bash
run: |
set -euo pipefail
python3 - "$GITHUB_OUTPUT" <<'PY'
test ! -e .gitmodules
if git ls-files -s | awk '$1 == "160000" { found=1 } END { exit !found }'
then
echo "root release contains a gitlink" >&2
exit 1
fi
python3 - <<'PY'
import json
import pathlib
import sys
lock = json.loads(pathlib.Path("components.lock.json").read_text())
with pathlib.Path(sys.argv[1]).open("a") as output:
for component, key in (
("EchoionApi", "api"),
("EchoionCore", "core"),
("EchoionDesktop", "desktop"),
):
entry = lock["components"][component]
print(f"{key}_repository={entry['repository']}", file=output)
print(f"{key}_revision={entry['revision']}", file=output)
components = json.loads(pathlib.Path("components.json").read_text())
embedded = [
name for name in components["components"]
if pathlib.Path(name).exists()
]
if embedded:
raise SystemExit(f"embedded component sources: {embedded}")
PY
- name: Check out EchoionApi
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
repository: ${{ steps.components.outputs.api_repository }}
ref: ${{ steps.components.outputs.api_revision }}
path: EchoionApi
fetch-depth: 1
token: ${{ secrets.RELEASE_BOT_TOKEN }}
persist-credentials: false
- name: Check out every locked component and dependency over SSH
shell: bash
env:
ECHOION_COMPONENT_SSH_KEY: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }}
run: >-
scripts/ci-checkout-components.sh
"$PWD/components"
"$PWD/dependencies"
- name: Check out EchoionCore
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
repository: ${{ steps.components.outputs.core_repository }}
ref: ${{ steps.components.outputs.core_revision }}
path: EchoionCore
fetch-depth: 1
token: ${{ secrets.RELEASE_BOT_TOKEN }}
persist-credentials: false
- name: Check out EchoionDesktop
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
repository: ${{ steps.components.outputs.desktop_repository }}
ref: ${{ steps.components.outputs.desktop_revision }}
path: EchoionDesktop
fetch-depth: 1
token: ${{ secrets.RELEASE_BOT_TOKEN }}
persist-credentials: false
- name: Verify protected annotated SSH tag
- name: Verify protected annotated SSH tag and release lock
shell: bash
env:
TAG: ${{ gitea.ref_name }}
@@ -112,6 +95,9 @@ jobs:
--notes-output "$RUNNER_TEMP/release-notes.md"
)
printf 'RELEASE_TARGET=%s\n' "$target_commit" >>"$GITHUB_ENV"
scripts/prepare-release.sh \
--workspace "$PWD/components" \
--check
owner=${REPOSITORY%%/*}
repo=${REPOSITORY#*/}
python3 scripts/gitea_release.py \
@@ -121,13 +107,14 @@ jobs:
--repo "$repo" \
--required-pattern 'v*'
- name: Derive the stable or beta release
- name: Derive release channel and URLs
shell: bash
env:
TAG: ${{ gitea.ref_name }}
API_URL: ${{ gitea.api_url }}
SERVER_URL: ${{ gitea.server_url }}
REPOSITORY: ${{ gitea.repository }}
RUN_NUMBER: ${{ gitea.run_number }}
run: |
set -euo pipefail
version=${TAG#v}
@@ -140,39 +127,37 @@ jobs:
--cmake-file CMakeLists.txt
)
tag_base=${version%%[-+]*}
if [[ "$tag_base" != "$project_version" ]]; then
printf 'release tag %s does not match root CMake project version %s\n' \
"$TAG" "$project_version" >&2
exit 1
fi
test "$tag_base" = "$project_version"
channel=stable
prerelease=false
if [[ "$version" == *-* ]]; then
channel=beta
prerelease=true
fi
artifact="echoion-${version}-linux-x86_64.tar.zst"
url="${SERVER_URL}/${REPOSITORY}/releases/download/${TAG}/${artifact}"
feed_url="${SERVER_URL}/${REPOSITORY}/raw/branch/release-feed/feeds/echoion-runtime.json"
feed_url="${SERVER_URL}/${REPOSITORY}/raw/branch/release-feed/feeds/${channel}/catalog.json"
artifact_url="${SERVER_URL}/${REPOSITORY}/releases/download/${TAG}"
{
printf 'RELEASE_TAG=%s\n' "$TAG"
printf 'RELEASE_VERSION=%s\n' "$version"
printf 'RELEASE_CHANNEL=%s\n' "$channel"
printf 'RELEASE_PRERELEASE=%s\n' "$prerelease"
printf 'RELEASE_ARTIFACT_URL=%s\n' "$url"
printf 'RELEASE_SEQUENCE=%s\n' "$RUN_NUMBER"
printf 'RELEASE_ARTIFACT_BASE_URL=%s\n' "$artifact_url"
printf 'RELEASE_FEED_URL=%s\n' "$feed_url"
} >>"$GITHUB_ENV"
- name: Build and test the dynamic release in Docker
- name: Build, test, and package all locked repositories in Docker
shell: bash
run: |
set -euo pipefail
scripts/release.sh \
--version "$RELEASE_VERSION" \
--update-url "$RELEASE_ARTIFACT_URL" \
--component-workspace "$PWD/components" \
--void-source "$PWD/dependencies/VoidLibrary" \
--void-teamspeak-source "$PWD/dependencies/VoidTeamspeak" \
--official-update-feed-url "$RELEASE_FEED_URL" \
--update-channel "$RELEASE_CHANNEL" \
--update-valid-days 45
--update-sequence "$RELEASE_SEQUENCE"
- name: Create draft, upload, download-verify, and publish
shell: bash
@@ -200,63 +185,56 @@ jobs:
--artifacts dist \
"${prerelease[@]}"
- name: Check out the aggregate feed branch
- name: Check out the protected release-feed branch over SSH
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
ref: release-feed
path: feed-state
token: ${{ secrets.RELEASE_BOT_TOKEN }}
fetch-depth: 1
fetch-depth: 0
ssh-key: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }}
ssh-user: gitea
ssh-known-hosts: >-
git.faumaray.ru ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw==
- name: Sign and push the aggregate feed last
- name: Sign and push the complete channel feed transaction
shell: bash
env:
FEED_PRIVATE_KEY: ${{ secrets.RELEASE_FEED_ED25519_PRIVATE_KEY }}
FEED_COMMIT_SIGNING_KEY: ${{ secrets.RELEASE_FEED_GIT_SIGNING_KEY }}
run: |
set -euo pipefail
key="$RUNNER_TEMP/echoion-release-2026-07.pem"
payload="$RUNNER_TEMP/echoion-runtime.payload.json"
envelope="$RUNNER_TEMP/echoion-runtime.json"
trap 'rm -f -- "$key" "$payload" "$envelope"' EXIT
feed_key="$RUNNER_TEMP/echoion-feed-ed25519.pem"
commit_key="$RUNNER_TEMP/echoion-feed-commit-key"
trap 'rm -f -- "$feed_key" "$commit_key"' EXIT
umask 077
printf '%s\n' "$FEED_PRIVATE_KEY" >"$key"
chmod 0600 "$key"
openssl pkey -in "$key" -noout
mkdir -p feed-state/feeds
existing=()
if [[ -s feed-state/feeds/echoion-runtime.json ]]; then
existing+=(
--existing-envelope feed-state/feeds/echoion-runtime.json
)
fi
python3 scripts/aggregate_update_feed.py \
--new-payload \
"dist/echoion-${RELEASE_VERSION}-linux-x86_64.update-payload.json" \
--new-payload \
"dist/echoion-core-${RELEASE_VERSION}-linux-x86_64.update-payload.json" \
--new-payload \
"dist/url-shortener-internal-${RELEASE_VERSION}-linux-x86_64.update-payload.json" \
--new-payload \
"dist/url-shortener-external-${RELEASE_VERSION}-linux-x86_64.update-payload.json" \
"${existing[@]}" \
--public-key \
.gitea/release-keys/echoion-release-2026-07.pub.pem \
--private-key "$key" \
--key-id echoion-release-2026-07 \
printf '%s\n' "$FEED_PRIVATE_KEY" >"$feed_key"
printf '%s\n' "$FEED_COMMIT_SIGNING_KEY" >"$commit_key"
chmod 0600 "$feed_key" "$commit_key"
openssl pkey -in "$feed_key" -noout
python3 scripts/publish-component-feeds.py \
--registry components.json \
--lock components.lock.json \
--artifacts dist/components \
--feed-root feed-state \
--base-url \
"${{ gitea.server_url }}/${{ gitea.repository }}/raw/branch/release-feed" \
--artifact-base-url "$RELEASE_ARTIFACT_BASE_URL" \
--channel "$RELEASE_CHANNEL" \
--sequence "$RELEASE_SEQUENCE" \
--valid-days 45 \
--nightly-retention 14 \
--output-payload "$payload" \
--output-envelope "$envelope"
install -m 0644 "$payload" \
feed-state/feeds/echoion-runtime.payload.json
install -m 0644 "$envelope" feed-state/feeds/echoion-runtime.json
--key-id echoion-release-2026-07 \
--private-key "$feed_key"
git -C feed-state config user.name 'Echoion Release Bot'
git -C feed-state config user.email 'release-bot@echoion.invalid'
git -C feed-state add \
feeds/echoion-runtime.json feeds/echoion-runtime.payload.json
git -C feed-state config gpg.format ssh
git -C feed-state config user.signingkey "$commit_key"
git -C feed-state config commit.gpgsign true
git -C feed-state add feeds state
if git -C feed-state diff --cached --quiet; then
exit 0
fi
git -C feed-state commit -m \
git -C feed-state commit -S -m \
"Feed: ${RELEASE_CHANNEL} ${RELEASE_VERSION}"
git -C feed-state cat-file commit HEAD |
grep -q '^gpgsig '
git -C feed-state push origin HEAD:release-feed
+7
View File
@@ -16,3 +16,10 @@ AGENTS.md
/EchoionApi/
/EchoionCore/
/EchoionDesktop/
/EchoionHost/
/EchoionStandalone/
/EchoionUpdater/
/EchoionWeb/
/EchoionPluginUrlShortenerInternal/
/EchoionPluginUrlShortenerExternal/
/components/
+174 -22
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 4.0.0)
project(Echoion VERSION 1.0.7 LANGUAGES CXX)
project(Echoion VERSION 2.0.0 LANGUAGES CXX)
include(GNUInstallDirs)
include(cmake/DependencyLock.cmake)
@@ -8,15 +8,8 @@ include(cmake/DependencyLock.cmake)
# component project consumes this value when orchestrated by Echoion; their
# standalone fallback is intentionally 0.0.0 and is never used for a product
# release.
if(DEFINED ECHOION_RELEASE_VERSION AND
NOT ECHOION_RELEASE_VERSION STREQUAL "")
set(ECHOION_COMPONENT_VERSION "${ECHOION_RELEASE_VERSION}")
string(REGEX REPLACE "[-+].*$" ""
ECHOION_PRODUCT_VERSION "${ECHOION_RELEASE_VERSION}")
else()
set(ECHOION_PRODUCT_VERSION "${PROJECT_VERSION}")
set(ECHOION_COMPONENT_VERSION "${PROJECT_VERSION}")
endif()
set(ECHOION_PRODUCT_VERSION "${PROJECT_VERSION}")
set(ECHOION_COMPONENT_VERSION "${PROJECT_VERSION}")
# Default to a Release build when the developer/CI did not pick a config.
# Without this, single-config generators leave CMAKE_BUILD_TYPE empty and GCC
@@ -113,7 +106,7 @@ CPMAddPackage(
# which CPM honours over the git checkout below.
CPMAddPackage(
NAME Void
GIT_REPOSITORY https://git.faumaray.ru/void/voidlibrary.git
GIT_REPOSITORY ssh://gitea@git.faumaray.ru/void/voidlibrary.git
# Keep clean/container releases reproducible. CPM_Void_SOURCE still
# overrides this revision for local dependency development.
GIT_TAG ${ECHOION_VOID_REVISION}
@@ -126,7 +119,7 @@ CPMAddPackage(
# -DCPM_VoidTeamspeak_SOURCE=$HOME/Project/Personal/VoidTeamspeak
CPMAddPackage(
NAME VoidTeamspeak
GIT_REPOSITORY https://git.faumaray.ru/void/voidteamspeak.git
GIT_REPOSITORY ssh://gitea@git.faumaray.ru/void/voidteamspeak.git
# This revision supplies the typed administration API used by Standalone.
GIT_TAG ${ECHOION_VOID_TEAMSPEAK_REVISION}
OPTIONS
@@ -182,12 +175,17 @@ set_property(GLOBAL PROPERTY USE_FOLDERS ON)
# Options
option(BUILD_API "Build EchoionApi" ON)
option(BUILD_HOST "Build EchoionHost module loader" ON)
option(BUILD_CORE "Build EchoionCore" ON)
option(BUILD_DESKTOP "Build EchoionDesktop" ON)
option(BUILD_WEB "Build EchoionWeb browser dashboard" ON)
option(BUILD_STANDALONE "Build EchoionStandalone daemon with native TeamSpeak client" ON)
option(BUILD_UPDATER "Build EchoionUpdater lifecycle helper" ON)
option(BUILD_FIRST_PARTY_PLUGINS "Build bundled Echoion extension plugins" ON)
option(BUILD_TESTS "Build tests" OFF)
set(ECHOION_COMPONENT_WORKSPACE
"${CMAKE_CURRENT_SOURCE_DIR}/.."
CACHE PATH "Directory containing permanent Echoion component repositories")
if(BUILD_TESTS)
enable_testing()
@@ -196,17 +194,22 @@ endif()
# Find packages
find_package(Threads REQUIRED)
# Add subdirectories
# All component source directories come from CPM. Local development can set
# CPM_<Component>_SOURCE; normal development follows main; release builds use
# exact components.lock.json revisions.
set(ECHOION_ORCHESTRATOR_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
if(BUILD_API)
echoion_add_component(EchoionApi)
endif()
if(BUILD_FIRST_PARTY_PLUGINS)
add_subdirectory(plugins)
echoion_add_component(EchoionPluginUrlShortenerInternal)
echoion_add_component(EchoionPluginUrlShortenerExternal)
endif()
if(BUILD_STANDALONE)
add_subdirectory(EchoionHost)
if(BUILD_HOST OR BUILD_STANDALONE)
echoion_add_component(EchoionHost)
endif()
if(BUILD_CORE)
@@ -217,7 +220,7 @@ endif()
# targets Core discovers. Core owns and starts the web server, so link them
# here (both targets now exist) and flag Core so the wiring compiles in.
if(BUILD_WEB AND BUILD_CORE)
add_subdirectory(EchoionWeb)
echoion_add_component(EchoionWeb)
if(TARGET EchoionCore AND TARGET EchoionWeb)
target_link_libraries(EchoionCore PRIVATE EchoionWeb)
target_compile_definitions(EchoionCore PRIVATE ECHOION_WITH_WEB)
@@ -231,13 +234,13 @@ endif()
# It validates and journals local operations but leaves network/feed work to
# the daemon through typed request files. Define it before Standalone so the
# Linux release-staging test can use the real helper binary.
if(UNIX AND NOT APPLE)
add_subdirectory(packaging/updater)
if(BUILD_UPDATER AND UNIX AND NOT APPLE)
echoion_add_component(EchoionUpdater)
endif()
# EchoionStandalone links the host-common loader and native protocol client.
if(BUILD_STANDALONE)
add_subdirectory(EchoionStandalone)
echoion_add_component(EchoionStandalone)
endif()
if(BUILD_DESKTOP)
@@ -274,7 +277,7 @@ if(ECHOION_INSTALL_RUNTIME_BUNDLE)
endif()
if(TARGET EchoionWeb)
install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/EchoionWeb/frontend/web-dist/"
install(DIRECTORY "${EchoionWeb_SOURCE_DIR}/frontend/web-dist/"
DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/web"
COMPONENT Runtime)
endif()
@@ -282,6 +285,11 @@ if(ECHOION_INSTALL_RUNTIME_BUNDLE)
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/config.example.json"
DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion"
COMPONENT Runtime)
install(FILES
"${CMAKE_CURRENT_SOURCE_DIR}/components.json"
"${CMAKE_CURRENT_SOURCE_DIR}/components.lock.json"
DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion"
COMPONENT Runtime)
install(FILES
"${CMAKE_CURRENT_SOURCE_DIR}/packaging/service/echoion.service.in"
"${CMAKE_CURRENT_SOURCE_DIR}/packaging/service/echoion-updater.service.in"
@@ -301,6 +309,112 @@ if(ECHOION_INSTALL_RUNTIME_BUNDLE)
endif()
endif()
# Independent component package staging. Each named install component contains
# only that component's first-party payload; release tooling adds its private
# runtime dependency closure and a signed-feed manifest afterwards.
option(ECHOION_INSTALL_COMPONENT_PACKAGES
"Provide one install component for every independently released component"
ON)
if(ECHOION_INSTALL_COMPONENT_PACKAGES)
if(TARGET EchoionApiPluginSdk)
install(TARGETS EchoionApiPluginSdk
ARCHIVE DESTINATION lib
COMPONENT PackageEchoionApi)
install(DIRECTORY "${EchoionApi_SOURCE_DIR}/include/"
DESTINATION include
COMPONENT PackageEchoionApi)
install(FILES
"${EchoionApi_SOURCE_DIR}/abi/echoion-module-v1.json"
DESTINATION abi
COMPONENT PackageEchoionApi)
endif()
if(TARGET EchoionHost)
install(TARGETS EchoionHost
LIBRARY DESTINATION lib
COMPONENT PackageEchoionHost
RUNTIME DESTINATION bin
COMPONENT PackageEchoionHost)
install(FILES "${EchoionHost_SOURCE_DIR}/abi/module.json"
DESTINATION abi
COMPONENT PackageEchoionHost)
endif()
if(TARGET EchoionCore)
install(TARGETS EchoionCore
LIBRARY DESTINATION lib
COMPONENT PackageEchoionCore
RUNTIME DESTINATION bin
COMPONENT PackageEchoionCore)
install(FILES "${EchoionCore_SOURCE_DIR}/abi/module.json"
DESTINATION abi
COMPONENT PackageEchoionCore)
endif()
if(TARGET EchoionWeb)
install(TARGETS EchoionWeb
LIBRARY DESTINATION lib
COMPONENT PackageEchoionWeb
RUNTIME DESTINATION bin
COMPONENT PackageEchoionWeb)
install(FILES "${EchoionWeb_SOURCE_DIR}/abi/module.json"
DESTINATION abi
COMPONENT PackageEchoionWeb)
install(DIRECTORY "${EchoionWeb_SOURCE_DIR}/frontend/web-dist/"
DESTINATION share/echoion/web
COMPONENT PackageEchoionWeb)
endif()
if(TARGET EchoionStandalone)
install(TARGETS EchoionStandalone
RUNTIME DESTINATION bin
COMPONENT PackageEchoionStandalone)
endif()
if(TARGET EchoionUpdater)
install(TARGETS EchoionUpdater
RUNTIME DESTINATION bin
COMPONENT PackageEchoionUpdater)
endif()
if(TARGET EchoionDesktop)
install(TARGETS EchoionDesktop
RUNTIME DESTINATION bin
COMPONENT PackageEchoionDesktop
BUNDLE DESTINATION bin
COMPONENT PackageEchoionDesktop)
if(TARGET Qt6::QXcbIntegrationPlugin)
install(IMPORTED_RUNTIME_ARTIFACTS Qt6::QXcbIntegrationPlugin
LIBRARY DESTINATION plugins/platforms
COMPONENT PackageEchoionDesktop)
endif()
endif()
if(TARGET EchoionUrlShortenerInternalPlugin)
install(TARGETS EchoionUrlShortenerInternalPlugin
LIBRARY DESTINATION lib
COMPONENT PackageEchoionPluginUrlShortenerInternal
RUNTIME DESTINATION lib
COMPONENT PackageEchoionPluginUrlShortenerInternal)
install(FILES
"${EchoionPluginUrlShortenerInternal_SOURCE_DIR}/abi/module.json"
DESTINATION abi
COMPONENT PackageEchoionPluginUrlShortenerInternal)
endif()
if(TARGET EchoionUrlShortenerExternalPlugin)
install(TARGETS EchoionUrlShortenerExternalPlugin
LIBRARY DESTINATION lib
COMPONENT PackageEchoionPluginUrlShortenerExternal
RUNTIME DESTINATION lib
COMPONENT PackageEchoionPluginUrlShortenerExternal)
install(FILES
"${EchoionPluginUrlShortenerExternal_SOURCE_DIR}/abi/module.json"
DESTINATION abi
COMPONENT PackageEchoionPluginUrlShortenerExternal)
endif()
endif()
# Bundling and deployment helpers
# Function to bundle Qt dependencies
function(bundle_qt_dependencies target)
@@ -376,10 +490,46 @@ if(BUILD_CORE AND TARGET EchoionCore)
endif()
if(BUILD_TESTS AND UNIX)
find_package(Python3 REQUIRED COMPONENTS Interpreter)
add_test(NAME echoion_prepare_release_tests
COMMAND "${Python3_EXECUTABLE}"
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test_prepare_release.py")
add_test(NAME echoion_component_package_tests
COMMAND "${Python3_EXECUTABLE}"
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test_package_components.py")
add_test(NAME echoion_component_feed_tests
COMMAND "${Python3_EXECUTABLE}"
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test_publish_component_feeds.py")
if(NOT COMMAND void_add_tests AND DEFINED Void_SOURCE_DIR)
include("${Void_SOURCE_DIR}/cmake/VoidTesting.cmake")
endif()
if(COMMAND void_add_tests AND
TARGET EchoionHost AND TARGET EchoionCore AND TARGET EchoionWeb AND
TARGET EchoionUrlShortenerInternalPlugin AND
TARGET EchoionUrlShortenerExternalPlugin)
add_executable(EchoionModuleTests tests/ModuleDescriptors.cpp)
target_compile_features(EchoionModuleTests PRIVATE cxx_std_26)
target_link_libraries(EchoionModuleTests PRIVATE
Echoion::ApiModuleAbi
Void::Testing
${CMAKE_DL_LIBS})
target_compile_definitions(EchoionModuleTests PRIVATE
"ECHOION_TEST_HOST=\"$<TARGET_FILE:EchoionHost>\""
"ECHOION_TEST_CORE=\"$<TARGET_FILE:EchoionCore>\""
"ECHOION_TEST_WEB=\"$<TARGET_FILE:EchoionWeb>\""
"ECHOION_TEST_PLUGIN_INTERNAL=\"$<TARGET_FILE:EchoionUrlShortenerInternalPlugin>\""
"ECHOION_TEST_PLUGIN_EXTERNAL=\"$<TARGET_FILE:EchoionUrlShortenerExternalPlugin>\"")
void_add_tests(EchoionModuleTests)
add_test(NAME echoion_module_descriptor_tests
COMMAND EchoionModuleTests)
endif()
add_test(NAME echoion_release_manifest_packaging_tests
COMMAND bash
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-release-packaging.sh"
"${CMAKE_CURRENT_SOURCE_DIR}")
"${CMAKE_CURRENT_SOURCE_DIR}"
"${ECHOION_COMPONENT_WORKSPACE}")
add_test(NAME echoion_runtime_dependency_packaging_tests
COMMAND bash
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-runtime-dependencies.sh"
@@ -428,11 +578,13 @@ if(DEFINED ECHOION_RUNTIME_VERSION)
endif()
message(STATUS " C++ Standard: ${CMAKE_CXX_STANDARD}")
message(STATUS " Build API: ${BUILD_API}")
message(STATUS " Build Host: ${BUILD_HOST}")
message(STATUS " Build first-party plugins: ${BUILD_FIRST_PARTY_PLUGINS}")
message(STATUS " Build Core: ${BUILD_CORE}")
message(STATUS " Build Desktop: ${BUILD_DESKTOP}")
message(STATUS " Build Web: ${BUILD_WEB}")
message(STATUS " Build Standalone: ${BUILD_STANDALONE}")
message(STATUS " Build Updater: ${BUILD_UPDATER}")
message(STATUS " Build Tests: ${BUILD_TESTS}")
message(STATUS " Static Link: ${ECHOION_STATIC_LINK}")
message(STATUS " Runtime install component: ${ECHOION_INSTALL_RUNTIME_BUNDLE}")
+1 -1
View File
@@ -26,7 +26,7 @@
"ECHOION_BUILD_WEB": "ON",
"BUILD_STANDALONE": "ON",
"BUILD_FIRST_PARTY_PLUGINS": "ON",
"BUILD_DESKTOP": "OFF",
"BUILD_DESKTOP": "ON",
"BUILD_TESTS": "ON"
}
}
-38
View File
@@ -1,38 +0,0 @@
cmake_minimum_required(VERSION 4.0.0)
if(NOT DEFINED ECHOION_PRODUCT_VERSION)
set(ECHOION_PRODUCT_VERSION 0.0.0)
endif()
project(EchoionHost VERSION "${ECHOION_PRODUCT_VERSION}" LANGUAGES CXX)
add_library(EchoionHost STATIC
src/CoreLoader.cpp
)
add_library(Echoion::Host ALIAS EchoionHost)
target_compile_features(EchoionHost PUBLIC cxx_std_26)
set_target_properties(EchoionHost PROPERTIES POSITION_INDEPENDENT_CODE ON)
target_include_directories(EchoionHost PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
target_link_libraries(EchoionHost
PUBLIC
Echoion::ApiBase
Echoion::ApiConfig
Echoion::ApiPlugin
Echoion::ApiOpaque
Echoion::ApiCoreInterface
PRIVATE
Echoion::ApiLogger
Void::Data
Void::Log
Void::Plugin
Void::System
Void::Stacktrace
Threads::Threads
)
if(NOT MSVC)
target_compile_options(EchoionHost PRIVATE
-Wall -Wextra -Wpedantic -Wconversion -Wsign-conversion -Wshadow)
endif()
@@ -1,100 +0,0 @@
#pragma once
#include <Void/System/FileWatcher.hpp>
#include <Void/Plugin/Manager.hpp>
#include <CoreInterface.hpp>
#include <PluginTypes.hpp>
#include <Types.hpp>
#include <atomic>
#include <condition_variable>
#include <filesystem>
#include <functional>
#include <memory>
#include <mutex>
#include <queue>
#include <thread>
namespace Echoion::Host
{
class CoreLoader
{
public:
CoreLoader();
~CoreLoader();
Api::Result<void> load(const std::filesystem::path& libraryPath);
Api::Result<void> unload();
Api::Result<void>
hotReload(const std::filesystem::path& newLibraryPath);
[[nodiscard]] bool isLoaded() const noexcept;
[[nodiscard]] Api::CoreInterfacePtr getCore() const;
void setConfigPath(const std::filesystem::path& configPath);
[[nodiscard]] std::filesystem::path getConfigPath() const;
[[nodiscard]] bool isHotReloading() const noexcept;
Api::Result<void>
checkpoint(const std::filesystem::path& destination);
Api::Result<void>
restoreCheckpoint(const std::filesystem::path& source);
// Automatic hot reload
void enableAutoReload();
void disableAutoReload();
[[nodiscard]] bool isAutoReloadEnabled() const noexcept;
// Callback for hot reload completion (called after auto-reload
// finishes)
using HotReloadCallback = std::function<void()>;
using HotReloadPrepareCallback = std::function<void()>;
void setHotReloadPrepareCallback(HotReloadPrepareCallback callback)
{
hotReloadPrepareCallback_ = std::move(callback);
}
void setHotReloadCallback(HotReloadCallback callback)
{
hotReloadCallback_ = std::move(callback);
}
private:
Api::Result<void>
loadLibraryInternal(const std::filesystem::path& path);
Api::Result<void> unloadLibraryInternal();
[[nodiscard]] Api::Result<void> refreshCoreHandle();
Void::Plugin::PluginManager pluginManager_;
std::string pluginName_;
Api::CoreInterfacePtr core_;
std::filesystem::path currentLibraryPath_;
std::filesystem::path configPath_;
mutable std::mutex mutex_;
std::atomic<bool> loaded_{false};
std::atomic<bool> hotReloading_{false};
// Auto reload
Void::FileSystem::FileWatcher fileWatcher_;
std::atomic<bool> autoReloadEnabled_{false};
// Deferred reload - waits for current track to finish
std::thread deferredReloadThread_;
std::atomic<bool> hasPendingReload_{false};
std::atomic<bool> stopDeferredReload_{false};
std::condition_variable deferredReloadCv_;
std::filesystem::path pendingReloadPath_;
std::string pendingTrackId_; // Track ID that was playing when
// reload scheduled
mutable std::mutex pendingReloadMutex_;
// Hot reload completion callback
HotReloadPrepareCallback hotReloadPrepareCallback_;
HotReloadCallback hotReloadCallback_;
void onCoreFileChanged();
void waitForTrackAndReload(const std::filesystem::path& targetPath,
const std::string& trackId);
[[nodiscard]] bool isPlaybackActive() const;
[[nodiscard]] bool
isSameTrackPlaying(const std::string& trackId) const;
};
} // namespace Echoion::Host
-585
View File
@@ -1,585 +0,0 @@
#include "echoion/host/CoreLoader.hpp"
#include <Void/Log/Log.hpp>
#include <Void/Plugin/Loader.hpp>
#include <Void/System/Path.hpp>
#include <algorithm>
#include <chrono>
#include <format>
#include <fstream>
#include <iostream>
#include <thread>
#include <vector>
#ifndef _WIN32
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Echoion::Host
{
namespace
{
bool canCreateHotReloadCopy(const std::filesystem::path& libraryPath)
{
const auto directory = libraryPath.parent_path();
#ifdef _WIN32
std::error_code error;
const auto status = std::filesystem::status(directory, error);
if (error || !std::filesystem::is_directory(status)) {
return false;
}
constexpr auto writable = std::filesystem::perms::owner_write |
std::filesystem::perms::group_write |
std::filesystem::perms::others_write;
return (status.permissions() & writable) !=
std::filesystem::perms::none;
#else
struct stat metadata{};
if (::stat(directory.c_str(), &metadata) != 0 ||
!S_ISDIR(metadata.st_mode)) {
return false;
}
const auto effectiveUser = ::geteuid();
const auto effectiveGroup = ::getegid();
bool usesDirectoryGroup = effectiveGroup == metadata.st_gid;
if (!usesDirectoryGroup) {
const int count = ::getgroups(0, nullptr);
if (count > 0) {
std::vector<gid_t> groups(static_cast<std::size_t>(count));
if (::getgroups(count, groups.data()) == count) {
usesDirectoryGroup =
std::ranges::contains(groups, metadata.st_gid);
}
}
}
mode_t required{};
if (effectiveUser == metadata.st_uid) {
required = S_IWUSR | S_IXUSR;
} else if (usesDirectoryGroup) {
required = S_IWGRP | S_IXGRP;
} else {
required = S_IWOTH | S_IXOTH;
}
return (metadata.st_mode & required) == required &&
::access(directory.c_str(), W_OK | X_OK) == 0;
#endif
}
} // namespace
CoreLoader::CoreLoader()
: pluginManager_(Void::Plugin::PluginManager::Options{
.dlclose_on_swap = false,
// Packaged Core libraries live in an immutable, service-readable
// directory. Initial load must never create a hotswap sibling
// there.
.copy_on_load = false,
.config_provider =
[this](std::string_view) { return configPath_.string(); },
.instance_validator =
[](Void::Plugin::IPlugin& plugin,
const Void::Plugin::PluginInfo&) {
return dynamic_cast<Api::ICoreInterface*>(&plugin) !=
nullptr;
}})
{
}
void CoreLoader::enableAutoReload()
{
std::lock_guard<std::mutex> lock(mutex_);
if (autoReloadEnabled_.load()) {
return;
}
if (!currentLibraryPath_.empty() &&
std::filesystem::exists(currentLibraryPath_)) {
if (!canCreateHotReloadCopy(currentLibraryPath_)) {
Void::Log::info(
"CoreLoader", "{}",
std::format(
"Auto-reload disabled for read-only Core directory: {}",
currentLibraryPath_.parent_path().string()));
return;
}
autoReloadEnabled_ = true;
Void::Log::info("CoreLoader", "{}",
std::format("Enabling auto-reload for: {}",
currentLibraryPath_.string()));
fileWatcher_.watch(
currentLibraryPath_,
[this](const Void::FileSystem::FileWatcher::Event& event) {
if (event.exists) {
onCoreFileChanged();
}
});
}
}
void CoreLoader::disableAutoReload()
{
autoReloadEnabled_ = false;
if (!currentLibraryPath_.empty()) {
fileWatcher_.unwatch(currentLibraryPath_);
}
Void::Log::info("CoreLoader", "{}", "Auto-reload disabled");
}
bool CoreLoader::isAutoReloadEnabled() const noexcept
{
return autoReloadEnabled_.load();
}
void CoreLoader::onCoreFileChanged()
{
if (!autoReloadEnabled_.load() || hotReloading_.load()) {
return;
}
Void::Log::info(
"CoreLoader", "{}",
"Core file changed, scheduling hot reload after current track...");
// Small delay to ensure file write is complete
std::this_thread::sleep_for(std::chrono::milliseconds(500));
// Check if playback is active - if so, defer reload
if (isPlaybackActive()) {
std::string currentTrackId;
{
std::lock_guard<std::mutex> lock(pendingReloadMutex_);
hasPendingReload_ = true;
pendingReloadPath_ = currentLibraryPath_;
// Capture current track ID
auto state = core_->getPlaybackSummary();
if (state && state->currentTrack.has_value()) {
pendingTrackId_ = state->currentTrack->id;
currentTrackId = pendingTrackId_;
}
}
Void::Log::info(
"CoreLoader", "{}",
std::format("Playback active (track: {}), deferring reload "
"until track finishes",
currentTrackId));
// Start background thread to wait for track end
if (deferredReloadThread_.joinable()) {
deferredReloadThread_.join();
}
deferredReloadThread_ = std::thread([this, currentTrackId]() {
waitForTrackAndReload(pendingReloadPath_, currentTrackId);
});
} else {
// No playback, reload immediately
auto result = hotReload(currentLibraryPath_);
if (!result) {
Void::Log::error("CoreLoader", "{}",
std::format("Auto hot-reload failed: {}",
result.error().message));
} else {
Void::Log::info("CoreLoader", "{}",
"Auto hot-reload completed successfully");
}
}
}
bool CoreLoader::isPlaybackActive() const
{
if (!core_) {
return false;
}
auto state = core_->getPlaybackSummary();
if (!state) {
return false;
}
// Check if currently playing a track
return state->isPlaying && state->currentTrack.has_value();
}
bool CoreLoader::isSameTrackPlaying(const std::string& trackId) const
{
if (!core_ || trackId.empty()) {
return false;
}
auto state = core_->getPlaybackSummary();
if (!state || !state->currentTrack.has_value()) {
return false;
}
return state->currentTrack->id == trackId;
}
void CoreLoader::waitForTrackAndReload(
const std::filesystem::path& targetPath, const std::string& trackId)
{
Void::Log::info(
"CoreLoader", "{}",
std::format("Waiting for track {} to finish before reload...",
trackId));
// Poll every 500ms to check if the specific track finished
// (playback may continue with next track, but we only care about THIS
// track). The wait is interruptible so the destructor can join this
// thread instead of detaching it (detaching risks use-after-free when
// the plugin unloads mid-wait).
while (isSameTrackPlaying(trackId)) {
std::unique_lock<std::mutex> lock(pendingReloadMutex_);
if (deferredReloadCv_.wait_for(
lock, std::chrono::milliseconds(500),
[this] { return stopDeferredReload_.load(); })) {
Void::Log::info(
"CoreLoader", "{}",
"Deferred hot-reload cancelled (loader shutting down)");
return;
}
}
if (stopDeferredReload_.load()) {
return;
}
Void::Log::info("CoreLoader", "{}",
"Track finished, starting hot reload");
// Clear pending flag
{
std::lock_guard<std::mutex> lock(pendingReloadMutex_);
hasPendingReload_ = false;
pendingTrackId_.clear();
}
// Now do the reload
auto result = hotReload(targetPath);
if (!result) {
Void::Log::error("CoreLoader", "{}",
std::format("Deferred hot-reload failed: {}",
result.error().message));
} else {
Void::Log::info("CoreLoader", "{}",
"Deferred hot-reload completed successfully");
}
}
CoreLoader::~CoreLoader()
{
if (autoReloadEnabled_.load()) {
disableAutoReload();
}
// Signal the deferred reload thread to stop and wait for it. It must
// never outlive this object: it dereferences core_ and this.
stopDeferredReload_ = true;
deferredReloadCv_.notify_all();
if (deferredReloadThread_.joinable()) {
deferredReloadThread_.join();
}
if (auto result = unload(); !result) {
Void::Log::warn("CoreLoader", "{}",
std::format("Unload from destructor failed: {}",
result.error().message));
}
}
Api::Result<void> CoreLoader::load(const std::filesystem::path& libraryPath)
{
std::unique_lock<std::mutex> lock(mutex_);
if (loaded_) {
return Api::fail(Api::ErrorCode::AlreadyExists,
"Core already loaded");
}
if (!std::filesystem::exists(libraryPath)) {
return Api::fail(
Api::ErrorCode::NotFound,
std::format("Library not found: {}", libraryPath.string()));
}
auto result = loadLibraryInternal(libraryPath);
if (result) {
currentLibraryPath_ = libraryPath;
}
return result;
}
Api::Result<void> CoreLoader::unload()
{
std::lock_guard<std::mutex> lock(mutex_);
return unloadLibraryInternal();
}
Api::Result<void>
CoreLoader::hotReload(const std::filesystem::path& newLibraryPath)
{
std::unique_lock<std::mutex> lock(mutex_);
if (!loaded_) {
return Api::fail(Api::ErrorCode::NotFound,
"No core loaded to reload");
}
auto targetPath =
newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath;
if (!std::filesystem::exists(targetPath)) {
return Api::fail(
Api::ErrorCode::NotFound,
std::format("New library not found: {}", targetPath.string()));
}
const bool replacingPath = targetPath != currentLibraryPath_;
if (!replacingPath && !canCreateHotReloadCopy(targetPath)) {
return Api::fail(
Api::ErrorCode::PermissionDenied,
"in-place Core reload requires a writable library directory; "
"use "
"an immutable versioned path for installed updates");
}
hotReloading_ = true;
Void::Log::info("CoreLoader", "{}",
"Starting transactional hot reload...");
// No callback may execute code from the old shared object after this
// barrier returns. State capture and dlclose are safe only after event
// producers have been drained.
if (hotReloadPrepareCallback_) {
hotReloadPrepareCallback_();
}
// Core owns exclusive process resources (HTTP/RPC listeners), so its
// two generations cannot both be initialized during an RCU swap.
// Capture state first, then stop the old services while its plugin
// instance remains pinned for rollback.
Api::StateBlob state;
if (core_) {
state = core_->saveState();
if (auto stopped = core_->shutdown(); !stopped) {
hotReloading_ = false;
lock.unlock();
if (hotReloadCallback_) {
hotReloadCallback_();
}
return stopped;
}
}
const auto reloadResult =
replacingPath ? pluginManager_.replace(pluginName_, targetPath)
: pluginManager_.reload(pluginName_);
if (!reloadResult) {
hotReloading_ = false;
auto message =
std::format("new Core rejected; running Core retained: {}",
Void::Plugin::to_string(reloadResult.error()));
if (core_) {
if (auto initialized = core_->initialize(configPath_);
!initialized) {
message +=
std::format("; retained Core reactivation failed: {}",
initialized.error().message);
} else if (!state.empty()) {
if (auto restored = core_->restoreState(state); !restored) {
message += std::format(
"; retained Core state restore failed: {}",
restored.error().message);
}
}
}
Void::Log::warn("CoreLoader", "{}", message);
lock.unlock();
// The prepare callback removed the event route. Restore it against
// the still-current Core even though no swap occurred.
if (hotReloadCallback_) {
hotReloadCallback_();
}
return Api::fail(Api::ErrorCode::PluginError, message);
}
if (auto refreshed = refreshCoreHandle(); !refreshed) {
hotReloading_ = false;
return refreshed;
}
currentLibraryPath_ = targetPath;
if (!state.empty()) {
if (auto restored = core_->restoreState(state); !restored) {
Void::Log::warn("CoreLoader",
"new Core state restore failed: {}",
restored.error().message);
}
}
hotReloading_ = false;
Void::Log::info("CoreLoader", "{}", "Hot reload complete");
lock.unlock();
if (hotReloadCallback_) {
hotReloadCallback_();
}
return {};
}
bool CoreLoader::isLoaded() const noexcept { return loaded_.load(); }
Api::CoreInterfacePtr CoreLoader::getCore() const
{
std::lock_guard<std::mutex> lock(mutex_);
return core_;
}
void CoreLoader::setConfigPath(const std::filesystem::path& configPath)
{
std::lock_guard<std::mutex> lock(mutex_);
configPath_ = configPath;
}
std::filesystem::path CoreLoader::getConfigPath() const
{
std::lock_guard<std::mutex> lock(mutex_);
return configPath_;
}
bool CoreLoader::isHotReloading() const noexcept
{
return hotReloading_.load();
}
Api::Result<void>
CoreLoader::checkpoint(const std::filesystem::path& destination)
{
std::lock_guard<std::mutex> lock(mutex_);
if (!core_) {
return Api::fail(Api::ErrorCode::NotInitialized,
"cannot checkpoint without a loaded Core");
}
const auto state = core_->saveState();
std::string bytes;
bytes.reserve(8 + state.timestamp.size() + state.data.size());
auto appendU32 = [&bytes](uint32_t value) {
for (int shift : {24, 16, 8, 0}) {
bytes.push_back(static_cast<char>((value >> shift) & 0xffU));
}
};
appendU32(state.version);
appendU32(static_cast<uint32_t>(state.timestamp.size()));
bytes.append(state.timestamp);
bytes.append(reinterpret_cast<const char*>(state.data.data()),
state.data.size());
if (auto result = Void::FileSystem::atomic_write(destination, bytes);
!result) {
return Api::fail(Api::ErrorCode::PluginError,
result.error().message());
}
return {};
}
Api::Result<void>
CoreLoader::restoreCheckpoint(const std::filesystem::path& source)
{
std::lock_guard<std::mutex> lock(mutex_);
if (!core_) {
return Api::fail(Api::ErrorCode::NotInitialized,
"cannot restore without a loaded Core");
}
auto contents = Void::FileSystem::read_file(source);
if (!contents) {
return Api::fail(Api::ErrorCode::NotFound,
contents.error().message());
}
if (contents->size() < 8) {
return Api::fail(Api::ErrorCode::ParseError,
"checkpoint header is truncated");
}
auto readU32 = [&contents](std::size_t offset) {
uint32_t value = 0;
for (std::size_t index = 0; index < 4; ++index) {
value = (value << 8U) |
static_cast<unsigned char>((*contents)[offset + index]);
}
return value;
};
Api::StateBlob state;
state.version = readU32(0);
const auto timestampSize = readU32(4);
if (timestampSize > contents->size() - 8) {
return Api::fail(Api::ErrorCode::ParseError,
"checkpoint timestamp is truncated");
}
state.timestamp = contents->substr(8, timestampSize);
const auto dataOffset = 8 + timestampSize;
state.data.assign(contents->begin() +
static_cast<std::ptrdiff_t>(dataOffset),
contents->end());
return core_->restoreState(state);
}
Api::Result<void>
CoreLoader::loadLibraryInternal(const std::filesystem::path& path)
{
auto result = pluginManager_.load(path);
if (!result) {
return Api::fail(
Api::ErrorCode::PluginError,
std::format("failed to load Core plugin: {}",
Void::Plugin::to_string(result.error())));
}
pluginName_ = std::move(*result);
if (auto refreshed = refreshCoreHandle(); !refreshed) {
std::ignore = pluginManager_.unload(pluginName_);
pluginName_.clear();
return refreshed;
}
loaded_ = true;
Void::Log::info("CoreLoader", "Core plugin '{}' loaded", pluginName_);
return {};
}
Api::Result<void> CoreLoader::refreshCoreHandle()
{
auto pin = std::make_shared<Void::Plugin::PluginHandle>(
pluginManager_.acquire(pluginName_));
if (!*pin) {
return Api::fail(Api::ErrorCode::PluginError,
"Core plugin disappeared from the registry");
}
auto* interface = dynamic_cast<Api::ICoreInterface*>(pin->get());
if (interface == nullptr) {
return Api::fail(
Api::ErrorCode::InvalidArgument,
"Void plugin does not implement Echoion Core interface");
}
core_ = Api::CoreInterfacePtr{std::move(pin), interface};
return {};
}
Api::Result<void> CoreLoader::unloadLibraryInternal()
{
if (!loaded_) {
return {};
}
Void::Log::info("CoreLoader", "{}", "Unloading core library...");
core_.reset();
if (!pluginName_.empty()) {
if (auto result = pluginManager_.unload(pluginName_); !result) {
return Api::fail(
Api::ErrorCode::PluginError,
std::format("failed to unload Core plugin: {}",
Void::Plugin::to_string(result.error())));
}
pluginName_.clear();
}
loaded_ = false;
std::cout << "[Echoion] Core library unloaded" << '\n';
return {};
}
} // namespace Echoion::Host
-207
View File
@@ -1,207 +0,0 @@
# EchoionStandalone — the daemon that runs Core without a TeamSpeak client.
#
# It uses the host-common CoreLoader/FileWatcher to load and hot-reload Core,
# and implements IPluginInterface with the reusable VoidTeamspeak client.
cmake_minimum_required(VERSION 4.0.0)
if(NOT DEFINED ECHOION_PRODUCT_VERSION)
set(ECHOION_PRODUCT_VERSION 0.0.0)
endif()
project(EchoionStandalone VERSION "${ECHOION_PRODUCT_VERSION}" LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
find_package(PkgConfig REQUIRED)
pkg_check_modules(SWRESAMPLE REQUIRED IMPORTED_TARGET
libswresample>=4
libavutil>=57
)
pkg_check_modules(OPUS REQUIRED IMPORTED_TARGET opus)
find_package(Threads REQUIRED)
find_package(OpenSSL REQUIRED)
set(ECHOION_UPDATE_FEED_URL "" CACHE STRING
"Build-time default URL for the official signed update feed")
set(ECHOION_UPDATE_PUBLIC_KEYS_JSON "[]" CACHE STRING
"Build-time Ed25519 trust anchors as [{\"id\":...,\"ed25519\":...}]")
set(ECHOION_RUNTIME_VERSION "${PROJECT_VERSION}" CACHE STRING
"Canonical SemVer reported when no installed release manifest is present")
string(LENGTH "${ECHOION_RUNTIME_VERSION}" _runtime_version_length)
if(_runtime_version_length GREATER 64 OR
NOT ECHOION_RUNTIME_VERSION MATCHES
"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?$")
message(FATAL_ERROR
"ECHOION_RUNTIME_VERSION must be canonical SemVer without build metadata")
endif()
if(ECHOION_RUNTIME_VERSION MATCHES "-([^+]+)$")
set(_runtime_prerelease "${CMAKE_MATCH_1}")
string(REPLACE "." ";" _runtime_prerelease_identifiers
"${_runtime_prerelease}")
foreach(_identifier IN LISTS _runtime_prerelease_identifiers)
if(_identifier MATCHES "^0[0-9]+$")
message(FATAL_ERROR
"ECHOION_RUNTIME_VERSION has a non-canonical numeric prerelease identifier")
endif()
endforeach()
endif()
foreach(_update_default IN ITEMS
ECHOION_UPDATE_FEED_URL ECHOION_UPDATE_PUBLIC_KEYS_JSON
ECHOION_RUNTIME_VERSION)
if("${${_update_default}}" MATCHES "\\)ECHOION_UPDATE\\\"")
message(FATAL_ERROR "${_update_default} contains the generated-header delimiter")
endif()
endforeach()
set(ECHOION_TOOLCHAIN_ABI
"${CMAKE_CXX_COMPILER_ID}-${CMAKE_CXX_COMPILER_VERSION}-${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR}")
configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/standalone/UpdateBuildDefaults.hpp.in"
"${CMAKE_CURRENT_BINARY_DIR}/generated/echoion/standalone/UpdateBuildDefaults.hpp"
@ONLY)
add_executable(EchoionStandalone
src/main.cpp
src/StandaloneClientInterface.cpp
src/AudioEncoder.cpp
src/MessageChunker.cpp
src/ReleaseManifest.cpp
src/RuntimePaths.cpp
src/EventCallbackGate.cpp
src/UpdateService.cpp
)
target_include_directories(EchoionStandalone PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/include"
"${CMAKE_CURRENT_BINARY_DIR}/generated"
)
target_link_libraries(EchoionStandalone PRIVATE
Void::TeamSpeak
Echoion::Host
Echoion::ApiBase
Echoion::ApiPlugin
Echoion::ApiOpaque
Echoion::ApiPluginInterface
Echoion::ApiCoreInterface
Echoion::ApiLogger
Void::Data
Void::Core
Void::Log
Void::System
Void::Stacktrace
Void::Archive
Void::Crypto
Void::Net
Void::Plugin
Void::Update
Threads::Threads
PkgConfig::SWRESAMPLE
PkgConfig::OPUS
OpenSSL::Crypto
)
set_target_properties(EchoionStandalone PROPERTIES
OUTPUT_NAME "echoiond"
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
)
install(TARGETS EchoionStandalone RUNTIME DESTINATION bin)
if(BUILD_TESTS AND TARGET EchoionCore)
add_executable(echoion_core_loader_reload_tests
tests/test_core_loader_reload.cpp)
target_link_libraries(echoion_core_loader_reload_tests PRIVATE
Echoion::Host Echoion::ApiCoreInterface)
target_compile_features(echoion_core_loader_reload_tests PRIVATE cxx_std_26)
target_compile_definitions(echoion_core_loader_reload_tests PRIVATE
"ECHOION_TEST_CORE_PATH=\"$<TARGET_FILE:EchoionCore>\"")
add_dependencies(echoion_core_loader_reload_tests EchoionCore)
add_test(NAME echoion_core_loader_reload_tests
COMMAND echoion_core_loader_reload_tests)
endif()
if(BUILD_TESTS)
add_executable(echoion_standalone_message_tests
tests/test_message_chunker.cpp
src/MessageChunker.cpp
)
target_include_directories(echoion_standalone_message_tests PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/include"
)
target_compile_features(echoion_standalone_message_tests PRIVATE cxx_std_20)
add_test(NAME echoion_standalone_message_tests
COMMAND echoion_standalone_message_tests)
add_executable(echoion_release_manifest_tests
tests/test_release_manifest.cpp
src/ReleaseManifest.cpp
)
target_include_directories(echoion_release_manifest_tests PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/include"
)
target_compile_features(echoion_release_manifest_tests PRIVATE cxx_std_26)
target_link_libraries(echoion_release_manifest_tests PRIVATE
Echoion::ApiBase Void::Data Void::System OpenSSL::Crypto)
add_test(NAME echoion_release_manifest_tests
COMMAND echoion_release_manifest_tests)
add_executable(echoion_runtime_paths_tests
tests/test_runtime_paths.cpp
src/RuntimePaths.cpp
)
target_include_directories(echoion_runtime_paths_tests PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/include"
)
target_compile_features(echoion_runtime_paths_tests PRIVATE cxx_std_26)
add_test(NAME echoion_runtime_paths_tests
COMMAND echoion_runtime_paths_tests)
add_executable(echoion_event_callback_gate_tests
tests/test_event_callback_gate.cpp
src/EventCallbackGate.cpp
)
target_include_directories(echoion_event_callback_gate_tests PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/include"
)
target_compile_features(echoion_event_callback_gate_tests PRIVATE cxx_std_26)
target_link_libraries(echoion_event_callback_gate_tests PRIVATE
Echoion::ApiBase Echoion::ApiConfig Echoion::ApiPlugin
Void::Core Threads::Threads)
add_test(NAME echoion_event_callback_gate_tests
COMMAND echoion_event_callback_gate_tests)
add_executable(echoion_update_service_tests
tests/test_update_service.cpp
src/UpdateService.cpp
)
target_include_directories(echoion_update_service_tests PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/include"
)
target_compile_features(echoion_update_service_tests PRIVATE cxx_std_26)
target_link_libraries(echoion_update_service_tests PRIVATE
Echoion::ApiBase Echoion::ApiConfig
Void::Archive Void::Crypto Void::Data Void::Log Void::Net Void::Plugin
Void::System Void::Update Threads::Threads)
add_test(NAME echoion_update_service_tests
COMMAND echoion_update_service_tests)
add_executable(echoion_update_build_defaults_tests
tests/test_update_build_defaults.cpp)
target_include_directories(echoion_update_build_defaults_tests PRIVATE
"${CMAKE_CURRENT_BINARY_DIR}/generated")
target_compile_features(echoion_update_build_defaults_tests PRIVATE
cxx_std_20)
target_compile_definitions(echoion_update_build_defaults_tests PRIVATE
"ECHOION_EXPECTED_RUNTIME_VERSION=\"${ECHOION_RUNTIME_VERSION}\"")
add_test(NAME echoion_update_build_defaults_tests
COMMAND echoion_update_build_defaults_tests)
if(TARGET EchoionUpdater)
add_test(NAME echoion_stage_release_tests
COMMAND bash "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_stage_release.sh"
"${CMAKE_SOURCE_DIR}/scripts/stage-release.sh"
$<TARGET_FILE:EchoionUpdater>
"${CMAKE_SOURCE_DIR}/packaging/service")
endif()
endif()
@@ -1,42 +0,0 @@
#pragma once
// Converts Echoion's internal PCM (192 kHz stereo S16, delivered in 20 ms
// chunks) into TeamSpeak-ready Opus frames: resample to 48 kHz stereo, then
// Opus-encode in exact 20 ms (960 samples/ch) frames. A small PCM ring absorbs
// the resampler's priming latency so every emitted frame is exactly 960/ch.
#include <cstdint>
#include <span>
#include <vector>
struct SwrContext;
struct OpusEncoder;
namespace Echoion::Standalone
{
class AudioEncoder
{
public:
// inRate defaults to Echoion's 192 kHz internal pipeline.
explicit AudioEncoder(int bitrate = 96000, int inRate = 192000);
~AudioEncoder();
AudioEncoder(const AudioEncoder&) = delete;
AudioEncoder& operator=(const AudioEncoder&) = delete;
// Feed one chunk of interleaved stereo S16 at inRate. Returns zero or
// more complete Opus frames (each a 20 ms packet).
std::vector<std::vector<uint8_t>>
encode(std::span<const short> interleaved);
private:
SwrContext* swr_ = nullptr;
OpusEncoder* enc_ = nullptr;
int inRate_ = 192000;
std::vector<short> pcm_; // resampled 48 kHz interleaved stereo
};
} // namespace Echoion::Standalone
@@ -1,29 +0,0 @@
#pragma once
#include <PluginTypes.hpp>
#include <condition_variable>
#include <cstddef>
#include <mutex>
#include <vector>
namespace Echoion::Standalone
{
// Owns plugin-event callbacks across a dynamically loaded Core boundary.
// quiesce() is a lifetime barrier: after it returns no callback object, nor
// callback invocation, can still reference code from the old Core image.
class EventCallbackGate final
{
public:
void add(Api::EventCallback callback);
void quiesce();
void dispatch(const Api::PluginEvent& event);
private:
std::mutex mutex_;
std::condition_variable cv_;
std::vector<Api::EventCallback> callbacks_;
std::size_t activeDispatches_{0};
bool accepting_{true};
};
}
@@ -1,13 +0,0 @@
#pragma once
#include <cstddef>
#include <string>
#include <vector>
namespace Echoion::Standalone
{
// Split TeamSpeak messages on UTF-8/line boundaries while preserving each
// complete markdown-it `:::details ... :::` container in one message.
[[nodiscard]] std::vector<std::string>
chunkMessage(const std::string& message, std::size_t limit = 900);
}
@@ -1,41 +0,0 @@
#pragma once
#include <Types.hpp>
#include <cstdint>
#include <filesystem>
#include <string>
#include <vector>
namespace Echoion::Standalone
{
enum class ReleaseFileType : std::uint8_t {
Regular,
Symlink,
};
struct ReleaseFileEntry {
std::filesystem::path path;
ReleaseFileType type{ReleaseFileType::Regular};
std::uintmax_t size{};
std::filesystem::perms mode{std::filesystem::perms::unknown};
std::string sha256;
std::filesystem::path target;
};
struct ReleaseManifest {
std::uint32_t schemaVersion{1};
std::string version;
std::filesystem::path root;
std::filesystem::path executable;
std::filesystem::path core;
std::string executableSha256;
std::string coreSha256;
std::vector<ReleaseFileEntry> files;
[[nodiscard]] static Api::Result<ReleaseManifest>
load(const std::filesystem::path& manifestPath);
[[nodiscard]] Api::Result<void> validate() const;
[[nodiscard]] Api::Result<void> validateInstallLayout() const;
};
} // namespace Echoion::Standalone
@@ -1,42 +0,0 @@
#pragma once
#include <expected>
#include <filesystem>
#include <optional>
#include <string>
namespace Echoion::Standalone
{
[[nodiscard]] std::expected<std::filesystem::path, std::string>
runningExecutablePath();
[[nodiscard]] std::filesystem::path deriveInstallRoot(
const std::filesystem::path& executablePath,
const std::optional<std::filesystem::path>& homeOverride =
std::nullopt);
[[nodiscard]] std::filesystem::path resolveCorePath(
const std::filesystem::path& installRoot,
const std::filesystem::path& executableDirectory,
const std::optional<std::filesystem::path>& coreOverride =
std::nullopt);
[[nodiscard]] std::filesystem::path resolveStateDirectory(
const std::optional<std::filesystem::path>& commandLineOverride,
const std::optional<std::filesystem::path>& environmentOverride,
const std::optional<std::filesystem::path>& xdgStateHome,
const std::optional<std::filesystem::path>& userHome,
const std::filesystem::path& fallback);
[[nodiscard]] std::optional<std::filesystem::path> runtimeWorkingDirectory(
const std::filesystem::path& installRoot,
const std::filesystem::path& executableDirectory);
[[nodiscard]] std::optional<std::filesystem::path>
bundledCertificateBundle(const std::filesystem::path& installRoot);
[[nodiscard]] std::expected<std::filesystem::path, std::string>
resolveAvatarCacheDirectory(
const std::filesystem::path& configuredDirectory,
const std::filesystem::path& requestedDirectory = {});
} // namespace Echoion::Standalone
@@ -1,173 +0,0 @@
#pragma once
// Implements Echoion's host interface by adapting VoidTeamspeak's typed client
// operations and events. TeamSpeak protocol details remain inside
// VoidTeamspeak; Core only sees the host-neutral Echoion API contract.
#include <PluginInterface.hpp>
#include "echoion/standalone/EventCallbackGate.hpp"
#include <Void/TeamSpeak/TeamSpeak.hpp>
#include <atomic>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
namespace Echoion::Standalone
{
class AudioEncoder;
// Runtime knobs the protocol client needs that ServerConfig does not carry.
// Sourced from environment / defaults by main(), so no Core changes are
// required.
struct StandaloneSettings {
std::string identityPath; // where to load/persist the TS identity
std::string avatarCachePath;
int securityLevel = 8;
int opusBitrate = 96000;
};
class StandaloneClientInterface : public Api::IPluginInterface
{
public:
explicit StandaloneClientInterface(StandaloneSettings settings);
~StandaloneClientInterface() override;
// Lifecycle
Api::Result<void> initialize() override;
Api::Result<void> shutdown() override;
// Clients
[[nodiscard]] Api::Result<std::vector<Api::ClientInfo>>
getClients() override;
[[nodiscard]] Api::Result<std::optional<Api::ClientInfo>>
getClient(uint64_t clientId) override;
[[nodiscard]] Api::Result<std::optional<std::string>>
getClientIp(uint64_t clientId) override;
[[nodiscard]] Api::Result<std::optional<std::string>>
getClientAvatarPath(uint64_t clientId) override;
[[nodiscard]] Api::Result<std::optional<std::string>>
getClientAvatarUrl(uint64_t clientId) override;
[[nodiscard]] Api::Result<std::optional<std::string>>
requestClientAvatar(uint64_t clientId,
const std::string& destDir) override;
Api::Result<void> moveClient(uint64_t clientId,
uint64_t channelId) override;
Api::Result<void> kickClient(uint64_t clientId,
const std::string& reason) override;
Api::Result<void>
kickClientFromChannel(uint64_t clientId,
const std::string& reason) override;
Api::Result<void> banClient(uint64_t clientId,
uint64_t durationSeconds,
const std::string& reason) override;
[[nodiscard]] Api::Result<std::vector<Api::BanInfo>>
getBans() override;
Api::Result<void> unban(uint64_t banId) override;
// Channels
[[nodiscard]] Api::Result<std::vector<Api::ChannelInfo>>
getChannels() const override;
[[nodiscard]] Api::Result<std::optional<Api::ChannelInfo>>
getChannel(uint64_t channelId) const override;
Api::Result<uint64_t> createChannel(
const Api::ChannelCreateOptions& options) override;
Api::Result<void>
editChannel(uint64_t channelId,
const Api::ChannelEditOptions& options) override;
Api::Result<void> reorderChannel(uint64_t channelId,
uint64_t parentId,
uint64_t orderAfterId) override;
Api::Result<void> deleteChannel(uint64_t channelId,
bool force) override;
[[nodiscard]] Api::Result<std::vector<Api::ServerGroupInfo>>
getServerGroups() override;
Api::Result<void>
addClientToServerGroup(uint64_t groupId,
uint64_t clientDatabaseId) override;
Api::Result<void>
removeClientFromServerGroup(uint64_t groupId,
uint64_t clientDatabaseId) override;
[[nodiscard]] Api::Result<Api::ServerInfo>
getTeamSpeakServerInfo() override;
// Messaging
Api::Result<void>
sendTextMessage(uint64_t targetId,
const std::string& message) override;
Api::Result<void>
sendChannelMessage(uint64_t channelId,
const std::string& message) override;
Api::Result<void>
sendServerMessage(const std::string& message) override;
// Audio
Api::Result<void>
sendAudioData(const std::span<const short>& data) override;
Api::Result<void>
setWhisperList(const std::vector<uint64_t>& clientIds) override;
// Connection
Api::Result<void>
connectToServer(const Api::ServerConfig& config) override;
Api::Result<void> disconnectFromServer() override;
[[nodiscard]] bool isConnected() const override;
Api::Result<void> reconnect() override;
// Events
void registerEventCallback(const Api::EventCallback& cb) override;
void unregisterEventCallback(const Api::EventCallback& cb) override;
[[nodiscard]] Api::Result<std::string>
hostControl(const std::string& method,
const std::string& requestJson) override;
using HostControlHandler = std::function<Api::Result<std::string>(
const std::string&, const std::string&)>;
void setHostControlHandler(HostControlHandler handler);
// Prevent new event dispatches, release registered callbacks and
// wait until every callback already in flight has returned. The
// host must call this before unloading code that owns an event
// callback.
void quiesceEventCallbacks();
private:
void wireCallbacks();
void broadcast(const Api::PluginEvent& event);
void loadInitialSnapshot();
[[nodiscard]] Api::Result<void> commandResult(
const Void::Result::Result<void, Void::TeamSpeak::Error>&
result) const;
StandaloneSettings settings_;
std::shared_ptr<Void::TeamSpeak::Identity> identity_;
std::unique_ptr<Void::TeamSpeak::Client> client_;
std::unique_ptr<AudioEncoder> encoder_;
Api::ServerConfig currentConfig_{};
std::atomic<bool> initialized_{false};
mutable std::mutex mirrorMutex_;
std::map<uint64_t, Void::TeamSpeak::RemoteClient> clients_;
std::map<uint64_t, Void::TeamSpeak::Channel> channels_;
std::optional<Void::TeamSpeak::ServerInfo> serverInfo_;
std::map<uint64_t, std::string> clientIps_;
std::map<uint64_t, std::string> avatarHashes_;
std::map<uint64_t, std::string> avatarUrls_;
std::map<uint64_t, std::string> avatarPaths_;
std::vector<uint64_t> whisperList_;
std::jthread snapshotThread_;
mutable std::mutex hostControlMutex_;
HostControlHandler hostControlHandler_;
EventCallbackGate eventCallbacks_;
};
} // namespace Echoion::Standalone
@@ -1,17 +0,0 @@
#pragma once
#include <string_view>
namespace Echoion::Standalone::UpdateBuildDefaults
{
inline constexpr std::string_view FeedUrl =
R"ECHOION_UPDATE(@ECHOION_UPDATE_FEED_URL@)ECHOION_UPDATE";
inline constexpr std::string_view PublicKeysJson =
R"ECHOION_UPDATE(@ECHOION_UPDATE_PUBLIC_KEYS_JSON@)ECHOION_UPDATE";
inline constexpr std::string_view RuntimeVersion =
R"ECHOION_UPDATE(@ECHOION_RUNTIME_VERSION@)ECHOION_UPDATE";
inline constexpr std::string_view ApiVersion =
R"ECHOION_UPDATE(@PROJECT_VERSION@)ECHOION_UPDATE";
inline constexpr std::string_view ToolchainAbi =
R"ECHOION_UPDATE(@ECHOION_TOOLCHAIN_ABI@)ECHOION_UPDATE";
}
@@ -1,110 +0,0 @@
#pragma once
#include <Types.hpp>
#include <filesystem>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
namespace Echoion::Standalone
{
struct ManagedCoreStartupSelection {
std::filesystem::path corePath;
std::optional<std::filesystem::path> archivedStore;
bool runtimeBaselineChanged = false;
};
// Installed runtime releases own their bundled Core baseline. A runtime
// version change archives the previous managed store; Core-only updates
// remain active across ordinary restarts of the same runtime.
[[nodiscard]] Api::Result<ManagedCoreStartupSelection>
selectManagedCoreForStartup(
const std::filesystem::path& stateDirectory,
const std::filesystem::path& bundledCore,
std::optional<std::string_view> installedRuntimeVersion);
// Roll back any uncommitted managed-plugin activation before Core loads and
// discovers plugin `current` links. This must run before PluginHost
// startup.
[[nodiscard]] Api::Result<void> reconcileManagedPluginUpdates(
const std::filesystem::path& stateDirectory);
// Host-owned update coordinator. Core only forwards authenticated RPC
// requests across the append-only host interface; all trust, download,
// staging and activation decisions remain in the long-lived daemon.
class UpdateService final
{
public:
struct Options {
std::filesystem::path configPath;
std::filesystem::path stateDirectory;
std::filesystem::path installRoot;
std::filesystem::path runningExecutable;
std::filesystem::path currentCore;
std::filesystem::path releaseManifestPath;
std::string officialFeedUrl;
std::string officialPublicKeysJson = "[]";
std::string runtimeVersion;
std::string apiVersion;
std::string toolchainAbi;
// Trusted administrator drop directory for file://
// feeds/artifacts. Empty selects stateDirectory /
// "incoming".
std::filesystem::path incomingDirectory;
};
struct Hooks {
std::function<Api::Result<void>(
const std::filesystem::path&)>
replaceCore;
std::function<Api::Result<std::string>(const std::string&)>
managePlugins;
std::function<Api::Result<std::string>(const std::string&)>
manageRuntime;
std::function<bool()> playbackActive;
std::function<std::string()> coreVersion;
};
UpdateService(Options options, Hooks hooks);
~UpdateService();
UpdateService(const UpdateService&) = delete;
UpdateService& operator=(const UpdateService&) = delete;
UpdateService(UpdateService&&) noexcept;
UpdateService& operator=(UpdateService&&) noexcept;
[[nodiscard]] Api::Result<void> start();
void stop() noexcept;
// Execute host mutations which must not run on the Core RPC stack.
// The daemon calls this from its polling loop after an RPC has
// returned.
void processPendingHostActions();
// Methods are the internal `updates.*` names forwarded by Core.
// Requests and successful responses are JSON documents matching the
// web contract.
[[nodiscard]] Api::Result<std::string>
handle(const std::string& method,
const std::string& requestJson);
private:
class Impl;
std::unique_ptr<Impl> impl_;
};
using UpdateControlHandler = std::function<Api::Result<std::string>(
const std::string&, const std::string&)>;
// Keep the service alive for the complete duration of an in-flight host
// control request. StandaloneClientInterface intentionally invokes a copied
// handler outside its mutex, so clearing the registered handler cannot
// cancel a callback which has already started.
[[nodiscard]] UpdateControlHandler
bindUpdateService(std::shared_ptr<UpdateService> service);
} // namespace Echoion::Standalone
-102
View File
@@ -1,102 +0,0 @@
#include "echoion/standalone/AudioEncoder.hpp"
extern "C" {
#include <libavutil/channel_layout.h>
#include <libavutil/opt.h>
#include <libavutil/samplefmt.h>
#include <libswresample/swresample.h>
#include <opus/opus.h>
}
#include <stdexcept>
namespace Echoion::Standalone
{
namespace
{
constexpr int OUT_RATE = 48000;
constexpr int CHANNELS = 2;
constexpr int FRAME_SAMPLES = 960; // 20 ms @ 48 kHz per channel
constexpr int FRAME_SHORTS = FRAME_SAMPLES * CHANNELS;
constexpr int MAX_OPUS = 4000;
} // namespace
AudioEncoder::AudioEncoder(int bitrate, int inRate) : inRate_(inRate)
{
AVChannelLayout stereo = AV_CHANNEL_LAYOUT_STEREO;
if (swr_alloc_set_opts2(&swr_, &stereo, AV_SAMPLE_FMT_S16, OUT_RATE,
&stereo, AV_SAMPLE_FMT_S16, inRate_, 0,
nullptr) < 0 ||
swr_init(swr_) < 0) {
throw std::runtime_error("AudioEncoder: swresample init failed");
}
int err = 0;
enc_ = opus_encoder_create(OUT_RATE, CHANNELS, OPUS_APPLICATION_AUDIO,
&err);
if (err != OPUS_OK || !enc_) {
throw std::runtime_error("AudioEncoder: opus encoder init failed");
}
opus_encoder_ctl(enc_, OPUS_SET_BITRATE(bitrate));
opus_encoder_ctl(enc_, OPUS_SET_SIGNAL(OPUS_SIGNAL_MUSIC));
}
AudioEncoder::~AudioEncoder()
{
if (enc_) {
opus_encoder_destroy(enc_);
}
if (swr_) {
swr_free(&swr_);
}
}
std::vector<std::vector<uint8_t>>
AudioEncoder::encode(std::span<const short> interleaved)
{
std::vector<std::vector<uint8_t>> out;
const int inSamplesPerCh =
static_cast<int>(interleaved.size() / CHANNELS);
if (inSamplesPerCh <= 0) {
return out;
}
// Upper bound on resampled samples for this chunk.
int maxOut = static_cast<int>(
av_rescale_rnd(swr_get_delay(swr_, inRate_) + inSamplesPerCh,
OUT_RATE, inRate_, AV_ROUND_UP));
std::vector<short> resampled(
static_cast<size_t>(maxOut) * CHANNELS, 0);
const uint8_t* inPtr =
reinterpret_cast<const uint8_t*>(interleaved.data());
uint8_t* outPtr = reinterpret_cast<uint8_t*>(resampled.data());
int gotPerCh = swr_convert(swr_, &outPtr, maxOut, &inPtr,
inSamplesPerCh);
if (gotPerCh < 0) {
return out;
}
pcm_.insert(pcm_.end(), resampled.begin(),
resampled.begin() +
static_cast<size_t>(gotPerCh) * CHANNELS);
// Emit as many full 20 ms frames as we have buffered.
size_t consumed = 0;
while (pcm_.size() - consumed >= static_cast<size_t>(FRAME_SHORTS)) {
uint8_t packet[MAX_OPUS];
int n = opus_encode(enc_, pcm_.data() + consumed, FRAME_SAMPLES,
packet, MAX_OPUS);
if (n > 0) {
out.emplace_back(packet, packet + n);
}
consumed += FRAME_SHORTS;
}
if (consumed > 0) {
pcm_.erase(pcm_.begin(),
pcm_.begin() + static_cast<std::ptrdiff_t>(consumed));
}
return out;
}
} // namespace Echoion::Standalone
@@ -1,42 +0,0 @@
#include "echoion/standalone/EventCallbackGate.hpp"
#include <Void/Core/Scope.hpp>
#include <utility>
namespace Echoion::Standalone
{
void EventCallbackGate::add(Api::EventCallback callback)
{
std::lock_guard lock(mutex_);
accepting_ = true;
callbacks_.push_back(std::move(callback));
}
void EventCallbackGate::quiesce()
{
std::unique_lock lock(mutex_);
accepting_ = false;
callbacks_.clear();
cv_.wait(lock, [this] { return activeDispatches_ == 0; });
}
void EventCallbackGate::dispatch(const Api::PluginEvent& event)
{
std::vector<Api::EventCallback> callbacks;
{
std::lock_guard lock(mutex_);
if (!accepting_) return;
++activeDispatches_;
callbacks = callbacks_;
}
const auto complete = Void::Scope::on_exit([this] {
std::lock_guard lock(mutex_);
--activeDispatches_;
cv_.notify_all();
});
for (const auto& callback : callbacks) {
if (callback) callback(event);
}
}
}
-86
View File
@@ -1,86 +0,0 @@
#include "echoion/standalone/MessageChunker.hpp"
#include <string_view>
namespace Echoion::Standalone
{
std::vector<std::string> chunkMessage(const std::string& message,
std::size_t limit)
{
if (limit == 0 || message.empty()) {
return message.empty() ? std::vector<std::string>{}
: std::vector<std::string>{message};
}
if (message.size() <= limit) {
return {message};
}
const auto isBlank = [](const std::string& value) {
return value.find_first_not_of(" \t\r\n") == std::string::npos;
};
std::vector<std::string> chunks;
std::string current;
int detailsDepth = 0;
const auto flush = [&] {
if (!current.empty() && !isBlank(current)) {
chunks.push_back(current);
}
current.clear();
};
std::size_t position = 0;
while (position < message.size()) {
const auto newline = message.find('\n', position);
std::string line = newline == std::string::npos
? message.substr(position)
: message.substr(position, newline - position + 1);
position = newline == std::string::npos ? message.size() : newline + 1;
const bool opens = line.starts_with(":::details");
std::string_view trimmed = line;
while (!trimmed.empty() &&
(trimmed.back() == '\n' || trimmed.back() == '\r' ||
trimmed.back() == ' ' || trimmed.back() == '\t')) {
trimmed.remove_suffix(1);
}
const bool closes = trimmed == ":::";
if (detailsDepth == 0 && !current.empty() &&
(opens || current.size() + line.size() > limit)) {
flush();
}
// A details block must remain syntactically complete even if it is
// longer than the preferred message limit. Normal lines are split at
// a UTF-8 code-point boundary.
if (detailsDepth == 0 && !opens) {
while (line.size() > limit) {
std::size_t cut = limit;
while (cut > 0 &&
(static_cast<unsigned char>(line[cut]) & 0xc0) == 0x80) {
--cut;
}
if (cut == 0) {
cut = limit;
}
flush();
auto piece = line.substr(0, cut);
if (!isBlank(piece)) {
chunks.push_back(std::move(piece));
}
line.erase(0, cut);
}
}
current += line;
if (opens) {
++detailsDepth;
}
if (closes && detailsDepth > 0) {
--detailsDepth;
}
}
flush();
return chunks;
}
}
-650
View File
@@ -1,650 +0,0 @@
#include "echoion/standalone/ReleaseManifest.hpp"
#include <Void/Data/Json.hpp>
#include <Void/System/Path.hpp>
#include <openssl/evp.h>
#include <algorithm>
#include <array>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <memory>
#include <ranges>
#include <sstream>
#include <tuple>
#include <unordered_set>
namespace Echoion::Standalone
{
namespace
{
constexpr auto kExecutablePermissions =
std::filesystem::perms::owner_exec |
std::filesystem::perms::group_exec |
std::filesystem::perms::others_exec;
constexpr auto kUnsafeWritablePermissions =
std::filesystem::perms::group_write |
std::filesystem::perms::others_write;
constexpr std::array<std::string_view, 4> kImmutableRoots{
"bin", "lib", "service", "share"};
constexpr double kMaximumExactJsonInteger = 9'007'199'254'740'991.0;
Api::Result<std::string> sha256(const std::filesystem::path& path)
{
std::ifstream input(path, std::ios::binary);
if (!input) {
return Api::fail(Api::ErrorCode::NotFound,
"release artifact not found: " +
path.string());
}
using Context =
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
Context context(EVP_MD_CTX_new(), &EVP_MD_CTX_free);
if (!context ||
EVP_DigestInit_ex(context.get(), EVP_sha256(), nullptr) != 1) {
return Api::fail(Api::ErrorCode::UnknownError,
"cannot initialize SHA-256");
}
std::array<char, 64 * 1024> buffer{};
while (input) {
input.read(buffer.data(),
static_cast<std::streamsize>(buffer.size()));
if (const auto count = input.gcount();
count > 0 &&
EVP_DigestUpdate(context.get(), buffer.data(),
static_cast<std::size_t>(count)) != 1) {
return Api::fail(Api::ErrorCode::UnknownError,
"cannot hash release artifact");
}
}
std::array<unsigned char, EVP_MAX_MD_SIZE> digest{};
unsigned int size{};
if (EVP_DigestFinal_ex(context.get(), digest.data(), &size) != 1) {
return Api::fail(Api::ErrorCode::UnknownError,
"cannot finalize release hash");
}
std::ostringstream output;
output << std::hex << std::setfill('0');
for (unsigned int index = 0; index < size; ++index) {
output << std::setw(2)
<< static_cast<unsigned int>(digest[index]);
}
return output.str();
}
bool isSafeRelativePath(const std::filesystem::path& path)
{
if (path.empty() || path.is_absolute() || path.has_root_name() ||
path.filename().empty() ||
std::ranges::contains(path.native(), '\0')) {
return false;
}
if (path.generic_string() !=
path.lexically_normal().generic_string()) {
return false;
}
return std::ranges::none_of(path, [](const auto& component) {
return component == "." || component == "..";
});
}
bool isSha256(std::string_view value)
{
return value.size() == 64 &&
std::ranges::all_of(
value, [](const unsigned char character) {
return (character >= '0' && character <= '9') ||
(character >= 'a' && character <= 'f');
});
}
std::optional<std::filesystem::perms> parseMode(std::string_view value)
{
if (value.size() != 4 || value.front() != '0' ||
!std::ranges::all_of(value.substr(1), [](const char character) {
return character >= '0' && character <= '7';
})) {
return std::nullopt;
}
unsigned int result{};
for (const char character : value.substr(1)) {
result =
result * 8U + static_cast<unsigned int>(character - '0');
}
return static_cast<std::filesystem::perms>(result);
}
std::optional<std::uintmax_t> parseSize(const Void::Json::Value& entry)
{
const auto* value = entry.find("size");
if (!value || !value->is_number()) {
return std::nullopt;
}
const double number = value->as_number();
if (!std::isfinite(number) || number < 0.0 ||
number > kMaximumExactJsonInteger ||
std::trunc(number) != number) {
return std::nullopt;
}
return static_cast<std::uintmax_t>(number);
}
std::filesystem::path
normalizedAbsolute(const std::filesystem::path& path)
{
std::error_code error;
auto absolute = std::filesystem::absolute(path, error);
return (error ? path : absolute).lexically_normal();
}
bool isWithin(const std::filesystem::path& root,
const std::filesystem::path& candidate)
{
const auto relative = candidate.lexically_relative(root);
return !relative.empty() && !relative.is_absolute() &&
std::ranges::none_of(relative, [](const auto& component) {
return component == "..";
});
}
bool hasUnsafeWritablePermissions(
const std::filesystem::file_status& status)
{
return (status.permissions() & kUnsafeWritablePermissions) !=
std::filesystem::perms::none;
}
std::optional<std::filesystem::path>
relativeToPayload(const std::filesystem::path& path,
const std::filesystem::path& prefix)
{
if (prefix.empty()) {
return path;
}
const auto relative = path.lexically_relative(prefix);
if (!isSafeRelativePath(relative)) {
return std::nullopt;
}
return relative;
}
bool isImmutablePayloadPath(const std::filesystem::path& path,
const std::filesystem::path& prefix)
{
const auto relative = relativeToPayload(path, prefix);
if (!relative || relative->empty()) {
return false;
}
return std::ranges::contains(kImmutableRoots,
relative->begin()->generic_string());
}
Api::Result<std::filesystem::path>
payloadPrefix(const ReleaseManifest& manifest)
{
const auto executable =
manifest.executable.lexically_relative(manifest.root);
if (!isSafeRelativePath(executable) ||
executable.filename() != "echoiond" ||
executable.parent_path().filename() != "bin") {
return Api::fail(Api::ErrorCode::IncompatibleVersion,
"v2 release executable must use the payload "
"bin/echoiond layout");
}
const auto prefix = executable.parent_path().parent_path();
const auto expectedCore =
(manifest.root / prefix / "lib" / "Echoion.ts")
.lexically_normal();
if (manifest.core.lexically_normal() != expectedCore) {
return Api::fail(Api::ErrorCode::IncompatibleVersion,
"v2 release Core must use the payload "
"lib/Echoion.ts layout");
}
return prefix;
}
Api::Result<void>
validateImmutableCoverage(const ReleaseManifest& manifest)
{
auto prefix = payloadPrefix(manifest);
if (!prefix) {
return std::unexpected(prefix.error());
}
std::unordered_set<std::string> declared;
declared.reserve(manifest.files.size());
for (const auto& entry : manifest.files) {
if (!isImmutablePayloadPath(entry.path, *prefix)) {
return Api::fail(
Api::ErrorCode::InvalidArgument,
"release manifest entry is outside the immutable "
"payload roots: " +
entry.path.string());
}
declared.insert(entry.path.generic_string());
}
const auto payloadRoot = manifest.root / *prefix;
std::error_code payloadError;
const auto payloadStatus =
std::filesystem::symlink_status(payloadRoot, payloadError);
if (payloadError ||
payloadStatus.type() != std::filesystem::file_type::directory) {
return Api::fail(Api::ErrorCode::NotFound,
"immutable payload root is missing or has an "
"unexpected type: " +
payloadRoot.string());
}
if (hasUnsafeWritablePermissions(payloadStatus)) {
return Api::fail(Api::ErrorCode::PermissionDenied,
"immutable payload directory is group- or "
"world-writable: " +
payloadRoot.string());
}
for (const auto name : kImmutableRoots) {
const auto directory = manifest.root / *prefix / name;
std::error_code error;
const auto rootStatus =
std::filesystem::symlink_status(directory, error);
if (error || rootStatus.type() !=
std::filesystem::file_type::directory) {
return Api::fail(
Api::ErrorCode::NotFound,
"immutable payload directory is missing or has an "
"unexpected type: " +
directory.string());
}
if (hasUnsafeWritablePermissions(rootStatus)) {
return Api::fail(Api::ErrorCode::PermissionDenied,
"immutable payload directory is group- or "
"world-writable: " +
directory.string());
}
std::filesystem::recursive_directory_iterator iterator{
directory, std::filesystem::directory_options::none, error};
const std::filesystem::recursive_directory_iterator end;
if (error) {
return Api::fail(
Api::ErrorCode::PermissionDenied,
"cannot inspect immutable payload directory: " +
directory.string());
}
while (iterator != end) {
const auto status = iterator->symlink_status(error);
if (error) {
return Api::fail(
Api::ErrorCode::PermissionDenied,
"cannot inspect immutable payload entry: " +
iterator->path().string());
}
if (status.type() ==
std::filesystem::file_type::directory) {
if (hasUnsafeWritablePermissions(status)) {
return Api::fail(
Api::ErrorCode::PermissionDenied,
"immutable payload directory is group- or "
"world-writable: " +
iterator->path().string());
}
} else {
const auto relative =
iterator->path().lexically_relative(manifest.root);
if (status.type() !=
std::filesystem::file_type::regular &&
status.type() !=
std::filesystem::file_type::symlink) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"special file is not allowed in "
"immutable payload: " +
relative.string());
}
if (!declared.contains(relative.generic_string())) {
return Api::fail(
Api::ErrorCode::InvalidArgument,
"undeclared immutable payload entry: " +
relative.string());
}
}
iterator.increment(error);
if (error) {
return Api::fail(
Api::ErrorCode::PermissionDenied,
"cannot traverse immutable payload directory: " +
directory.string());
}
}
}
return {};
}
Api::Result<ReleaseManifest>
loadVersionOne(const Void::Json::Value& json,
const std::filesystem::path& root)
{
ReleaseManifest manifest;
manifest.root = root;
manifest.version = json.get_str("version");
const auto executableEntry =
std::filesystem::path(json.get_str("executable"));
const auto coreEntry = std::filesystem::path(json.get_str("core"));
if (!isSafeRelativePath(executableEntry) ||
!isSafeRelativePath(coreEntry)) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"release artifact paths must stay within the "
"manifest directory");
}
manifest.executable = root / executableEntry;
manifest.core = root / coreEntry;
if (const auto* hashes = json.find("sha256");
hashes && hashes->is_object()) {
manifest.executableSha256 = hashes->get_str("executable");
manifest.coreSha256 = hashes->get_str("core");
}
if (manifest.version.empty() ||
!isSha256(manifest.executableSha256) ||
!isSha256(manifest.coreSha256)) {
return Api::fail(Api::ErrorCode::ParseError,
"release manifest is missing version, "
"artifacts, or hashes");
}
return manifest;
}
Api::Result<ReleaseManifest>
loadVersionTwo(const Void::Json::Value& json,
const std::filesystem::path& root)
{
ReleaseManifest manifest;
manifest.schemaVersion = 2;
manifest.root = root;
manifest.version = json.get_str("version");
const auto executableEntry =
std::filesystem::path(json.get_str("executable"));
const auto coreEntry = std::filesystem::path(json.get_str("core"));
const auto* files = json.child_array("files");
if (manifest.version.empty() ||
!isSafeRelativePath(executableEntry) ||
!isSafeRelativePath(coreEntry) || !files ||
files->as_array().empty()) {
return Api::fail(Api::ErrorCode::ParseError,
"v2 release manifest is missing version, "
"artifacts, or files");
}
std::unordered_set<std::string> paths;
manifest.files.reserve(files->as_array().size());
for (const auto& value : files->as_array()) {
if (!value.is_object()) {
return Api::fail(Api::ErrorCode::ParseError,
"release file entries must be objects");
}
ReleaseFileEntry entry;
entry.path = value.get_str("path");
if (!isSafeRelativePath(entry.path)) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"release file path is absolute, "
"traversing, or not normalized");
}
if (!paths.insert(entry.path.generic_string()).second) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"duplicate release file path: " +
entry.path.string());
}
const auto type = value.get_str("type");
if (type == "file") {
entry.type = ReleaseFileType::Regular;
const auto size = parseSize(value);
const auto mode = parseMode(value.get_str("mode"));
entry.sha256 = value.get_str("sha256");
if (!size || !mode || !isSha256(entry.sha256) ||
value.has("target")) {
return Api::fail(Api::ErrorCode::ParseError,
"regular release file entry has "
"invalid metadata: " +
entry.path.string());
}
entry.size = *size;
entry.mode = *mode;
if ((entry.mode & kUnsafeWritablePermissions) !=
std::filesystem::perms::none) {
return Api::fail(Api::ErrorCode::PermissionDenied,
"release file is group- or "
"world-writable: " +
entry.path.string());
}
} else if (type == "symlink") {
entry.type = ReleaseFileType::Symlink;
entry.target = value.get_str("target");
if (!isSafeRelativePath(entry.target) ||
value.has("size") || value.has("sha256") ||
value.has("mode")) {
return Api::fail(
Api::ErrorCode::ParseError,
"symbolic link entry has invalid metadata: " +
entry.path.string());
}
} else {
return Api::fail(Api::ErrorCode::ParseError,
"unknown release file type: " + type);
}
manifest.files.push_back(std::move(entry));
}
const auto executable = std::ranges::find(
manifest.files, executableEntry, &ReleaseFileEntry::path);
const auto core = std::ranges::find(manifest.files, coreEntry,
&ReleaseFileEntry::path);
if (executable == manifest.files.end() ||
core == manifest.files.end() ||
executable->type != ReleaseFileType::Regular ||
core->type != ReleaseFileType::Regular) {
return Api::fail(Api::ErrorCode::ParseError,
"release executable and Core must reference "
"regular file entries");
}
if ((executable->mode & kExecutablePermissions) ==
std::filesystem::perms::none) {
return Api::fail(Api::ErrorCode::PermissionDenied,
"release executable entry is not executable");
}
manifest.executable = root / executableEntry;
manifest.core = root / coreEntry;
manifest.executableSha256 = executable->sha256;
manifest.coreSha256 = core->sha256;
return manifest;
}
} // namespace
Api::Result<ReleaseManifest>
ReleaseManifest::load(const std::filesystem::path& manifestPath)
{
auto contents = Void::FileSystem::read_file(manifestPath);
if (!contents) {
return Api::fail(Api::ErrorCode::NotFound,
contents.error().message());
}
auto json = Void::Json::parse(*contents);
if (!json || !json->is_object()) {
return Api::fail(Api::ErrorCode::ParseError,
json ? "release manifest must be an object"
: "invalid release manifest: " +
json.error().message);
}
std::error_code error;
auto root = std::filesystem::weakly_canonical(
normalizedAbsolute(manifestPath).parent_path(), error);
if (error) {
return Api::fail(Api::ErrorCode::NotFound,
"cannot resolve release root: " + error.message());
}
const auto* schema = json->find("schemaVersion");
if (!schema) {
return loadVersionOne(*json, root);
}
if (!schema->is_number() || schema->as_number() != 2.0) {
return Api::fail(Api::ErrorCode::IncompatibleVersion,
"unsupported release manifest schema version");
}
return loadVersionTwo(*json, root);
}
Api::Result<void> ReleaseManifest::validate() const
{
if (schemaVersion == 1) {
std::error_code rootError;
const auto canonicalRoot =
std::filesystem::weakly_canonical(root, rootError);
if (rootError) {
return Api::fail(Api::ErrorCode::NotFound,
"cannot resolve release root: " +
rootError.message());
}
for (const auto& [path, expected, executableFile] :
{std::tuple{executable, executableSha256, true},
std::tuple{core, coreSha256, false}}) {
std::error_code error;
const auto status =
std::filesystem::symlink_status(path, error);
if (error ||
status.type() != std::filesystem::file_type::regular) {
return Api::fail(
Api::ErrorCode::NotFound,
"release executable and Core must be regular files");
}
const auto resolved = std::filesystem::canonical(path, error);
if (error || !isWithin(canonicalRoot, resolved)) {
return Api::fail(
Api::ErrorCode::InvalidArgument,
"release artifact resolves outside the release root: " +
path.string());
}
if (executableFile &&
(status.permissions() & kExecutablePermissions) ==
std::filesystem::perms::none) {
return Api::fail(Api::ErrorCode::PermissionDenied,
"release executable is not executable");
}
auto actual = sha256(path);
if (!actual) {
return std::unexpected(actual.error());
}
if (*actual != expected) {
return Api::fail(Api::ErrorCode::IncompatibleVersion,
"SHA-256 mismatch for " + path.string());
}
}
return {};
}
std::error_code rootError;
const auto canonicalRoot =
std::filesystem::weakly_canonical(root, rootError);
if (rootError) {
return Api::fail(Api::ErrorCode::NotFound,
"cannot resolve release root: " +
rootError.message());
}
for (const auto& entry : files) {
const auto path = root / entry.path;
std::error_code error;
const auto status = std::filesystem::symlink_status(path, error);
if (error ||
status.type() == std::filesystem::file_type::not_found) {
return Api::fail(Api::ErrorCode::NotFound,
"release payload entry is missing: " +
entry.path.string());
}
const auto expectedType = entry.type == ReleaseFileType::Regular
? std::filesystem::file_type::regular
: std::filesystem::file_type::symlink;
if (status.type() != expectedType) {
return Api::fail(
Api::ErrorCode::InvalidArgument,
"unexpected file type for release payload entry: " +
entry.path.string());
}
const auto resolved = std::filesystem::canonical(path, error);
if (error || !isWithin(canonicalRoot, resolved)) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"release payload entry resolves outside the "
"release root: " +
entry.path.string());
}
if (entry.type == ReleaseFileType::Symlink) {
const auto actualTarget =
std::filesystem::read_symlink(path, error);
if (error || actualTarget.generic_string() !=
entry.target.generic_string()) {
return Api::fail(Api::ErrorCode::IncompatibleVersion,
"symbolic link target mismatch for " +
entry.path.string());
}
continue;
}
const auto size = std::filesystem::file_size(path, error);
if (error || size != entry.size) {
return Api::fail(Api::ErrorCode::IncompatibleVersion,
"file size mismatch for " +
entry.path.string());
}
if ((status.permissions() & std::filesystem::perms::mask) !=
entry.mode) {
return Api::fail(Api::ErrorCode::PermissionDenied,
"file mode mismatch for " +
entry.path.string());
}
auto actual = sha256(path);
if (!actual) {
return std::unexpected(actual.error());
}
if (*actual != entry.sha256) {
return Api::fail(Api::ErrorCode::IncompatibleVersion,
"SHA-256 mismatch for " + entry.path.string());
}
}
return validateImmutableCoverage(*this);
}
Api::Result<void> ReleaseManifest::validateInstallLayout() const
{
if (schemaVersion != 2) {
return Api::fail(
Api::ErrorCode::IncompatibleVersion,
"installation validation requires a v2 release manifest");
}
if (auto result = validate(); !result) {
return result;
}
const std::filesystem::path expectedExecutable{"bin/echoiond"};
const std::filesystem::path expectedCore{"lib/Echoion.ts"};
const std::filesystem::path expectedWeb{"share/echoion/web/index.html"};
if (executable.lexically_normal() != (root / expectedExecutable) ||
core.lexically_normal() != (root / expectedCore)) {
return Api::fail(Api::ErrorCode::IncompatibleVersion,
"installation manifest does not describe the "
"canonical runtime layout");
}
const auto web =
std::ranges::find(files, expectedWeb, &ReleaseFileEntry::path);
if (web == files.end() || web->type != ReleaseFileType::Regular) {
return Api::fail(Api::ErrorCode::NotFound,
"installation manifest is missing the web "
"dashboard entry point");
}
return {};
}
} // namespace Echoion::Standalone
-194
View File
@@ -1,194 +0,0 @@
#include "echoion/standalone/RuntimePaths.hpp"
#include <algorithm>
#include <array>
#include <ranges>
#include <system_error>
namespace Echoion::Standalone
{
namespace
{
std::filesystem::path absoluteNormalized(std::filesystem::path path)
{
std::error_code error;
auto absolute = std::filesystem::absolute(path, error);
if (error) {
return path.lexically_normal();
}
return absolute.lexically_normal();
}
bool isWithinOrEqual(const std::filesystem::path& root,
const std::filesystem::path& candidate)
{
const auto relative = candidate.lexically_relative(root);
return !relative.empty() && !relative.is_absolute() &&
std::ranges::none_of(relative, [](const auto& component) {
return component == "..";
});
}
} // namespace
std::expected<std::filesystem::path, std::string> runningExecutablePath()
{
std::error_code error;
auto executable =
std::filesystem::read_symlink("/proc/self/exe", error);
if (error || executable.empty()) {
return std::unexpected("cannot resolve /proc/self/exe: " +
error.message());
}
auto canonical = std::filesystem::weakly_canonical(executable, error);
if (error) {
return absoluteNormalized(std::move(executable));
}
return canonical;
}
std::filesystem::path deriveInstallRoot(
const std::filesystem::path& executablePath,
const std::optional<std::filesystem::path>& homeOverride)
{
if (homeOverride && !homeOverride->empty()) {
return absoluteNormalized(*homeOverride);
}
const auto executableDirectory =
absoluteNormalized(executablePath).parent_path();
if (executableDirectory.filename() == "bin") {
return executableDirectory.parent_path();
}
return executableDirectory;
}
std::filesystem::path resolveCorePath(
const std::filesystem::path& installRoot,
const std::filesystem::path& executableDirectory,
const std::optional<std::filesystem::path>& coreOverride)
{
if (coreOverride && !coreOverride->empty()) {
return coreOverride->is_absolute()
? coreOverride->lexically_normal()
: (installRoot / *coreOverride).lexically_normal();
}
const std::array candidates{
installRoot / "lib" / "Echoion.ts",
executableDirectory / "Echoion.ts",
installRoot / "bin" / "Echoion.ts",
installRoot / "plugins" / "Echoion.ts",
};
for (const auto& candidate : candidates) {
std::error_code error;
if (std::filesystem::is_regular_file(candidate, error) && !error) {
return candidate.lexically_normal();
}
}
return candidates.front().lexically_normal();
}
std::filesystem::path resolveStateDirectory(
const std::optional<std::filesystem::path>& commandLineOverride,
const std::optional<std::filesystem::path>& environmentOverride,
const std::optional<std::filesystem::path>& xdgStateHome,
const std::optional<std::filesystem::path>& userHome,
const std::filesystem::path& fallback)
{
if (commandLineOverride && !commandLineOverride->empty()) {
return absoluteNormalized(*commandLineOverride);
}
if (environmentOverride && !environmentOverride->empty()) {
return absoluteNormalized(*environmentOverride);
}
if (xdgStateHome && !xdgStateHome->empty()) {
return absoluteNormalized(*xdgStateHome / "echoion");
}
if (userHome && !userHome->empty()) {
return absoluteNormalized(*userHome / ".local" / "state" /
"echoion");
}
return absoluteNormalized(fallback);
}
std::optional<std::filesystem::path> runtimeWorkingDirectory(
const std::filesystem::path& installRoot,
const std::filesystem::path& executableDirectory)
{
const auto packagedDirectory = installRoot / "share" / "echoion";
std::error_code error;
if (std::filesystem::is_regular_file(
packagedDirectory / "web" / "index.html", error) &&
!error) {
// Installed config paths are rooted at the release prefix (for
// example ./share/echoion/web), so the working directory must be
// the installation root rather than share/echoion itself.
return installRoot;
}
error.clear();
if (std::filesystem::is_regular_file(
executableDirectory / "web" / "index.html", error) &&
!error) {
return executableDirectory;
}
return std::nullopt;
}
std::optional<std::filesystem::path>
bundledCertificateBundle(const std::filesystem::path& installRoot)
{
const auto bundle =
installRoot / "share" / "echoion" / "certs" / "ca-certificates.crt";
std::error_code error;
if (!std::filesystem::is_regular_file(bundle, error) || error ||
std::filesystem::file_size(bundle, error) == 0 || error) {
return std::nullopt;
}
return bundle.lexically_normal();
}
std::expected<std::filesystem::path, std::string>
resolveAvatarCacheDirectory(
const std::filesystem::path& configuredDirectory,
const std::filesystem::path& requestedDirectory)
{
if (configuredDirectory.empty()) {
return std::unexpected("avatar cache directory is not configured");
}
std::error_code error;
const auto configured = std::filesystem::weakly_canonical(
absoluteNormalized(configuredDirectory), error);
if (error) {
return std::unexpected("cannot resolve avatar cache directory: " +
error.message());
}
if (!requestedDirectory.empty() && !requestedDirectory.is_absolute() &&
(requestedDirectory != requestedDirectory.lexically_normal() ||
std::ranges::any_of(requestedDirectory, [](const auto& component) {
return component == "." || component == "..";
}))) {
return std::unexpected("avatar cache subdirectory must be "
"normalized and non-traversing");
}
const auto requested = requestedDirectory.empty() ? configured
: requestedDirectory.is_absolute()
? requestedDirectory
: configured / requestedDirectory;
const auto resolved = std::filesystem::weakly_canonical(
absoluteNormalized(requested), error);
if (error) {
return std::unexpected(
"cannot resolve requested avatar directory: " +
error.message());
}
if (!isWithinOrEqual(configured, resolved)) {
return std::unexpected("requested avatar directory is outside the "
"configured state cache");
}
return resolved;
}
} // namespace Echoion::Standalone
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,160 +0,0 @@
#include "echoion/host/CoreLoader.hpp"
#include <cstdlib>
#include <ctime>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <set>
#include <unistd.h>
namespace
{
int fail(const char* message)
{
std::cerr << message << '\n';
return 1;
}
} // namespace
int main()
{
const auto root = std::filesystem::temp_directory_path() /
("echoion-core-reload-" + std::to_string(::getpid()));
std::filesystem::create_directories(root);
const auto cleanup = [&root] {
std::error_code ec;
std::filesystem::permissions(root / "immutable-lib",
std::filesystem::perms::owner_all,
std::filesystem::perm_options::add, ec);
std::filesystem::remove_all(root, ec);
};
::setenv("XDG_CONFIG_HOME", root.c_str(), 1);
::setenv("XDG_CACHE_HOME", root.c_str(), 1);
::setenv("HOME", root.c_str(), 1);
const auto stateDirectory = root / "runtime-state";
::setenv("ECHOION_STATE_DIR", stateDirectory.c_str(), 1);
const auto dataDirectory = stateDirectory / "data";
::setenv("XDG_DATA_HOME", dataDirectory.c_str(), 1);
const auto ytDlp = dataDirectory / "echoion" / "yt-dlp" / "yt-dlp";
std::filesystem::create_directories(ytDlp.parent_path());
{
std::ofstream output{ytDlp};
output << "#!/bin/sh\necho 9999.01.01\n";
}
{
std::ofstream output{ytDlp.parent_path() / ".last_update"};
output << std::time(nullptr);
}
std::filesystem::permissions(ytDlp,
std::filesystem::perms::owner_read |
std::filesystem::perms::owner_write |
std::filesystem::perms::owner_exec);
const auto config = root / "config.json";
{
std::ofstream output{config};
output << R"({
"network": {"rpcEnabled": false},
"web": {"enabled": false},
"features": {"enableAutoUpdateCheck": false},
"advanced": {"cacheEnabled": false}
})";
}
const auto coreDirectory = root / "immutable-lib";
std::filesystem::create_directories(coreDirectory);
const auto corePath = coreDirectory / "Echoion.ts";
std::filesystem::copy_file(ECHOION_TEST_CORE_PATH, corePath);
const auto directoryEntries = [&coreDirectory] {
std::set<std::filesystem::path> entries;
for (const auto& entry :
std::filesystem::directory_iterator{coreDirectory}) {
entries.insert(entry.path().filename());
}
return entries;
};
const auto entriesBeforeLoad = directoryEntries();
std::filesystem::permissions(coreDirectory,
std::filesystem::perms::owner_read |
std::filesystem::perms::owner_exec |
std::filesystem::perms::group_read |
std::filesystem::perms::group_exec |
std::filesystem::perms::others_read |
std::filesystem::perms::others_exec,
std::filesystem::perm_options::replace);
Echoion::Host::CoreLoader loader;
loader.setConfigPath(config);
if (auto result = loader.load(corePath); !result) {
cleanup();
return fail(result.error().message.c_str());
}
if (directoryEntries() != entriesBeforeLoad) {
cleanup();
return fail(
"initial Core load wrote into the immutable library directory");
}
loader.enableAutoReload();
if (loader.isAutoReloadEnabled()) {
cleanup();
return fail("auto-reload was enabled for a read-only Core directory");
}
std::filesystem::permissions(coreDirectory,
std::filesystem::perms::owner_all |
std::filesystem::perms::group_read |
std::filesystem::perms::group_exec |
std::filesystem::perms::others_read |
std::filesystem::perms::others_exec,
std::filesystem::perm_options::replace);
loader.enableAutoReload();
if (!loader.isAutoReloadEnabled()) {
cleanup();
return fail(
"auto-reload was not enabled for a writable development Core");
}
loader.disableAutoReload();
const auto before = loader.getCore();
if (!before) {
cleanup();
return fail("Core missing after initial load");
}
if (!std::filesystem::is_regular_file(stateDirectory / "echoion.db") ||
std::filesystem::exists(root / "echoion.db") ||
!std::filesystem::is_directory(stateDirectory / "logs")) {
cleanup();
return fail("Core mutable files did not use ECHOION_STATE_DIR");
}
if (auto result = loader.hotReload(corePath); !result) {
cleanup();
return fail(result.error().message.c_str());
}
const auto after = loader.getCore();
if (!after || after.get() == before.get()) {
cleanup();
return fail("Core instance was not transactionally replaced");
}
const auto invalid = root / "Echoion.invalid";
{
std::ofstream output{invalid, std::ios::binary};
output << "not a shared library";
}
std::filesystem::rename(invalid, corePath);
if (auto result = loader.hotReload(corePath); result) {
cleanup();
return fail("invalid replacement unexpectedly activated");
}
const auto retained = loader.getCore();
if (!retained || retained.get() != after.get() ||
!retained->isInitialized()) {
cleanup();
return fail("running Core was not retained after failed activation");
}
if (auto result = loader.unload(); !result) {
cleanup();
return fail(result.error().message.c_str());
}
cleanup();
return 0;
}
@@ -1,59 +0,0 @@
#include "echoion/standalone/EventCallbackGate.hpp"
#include <atomic>
#include <cassert>
#include <chrono>
#include <condition_variable>
#include <future>
#include <memory>
#include <mutex>
int main()
{
Echoion::Standalone::EventCallbackGate gate;
std::mutex mutex;
std::condition_variable enteredCv;
std::condition_variable releaseCv;
bool entered = false;
bool release = false;
std::atomic<int> calls{0};
auto lifetime = std::make_shared<int>(42);
std::weak_ptr<int> observedLifetime = lifetime;
gate.add([&, lifetime](const Echoion::Api::PluginEvent&) {
++calls;
std::unique_lock lock(mutex);
entered = true;
enteredCv.notify_all();
releaseCv.wait(lock, [&] { return release; });
});
lifetime.reset();
Echoion::Api::PluginEvent event;
auto dispatch = std::async(std::launch::async, [&] { gate.dispatch(event); });
{
std::unique_lock lock(mutex);
enteredCv.wait(lock, [&] { return entered; });
}
auto quiesce = std::async(std::launch::async, [&] { gate.quiesce(); });
assert(quiesce.wait_for(std::chrono::milliseconds{30}) ==
std::future_status::timeout);
assert(!observedLifetime.expired());
{
std::lock_guard lock(mutex);
release = true;
}
releaseCv.notify_all();
dispatch.get();
quiesce.get();
assert(observedLifetime.expired());
gate.dispatch(event);
assert(calls == 1);
gate.add([&](const Echoion::Api::PluginEvent&) { ++calls; });
gate.dispatch(event);
assert(calls == 2);
}
@@ -1,41 +0,0 @@
#include "echoion/standalone/MessageChunker.hpp"
#include <iostream>
#include <string>
namespace
{
bool check(bool condition, const char* message)
{
if (!condition) {
std::cerr << "FAILED: " << message << '\n';
}
return condition;
}
}
int main()
{
using Echoion::Standalone::chunkMessage;
bool passed = true;
const std::string header = "# Help\n\n> [!TIP] Prefix is `!`\n\n";
const std::string details =
":::details ▶ Play — commands\n\n" + std::string(1100, 'x') +
"\n\n`!play` query\n> description\n:::\n\n";
const auto helpChunks = chunkMessage(header + details, 900);
passed &= check(helpChunks.size() == 2,
"help header and details block should be separate messages");
passed &= check(helpChunks.size() > 1 &&
helpChunks[1] == details.substr(0, details.size() - 1),
"details container must remain complete even above the limit");
const std::string utf8Line = std::string(899, 'a') + "я" + "tail";
const auto utf8Chunks = chunkMessage(utf8Line, 900);
passed &= check(utf8Chunks.size() == 2,
"long ordinary line should be split");
passed &= check(!utf8Chunks.empty() && utf8Chunks.front().size() == 899,
"UTF-8 sequence should not be split in the middle");
return passed ? 0 : 1;
}
@@ -1,289 +0,0 @@
#include "echoion/standalone/ReleaseManifest.hpp"
#include <Void/System/Path.hpp>
#include <Void/System/TempDir.hpp>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <string_view>
#include <sys/stat.h>
#include <vector>
namespace
{
constexpr std::string_view kAbcSha256 =
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
std::string fileEntry(std::string_view path, std::uintmax_t size,
std::string_view mode,
std::string_view sha256 = kAbcSha256)
{
return "{\"path\":\"" + std::string(path) +
"\",\"type\":\"file\",\"size\":" + std::to_string(size) +
",\"mode\":\"" + std::string(mode) + "\",\"sha256\":\"" +
std::string(sha256) + "\"}";
}
std::string symlinkEntry(std::string_view path, std::string_view target)
{
return "{\"path\":\"" + std::string(path) +
"\",\"type\":\"symlink\",\"target\":\"" + std::string(target) +
"\"}";
}
std::string manifest(std::vector<std::string> entries,
std::string_view executable = "bin/echoiond",
std::string_view core = "lib/Echoion.ts")
{
std::string files;
for (const auto& entry : entries) {
if (!files.empty()) {
files += ',';
}
files += entry;
}
return "{\"schemaVersion\":2,\"version\":\"1.2.3\","
"\"executable\":\"" +
std::string(executable) + "\",\"core\":\"" + std::string(core) +
"\",\"files\":[" + files + "]}";
}
bool writeFile(const std::filesystem::path& path, std::string_view contents,
std::filesystem::perms permissions)
{
std::filesystem::create_directories(path.parent_path());
if (auto result = Void::FileSystem::atomic_write(path, contents);
!result) {
std::cerr << result.error().message() << '\n';
return false;
}
std::error_code error;
std::filesystem::permissions(
path, permissions, std::filesystem::perm_options::replace, error);
if (error) {
std::cerr << error.message() << '\n';
return false;
}
return true;
}
} // namespace
int main()
{
int failures{};
const auto check = [&failures](bool condition, std::string_view message) {
if (!condition) {
std::cerr << message << '\n';
++failures;
}
};
auto directory = Void::FileSystem::TempDir::open("echoion-manifest-test");
if (!directory) {
std::cerr << directory.error().message() << '\n';
return 1;
}
const auto root = directory->path();
const auto manifestPath = root / "manifest.json";
const auto executablePath = root / "bin" / "echoiond";
const auto corePath = root / "lib" / "Echoion.ts";
const auto webPath = root / "share" / "echoion" / "web" / "index.html";
const auto servicePath = root / "service" / "echoion.service.in";
const auto aliasPath = root / "lib" / "libEchoionCore.so";
const auto otherPath = root / "lib" / "Other.so";
const auto executableMode = std::filesystem::perms::owner_read |
std::filesystem::perms::owner_write |
std::filesystem::perms::owner_exec |
std::filesystem::perms::group_read |
std::filesystem::perms::group_exec |
std::filesystem::perms::others_read |
std::filesystem::perms::others_exec;
const auto regularMode = std::filesystem::perms::owner_read |
std::filesystem::perms::owner_write |
std::filesystem::perms::group_read |
std::filesystem::perms::others_read;
if (!writeFile(executablePath, "abc", executableMode) ||
!writeFile(corePath, "abc", regularMode) ||
!writeFile(webPath, "abc", regularMode) ||
!writeFile(servicePath, "abc", regularMode) ||
!writeFile(otherPath, "abc", regularMode)) {
return 1;
}
std::error_code error;
std::filesystem::create_symlink("Echoion.ts", aliasPath, error);
if (error) {
std::cerr << error.message() << '\n';
return 1;
}
const auto validManifest = manifest({
fileEntry("bin/echoiond", 3, "0755"),
fileEntry("lib/Echoion.ts", 3, "0644"),
fileEntry("lib/Other.so", 3, "0644"),
fileEntry("service/echoion.service.in", 3, "0644"),
fileEntry("share/echoion/web/index.html", 3, "0644"),
symlinkEntry("lib/libEchoionCore.so", "Echoion.ts"),
});
check(
Void::FileSystem::atomic_write(manifestPath, validManifest).has_value(),
"failed to write valid manifest");
auto loaded = Echoion::Standalone::ReleaseManifest::load(manifestPath);
check(loaded.has_value(), "valid v2 manifest was rejected while loading");
if (loaded) {
check(loaded->validate().has_value(),
"valid v2 manifest payload was rejected");
check(loaded->validateInstallLayout().has_value(),
"valid canonical install layout was rejected");
const auto undeclaredFile = root / "lib" / "undeclared.so";
check(writeFile(undeclaredFile, "abc", regularMode),
"failed to create undeclared regular-file fixture");
check(!loaded->validate(),
"undeclared regular file in immutable payload was accepted");
std::filesystem::remove(undeclaredFile, error);
const auto undeclaredLink = root / "lib" / "undeclared-link.so";
std::filesystem::create_symlink("Echoion.ts", undeclaredLink, error);
check(!error, "failed to create undeclared symbolic-link fixture");
check(!loaded->validate(),
"undeclared symbolic link in immutable payload was accepted");
std::filesystem::remove(undeclaredLink, error);
const auto specialFile = root / "lib" / "unexpected.fifo";
check(::mkfifo(specialFile.c_str(), 0600) == 0,
"failed to create special-file fixture");
check(!loaded->validate(),
"special file in immutable payload was accepted");
std::filesystem::remove(specialFile, error);
check(writeFile(root / "data" / "mutable-state", "abc", regularMode),
"failed to create mutable-root fixture");
check(loaded->validate().has_value(),
"mutable file outside immutable payload roots was rejected");
std::filesystem::permissions(root / "lib", std::filesystem::perms::all,
std::filesystem::perm_options::replace,
error);
check(!error, "failed to make immutable directory writable");
check(!loaded->validate(),
"world-writable immutable directory was accepted");
std::filesystem::permissions(root / "lib",
std::filesystem::perms::owner_all |
std::filesystem::perms::group_read |
std::filesystem::perms::group_exec |
std::filesystem::perms::others_read |
std::filesystem::perms::others_exec,
std::filesystem::perm_options::replace,
error);
check(!error, "failed to restore immutable directory mode");
}
const auto expectLoadFailure = [&](const std::string& contents,
std::string_view message) {
check(
Void::FileSystem::atomic_write(manifestPath, contents).has_value(),
"failed to write invalid manifest fixture");
check(!Echoion::Standalone::ReleaseManifest::load(manifestPath),
message);
};
expectLoadFailure(manifest({fileEntry("../echoiond", 3, "0755"),
fileEntry("lib/Echoion.ts", 3, "0644")},
"../echoiond"),
"path traversal manifest was accepted");
expectLoadFailure(manifest({fileEntry("bin/echoiond", 3, "0755"),
fileEntry("bin/echoiond", 3, "0755"),
fileEntry("lib/Echoion.ts", 3, "0644")}),
"duplicate payload path was accepted");
expectLoadFailure(
manifest({fileEntry("bin/echoiond", 3, "0755"),
fileEntry("lib/Echoion.ts", 3, "0644"),
symlinkEntry("lib/escape.so", "../outside.so")}),
"traversing symbolic link target was accepted");
expectLoadFailure(manifest({fileEntry("bin/echoiond", 3, "0777"),
fileEntry("lib/Echoion.ts", 3, "0644")}),
"world-writable executable metadata was accepted");
expectLoadFailure(manifest({fileEntry("bin/echoiond", 3, "0755"),
fileEntry("lib/Echoion.ts", 3, "0666")}),
"world-writable non-executable metadata was accepted");
check(writeFile(root / "outside.dat", "abc", regularMode),
"failed to create outside-root manifest fixture");
const auto outsideManifest = manifest({
fileEntry("bin/echoiond", 3, "0755"),
fileEntry("lib/Echoion.ts", 3, "0644"),
fileEntry("lib/Other.so", 3, "0644"),
fileEntry("service/echoion.service.in", 3, "0644"),
fileEntry("share/echoion/web/index.html", 3, "0644"),
symlinkEntry("lib/libEchoionCore.so", "Echoion.ts"),
fileEntry("outside.dat", 3, "0644"),
});
check(Void::FileSystem::atomic_write(manifestPath, outsideManifest)
.has_value(),
"failed to write outside-root manifest");
const auto outside =
Echoion::Standalone::ReleaseManifest::load(manifestPath);
check(outside.has_value() && !outside->validate(),
"manifest entry outside immutable roots was accepted");
expectLoadFailure("{\"schemaVersion\":3,\"version\":\"future\"}",
"unsupported schema version was accepted");
check(
Void::FileSystem::atomic_write(manifestPath, validManifest).has_value(),
"failed to restore valid manifest");
loaded = Echoion::Standalone::ReleaseManifest::load(manifestPath);
if (!loaded) {
std::cerr << "could not reload valid manifest\n";
return 1;
}
{
std::ofstream output(corePath, std::ios::trunc);
output << "xyz";
}
check(!loaded->validate(), "tampered payload hash was accepted");
check(writeFile(corePath, "abc", regularMode),
"failed to restore Core fixture");
std::filesystem::permissions(corePath, std::filesystem::perms::owner_read,
std::filesystem::perm_options::replace, error);
check(!error, "failed to modify Core permissions fixture");
check(!loaded->validate(), "payload mode mismatch was accepted");
std::filesystem::permissions(corePath, regularMode,
std::filesystem::perm_options::replace, error);
std::filesystem::remove(aliasPath, error);
std::filesystem::create_symlink("Other.so", aliasPath, error);
check(!error, "failed to replace symbolic link fixture");
check(!loaded->validate(), "symbolic link target mismatch was accepted");
std::filesystem::remove(aliasPath, error);
check(writeFile(aliasPath, "abc", regularMode),
"failed to create wrong-type fixture");
check(!loaded->validate(), "unexpected regular-file type was accepted");
std::filesystem::remove(aliasPath, error);
std::filesystem::create_symlink("Echoion.ts", aliasPath, error);
std::filesystem::remove(webPath, error);
check(!loaded->validate(), "missing payload entry was accepted");
check(writeFile(webPath, "abc", regularMode),
"failed to restore web fixture");
const std::string legacyManifest =
"{\"version\":\"legacy\",\"executable\":\"bin/echoiond\","
"\"core\":\"lib/Echoion.ts\",\"sha256\":{\"executable\":\"" +
std::string(kAbcSha256) + "\",\"core\":\"" + std::string(kAbcSha256) +
"\"}}";
check(Void::FileSystem::atomic_write(manifestPath, legacyManifest)
.has_value(),
"failed to write legacy manifest");
auto legacy = Echoion::Standalone::ReleaseManifest::load(manifestPath);
check(legacy.has_value(), "legacy release manifest was rejected");
if (legacy) {
check(legacy->validate().has_value(),
"legacy release payload was rejected");
check(!legacy->validateInstallLayout(),
"legacy manifest was accepted for full install validation");
}
return failures == 0 ? 0 : 1;
}
@@ -1,152 +0,0 @@
#include "echoion/standalone/RuntimePaths.hpp"
#include <filesystem>
#include <fstream>
#include <iostream>
#include <random>
#include <string>
namespace
{
class TemporaryTree
{
public:
TemporaryTree()
{
std::random_device random;
path_ =
std::filesystem::temp_directory_path() /
("echoion-runtime-paths-" +
std::to_string(static_cast<unsigned long long>(random())));
std::filesystem::create_directories(path_);
}
~TemporaryTree()
{
std::error_code error;
std::filesystem::remove_all(path_, error);
}
TemporaryTree(const TemporaryTree&) = delete;
TemporaryTree& operator=(const TemporaryTree&) = delete;
[[nodiscard]] const std::filesystem::path& path() const noexcept
{
return path_;
}
private:
std::filesystem::path path_;
};
bool writeFile(const std::filesystem::path& path)
{
std::filesystem::create_directories(path.parent_path());
std::ofstream output(path);
output << "test\n";
return output.good();
}
} // namespace
int main()
{
int failures{};
const auto check = [&failures](bool condition, const std::string& message) {
if (!condition) {
std::cerr << message << '\n';
++failures;
}
};
TemporaryTree tree;
const auto installRoot = tree.path() / "echoion";
const auto executable = installRoot / "bin" / "echoiond";
const auto executableDirectory = executable.parent_path();
check(Echoion::Standalone::deriveInstallRoot(executable) == installRoot,
"bin/echoiond did not resolve to its installation root");
check(Echoion::Standalone::deriveInstallRoot(
executable, tree.path() / "override") == tree.path() / "override",
"ECHOION_HOME-style override was not preferred");
const auto state = Echoion::Standalone::resolveStateDirectory(
tree.path() / "cli-state", tree.path() / "environment-state",
tree.path() / "xdg-state", tree.path() / "home",
tree.path() / "fallback");
check(state == tree.path() / "cli-state",
"command-line state directory did not win precedence");
check(Echoion::Standalone::resolveStateDirectory(
std::nullopt, tree.path() / "environment-state",
tree.path() / "xdg-state", tree.path() / "home",
tree.path() / "fallback") == tree.path() / "environment-state",
"environment state directory did not win precedence");
check(Echoion::Standalone::resolveStateDirectory(
std::nullopt, std::nullopt, tree.path() / "xdg-state",
tree.path() / "home", tree.path() / "fallback") ==
tree.path() / "xdg-state" / "echoion",
"XDG state directory fallback is incorrect");
const auto packagedCore = installRoot / "lib" / "Echoion.ts";
check(writeFile(packagedCore), "failed to create packaged Core fixture");
check(Echoion::Standalone::resolveCorePath(
installRoot, executableDirectory) == packagedCore,
"packaged Core was not resolved from install-root/lib");
check(Echoion::Standalone::resolveCorePath(
installRoot, executableDirectory,
std::filesystem::path{"custom/Echoion.ts"}) ==
installRoot / "custom" / "Echoion.ts",
"relative Core override was not anchored at the install root");
const auto packagedIndex =
installRoot / "share" / "echoion" / "web" / "index.html";
check(writeFile(packagedIndex), "failed to create packaged web fixture");
check(Echoion::Standalone::runtimeWorkingDirectory(
installRoot, executableDirectory) == installRoot,
"packaged web root did not select the installation root as working "
"directory");
const auto bundledCertificates =
installRoot / "share" / "echoion" / "certs" / "ca-certificates.crt";
check(!Echoion::Standalone::bundledCertificateBundle(installRoot),
"missing bundled certificate store was accepted");
check(writeFile(bundledCertificates),
"failed to create bundled certificate store fixture");
check(Echoion::Standalone::bundledCertificateBundle(installRoot) ==
bundledCertificates,
"bundled certificate store was not resolved from the install root");
std::filesystem::remove_all(installRoot / "share");
const auto developmentIndex = executableDirectory / "web" / "index.html";
check(writeFile(developmentIndex),
"failed to create development web fixture");
check(Echoion::Standalone::runtimeWorkingDirectory(
installRoot, executableDirectory) == executableDirectory,
"development web root did not select the executable directory");
const auto avatarCache = tree.path() / "state" / "avatars";
std::filesystem::create_directories(avatarCache);
check(Echoion::Standalone::resolveAvatarCacheDirectory(avatarCache) ==
avatarCache,
"empty avatar directory request did not select the state cache");
check(Echoion::Standalone::resolveAvatarCacheDirectory(
avatarCache, "legacy") == avatarCache / "legacy",
"relative avatar directory was not rooted below state");
check(!Echoion::Standalone::resolveAvatarCacheDirectory(avatarCache,
"../escape"),
"traversing avatar directory was accepted");
check(!Echoion::Standalone::resolveAvatarCacheDirectory(
avatarCache, tree.path() / "outside"),
"absolute avatar directory outside state was accepted");
const auto avatarEscape = avatarCache / "escape";
std::error_code avatarError;
std::filesystem::create_symlink(tree.path(), avatarEscape, avatarError);
check(!avatarError, "failed to create avatar symlink escape fixture");
check(!Echoion::Standalone::resolveAvatarCacheDirectory(avatarCache,
"escape/cache"),
"avatar directory escaped state through a symbolic link");
const auto runningExecutable = Echoion::Standalone::runningExecutablePath();
check(runningExecutable.has_value() &&
std::filesystem::is_regular_file(*runningExecutable),
"running executable could not be resolved through /proc/self/exe");
return failures == 0 ? 0 : 1;
}
@@ -1,64 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
stage_script=$1
updater=$2
service_templates=$3
generator=$(dirname -- "$stage_script")/generate-release-manifest.py
manifest_validator=$(dirname -- "$stage_script")/validate-release-manifest.py
root=$(mktemp -d)
trap 'rm -rf -- "$root"' EXIT
bundle=$root/bundle
mkdir -p -- \
"$bundle/bin" \
"$bundle/lib" \
"$bundle/service" \
"$bundle/share/echoion/certs" \
"$bundle/share/echoion/tools" \
"$bundle/share/echoion/web"
printf '#!/bin/sh\necho "echoiond must not run during release staging" >&2\nexit 97\n' \
> "$bundle/bin/echoiond"
chmod 0755 "$bundle/bin/echoiond"
install -m 0755 -- "$updater" "$bundle/bin/echoion-updater"
printf 'test core\n' > "$bundle/lib/Echoion.ts"
install -m 0644 -- \
"$service_templates/echoion.service.in" \
"$service_templates/echoion-updater.service.in" \
"$service_templates/echoion-updater.timer.in" \
"$bundle/service/"
printf '{"webRoot":"./web"}\n' > "$bundle/share/echoion/config.example.json"
printf 'test trust bundle\n' > "$bundle/share/echoion/certs/ca-certificates.crt"
install -m 0755 -- "$manifest_validator" \
"$bundle/share/echoion/tools/validate-release-manifest.py"
printf '<!doctype html>\n' > "$bundle/share/echoion/web/index.html"
ln -s -- Echoion.ts "$bundle/lib/libEchoionCore.so"
python3 "$generator" --root "$bundle" --version 1.2.3
python3 "$manifest_validator" --root "$bundle" --version 1.2.3
bash "$stage_script" "$root/releases" 1.2.3 "$bundle"
manifest=$root/releases/pending-release.json
test -x "$root/releases/1.2.3/bin/echoiond"
test -x "$root/releases/1.2.3/bin/echoion-updater"
test -f "$root/releases/1.2.3/lib/Echoion.ts"
test -L "$root/releases/1.2.3/lib/libEchoionCore.so"
grep -q '"version": "1.2.3"' "$manifest"
grep -q '"executable": "1.2.3/bin/echoiond"' "$manifest"
grep -q '"updater": "1.2.3/bin/echoion-updater"' "$manifest"
grep -q '"path": "1.2.3/share/echoion/web/index.html"' "$manifest"
python3 "$manifest_validator" --root "$root/releases/1.2.3" --version 1.2.3
printf 'tampered\n' >> "$root/releases/1.2.3/lib/Echoion.ts"
if python3 "$manifest_validator" --root "$root/releases/1.2.3" --version 1.2.3 \
>/dev/null 2>&1; then
echo "tampered Core artifact was accepted" >&2
exit 1
fi
if bash "$stage_script" "$root/releases" '../unsafe' "$bundle" \
>/dev/null 2>&1; then
echo "unsafe version was accepted" >&2
exit 1
fi
@@ -1,41 +0,0 @@
#include "echoion/standalone/UpdateBuildDefaults.hpp"
#include <iostream>
#include <string_view>
#ifndef ECHOION_EXPECTED_RUNTIME_VERSION
#error "ECHOION_EXPECTED_RUNTIME_VERSION must be defined by CMake"
#endif
namespace
{
bool check(bool condition, std::string_view message)
{
if (!condition) {
std::cerr << "FAILED: " << message << '\n';
}
return condition;
}
} // namespace
int main()
{
namespace Defaults = Echoion::Standalone::UpdateBuildDefaults;
bool passed = true;
passed &=
check(Defaults::RuntimeVersion == ECHOION_EXPECTED_RUNTIME_VERSION,
"generated runtime version does not match the configured release "
"version");
passed &=
check(!Defaults::ApiVersion.empty(), "generated API version is empty");
passed &= check(!Defaults::ToolchainAbi.empty(),
"generated toolchain ABI is empty");
passed &=
check(Defaults::PublicKeysJson.size() >= 2 &&
Defaults::PublicKeysJson.front() == '[' &&
Defaults::PublicKeysJson.back() == ']',
"generated update public-key configuration is not a JSON array");
return passed ? 0 : 1;
}
@@ -1,761 +0,0 @@
#include "echoion/standalone/UpdateService.hpp"
#include <Void/Crypto/Crypto.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Text/Hex.hpp>
#include <Void/Update/Update.hpp>
#include <filesystem>
#include <format>
#include <fstream>
#include <iostream>
#include <random>
#include <string>
#include <string_view>
namespace
{
class TemporaryTree
{
public:
TemporaryTree()
{
std::random_device random;
path_ =
std::filesystem::temp_directory_path() /
("echoion-update-service-" +
std::to_string(static_cast<unsigned long long>(random())));
std::filesystem::create_directories(path_);
}
~TemporaryTree()
{
std::error_code error;
std::filesystem::remove_all(path_, error);
}
TemporaryTree(const TemporaryTree&) = delete;
TemporaryTree& operator=(const TemporaryTree&) = delete;
[[nodiscard]] const std::filesystem::path& path() const noexcept
{
return path_;
}
private:
std::filesystem::path path_;
};
bool writeFile(const std::filesystem::path& path, std::string_view contents)
{
std::filesystem::create_directories(path.parent_path());
std::ofstream output(path, std::ios::binary);
output.write(contents.data(),
static_cast<std::streamsize>(contents.size()));
return output.good();
}
std::string readFile(const std::filesystem::path& path)
{
std::ifstream input(path, std::ios::binary);
return {std::istreambuf_iterator<char>{input},
std::istreambuf_iterator<char>{}};
}
bool publishHistoricalVersion(const std::filesystem::path& root,
std::string_view versionText,
const std::filesystem::path& filename,
std::string_view contents)
{
const auto version = Void::Semver::parse_strict(versionText);
if (!version) {
return false;
}
Void::Update::VersionStore store(root);
if (auto initialized = store.initialize(); !initialized) {
return false;
}
auto staging = store.prepare(*version);
if (!staging || !writeFile(*staging / filename, contents)) {
return false;
}
if (auto published = store.publish(*version, *staging); !published) {
return false;
}
return store.recordHealthy(*version).has_value();
}
bool activatePublishedVersion(const std::filesystem::path& root,
std::string_view versionText)
{
const auto version = Void::Semver::parse_strict(versionText);
if (!version) {
return false;
}
Void::Update::VersionStore store(root);
if (auto initialized = store.initialize(); !initialized) {
return false;
}
if (auto activated = store.activate(*version); !activated) {
return false;
}
return store.commit().has_value();
}
std::string sha256(std::string_view contents)
{
auto digest = Void::Crypto::sha256(contents);
return digest ? Void::Encoding::Hex::encode(*digest) : std::string{};
}
std::string architecture()
{
#if defined(__x86_64__) || defined(_M_X64)
return "x86_64";
#elif defined(__aarch64__) || defined(_M_ARM64)
return "aarch64";
#elif defined(__i386__) || defined(_M_IX86)
return "x86";
#else
return "unknown";
#endif
}
std::string configDocument(const std::filesystem::path& feed)
{
return R"json({"updates":{"enabled":false,"retainHealthyVersions":1,"sources":{"official":{"url":"file://)json" +
feed.string() +
R"json(","publicKeys":[],"allowUnsigned":true,"bearerTokenEnv":""}},"runtime":{"enabled":false,"source":"official","channel":"stable","autoApply":false},"core":{"enabled":true,"source":"official","channel":"stable","autoApply":false},"plugins":{"enabled":true,"source":"official","channel":"stable","autoApply":false,"managedOnly":true,"overrides":{}}}})json";
}
std::string release(std::string_view component, std::string_view artifactId,
std::string_view version,
const std::filesystem::path& artifact,
std::string_view contents)
{
return std::format(
R"json({{"component":"{}","artifactId":"{}","channel":"stable","version":"{}","cohort":"test","platform":"linux","arch":"{}","url":"file://{}","size":{},"sha256":"{}","packageType":"file","compatibility":{{"versionContracts":{{}},"exactContracts":{{}}}},"releaseManifestSha256":"0000000000000000000000000000000000000000000000000000000000000000"}})json",
component, artifactId, version, architecture(), artifact.string(),
contents.size(), sha256(contents));
}
std::string feedDocument(const std::filesystem::path& coreArtifact,
std::string_view coreContents,
const std::filesystem::path& pluginArtifact,
std::string_view pluginContents,
std::uint64_t sequence = 1)
{
return std::format(
R"json({{"schemaVersion":1,"feedId":"test","sequence":{},"generatedAt":"2026-01-01T00:00:00Z","expiresAt":"2099-01-01T00:00:00Z","releases":[{},{}]}})json",
sequence,
release("core", "", "2.0.0", coreArtifact, coreContents),
release("plugin", "fixture", "4.0.0", pluginArtifact,
pluginContents));
}
const Void::Json::Value*
parseResponse(const Echoion::Api::Result<std::string>& response,
std::optional<Void::Json::Value>& storage)
{
if (!response) {
return nullptr;
}
auto parsed = Void::Json::parse(*response);
if (!parsed) {
return nullptr;
}
storage = std::move(*parsed);
return &*storage;
}
std::string coreCandidateId(const Void::Json::Value& status)
{
const auto* components = status.find("components");
const auto* core = components ? components->find("core") : nullptr;
const auto* candidate = core ? core->find("candidate") : nullptr;
const auto* id = candidate ? candidate->find("id") : nullptr;
return id && id->is_string() ? id->as_string() : std::string{};
}
std::string pluginCandidateId(const Void::Json::Value& status)
{
const auto* plugins = status.find("plugins");
if (!plugins || !plugins->is_array()) {
return {};
}
for (const auto& plugin : plugins->as_array()) {
if (plugin.get_str("id") != "fixture") {
continue;
}
const auto* candidate = plugin.find("candidate");
const auto* id = candidate ? candidate->find("id") : nullptr;
return id && id->is_string() ? id->as_string() : std::string{};
}
return {};
}
std::string componentRollbackVersion(const Void::Json::Value& status,
std::string_view componentId)
{
const auto* components = status.find("components");
const auto* component =
components ? components->find(componentId) : nullptr;
return component ? component->get_str("rollbackVersion")
: std::string{};
}
std::string pluginRollbackVersion(const Void::Json::Value& status,
std::string_view pluginId)
{
const auto* plugins = status.find("plugins");
if (!plugins || !plugins->is_array()) {
return {};
}
for (const auto& plugin : plugins->as_array()) {
if (plugin.get_str("id") == pluginId) {
return plugin.get_str("rollbackVersion");
}
}
return {};
}
std::string confirmationToken(Echoion::Standalone::UpdateService& service,
std::string_view component,
std::string_view pluginId,
std::string_view candidateId,
std::string_view version)
{
const auto request = std::format(
R"json({{"component":"{}","pluginId":"{}","candidateId":"{}","version":"{}","confirmation":"UNSIGNED {}"}})json",
component, pluginId, candidateId, version, version);
auto response = service.handle("updates.confirmUnsigned", request);
if (!response) {
return {};
}
auto parsed = Void::Json::parse(*response);
return parsed ? parsed->get_str("confirmationToken") : std::string{};
}
} // namespace
int main()
{
int failures{};
const auto check = [&failures](bool condition, std::string_view message) {
if (!condition) {
std::cerr << message << '\n';
++failures;
}
};
TemporaryTree tree;
{
auto ownedService =
std::make_shared<Echoion::Standalone::UpdateService>(
Echoion::Standalone::UpdateService::Options{},
Echoion::Standalone::UpdateService::Hooks{});
std::weak_ptr<Echoion::Standalone::UpdateService> observedService =
ownedService;
auto handler =
Echoion::Standalone::bindUpdateService(ownedService);
ownedService.reset();
check(!observedService.expired(),
"host control handler did not retain UpdateService");
check(handler("updates.getStatus", "{}").has_value(),
"retained UpdateService handler could not serve status");
handler = {};
check(observedService.expired(),
"cleared host control handler retained UpdateService");
}
const auto startupState = tree.path() / "startup-state";
const auto bundledStartupCore =
tree.path() / "startup-runtime" / "lib" / "Echoion.ts";
check(writeFile(bundledStartupCore, "runtime-core"),
"failed to write startup Core fixture");
const auto startupStore = startupState / "updates" / "components" / "core";
check(publishHistoricalVersion(startupStore, "1.1.0", "Echoion.ts",
"stale-managed-core"),
"failed to publish stale managed Core fixture");
check(activatePublishedVersion(startupStore, "1.1.0"),
"failed to activate stale managed Core fixture");
auto firstRuntimeSelection =
Echoion::Standalone::selectManagedCoreForStartup(
startupState, bundledStartupCore, std::string_view{"2.0.0"});
check(firstRuntimeSelection.has_value(),
"runtime Core baseline selection failed");
if (firstRuntimeSelection) {
check(firstRuntimeSelection->corePath == bundledStartupCore,
"new runtime did not prefer its bundled Core");
check(firstRuntimeSelection->runtimeBaselineChanged,
"new runtime did not report a Core baseline change");
check(firstRuntimeSelection->archivedStore.has_value() &&
std::filesystem::is_regular_file(
*firstRuntimeSelection->archivedStore / "versions" /
"1.1.0" / "Echoion.ts"),
"stale managed Core store was not archived");
}
check(publishHistoricalVersion(startupStore, "1.1.0", "Echoion.ts",
"runtime-core"),
"failed to seed the new runtime Core store");
check(activatePublishedVersion(startupStore, "1.1.0"),
"failed to activate the new runtime Core baseline");
auto sameRuntimeSelection =
Echoion::Standalone::selectManagedCoreForStartup(
startupState, bundledStartupCore, std::string_view{"2.0.0"});
check(sameRuntimeSelection.has_value() &&
sameRuntimeSelection->corePath ==
startupStore / "versions" / "1.1.0" / "Echoion.ts" &&
!sameRuntimeSelection->runtimeBaselineChanged,
"same runtime did not retain its managed Core selection");
auto nextRuntimeSelection =
Echoion::Standalone::selectManagedCoreForStartup(
startupState, bundledStartupCore, std::string_view{"2.1.0"});
check(nextRuntimeSelection.has_value() &&
nextRuntimeSelection->corePath == bundledStartupCore &&
nextRuntimeSelection->runtimeBaselineChanged,
"next runtime did not invalidate the prior managed Core baseline");
const auto state = tree.path() / "state";
const auto incoming = tree.path() / "incoming";
const auto currentCore = tree.path() / "installed" / "Echoion.ts";
const auto currentPlugin = tree.path() / "installed" / "fixture.so";
const auto installRoot = tree.path() / "runtime";
const auto runningExecutable = installRoot / "bin" / "echoiond";
const auto coreArtifact = incoming / "Echoion-2.0.0.ts";
const auto pluginArtifact = incoming / "fixture-4.0.0.so";
const auto feed = incoming / "feed.json";
const auto config = tree.path() / "config.json";
constexpr std::string_view oldCore = "old-core";
constexpr std::string_view newCore = "new-core";
constexpr std::string_view oldPlugin = "old-plugin";
constexpr std::string_view newPlugin = "new-plugin";
check(writeFile(currentCore, oldCore), "failed to write current Core");
check(writeFile(currentPlugin, oldPlugin),
"failed to write current plugin");
check(writeFile(coreArtifact, newCore), "failed to write Core artifact");
check(writeFile(pluginArtifact, newPlugin),
"failed to write plugin artifact");
check(writeFile(feed,
feedDocument(coreArtifact, newCore, pluginArtifact,
newPlugin, 9)),
"failed to write update feed");
check(writeFile(config, configDocument(feed)), "failed to write config");
check(publishHistoricalVersion(state / "updates" / "components" / "core",
"0.9.0", "Echoion.ts", "historical-core"),
"failed to seed a historical Core version");
check(publishHistoricalVersion(state / "plugins" / ".managed" / "fixture",
"1.0.0", "fixture.so", "oldest-plugin"),
"failed to seed the oldest historical plugin version");
check(publishHistoricalVersion(state / "plugins" / ".managed" / "fixture",
"2.0.0", "fixture.so", "historical-plugin"),
"failed to seed a historical plugin version");
check(publishHistoricalVersion(installRoot, "0.8.0", "bin/echoiond",
"previous-runtime"),
"failed to seed a runtime rollback version");
check(publishHistoricalVersion(installRoot, "0.9.0", "bin/not-echoiond",
"invalid-runtime-rollback"),
"failed to seed a runtime rollback decoy");
check(publishHistoricalVersion(installRoot, "1.0.0", "bin/echoiond",
"current-runtime"),
"failed to seed the current runtime version");
check(activatePublishedVersion(installRoot, "1.0.0"),
"failed to activate the current runtime version");
std::string coreVersion = "1.0.0";
std::string pluginVersion = "3.0.0";
std::filesystem::path activatedCore;
std::filesystem::path activatedPlugin;
int coreReplacements{};
int pluginReplacements{};
bool rejectCore{};
Void::Update::VersionStore pluginStore(state / "plugins" / ".managed" /
"fixture");
const auto makeService = [&] {
return Echoion::Standalone::UpdateService(
Echoion::Standalone::UpdateService::Options{
.configPath = config,
.stateDirectory = state,
.installRoot = installRoot,
.runningExecutable = runningExecutable,
.currentCore = currentCore,
.releaseManifestPath = {},
.officialFeedUrl = {},
.officialPublicKeysJson = "[]",
.runtimeVersion = "1.0.0",
.apiVersion = "1.1.0",
.toolchainAbi = "test",
.incomingDirectory = incoming},
Echoion::Standalone::UpdateService::Hooks{
.replaceCore = [&](const std::filesystem::path& path)
-> Echoion::Api::Result<void> {
++coreReplacements;
if (rejectCore) {
return Echoion::Api::fail(
Echoion::Api::ErrorCode::PluginError,
"rejected by test");
}
activatedCore = path;
coreVersion = path.parent_path().filename().string();
return {};
},
.managePlugins = [&](const std::string& request)
-> Echoion::Api::Result<std::string> {
auto parsed = Void::Json::parse(request);
if (!parsed) {
return Echoion::Api::fail(
Echoion::Api::ErrorCode::ParseError,
"invalid test request");
}
if (parsed->get_str("action") == "status") {
return std::format(
R"json({{"plugins":[{{"id":"fixture","name":"Fixture","version":"{}","path":"{}","managed":true}}]}})json",
pluginVersion, currentPlugin.string());
}
if (parsed->get_str("action") != "replace") {
return Echoion::Api::fail(
Echoion::Api::ErrorCode::InvalidArgument,
"unexpected test plugin action");
}
++pluginReplacements;
activatedPlugin = parsed->get_str("path");
pluginVersion = parsed->get_str("version");
return "{}";
},
.manageRuntime = {},
.playbackActive = [] { return false; },
.coreVersion = [&] { return coreVersion; }});
};
auto service = makeService();
check(service.start().has_value(), "UpdateService did not start");
check(!std::filesystem::exists(
pluginStore.versionPath(*Void::Semver::parse("1.0.0"))),
"managed plugin startup retention did not prune the oldest version");
auto checked = service.handle("updates.check", "{}");
std::optional<Void::Json::Value> checkedJson;
const auto* checkedStatus = parseResponse(checked, checkedJson);
check(checkedStatus != nullptr, "manual update check failed");
const auto coreId = checkedStatus ? coreCandidateId(*checkedStatus) : "";
const auto pluginId =
checkedStatus ? pluginCandidateId(*checkedStatus) : "";
if ((coreId.empty() || pluginId.empty()) && checked) {
std::cerr << "update check response: " << *checked << '\n';
}
check(!coreId.empty(), "Core candidate was not selected");
check(!pluginId.empty(), "plugin candidate was not selected");
check(checkedStatus && !checkedStatus->get_bool("checking", true),
"completed manual check was returned as still running");
auto repeatedCheck = service.handle("updates.check", "{}");
std::optional<Void::Json::Value> repeatedJson;
const auto* repeatedStatus = parseResponse(repeatedCheck, repeatedJson);
check(repeatedStatus && coreCandidateId(*repeatedStatus) == coreId &&
pluginCandidateId(*repeatedStatus) == pluginId,
"an unchanged feed sequence was incorrectly treated as a replay");
const auto replacementFeed = incoming / "replacement-feed.json";
check(writeFile(
replacementFeed,
feedDocument(coreArtifact, newCore, pluginArtifact, newPlugin)),
"failed to write replacement update feed");
auto replacementConfig = Void::Json::parse(configDocument(replacementFeed));
const auto* replacementUpdates =
replacementConfig ? replacementConfig->find("updates") : nullptr;
check(replacementUpdates != nullptr,
"failed to construct replacement updater configuration");
bool replacementSaved = false;
if (replacementUpdates) {
replacementSaved =
service
.handle("updates.setConfig",
std::format(R"({{"config":{}}})",
Void::Json::serialize(*replacementUpdates)))
.has_value();
}
check(replacementSaved, "custom source URL could not be saved");
auto replacementCheck = service.handle("updates.check", "{}");
std::optional<Void::Json::Value> replacementJson;
const auto* replacementStatus =
parseResponse(replacementCheck, replacementJson);
check(replacementStatus && coreCandidateId(*replacementStatus) == coreId &&
pluginCandidateId(*replacementStatus) == pluginId,
"changing a custom source URL inherited the old feed replay floor");
const auto rejectedCoreToken =
confirmationToken(service, "core", "", coreId, "2.0.0");
check(!rejectedCoreToken.empty(), "Core unsigned confirmation failed");
rejectCore = true;
auto rejectedCoreApply = service.handle(
"updates.apply",
std::format(
R"json({{"component":"core","candidateId":"{}","version":"2.0.0","confirmationToken":"{}"}})json",
coreId, rejectedCoreToken));
check(rejectedCoreApply.has_value(), "failing Core apply did not queue");
service.processPendingHostActions();
check(coreReplacements == 1,
"failing queued Core replacement did not run exactly once");
auto replayedCoreApply = service.handle(
"updates.apply",
std::format(
R"json({{"component":"core","candidateId":"{}","version":"2.0.0","confirmationToken":"{}"}})json",
coreId, rejectedCoreToken));
check(!replayedCoreApply.has_value(),
"failed unsigned Core apply reused a consumed confirmation token");
const auto coreToken =
confirmationToken(service, "core", "", coreId, "2.0.0");
check(!coreToken.empty(), "fresh Core unsigned confirmation failed");
rejectCore = false;
auto coreApply = service.handle(
"updates.apply",
std::format(
R"json({{"component":"core","candidateId":"{}","version":"2.0.0","confirmationToken":"{}"}})json",
coreId, coreToken));
check(coreApply.has_value(), "Core apply did not queue");
check(coreReplacements == 1,
"Core was replaced synchronously on the RPC call stack");
service.processPendingHostActions();
check(coreReplacements == 2, "queued Core replacement did not run");
check(readFile(activatedCore) == newCore,
"queued Core replacement used the wrong artifact");
Void::Update::VersionStore coreStore(state / "updates" / "components" /
"core");
auto activeCoreVersion = coreStore.currentVersion();
check(activeCoreVersion && activeCoreVersion->has_value() &&
(*activeCoreVersion)->to_string() == "2.0.0",
"Core activation was not committed");
check(readFile(coreStore.versionPath(*Void::Semver::parse("1.0.0")) /
"Echoion.ts") == oldCore,
"initial Core was not seeded for rollback");
check(!std::filesystem::exists(
coreStore.versionPath(*Void::Semver::parse("0.9.0"))),
"Core retention did not remove an excess healthy version");
const auto pluginToken =
confirmationToken(service, "plugins", "fixture", pluginId, "4.0.0");
check(!pluginToken.empty(), "plugin unsigned confirmation failed");
auto pluginApply = service.handle(
"updates.apply",
std::format(
R"json({{"component":"plugins","pluginId":"fixture","candidateId":"{}","version":"4.0.0","confirmationToken":"{}"}})json",
pluginId, pluginToken));
check(pluginApply.has_value(), "plugin apply failed");
check(pluginReplacements == 1 && readFile(activatedPlugin) == newPlugin,
"plugin replacement used the wrong artifact");
check(readFile(pluginStore.versionPath(*Void::Semver::parse("3.0.0")) /
"fixture.so") == oldPlugin,
"initial plugin was not seeded for rollback");
check(!std::filesystem::exists(
pluginStore.versionPath(*Void::Semver::parse("2.0.0"))),
"plugin retention did not remove an excess healthy version");
auto unsafePluginRollback = service.handle(
"updates.rollback",
R"({"component":"plugins","pluginId":"../escape","version":"3.0.0"})");
check(!unsafePluginRollback.has_value(),
"plugin rollback accepted a path-traversal plugin id");
auto pluginRollback = service.handle(
"updates.rollback",
R"({"component":"plugins","pluginId":"fixture","version":"3.0.0"})");
check(pluginRollback.has_value() && pluginReplacements == 2 &&
readFile(activatedPlugin) == oldPlugin,
"plugin rollback did not restore the seeded version");
auto unadvertisedRollback = service.handle(
"updates.rollback", R"({"component":"core","version":"2.0.0"})");
check(!unadvertisedRollback.has_value(),
"Core rollback accepted a version that was not advertised healthy");
auto rollback = service.handle("updates.rollback",
R"({"component":"core","version":"1.0.0"})");
check(rollback.has_value(), "Core rollback did not queue");
check(coreReplacements == 2,
"Core rollback ran synchronously on the RPC call stack");
service.processPendingHostActions();
check(coreReplacements == 3 && readFile(activatedCore) == oldCore,
"queued Core rollback did not restore the seed");
rejectCore = true;
auto failedRollback = service.handle(
"updates.rollback", R"({"component":"core","version":"2.0.0"})");
check(failedRollback.has_value(), "failing Core rollback did not queue");
service.processPendingHostActions();
activeCoreVersion = coreStore.currentVersion();
check(coreReplacements == 4 && activeCoreVersion &&
activeCoreVersion->has_value() &&
(*activeCoreVersion)->to_string() == "1.0.0",
"failed Core replacement did not roll back the VersionStore");
auto finalStatus = service.handle("updates.getStatus", "{}");
check(finalStatus && finalStatus->contains("rejected by test"),
"failed deferred activation was not reported in status/history");
const auto plugin4 = *Void::Semver::parse("4.0.0");
check(pluginStore.activate(plugin4).has_value(),
"could not stage an interrupted plugin activation");
check(Echoion::Standalone::reconcileManagedPluginUpdates(state).has_value(),
"managed plugin startup reconciliation failed");
auto recoveredPluginVersion = pluginStore.currentVersion();
check(recoveredPluginVersion && recoveredPluginVersion->has_value() &&
(*recoveredPluginVersion)->to_string() == "3.0.0",
"startup reconciliation did not roll back the interrupted plugin");
const auto sequenceState = state / "updates" / "sequences.json";
std::filesystem::remove(sequenceState);
std::filesystem::create_directory(sequenceState);
check(!service.handle("updates.check", "{}").has_value(),
"update check ignored a replay-floor persistence failure");
std::filesystem::remove(sequenceState);
service.stop();
auto restarted = makeService();
check(restarted.start().has_value(),
"restarted UpdateService did not start");
auto restartedStatusResponse = restarted.handle("updates.getStatus", "{}");
std::optional<Void::Json::Value> restartedStatusJson;
const auto* restartedStatus =
parseResponse(restartedStatusResponse, restartedStatusJson);
check(restartedStatus != nullptr,
"restarted UpdateService did not return status");
check(restartedStatus &&
componentRollbackVersion(*restartedStatus, "runtime") == "0.8.0",
"runtime rollback metadata was not reconstructed or accepted an "
"invalid payload");
check(restartedStatus &&
componentRollbackVersion(*restartedStatus, "core") == "2.0.0",
"Core rollback metadata was not reconstructed after restart");
check(restartedStatus &&
pluginRollbackVersion(*restartedStatus, "fixture") == "4.0.0",
"plugin rollback metadata was not reconstructed after restart");
check(readFile(coreStore.versionPath(*Void::Semver::parse("2.0.0")) /
"Echoion.ts") == newCore,
"retained Core rollback payload was unavailable after restart");
check(readFile(pluginStore.versionPath(*Void::Semver::parse("4.0.0")) /
"fixture.so") == newPlugin,
"retained plugin rollback payload was unavailable after restart");
Void::Update::VersionStore runtimeStore(installRoot);
check(readFile(runtimeStore.versionPath(*Void::Semver::parse("0.8.0")) /
"bin" / "echoiond") == "previous-runtime",
"retained runtime rollback payload was unavailable after restart");
restarted.stop();
check(writeFile(sequenceState, "{not-json"),
"failed to write corrupt replay-floor fixture");
auto corruptReplayState = makeService();
const auto corruptReplayStart = corruptReplayState.start();
check(
!corruptReplayStart &&
corruptReplayStart.error().message.contains("replay-floor"),
"corrupt replay-floor state silently disabled anti-replay persistence");
std::filesystem::remove(sequenceState);
#ifndef _WIN32
const auto runtimeLock = installRoot / ".update.lock";
const auto runtimeHealth = installRoot / "health.log";
std::filesystem::permissions(runtimeLock, std::filesystem::perms::none,
std::filesystem::perm_options::replace);
std::filesystem::permissions(runtimeHealth, std::filesystem::perms::none,
std::filesystem::perm_options::replace);
std::ifstream unreadableProbe{runtimeLock, std::ios::binary};
if (!unreadableProbe) {
auto legacy = makeService();
check(legacy.start().has_value(),
"unreadable legacy runtime metadata disabled UpdateService");
auto legacyStatusResponse = legacy.handle("updates.getStatus", "{}");
std::optional<Void::Json::Value> legacyStatusJson;
const auto* legacyStatus =
parseResponse(legacyStatusResponse, legacyStatusJson);
check(legacyStatus &&
componentRollbackVersion(*legacyStatus, "runtime").empty(),
"unreadable legacy metadata exposed a runtime rollback");
legacy.stop();
}
const auto readableMetadata = std::filesystem::perms::owner_read |
std::filesystem::perms::owner_write |
std::filesystem::perms::group_read |
std::filesystem::perms::others_read;
std::filesystem::permissions(runtimeLock, readableMetadata,
std::filesystem::perm_options::replace);
std::filesystem::permissions(runtimeHealth, readableMetadata,
std::filesystem::perm_options::replace);
#endif
TemporaryTree freshTree;
const auto freshState = freshTree.path() / "state";
const auto freshIncoming = freshTree.path() / "incoming";
const auto freshFeed = freshIncoming / "feed.json";
const auto freshConfig = freshTree.path() / "config.json";
const auto freshCore = freshTree.path() / "installed" / "Echoion.ts";
const auto freshInstall = freshTree.path() / "runtime";
check(writeFile(freshFeed, "{}"),
"failed to write fresh-install feed fixture");
check(writeFile(freshConfig, configDocument(freshFeed)),
"failed to write fresh-install config fixture");
check(writeFile(freshCore, oldCore),
"failed to write fresh-install Core fixture");
check(writeFile(freshInstall / "versions" / "1.0.0" / "bin" / "echoiond",
"fresh-runtime"),
"failed to write fresh-install runtime fixture");
std::filesystem::create_directory_symlink(
std::filesystem::path{"versions"} / "1.0.0", freshInstall / "current");
Echoion::Standalone::UpdateService freshService(
Echoion::Standalone::UpdateService::Options{
.configPath = freshConfig,
.stateDirectory = freshState,
.installRoot = freshInstall,
.runningExecutable = freshInstall / "bin" / "echoiond",
.currentCore = freshCore,
.releaseManifestPath = {},
.officialFeedUrl = {},
.officialPublicKeysJson = "[]",
.runtimeVersion = "1.0.0",
.apiVersion = "1.1.0",
.toolchainAbi = "test",
.incomingDirectory = freshIncoming},
Echoion::Standalone::UpdateService::Hooks{});
check(freshService.start().has_value(),
"fresh install without VersionStore metadata did not start");
auto freshStatusResponse = freshService.handle("updates.getStatus", "{}");
std::optional<Void::Json::Value> freshStatusJson;
const auto* freshStatus =
parseResponse(freshStatusResponse, freshStatusJson);
check(freshStatus &&
componentRollbackVersion(*freshStatus, "runtime").empty(),
"fresh install synthesized runtime rollback metadata");
freshService.stop();
TemporaryTree blockedTree;
const auto blockedState = blockedTree.path() / "state";
const auto blockedIncoming = blockedTree.path() / "incoming";
const auto blockedFeed = blockedIncoming / "feed.json";
const auto blockedConfig = blockedTree.path() / "config.json";
const auto blockedCore = blockedTree.path() / "installed" / "Echoion.ts";
check(writeFile(blockedFeed, "{}"),
"failed to write blocked-start feed fixture");
check(writeFile(blockedConfig, configDocument(blockedFeed)),
"failed to write blocked-start config fixture");
check(writeFile(blockedCore, oldCore),
"failed to write blocked-start Core fixture");
check(writeFile(blockedState / "updates" / "downloads", "not-a-directory"),
"failed to create blocked updater directory fixture");
Echoion::Standalone::UpdateService blockedService(
Echoion::Standalone::UpdateService::Options{
.configPath = blockedConfig,
.stateDirectory = blockedState,
.installRoot = blockedTree.path() / "runtime",
.runningExecutable =
blockedTree.path() / "runtime" / "bin" / "echoiond",
.currentCore = blockedCore,
.releaseManifestPath = {},
.officialFeedUrl = {},
.officialPublicKeysJson = "[]",
.runtimeVersion = "1.0.0",
.apiVersion = "1.1.0",
.toolchainAbi = "test",
.incomingDirectory = blockedIncoming},
Echoion::Standalone::UpdateService::Hooks{});
const auto blockedStart = blockedService.start();
check(!blockedStart && blockedStart.error().message.contains("downloads"),
"startup masked an earlier updater directory creation failure");
blockedService.stop();
return failures == 0 ? 0 : 1;
}
-131
View File
@@ -1,131 +0,0 @@
cmake_minimum_required(VERSION 4.0.0)
if(NOT DEFINED ECHOION_PRODUCT_VERSION)
set(ECHOION_PRODUCT_VERSION 0.0.0)
endif()
project(EchoionWeb VERSION "${ECHOION_PRODUCT_VERSION}" LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
file(GLOB_RECURSE WEB_SOURCES CONFIGURE_DEPENDS "src/**.cpp")
add_library(EchoionWeb STATIC ${WEB_SOURCES})
add_library(Echoion::Web ALIAS EchoionWeb)
target_include_directories(EchoionWeb PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
# EchoionCore is configured before this module and creates the header-only
# Boost:: targets from the single system Boost. Fall back to discovering them
# only if this module is ever built without Core. Check each target because
# aliases created by a sibling directory are not necessarily visible here.
find_package(Boost 1.87 CONFIG QUIET COMPONENTS system url)
foreach(_hdr asio beast system)
if(NOT TARGET Boost::${_hdr})
add_library(_web_boost_${_hdr}_hdr INTERFACE)
add_library(Boost::${_hdr} ALIAS _web_boost_${_hdr}_hdr)
target_include_directories(_web_boost_${_hdr}_hdr INTERFACE
"${Boost_INCLUDE_DIRS}")
endif()
endforeach()
find_package(Threads REQUIRED)
target_link_libraries(EchoionWeb
PUBLIC
Echoion::ApiConfig
Void::Data
Void::Log
Void::Async
PRIVATE
Threads::Threads
Boost::beast
Boost::asio
Boost::system
Boost::url
)
if(MSVC)
target_compile_options(EchoionWeb PRIVATE /W4 /WX-)
else()
target_compile_options(EchoionWeb PRIVATE -Wall -Wextra -Wpedantic)
endif()
# ── Browser frontend (Vite + React + TypeScript) ─────────────────────────────
# The UI lives in frontend/ and is built with npm/vite into frontend/web-dist.
# That build output is what ships next to the runtime binary (default webRoot
# "./web", relative to the working directory) and is installed. Opt out with
# -DECHOION_BUILD_WEB=OFF to skip the npm build (e.g. for a C++-only CI job).
if(BUILD_TESTS)
add_executable(echoion_web_security_tests
tests/HttpSecurityTests.cpp)
target_link_libraries(echoion_web_security_tests PRIVATE
EchoionWeb
Threads::Threads)
add_test(NAME echoion_web_security_tests
COMMAND echoion_web_security_tests)
endif()
option(ECHOION_BUILD_WEB "Build the React dashboard frontend with npm/vite" ON)
set(_web_frontend "${CMAKE_CURRENT_SOURCE_DIR}/frontend")
set(_web_dist "${_web_frontend}/web-dist")
if(ECHOION_BUILD_WEB)
find_program(NPM_EXECUTABLE NAMES npm npm.cmd)
if(NOT NPM_EXECUTABLE)
message(FATAL_ERROR
"npm was not found but ECHOION_BUILD_WEB is ON. Install Node.js/npm, "
"or configure with -DECHOION_BUILD_WEB=OFF to skip the web frontend.")
endif()
# Rebuild web-dist whenever any source/config under frontend/ (excluding
# node_modules and the output dir) changes. CONFIGURE_DEPENDS re-globs at
# build time so new files are picked up without re-running CMake.
file(GLOB_RECURSE _web_tree_srcs CONFIGURE_DEPENDS
LIST_DIRECTORIES FALSE
"${_web_frontend}/src/*"
"${_web_frontend}/public/*")
set(_web_srcs
${_web_tree_srcs}
"${_web_frontend}/index.html"
"${_web_frontend}/package.json"
"${_web_frontend}/package-lock.json"
"${_web_frontend}/tsconfig.json"
"${_web_frontend}/vite.config.ts")
add_custom_command(
OUTPUT "${_web_dist}/index.html"
# Release builds run `npm ci` before CMake. This lockfile-aware fallback
# keeps direct developer builds convenient without reinstalling on every
# incremental build.
COMMAND ${NPM_EXECUTABLE} install --prefer-offline --no-audit --no-fund
COMMAND ${NPM_EXECUTABLE} run build
WORKING_DIRECTORY "${_web_frontend}"
DEPENDS ${_web_srcs}
COMMENT "Building Echoion web frontend (vite)"
VERBATIM)
add_custom_target(EchoionWebFrontend ALL
DEPENDS "${_web_dist}/index.html")
add_dependencies(EchoionWeb EchoionWebFrontend)
set(_web_assets "${_web_dist}")
else()
# Frontend build skipped: ship whatever is already in web-dist (a prior
# build or a committed snapshot). Falls back to nothing if absent.
set(_web_assets "${_web_dist}")
endif()
# Ship the built browser assets next to the runtime binary. Remove the target
# first so stale files (e.g. an earlier vanilla-JS build) never linger.
add_custom_command(TARGET EchoionWeb POST_BUILD
COMMAND ${CMAKE_COMMAND} -E rm -rf "${CMAKE_BINARY_DIR}/bin/web"
COMMAND ${CMAKE_COMMAND} -E copy_directory
"${_web_assets}"
"${CMAKE_BINARY_DIR}/bin/web"
COMMENT "Copying EchoionWeb static assets to bin/web"
)
install(DIRECTORY "${_web_dist}/" DESTINATION share/echoion/web)
-3
View File
@@ -1,3 +0,0 @@
node_modules/
web-dist/
*.tsbuildinfo
-19
View File
@@ -1,19 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Echoion — Music Bot</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<link rel="manifest" href="/manifest.webmanifest">
<meta name="theme-color" content="#151522">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="Echoion">
<link rel="apple-touch-icon" href="/icon.svg">
<link rel="stylesheet" href="/fonts.css">
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
File diff suppressed because it is too large. Load diff
-26
View File
@@ -1,26 +0,0 @@
{
"name": "echoion-web",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview",
"test": "vitest run",
"i18n:check": "node scripts/i18n-check.mjs"
},
"dependencies": {
"react": "^19.1.0",
"react-dom": "^19.1.0"
},
"devDependencies": {
"@types/react": "^19.1.0",
"@types/react-dom": "^19.1.0",
"@types/youtube": "^0.1.2",
"@vitejs/plugin-react": "^4.5.0",
"typescript": "^5.8.0",
"vite": "^6.3.0",
"vitest": "^3.1.0"
}
}
-6
View File
@@ -1,6 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<rect width="24" height="24" rx="5" fill="#151522"/>
<rect x="4" y="9" width="3.4" height="10" rx="1.6" fill="#a970ff"/>
<rect x="10.3" y="4" width="3.4" height="15" rx="1.6" fill="#ff8080"/>
<rect x="16.6" y="12" width="3.4" height="7" rx="1.6" fill="#ffd977"/>
</svg>

Before

Width:  |  Height:  |  Size: 335 B

-480
View File
@@ -1,480 +0,0 @@
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/JetBrainsMono-1.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/JetBrainsMono-2.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/JetBrainsMono-3.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/JetBrainsMono-4.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/JetBrainsMono-5.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/JetBrainsMono-6.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/JetBrainsMono-1.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/JetBrainsMono-2.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/JetBrainsMono-3.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/JetBrainsMono-4.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/JetBrainsMono-5.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/JetBrainsMono-6.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/JetBrainsMono-1.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/JetBrainsMono-2.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/JetBrainsMono-3.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/JetBrainsMono-4.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/JetBrainsMono-5.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/JetBrainsMono-6.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/Manrope-7.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/Manrope-8.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/Manrope-9.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/Manrope-10.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/Manrope-11.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/Manrope-12.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/Manrope-7.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/Manrope-8.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/Manrope-9.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/Manrope-10.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/Manrope-11.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/Manrope-12.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/Manrope-7.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/Manrope-8.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/Manrope-9.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/Manrope-10.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/Manrope-11.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/Manrope-12.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/Manrope-7.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/Manrope-8.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/Manrope-9.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/Manrope-10.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/Manrope-11.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/Manrope-12.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url("/fonts/Manrope-7.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url("/fonts/Manrope-8.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url("/fonts/Manrope-9.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url("/fonts/Manrope-10.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url("/fonts/Manrope-11.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url("/fonts/Manrope-12.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/SpaceGrotesk-13.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/SpaceGrotesk-14.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/SpaceGrotesk-15.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/SpaceGrotesk-13.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/SpaceGrotesk-14.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/SpaceGrotesk-15.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/SpaceGrotesk-13.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/SpaceGrotesk-14.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/SpaceGrotesk-15.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/SpaceGrotesk-13.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/SpaceGrotesk-14.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/SpaceGrotesk-15.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,7 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<!-- Full-bleed background for the maskable safe area; bars inset ~20%. -->
<rect width="512" height="512" fill="#151522"/>
<rect x="150" y="232" width="52" height="150" rx="24" fill="#a970ff"/>
<rect x="238" y="160" width="52" height="222" rx="24" fill="#ff8080"/>
<rect x="326" y="278" width="52" height="104" rx="24" fill="#ffd977"/>
</svg>

Before

Width:  |  Height:  |  Size: 412 B

-6
View File
@@ -1,6 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<rect width="512" height="512" rx="112" fill="#151522"/>
<rect x="96" y="200" width="72" height="212" rx="34" fill="#a970ff"/>
<rect x="220" y="100" width="72" height="312" rx="34" fill="#ff8080"/>
<rect x="344" y="264" width="72" height="148" rx="34" fill="#ffd977"/>
</svg>

Before

Width:  |  Height:  |  Size: 343 B

@@ -1,25 +0,0 @@
{
"name": "Echoion Music Bot",
"short_name": "Echoion",
"description": "Control the Echoion TeamSpeak music bot and view live server activity.",
"start_url": "/",
"scope": "/",
"display": "standalone",
"orientation": "any",
"background_color": "#0d0d1f",
"theme_color": "#151522",
"icons": [
{
"src": "/icon.svg",
"sizes": "any",
"type": "image/svg+xml",
"purpose": "any"
},
{
"src": "/icon-maskable.svg",
"sizes": "any",
"type": "image/svg+xml",
"purpose": "maskable"
}
]
}
-82
View File
@@ -1,82 +0,0 @@
// Minimal, dependency-free service worker: makes the panel installable and
// keeps the app shell available offline. It deliberately does NOT touch the
// live surfaces — /rpc (WebSockets aren't interceptable anyway),
// /config.json, /api/* and /avatar/* all fall through to the network so the
// UI never shows stale identity/config.
// Bump when the player shell changes materially so installed/PWA clients do
// not retain an index that references a removed hashed bundle.
const CACHE = 'echoion-shell-v4';
const SHELL = ['/', '/manifest.webmanifest', '/icon.svg', '/icon-maskable.svg'];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE).then((c) => c.addAll(SHELL)).then(() => self.skipWaiting())
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches
.keys()
.then((keys) =>
Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))
)
.then(() => self.clients.claim())
);
});
// Only same-origin GETs are cacheable; everything else passes through.
function isStaticAsset(url) {
return (
url.pathname.startsWith('/assets/') ||
url.pathname === '/manifest.webmanifest' ||
url.pathname.startsWith('/icon') ||
url.pathname.startsWith('/fonts') ||
url.pathname.endsWith('.css') ||
url.pathname.endsWith('.woff2') ||
url.pathname.endsWith('.svg')
);
}
self.addEventListener('fetch', (event) => {
const req = event.request;
if (req.method !== 'GET') return;
const url = new URL(req.url);
if (url.origin !== self.location.origin) return;
// Never intercept the live control/config/media surfaces.
if (
url.pathname === '/config.json' ||
url.pathname.startsWith('/api/') ||
url.pathname.startsWith('/rpc') ||
url.pathname.startsWith('/avatar')
) {
return;
}
// SPA navigations: network-first, fall back to the cached shell offline.
if (req.mode === 'navigate') {
event.respondWith(
fetch(req).catch(() => caches.match('/').then((r) => r || fetch(req)))
);
return;
}
// Hashed static assets: cache-first, populate on first hit.
if (isStaticAsset(url)) {
event.respondWith(
caches.match(req).then(
(hit) =>
hit ||
fetch(req).then((resp) => {
if (resp.ok) {
const copy = resp.clone();
caches.open(CACHE).then((c) => c.put(req, copy));
}
return resp;
})
)
);
}
});
-103
View File
@@ -1,103 +0,0 @@
#!/usr/bin/env node
// Diffs the Russian catalog (src/i18n/ru.ts) against every t('…') / tf('…')
// literal in src/**/*.ts{,x}, both ways:
// - missing: used in code but absent from ru.ts (falls back to English)
// - orphaned: present in ru.ts but never used as a literal key
//
// Dynamic keys can't be found by this scan and must be checked by hand:
// - SHORTCUTS labels (lib/shortcuts.ts) rendered via t(sc.label)
// - HEADS view titles/subtitles (App.tsx) rendered via t(title)/t(sub)
// Orphans reported here may be one of those dynamic keys — the KNOWN_DYNAMIC
// list below suppresses the ones we know about.
//
// Usage: npm run i18n:check (exits 1 when keys are missing)
import { readFileSync, readdirSync, statSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
const srcDir = join(root, 'src');
const ruFile = join(srcDir, 'i18n', 'ru.ts');
// Keys reached through variables (see header); keep in sync by hand.
const KNOWN_DYNAMIC = new Set([
// connection state rendered via t(s.connection) in Sidebar.tsx
'connected',
'disconnected',
'error',
// SHORTCUTS labels (lib/shortcuts.ts)
'Play / pause',
'Seek 5s',
'Volume',
'Skip / vote skip',
'Focus search',
'This help',
// HEADS view titles/subtitles (App.tsx)
'Dashboard',
'Live playback and TeamSpeak server activity',
'Queue',
'Reorder and manage upcoming tracks',
'Search',
'Find tracks across YouTube and Yandex Music',
'Library',
'Your favorites and saved playlists',
'History & Stats',
'Playback history and server insights',
'Server & Admin',
'Manage subscribers and broadcast',
'Updates',
'Runtime, Core, and plugin release control',
'RPC / API',
'Connect to Echoion programmatically',
// Sidebar NAV labels rendered via t(item.label) — same strings as HEADS
// titles, listed above.
]);
const unescape = (s) => s.replace(/\\(.)/g, '$1');
function walk(dir, out = []) {
for (const name of readdirSync(dir)) {
const p = join(dir, name);
if (statSync(p).isDirectory()) walk(p, out);
else if (/\.tsx?$/.test(name) && !/\.test\.tsx?$/.test(name)) {
out.push(p);
}
}
return out;
}
// Catalog keys: top-level `'key': '…'` entries of the ru object literal.
const ruKeys = new Set();
for (const m of readFileSync(ruFile, 'utf8').matchAll(
/^\s*'((?:[^'\\]|\\.)*)':/gm
)) {
ruKeys.add(unescape(m[1]));
}
// Used keys: every t('…') / tf('…', …) string literal.
const used = new Set();
for (const file of walk(srcDir)) {
if (file === ruFile) continue;
const text = readFileSync(file, 'utf8');
for (const m of text.matchAll(/\btf?\(\s*'((?:[^'\\]|\\.)*)'/g)) {
used.add(unescape(m[1]));
}
}
const missing = [...used].filter((k) => !ruKeys.has(k)).sort();
const orphaned = [...ruKeys]
.filter((k) => !used.has(k) && !KNOWN_DYNAMIC.has(k))
.sort();
if (missing.length) {
console.log(`Missing from ru.ts (${missing.length}):`);
for (const k of missing) console.log(`\t'${k.replace(/'/g, "\\'")}':`);
}
if (orphaned.length) {
console.log(`\nIn ru.ts but never used as a literal (${orphaned.length}):`);
for (const k of orphaned) console.log(`\t'${k.replace(/'/g, "\\'")}'`);
console.log('(may be dynamic keys — verify before deleting)');
}
if (!missing.length && !orphaned.length) console.log('i18n: OK');
process.exit(missing.length ? 1 : 0);
-107
View File
@@ -1,107 +0,0 @@
import { useEffect } from 'react';
import { appStore, boot } from './lib/app';
import { initRouter } from './lib/router';
import { initShortcuts } from './lib/shortcuts';
import { initMediaSession } from './lib/mediaSession';
import { useStore } from './lib/store';
import { useLanguage, t } from './i18n';
import { HelpIcon, MenuIcon } from './components/icons';
import { Sidebar } from './components/Sidebar';
import { MiniPlayer } from './components/MiniPlayer';
import { DialogHost } from './components/DialogHost';
import { ShortcutsHelp } from './components/ShortcutsHelp';
import { DashboardView } from './views/DashboardView';
import { QueueView } from './views/QueueView';
import { SearchView } from './views/SearchView';
import { LibraryView } from './views/LibraryView';
import { StatsView } from './views/StatsView';
import { ServerView } from './views/ServerView';
import { UpdatesView } from './views/UpdatesView';
import { RpcView } from './views/RpcView';
const HEADS: Record<string, [string, string]> = {
dashboard: ['Dashboard', 'Live playback and TeamSpeak server activity'],
queue: ['Queue', 'Reorder and manage upcoming tracks'],
search: ['Search', 'Find tracks across YouTube and Yandex Music'],
library: ['Library', 'Your favorites and saved playlists'],
stats: ['History & Stats', 'Playback history and server insights'],
server: ['Server & Admin', 'Manage subscribers and broadcast'],
updates: ['Updates', 'Runtime, Core, and plugin release control'],
rpc: ['RPC / API', 'Connect to Echoion programmatically'],
};
export function App() {
const s = useStore(appStore);
useLanguage(); // re-render everything on language switch
useEffect(() => {
boot();
initRouter();
initShortcuts();
initMediaSession();
}, []);
const [title, sub] = HEADS[s.view] || HEADS.dashboard;
return (
<div id="app">
<Sidebar />
{s.sidebarOpen && (
<div
className="drawer-backdrop"
onClick={() => appStore.set({ sidebarOpen: false })}
/>
)}
<main className="main">
<header className="header">
<div className="header-title">
<button
className="icon-btn hamburger"
title={t('Menu')}
aria-label={t('Menu')}
onClick={() =>
appStore.set({ sidebarOpen: !s.sidebarOpen })
}
>
<MenuIcon />
</button>
<div>
<h1>{t(title)}</h1>
<div className="header-sub">{t(sub)}</div>
</div>
</div>
<div className="header-right">
<span className="pill">
<span className="dot dot-green" />
{s.onlineCount}&nbsp;{t('online')}
</span>
<button
className="icon-btn"
title={t('Keyboard shortcuts')}
aria-label={t('Keyboard shortcuts')}
onClick={() =>
appStore.set({ shortcutsOpen: true })
}
>
<HelpIcon />
</button>
</div>
</header>
{s.view === 'dashboard' && <DashboardView />}
{s.view === 'queue' && <QueueView />}
{s.view === 'search' && <SearchView />}
{s.view === 'library' && <LibraryView />}
{s.view === 'stats' && <StatsView />}
{s.view === 'server' && <ServerView />}
{s.view === 'updates' && <UpdatesView />}
{s.view === 'rpc' && <RpcView />}
<MiniPlayer />
</main>
{s.toast && <div className="toast">{s.toast}</div>}
<DialogHost />
<ShortcutsHelp />
</div>
);
}
@@ -1,114 +0,0 @@
import { useState } from 'react';
import { safeCall, toast } from '../lib/app';
import { renderTsMarkup } from '../lib/tsMarkup';
import { Modal } from './Modal';
import { t } from '../i18n';
// Announce composer with a live TS6-markdown/BBCode preview (item 14).
// Replaces the old prompt(). A small toolbar wraps the selection in common
// formatting tags; the preview renders exactly what subscribers will see.
const TOOLBAR: Array<{ label: string; before: string; after: string }> = [
{ label: 'B', before: '**', after: '**' },
{ label: 'I', before: '*', after: '*' },
{ label: 'U', before: '[u]', after: '[/u]' },
{ label: 'S', before: '~~', after: '~~' },
{ label: '</>', before: '`', after: '`' },
{ label: '🔗', before: '[', after: '](https://)' },
{ label: 'H', before: '# ', after: '' },
{ label: '❝', before: '> ', after: '' },
];
export function AnnounceModal({ onClose }: { onClose: () => void }) {
const [text, setText] = useState('');
const [sending, setSending] = useState(false);
let ref: HTMLTextAreaElement | null = null;
const wrap = (before: string, after: string) => {
const el = ref;
if (!el) return;
const start = el.selectionStart;
const end = el.selectionEnd;
const selected = text.slice(start, end);
const next =
text.slice(0, start) + before + selected + after + text.slice(end);
setText(next);
// Restore focus with the caret after the inserted opening tag.
queueMicrotask(() => {
el.focus();
const pos = start + before.length + selected.length;
el.setSelectionRange(pos, pos);
});
};
return (
<Modal
title={t('Compose announcement')}
onClose={onClose}
wide
footer={
<>
<button className="btn btn-ghost" onClick={onClose}>
{t('Cancel')}
</button>
<button
className="btn btn-accent"
disabled={!text.trim() || sending}
onClick={async () => {
setSending(true);
const res = await safeCall<{ message?: string }>(
'Announce',
{ text: text.trim() }
);
setSending(false);
if (res) {
toast(res.message || t('Announcement sent'));
onClose();
}
}}
>
{t('Send announcement')}
</button>
</>
}
>
<div className="announce-toolbar">
{TOOLBAR.map((b) => (
<button
key={b.label}
className="btn btn-ghost"
type="button"
onClick={() => wrap(b.before, b.after)}
>
{b.label}
</button>
))}
</div>
<div className="announce-grid">
<textarea
ref={(el) => {
ref = el;
}}
className="announce-input"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder={t('Announcement to all subscribers:')}
rows={10}
/>
<div className="announce-preview">
<div className="announce-preview-label">
{t('Preview')}
</div>
<div className="ts-markup">
{text.trim() ? (
renderTsMarkup(text)
) : (
<span className="muted">
{t('Nothing to preview yet')}
</span>
)}
</div>
</div>
</div>
</Modal>
);
}
@@ -1,72 +0,0 @@
import { useEffect, useRef, useState } from 'react';
import { avatarColor } from '../lib/format';
// User avatar: tries the TeamSpeak avatar served at /avatar/<uid>, falling
// back to the initial-letter-on-gradient avatar when the image is missing.
// `uid` is the stable TeamSpeak unique id.
//
// The server fetches avatars from TeamSpeak lazily (it must first sync the
// client's avatar hash, then download the file), so the first few requests can
// 404 while that completes. We retry a handful of times with a growing delay,
// bypassing the browser's negative cache with a ?v=N buster, before giving up
// and showing initials.
const RETRY_DELAYS_MS = [2500, 4000, 6000, 9000];
export function Avatar(props: {
name: string;
uid?: string | null;
size?: number;
className?: string;
}) {
const { name, uid, size, className } = props;
const [attempt, setAttempt] = useState(0);
const [failed, setFailed] = useState(false);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
// Reset retry state whenever the target uid changes.
useEffect(() => {
setAttempt(0);
setFailed(false);
return () => {
if (timer.current) clearTimeout(timer.current);
};
}, [uid]);
const style: React.CSSProperties = size
? { width: `${size}px`, height: `${size}px` }
: {};
if (uid && !failed) {
const src =
`/avatar/${encodeURIComponent(uid)}` +
(attempt > 0 ? `?v=${attempt}` : '');
return (
<img
className={'avatar avatar-img' + (className ? ` ${className}` : '')}
style={style}
src={src}
alt={name}
onError={() => {
if (attempt < RETRY_DELAYS_MS.length) {
const delay = RETRY_DELAYS_MS[attempt];
if (timer.current) clearTimeout(timer.current);
timer.current = setTimeout(
() => setAttempt((a) => a + 1),
delay
);
} else {
setFailed(true);
}
}}
/>
);
}
return (
<span
className={'avatar' + (className ? ` ${className}` : '')}
style={{ ...style, background: avatarColor(name || '?') }}
>
{(name || '?').charAt(0).toUpperCase()}
</span>
);
}
@@ -1,82 +0,0 @@
import { useRef, useState } from 'react';
// Pointer-drag on a bar: the fill tracks the pointer while dragging and
// onCommit fires once on release (a plain click is a zero-length drag).
// Port of app.js makeDraggableBar.
//
// When `formatValue` is given, a tooltip bubble follows the pointer on hover
// and drag showing the value at that position (item 14) — e.g. a seek time or
// a volume percentage.
export function Bar(props: {
pct: number; // 0..100, authoritative fill when not dragging
bufferPct?: number; // 0..100, second fill layer behind the progress
slim?: boolean;
className?: string;
onCommit?: (fraction: number) => void;
onDragStart?: () => boolean; // return false to refuse the drag
live?: boolean; // live drag feedback: onCommit also fires on move
formatValue?: (fraction: number) => string; // tooltip text at a fraction
}) {
const el = useRef<HTMLDivElement>(null);
const [dragPct, setDragPct] = useState<number | null>(null);
// Pointer position (0..100) for the tooltip; null when the pointer is away.
const [hoverPct, setHoverPct] = useState<number | null>(null);
const fraction = (e: React.PointerEvent) => {
const r = el.current!.getBoundingClientRect();
return Math.min(1, Math.max(0, (e.clientX - r.left) / r.width));
};
const tipPct = dragPct ?? hoverPct;
const showTip = props.formatValue && tipPct != null;
return (
<div
ref={el}
className={
'bar' +
(props.slim ? ' bar-slim' : '') +
(props.className ? ` ${props.className}` : '')
}
onPointerDown={(e) => {
if (props.onDragStart && !props.onDragStart()) return;
e.currentTarget.setPointerCapture(e.pointerId);
const f = fraction(e);
setDragPct(f * 100);
if (props.live) props.onCommit?.(f);
}}
onPointerMove={(e) => {
const f = fraction(e);
setHoverPct(f * 100);
if (dragPct == null) return;
setDragPct(f * 100);
if (props.live) props.onCommit?.(f);
}}
onPointerLeave={() => setHoverPct(null)}
onPointerUp={(e) => {
if (dragPct == null) return;
setDragPct(null);
if (!props.live) props.onCommit?.(fraction(e));
}}
>
{props.bufferPct != null && (
<div
className="bar-buffer"
style={{ width: `${Math.min(100, props.bufferPct)}%` }}
/>
)}
<div
className="bar-fill"
style={{ width: `${dragPct ?? props.pct}%` }}
/>
{showTip && (
<div
className="bar-tip"
style={{ left: `${tipPct}%` }}
>
{props.formatValue!((tipPct as number) / 100)}
</div>
)}
</div>
);
}
@@ -1,94 +0,0 @@
import { useEffect, useRef, useState } from 'react';
import { Modal } from './Modal';
import { useStore } from '../lib/store';
import { dialogStore, resolveConfirm, resolvePrompt } from '../lib/dialog';
import { t } from '../i18n';
// Renders the active custom dialog (confirm/prompt). Mounted once at the app
// root; see lib/dialog.ts for the confirmDialog/promptDialog helpers.
export function DialogHost() {
const { current } = useStore(dialogStore);
const [text, setText] = useState('');
const inputRef = useRef<HTMLInputElement>(null);
// Seed the prompt field with its initial value and focus it each time a
// new prompt opens.
useEffect(() => {
if (current && current.kind === 'prompt') {
setText(current.initial || '');
// Focus after the modal mounts.
setTimeout(() => inputRef.current?.focus(), 0);
}
}, [current]);
if (!current) return null;
if (current.kind === 'confirm') {
return (
<Modal
title={current.title}
onClose={() => resolveConfirm(false)}
footer={
<>
<button
className="btn btn-ghost"
onClick={() => resolveConfirm(false)}
>
{current.cancelLabel || t('Cancel')}
</button>
<button
className={
'btn ' +
(current.danger ? 'btn-danger' : 'btn-accent')
}
onClick={() => resolveConfirm(true)}
>
{current.confirmLabel || t('Confirm')}
</button>
</>
}
>
<p>{current.message}</p>
</Modal>
);
}
return (
<Modal
title={current.title}
onClose={() => resolvePrompt(null)}
footer={
<>
<button
className="btn btn-ghost"
onClick={() => resolvePrompt(null)}
>
{current.cancelLabel || t('Cancel')}
</button>
<button
className="btn btn-accent"
onClick={() => resolvePrompt(text.trim() || null)}
>
{current.confirmLabel || t('OK')}
</button>
</>
}
>
<form
onSubmit={(e) => {
e.preventDefault();
resolvePrompt(text.trim() || null);
}}
>
{current.message && <p>{current.message}</p>}
<input
ref={inputRef}
value={text}
onChange={(e) => setText(e.target.value)}
placeholder={current.placeholder}
autoComplete="off"
/>
</form>
</Modal>
);
}
@@ -1,108 +0,0 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { appStore, safeCall } from '../lib/app';
import { useStore } from '../lib/store';
import type { LyricsResult } from '../lib/types';
import { t } from '../i18n';
// Lyrics for the current track (via the bot's GetLyrics → lrclib). When the
// provider returns time-synced lines we highlight the active one against the
// shared playback clock (appStore.positionMs) and keep it scrolled into view;
// otherwise we show plain scrollable text. Collapsed by default so we only
// fetch when the listener asks for it.
export function LyricsPanel() {
const s = useStore(appStore);
const [open, setOpen] = useState(false);
const [lyrics, setLyrics] = useState<LyricsResult | null>(null);
const [loading, setLoading] = useState(false);
const activeRef = useRef<HTMLDivElement>(null);
const track = s.current;
// Refetch when the track identity changes (url is stable per track).
const key = track ? track.url || track.title || '' : '';
useEffect(() => {
if (!open || !key) {
return;
}
let cancelled = false;
setLoading(true);
setLyrics(null);
safeCall<LyricsResult>('GetLyrics').then((res) => {
if (!cancelled) {
setLyrics(res);
setLoading(false);
}
});
return () => {
cancelled = true;
};
}, [key, open]);
const synced = lyrics?.synced ?? [];
// Index of the last line whose timestamp has passed.
const activeIdx = useMemo(() => {
if (!synced.length) return -1;
let idx = -1;
for (let i = 0; i < synced.length; i++) {
if (synced[i].ms <= s.positionMs) idx = i;
else break;
}
return idx;
}, [synced, s.positionMs]);
useEffect(() => {
activeRef.current?.scrollIntoView({ block: 'nearest' });
}, [activeIdx]);
return (
<div className="card">
<div className="card-head">
<h3>{t('Lyrics')}</h3>
<button
className="link"
onClick={() => setOpen((v) => !v)}
disabled={!track}
>
{open ? t('Hide') : t('Show')}
</button>
</div>
{open && (
<div className="lyrics-body">
{!track ? (
<div className="lyrics-empty">
{t('Nothing playing')}
</div>
) : loading ? (
<div className="lyrics-empty">{t('Loading…')}</div>
) : !lyrics || !lyrics.found ? (
<div className="lyrics-empty">
{t('No lyrics found')}
</div>
) : synced.length ? (
<div className="lyrics-synced">
{synced.map((line, i) => (
<div
key={i}
ref={i === activeIdx ? activeRef : null}
className={
'lyrics-line' +
(i === activeIdx ? ' active' : '')
}
>
{line.text || '♪'}
</div>
))}
</div>
) : (
<pre className="lyrics-plain">{lyrics.plain}</pre>
)}
{lyrics && lyrics.found && lyrics.source && (
<div className="lyrics-source muted">
{t('Lyrics via')} {lyrics.source}
</div>
)}
</div>
)}
</div>
);
}
@@ -1,68 +0,0 @@
import { appStore, safeCall } from '../lib/app';
import { useStore } from '../lib/store';
import { Bar } from './Bar';
import { coverStyle, fmtMs } from '../lib/format';
import { PauseIcon, PlayIcon, SkipNextIcon } from './icons';
import { t } from '../i18n';
async function togglePlay() {
const st = appStore.get().status || {};
if (st.isPlaying && !st.isPaused) await safeCall('Pause');
else await safeCall('Resume');
}
// Mini player mirrors the current track on views other than Now Playing.
export function MiniPlayer() {
const s = useStore(appStore);
if (s.view === 'dashboard' || !s.current) return null;
const playing = !!(s.status && s.status.isPlaying && !s.status.isPaused);
const canForceSkip = !!(
s.identity &&
(s.identity.isAdmin || s.identity.isDj)
);
const durationMs = s.durationMs || s.current.duration || 0;
const pct =
durationMs > 0 ? Math.min(100, (s.positionMs / durationMs) * 100) : 0;
return (
<div className="miniplayer">
<div
className="mini-cover"
style={{ background: coverStyle(s.current) }}
/>
<div className="mini-info">
<div className="mini-title">{s.current.title}</div>
<div className="mini-artist">{s.current.artist || ''}</div>
</div>
<button
className="ctrl"
title={t('Play/Pause')}
onClick={togglePlay}
>
{playing ? <PauseIcon /> : <PlayIcon />}
</button>
{canForceSkip && (
<button
className="ctrl"
title={t('Force skip')}
onClick={() => safeCall('Skip', { count: 1 })}
>
<SkipNextIcon />
</button>
)}
<Bar
slim
className="mini-bar"
pct={pct}
formatValue={(f) =>
durationMs ? fmtMs(Math.round(f * durationMs)) : ''
}
onDragStart={() => durationMs > 0}
onCommit={(f) =>
safeCall('Seek', {
position: Math.round(f * durationMs),
})
}
/>
</div>
);
}
@@ -1,17 +0,0 @@
import { describe, expect, it } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
import { Modal } from './Modal';
describe('Modal accessibility', () => {
it('labels the dialog and exposes a named close control', () => {
const html = renderToStaticMarkup(
<Modal title="Confirm update" onClose={() => {}}>
<p>Review the candidate.</p>
</Modal>
);
expect(html).toContain('role="dialog"');
expect(html).toContain('aria-modal="true"');
expect(html).toContain('aria-labelledby=');
expect(html).toContain('aria-label="Close"');
});
});
@@ -1,76 +0,0 @@
import { useEffect, useId, useRef, type KeyboardEvent, type ReactNode } from 'react';
import { CloseIcon } from './icons';
import { t } from '../i18n';
export function Modal(props: {
title: string;
onClose: () => void;
children: ReactNode;
footer?: ReactNode;
wide?: boolean;
}) {
const titleId = useId();
const modalRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const previous = document.activeElement as HTMLElement | null;
const focusable = modalRef.current?.querySelector<HTMLElement>(
'button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])'
);
focusable?.focus();
return () => previous?.focus();
}, []);
function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
if (event.key === 'Escape') {
event.preventDefault();
props.onClose();
return;
}
if (event.key !== 'Tab' || !modalRef.current) return;
const focusable = Array.from(
modalRef.current.querySelectorAll<HTMLElement>(
'button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])'
)
);
if (!focusable.length) return;
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
}
return (
<div className="modal-backdrop" onClick={props.onClose}>
<div
ref={modalRef}
className={'modal' + (props.wide ? ' modal-wide' : '')}
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
onKeyDown={onKeyDown}
onClick={(e) => e.stopPropagation()}
>
<div className="modal-head">
<h2 id={titleId}>{props.title}</h2>
<button
className="icon-btn"
aria-label={t('Close')}
onClick={props.onClose}
>
<CloseIcon />
</button>
</div>
<div className="modal-body">{props.children}</div>
{props.footer && (
<div className="modal-foot">{props.footer}</div>
)}
</div>
</div>
);
}
@@ -1,16 +0,0 @@
import { describe, expect, it } from 'vitest';
import { shouldCorrectVideoDrift } from '../lib/nowPlayingVideoSync';
describe('NowPlayingVideo drift correction', () => {
it('never seeks while unstarted, cued, or buffering', () => {
for (const state of [-1, 3, 5]) {
expect(shouldCorrectVideoDrift(state, 0, 30, 10_000)).toBe(false);
}
});
it('waits for cooldown and ignores small playing drift', () => {
expect(shouldCorrectVideoDrift(1, 0, 30, 1000)).toBe(false);
expect(shouldCorrectVideoDrift(1, 28, 30, 10_000)).toBe(false);
expect(shouldCorrectVideoDrift(1, 10, 30, 10_000)).toBe(true);
});
});
@@ -1,133 +0,0 @@
import { useEffect, useRef } from 'react';
import { appStore } from '../lib/app';
import {
loadYouTubeApi,
YOUTUBE_EMBED_HOST,
youtubeEmbedVars,
} from '../lib/youtube';
import { shouldCorrectVideoDrift } from '../lib/nowPlayingVideoSync';
// The muted YouTube video of the current track, shown in Now Playing when the
// user enables it (item 11). The bot's audio is the source of truth, so the
// video is always muted and only follows the server position — it resyncs
// with a hard seek when it drifts past the threshold, and pauses/plays to
// match. Purely a local visual aid; it sends nothing to the server.
const SEEK_LEAD_SECONDS = 0.75;
export function NowPlayingVideo({ videoId }: { videoId: string }) {
const mountRef = useRef<HTMLDivElement>(null);
const playerRef = useRef<YT.Player | null>(null);
const currentVideo = useRef<string>('');
const pendingVideo = useRef(videoId);
const lastSeekAt = useRef(0);
const playIntent = useRef<boolean | null>(null);
useEffect(() => {
let cancelled = false;
loadYouTubeApi().then(() => {
if (cancelled || !mountRef.current) return;
const el = document.createElement('div');
mountRef.current.appendChild(el);
playerRef.current = new YT.Player(el, {
width: '100%',
height: '100%',
videoId,
host: YOUTUBE_EMBED_HOST,
playerVars: youtubeEmbedVars({ mute: 1 }),
events: {
onReady: () => {
const p = playerRef.current;
if (!p) return;
const requested = pendingVideo.current;
const startSeconds = appStore.get().positionMs / 1000;
if (requested !== videoId) {
p.loadVideoById({ videoId: requested, startSeconds });
} else if (startSeconds > 0) {
p.seekTo(startSeconds, true);
}
p.mute();
currentVideo.current = requested;
lastSeekAt.current = performance.now();
playIntent.current = null;
},
},
});
});
return () => {
cancelled = true;
playerRef.current?.destroy();
playerRef.current = null;
if (mountRef.current) mountRef.current.innerHTML = '';
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Load a new video id in place without recreating the player.
useEffect(() => {
pendingVideo.current = videoId;
const p = playerRef.current;
if (!p || !p.loadVideoById || currentVideo.current === videoId) return;
p.loadVideoById({
videoId,
startSeconds: appStore.get().positionMs / 1000,
});
p.mute();
currentVideo.current = videoId;
lastSeekAt.current = performance.now();
playIntent.current = null;
}, [videoId]);
// Follow the server position: resync on drift, match play/pause state.
useEffect(() => {
const id = setInterval(() => {
const p = playerRef.current;
if (!p || !p.getCurrentTime || !p.seekTo) return;
const s = appStore.get();
const targetSec = s.positionMs / 1000;
const playing = !!(
s.status &&
s.status.isPlaying &&
!s.status.isPaused
);
try {
const st = p.getPlayerState();
const now = performance.now();
// Seeking while CUED/BUFFERING repeatedly restarts YouTube's
// buffer. Drift is meaningful only once the playback clock moves.
if (shouldCorrectVideoDrift(
st,
p.getCurrentTime(),
targetSec,
now - lastSeekAt.current
)) {
p.seekTo(targetSec + SEEK_LEAD_SECONDS, true);
lastSeekAt.current = now;
}
if (
playing &&
playIntent.current !== true &&
(st === YT.PlayerState.CUED ||
st === YT.PlayerState.PAUSED ||
st === YT.PlayerState.ENDED)
) {
p.playVideo();
playIntent.current = true;
}
else if (
!playing &&
playIntent.current !== false &&
(st === YT.PlayerState.PLAYING || st === YT.PlayerState.BUFFERING)
) {
p.pauseVideo();
playIntent.current = false;
}
p.mute(); // guard against unmute on state changes
} catch {
/* player not ready yet */
}
}, 1000);
return () => clearInterval(id);
}, []);
return <div className="np-video" ref={mountRef} />;
}
@@ -1,31 +0,0 @@
import type { ReactNode } from 'react';
import { Avatar } from './Avatar';
export function PersonRow(props: {
name: string;
uid?: string | null;
sub?: string;
status?: string;
statusColor?: string;
children?: ReactNode;
}) {
const { name, uid, sub, status, statusColor, children } = props;
return (
<div className="person">
<Avatar name={name} uid={uid} />
<div className="person-main">
<div className="person-name">{name}</div>
{sub && <div className="person-sub">{sub}</div>}
</div>
{status && (
<span
className="person-status"
style={statusColor ? { color: statusColor } : undefined}
>
{status}
</span>
)}
{children}
</div>
);
}
@@ -1,62 +0,0 @@
import { describe, expect, it } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
import { PlayerControls } from './PlayerControls';
const noop = () => {};
function render(over: Partial<Parameters<typeof PlayerControls>[0]> = {}) {
return renderToStaticMarkup(
<PlayerControls
playing={false}
positionMs={30_000}
durationMs={120_000}
canControl
volumePct={50}
onTogglePlay={noop}
onSeekMs={noop}
onSeekBy={noop}
onVolume={noop}
{...over}
/>
);
}
describe('PlayerControls', () => {
it('shows transport, times and volume when controllable', () => {
const html = render();
expect(html).toContain('0:30');
expect(html).toContain('2:00');
expect(html).toContain('Back 10 seconds');
expect(html).toContain('Forward 10 seconds');
expect(html).not.toContain('disabled');
});
it('disables transport when canControl is false', () => {
const html = render({ canControl: false });
// Play/pause + the two ±10s buttons are disabled…
expect(html.match(/disabled/g)?.length).toBe(3);
// …but the volume bar (local) is still rendered.
expect(html).toContain('50%');
});
it('hides seek buttons and shows LIVE for live sources', () => {
const html = render({ live: true });
expect(html).not.toContain('Back 10 seconds');
expect(html).toContain('LIVE');
});
it('renders skip only when onSkip is given', () => {
expect(render()).not.toContain('Play next');
expect(render({ onSkip: noop })).toContain('Play next');
});
it('hides the local row when showLocal is false', () => {
expect(render({ showLocal: false })).not.toContain('Vol');
});
it('renders the unified settings slot in the local row', () => {
expect(render({ settings: <button>Settings gear</button> })).toContain(
'Settings gear'
);
});
});
@@ -1,128 +0,0 @@
import type { ReactNode } from 'react';
import { Bar } from './Bar';
import { fmtMs } from '../lib/format';
import {
ForwardIcon,
FullscreenIcon,
PauseIcon,
PlayIcon,
RewindIcon,
SkipNextIcon,
} from './icons';
import { t } from '../i18n';
// Dashboard playback controls. This component is presentational; authenticated
// RPC callbacks are supplied by the dashboard while visitors receive a
// disabled, read-only transport surface.
export function PlayerControls(props: {
playing: boolean;
positionMs: number;
durationMs: number; // 0 = unknown
live?: boolean; // no seekable timeline (Twitch / generic embeds)
canControl: boolean; // transport disabled when false; volume stays local
bufferedPct?: number; // 0..100 second fill on the seek bar
volumePct: number; // 0..100
volumeLive?: boolean; // apply volume while dragging (local volume)
onTogglePlay: () => void;
onSeekMs: (ms: number) => void;
onSeekBy?: (deltaSec: number) => void; // renders ±10s when present
onVolume: (pct: number) => void;
onSkip?: () => void; // renders next-track button when present
skipDisabled?: boolean;
onFullscreen?: () => void;
settings?: ReactNode;
showLocal?: boolean; // hide the volume/quality row (default shown)
extra?: ReactNode; // view-specific buttons after the seek bar
extraLocal?: ReactNode; // view-specific controls in the volume row
}) {
const { live, durationMs, positionMs, canControl } = props;
const progressPct = live
? 100
: durationMs > 0
? Math.min(100, (positionMs / durationMs) * 100)
: 0;
return (
<div className="player-controls">
<div className="player-control-row">
<button
className="ctrl ctrl-main"
title={t('Play/Pause')}
disabled={!canControl}
onClick={props.onTogglePlay}
>
{props.playing ? <PauseIcon /> : <PlayIcon />}
</button>
{!live && props.onSeekBy && (
<>
<button
className="ctrl"
title={t('Back 10 seconds')}
disabled={!canControl}
onClick={() => props.onSeekBy!(-10)}
>
<RewindIcon />
</button>
<button
className="ctrl"
title={t('Forward 10 seconds')}
disabled={!canControl}
onClick={() => props.onSeekBy!(10)}
>
<ForwardIcon />
</button>
</>
)}
{props.onSkip && (
<button
className="ctrl"
title={t('Play next')}
disabled={!canControl || props.skipDisabled}
onClick={props.onSkip}
>
<SkipNextIcon />
</button>
)}
<span className="mono">{live ? '—' : fmtMs(positionMs)}</span>
<Bar
pct={progressPct}
bufferPct={live ? undefined : props.bufferedPct}
formatValue={(f) =>
live || !durationMs
? t('LIVE')
: fmtMs(Math.round(f * durationMs))
}
onDragStart={() => !live && durationMs > 0}
onCommit={(f) => props.onSeekMs(Math.round(f * durationMs))}
/>
<span className="mono">
{live ? t('LIVE') : fmtMs(durationMs)}
</span>
{props.extra}
</div>
{(props.showLocal ?? true) && (
<div className="player-control-row player-local-row">
<span className="muted">{t('Vol')}</span>
<Bar
slim
live={props.volumeLive}
pct={props.volumePct}
formatValue={(f) => `${Math.round(f * 100)}%`}
onCommit={(f) => props.onVolume(Math.round(f * 100))}
/>
<span className="mono">{Math.round(props.volumePct)}%</span>
{props.settings}
{props.onFullscreen && (
<button
className="ctrl"
title={t('Fullscreen')}
onClick={props.onFullscreen}
>
<FullscreenIcon />
</button>
)}
{props.extraLocal}
</div>
)}
</div>
);
}
@@ -1,34 +0,0 @@
import { appStore } from '../lib/app';
import { useStore } from '../lib/store';
import { SHORTCUTS } from '../lib/shortcuts';
import { t } from '../i18n';
// Cheat-sheet overlay for keyboard shortcuts, toggled with "?".
export function ShortcutsHelp() {
const s = useStore(appStore);
if (!s.shortcutsOpen) return null;
return (
<div
className="modal-backdrop"
onClick={() => appStore.set({ shortcutsOpen: false })}
>
<div className="modal shortcuts-modal" onClick={(e) => e.stopPropagation()}>
<h2>{t('Keyboard shortcuts')}</h2>
<div className="shortcuts-list">
{SHORTCUTS.map((sc) => (
<div key={sc.keys} className="shortcut-row">
<kbd>{sc.keys}</kbd>
<span>{t(sc.label)}</span>
</div>
))}
</div>
<button
className="btn btn-ghost"
onClick={() => appStore.set({ shortcutsOpen: false })}
>
{t('Close')}
</button>
</div>
</div>
);
}
@@ -1,199 +0,0 @@
import { useState, type ReactNode } from 'react';
import {
appStore,
changeLanguage,
connectWithToken,
getStoredToken,
logout,
requestToken,
showView,
type ViewName,
} from '../lib/app';
import { useStore } from '../lib/store';
import { promptDialog } from '../lib/dialog';
import { Avatar } from './Avatar';
import {
CodeIcon,
GearIcon,
HeartIcon,
PlayIcon,
QueueIcon,
SearchIcon,
StatsIcon,
UpdateIcon,
WatchIcon,
} from './icons';
import { t, useLanguage } from '../i18n';
const NAV: Array<{ view: ViewName; icon: ReactNode; label: string }> = [
{ view: 'dashboard', icon: <PlayIcon />, label: 'Dashboard' },
{ view: 'queue', icon: <QueueIcon />, label: 'Queue' },
{ view: 'search', icon: <SearchIcon />, label: 'Search' },
{ view: 'library', icon: <HeartIcon />, label: 'Library' },
{ view: 'stats', icon: <StatsIcon />, label: 'History & Stats' },
{ view: 'server', icon: <GearIcon />, label: 'Server & Admin' },
{ view: 'updates', icon: <UpdateIcon />, label: 'Updates' },
{ view: 'rpc', icon: <CodeIcon />, label: 'RPC / API' },
];
export function Sidebar() {
const s = useStore(appStore);
const language = useLanguage();
const [token, setToken] = useState(getStoredToken() || '');
const isAdmin = !!(s.identity && s.identity.isAdmin);
const playing = !!(
s.status &&
s.status.isPlaying &&
!s.status.isPaused
);
const name = s.identity
? s.identity.nickname || s.identity.uid || t('user')
: '';
return (
<aside className={'sidebar' + (s.sidebarOpen ? ' open' : '')}>
<div className="brand">
<div className="brand-icon">
<svg viewBox="0 0 24 24" width="22" height="22" fill="#fff">
<rect x="4" y="9" width="3.4" height="10" rx="1.6" />
<rect x="10.3" y="4" width="3.4" height="15" rx="1.6" />
<rect x="16.6" y="12" width="3.4" height="7" rx="1.6" />
</svg>
</div>
<div>
<div className="brand-name">Echoion</div>
<div className="brand-sub">{t('MUSIC BOT · TS3')}</div>
</div>
</div>
<nav className="nav">
{NAV.filter(
(item) =>
(item.view !== 'server' && item.view !== 'updates') ||
isAdmin
).map((item) => (
<button
key={item.view}
className={
'nav-item' +
(s.view === item.view ? ' active' : '')
}
aria-current={s.view === item.view ? 'page' : undefined}
onClick={() => showView(item.view)}
>
<span className="nav-ico">{item.icon}</span>
{t(item.label)}
{item.view === 'dashboard' && playing && (
<span className="live-dot" />
)}
{item.view === 'queue' && s.queue.length > 0 && (
<span className="nav-badge">{s.queue.length}</span>
)}
</button>
))}
{s.watchUrl && (
<a
className="nav-item"
href={s.watchUrl}
target="_blank"
rel="noreferrer"
>
<span className="nav-ico">
<WatchIcon />
</span>
{t('Watch Together')}
<span className="nav-external" aria-hidden="true">
↗
</span>
</a>
)}
</nav>
<div className="sidebar-foot">
<div className="conn-row">
<span
className={
'conn-dot' +
(s.connection === 'connected'
? ' on'
: s.connection === 'error'
? ' err'
: '')
}
/>
<span>{t(s.connection)}</span>
<select
className="lang-select"
value={language}
title={t('Language')}
onChange={(e) =>
changeLanguage(e.target.value as 'en' | 'ru')
}
>
<option value="en">EN</option>
<option value="ru">RU</option>
</select>
</div>
{!s.identity ? (
<div>
<input
type="password"
placeholder={t('RPC token')}
autoComplete="off"
value={token}
onChange={(e) => setToken(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
connectWithToken(token);
}
}}
/>
<button
className="btn btn-accent"
onClick={() => connectWithToken(token)}
>
{t('Connect')}
</button>
<button
className="btn btn-ghost"
title={t('Send my token via TeamSpeak PM')}
onClick={async () => {
const nickname = await promptDialog({
title: t('Get token by nickname'),
message: t(
'Your TeamSpeak nickname (must be subscribed):'
),
placeholder: t('Nickname'),
confirmLabel: t('Send'),
});
if (nickname) requestToken(nickname);
}}
>
{t('Get token by nickname…')}
</button>
</div>
) : (
<div className="whoami">
<Avatar name={name} uid={s.identity.uid} />
<span>{name}</span>
{isAdmin && (
<span className="admin-chip">{t('ADMIN')}</span>
)}
{!isAdmin && s.identity.isDj && (
<span className="admin-chip">{t('DJ')}</span>
)}
<button
className="btn btn-ghost"
onClick={() => {
logout();
setToken('');
}}
>
{t('Logout')}
</button>
</div>
)}
</div>
</aside>
);
}
@@ -1,480 +0,0 @@
import { useCallback, useEffect, useState } from 'react';
import { safeCall, toast } from '../lib/app';
import type { RpcMethodName } from '../lib/rpc';
import { confirmDialog, promptDialog } from '../lib/dialog';
import { EmptyRow } from './TrackRow';
import { t, tf } from '../i18n';
import { teamSpeakChannelDisplayName } from '../lib/teamspeak';
interface AdminClient {
id: number;
databaseId: number | null;
uid: string | null;
nickname: string;
channelId: number;
talking: boolean;
muted: boolean;
deafened: boolean;
away: boolean;
groups: number[];
}
interface AdminChannel {
id: number;
name: string;
parentId: number | null;
default: boolean;
password: boolean;
maxClients: number;
currentClients: number;
clients: AdminClient[];
channels: AdminChannel[];
}
interface DirectoryResponse {
server: {
name: string;
connected: boolean;
clientCount: number;
maxClients: number;
};
channels: AdminChannel[];
}
interface Ban {
id: number;
uid: string | null;
nickname: string | null;
reason: string;
createdAt: number;
durationSeconds: number;
}
interface ServerGroup {
id: number;
name: string;
default: boolean;
}
export function TeamSpeakAdmin() {
const [directory, setDirectory] = useState<DirectoryResponse | null>(null);
const [bans, setBans] = useState<Ban[]>([]);
const [groups, setGroups] = useState<ServerGroup[]>([]);
const [loading, setLoading] = useState(false);
const refresh = useCallback(async () => {
setLoading(true);
const [nextDirectory, nextBans, nextGroups] = await Promise.all([
safeCall<DirectoryResponse>('GetTeamSpeakDirectory'),
safeCall<{ bans?: Ban[] }>('GetTeamSpeakBans'),
safeCall<{ groups?: ServerGroup[] }>('GetTeamSpeakServerGroups'),
]);
if (nextDirectory) setDirectory(nextDirectory);
if (nextBans) setBans(nextBans.bans || []);
if (nextGroups) setGroups(nextGroups.groups || []);
setLoading(false);
}, []);
useEffect(() => {
void refresh();
}, [refresh]);
const mutate = useCallback(
async (
method: RpcMethodName,
params: Record<string, unknown>,
message: string
) => {
const result = await safeCall(method, params);
if (!result) return false;
toast(message);
await refresh();
return true;
},
[refresh]
);
async function sendServerMessage() {
const message = await promptDialog({
title: t('Server message'),
message: t('Message sent to every connected TeamSpeak client:'),
confirmLabel: t('Send'),
});
if (message) {
await mutate(
'SendTeamSpeakServerMessage',
{ message },
t('Server message sent')
);
}
}
async function createChannel(parentId = 0) {
const name = await promptDialog({
title: t('Create channel'),
message: t('Channel name:'),
confirmLabel: t('Create'),
});
if (name) {
await mutate(
'CreateTeamSpeakChannel',
{ name, parentId, permanent: true },
t('Channel created')
);
}
}
function ClientRow({ client }: { client: AdminClient }) {
return (
<div className="ts-admin-client">
<div className="ts-admin-client-main">
<span
className={'ts-presence' + (client.talking ? ' talking' : '')}
/>
<strong>{client.nickname}</strong>
<span className="muted">#{client.id}</span>
{client.away && <span className="ts-tag">{t('away')}</span>}
{client.muted && <span className="ts-tag">{t('muted')}</span>}
{client.deafened && <span className="ts-tag">{t('deafened')}</span>}
</div>
<div className="ts-admin-private muted">
<span>UID: {client.uid || '—'}</span>
<span>DB: {client.databaseId || '—'}</span>
<span>{t('Groups')}: {client.groups.join(', ') || '—'}</span>
</div>
<div className="ts-admin-actions">
<button
className="btn btn-ghost"
onClick={async () => {
const message = await promptDialog({
title: tf('Message {0}', client.nickname),
message: t('Private message:'),
confirmLabel: t('Send'),
});
if (message)
await mutate(
'SendTeamSpeakPrivateMessage',
{ clientId: client.id, message },
t('Message sent')
);
}}
>
{t('Message')}
</button>
<button
className="btn btn-ghost"
onClick={async () => {
const channelId = await promptDialog({
title: tf('Move {0}', client.nickname),
message: t('Destination channel ID:'),
confirmLabel: t('Move'),
});
if (channelId && /^\d+$/.test(channelId))
await mutate(
'MoveTeamSpeakClient',
{ clientId: client.id, channelId: Number(channelId) },
t('Client moved')
);
}}
>
{t('Move')}
</button>
{client.databaseId && (
<button
className="btn btn-ghost"
onClick={async () => {
const groupId = await promptDialog({
title: t('Add server group'),
message: groups.length
? groups.map((g) => `${g.id}: ${g.name}`).join('\n')
: t('Server group ID:'),
confirmLabel: t('Add'),
});
if (groupId && /^\d+$/.test(groupId))
await mutate(
'AddTeamSpeakServerGroupMember',
{
groupId: Number(groupId),
clientDatabaseId: client.databaseId,
},
t('Group added')
);
}}
>
{t('Add group')}
</button>
)}
{client.databaseId && client.groups.length > 0 && (
<button
className="btn btn-ghost"
onClick={async () => {
const groupId = await promptDialog({
title: t('Remove server group'),
message: `${t('Current groups')}: ${client.groups.join(', ')}`,
confirmLabel: t('Remove'),
});
if (groupId && /^\d+$/.test(groupId))
await mutate(
'RemoveTeamSpeakServerGroupMember',
{
groupId: Number(groupId),
clientDatabaseId: client.databaseId,
},
t('Group removed')
);
}}
>
{t('Remove group')}
</button>
)}
<button
className="btn btn-danger-ghost"
onClick={async () => {
if (
await confirmDialog({
title: tf('Kick {0}', client.nickname),
message: t('Kick this client from the server?'),
confirmLabel: t('Kick'),
danger: true,
})
)
await mutate(
'KickTeamSpeakClient',
{ clientId: client.id, fromServer: true },
t('Client kicked')
);
}}
>
{t('Kick')}
</button>
<button
className="btn btn-danger-ghost"
onClick={async () => {
const duration = await promptDialog({
title: tf('Ban {0}', client.nickname),
message: t('Duration in seconds (0 = permanent):'),
confirmLabel: t('Continue'),
});
if (!duration || !/^\d+$/.test(duration)) return;
if (
await confirmDialog({
title: tf('Ban {0}', client.nickname),
message: t('Apply this ban now?'),
confirmLabel: t('Ban'),
danger: true,
})
)
await mutate(
'BanTeamSpeakClient',
{
clientId: client.id,
durationSeconds: Number(duration),
},
t('Client banned')
);
}}
>
{t('Ban')}
</button>
</div>
</div>
);
}
function Channel({ channel, depth = 0 }: { channel: AdminChannel; depth?: number }) {
const displayName = teamSpeakChannelDisplayName(channel.name);
return (
<div className="ts-admin-channel" style={{ marginLeft: depth * 16 }}>
<div className="ts-admin-channel-head">
<strong
className={displayName.spacer ? 'ts-admin-spacer' : undefined}
title={channel.name}
>
{displayName.label}
</strong>
<span className="muted">#{channel.id}</span>
<span className="ts-capacity">
{channel.currentClients}/{channel.maxClients || '∞'}
</span>
<button className="btn btn-ghost" onClick={() => createChannel(channel.id)}>
{t('Add child')}
</button>
<button
className="btn btn-ghost"
onClick={async () => {
const name = await promptDialog({
title: t('Rename channel'),
message: channel.name,
confirmLabel: t('Save'),
});
if (name)
await mutate(
'EditTeamSpeakChannel',
{ channelId: channel.id, name },
t('Channel updated')
);
}}
>
{t('Edit')}
</button>
<button
className="btn btn-ghost"
onClick={async () => {
const message = await promptDialog({
title: tf('Message {0}', channel.name),
message: t('Channel message:'),
confirmLabel: t('Send'),
});
if (message)
await mutate(
'SendTeamSpeakChannelMessage',
{ channelId: channel.id, message },
t('Message sent')
);
}}
>
{t('Message')}
</button>
<button
className="btn btn-ghost"
onClick={async () => {
const parentId = await promptDialog({
title: t('Reorder channel'),
message: t('Parent channel ID (0 = root):'),
confirmLabel: t('Continue'),
});
if (parentId === null || !/^\d+$/.test(parentId)) return;
const orderAfterId = await promptDialog({
title: t('Reorder channel'),
message: t('Previous sibling channel ID (0 = first):'),
confirmLabel: t('Move'),
});
if (orderAfterId === null || !/^\d+$/.test(orderAfterId)) return;
await mutate(
'ReorderTeamSpeakChannel',
{
channelId: channel.id,
parentId: Number(parentId),
orderAfterId: Number(orderAfterId),
},
t('Channel reordered')
);
}}
>
{t('Reorder')}
</button>
{!channel.default && (
<button
className="btn btn-danger-ghost"
onClick={async () => {
if (
await confirmDialog({
title: t('Delete channel'),
message: tf('Delete {0} and its contents?', channel.name),
confirmLabel: t('Delete'),
danger: true,
})
)
await mutate(
'DeleteTeamSpeakChannel',
{ channelId: channel.id, force: true },
t('Channel deleted')
);
}}
>
{t('Delete')}
</button>
)}
</div>
{channel.clients.map((client) => (
<ClientRow key={client.id} client={client} />
))}
{channel.channels.map((child) => (
<Channel key={child.id} channel={child} depth={depth + 1} />
))}
</div>
);
}
return (
<div className="admin-stack">
<div className="card">
<div className="card-head">
<div>
<h2>{directory?.server.name || t('TeamSpeak')}</h2>
<div className="muted">
{directory?.server.connected ? t('Connected') : t('Disconnected')}
{' · '}
{directory?.server.clientCount || 0}/{directory?.server.maxClients || '∞'}
</div>
</div>
<div className="row-gap">
<button className="btn btn-ghost" onClick={sendServerMessage}>
{t('Server message')}
</button>
<button className="btn btn-ghost" onClick={() => createChannel()}>
{t('Create channel')}
</button>
<button className="btn btn-ghost" disabled={loading} onClick={refresh}>
{loading ? t('Loading…') : t('Refresh')}
</button>
</div>
</div>
<div className="ts-admin-tree">
{directory?.channels.length ? (
directory.channels.map((channel) => (
<Channel key={channel.id} channel={channel} />
))
) : (
<EmptyRow text={t('No TeamSpeak topology available')} />
)}
</div>
</div>
<div className="card">
<div className="card-head">
<h2>{t('Bans')}</h2>
<span className="muted">{bans.length}</span>
</div>
<div className="tracklist">
{bans.length ? (
bans.map((ban) => (
<div className="ts-ban-row" key={ban.id}>
<div>
<strong>{ban.nickname || ban.uid || `#${ban.id}`}</strong>
<div className="muted">{ban.reason || t('No reason')}</div>
</div>
<span className="muted">
{ban.durationSeconds ? `${ban.durationSeconds}s` : t('Permanent')}
</span>
<button
className="btn btn-danger-ghost"
onClick={async () => {
if (
await confirmDialog({
title: t('Remove ban'),
message: t('Remove this TeamSpeak ban?'),
confirmLabel: t('Unban'),
danger: true,
})
)
await mutate(
'UnbanTeamSpeakClient',
{ banId: ban.id },
t('Ban removed')
);
}}
>
{t('Unban')}
</button>
</div>
))
) : (
<EmptyRow text={t('No bans')} />
)}
</div>
</div>
</div>
);
}
@@ -1,79 +0,0 @@
import type { ReactNode } from 'react';
import type { Track } from '../lib/types';
import { coverStyle, fmtMs, sourceInfo } from '../lib/format';
import { t } from '../i18n';
export interface TrackAction {
icon: ReactNode;
title: string;
cls?: string;
onClick: () => void;
}
export function TrackRow(props: {
track: Track;
num?: number;
playing?: boolean;
sub?: string;
actions?: Array<TrackAction | null | false>;
rowProps?: React.HTMLAttributes<HTMLDivElement> & { draggable?: boolean };
children?: ReactNode;
}) {
const { track, num, playing, sub, rowProps, children } = props;
const actions = (props.actions || []).filter(Boolean) as TrackAction[];
const src = sourceInfo(track);
return (
<div
{...rowProps}
className={
'track-row' +
(playing ? ' playing' : '') +
(rowProps?.className ? ` ${rowProps.className}` : '')
}
>
{num != null && (
<span className="track-num">
{String(num).padStart(2, '0')}
</span>
)}
<div
className="track-cover"
style={{ background: coverStyle(track) }}
/>
<div className="track-main">
<div className="track-title">
{track.title || t('(untitled)')}
</div>
<div className="track-sub">
{[track.artist, sub].filter(Boolean).join(' · ')}
</div>
</div>
{src && <span className={src.cls}>{src.label}</span>}
{!!track.duration && (
<span className="track-dur">{fmtMs(track.duration)}</span>
)}
{actions.length > 0 && (
<div className="track-actions">
{actions.map((a, i) => (
<button
key={i}
className={'icon-btn' + (a.cls ? ` ${a.cls}` : '')}
title={a.title}
onClick={(e) => {
e.stopPropagation();
a.onClick();
}}
>
{a.icon}
</button>
))}
</div>
)}
{children}
</div>
);
}
export function EmptyRow({ text }: { text: string }) {
return <div className="empty">{text}</div>;
}
@@ -1,99 +0,0 @@
import type { SVGProps } from 'react';
// Inline SVG icon set replacing the raw unicode glyphs (✕ ▶ ⏸ ⚙ …), which
// rendered inconsistently across platforms and fonts. Sized in em so icons
// scale with the button font-size; color follows currentColor.
type IconProps = SVGProps<SVGSVGElement>;
function makeIcon(d: string) {
return function Icon(props: IconProps) {
return (
<svg
viewBox="0 0 24 24"
width="1em"
height="1em"
fill="currentColor"
aria-hidden="true"
focusable="false"
{...props}
>
<path d={d} />
</svg>
);
};
}
export const PlayIcon = makeIcon('M8 5v14l11-7z');
export const PauseIcon = makeIcon('M6 19h4V5H6v14zm8-14v14h4V5h-4z');
export const SkipNextIcon = makeIcon('M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z');
export const SkipPrevIcon = makeIcon('M6 6h2v12H6zm3.5 6l8.5 6V6l-8.5 6z');
export const RewindIcon = makeIcon(
'M11 18V6l-8.5 6 8.5 6zm.5-6l8.5 6V6l-8.5 6z'
);
export const ForwardIcon = makeIcon(
'M4 18l8.5-6L4 6v12zm9-12v12l8.5-6L13 6z'
);
export const ShuffleIcon = makeIcon(
'M10.59 9.17L5.41 4 4 5.41l5.17 5.17 1.42-1.41zM14.5 4l2.04 2.04L4 18.59 5.41 20 17.96 7.46 20 9.5V4h-5.5zm.33 9.41l-1.41 1.41 3.13 3.13L14.5 20H20v-5.5l-2.04 2.04-3.13-3.13z'
);
export const RepeatIcon = makeIcon(
'M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z'
);
export const HeartIcon = makeIcon(
'M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z'
);
export const CloseIcon = makeIcon(
'M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z'
);
export const SearchIcon = makeIcon(
'M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z'
);
export const QueueIcon = makeIcon(
'M15 6H3v2h12V6zm0 4H3v2h12v-2zM3 16h8v-2H3v2zm14-10v8.18c-.31-.11-.65-.18-1-.18-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3V8h3V6h-5z'
);
export const StatsIcon = makeIcon(
'M5 9.2h3V19H5V9.2zM10.6 5h2.8v14h-2.8V5zm5.6 8H19v6h-2.8v-6z'
);
export const WatchIcon = makeIcon(
'M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H4V6h16v12zM9.5 8.5l7 3.5-7 3.5v-7z'
);
export const RoomsIcon = makeIcon(
'M4 4h6v6H4V4zm10 0h6v6h-6V4zM4 14h6v6H4v-6zm10 0h6v6h-6v-6z'
);
export const GearIcon = makeIcon(
'M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z'
);
export const UpdateIcon = makeIcon(
'M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.96-.69 2.8l1.46 1.46A7.93 7.93 0 0020 12c0-4.42-3.58-8-8-8zm-5.31 5.2L5.23 7.74A7.93 7.93 0 004 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3c-3.31 0-6-2.69-6-6 0-1.01.25-1.96.69-2.8z'
);
export const CodeIcon = makeIcon(
'M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z'
);
export const FullscreenIcon = makeIcon(
'M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z'
);
export const PowerIcon = makeIcon(
'M13 3h-2v10h2V3zm4.83 2.17l-1.42 1.42C17.99 7.86 19 9.81 19 12c0 3.87-3.13 7-7 7s-7-3.13-7-7c0-2.19 1.01-4.14 2.58-5.42L6.17 5.17C4.23 6.82 3 9.26 3 12c0 4.97 4.03 9 9 9s9-4.03 9-9c0-2.74-1.23-5.18-3.17-6.83z'
);
export const CrownIcon = makeIcon(
'M5 16L3 6l5.5 4L12 4l3.5 6L21 6l-2 10H5zm14 3c0 .55-.45 1-1 1H6c-.55 0-1-.45-1-1v-1h14v1z'
);
export const RefreshIcon = makeIcon(
'M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z'
);
export const PlusIcon = makeIcon('M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z');
export const ArrowUpIcon = makeIcon('M4 12l1.41 1.41L11 7.83V20h2V7.83l5.59 5.58L20 12l-8-8-8 8z');
export const ArrowDownIcon = makeIcon('M20 12l-1.41-1.41L13 16.17V4h-2v12.17l-5.59-5.58L4 12l8 8 8-8z');
export const VolumeIcon = makeIcon(
'M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z'
);
export const VolumeMuteIcon = makeIcon(
'M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z'
);
export const HelpIcon = makeIcon(
'M11 18h2v-2h-2v2zm1-16C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4z'
);
export const MenuIcon = makeIcon('M3 6h18v2H3V6zm0 5h18v2H3v-2zm0 5h18v2H3v-2z');
export const ExternalLinkIcon = makeIcon(
'M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z'
);
-58
View File
@@ -1,58 +0,0 @@
// Web UI localization, mirroring the bot's approach (EchoionCore i18n):
// English source strings are the keys; a missing entry falls back to the
// English original. Language resolution order matches the bot's
// CommandManager::resolveLanguage: the authenticated user's server-side
// preference (kv "lang:<uid>", shared with !lang) → local override →
// browser language → English.
import { Store, useStore } from '../lib/store';
import { ru } from './ru';
export type Language = 'en' | 'ru';
const LS_KEY = 'echoion.lang';
function initialLanguage(): Language {
// Not a browser (node test runner): no stored preference, use English.
if (typeof localStorage === 'undefined') return 'en';
const stored = localStorage.getItem(LS_KEY);
if (stored === 'en' || stored === 'ru') return stored;
return (navigator.language || '').toLowerCase().startsWith('ru')
? 'ru'
: 'en';
}
export const languageStore = new Store<{ language: Language }>({
language: initialLanguage(),
});
export function getLanguage(): Language {
return languageStore.get().language;
}
// `persist` distinguishes a user choice (saved locally, pushed to the
// server by the caller) from applying the server-side preference.
export function setLanguage(language: Language, persist = true) {
if (persist) localStorage.setItem(LS_KEY, language);
languageStore.set({ language });
document.documentElement.lang = language;
}
export function t(english: string): string {
if (getLanguage() === 'ru') return ru[english] ?? english;
return english;
}
// Translate a template, then substitute {0}, {1}, … arguments.
export function tf(english: string, ...args: Array<string | number>): string {
const template = t(english);
return template.replace(/\{(\d+)\}/g, (m, i) => {
const v = args[Number(i)];
return v === undefined ? m : String(v);
});
}
// Components subscribe so a language switch re-renders everything.
export function useLanguage(): Language {
return useStore(languageStore).language;
}
-455
View File
@@ -1,455 +0,0 @@
// Russian catalog for the web UI. Same philosophy as the bot's compiled-in
// RussianCatalog.inc: English source strings are the keys; a missing entry
// falls back to English. Placeholders are {0}, {1}, … (see tf()).
export const ru: Record<string, string> = {
// Sidebar / navigation
'Dashboard': 'Панель',
'Queue': 'Очередь',
'Search': 'Поиск',
'Library': 'Библиотека',
'History & Stats': 'История и статистика',
'Watch Together': 'Совместный просмотр',
'Server & Admin': 'Сервер и админ',
'Updates': 'Обновления',
'RPC / API': 'RPC / API',
'MUSIC BOT · TS3': 'МУЗЫКАЛЬНЫЙ БОТ · TS3',
'Connect': 'Подключиться',
'Get token by nickname…': 'Получить токен по нику…',
'Send my token via TeamSpeak PM': 'Прислать мой токен личным сообщением в TeamSpeak',
'RPC token': 'RPC-токен',
'Logout': 'Выйти',
'ADMIN': 'АДМИН',
'DJ': 'DJ',
'connected': 'подключено',
'disconnected': 'отключено',
'error': 'ошибка',
// View headers
'Live playback and TeamSpeak server activity':
'Текущее воспроизведение и активность сервера TeamSpeak',
'Reorder and manage upcoming tracks': 'Управляйте порядком предстоящих треков',
'Find tracks across YouTube and Yandex Music': 'Ищите треки на YouTube и в Яндекс Музыке',
'Your favorites and saved playlists': 'Ваше избранное и сохранённые плейлисты',
'Playback history and server insights': 'История воспроизведения и статистика сервера',
'Manage subscribers and broadcast': 'Управление подписчиками и объявления',
'Runtime, Core, and plugin release control':
'Управление выпусками среды, ядра и плагинов',
'Connect to Echoion programmatically': 'Подключение к Echoion из кода',
// Updates
'Runtime bundle': 'Среда выполнения',
'Core': 'Ядро',
'Plugins': 'Плагины',
'default source': 'источник по умолчанию',
'stable': 'стабильный',
'Idle': 'Ожидание',
'Installed': 'Установлено',
'Available': 'Доступно',
'Up to date': 'Актуальная версия',
'Candidate attributes': 'Свойства кандидата',
'Unsigned': 'Без подписи',
'Signed': 'Подписано',
'Downgrade': 'Понижение версии',
'Incompatible': 'Несовместимо',
'Restart required': 'Нужен перезапуск',
'Apply {0}': 'Применить {0}',
'No update': 'Нет обновления',
'Rollback to {0}': 'Откатить до {0}',
'No rollback': 'Откат недоступен',
'Enabled': 'Включено',
'Source': 'Источник',
'Channel': 'Канал',
'{0} source': 'Источник: {0}',
'{0} channel': 'Канал: {0}',
'Auto-apply': 'Применять автоматически',
'Build default': 'Встроенное значение',
'Feed URL': 'URL ленты',
'Empty uses the release build default':
'Пустое поле использует адрес из сборки выпуска',
'Bearer token environment variable': 'Переменная окружения с Bearer-токеном',
'Secret is present in the service environment':
'Секрет присутствует в окружении службы',
'Secret is missing from the service environment':
'Секрет отсутствует в окружении службы',
'Secret presence was not reported': 'Наличие секрета не сообщено службой',
'No bearer token configured': 'Bearer-токен не настроен',
'Permit manual unsigned staging':
'Разрешить ручную подготовку обновлений без подписи',
'Ed25519 trust keys': 'Доверенные ключи Ed25519',
'Only public verification keys belong here.':
'Здесь должны находиться только открытые ключи проверки.',
'Add key': 'Добавить ключ',
'Key ID': 'ID ключа',
'Public key': 'Открытый ключ',
'Remove key {0}': 'Удалить ключ {0}',
'No custom keys; the build-injected keyring is used when available.':
'Пользовательских ключей нет; используется встроенное в сборку хранилище ключей.',
'Remove source': 'Удалить источник',
'Managed': 'Управляемый',
'Unmanaged': 'Неуправляемый',
'Apply': 'Применить',
'Rollback': 'Откатить',
'Never': 'Никогда',
'Automatic updates armed': 'Автоматические обновления активны',
'Automatic updates paused': 'Автоматические обновления приостановлены',
'Last check: {0}': 'Последняя проверка: {0}',
'Next: {0}': 'Следующая: {0}',
'Check now': 'Проверить сейчас',
'Checking…': 'Проверка…',
'Loading update state…': 'Загрузка состояния обновлений…',
'Installed plugins': 'Установленные плагины',
'Only managed plugins participate in update activation.':
'В активации обновлений участвуют только управляемые плагины.',
'managed': 'управляемых',
'No installed plugins reported': 'Установленные плагины не обнаружены',
'Update history': 'История обновлений',
'Checks, staging, activation, and rollback outcomes':
'Результаты проверок, подготовки, активации и откатов',
'When': 'Когда',
'Target': 'Цель',
'Action': 'Действие',
'Result': 'Результат',
'Recorded': 'Записано',
'No update history yet': 'История обновлений пока пуста',
'POLICY DECK': 'ПАНЕЛЬ ПОЛИТИКИ',
'Automation and trust': 'Автоматизация и доверие',
'Configure timing, independent channels, feeds, and public trust roots.':
'Настройте расписание, независимые каналы, ленты и открытые корни доверия.',
'Discard changes': 'Отменить изменения',
'Save policy': 'Сохранить политику',
'Saving…': 'Сохранение…',
'Enable the update scheduler': 'Включить планировщик обновлений',
'Check interval': 'Интервал проверки',
'Schedule jitter': 'Разброс расписания',
'Maintenance start (UTC)': 'Начало обслуживания (UTC)',
'Maintenance duration': 'Длительность обслуживания',
'Maximum runtime deferral': 'Максимальная отсрочка среды',
'Previous healthy versions retained': 'Хранимые предыдущие исправные версии',
'Component channels': 'Каналы компонентов',
'Selections remain independent; incompatible cohorts stay staged.':
'Выбор остаётся независимым; несовместимые наборы остаются подготовленными.',
'Never modify loose local plugin files':
'Никогда не изменять отдельные локальные файлы плагинов',
'Plugin channel overrides': 'Переопределения каналов плагинов',
'Pin individual managed plugins to another source or channel.':
'Назначьте отдельным управляемым плагинам другой источник или канал.',
'Add override': 'Добавить переопределение',
'No plugin overrides': 'Переопределений плагинов нет',
'Sources and trust roots': 'Источники и корни доверия',
'Secret values stay in the service environment and are never returned here.':
'Значения секретов остаются в окружении службы и никогда не возвращаются сюда.',
'Add source': 'Добавить источник',
'Confirm unsigned update': 'Подтвердите обновление без подписи',
'This artifact has no trusted signature. Type {0} to authorize this exact candidate.':
'У этого артефакта нет доверенной подписи. Введите {0}, чтобы разрешить именно этот кандидат.',
'Authorize unsigned candidate': 'Разрешить кандидат без подписи',
'Confirm downgrade': 'Подтвердите понижение версии',
'A downgrade may make saved state incompatible. Type DOWNGRADE to continue.':
'Понижение версии может сделать сохранённое состояние несовместимым. Введите DOWNGRADE для продолжения.',
'Continue with downgrade': 'Продолжить понижение версии',
'Restart Echoion': 'Перезапустить Echoion',
'Applying this update restarts Echoion after it becomes idle. Continue?':
'После перехода в режим ожидания Echoion будет перезапущен для применения обновления. Продолжить?',
'Apply and restart': 'Применить и перезапустить',
'{0} update queued': 'Обновление {0} поставлено в очередь',
'Confirm rollback': 'Подтвердите откат',
'Roll back {0} to {1}?': 'Откатить {0} до {1}?',
'Rollback queued': 'Откат поставлен в очередь',
'Enable unsigned update policy': 'Разрешить политику обновлений без подписи',
'Unsigned staging will be permitted for: {0}. Type ENABLE UNSIGNED to save this policy.':
'Подготовка без подписи будет разрешена для: {0}. Введите ENABLE UNSIGNED, чтобы сохранить политику.',
'Save unsafe policy': 'Сохранить небезопасную политику',
'Update policy saved': 'Политика обновлений сохранена',
'Add update source': 'Добавить источник обновлений',
'Use a short ID made from letters, numbers, dots, dashes, or underscores.':
'Используйте короткий ID из букв, цифр, точек, дефисов или подчёркиваний.',
'Invalid source ID': 'Недопустимый ID источника',
'That source already exists': 'Такой источник уже существует',
'Move every component off this source before removing it':
'Перед удалением переведите все компоненты на другой источник',
'Remove update source': 'Удалить источник обновлений',
'Remove source {0} and its public keys?':
'Удалить источник {0} и его открытые ключи?',
'Add plugin channel override': 'Добавить переопределение канала плагина',
'Enter the exact managed plugin ID.': 'Введите точный ID управляемого плагина.',
'That plugin override already exists':
'Переопределение для этого плагина уже существует',
'Update check completed': 'Проверка обновлений завершена',
'Update policy, trust keys, and activation controls are restricted to administrators.':
'Политика обновлений, доверенные ключи и активация доступны только администраторам.',
// Now playing
'Nothing playing': 'Ничего не играет',
'Up Next': 'Далее',
'Open queue →': 'Открыть очередь →',
'Listening now': 'Сейчас слушают',
'Queue is empty': 'Очередь пуста',
'Vol': 'Гром.',
'Radio': 'Радио',
'Vote skip': 'Голос за пропуск',
'Vote skip {0}/{1}': 'Пропуск {0}/{1}',
'Shuffle': 'Перемешать',
'Restart track': 'Сначала',
'Play/Pause': 'Играть/Пауза',
'Repeat': 'Повтор',
'Favorite': 'В избранное',
'Vote to skip': 'Голосовать за пропуск',
'Force skip': 'Принудительный пропуск',
'Radio mode is admin-only — ask an admin or use !autoplay':
'Режим радио доступен только админам — попросите админа или используйте !autoplay',
'Radio mode on': 'Режим радио включён',
'Radio mode off': 'Режим радио выключен',
'Vote passed — track skipped': 'Голосование прошло — трек пропущен',
'Added to favorites': 'Добавлено в избранное',
'Removed from favorites': 'Удалено из избранного',
'Playing now': 'Играет сейчас',
'Lyrics': 'Текст песни',
'Show': 'Показать',
'Hide': 'Скрыть',
'Loading…': 'Загрузка…',
'No lyrics found': 'Текст не найден',
'Lyrics via': 'Текст из',
// Queue view
'Queue is empty — add something from Search': 'Очередь пуста — добавьте что-нибудь из Поиска',
'Shuffle queue': 'Перемешать очередь',
'Clear': 'Очистить',
'Clear the whole queue?': 'Очистить всю очередь?',
'Queue cleared': 'Очередь очищена',
'Play now': 'Играть сейчас',
'Remove': 'Удалить',
'{0} tracks': '{0} треков',
// Search
'Search YouTube and Yandex Music… or paste a URL': 'Ищите на YouTube и в Яндекс Музыке… или вставьте ссылку',
'All': 'Все',
'No results yet — search for something': 'Пока нет результатов — поищите что-нибудь',
'Searching “{0}”…': 'Ищем «{0}»…',
'Add to queue': 'Добавить в очередь',
'Added “{0}” to queue': '«{0}» добавлен в очередь',
'Save to favorites': 'Сохранить в избранное',
'Saved to favorites': 'Сохранено в избранное',
// Library
'Your favorites': 'Ваше избранное',
'Playlists': 'Плейлисты',
'Save queue as playlist': 'Сохранить очередь как плейлист',
'Authenticate to use favorites': 'Войдите, чтобы пользоваться избранным',
'No favorites yet — ♥ a track anywhere': 'Пока нет избранного — нажмите ♥ на любом треке',
'No playlists saved yet': 'Плейлистов пока нет',
'Playlist name (saves the current queue):': 'Название плейлиста (сохранит текущую очередь):',
'Playlist “{0}” saved': 'Плейлист «{0}» сохранён',
'Loading playlist “{0}”…': 'Загружаем плейлист «{0}»…',
'Saved from web UI': 'Сохранено из веб-интерфейса',
'Delete': 'Удалить',
'Delete playlist': 'Удалить плейлист',
'Delete playlist “{0}”? This cannot be undone.':
'Удалить плейлист «{0}»? Это нельзя отменить.',
'Playlist “{0}” deleted': 'Плейлист «{0}» удалён',
'Close': 'Закрыть',
'This playlist is empty': 'Плейлист пуст',
// Stats
'Recently played': 'Недавно игравшие',
'Top requesters': 'Топ заказчиков',
'Source split': 'Источники',
'Nothing played yet': 'Пока ничего не игралось',
'No requests logged yet': 'Запросов пока нет',
'Queue again': 'Заказать снова',
'Tracks played today': 'Треков за сегодня',
'Listening hours': 'Часов прослушивания',
'Queue additions': 'Добавлений в очередь',
'Skips': 'Пропусков',
'{0} all-time': '{0} за всё время',
'today': 'сегодня',
'{0}% skip rate': '{0}% пропусков',
'{0} requests': '{0} запросов',
// Shared playback and action labels
'Load': 'Загрузить',
'Play next': 'Следующее',
'LIVE': 'ЭФИР',
'Send': 'Отправить',
'Fullscreen': 'Во весь экран',
// Server & admin
'Administration': 'Администрирование',
'Administrator authentication required': 'Требуется вход администратора',
'Sign in with an account in a configured TeamSpeak admin group.':
'Войдите под учётной записью, входящей в настроенную группу администраторов TeamSpeak.',
'TeamSpeak': 'TeamSpeak',
'Echoion service': 'Служба Echoion',
'Bot messaging and runtime operations':
'Сообщения бота и управление службой',
'Subscribers': 'Подписчики',
'Emojis': 'Эмодзи',
'Audit history': 'Журнал действий',
'Room emojis moved to VoidWatch and are managed from its administration page.':
'Эмодзи комнат перенесены в VoidWatch и управляются на его странице администрирования.',
'Open VoidWatch admin ↗': 'Открыть панель VoidWatch ↗',
'Announce…': 'Объявление…',
'Reload config': 'Перезагрузить конфиг',
'Restart web UI': 'Перезапустить веб-интерфейс',
'Unsub all': 'Отписать всех',
'No subscribers': 'Нет подписчиков',
'Nobody online right now': 'Сейчас никого нет в сети',
'Online': 'В сети',
'Offline': 'Не в сети',
'Unsub': 'Отписать',
'Unsubscribe {0}?': 'Отписать {0}?',
'Announcement to all subscribers:': 'Объявление всем подписчикам:',
'Announcement sent': 'Объявление отправлено',
'Configuration reloaded': 'Конфигурация перезагружена',
'Restart the web interface? Everyone disconnects briefly.':
'Перезапустить веб-интерфейс? Все ненадолго отключатся.',
'Web interface restarting — this page will reconnect':
'Веб-интерфейс перезапускается — страница переподключится',
'Remove ALL subscriptions? This cannot be undone.':
'Удалить ВСЕ подписки? Это нельзя отменить.',
'All subscriptions removed': 'Все подписки удалены',
'Listening': 'Слушает',
'Refresh': 'Обновить',
'No audit entries yet': 'Записей аудита пока нет',
'client #{0}': 'клиент №{0}',
// Public TeamSpeak directory
'TeamSpeak server': 'Сервер TeamSpeak',
'Complete channel directory': 'Полное дерево каналов',
'Connected': 'Подключено',
'Disconnected': 'Отключено',
'No channels available': 'Нет доступных каналов',
'Password protected': 'Защищён паролем',
'Talking': 'Говорит',
'Away': 'Отошёл',
'Muted': 'Микрофон выключен',
'Deafened': 'Звук выключен',
'clients': 'клиентов',
'channels': 'каналов',
'capacity': 'вместимость',
'online': 'в сети',
'default': 'по умолчанию',
'locked': 'закрыт',
'away': 'отошёл',
'muted': 'микрофон выкл.',
'deafened': 'звук выкл.',
// TeamSpeak administration
'No TeamSpeak topology available': 'Дерево TeamSpeak недоступно',
'Message': 'Сообщение',
'Message {0}': 'Сообщение для {0}',
'Private message:': 'Личное сообщение:',
'Channel message:': 'Сообщение в канал:',
'Message sent': 'Сообщение отправлено',
'Server message': 'Сообщение серверу',
'Message sent to every connected TeamSpeak client:':
'Сообщение всем подключённым клиентам TeamSpeak:',
'Server message sent': 'Сообщение серверу отправлено',
'Move': 'Переместить',
'Move {0}': 'Переместить {0}',
'Destination channel ID:': 'ID целевого канала:',
'Client moved': 'Клиент перемещён',
'Kick': 'Выгнать',
'Kick {0}': 'Выгнать {0}',
'Kick this client from the server?': 'Выгнать этого клиента с сервера?',
'Client kicked': 'Клиент выгнан',
'Ban': 'Заблокировать',
'Ban {0}': 'Заблокировать {0}',
'Duration in seconds (0 = permanent):':
'Срок в секундах (0 = бессрочно):',
'Apply this ban now?': 'Заблокировать этого клиента сейчас?',
'Client banned': 'Клиент заблокирован',
'Bans': 'Блокировки',
'No bans': 'Блокировок нет',
'No reason': 'Без причины',
'Permanent': 'Бессрочно',
'Remove ban': 'Снять блокировку',
'Remove this TeamSpeak ban?': 'Снять эту блокировку TeamSpeak?',
'Unban': 'Разблокировать',
'Ban removed': 'Блокировка снята',
'Groups': 'Группы',
'Current groups': 'Текущие группы',
'Server group ID:': 'ID серверной группы:',
'Add server group': 'Добавление в серверную группу',
'Add group': 'Добавить в группу',
'Group added': 'Клиент добавлен в группу',
'Remove server group': 'Удаление из серверной группы',
'Remove group': 'Удалить из группы',
'Group removed': 'Клиент удалён из группы',
'Create channel': 'Создать канал',
'Channel name:': 'Название канала:',
'Create': 'Создать',
'Channel created': 'Канал создан',
'Add child': 'Добавить подканал',
'Rename channel': 'Переименовать канал',
'Edit': 'Изменить',
'Channel updated': 'Канал обновлён',
'Reorder': 'Переместить',
'Reorder channel': 'Переместить канал',
'Parent channel ID (0 = root):': 'ID родительского канала (0 = корень):',
'Previous sibling channel ID (0 = first):':
'ID предыдущего канала на этом уровне (0 = первый):',
'Channel reordered': 'Канал перемещён',
'Delete channel': 'Удалить канал',
'Delete {0} and its contents?': 'Удалить {0} вместе с содержимым?',
'Channel deleted': 'Канал удалён',
'Continue': 'Продолжить',
// RPC view
'Connect programmatically': 'Программное подключение',
'Copy snippet': 'Скопировать пример',
'Snippet copied': 'Пример скопирован',
'Copy': 'Копировать',
'{0} copied': '{0} — скопировано',
'(authenticate first)': '(сначала войдите)',
// Auth / connection
'Signed in as {0}': 'Вы вошли как {0}',
'Welcome, {0}!': 'Добро пожаловать, {0}!',
'subscriber': 'подписчик',
'friend': 'друг',
'user': 'пользователь',
'Connection failed': 'Не удалось подключиться',
'Reconnected': 'Переподключено',
'Logged out': 'Вы вышли',
'Your TeamSpeak nickname (must be subscribed):': 'Ваш ник в TeamSpeak (нужна подписка):',
'Token sent via TeamSpeak PM': 'Токен отправлен личным сообщением в TeamSpeak',
'Request failed': 'Запрос не удался',
'Language': 'Язык',
'(untitled)': '(без названия)',
// Main-UI feature additions (items 9, 11, 14, 15, 18)
'Open original link': 'Открыть оригинальную ссылку',
'Watch video': 'Смотреть видео',
'Hide video': 'Скрыть видео',
'Compose announcement': 'Составить объявление',
'Send announcement': 'Отправить объявление',
'Cancel': 'Отмена',
'Preview': 'Предпросмотр',
'Nothing to preview yet': 'Пока нечего показать',
// Keyboard shortcuts
'Keyboard shortcuts': 'Горячие клавиши',
'Play / pause': 'Играть / пауза',
'Seek 5s': 'Перемотка 5с',
'Volume': 'Громкость',
'Skip / vote skip': 'Пропустить / голос за пропуск',
'Focus search': 'Перейти к поиску',
'This help': 'Эта справка',
// Mobile / unified player / cleanup update
'Menu': 'Меню',
'Back 10 seconds': 'Назад на 10 секунд',
'Forward 10 seconds': 'Вперёд на 10 секунд',
'Clear queue': 'Очистить очередь',
'Confirm': 'Подтвердить',
'OK': 'ОК',
'Save': 'Сохранить',
'Restart': 'Перезапустить',
'Remove all': 'Удалить все',
'Unsubscribe': 'Отписаться',
'Get token by nickname': 'Получить токен по нику',
'Nickname': 'Ник',
'Playlist name': 'Название плейлиста',
'Save playlist': 'Сохранить плейлист',
'Add': 'Добавить',
};
-507
View File
@@ -1,507 +0,0 @@
// App-level state + orchestration — the controller half of the old app.js.
// Views render from `appStore`; server push and the refresh helpers below
// mutate it.
import { rpc, type RpcMethodName } from './rpc';
import { Store } from './store';
import { t, tf, setLanguage, getLanguage } from '../i18n';
import type {
Identity,
PublicDashboard,
QueueEntry,
ServerInfo,
Status,
Subscriber,
Track,
} from './types';
export type ViewName =
| 'dashboard'
| 'queue'
| 'search'
| 'library'
| 'stats'
| 'server'
| 'updates'
| 'rpc';
export interface AppState {
view: ViewName;
connection: 'connected' | 'disconnected' | 'error';
identity: Identity | null;
status: Status | null;
current: Track | null;
queue: QueueEntry[];
favorites: Track[];
favUrls: Set<string>;
searchResults: Track[];
searchTab: 'all' | 'youtube' | 'yandex';
positionMs: number;
durationMs: number;
onlineCount: number;
listeners: Subscriber[];
publicDashboard: PublicDashboard | null;
watchUrl: string;
toast: string | null;
// Server-wide switch for the Now Playing video preview (item 11), from
// /config.json; users can still disable it locally.
nowPlayingVideoAllowed: boolean;
// Keyboard-shortcut cheat-sheet overlay (toggled with "?").
shortcutsOpen: boolean;
// Sidebar drawer on small screens (hamburger in the header); ignored by
// CSS on desktop widths where the sidebar is always visible.
sidebarOpen: boolean;
capabilities: {
plugins: boolean;
webExtensions: boolean;
};
}
export const appStore = new Store<AppState>({
view: 'dashboard',
connection: 'disconnected',
identity: null,
status: null,
current: null,
queue: [],
favorites: [],
favUrls: new Set(),
searchResults: [],
searchTab: 'all',
positionMs: 0,
durationMs: 0,
onlineCount: 0,
listeners: [],
publicDashboard: null,
watchUrl: '',
toast: null,
nowPlayingVideoAllowed: true,
shortcutsOpen: false,
sidebarOpen: false,
capabilities: {
plugins: false,
webExtensions: false,
},
});
// ── toast ────────────────────────────────────────────────────────────────────
let toastTimer: ReturnType<typeof setTimeout> | null = null;
export function toast(msg: string) {
appStore.set({ toast: msg });
if (toastTimer) clearTimeout(toastTimer);
toastTimer = setTimeout(() => appStore.set({ toast: null }), 2400);
}
export async function safeCall<T = unknown>(
method: RpcMethodName,
params?: Record<string, unknown>
): Promise<T | null> {
try {
return await rpc.call<T>(method, params);
} catch (e) {
const err = e as { message?: string };
if (err && err.message) toast(err.message);
console.warn(method, 'failed', e);
return null;
}
}
// ── auth ─────────────────────────────────────────────────────────────────────
export function getStoredToken(): string | null {
return localStorage.getItem('echoion.token');
}
async function loadUserPrefs() {
const prefs = await safeCall<{ language?: string }>('GetUserPrefs');
if (prefs && (prefs.language === 'en' || prefs.language === 'ru')) {
// Server-side preference (set here or via !lang) wins over the
// browser default but is not written to the local override.
if (!localStorage.getItem('echoion.lang')) {
setLanguage(prefs.language, false);
}
}
}
export async function changeLanguage(language: 'en' | 'ru') {
setLanguage(language);
if (appStore.get().identity) {
await safeCall('SetUserPrefs', { language });
}
}
export function applyIdentity(auth: Identity | null) {
appStore.set({ identity: auth });
if (auth) {
void loadUserPrefs();
}
}
// Autologin: the bot matches this browser's IP against online subscribers'
// TeamSpeak addresses and hands back the user's persistent token, so people
// on their usual machine never type anything.
export async function tryAutologin(): Promise<boolean> {
try {
const auth = await rpc.call<Identity>('AuthenticateByAddress');
if (auth && auth.token) {
localStorage.setItem('echoion.token', auth.token);
rpc.token = auth.token;
applyIdentity(auth);
toast(tf('Signed in as {0}', auth.nickname || t('subscriber')));
return true;
}
} catch {
/* no address match — the manual auth box stays available */
}
return false;
}
// Restore the authenticated session: use the stored token, and if it's
// missing or rejected (expired/revoked), clear it and fall back to address
// autologin. Never throws — a failure just leaves the user as a guest with the
// auth box available, so callers can always proceed to refresh state.
async function restoreSession(): Promise<void> {
const token = getStoredToken();
if (token) {
try {
applyIdentity((await rpc.authenticate(token)) as Identity);
return;
} catch {
// Stale token — drop it so it doesn't wedge every reconnect.
localStorage.removeItem('echoion.token');
rpc.token = null;
}
}
await tryAutologin();
}
export async function connectWithToken(tokenInput: string) {
const token = tokenInput.trim() || getStoredToken() || '';
try {
if (!rpc.connected) await rpc.connect();
if (token) {
const auth = (await rpc.authenticate(token)) as Identity;
localStorage.setItem('echoion.token', token);
applyIdentity(auth);
await loadCapabilities();
toast(tf('Welcome, {0}!', auth.nickname || t('friend')));
}
refreshAll();
} catch (e) {
const err = e as { message?: string };
toast((err && err.message) || t('Connection failed'));
}
}
export async function requestToken(nickname: string) {
try {
if (!rpc.connected) await rpc.connect();
const res = (await rpc.requestToken(nickname.trim())) as Identity;
toast((res && res.message) || t('Token sent via TeamSpeak PM'));
} catch (e) {
const err = e as { message?: string };
toast((err && err.message) || t('Request failed'));
}
}
export async function logout() {
await safeCall('Logout');
localStorage.removeItem('echoion.token');
rpc.token = null;
applyIdentity(null);
toast(t('Logged out'));
}
// ── view routing ─────────────────────────────────────────────────────────────
export function showView(view: ViewName) {
// Navigation closes the mobile drawer.
appStore.set({ view, sidebarOpen: false });
// Reflect the selection in the URL for back/forward + shareable links.
const target = `#${view}`;
if (location.hash !== target) location.hash = target;
}
// ── refresh orchestration ────────────────────────────────────────────────────
export async function refreshCore() {
if (!rpc.connected) return;
const [status, current, queue, info] = await Promise.all([
safeCall<Status>('GetStatus'),
safeCall<{ track?: Track }>('GetCurrentTrack'),
safeCall<{ queue?: QueueEntry[] }>('GetQueue'),
safeCall<ServerInfo>('GetServerInfo'),
]);
const state = appStore.get();
const next: Partial<AppState> = {
status,
current: (current && current.track) || null,
queue: (queue && queue.queue) || [],
};
if (info && typeof info.onlineSubscribers === 'number') {
next.onlineCount = info.onlineSubscribers;
}
// The nicknames + uids on GetServerInfo feed the "Listening now" card for
// everyone. Admins get a richer list from the server view's loadSubscribers,
// but that only runs once they open that view — so populate here
// unconditionally (previously admins saw an empty card on the Now tab).
if (info) {
const names = info.onlineSubscriberNames || [];
const uids = info.onlineSubscriberUids || [];
next.listeners = names.map((n, i) => ({
uid: uids[i] || n,
nickname: n,
online: true,
}));
}
const track = next.current;
if (track && track.duration && !state.durationMs) {
next.durationMs = track.duration;
}
appStore.set(next);
}
export async function refreshAll() {
await refreshCore();
}
export async function loadFavorites() {
if (!appStore.get().identity) return;
const res = await safeCall<{ tracks?: Track[] }>('GetFavorites');
const favorites = (res && res.tracks) || [];
appStore.set({
favorites,
favUrls: new Set(
favorites.map((tr) => tr.url).filter(Boolean) as string[]
),
});
}
// ── boot ─────────────────────────────────────────────────────────────────────
let booted = false;
let dashboardEtag = '';
export async function refreshPublicDashboard() {
try {
const response = await fetch('/api/public/dashboard', {
headers: dashboardEtag ? { 'If-None-Match': dashboardEtag } : {},
cache: 'no-cache',
});
if (response.status === 304) return;
if (!response.ok) return;
const dashboard = (await response.json()) as PublicDashboard;
dashboardEtag = response.headers.get('ETag') || '';
const state = appStore.get();
const publicTrack = dashboard.playback.track;
const sameTrack =
publicTrack && state.current && publicTrack.id === state.current.id;
const current = publicTrack
? {
...(sameTrack ? state.current! : {}),
...publicTrack,
duration:
publicTrack.durationMs ?? publicTrack.duration ?? 0,
}
: null;
appStore.set({
publicDashboard: dashboard,
current,
status: {
...(state.status || {}),
isPlaying: dashboard.playback.isPlaying,
isPaused: dashboard.playback.isPaused,
volume: dashboard.playback.volume,
},
positionMs: dashboard.playback.positionMs,
durationMs: current?.duration || 0,
onlineCount: dashboard.server.clientCount,
});
} catch {
/* The RPC login remains usable if the public snapshot is unavailable. */
}
}
export function boot() {
if (booted) return;
booted = true;
// Apply the persisted language before anything renders text.
setLanguage(getLanguage(), false);
// Server config: the video preview policy and external VoidWatch link.
fetch('/config.json')
.then((r) => r.json())
.then((cfg) => {
appStore.set({
nowPlayingVideoAllowed: cfg?.nowPlayingVideo !== false,
watchUrl:
typeof cfg?.watchUrl === 'string' ? cfg.watchUrl : '',
});
})
.catch(() => {
/* keep the default (allowed) */
});
rpc.onState = (s) => appStore.set({ connection: s });
void refreshPublicDashboard();
setInterval(() => void refreshPublicDashboard(), 5000);
// After an automatic reconnect, restore the authenticated session from
// the stored token (or autologin) and pull fresh state.
rpc.onReconnected = async () => {
await restoreSession();
await loadCapabilities();
refreshAll();
toast(t('Reconnected'));
};
// Server push: any event nudges a debounced refresh; position updates
// are applied directly so the progress bar stays smooth.
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
rpc.on('*', (event) => {
if (event === 'playback.position') return;
if (refreshTimer) clearTimeout(refreshTimer);
refreshTimer = setTimeout(refreshAll, 150);
});
rpc.on('playback.position', (d) => {
const data = d as { position?: number; duration?: number } | null;
if (!data) return;
appStore.set({
positionMs: data.position || 0,
durationMs: data.duration || 0,
});
});
rpc.on('voteskip.updated', (d) => {
const data = d as { votes?: number; needed?: number } | null;
if (!data) return;
const status = appStore.get().status;
if (status) {
appStore.set({
status: {
...status,
skipVotes: data.votes,
skipVotesNeeded: data.needed,
},
});
}
});
rpc.on('plugins.updated', () => {
if (appStore.get().capabilities.webExtensions) void loadWebExtensions();
});
// Local 1s ticker keeps the progress bar moving between server updates.
setInterval(() => {
const s = appStore.get();
if (
s.status &&
s.status.isPlaying &&
!s.status.isPaused &&
s.durationMs > 0
) {
appStore.set({
positionMs: Math.min(s.durationMs, s.positionMs + 1000),
});
}
}, 1000);
(async () => {
try {
await rpc.connect();
} catch {
/* connection failed — stay on the auth box */
return;
}
// Session restore is independent of the connection: even if auth fails
// we still refresh so guests see live state instead of a blank app.
await restoreSession();
await loadCapabilities();
refreshAll();
})();
}
async function loadCapabilities() {
const capabilities = await safeCall<AppState['capabilities']>(
'GetCapabilities'
);
if (capabilities) {
appStore.set({ capabilities });
if (capabilities.webExtensions) await loadWebExtensions();
}
}
interface PluginWebAsset {
id: string;
javascript: string;
css: string;
}
interface LoadedWebExtension {
signature: string;
cleanup?: () => void;
}
const loadedWebExtensions = new Map<string, LoadedWebExtension>();
function unloadWebExtension(id: string) {
const loaded = loadedWebExtensions.get(id);
if (!loaded) return;
try {
loaded.cleanup?.();
} catch (error) {
console.error(`Echoion plugin web asset ${id} cleanup failed`, error);
}
document
.querySelectorAll(`style[data-echoion-plugin="${CSS.escape(id)}"]`)
.forEach((style) => style.remove());
loadedWebExtensions.delete(id);
}
async function loadWebExtensions() {
const response = await safeCall<{ assets?: PluginWebAsset[] }>(
'GetPluginExtensions'
);
if (!response) return;
const assets = response.assets || [];
const currentIds = new Set(assets.map((asset) => asset.id).filter(Boolean));
for (const id of loadedWebExtensions.keys()) {
if (!currentIds.has(id)) unloadWebExtension(id);
}
for (const asset of assets) {
if (!asset.id) continue;
const signature = `${asset.javascript}\0${asset.css}`;
if (loadedWebExtensions.get(asset.id)?.signature === signature) continue;
unloadWebExtension(asset.id);
let style: HTMLStyleElement | undefined;
if (asset.css) {
style = document.createElement('style');
style.dataset.echoionPlugin = asset.id;
style.textContent = asset.css;
document.head.appendChild(style);
}
try {
const host = {
call: async (plugin: string, method: string, params: unknown = {}) =>
rpc.call('PluginCall', {
plugin,
method,
params: JSON.stringify(params),
}),
store: appStore,
toast,
};
const cleanup = new Function(
'Echoion',
`'use strict';\n${asset.javascript}`
)(host);
loadedWebExtensions.set(asset.id, {
signature,
cleanup: typeof cleanup === 'function' ? cleanup : undefined,
});
} catch (error) {
style?.remove();
console.error(`Echoion plugin web asset ${asset.id} failed`, error);
}
}
}
@@ -1,15 +0,0 @@
import { describe, expect, it } from 'vitest';
import { auditMethodName } from './auditMethods';
describe('audit RPC method mapping', () => {
it('keeps removed room audit slots and newer methods aligned', () => {
expect(auditMethodName(53)).toBe('Reserved53');
expect(auditMethodName(66)).toBe('Reserved66');
expect(auditMethodName(67)).toBe('GetCapabilities');
expect(auditMethodName(72)).toBe('Reserved72');
expect(auditMethodName(73)).toBe('GetTeamSpeakDirectory');
expect(auditMethodName(88)).toBe('SendTeamSpeakServerMessage');
expect(auditMethodName(89)).toBe('GetUpdateStatus');
expect(auditMethodName(95)).toBe('ConfirmUnsignedUpdate');
});
});
-108
View File
@@ -1,108 +0,0 @@
// Maps the numeric RpcMethod enum value carried by audit-log entries to a
// human name. This mirrors the declaration order of `enum class RpcMethod`
// in EchoionApi/include/echoion/api/rpc/RpcTypes.hpp, which is explicitly
// append-only ("numeric values are server-internal and only need to stay
// self-consistent") — so index == enum value. When you append a method to
// that enum, append it here too.
const RPC_METHOD_BY_INDEX: readonly string[] = [
'Play', // 0
'Pause',
'Resume',
'Stop',
'Skip',
'Seek',
'SetVolume',
'QueueTrack',
'RemoveFromQueue',
'ClearQueue',
'GetQueue', // 10
'MoveInQueue',
'GetCurrentTrack',
'GetTrackInfo',
'SearchTracks',
'LoadPlaylist',
'SavePlaylist',
'GetPlaylists',
'DeletePlaylist',
'GetConfig',
'SetConfig', // 20
'ReloadConfig',
'GetStatus',
'HotReload',
'Shutdown',
'Authenticate',
'Logout',
'GetAuditLog',
'ManageUsers',
'GetServerInfo',
'RequestLoginToken', // 30
'ValidateLoginToken',
'ToggleShuffle',
'ToggleRepeat',
'ShuffleQueue',
'GetPlaylist',
'GetHistory',
'GetStats',
'GetFavorites',
'AddFavorite',
'RemoveFavorite', // 40
'VoteSkip',
'Announce',
'GetAggregateStats',
'AuthenticateByAddress',
'RestartWebInterface',
'ToggleAutoplay',
'GetUserPrefs',
'SetUserPrefs',
'Reserved49',
'Reserved50',
'Reserved51',
'GetLyrics',
'Reserved53',
'Reserved54',
'Reserved55',
'Reserved56',
'Reserved57',
'Reserved58',
'Reserved59',
'Reserved60',
'Reserved61',
'Reserved62',
'Reserved63',
'Reserved64',
'Reserved65',
'Reserved66',
'GetCapabilities',
'GetPluginExtensions',
'PluginCall',
'Reserved70',
'Reserved71',
'Reserved72',
'GetTeamSpeakDirectory',
'MoveTeamSpeakClient',
'KickTeamSpeakClient',
'BanTeamSpeakClient',
'GetTeamSpeakBans',
'UnbanTeamSpeakClient',
'CreateTeamSpeakChannel',
'EditTeamSpeakChannel',
'ReorderTeamSpeakChannel',
'DeleteTeamSpeakChannel',
'GetTeamSpeakServerGroups',
'AddTeamSpeakServerGroupMember',
'RemoveTeamSpeakServerGroupMember',
'SendTeamSpeakPrivateMessage',
'SendTeamSpeakChannelMessage',
'SendTeamSpeakServerMessage',
'GetUpdateStatus', // 89
'GetUpdateConfig',
'SetUpdateConfig',
'CheckForUpdates',
'ApplyUpdate',
'RollbackUpdate',
'ConfirmUnsignedUpdate', // 95
];
export function auditMethodName(method: number): string {
return RPC_METHOD_BY_INDEX[method] ?? `Method #${method}`;
}
-84
View File
@@ -1,84 +0,0 @@
// Imperative custom dialogs (item 10) replacing the browser's native
// confirm()/prompt(), which can't be styled and look out of place. A single
// <DialogHost/> mounted at the app root renders the active request; the
// confirmDialog/promptDialog helpers return a promise that resolves when the
// user answers, so call sites read like `if (await confirmDialog(...))`.
import { Store } from './store';
export interface ConfirmRequest {
kind: 'confirm';
title: string;
message: string;
confirmLabel?: string;
cancelLabel?: string;
danger?: boolean;
resolve: (ok: boolean) => void;
}
export interface PromptRequest {
kind: 'prompt';
title: string;
message?: string;
placeholder?: string;
initial?: string;
confirmLabel?: string;
cancelLabel?: string;
resolve: (value: string | null) => void;
}
export type DialogRequest = ConfirmRequest | PromptRequest;
interface DialogState {
current: DialogRequest | null;
}
export const dialogStore = new Store<DialogState>({ current: null });
// Resolve the active dialog and clear it. Guards against double-resolve (e.g.
// clicking confirm and the backdrop in quick succession).
function settle(value: boolean | string | null) {
const req = dialogStore.get().current;
if (!req) return;
dialogStore.set({ current: null });
if (req.kind === 'confirm') {
req.resolve(value === true);
} else {
req.resolve(typeof value === 'string' ? value : null);
}
}
export function resolveConfirm(ok: boolean) {
settle(ok);
}
export function resolvePrompt(value: string | null) {
settle(value);
}
export function confirmDialog(
opts: Omit<ConfirmRequest, 'kind' | 'resolve'>
): Promise<boolean> {
// A pending dialog is cancelled if a new one opens (shouldn't overlap).
const pending = dialogStore.get().current;
if (pending) {
if (pending.kind === 'confirm') pending.resolve(false);
else pending.resolve(null);
}
return new Promise<boolean>((resolve) => {
dialogStore.set({ current: { kind: 'confirm', ...opts, resolve } });
});
}
export function promptDialog(
opts: Omit<PromptRequest, 'kind' | 'resolve'>
): Promise<string | null> {
const pending = dialogStore.get().current;
if (pending) {
if (pending.kind === 'confirm') pending.resolve(false);
else pending.resolve(null);
}
return new Promise<string | null>((resolve) => {
dialogStore.set({ current: { kind: 'prompt', ...opts, resolve } });
});
}
-64
View File
@@ -1,64 +0,0 @@
// Presentation helpers shared across views — ported from web/app.js.
import type { Track } from './types';
export function fmtMs(ms: number | undefined | null): string {
const s = Math.max(0, Math.floor((ms || 0) / 1000));
const m = Math.floor(s / 60);
return `${m}:${String(s % 60).padStart(2, '0')}`;
}
export function cover(seed: number): string {
const h = (seed * 47) % 360;
const h2 = (h + 40) % 360;
return `linear-gradient(135deg, hsl(${h} 55% 42%), hsl(${h2} 60% 26%))`;
}
export function seedOf(t: Track | null | undefined): number {
const s = (t && (t.id || t.title)) || '?';
let n = 0;
for (let i = 0; i < s.length; i++) n = (n * 31 + s.charCodeAt(i)) & 0xffff;
return n;
}
// Prefer source-provided artwork; otherwise derive the YouTube thumbnail from
// the video id (covers tracks stored before thumbnails were persisted).
export function thumbFor(t: Track | null | undefined): string | null {
if (!t) return null;
if (t.thumbnailUrl) return t.thumbnailUrl;
const m = (t.url || '').match(/(?:v=|youtu\.be\/|\/embed\/)([\w-]{11})/);
if (m) return `https://i.ytimg.com/vi/${m[1]}/mqdefault.jpg`;
if (t.source === 1 && /^[\w-]{11}$/.test(t.id || '')) {
return `https://i.ytimg.com/vi/${t.id}/mqdefault.jpg`;
}
return null;
}
// TrackSource enum: 1 = YouTube, 6 = Yandex (see EchoionApi TrackTypes.hpp).
export function sourceInfo(
t: Track | null | undefined
): { label: string; cls: string } | null {
const url = (t && t.url) || '';
if ((t && t.source === 6) || url.includes('yandex')) {
return { label: 'YANDEX', cls: 'src-badge yandex' };
}
if ((t && t.source === 1) || url.includes('youtu')) {
return { label: 'YOUTUBE', cls: 'src-badge' };
}
return null;
}
export function avatarColor(name: string | undefined | null): string {
let n = 0;
const s = name || '';
for (let i = 0; i < s.length; i++) n = (n * 31 + s.charCodeAt(i)) & 0xffff;
const h = n % 360;
return `linear-gradient(135deg, hsl(${h} 60% 55%), hsl(${(h + 45) % 360} 55% 40%))`;
}
export function coverStyle(t: Track | null | undefined): string {
const thumb = thumbFor(t);
if (thumb) return `url("${thumb}") center/cover`;
if (t) return cover(seedOf(t));
return 'linear-gradient(135deg, #2a1a4a, #0d0d1f)';
}
-31
View File
@@ -1,31 +0,0 @@
// "Open original link" (item 18): a per-row external-link button that opens
// the track's real source page in a new tab. Prefers the canonical original
// URL (the long, expanded source page) over the shortened faumaray.ru link,
// so users land on the real source rather than a redirector. Never the
// CDN/stream URL (the DTO doesn't expose it).
import type { TrackAction } from '../components/TrackRow';
import type { Track } from './types';
import { ExternalLinkIcon } from '../components/icons';
import { t } from '../i18n';
export function originalLinkUrl(track: Track): string | null {
return track.url || track.shortenedUrl || null;
}
export function openOriginal(track: Track) {
const url = originalLinkUrl(track);
if (url) window.open(url, '_blank', 'noopener');
}
// A TrackRow action for the link, or null when the track has no openable URL.
// Rendered as a dedicated icon button (not a whole-row click, which would
// fight drag-and-drop and the other row actions).
export function originalLinkAction(track: Track): TrackAction | null {
if (!originalLinkUrl(track)) return null;
return {
icon: <ExternalLinkIcon />,
title: t('Open original link'),
onClick: () => openOriginal(track),
};
}
@@ -1,85 +0,0 @@
// Bridges playback state to the OS via the Media Session API, so hardware
// media keys and the lockscreen/notification controls (phone especially)
// drive the bot. Metadata + position follow appStore; the action handlers
// map straight onto the RPC calls the UI already uses.
import { appStore, safeCall } from './app';
import { thumbFor } from './format';
function skip() {
const id = appStore.get().identity;
if (id && (id.isAdmin || id.isDj)) safeCall('Skip', { count: 1 });
else safeCall('VoteSkip');
}
export function initMediaSession() {
if (!('mediaSession' in navigator)) return;
const ms = navigator.mediaSession;
ms.setActionHandler('play', () => void safeCall('Resume'));
ms.setActionHandler('pause', () => void safeCall('Pause'));
ms.setActionHandler('previoustrack', () =>
void safeCall('Seek', { position: 0 })
);
ms.setActionHandler('nexttrack', () => skip());
ms.setActionHandler('seekto', (d) => {
if (typeof d.seekTime === 'number') {
safeCall('Seek', { position: Math.round(d.seekTime * 1000) });
}
});
ms.setActionHandler('seekbackward', (d) => {
const by = (d.seekOffset || 10) * 1000;
const s = appStore.get();
safeCall('Seek', { position: Math.max(0, s.positionMs - by) });
});
ms.setActionHandler('seekforward', (d) => {
const by = (d.seekOffset || 10) * 1000;
const s = appStore.get();
const dur = s.durationMs || s.positionMs + by;
safeCall('Seek', { position: Math.min(dur, s.positionMs + by) });
});
let lastKey = '';
appStore.subscribe(() => {
const s = appStore.get();
const track = s.current;
const st = s.status;
ms.playbackState = !track
? 'none'
: st && st.isPlaying && !st.isPaused
? 'playing'
: 'paused';
// Rebuild metadata only when the track changes.
const key = track ? track.url || track.title || '' : '';
if (track && key !== lastKey) {
lastKey = key;
const artwork = thumbFor(track);
ms.metadata = new MediaMetadata({
title: track.title || 'Echoion',
artist: track.artist || '',
album: 'Echoion',
artwork: artwork
? [{ src: artwork, sizes: '512x512', type: 'image/jpeg' }]
: [],
});
} else if (!track) {
lastKey = '';
ms.metadata = null;
}
// Keep the scrubber in sync where supported.
if (typeof ms.setPositionState === 'function' && s.durationMs > 0) {
try {
ms.setPositionState({
duration: s.durationMs / 1000,
position: Math.min(s.positionMs, s.durationMs) / 1000,
playbackRate: 1,
});
} catch {
/* invalid position state (e.g. position > duration) — ignore */
}
}
});
}
@@ -1,15 +0,0 @@
const DRIFT_THRESHOLD_SECONDS = 3;
const SEEK_COOLDOWN_MS = 5000;
export function shouldCorrectVideoDrift(
playerState: number,
currentSeconds: number,
targetSeconds: number,
millisSinceSeek: number
): boolean {
return (
playerState === 1 &&
millisSinceSeek >= SEEK_COOLDOWN_MS &&
Math.abs(currentSeconds - targetSeconds) > DRIFT_THRESHOLD_SECONDS
);
}
@@ -1,16 +0,0 @@
import { describe, expect, it } from 'vitest';
import { viewFromHash } from './router';
describe('dashboard routing', () => {
it('uses dashboard as the default and redirects the retired now view', () => {
expect(viewFromHash('')).toBe('dashboard');
expect(viewFromHash('#now')).toBe('dashboard');
expect(viewFromHash('#dashboard')).toBe('dashboard');
});
it('keeps the remaining flat views bookmarkable', () => {
expect(viewFromHash('#queue')).toBe('queue');
expect(viewFromHash('#server')).toBe('server');
expect(viewFromHash('#updates')).toBe('updates');
});
});
-41
View File
@@ -1,41 +0,0 @@
// Tiny hash router: keeps the active view in the URL so views are
// bookmarkable and the browser back/forward buttons work. No dependency —
// the app has a single flat set of views.
import { appStore, type ViewName } from './app';
const VIEWS: readonly ViewName[] = [
'dashboard',
'queue',
'search',
'library',
'stats',
'server',
'updates',
'rpc',
];
// The view named by the current hash, defaulting to `dashboard`. Old `#now`
// bookmarks are intentionally canonicalized during router initialization.
export function viewFromHash(hash = location.hash): ViewName {
const raw = hash.replace(/^#\/?/, '');
const base = raw.split(/[/?]/)[0];
if (base === 'now') return 'dashboard';
return (VIEWS as readonly string[]).includes(base)
? (base as ViewName)
: 'dashboard';
}
export function initRouter() {
// Initial view comes from the hash (refresh / shared link).
const initial = viewFromHash();
appStore.set({ view: initial });
if (location.hash.replace(/^#\/?/, '').split(/[/?]/)[0] === 'now') {
history.replaceState(null, '', '#dashboard');
}
window.addEventListener('hashchange', () => {
const view = viewFromHash();
appStore.set({ view });
});
}
-183
View File
@@ -1,183 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { RpcClient } from './rpc';
// A minimal fake WebSocket that records sent frames and lets the test push
// server frames back. Installed as the global before each RpcClient is made.
class FakeWebSocket {
static OPEN = 1;
static instances: FakeWebSocket[] = [];
readyState = FakeWebSocket.OPEN;
sent: string[] = [];
onopen: (() => void) | null = null;
onclose: (() => void) | null = null;
onerror: (() => void) | null = null;
onmessage: ((ev: { data: string }) => void) | null = null;
constructor(public url: string) {
FakeWebSocket.instances.push(this);
queueMicrotask(() => this.onopen && this.onopen());
}
send(data: string) {
this.sent.push(data);
}
close() {
this.readyState = 3;
this.onclose && this.onclose();
}
receive(obj: unknown) {
this.onmessage && this.onmessage({ data: JSON.stringify(obj) });
}
}
function installFakes() {
FakeWebSocket.instances = [];
vi.stubGlobal('WebSocket', FakeWebSocket as unknown as typeof WebSocket);
// /config.json → same-origin /rpc bridge.
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ json: async () => ({ rpcUrl: '/rpc' }) }))
);
vi.stubGlobal('location', {
protocol: 'http:',
host: 'bot.local',
hostname: 'bot.local',
});
}
afterEach(() => vi.unstubAllGlobals());
describe('RpcClient wire contract', () => {
it('encodes method as the enum name and params as a JSON string', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
rpc.call('Seek', { position: 4200 });
expect(ws.sent).toHaveLength(1);
const frame = JSON.parse(ws.sent[0]);
expect(frame.method).toBe('Seek');
// params must be a JSON-encoded *string*, not a nested object.
expect(typeof frame.params).toBe('string');
expect(JSON.parse(frame.params)).toEqual({ position: 4200 });
expect(frame.id).toBe(1);
});
it('attaches the auth token once set', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
rpc.token = 'tok-abc';
rpc.call('GetStatus');
const frame = JSON.parse(ws.sent[0]);
expect(frame.authToken).toBe('tok-abc');
});
it('sends updater requests through their append-only RPC enum names', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
rpc.call('GetUpdateStatus');
const frame = JSON.parse(ws.sent[0]);
expect(frame.method).toBe('GetUpdateStatus');
expect(JSON.parse(frame.params)).toEqual({});
});
it('resolves a call by requestId and JSON-decodes the result string', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
const p = rpc.call('GetStatus');
const frame = JSON.parse(ws.sent[0]);
ws.receive({
requestId: frame.id,
success: true,
result: JSON.stringify({ isPlaying: true, volume: 0.5 }),
});
await expect(p).resolves.toEqual({ isPlaying: true, volume: 0.5 });
});
it('rejects with the decoded error payload', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
const p = rpc.call('Skip');
const frame = JSON.parse(ws.sent[0]);
ws.receive({
requestId: frame.id,
success: false,
error: JSON.stringify({ code: 7, message: 'DJ required' }),
});
await expect(p).rejects.toMatchObject({
code: 7,
message: 'DJ required',
});
});
it('dispatches notifications with the data string decoded', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
const seen: unknown[] = [];
rpc.on('playback.position', (d) => seen.push(d));
ws.receive({
event: 'playback.position',
data: JSON.stringify({ position: 1000, duration: 200000 }),
});
expect(seen).toEqual([{ position: 1000, duration: 200000 }]);
});
it('dispatches the updater change event without renaming it', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
const seen: unknown[] = [];
rpc.on('updates.changed', (data) => seen.push(data));
ws.receive({
event: 'updates.changed',
data: JSON.stringify({ component: 'core', state: 'staged' }),
});
expect(seen).toEqual([{ component: 'core', state: 'staged' }]);
});
it('fires the wildcard listener with event name and data', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
const seen: Array<[unknown, unknown]> = [];
rpc.on('*', (event, data) => seen.push([event, data]));
ws.receive({
event: 'queue.updated',
data: JSON.stringify({ size: 3 }),
});
expect(seen).toEqual([['queue.updated', { size: 3 }]]);
});
it('unsubscribes a notification listener', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
const seen: unknown[] = [];
const unsubscribe = rpc.on('listening_rooms.updated', (data) =>
seen.push(data)
);
unsubscribe();
ws.receive({ event: 'listening_rooms.updated', data: '{}' });
expect(seen).toEqual([]);
});
});
-273
View File
@@ -1,273 +0,0 @@
// Browser RPC client for the Echoion RPC server — TypeScript port of the
// original web/rpc.js. The web UI is a desktop-style client: it connects
// straight to the RPC WebSocket and speaks the exact same JSON protocol the
// Qt desktop client uses.
//
// Wire contract (must match the server — do not "clean up"):
// - request.method is the RpcMethod enum *name* (e.g. "Play").
// - request.params is a JSON-encoded *string*, not a nested object.
// - responses are correlated by requestId; result/error are JSON strings.
// - notifications carry { event, data } where data is a JSON string.
export type RpcConnectionState = 'connected' | 'disconnected' | 'error';
export interface RpcError {
code?: number;
message: string;
source?: string;
}
// Method names mirroring EchoionApi RpcTypes.hpp; the wire carries the name.
export type RpcMethodName =
| 'Authenticate'
| 'AuthenticateByAddress'
| 'Logout'
| 'Play'
| 'Pause'
| 'Resume'
| 'Stop'
| 'Skip'
| 'Seek'
| 'SetVolume'
| 'ToggleShuffle'
| 'ToggleRepeat'
| 'ToggleAutoplay'
| 'ShuffleQueue'
| 'QueueTrack'
| 'RemoveFromQueue'
| 'ClearQueue'
| 'GetQueue'
| 'MoveInQueue'
| 'SearchTracks'
| 'GetCurrentTrack'
| 'GetStatus'
| 'GetServerInfo'
| 'GetPlaylist'
| 'GetPlaylists'
| 'SavePlaylist'
| 'LoadPlaylist'
| 'DeletePlaylist'
| 'GetHistory'
| 'GetStats'
| 'GetLyrics'
| 'GetFavorites'
| 'AddFavorite'
| 'RemoveFavorite'
| 'VoteSkip'
| 'Announce'
| 'GetAggregateStats'
| 'ReloadConfig'
| 'RestartWebInterface'
| 'ManageUsers'
| 'GetAuditLog'
| 'GetUserPrefs'
| 'SetUserPrefs'
| 'GetCapabilities'
| 'GetPluginExtensions'
| 'PluginCall'
| 'GetTeamSpeakDirectory'
| 'MoveTeamSpeakClient'
| 'KickTeamSpeakClient'
| 'BanTeamSpeakClient'
| 'GetTeamSpeakBans'
| 'UnbanTeamSpeakClient'
| 'CreateTeamSpeakChannel'
| 'EditTeamSpeakChannel'
| 'ReorderTeamSpeakChannel'
| 'DeleteTeamSpeakChannel'
| 'GetTeamSpeakServerGroups'
| 'AddTeamSpeakServerGroupMember'
| 'RemoveTeamSpeakServerGroupMember'
| 'SendTeamSpeakPrivateMessage'
| 'SendTeamSpeakChannelMessage'
| 'SendTeamSpeakServerMessage'
| 'GetUpdateStatus'
| 'GetUpdateConfig'
| 'SetUpdateConfig'
| 'CheckForUpdates'
| 'ApplyUpdate'
| 'RollbackUpdate'
| 'ConfirmUnsignedUpdate';
type Pending = {
resolve: (value: unknown) => void;
reject: (err: RpcError) => void;
};
export class RpcClient {
private ws: WebSocket | null = null;
private nextId = 1;
private pending = new Map<number, Pending>();
private listeners = new Map<string, Array<(...args: unknown[]) => void>>();
token: string | null = null;
onState: (s: RpcConnectionState) => void = () => {};
// Fired after an automatic reconnect succeeds so the app can
// re-authenticate and refresh its state.
onReconnected: () => void = () => {};
private wantReconnect = false;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectDelay = 2000;
async connect(): Promise<void> {
let cfg: { rpcUrl?: string; rpcPort?: number } = {};
try {
cfg = await fetch('/config.json').then((r) => r.json());
} catch {
/* fall back to derived URL below */
}
// A path-only rpcUrl (default "/rpc") means the same-origin bridge on
// the web server; absolute URLs and the bare-port fallback still work.
const wsProto = location.protocol === 'https:' ? 'wss' : 'ws';
let url: string;
if (cfg.rpcUrl && cfg.rpcUrl.startsWith('/')) {
url = `${wsProto}://${location.host}${cfg.rpcUrl}`;
} else if (cfg.rpcUrl && cfg.rpcUrl.length) {
url = cfg.rpcUrl;
} else {
url = `ws://${location.hostname}:${cfg.rpcPort || 8765}`;
}
return new Promise((resolve, reject) => {
this.ws = new WebSocket(url);
this.ws.onopen = () => {
this.wantReconnect = true;
this.reconnectDelay = 2000;
this.onState('connected');
resolve();
};
this.ws.onclose = () => {
this.onState('disconnected');
this.failAll('Connection closed');
this.scheduleReconnect();
};
this.ws.onerror = () => {
this.onState('error');
reject(new Error('WebSocket error'));
};
this.ws.onmessage = (ev) => this.onMessage(String(ev.data));
});
}
// Reconnect with backoff after an unexpected close. Only armed once a
// connection has succeeded; an explicit disconnect() disarms it.
private scheduleReconnect() {
if (!this.wantReconnect || this.reconnectTimer) return;
const delay = this.reconnectDelay;
this.reconnectDelay = Math.min(this.reconnectDelay * 2, 15000);
this.reconnectTimer = setTimeout(async () => {
this.reconnectTimer = null;
try {
await this.connect();
this.onReconnected();
} catch {
this.scheduleReconnect();
}
}, delay);
}
disconnect() {
this.wantReconnect = false;
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
if (this.ws) {
this.ws.close();
this.ws = null;
}
}
get connected(): boolean {
return !!this.ws && this.ws.readyState === WebSocket.OPEN;
}
private decode(s: unknown): unknown {
if (s == null) return null;
if (typeof s !== 'string') return s;
try {
return JSON.parse(s);
} catch {
return s;
}
}
private onMessage(raw: string) {
let msg: Record<string, unknown>;
try {
msg = JSON.parse(raw);
} catch {
return;
}
if ('requestId' in msg) {
const p = this.pending.get(msg.requestId as number);
if (!p) return;
this.pending.delete(msg.requestId as number);
if (msg.success) {
p.resolve(this.decode(msg.result));
} else {
p.reject(
(this.decode(msg.error) as RpcError) || {
message: 'RPC error',
}
);
}
} else if ('event' in msg) {
const data = this.decode(msg.data);
const event = msg.event as string;
(this.listeners.get(event) || []).forEach((cb) => cb(data));
(this.listeners.get('*') || []).forEach((cb) => cb(event, data));
}
}
private failAll(message: string) {
for (const [, p] of this.pending) p.reject({ message });
this.pending.clear();
}
call<T = unknown>(
method: RpcMethodName,
params: Record<string, unknown> = {}
): Promise<T> {
return new Promise((resolve, reject) => {
if (!this.connected || !this.ws) {
reject({ message: 'Not connected' });
return;
}
const id = this.nextId++;
const req: Record<string, unknown> = {
id,
method,
params: JSON.stringify(params),
};
if (this.token) req.authToken = this.token;
this.pending.set(id, {
resolve: resolve as (v: unknown) => void,
reject,
});
this.ws.send(JSON.stringify(req));
});
}
on(event: string, cb: (...args: unknown[]) => void) {
if (!this.listeners.has(event)) this.listeners.set(event, []);
this.listeners.get(event)!.push(cb);
return () => {
const listeners = this.listeners.get(event);
if (!listeners) return;
const index = listeners.indexOf(cb);
if (index >= 0) listeners.splice(index, 1);
if (listeners.length === 0) this.listeners.delete(event);
};
}
authenticate(token: string) {
this.token = token;
return this.call('Authenticate', { token });
}
requestToken(nickname: string) {
return this.call('Authenticate', { nickname });
}
}
// Singleton shared by the whole app (mirrors the vanilla `const rpc`).
export const rpc = new RpcClient();
-111
View File
@@ -1,111 +0,0 @@
// Global keyboard shortcuts for desktop control. Ignored while typing in a
// field, and while any modifier is held (so browser/OS chords still work).
import { appStore, safeCall, showView } from './app';
// List shown in the "?" cheat-sheet overlay. English source strings; the
// overlay translates the labels.
export const SHORTCUTS: Array<{ keys: string; label: string }> = [
{ keys: 'Space', label: 'Play / pause' },
{ keys: '← / →', label: 'Seek 5s' },
{ keys: '↑ / ↓', label: 'Volume' },
{ keys: 'N', label: 'Skip / vote skip' },
{ keys: '/', label: 'Focus search' },
{ keys: '?', label: 'This help' },
];
function isTyping(): boolean {
const el = document.activeElement as HTMLElement | null;
if (!el) return false;
const tag = el.tagName;
return (
tag === 'INPUT' ||
tag === 'TEXTAREA' ||
tag === 'SELECT' ||
el.isContentEditable
);
}
async function togglePlay() {
const st = appStore.get().status || {};
if (st.isPlaying && !st.isPaused) await safeCall('Pause');
else await safeCall('Resume');
}
function seekBy(deltaSec: number) {
const s = appStore.get();
const dur = s.durationMs || 0;
if (!dur) return;
const pos = Math.max(0, Math.min(dur, s.positionMs + deltaSec * 1000));
safeCall('Seek', { position: Math.round(pos) });
}
function volumeBy(deltaPct: number) {
const st = appStore.get().status || {};
const cur = Math.round((st.volume ?? 0.5) * 100);
const next = Math.max(0, Math.min(100, cur + deltaPct));
safeCall('SetVolume', { volume: next / 100 });
}
function skip() {
const id = appStore.get().identity;
// Mirror the Now view: DJ/admin force-skip, everyone else votes.
if (id && (id.isAdmin || id.isDj)) safeCall('Skip', { count: 1 });
else safeCall('VoteSkip');
}
export function initShortcuts() {
window.addEventListener('keydown', (e) => {
if (e.ctrlKey || e.metaKey || e.altKey) return;
if (isTyping()) {
if (e.key === 'Escape') {
(document.activeElement as HTMLElement | null)?.blur();
}
return;
}
switch (e.key) {
case ' ':
e.preventDefault();
void togglePlay();
break;
case 'ArrowLeft':
seekBy(-5);
break;
case 'ArrowRight':
seekBy(5);
break;
case 'ArrowUp':
e.preventDefault();
volumeBy(5);
break;
case 'ArrowDown':
e.preventDefault();
volumeBy(-5);
break;
case 'n':
case 'N':
skip();
break;
case '/':
e.preventDefault();
showView('search');
setTimeout(() => {
document
.querySelector<HTMLInputElement>('#view-search input')
?.focus();
}, 50);
break;
case '?':
appStore.set({ shortcutsOpen: !appStore.get().shortcutsOpen });
break;
case 'Escape': {
const s = appStore.get();
if (s.shortcutsOpen) appStore.set({ shortcutsOpen: false });
else if (s.sidebarOpen) appStore.set({ sidebarOpen: false });
break;
}
default:
break;
}
});
}
-36
View File
@@ -1,36 +0,0 @@
// Minimal external store + useSyncExternalStore hook. One immutable snapshot
// for the whole app state (the vanilla UI re-rendered everything on any
// refresh anyway, so per-field granularity buys nothing at this scale).
import { useSyncExternalStore } from 'react';
export class Store<T> {
private state: T;
private listeners = new Set<() => void>();
constructor(initial: T) {
this.state = initial;
}
get(): T {
return this.state;
}
set(partial: Partial<T>) {
this.state = { ...this.state, ...partial };
this.listeners.forEach((l) => l());
}
subscribe = (listener: () => void): (() => void) => {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
};
}
export function useStore<T>(store: Store<T>): T {
return useSyncExternalStore(
store.subscribe,
() => store.get(),
() => store.get()
);
}
@@ -1,33 +0,0 @@
import { describe, expect, it } from 'vitest';
import { teamSpeakChannelDisplayName } from './teamspeak';
describe('TeamSpeak channel display names', () => {
it('leaves ordinary channel names unchanged', () => {
expect(teamSpeakChannelDisplayName('Minecraft')).toEqual({
label: 'Minecraft',
spacer: false,
alignment: 'left',
});
});
it('removes spacer control prefixes and preserves alignment', () => {
expect(teamSpeakChannelDisplayName('[cspacer0]Гамесы')).toEqual({
label: 'Гамесы',
spacer: true,
alignment: 'center',
});
expect(teamSpeakChannelDisplayName('[rspacer12]Подвал')).toEqual({
label: 'Подвал',
spacer: true,
alignment: 'right',
});
});
it('recognizes repeating spacer channels', () => {
expect(teamSpeakChannelDisplayName('[*spacer3]—')).toEqual({
label: '—',
spacer: true,
alignment: 'repeat',
});
});
});
-33
View File
@@ -1,33 +0,0 @@
export type TeamSpeakSpacerAlignment = 'left' | 'center' | 'right' | 'repeat';
export interface TeamSpeakChannelDisplayName {
label: string;
spacer: boolean;
alignment: TeamSpeakSpacerAlignment;
}
const SPACER_NAME = /^\[([clr]|\*)?spacer\d*\](.*)$/i;
export function teamSpeakChannelDisplayName(
name: string
): TeamSpeakChannelDisplayName {
const match = SPACER_NAME.exec(name);
if (!match) {
return { label: name, spacer: false, alignment: 'left' };
}
const alignment =
match[1]?.toLowerCase() === 'c'
? 'center'
: match[1]?.toLowerCase() === 'r'
? 'right'
: match[1] === '*'
? 'repeat'
: 'left';
return {
label: match[2].trim(),
spacer: true,
alignment,
};
}
Loaded 100 of 169 files, more files were not shown because too many files have changed in this diff. Show more