Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9401f19ad5 | ||
|
|
30e669359a | ||
|
|
523355a128 | ||
|
|
2e8e1fc0ba | ||
|
|
7dca9db7dc | ||
|
|
5547621cfa | ||
|
|
c08ff6ca68 | ||
|
|
ff25742659 | ||
|
|
6b5b182c33 | ||
|
|
dbddb80b82 | ||
|
|
ecb4cda800 | ||
|
|
41937b2987 | ||
|
|
0b7af2e96a | ||
|
|
bdd69f0aad | ||
|
|
639362fbf5 | ||
|
|
818d391022 | ||
|
|
ef3139ca64 | ||
|
|
2d1d03db1e | ||
|
|
c9a52b73ac | ||
|
|
3b3dd2be4f | ||
|
|
206c92e3ea | ||
|
|
000663b422 |
No files matched your search
@@ -0,0 +1,7 @@
|
||||
.git
|
||||
build*
|
||||
dist
|
||||
release
|
||||
EchoionWeb/frontend/node_modules
|
||||
EchoionWeb/frontend/web-dist
|
||||
docs
|
||||
@@ -0,0 +1,190 @@
|
||||
# Echoion releases on Gitea
|
||||
|
||||
Echoion release builds run only through `scripts/release.sh`, whose default
|
||||
mode builds, tests, validates, and packages inside
|
||||
`containers/release.Dockerfile`. The runner host only checks out sources and
|
||||
controls Docker; the workflow never starts `echoiond`.
|
||||
|
||||
## One-time Gitea setup
|
||||
|
||||
The workflows target the standard `ubuntu-24.04` label advertised by a default
|
||||
Gitea runner. No custom runner label is required. Use one trusted Linux AMD64
|
||||
runner with capacity set to one so release and feed writes remain serialized
|
||||
on Gitea versions that do not implement workflow `concurrency`. The job image
|
||||
needs Bash, Git with SSH-signature support, OpenSSH client tools, Python 3.10
|
||||
or newer, OpenSSL with Ed25519 support, coreutils, the Docker CLI, and access
|
||||
to a Docker daemon. The release builder itself remains containerized.
|
||||
|
||||
Every workflow starts by running `docker version` and `docker info`. These
|
||||
commands verify both the Docker client in the `ubuntu-24.04` job image and
|
||||
access to the daemon before checkout, secrets, or a long release build are
|
||||
used. A runner installed as a container must have the host socket mounted:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
runner:
|
||||
volumes:
|
||||
- ./data:/data
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
```
|
||||
|
||||
Leave `container.docker_host` at its generated default (`""`) so `act_runner`
|
||||
passes the detected Docker endpoint to job containers. Do not set it to `-`,
|
||||
which explicitly prevents that endpoint from being mounted. Restart the runner
|
||||
after changing its configuration. `scripts/lib/docker-daemon-path.sh` detects
|
||||
when commands run inside the job container and translates checked-out paths
|
||||
through that container's Docker mount table. The release wrapper and
|
||||
control-plane tests both use it because bind mount paths passed to the socket
|
||||
are resolved by the runner host daemon, not inside the Actions job container.
|
||||
|
||||
The SSH checkout steps pin the current `git.faumaray.ru` RSA host key. Its
|
||||
verified fingerprint is
|
||||
`SHA256:fugBYnqAnqmTLsGpafVgQF9gPQzJqps7uHvs48blg2A`. If the Gitea SSH host key
|
||||
is intentionally rotated, verify the new fingerprint through an independent
|
||||
administrator channel and update `ssh-known-hosts` in all three workflows.
|
||||
Never work around a rotation by disabling strict host-key checking.
|
||||
|
||||
The Docker-capable runner executes only protected `main` pushes, manual runs,
|
||||
scheduled nightlies, and signed release tags. The container CI workflow does
|
||||
not run for pull requests because contributor-controlled scripts must not
|
||||
receive a privileged Docker socket or the private-submodule checkout key. If
|
||||
pre-merge CI is required, register a separate ephemeral `echoion-pr` runner
|
||||
without release secrets or host-level Docker access and give it a dedicated
|
||||
workflow. A global runner such as the default installation shown in Gitea must
|
||||
only serve repositories you trust: a workflow with Docker-daemon access can
|
||||
control the runner host.
|
||||
|
||||
Enable Actions and add these repository secrets:
|
||||
|
||||
| Secret | Purpose |
|
||||
| --- | --- |
|
||||
| `RELEASE_CHECKOUT_SSH_KEY` | Read-only deploy key that can clone every private nested repository in `.gitmodules`. |
|
||||
| `RELEASE_BOT_TOKEN` | PAT owned by a dedicated bot, limited to writing releases, tags, and the `release-feed` branch 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. |
|
||||
|
||||
The release PAT must not be shared with checkout of nested repositories. The
|
||||
feed signing key must not be stored in Git, runner images, Actions variables,
|
||||
or release assets.
|
||||
|
||||
Create an orphan `release-feed` branch containing a tracked `feeds/`
|
||||
directory, then protect it so only the release bot can push. Protect the `v*`
|
||||
tag pattern so only the release maintainers represented by
|
||||
`RELEASE_TAG_ALLOWED_SIGNERS` can create, update, or delete matching tags. The
|
||||
workflow requires the exact `v*` rule to have an explicit non-empty user or
|
||||
team allowlist. Configure it under repository **Settings → Tags → Protected
|
||||
tags**; a similar pattern such as `v*.*` does not satisfy the release check.
|
||||
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:
|
||||
|
||||
```text
|
||||
https://<gitea>/<owner>/<repo>/raw/branch/release-feed/feeds/echoion-runtime.json
|
||||
```
|
||||
|
||||
The embedded updater trust configuration is represented by
|
||||
`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.
|
||||
|
||||
## Stable and beta releases
|
||||
|
||||
Create an annotated SSH-signed tag. A version without a prerelease suffix goes
|
||||
to `stable`; any strict SemVer prerelease goes to `beta`.
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
The private-key path works without an SSH agent. A `.pub` path may be used
|
||||
instead when its matching private key is already loaded in `ssh-agent`.
|
||||
|
||||
`.gitea/workflows/release.yml` rejects a lightweight tag, a non-SSH
|
||||
signature, an untrusted signer, a repository without the exact `v*` protected
|
||||
tag rule and explicit allowlist, a non-SemVer name, an event object unrelated
|
||||
to the tag, or a checkout whose commit differs from the signed tag target.
|
||||
Release notes contain the signed tag subject and body but not its SSH signature
|
||||
armor.
|
||||
|
||||
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.
|
||||
|
||||
## Nightly releases
|
||||
|
||||
`.gitea/workflows/nightly.yml` runs at 02:17 UTC and can also be dispatched
|
||||
manually. Nightly versions use
|
||||
`0.0.0-nightly.YYYYMMDD.RUN_NUMBER`, publish as prereleases on the `nightly`
|
||||
channel, 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 `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
|
||||
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.
|
||||
|
||||
## Feed key custody and rotation
|
||||
|
||||
The active public key id is `echoion-release-2026-07`. To rotate, generate the
|
||||
private key on a trusted operator machine:
|
||||
|
||||
```bash
|
||||
umask 077
|
||||
openssl genpkey -algorithm ED25519 -out echoion-release-YYYY-MM.pem
|
||||
openssl pkey -in echoion-release-YYYY-MM.pem -pubout \
|
||||
-out echoion-release-YYYY-MM.pub.pem
|
||||
```
|
||||
|
||||
The PEM public key contains an RFC 8410 SubjectPublicKeyInfo wrapper. The
|
||||
`ed25519` field in `release-keys/official-update-keys.json` must instead contain
|
||||
the standard Base64 encoding of only the raw 32-byte public key. Derive that
|
||||
value with:
|
||||
|
||||
```bash
|
||||
openssl pkey -pubin -in echoion-release-YYYY-MM.pub.pem -outform DER |
|
||||
tail -c 32 |
|
||||
base64 -w0
|
||||
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.
|
||||
|
||||
## Recovery rules
|
||||
|
||||
- A failed build creates no Gitea release.
|
||||
- A failed upload leaves a draft. Rerun the same workflow to replace the
|
||||
partial draft assets.
|
||||
- A failed verification never publishes the draft.
|
||||
- A published release with mismatched assets is immutable; investigate and
|
||||
create a new version instead of replacing it.
|
||||
- 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.
|
||||
@@ -0,0 +1,3 @@
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MCowBQYDK2VwAyEAqD97/GZ6BJaeQpg6shajRcNhwMzvNZ3SvkQtAu6pxEw=
|
||||
-----END PUBLIC KEY-----
|
||||
@@ -0,0 +1,6 @@
|
||||
[
|
||||
{
|
||||
"id": "echoion-release-2026-07",
|
||||
"ed25519": "qD97/GZ6BJaeQpg6shajRcNhwMzvNZ3SvkQtAu6pxEw="
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,59 @@
|
||||
name: Container CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
release-build:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Verify the Docker-capable Gitea runner
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$(uname -s)" = Linux
|
||||
command -v docker
|
||||
docker version
|
||||
docker info
|
||||
|
||||
- name: Check out source and nested repositories
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
fetch-depth: 0
|
||||
submodules: recursive
|
||||
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==
|
||||
persist-credentials: false
|
||||
|
||||
- name: Build, test, and package without starting Echoion
|
||||
env:
|
||||
CI_VERSION: 0.0.0-ci.${{ gitea.run_number }}.${{ gitea.run_attempt }}
|
||||
run: |
|
||||
set -eu
|
||||
scripts/release.sh --version "$CI_VERSION"
|
||||
|
||||
- name: Test release control-plane scripts
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
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
|
||||
@@ -0,0 +1,171 @@
|
||||
name: Nightly release
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '17 2 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
publish-nightly:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Verify the Docker-capable Gitea runner
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$(uname -s)" = Linux
|
||||
command -v docker
|
||||
docker version
|
||||
docker info
|
||||
|
||||
- name: Check out main and nested repositories
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 0
|
||||
submodules: recursive
|
||||
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==
|
||||
persist-credentials: false
|
||||
|
||||
- name: Derive the nightly identity
|
||||
shell: bash
|
||||
env:
|
||||
SERVER_URL: ${{ gitea.server_url }}
|
||||
REPOSITORY: ${{ gitea.repository }}
|
||||
RUN_NUMBER: ${{ gitea.run_number }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
date_id=$(date -u +%Y%m%d)
|
||||
version="0.0.0-nightly.${date_id}.${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_TARGET=%s\n' "$(git rev-parse HEAD)"
|
||||
} >>"$GITHUB_ENV"
|
||||
|
||||
- name: Build and test the dynamic nightly in Docker
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
scripts/release.sh \
|
||||
--version "$RELEASE_VERSION" \
|
||||
--update-url "$RELEASE_ARTIFACT_URL" \
|
||||
--official-update-feed-url "$RELEASE_FEED_URL" \
|
||||
--update-channel nightly \
|
||||
--update-valid-days 45
|
||||
{
|
||||
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
|
||||
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" \
|
||||
publish \
|
||||
--owner "$owner" \
|
||||
--repo "$repo" \
|
||||
--tag "$RELEASE_TAG" \
|
||||
--target "$RELEASE_TARGET" \
|
||||
--name "Echoion nightly $RELEASE_VERSION" \
|
||||
--body-file "$RUNNER_TEMP/release-notes.md" \
|
||||
--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 \
|
||||
--owner "$owner" \
|
||||
--repo "$repo" \
|
||||
--tag-prefix nightly- \
|
||||
--keep 14 \
|
||||
--protect-tag "$RELEASE_TAG"
|
||||
|
||||
- name: Check out the aggregate feed branch
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
ref: release-feed
|
||||
path: feed-state
|
||||
token: ${{ secrets.RELEASE_BOT_TOKEN }}
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Sign and push the aggregate feed last
|
||||
shell: bash
|
||||
env:
|
||||
FEED_PRIVATE_KEY: ${{ secrets.RELEASE_FEED_ED25519_PRIVATE_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
|
||||
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" \
|
||||
"${existing[@]}" \
|
||||
--public-key \
|
||||
.gitea/release-keys/echoion-release-2026-07.pub.pem \
|
||||
--private-key "$key" \
|
||||
--key-id echoion-release-2026-07 \
|
||||
--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
|
||||
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
|
||||
if git -C feed-state diff --cached --quiet; then
|
||||
exit 0
|
||||
fi
|
||||
git -C feed-state commit -m \
|
||||
"Feed: nightly ${RELEASE_VERSION}"
|
||||
git -C feed-state push origin HEAD:release-feed
|
||||
@@ -0,0 +1,192 @@
|
||||
name: Signed release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- v*
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Verify the Docker-capable Gitea runner
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$(uname -s)" = Linux
|
||||
command -v docker
|
||||
docker version
|
||||
docker info
|
||||
|
||||
- name: Check out the signed tag
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
ref: ${{ gitea.ref }}
|
||||
fetch-depth: 0
|
||||
submodules: recursive
|
||||
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==
|
||||
persist-credentials: false
|
||||
|
||||
- name: Verify protected annotated SSH tag
|
||||
shell: bash
|
||||
env:
|
||||
TAG: ${{ gitea.ref_name }}
|
||||
EXPECTED_EVENT_SHA: ${{ gitea.sha }}
|
||||
EXPECTED_REF: ${{ gitea.ref }}
|
||||
EXPECTED_REF_TYPE: ${{ gitea.ref_type }}
|
||||
TAG_ALLOWED_SIGNERS: ${{ secrets.RELEASE_TAG_ALLOWED_SIGNERS }}
|
||||
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }}
|
||||
API_URL: ${{ gitea.api_url }}
|
||||
REPOSITORY: ${{ gitea.repository }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$EXPECTED_REF_TYPE" = tag
|
||||
test "$EXPECTED_REF" = "refs/tags/$TAG"
|
||||
allowed_signers="$RUNNER_TEMP/echoion-release-allowed-signers"
|
||||
trap 'rm -f -- "$allowed_signers"' EXIT
|
||||
umask 077
|
||||
printf '%s\n' "$TAG_ALLOWED_SIGNERS" >"$allowed_signers"
|
||||
test -s "$allowed_signers"
|
||||
target_commit=$(
|
||||
scripts/verify-gitea-release-tag.sh \
|
||||
--tag "$TAG" \
|
||||
--event-sha "$EXPECTED_EVENT_SHA" \
|
||||
--allowed-signers "$allowed_signers" \
|
||||
--notes-output "$RUNNER_TEMP/release-notes.md"
|
||||
)
|
||||
printf 'RELEASE_TARGET=%s\n' "$target_commit" >>"$GITHUB_ENV"
|
||||
owner=${REPOSITORY%%/*}
|
||||
repo=${REPOSITORY#*/}
|
||||
python3 scripts/gitea_release.py \
|
||||
--api-url "$API_URL" \
|
||||
verify-tag-protection \
|
||||
--owner "$owner" \
|
||||
--repo "$repo" \
|
||||
--required-pattern 'v*'
|
||||
|
||||
- name: Derive the stable or beta release
|
||||
shell: bash
|
||||
env:
|
||||
TAG: ${{ gitea.ref_name }}
|
||||
SERVER_URL: ${{ gitea.server_url }}
|
||||
REPOSITORY: ${{ gitea.repository }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version=${TAG#v}
|
||||
test "$version" != "$TAG"
|
||||
python3 scripts/validate-semver.py "$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"
|
||||
{
|
||||
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_FEED_URL=%s\n' "$feed_url"
|
||||
} >>"$GITHUB_ENV"
|
||||
|
||||
- name: Build and test the dynamic release in Docker
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
scripts/release.sh \
|
||||
--version "$RELEASE_VERSION" \
|
||||
--update-url "$RELEASE_ARTIFACT_URL" \
|
||||
--official-update-feed-url "$RELEASE_FEED_URL" \
|
||||
--update-channel "$RELEASE_CHANNEL" \
|
||||
--update-valid-days 45
|
||||
|
||||
- name: Create draft, upload, download-verify, and publish
|
||||
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#*/}
|
||||
prerelease=()
|
||||
if [[ "$RELEASE_PRERELEASE" = true ]]; then
|
||||
prerelease+=(--prerelease)
|
||||
fi
|
||||
python3 scripts/gitea_release.py \
|
||||
--api-url "$API_URL" \
|
||||
publish \
|
||||
--owner "$owner" \
|
||||
--repo "$repo" \
|
||||
--tag "$RELEASE_TAG" \
|
||||
--target "$RELEASE_TARGET" \
|
||||
--name "Echoion $RELEASE_VERSION" \
|
||||
--body-file "$RUNNER_TEMP/release-notes.md" \
|
||||
--artifacts dist \
|
||||
"${prerelease[@]}"
|
||||
|
||||
- name: Check out the aggregate feed branch
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
ref: release-feed
|
||||
path: feed-state
|
||||
token: ${{ secrets.RELEASE_BOT_TOKEN }}
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Sign and push the aggregate feed last
|
||||
shell: bash
|
||||
env:
|
||||
FEED_PRIVATE_KEY: ${{ secrets.RELEASE_FEED_ED25519_PRIVATE_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
|
||||
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" \
|
||||
"${existing[@]}" \
|
||||
--public-key \
|
||||
.gitea/release-keys/echoion-release-2026-07.pub.pem \
|
||||
--private-key "$key" \
|
||||
--key-id echoion-release-2026-07 \
|
||||
--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
|
||||
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
|
||||
if git -C feed-state diff --cached --quiet; then
|
||||
exit 0
|
||||
fi
|
||||
git -C feed-state commit -m \
|
||||
"Feed: ${RELEASE_CHANNEL} ${RELEASE_VERSION}"
|
||||
git -C feed-state push origin HEAD:release-feed
|
||||
+7
-1
@@ -1,6 +1,12 @@
|
||||
*build*
|
||||
!EchoionStandalone/tests/test_update_build_defaults.cpp
|
||||
release
|
||||
/dist/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.claude
|
||||
.cache
|
||||
.idea
|
||||
AGENTS.md
|
||||
.vscode
|
||||
.opencode/
|
||||
.opencode/
|
||||
@@ -4,12 +4,6 @@
|
||||
[submodule "EchoionCore"]
|
||||
path = EchoionCore
|
||||
url = ssh://gitea@git.faumaray.ru/void/echoioncore.git
|
||||
[submodule "EchoionPlugin"]
|
||||
path = EchoionPlugin
|
||||
url = ssh://gitea@git.faumaray.ru/void/echoionplugin.git
|
||||
[submodule "EchoionDesktop"]
|
||||
path = EchoionDesktop
|
||||
url = ssh://gitea@git.faumaray.ru/void/echoiondesktop.git
|
||||
[submodule "docs"]
|
||||
path = docs
|
||||
url = ssh://gitea@git.faumaray.ru/void/echoion.wiki.git
|
||||
+195
-47
@@ -1,6 +1,9 @@
|
||||
cmake_minimum_required(VERSION 4.0.0)
|
||||
project(Echoion VERSION 1.0.0 LANGUAGES CXX)
|
||||
|
||||
include(GNUInstallDirs)
|
||||
include(cmake/DependencyLock.cmake)
|
||||
|
||||
# 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
|
||||
# falls back to -O0, so "production" builds shipped unoptimised. Set this before
|
||||
@@ -26,6 +29,51 @@ if(ECHOION_USE_CCACHE AND NOT CMAKE_CXX_COMPILER_LAUNCHER)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Decide linkage before configuring CPM dependencies. Protocol and VoidLibrary
|
||||
# must be part of the validated echoiond artifact in production, otherwise a
|
||||
# release could pair a new daemon with an old/incompatible shared library.
|
||||
option(BUILD_SHARED_LIBS "Build shared libraries" ON)
|
||||
option(ECHOION_STATIC_LINK "Statically link the GCC runtimes" OFF)
|
||||
if(ECHOION_STATIC_LINK)
|
||||
set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++" CACHE STRING "" FORCE)
|
||||
set(BUILD_SHARED_LIBS OFF)
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
message(STATUS "Static GCC runtime linking enabled")
|
||||
endif()
|
||||
|
||||
# Release artifacts should not expose checkout, dependency, or build-machine
|
||||
# paths through __FILE__, std::source_location, or optional DWARF data. Keep
|
||||
# developer builds unchanged so local diagnostics can still use absolute paths;
|
||||
# scripts/release.sh enables this option for production builds.
|
||||
option(ECHOION_REPRODUCIBLE_BUILD
|
||||
"Replace local source/build prefixes in compiler-generated paths" OFF)
|
||||
if(ECHOION_REPRODUCIBLE_BUILD)
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
|
||||
set(_echoionPrefixMaps
|
||||
"${CMAKE_SOURCE_DIR}=Echoion"
|
||||
"${CMAKE_BINARY_DIR}=EchoionBuild")
|
||||
if(DEFINED CPM_Void_SOURCE AND NOT CPM_Void_SOURCE STREQUAL "")
|
||||
list(APPEND _echoionPrefixMaps
|
||||
"${CPM_Void_SOURCE}=VoidLibrary")
|
||||
endif()
|
||||
if(DEFINED CPM_VoidTeamspeak_SOURCE AND
|
||||
NOT CPM_VoidTeamspeak_SOURCE STREQUAL "")
|
||||
list(APPEND _echoionPrefixMaps
|
||||
"${CPM_VoidTeamspeak_SOURCE}=VoidTeamspeak")
|
||||
endif()
|
||||
foreach(_echoionPrefixMap IN LISTS _echoionPrefixMaps)
|
||||
add_compile_options(
|
||||
"$<$<COMPILE_LANGUAGE:C,CXX>:-ffile-prefix-map=${_echoionPrefixMap}>"
|
||||
"$<$<COMPILE_LANGUAGE:C,CXX>:-fmacro-prefix-map=${_echoionPrefixMap}>"
|
||||
"$<$<COMPILE_LANGUAGE:C,CXX>:-fdebug-prefix-map=${_echoionPrefixMap}>")
|
||||
endforeach()
|
||||
message(STATUS "Reproducible compiler path mapping enabled")
|
||||
else()
|
||||
message(WARNING
|
||||
"ECHOION_REPRODUCIBLE_BUILD is not supported by this compiler")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Include CPM
|
||||
file(
|
||||
DOWNLOAD
|
||||
@@ -50,12 +98,27 @@ CPMAddPackage(
|
||||
# which CPM honours over the git checkout below.
|
||||
CPMAddPackage(
|
||||
NAME Void
|
||||
GIT_REPOSITORY http://git.faumaray.ru/void/voidlibrary.git
|
||||
GIT_TAG main
|
||||
GIT_REPOSITORY https://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}
|
||||
OPTIONS
|
||||
"VOID_ENABLE_TESTING OFF"
|
||||
)
|
||||
|
||||
# Modern native TeamSpeak client library. Local development can point at the
|
||||
# adjacent history-preserving extraction with:
|
||||
# -DCPM_VoidTeamspeak_SOURCE=$HOME/Project/Personal/VoidTeamspeak
|
||||
CPMAddPackage(
|
||||
NAME VoidTeamspeak
|
||||
GIT_REPOSITORY https://git.faumaray.ru/void/voidteamspeak.git
|
||||
# This revision supplies the typed administration API used by Standalone.
|
||||
GIT_TAG ${ECHOION_VOID_TEAMSPEAK_REVISION}
|
||||
OPTIONS
|
||||
"VOID_TEAMSPEAK_BUILD_TESTS OFF"
|
||||
"VOID_ENABLE_TESTING OFF"
|
||||
)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
@@ -103,18 +166,14 @@ set_property(GLOBAL PROPERTY USE_FOLDERS ON)
|
||||
# Options
|
||||
option(BUILD_API "Build EchoionApi" ON)
|
||||
option(BUILD_CORE "Build EchoionCore" ON)
|
||||
option(BUILD_PLUGIN "Build EchoionPlugin" ON)
|
||||
option(BUILD_DESKTOP "Build EchoionDesktop" ON)
|
||||
option(BUILD_WEB "Build EchoionWeb (browser interface + sync-watch)" ON)
|
||||
option(BUILD_WEB "Build EchoionWeb browser dashboard" ON)
|
||||
option(BUILD_STANDALONE "Build EchoionStandalone daemon with native TeamSpeak client" ON)
|
||||
option(BUILD_FIRST_PARTY_PLUGINS "Build bundled Echoion extension plugins" ON)
|
||||
option(BUILD_TESTS "Build tests" OFF)
|
||||
option(BUILD_SHARED_LIBS "Build shared libraries" ON)
|
||||
option(ECHOION_STATIC_LINK "Statically link dependencies for standalone distribution" ON)
|
||||
|
||||
# Static linking configuration
|
||||
if(ECHOION_STATIC_LINK)
|
||||
set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++" CACHE STRING "" FORCE)
|
||||
set(BUILD_SHARED_LIBS OFF)
|
||||
message(STATUS "Static linking enabled - building standalone distribution")
|
||||
if(BUILD_TESTS)
|
||||
enable_testing()
|
||||
endif()
|
||||
|
||||
# Find packages
|
||||
@@ -125,6 +184,14 @@ if(BUILD_API)
|
||||
add_subdirectory(EchoionApi)
|
||||
endif()
|
||||
|
||||
if(BUILD_FIRST_PARTY_PLUGINS)
|
||||
add_subdirectory(plugins)
|
||||
endif()
|
||||
|
||||
if(BUILD_STANDALONE)
|
||||
add_subdirectory(EchoionHost)
|
||||
endif()
|
||||
|
||||
if(BUILD_CORE)
|
||||
add_subdirectory(EchoionCore)
|
||||
endif()
|
||||
@@ -140,49 +207,84 @@ if(BUILD_WEB AND BUILD_CORE)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(BUILD_PLUGIN)
|
||||
add_subdirectory(EchoionPlugin)
|
||||
# VoidTeamspeak is resolved above as a regular reusable package. The legacy
|
||||
# TeamSpeak client plugin and in-tree protocol directories are no longer built.
|
||||
|
||||
# The updater is a deliberately small, dynamically linked lifecycle helper.
|
||||
# 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)
|
||||
endif()
|
||||
|
||||
# EchoionStandalone links the host-common loader and native protocol client.
|
||||
if(BUILD_STANDALONE)
|
||||
add_subdirectory(EchoionStandalone)
|
||||
endif()
|
||||
|
||||
if(BUILD_DESKTOP)
|
||||
add_subdirectory(EchoionDesktop)
|
||||
endif()
|
||||
|
||||
# Tests
|
||||
if(BUILD_TESTS)
|
||||
enable_testing()
|
||||
add_subdirectory(tests)
|
||||
endif()
|
||||
# The release install component is deliberately runtime-only. Nested projects
|
||||
# keep their normal SDK/development install rules, while scripts/release.sh uses
|
||||
# this component as the single input to dependency collection and packaging.
|
||||
option(ECHOION_INSTALL_RUNTIME_BUNDLE
|
||||
"Provide the relocatable Echoion Runtime install component" ON)
|
||||
if(ECHOION_INSTALL_RUNTIME_BUNDLE)
|
||||
if(TARGET EchoionStandalone)
|
||||
if(UNIX AND NOT APPLE)
|
||||
set_target_properties(EchoionStandalone PROPERTIES
|
||||
INSTALL_RPATH "$ORIGIN/../${CMAKE_INSTALL_LIBDIR}"
|
||||
INSTALL_RPATH_USE_LINK_PATH FALSE)
|
||||
endif()
|
||||
install(TARGETS EchoionStandalone
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
|
||||
COMPONENT Runtime)
|
||||
endif()
|
||||
|
||||
# Packaging configuration
|
||||
include(CPack)
|
||||
set(CPACK_PACKAGE_NAME "Echoion")
|
||||
set(CPACK_PACKAGE_VENDOR "Echoion")
|
||||
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Echoion Music Bot for TeamSpeak")
|
||||
set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR})
|
||||
set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR})
|
||||
set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH})
|
||||
set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE")
|
||||
set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md")
|
||||
if(TARGET EchoionCore)
|
||||
if(UNIX AND NOT APPLE)
|
||||
set_target_properties(EchoionCore PROPERTIES
|
||||
INSTALL_RPATH "$ORIGIN"
|
||||
INSTALL_RPATH_USE_LINK_PATH FALSE)
|
||||
endif()
|
||||
install(TARGETS EchoionCore
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
COMPONENT Runtime)
|
||||
endif()
|
||||
|
||||
# Platform-specific packaging
|
||||
if(WIN32)
|
||||
set(CPACK_GENERATOR "ZIP;NSIS")
|
||||
set(CPACK_NSIS_DISPLAY_NAME "Echoion Music Bot")
|
||||
set(CPACK_NSIS_HELP_LINK "https://github.com/yourusername/echoion")
|
||||
set(CPACK_NSIS_URL_INFO_ABOUT "https://github.com/yourusername/echoion")
|
||||
elseif(APPLE)
|
||||
set(CPACK_GENERATOR "DragNDMGZ")
|
||||
set(CPACK_DMG_VOLUME_NAME "Echoion")
|
||||
else()
|
||||
set(CPACK_GENERATOR "TGZ;DEB;RPM")
|
||||
set(CPACK_DEBIAN_PACKAGE_DEPENDS "libssl3, libavformat58, libavcodec58, libsqlite3-0")
|
||||
set(CPACK_RPM_PACKAGE_REQUIRES "openssl, ffmpeg-libs, sqlite")
|
||||
if(TARGET EchoionWeb)
|
||||
install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/EchoionWeb/frontend/web-dist/"
|
||||
DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/web"
|
||||
COMPONENT Runtime)
|
||||
endif()
|
||||
|
||||
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/config.example.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"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/packaging/service/echoion-updater.timer.in"
|
||||
DESTINATION service
|
||||
COMPONENT Runtime)
|
||||
install(PROGRAMS
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/validate-release-manifest.py"
|
||||
DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/tools"
|
||||
COMPONENT Runtime)
|
||||
|
||||
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE")
|
||||
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE"
|
||||
DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/licenses"
|
||||
RENAME Echoion-LICENSE
|
||||
COMPONENT Runtime)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Bundling and deployment helpers
|
||||
include(GNUInstallDirs)
|
||||
|
||||
# Function to bundle Qt dependencies
|
||||
function(bundle_qt_dependencies target)
|
||||
if(NOT TARGET ${target})
|
||||
@@ -256,24 +358,70 @@ if(BUILD_CORE AND TARGET EchoionCore)
|
||||
install_with_dependencies(EchoionCore)
|
||||
endif()
|
||||
|
||||
if(BUILD_PLUGIN AND TARGET EchoionPlugin)
|
||||
install_with_dependencies(EchoionPlugin)
|
||||
if(BUILD_TESTS AND UNIX)
|
||||
add_test(NAME echoion_release_manifest_packaging_tests
|
||||
COMMAND bash
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-release-packaging.sh"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
add_test(NAME echoion_runtime_dependency_packaging_tests
|
||||
COMMAND bash
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-runtime-dependencies.sh"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
add_test(NAME echoion_release_archive_packaging_tests
|
||||
COMMAND bash
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-release-archive.sh"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
add_test(NAME echoion_frontend_license_packaging_tests
|
||||
COMMAND bash
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-frontend-licenses.sh"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
add_test(NAME echoion_installer_packaging_tests
|
||||
COMMAND bash
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/packaging/tests/installer_test.sh")
|
||||
endif()
|
||||
|
||||
# The universal .tar.zst/.run workflow is the supported Linux distribution
|
||||
# format. Keep legacy CPack available for local Windows/macOS experiments,
|
||||
# without publishing inaccurate DEB/RPM host-dependency metadata.
|
||||
option(ECHOION_ENABLE_LEGACY_CPACK "Enable legacy platform packaging" OFF)
|
||||
if(ECHOION_ENABLE_LEGACY_CPACK)
|
||||
set(CPACK_PACKAGE_NAME "Echoion")
|
||||
set(CPACK_PACKAGE_VENDOR "Echoion")
|
||||
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Echoion Music Bot for TeamSpeak")
|
||||
set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION})
|
||||
set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md")
|
||||
if(WIN32)
|
||||
set(CPACK_GENERATOR "ZIP;NSIS")
|
||||
set(CPACK_NSIS_DISPLAY_NAME "Echoion Music Bot")
|
||||
elseif(APPLE)
|
||||
set(CPACK_GENERATOR "DragNDrop")
|
||||
set(CPACK_DMG_VOLUME_NAME "Echoion")
|
||||
else()
|
||||
set(CPACK_GENERATOR "TGZ")
|
||||
endif()
|
||||
include(CPack)
|
||||
endif()
|
||||
|
||||
# Print configuration summary
|
||||
message(STATUS "")
|
||||
message(STATUS "Echoion Configuration:")
|
||||
message(STATUS " Version: ${PROJECT_VERSION}")
|
||||
if(DEFINED ECHOION_RUNTIME_VERSION)
|
||||
message(STATUS " Runtime release version: ${ECHOION_RUNTIME_VERSION}")
|
||||
endif()
|
||||
message(STATUS " C++ Standard: ${CMAKE_CXX_STANDARD}")
|
||||
message(STATUS " Build API: ${BUILD_API}")
|
||||
message(STATUS " Build first-party plugins: ${BUILD_FIRST_PARTY_PLUGINS}")
|
||||
message(STATUS " Build Core: ${BUILD_CORE}")
|
||||
message(STATUS " Build Plugin: ${BUILD_PLUGIN}")
|
||||
message(STATUS " Build Desktop: ${BUILD_DESKTOP}")
|
||||
message(STATUS " Build Web: ${BUILD_WEB}")
|
||||
message(STATUS " Build Standalone: ${BUILD_STANDALONE}")
|
||||
message(STATUS " Build Tests: ${BUILD_TESTS}")
|
||||
message(STATUS " Static Link: ${ECHOION_STATIC_LINK}")
|
||||
message(STATUS " Runtime install component: ${ECHOION_INSTALL_RUNTIME_BUNDLE}")
|
||||
message(STATUS "")
|
||||
message(STATUS "Install prefix: ${CMAKE_INSTALL_PREFIX}")
|
||||
message(STATUS "To build: cmake --build build")
|
||||
message(STATUS "To install: cmake --install build --prefix <install_dir>")
|
||||
message(STATUS "To package: cpack -G TGZ (or DEB, RPM, ZIP, NSIS)")
|
||||
message(STATUS "To release: scripts/release.sh --version <version>")
|
||||
message(STATUS "")
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"version": 9,
|
||||
"cmakeMinimumRequired": {
|
||||
"major": 4,
|
||||
"minor": 0,
|
||||
"patch": 0
|
||||
},
|
||||
"configurePresets": [
|
||||
{
|
||||
"name": "linux-release",
|
||||
"displayName": "Linux dynamic runtime release",
|
||||
"description": "Bot, Core, web dashboard, tests, and a runtime-only install component",
|
||||
"generator": "Ninja",
|
||||
"binaryDir": "${sourceDir}/build-release",
|
||||
"cacheVariables": {
|
||||
"CMAKE_BUILD_TYPE": "Release",
|
||||
"CMAKE_INSTALL_PREFIX": "${sourceDir}/build-release/stage",
|
||||
"BUILD_SHARED_LIBS": "ON",
|
||||
"ECHOION_STATIC_LINK": "OFF",
|
||||
"ECHOION_INSTALL_RUNTIME_BUNDLE": "ON",
|
||||
"ECHOION_ENABLE_LEGACY_CPACK": "OFF",
|
||||
"ECHOION_ENABLE_LTO": "ON",
|
||||
"BUILD_API": "ON",
|
||||
"BUILD_CORE": "ON",
|
||||
"BUILD_WEB": "ON",
|
||||
"ECHOION_BUILD_WEB": "ON",
|
||||
"BUILD_STANDALONE": "ON",
|
||||
"BUILD_FIRST_PARTY_PLUGINS": "ON",
|
||||
"BUILD_DESKTOP": "OFF",
|
||||
"BUILD_TESTS": "ON"
|
||||
}
|
||||
}
|
||||
],
|
||||
"buildPresets": [
|
||||
{
|
||||
"name": "linux-release",
|
||||
"configurePreset": "linux-release",
|
||||
"configuration": "Release"
|
||||
}
|
||||
],
|
||||
"testPresets": [
|
||||
{
|
||||
"name": "linux-release",
|
||||
"configurePreset": "linux-release",
|
||||
"configuration": "Release",
|
||||
"output": {
|
||||
"outputOnFailure": true
|
||||
},
|
||||
"execution": {
|
||||
"noTestsAction": "error"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
+1
-1
Submodule EchoionApi updated: e7573fbcd0...caac928923.
+1
-1
Submodule EchoionCore updated: 5c036d91fb...7975f2b38e.
@@ -0,0 +1,35 @@
|
||||
cmake_minimum_required(VERSION 4.0.0)
|
||||
project(EchoionHost VERSION 1.0.0 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()
|
||||
@@ -0,0 +1,100 @@
|
||||
#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
|
||||
@@ -0,0 +1,585 @@
|
||||
#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
|
||||
Submodule EchoionPlugin deleted from 470ab507e1.
@@ -0,0 +1,202 @@
|
||||
# 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)
|
||||
project(EchoionStandalone VERSION 1.0.0 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)
|
||||
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)
|
||||
|
||||
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()
|
||||
@@ -0,0 +1,42 @@
|
||||
#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
|
||||
@@ -0,0 +1,29 @@
|
||||
#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};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
#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);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
#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
|
||||
@@ -0,0 +1,39 @@
|
||||
#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::expected<std::filesystem::path, std::string>
|
||||
resolveAvatarCacheDirectory(
|
||||
const std::filesystem::path& configuredDirectory,
|
||||
const std::filesystem::path& requestedDirectory = {});
|
||||
} // namespace Echoion::Standalone
|
||||
@@ -0,0 +1,173 @@
|
||||
#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
|
||||
@@ -0,0 +1,17 @@
|
||||
#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";
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
#pragma once
|
||||
|
||||
#include <Types.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Standalone
|
||||
{
|
||||
// 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_;
|
||||
};
|
||||
} // namespace Echoion::Standalone
|
||||
@@ -0,0 +1,102 @@
|
||||
#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
|
||||
@@ -0,0 +1,42 @@
|
||||
#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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
#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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,650 @@
|
||||
#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
|
||||
@@ -0,0 +1,178 @@
|
||||
#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) {
|
||||
return packagedDirectory;
|
||||
}
|
||||
|
||||
error.clear();
|
||||
if (std::filesystem::is_regular_file(
|
||||
executableDirectory / "web" / "index.html", error) &&
|
||||
!error) {
|
||||
return executableDirectory;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
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
@@ -0,0 +1,991 @@
|
||||
// Standalone Echoion host. It loads the hot-reloadable Core through CoreLoader
|
||||
// and adapts Echoion's host contract to VoidTeamspeak's typed client API.
|
||||
|
||||
#include "echoion/host/CoreLoader.hpp"
|
||||
#include "echoion/standalone/ReleaseManifest.hpp"
|
||||
#include "echoion/standalone/RuntimePaths.hpp"
|
||||
#include "echoion/standalone/StandaloneClientInterface.hpp"
|
||||
#include "echoion/standalone/UpdateBuildDefaults.hpp"
|
||||
#include "echoion/standalone/UpdateService.hpp"
|
||||
|
||||
#include <CoreInterface.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Stacktrace/Stacktrace.hpp>
|
||||
#include <Void/System/FileWatcher.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Process.hpp>
|
||||
#include <Void/System/SignalWatcher.hpp>
|
||||
#include <Void/TeamSpeak/Identity.hpp>
|
||||
#include <Void/Update/Update.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <exception>
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <system_error>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace
|
||||
{
|
||||
std::atomic<bool> g_updateRequested{false};
|
||||
|
||||
void requestUpdate() { g_updateRequested = true; }
|
||||
|
||||
std::optional<std::string_view> argumentValue(int argc, char** argv,
|
||||
std::string_view name)
|
||||
{
|
||||
for (int index = 1; index + 1 < argc; ++index) {
|
||||
if (std::string_view{argv[index]} == name) {
|
||||
return argv[index + 1];
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
bool hasArgument(int argc, char** argv, std::string_view name)
|
||||
{
|
||||
for (int index = 1; index < argc; ++index) {
|
||||
if (std::string_view{argv[index]} == name) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::optional<std::filesystem::path>
|
||||
optionalArgumentPath(int argc, char** argv, std::string_view name)
|
||||
{
|
||||
for (int index = 1; index < argc; ++index) {
|
||||
if (std::string_view{argv[index]} != name) {
|
||||
continue;
|
||||
}
|
||||
if (index + 1 < argc &&
|
||||
!std::string_view{argv[index + 1]}.starts_with("--")) {
|
||||
return std::filesystem::path{argv[index + 1]};
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::optional<std::filesystem::path> environmentPath(const char* name)
|
||||
{
|
||||
const char* value = std::getenv(name);
|
||||
if (!value || std::string_view{value}.empty()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return std::filesystem::path{value};
|
||||
}
|
||||
|
||||
std::filesystem::path absolutePath(const std::filesystem::path& path)
|
||||
{
|
||||
std::error_code error;
|
||||
auto absolute = std::filesystem::absolute(path, error);
|
||||
return (error ? path : absolute).lexically_normal();
|
||||
}
|
||||
|
||||
struct RuntimeHandoff {
|
||||
std::filesystem::path manifestPath;
|
||||
std::string state;
|
||||
std::string version;
|
||||
std::string previousVersion;
|
||||
std::uint32_t retainHealthyVersions = 2;
|
||||
};
|
||||
|
||||
[[nodiscard]] std::optional<std::uint32_t>
|
||||
retainHealthyVersions(const Void::Json::Value& object)
|
||||
{
|
||||
const auto* value = object.find("retainHealthyVersions");
|
||||
if (value == nullptr) {
|
||||
return 2U;
|
||||
}
|
||||
if (!value->is_number()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const double number = value->as_number();
|
||||
if (!std::isfinite(number) || std::trunc(number) != number ||
|
||||
number < 1.0 || number > 10.0) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return static_cast<std::uint32_t>(number);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool pathWithin(const std::filesystem::path& path,
|
||||
const std::filesystem::path& root)
|
||||
{
|
||||
auto pathIterator = path.begin();
|
||||
for (auto rootIterator = root.begin(); rootIterator != root.end();
|
||||
++rootIterator, ++pathIterator) {
|
||||
if (pathIterator == path.end() || *pathIterator != *rootIterator) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<RuntimeHandoff>
|
||||
readRuntimeHandoff(const std::filesystem::path& handoff,
|
||||
const std::filesystem::path& installationPrefix)
|
||||
{
|
||||
auto contents = Void::FileSystem::read_file(handoff);
|
||||
if (!contents) {
|
||||
return std::nullopt;
|
||||
}
|
||||
auto parsed = Void::Json::parse(*contents);
|
||||
if (!parsed || !parsed->is_object()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto stringField = [&parsed](std::string_view name) {
|
||||
const auto* value = parsed->find(name);
|
||||
return value && value->is_string() ? value->as_string()
|
||||
: std::string{};
|
||||
};
|
||||
const auto manifestValue = stringField("manifestPath");
|
||||
const auto state = stringField("state");
|
||||
const auto version = stringField("version");
|
||||
const auto retention = retainHealthyVersions(*parsed);
|
||||
if (manifestValue.empty() || state.empty() || version.empty() ||
|
||||
!retention.has_value()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const std::filesystem::path relativeManifest{manifestValue};
|
||||
if (relativeManifest.is_absolute()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
std::error_code error;
|
||||
const auto manifest = std::filesystem::canonical(
|
||||
installationPrefix / relativeManifest, error);
|
||||
if (error) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto versions =
|
||||
std::filesystem::canonical(installationPrefix / "versions", error);
|
||||
if (error || !std::filesystem::is_regular_file(manifest)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
if (!pathWithin(manifest, versions)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return RuntimeHandoff{.manifestPath = manifest,
|
||||
.state = state,
|
||||
.version = version,
|
||||
.previousVersion = stringField("previousVersion"),
|
||||
.retainHealthyVersions = *retention};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::filesystem::path
|
||||
installationPrefix(const std::filesystem::path& installRoot)
|
||||
{
|
||||
std::error_code error;
|
||||
if (installRoot.filename() == "current" &&
|
||||
std::filesystem::is_symlink(
|
||||
std::filesystem::symlink_status(installRoot, error))) {
|
||||
return installRoot.parent_path();
|
||||
}
|
||||
return installRoot;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::filesystem::path
|
||||
updaterIncomingDirectory(const std::filesystem::path& root,
|
||||
const std::filesystem::path& stateDirectory)
|
||||
{
|
||||
if (const auto configured = environmentPath("ECHOION_INCOMING_DIR")) {
|
||||
return absolutePath(*configured);
|
||||
}
|
||||
if (auto record =
|
||||
Void::FileSystem::read_file(root / ".echoion-install")) {
|
||||
constexpr std::string_view prefix{"incoming_dir="};
|
||||
std::string_view contents{*record};
|
||||
while (!contents.empty()) {
|
||||
const auto end = contents.find('\n');
|
||||
const auto line = contents.substr(0, end);
|
||||
if (line.starts_with(prefix) && line.size() > prefix.size()) {
|
||||
std::filesystem::path path{line.substr(prefix.size())};
|
||||
return absolutePath(path.is_absolute() ? path
|
||||
: root / path);
|
||||
}
|
||||
if (end == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
contents.remove_prefix(end + 1);
|
||||
}
|
||||
}
|
||||
return stateDirectory / "incoming";
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<Echoion::Standalone::ReleaseManifest>
|
||||
runningReleaseManifest(const std::filesystem::path& executable,
|
||||
const std::filesystem::path& installRoot)
|
||||
{
|
||||
const std::array candidates{executable.parent_path().parent_path() /
|
||||
"manifest.json",
|
||||
installRoot / "manifest.json"};
|
||||
for (const auto& candidate : candidates) {
|
||||
if (auto manifest =
|
||||
Echoion::Standalone::ReleaseManifest::load(candidate)) {
|
||||
return std::move(*manifest);
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::filesystem::path
|
||||
reconcileManagedCore(const std::filesystem::path& stateDirectory,
|
||||
const std::filesystem::path& fallback)
|
||||
{
|
||||
Void::Update::VersionStore store(stateDirectory / "updates" /
|
||||
"components" / "core");
|
||||
if (auto initialized = store.initialize(); !initialized) {
|
||||
Void::Log::warn("main", "Cannot initialize managed Core store: {}",
|
||||
initialized.error().message());
|
||||
return fallback;
|
||||
}
|
||||
if (auto reconciled = store.reconcile(); !reconciled) {
|
||||
Void::Log::warn("main", "Cannot reconcile managed Core store: {}",
|
||||
reconciled.error().message());
|
||||
return fallback;
|
||||
}
|
||||
auto current = store.currentVersion();
|
||||
if (!current || !*current) {
|
||||
return fallback;
|
||||
}
|
||||
const auto managed = store.versionPath(**current) / fallback.filename();
|
||||
return std::filesystem::is_regular_file(managed) ? managed : fallback;
|
||||
}
|
||||
|
||||
[[nodiscard]] Echoion::Api::Result<std::string>
|
||||
invokeRuntimeHelper(const std::filesystem::path& helper,
|
||||
const std::filesystem::path& root,
|
||||
std::string_view operationJson)
|
||||
{
|
||||
auto operation = Void::Json::parse(operationJson);
|
||||
if (!operation || !operation->is_object()) {
|
||||
return Echoion::Api::fail(
|
||||
Echoion::Api::ErrorCode::ParseError,
|
||||
"runtime update operation must be a JSON object");
|
||||
}
|
||||
const auto field = [&operation](std::string_view name) {
|
||||
const auto* value = operation->find(name);
|
||||
return value && value->is_string() ? value->as_string()
|
||||
: std::string{};
|
||||
};
|
||||
const auto action = field("action");
|
||||
const auto version = field("version");
|
||||
const auto retention = retainHealthyVersions(*operation);
|
||||
if (!retention.has_value()) {
|
||||
return Echoion::Api::fail(
|
||||
Echoion::Api::ErrorCode::InvalidArgument,
|
||||
"retainHealthyVersions must be an integer from 1 to 10");
|
||||
}
|
||||
std::string command;
|
||||
std::vector<std::string> options;
|
||||
if (action == "activate") {
|
||||
command = "activate-runtime";
|
||||
options = {"--staging", field("stagingId"),
|
||||
"--version", version,
|
||||
"--manifest-sha256", field("manifestSha256")};
|
||||
} else if (action == "rollback") {
|
||||
command = "rollback-runtime";
|
||||
options = {"--version", version};
|
||||
} else if (action == "commit") {
|
||||
command = "commit-runtime";
|
||||
options = {"--version", version};
|
||||
} else {
|
||||
return Echoion::Api::fail(Echoion::Api::ErrorCode::InvalidArgument,
|
||||
"unknown runtime update operation");
|
||||
}
|
||||
if (version.empty() ||
|
||||
std::ranges::any_of(
|
||||
options, [](const auto& value) { return value.empty(); })) {
|
||||
return Echoion::Api::fail(
|
||||
Echoion::Api::ErrorCode::InvalidArgument,
|
||||
"runtime update operation is missing required fields");
|
||||
}
|
||||
options.insert(options.end(), {"--retain", std::to_string(*retention)});
|
||||
|
||||
bool direct = false;
|
||||
#ifndef _WIN32
|
||||
direct = ::access((root / "versions").c_str(), W_OK) == 0;
|
||||
#endif
|
||||
std::vector<std::string> arguments{"--root", root.string()};
|
||||
if (!direct) {
|
||||
arguments.insert(arguments.end(), {"request", command});
|
||||
} else {
|
||||
arguments.push_back(command);
|
||||
}
|
||||
arguments.insert(arguments.end(), options.begin(), options.end());
|
||||
if (!direct) {
|
||||
arguments.insert(arguments.end(), {"--origin", "daemon"});
|
||||
}
|
||||
auto result =
|
||||
Void::Process::run(helper, arguments, {}, std::chrono::seconds{30});
|
||||
if (!result) {
|
||||
return Echoion::Api::fail(
|
||||
Echoion::Api::ErrorCode::ServiceUnavailable,
|
||||
result.error().message());
|
||||
}
|
||||
if (result->exit_code != 0) {
|
||||
return Echoion::Api::fail(
|
||||
Echoion::Api::ErrorCode::ServiceUnavailable,
|
||||
result->err.empty() ? "runtime update helper failed"
|
||||
: result->err);
|
||||
}
|
||||
return result->out.empty() ? std::string{"{}"} : std::move(result->out);
|
||||
}
|
||||
|
||||
std::filesystem::path configDir()
|
||||
{
|
||||
if (const char* x = std::getenv("XDG_CONFIG_HOME")) {
|
||||
return std::filesystem::path(x) / "echoion";
|
||||
}
|
||||
if (const char* h = std::getenv("HOME")) {
|
||||
return std::filesystem::path(h) / ".config" / "echoion";
|
||||
}
|
||||
return std::filesystem::path(".") / "echoion";
|
||||
}
|
||||
|
||||
bool prepareStateDirectory(const std::filesystem::path& stateDirectory,
|
||||
bool explicitlySelected)
|
||||
{
|
||||
std::error_code error;
|
||||
std::filesystem::create_directories(stateDirectory, error);
|
||||
if (error) {
|
||||
std::cerr << "Cannot create state directory " << stateDirectory
|
||||
<< ": " << error.message() << '\n';
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto setPath = [](const char* name,
|
||||
const std::filesystem::path& path,
|
||||
bool overwrite) {
|
||||
const auto value = path.string();
|
||||
return ::setenv(name, value.c_str(), overwrite ? 1 : 0) == 0;
|
||||
};
|
||||
const auto temporaryDirectory = stateDirectory / "tmp";
|
||||
std::filesystem::create_directories(temporaryDirectory, error);
|
||||
if (error) {
|
||||
std::cerr << "Cannot create temporary directory "
|
||||
<< temporaryDirectory << ": " << error.message() << '\n';
|
||||
return false;
|
||||
}
|
||||
if (!setPath("ECHOION_STATE_DIR", stateDirectory, true) ||
|
||||
!setPath("XDG_CACHE_HOME", stateDirectory / "cache",
|
||||
explicitlySelected) ||
|
||||
!setPath("XDG_STATE_HOME", stateDirectory / "state",
|
||||
explicitlySelected) ||
|
||||
!setPath("XDG_DATA_HOME", stateDirectory / "data",
|
||||
explicitlySelected) ||
|
||||
!setPath("TMPDIR", temporaryDirectory, explicitlySelected)) {
|
||||
std::cerr << "Cannot export runtime state paths\n";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int validateInstall(const std::filesystem::path& installRoot)
|
||||
{
|
||||
auto manifest = Echoion::Standalone::ReleaseManifest::load(
|
||||
installRoot / "manifest.json");
|
||||
if (!manifest) {
|
||||
std::cerr << manifest.error().message << '\n';
|
||||
return 2;
|
||||
}
|
||||
if (auto result = manifest->validateInstallLayout(); !result) {
|
||||
std::cerr << result.error().message << '\n';
|
||||
return 2;
|
||||
}
|
||||
std::cout << "Echoion installation is valid: " << installRoot << '\n';
|
||||
return 0;
|
||||
}
|
||||
|
||||
void recordInterruptedRelease(const std::filesystem::path& directory)
|
||||
{
|
||||
const auto transaction = directory / "release-transaction";
|
||||
if (!std::filesystem::exists(transaction) ||
|
||||
std::getenv("ECHOION_REEXEC_VERSION")) {
|
||||
return;
|
||||
}
|
||||
auto version = Void::FileSystem::read_file(transaction);
|
||||
if (version && !version->empty()) {
|
||||
std::ignore = Void::FileSystem::atomic_write(
|
||||
directory / "failed-release", *version);
|
||||
Void::Log::error("main",
|
||||
"Release {} failed its startup health check; "
|
||||
"stable service restored",
|
||||
*version);
|
||||
}
|
||||
std::ignore = Void::FileSystem::remove_path(transaction);
|
||||
}
|
||||
|
||||
std::string envOr(const char* key, const std::string& fallback)
|
||||
{
|
||||
const char* v = std::getenv(key);
|
||||
return v ? std::string(v) : fallback;
|
||||
}
|
||||
|
||||
int envInt(const char* key, int fallback)
|
||||
{
|
||||
const char* v = std::getenv(key);
|
||||
if (!v) {
|
||||
return fallback;
|
||||
}
|
||||
try {
|
||||
return std::stoi(v);
|
||||
} catch (...) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
int importIdentity(int argc, char** argv,
|
||||
const std::filesystem::path& defaultIdentityPath)
|
||||
{
|
||||
std::optional<std::filesystem::path> source;
|
||||
auto destination = defaultIdentityPath;
|
||||
bool force = false;
|
||||
bool importRequested = false;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
const std::string_view argument{argv[i]};
|
||||
if (argument == "--help") {
|
||||
std::cout
|
||||
<< "Usage: echoiond [--config PATH] [--state-dir PATH]\n"
|
||||
" echoiond --import-identity EXPORT.ini "
|
||||
"[--identity-path PATH] [--force]\n"
|
||||
" echoiond --validate-install [ROOT]\n";
|
||||
return 0;
|
||||
}
|
||||
if (argument == "--import-identity") {
|
||||
importRequested = true;
|
||||
if (i + 1 < argc &&
|
||||
!std::string_view{argv[i + 1]}.starts_with("--")) {
|
||||
source = argv[++i];
|
||||
}
|
||||
} else if (argument == "--identity-path" && i + 1 < argc) {
|
||||
destination = argv[++i];
|
||||
} else if (argument == "--force") {
|
||||
force = true;
|
||||
}
|
||||
}
|
||||
if (!importRequested) {
|
||||
return -1;
|
||||
}
|
||||
if (!source) {
|
||||
std::cerr << "--import-identity requires an exported INI path.\n";
|
||||
return 2;
|
||||
}
|
||||
try {
|
||||
if (std::filesystem::exists(destination) && !force) {
|
||||
std::cerr << "Identity already exists at " << destination
|
||||
<< "; pass --force to replace it.\n";
|
||||
return 2;
|
||||
}
|
||||
const auto identity =
|
||||
Void::TeamSpeak::Identity::importTeamSpeakIni(source->string());
|
||||
if (const auto parent = destination.parent_path();
|
||||
!parent.empty()) {
|
||||
std::filesystem::create_directories(parent);
|
||||
}
|
||||
identity.save(destination.string());
|
||||
std::cout << "Imported TeamSpeak identity " << identity.uid()
|
||||
<< " to " << destination << '\n';
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << "Identity import failed: " << error.what() << '\n';
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
std::set_terminate([] {
|
||||
const auto frames = Void::Stacktrace::capture_stacktrace();
|
||||
std::cerr << Void::Stacktrace::format_stacktrace(frames) << '\n';
|
||||
std::abort();
|
||||
});
|
||||
|
||||
if (hasArgument(argc, argv, "--validate-release")) {
|
||||
const auto validationPath =
|
||||
argumentValue(argc, argv, "--validate-release");
|
||||
if (!validationPath || validationPath->starts_with("--")) {
|
||||
std::cerr << "--validate-release requires a manifest path\n";
|
||||
return 2;
|
||||
}
|
||||
auto manifest =
|
||||
Echoion::Standalone::ReleaseManifest::load(*validationPath);
|
||||
if (!manifest) {
|
||||
std::cerr << manifest.error().message << '\n';
|
||||
return 2;
|
||||
}
|
||||
if (auto result = manifest->validate(); !result) {
|
||||
std::cerr << result.error().message << '\n';
|
||||
return 2;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
const auto runningExecutable = Echoion::Standalone::runningExecutablePath();
|
||||
if (!runningExecutable) {
|
||||
std::cerr << runningExecutable.error() << '\n';
|
||||
return 2;
|
||||
}
|
||||
const auto installRoot = Echoion::Standalone::deriveInstallRoot(
|
||||
*runningExecutable, environmentPath("ECHOION_HOME"));
|
||||
const auto updateRoot = installationPrefix(installRoot);
|
||||
if (hasArgument(argc, argv, "--validate-install")) {
|
||||
const auto requestedRoot =
|
||||
optionalArgumentPath(argc, argv, "--validate-install");
|
||||
return validateInstall(requestedRoot ? absolutePath(*requestedRoot)
|
||||
: installRoot);
|
||||
}
|
||||
const auto installRootString = installRoot.string();
|
||||
if (::setenv("ECHOION_HOME", installRootString.c_str(), 1) != 0) {
|
||||
std::cerr << "Cannot export ECHOION_HOME\n";
|
||||
return 2;
|
||||
}
|
||||
for (const std::string_view requiredValue : {"--config", "--state-dir"}) {
|
||||
if (hasArgument(argc, argv, requiredValue) &&
|
||||
!optionalArgumentPath(argc, argv, requiredValue)) {
|
||||
std::cerr << requiredValue << " requires a path\n";
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
const auto cfgDir = absolutePath(configDir());
|
||||
std::filesystem::path cfgPath = cfgDir / "config.json";
|
||||
if (const auto requestedConfig =
|
||||
optionalArgumentPath(argc, argv, "--config")) {
|
||||
cfgPath = absolutePath(*requestedConfig);
|
||||
}
|
||||
const auto commandLineState =
|
||||
optionalArgumentPath(argc, argv, "--state-dir");
|
||||
const auto environmentState = environmentPath("ECHOION_STATE_DIR");
|
||||
const auto stateDirectory = Echoion::Standalone::resolveStateDirectory(
|
||||
commandLineState, environmentState, environmentPath("XDG_STATE_HOME"),
|
||||
environmentPath("HOME"), cfgDir);
|
||||
if (!prepareStateDirectory(stateDirectory,
|
||||
commandLineState.has_value() ||
|
||||
environmentState.has_value())) {
|
||||
return 2;
|
||||
}
|
||||
auto signalWatcherResult = Void::Process::SignalWatcher::create();
|
||||
if (!signalWatcherResult) {
|
||||
std::cerr << "Cannot install signal watcher: "
|
||||
<< signalWatcherResult.error().message() << '\n';
|
||||
return 2;
|
||||
}
|
||||
auto signalWatcher = std::move(*signalWatcherResult);
|
||||
recordInterruptedRelease(stateDirectory);
|
||||
|
||||
const auto identityPath = absolutePath(std::filesystem::path(envOr(
|
||||
"ECHOION_IDENTITY_PATH", (stateDirectory / "identity.txt").string())));
|
||||
if (const auto importResult = importIdentity(argc, argv, identityPath);
|
||||
importResult >= 0) {
|
||||
return importResult;
|
||||
}
|
||||
const auto requestedRestore =
|
||||
optionalArgumentPath(argc, argv, "--restore-state");
|
||||
const std::optional<std::filesystem::path> restorePath =
|
||||
requestedRestore ? std::optional{absolutePath(*requestedRestore)}
|
||||
: std::nullopt;
|
||||
const auto requestedManifest = environmentPath("ECHOION_RELEASE_MANIFEST");
|
||||
const auto activationHandoff =
|
||||
stateDirectory / "updates" / "activated-runtime.json";
|
||||
const auto releaseTriggerPath = requestedManifest
|
||||
? absolutePath(*requestedManifest)
|
||||
: activationHandoff;
|
||||
const bool releaseTriggerIsHandoff = !requestedManifest.has_value();
|
||||
const auto runningManifest =
|
||||
runningReleaseManifest(*runningExecutable, installRoot);
|
||||
const auto runtimeVersion =
|
||||
runningManifest
|
||||
? runningManifest->version
|
||||
: std::string{
|
||||
Echoion::Standalone::UpdateBuildDefaults::RuntimeVersion};
|
||||
if (auto recovered =
|
||||
Echoion::Standalone::reconcileManagedPluginUpdates(stateDirectory);
|
||||
!recovered) {
|
||||
Void::Log::error("main", "cannot recover managed plugin updates: {}",
|
||||
recovered.error().message);
|
||||
return 1;
|
||||
}
|
||||
|
||||
Echoion::Standalone::StandaloneSettings settings;
|
||||
settings.identityPath = identityPath.string();
|
||||
settings.avatarCachePath = (stateDirectory / "avatars").string();
|
||||
settings.securityLevel = envInt("ECHOION_SECURITY_LEVEL", 8);
|
||||
settings.opusBitrate = envInt("ECHOION_OPUS_BITRATE", 96000);
|
||||
|
||||
auto interface =
|
||||
std::make_shared<Echoion::Standalone::StandaloneClientInterface>(
|
||||
settings);
|
||||
if (auto r = interface->initialize(); !r) {
|
||||
Void::Log::error("main", "interface init failed: {}",
|
||||
r.error().message);
|
||||
return 1;
|
||||
}
|
||||
|
||||
Echoion::Host::CoreLoader loader;
|
||||
loader.setConfigPath(cfgPath);
|
||||
|
||||
const auto executableDirectory = runningExecutable->parent_path();
|
||||
const auto configuredCoreOverride = environmentPath("ECHOION_CORE_PATH");
|
||||
const auto configuredCorePath = Echoion::Standalone::resolveCorePath(
|
||||
installRoot, executableDirectory, configuredCoreOverride);
|
||||
const bool customCoreOverride =
|
||||
configuredCoreOverride &&
|
||||
absolutePath(*configuredCoreOverride) !=
|
||||
absolutePath(installRoot / "lib" / "Echoion.ts");
|
||||
const auto corePathResolved =
|
||||
customCoreOverride
|
||||
? configuredCorePath
|
||||
: reconcileManagedCore(stateDirectory, configuredCorePath);
|
||||
if (const auto workingDirectory =
|
||||
Echoion::Standalone::runtimeWorkingDirectory(installRoot,
|
||||
executableDirectory)) {
|
||||
std::error_code error;
|
||||
std::filesystem::current_path(*workingDirectory, error);
|
||||
if (error) {
|
||||
Void::Log::error("main",
|
||||
"cannot select runtime asset directory {}: {}",
|
||||
workingDirectory->string(), error.message());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
Void::Log::info("main", "Loading Core from {}", corePathResolved.string());
|
||||
if (auto r = loader.load(corePathResolved); !r) {
|
||||
Void::Log::error("main", "failed to load Core: {}", r.error().message);
|
||||
return 1;
|
||||
}
|
||||
if (restorePath) {
|
||||
if (auto result = loader.restoreCheckpoint(*restorePath); !result) {
|
||||
Void::Log::error("main", "failed to restore restart checkpoint: {}",
|
||||
result.error().message);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
auto core = loader.getCore();
|
||||
if (!core) {
|
||||
Void::Log::error("main", "Core not available after load");
|
||||
return 1;
|
||||
}
|
||||
|
||||
core->setPluginInterface(interface);
|
||||
interface->registerEventCallback(
|
||||
[core](const Echoion::Api::PluginEvent& ev) {
|
||||
std::ignore = core->onPluginEvent(ev);
|
||||
});
|
||||
loader.setHotReloadPrepareCallback(
|
||||
[interface] { interface->quiesceEventCallbacks(); });
|
||||
// Re-register the Core callback after each hot reload (new Core instance).
|
||||
loader.setHotReloadCallback([&loader, interface] {
|
||||
if (auto c = loader.getCore()) {
|
||||
c->setPluginInterface(interface);
|
||||
interface->registerEventCallback(
|
||||
[c](const Echoion::Api::PluginEvent& ev) {
|
||||
std::ignore = c->onPluginEvent(ev);
|
||||
});
|
||||
c->triggerAutoConnect();
|
||||
}
|
||||
});
|
||||
|
||||
const auto updaterExecutable =
|
||||
runningExecutable->parent_path() / "echoion-updater";
|
||||
auto updateService = std::make_unique<Echoion::Standalone::UpdateService>(
|
||||
Echoion::Standalone::UpdateService::Options{
|
||||
.configPath = cfgPath,
|
||||
.stateDirectory = stateDirectory,
|
||||
.installRoot = updateRoot,
|
||||
.runningExecutable = *runningExecutable,
|
||||
.currentCore = corePathResolved,
|
||||
.releaseManifestPath = runningManifest
|
||||
? runningManifest->root / "manifest.json"
|
||||
: std::filesystem::path{},
|
||||
.officialFeedUrl =
|
||||
std::string{Echoion::Standalone::UpdateBuildDefaults::FeedUrl},
|
||||
.officialPublicKeysJson =
|
||||
std::string{
|
||||
Echoion::Standalone::UpdateBuildDefaults::PublicKeysJson},
|
||||
.runtimeVersion = runtimeVersion,
|
||||
.apiVersion = Echoion::Api::VERSION_STRING,
|
||||
.toolchainAbi =
|
||||
std::string{
|
||||
Echoion::Standalone::UpdateBuildDefaults::ToolchainAbi},
|
||||
.incomingDirectory =
|
||||
updaterIncomingDirectory(updateRoot, stateDirectory)},
|
||||
Echoion::Standalone::UpdateService::Hooks{
|
||||
.replaceCore =
|
||||
[&loader](const std::filesystem::path& path) {
|
||||
return loader.hotReload(path);
|
||||
},
|
||||
.managePlugins = [&loader](const std::string& request)
|
||||
-> Echoion::Api::Result<std::string> {
|
||||
if (auto loadedCore = loader.getCore()) {
|
||||
return loadedCore->managePluginsJson(request);
|
||||
}
|
||||
return Echoion::Api::fail(
|
||||
Echoion::Api::ErrorCode::ServiceUnavailable,
|
||||
"Core is not available");
|
||||
},
|
||||
.manageRuntime =
|
||||
[updaterExecutable, updateRoot](const std::string& request) {
|
||||
return invokeRuntimeHelper(updaterExecutable, updateRoot,
|
||||
request);
|
||||
},
|
||||
.playbackActive =
|
||||
[&loader] {
|
||||
auto loadedCore = loader.getCore();
|
||||
if (!loadedCore) {
|
||||
return false;
|
||||
}
|
||||
auto playback = loadedCore->getPlaybackSummary();
|
||||
return playback && playback->isPlaying &&
|
||||
playback->currentTrack.has_value();
|
||||
},
|
||||
.coreVersion =
|
||||
[&loader] {
|
||||
if (auto loadedCore = loader.getCore()) {
|
||||
return loadedCore->getVersion();
|
||||
}
|
||||
return std::string{};
|
||||
}});
|
||||
if (auto started = updateService->start(); !started) {
|
||||
Void::Log::error("main", "Updater disabled: {}",
|
||||
started.error().message);
|
||||
updateService.reset();
|
||||
} else {
|
||||
interface->setHostControlHandler(
|
||||
[service = updateService.get()](const std::string& method,
|
||||
const std::string& request) {
|
||||
return service->handle(method, request);
|
||||
});
|
||||
}
|
||||
|
||||
core->triggerAutoConnect();
|
||||
core.reset();
|
||||
auto releaseWatcher = std::make_unique<Void::FileSystem::FileWatcher>();
|
||||
releaseWatcher->watch(
|
||||
releaseTriggerPath,
|
||||
[](const Void::FileSystem::FileWatcher::Event& event) {
|
||||
if (event.exists) {
|
||||
requestUpdate();
|
||||
}
|
||||
});
|
||||
Void::Log::info("main", "Watching runtime update trigger {}",
|
||||
releaseTriggerPath.string());
|
||||
if (std::filesystem::is_regular_file(releaseTriggerPath)) {
|
||||
requestUpdate();
|
||||
}
|
||||
|
||||
if (!std::filesystem::is_regular_file(installRoot / "manifest.json")) {
|
||||
// Compatibility mode for development. Production release bundles use
|
||||
// transactional daemon re-exec instead of replacing Core in isolation.
|
||||
loader.enableAutoReload();
|
||||
} else {
|
||||
Void::Log::info(
|
||||
"main", "{}",
|
||||
"Core auto-reload is disabled for an installed release payload");
|
||||
}
|
||||
|
||||
Void::Log::info("main", "Echoion standalone running. Ctrl-C to stop.");
|
||||
std::optional<std::string> healthVersion;
|
||||
if (const char* version = std::getenv("ECHOION_REEXEC_VERSION")) {
|
||||
healthVersion = version;
|
||||
Void::Log::info("main", "Release {} entered its 30 second health check",
|
||||
*healthVersion);
|
||||
}
|
||||
auto healthDeadline =
|
||||
std::chrono::steady_clock::now() + std::chrono::seconds{30};
|
||||
|
||||
std::optional<Echoion::Standalone::ReleaseManifest> pendingRelease;
|
||||
std::filesystem::path checkpointPath;
|
||||
bool stopRequested = false;
|
||||
while (!stopRequested && !pendingRelease) {
|
||||
if (updateService) {
|
||||
updateService->processPendingHostActions();
|
||||
}
|
||||
|
||||
if (healthVersion &&
|
||||
std::chrono::steady_clock::now() >= healthDeadline) {
|
||||
bool committed = true;
|
||||
const auto handoff =
|
||||
readRuntimeHandoff(activationHandoff, updateRoot);
|
||||
if (handoff && handoff->state == "pending" &&
|
||||
handoff->version == *healthVersion) {
|
||||
Void::Json::Value operation = Void::Json::object();
|
||||
operation.as_object().emplace_back("action",
|
||||
Void::Json::Value{"commit"});
|
||||
operation.as_object().emplace_back(
|
||||
"version", Void::Json::Value{*healthVersion});
|
||||
operation.as_object().emplace_back(
|
||||
"retainHealthyVersions",
|
||||
Void::Json::Value{static_cast<long long>(
|
||||
handoff->retainHealthyVersions)});
|
||||
auto result =
|
||||
invokeRuntimeHelper(updaterExecutable, updateRoot,
|
||||
Void::Json::serialize(operation));
|
||||
if (!result) {
|
||||
committed = false;
|
||||
Void::Log::error("main",
|
||||
"Cannot confirm runtime {} health: {}",
|
||||
*healthVersion, result.error().message);
|
||||
}
|
||||
}
|
||||
if (committed) {
|
||||
std::ignore = Void::FileSystem::atomic_write(
|
||||
stateDirectory / "release-health", *healthVersion);
|
||||
std::ignore = Void::FileSystem::remove_path(
|
||||
stateDirectory / "release-transaction");
|
||||
std::ignore = Void::FileSystem::remove_path(stateDirectory /
|
||||
"failed-release");
|
||||
Void::Log::info("main", "Release {} passed its health check",
|
||||
*healthVersion);
|
||||
healthVersion.reset();
|
||||
::unsetenv("ECHOION_REEXEC_VERSION");
|
||||
} else {
|
||||
healthDeadline =
|
||||
std::chrono::steady_clock::now() + std::chrono::seconds{5};
|
||||
}
|
||||
}
|
||||
|
||||
if (g_updateRequested.exchange(false)) {
|
||||
auto manifestPath = releaseTriggerPath;
|
||||
if (releaseTriggerIsHandoff) {
|
||||
auto handoff =
|
||||
readRuntimeHandoff(releaseTriggerPath, updateRoot);
|
||||
if (!handoff) {
|
||||
Void::Log::error("main",
|
||||
"runtime activation handoff is invalid");
|
||||
continue;
|
||||
}
|
||||
if (handoff->version == runtimeVersion) {
|
||||
continue;
|
||||
}
|
||||
manifestPath = handoff->manifestPath;
|
||||
}
|
||||
auto manifest =
|
||||
Echoion::Standalone::ReleaseManifest::load(manifestPath);
|
||||
if (!manifest) {
|
||||
Void::Log::error("main", "release rejected: {}",
|
||||
manifest.error().message);
|
||||
continue;
|
||||
}
|
||||
if (manifest->version == runtimeVersion) {
|
||||
continue;
|
||||
}
|
||||
if (auto failed = Void::FileSystem::read_file(stateDirectory /
|
||||
"failed-release");
|
||||
failed && *failed == manifest->version) {
|
||||
Void::Log::error(
|
||||
"main",
|
||||
"Release {} was previously rolled back; publish a new "
|
||||
"version to retry",
|
||||
manifest->version);
|
||||
continue;
|
||||
}
|
||||
auto validation = Void::Process::run(
|
||||
*runningExecutable,
|
||||
{"--validate-release", manifestPath.string()}, {},
|
||||
std::chrono::seconds{30});
|
||||
if (!validation || validation->exit_code != 0) {
|
||||
Void::Log::error("main", "release validation failed: {}",
|
||||
validation ? validation->err
|
||||
: validation.error().message());
|
||||
continue;
|
||||
}
|
||||
checkpointPath = stateDirectory / "restart-state.bin";
|
||||
if (auto checkpoint = loader.checkpoint(checkpointPath);
|
||||
!checkpoint) {
|
||||
Void::Log::error("main", "release checkpoint failed: {}",
|
||||
checkpoint.error().message);
|
||||
continue;
|
||||
}
|
||||
pendingRelease = std::move(*manifest);
|
||||
continue;
|
||||
}
|
||||
|
||||
auto observedSignal =
|
||||
signalWatcher.wait(std::chrono::milliseconds{250});
|
||||
if (!observedSignal) {
|
||||
Void::Log::error("main", "signal watcher failed: {}",
|
||||
observedSignal.error().message());
|
||||
stopRequested = true;
|
||||
} else if (observedSignal->has_value()) {
|
||||
stopRequested = true;
|
||||
}
|
||||
}
|
||||
|
||||
releaseWatcher.reset();
|
||||
Void::Log::info("main", "{}",
|
||||
pendingRelease ? "Applying validated release..."
|
||||
: "Shutting down...");
|
||||
interface->setHostControlHandler({});
|
||||
if (updateService) {
|
||||
updateService->stop();
|
||||
}
|
||||
updateService.reset();
|
||||
loader.disableAutoReload();
|
||||
(void)interface->disconnectFromServer();
|
||||
interface->quiesceEventCallbacks();
|
||||
(void)loader.unload();
|
||||
(void)interface->shutdown();
|
||||
if (pendingRelease) {
|
||||
if (auto transaction = Void::FileSystem::atomic_write(
|
||||
stateDirectory / "release-transaction",
|
||||
pendingRelease->version);
|
||||
!transaction) {
|
||||
Void::Log::error("main", "cannot record release transaction: {}",
|
||||
transaction.error().message());
|
||||
return 1;
|
||||
}
|
||||
const auto pendingRoot =
|
||||
Echoion::Standalone::deriveInstallRoot(pendingRelease->executable);
|
||||
const auto pendingHome =
|
||||
releaseTriggerIsHandoff ? updateRoot / "current" : pendingRoot;
|
||||
const auto pendingRootString = pendingHome.string();
|
||||
const auto pendingCoreString = pendingRelease->core.string();
|
||||
if (::setenv("ECHOION_HOME", pendingRootString.c_str(), 1) != 0 ||
|
||||
::setenv("ECHOION_CORE_PATH", pendingCoreString.c_str(), 1) != 0 ||
|
||||
::setenv("ECHOION_REEXEC_VERSION", pendingRelease->version.c_str(),
|
||||
1) != 0) {
|
||||
Void::Log::error("main", "cannot export pending release paths");
|
||||
return 1;
|
||||
}
|
||||
std::vector<std::string> arguments;
|
||||
arguments.reserve(static_cast<std::size_t>(argc) + 2);
|
||||
for (int index = 1; index < argc; ++index) {
|
||||
const std::string_view argument{argv[index]};
|
||||
if (argument == "--restore-state") {
|
||||
++index;
|
||||
continue;
|
||||
}
|
||||
arguments.emplace_back(argument);
|
||||
}
|
||||
arguments.emplace_back("--restore-state");
|
||||
arguments.push_back(checkpointPath.string());
|
||||
if (auto result =
|
||||
Void::Process::reexec(pendingRelease->executable, arguments);
|
||||
!result) {
|
||||
Void::Log::error("main", "release re-exec failed: {}",
|
||||
result.error().message());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
#include "echoion/host/CoreLoader.hpp"
|
||||
|
||||
#include <cstdlib>
|
||||
#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 ytDlp = root / ".local/share/echoion/yt-dlp/yt-dlp";
|
||||
std::filesystem::create_directories(ytDlp.parent_path());
|
||||
{
|
||||
std::ofstream output{ytDlp};
|
||||
output << "#!/bin/sh\necho 2026.01.01\n";
|
||||
}
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
#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);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
#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;
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
#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;
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
#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 / "share" / "echoion",
|
||||
"packaged web root did not select share/echoion as working directory");
|
||||
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;
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
#!/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/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"
|
||||
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
|
||||
@@ -0,0 +1,41 @@
|
||||
#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;
|
||||
}
|
||||
@@ -0,0 +1,691 @@
|
||||
#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;
|
||||
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;
|
||||
}
|
||||
+31
-18
@@ -16,18 +16,17 @@ target_include_directories(EchoionWeb PUBLIC
|
||||
|
||||
# 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.
|
||||
if(NOT TARGET Boost::beast)
|
||||
find_package(Boost 1.87 CONFIG QUIET)
|
||||
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()
|
||||
endif()
|
||||
# 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)
|
||||
|
||||
@@ -37,12 +36,12 @@ target_link_libraries(EchoionWeb
|
||||
Void::Data
|
||||
Void::Log
|
||||
Void::Async
|
||||
Void::Net
|
||||
PRIVATE
|
||||
Threads::Threads
|
||||
Boost::beast
|
||||
Boost::asio
|
||||
Boost::system
|
||||
Boost::url
|
||||
)
|
||||
|
||||
if(MSVC)
|
||||
@@ -56,7 +55,17 @@ endif()
|
||||
# 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).
|
||||
option(ECHOION_BUILD_WEB "Build the React web frontend with npm/vite" ON)
|
||||
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")
|
||||
@@ -72,9 +81,12 @@ if(ECHOION_BUILD_WEB)
|
||||
# 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_srcs CONFIGURE_DEPENDS
|
||||
file(GLOB_RECURSE _web_tree_srcs CONFIGURE_DEPENDS
|
||||
LIST_DIRECTORIES FALSE
|
||||
"${_web_frontend}/src/*"
|
||||
"${_web_frontend}/public/*"
|
||||
"${_web_frontend}/public/*")
|
||||
set(_web_srcs
|
||||
${_web_tree_srcs}
|
||||
"${_web_frontend}/index.html"
|
||||
"${_web_frontend}/package.json"
|
||||
"${_web_frontend}/package-lock.json"
|
||||
@@ -83,8 +95,9 @@ if(ECHOION_BUILD_WEB)
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT "${_web_dist}/index.html"
|
||||
# `npm ci` when the lockfile is newer than node_modules keeps installs
|
||||
# reproducible; the stamp check avoids reinstalling on every build.
|
||||
# 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}"
|
||||
|
||||
Generated
-39
@@ -894,9 +894,6 @@
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -911,9 +908,6 @@
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -928,9 +922,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -945,9 +936,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -962,9 +950,6 @@
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -979,9 +964,6 @@
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -996,9 +978,6 @@
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1013,9 +992,6 @@
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1030,9 +1006,6 @@
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1047,9 +1020,6 @@
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1064,9 +1034,6 @@
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1081,9 +1048,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1098,9 +1062,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "Echoion Music Bot",
|
||||
"short_name": "Echoion",
|
||||
"description": "Control the Echoion TeamSpeak music bot — play, queue, search and watch together.",
|
||||
"description": "Control the Echoion TeamSpeak music bot and view live server activity.",
|
||||
"start_url": "/",
|
||||
"scope": "/",
|
||||
"display": "standalone",
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
// 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 and /ws (WebSockets aren't interceptable anyway),
|
||||
// /config.json, /avatar/*, /emoji/* all fall through to the network so the UI
|
||||
// never shows stale identity/config.
|
||||
// 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-v2';
|
||||
const CACHE = 'echoion-shell-v4';
|
||||
const SHELL = ['/', '/manifest.webmanifest', '/icon.svg', '/icon-maskable.svg'];
|
||||
|
||||
self.addEventListener('install', (event) => {
|
||||
@@ -48,10 +48,9 @@ self.addEventListener('fetch', (event) => {
|
||||
// Never intercept the live control/config/media surfaces.
|
||||
if (
|
||||
url.pathname === '/config.json' ||
|
||||
url.pathname.startsWith('/api/') ||
|
||||
url.pathname.startsWith('/rpc') ||
|
||||
url.pathname.startsWith('/ws') ||
|
||||
url.pathname.startsWith('/avatar') ||
|
||||
url.pathname.startsWith('/emoji')
|
||||
url.pathname.startsWith('/avatar')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -5,11 +5,8 @@
|
||||
// - 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:
|
||||
// - watch.ts state strings rendered via t(w.playerEmpty)
|
||||
// - SHORTCUTS labels (lib/shortcuts.ts) rendered via t(sc.label)
|
||||
// - HEADS view titles/subtitles (App.tsx) rendered via t(title)/t(sub)
|
||||
// - server-sent watch.denied reasons (grep sendDenied in
|
||||
// EchoionWeb/src/WatchSession.cpp) rendered via t(msg.reason)
|
||||
// Orphans reported here may be one of those dynamic keys — the KNOWN_DYNAMIC
|
||||
// list below suppresses the ones we know about.
|
||||
//
|
||||
@@ -25,17 +22,6 @@ const ruFile = join(srcDir, 'i18n', 'ru.ts');
|
||||
|
||||
// Keys reached through variables (see header); keep in sync by hand.
|
||||
const KNOWN_DYNAMIC = new Set([
|
||||
// watch.ts playerEmpty / state strings
|
||||
'Nothing loaded — paste a URL above',
|
||||
'Twitch embeds require HTTPS — open the site via its https:// domain',
|
||||
// server-sent watch.denied reasons (grep sendDenied in WatchSession.cpp)
|
||||
'Sign in to control playback',
|
||||
'Only the host controls playback',
|
||||
'Watch queue is full',
|
||||
'Watch queue is empty',
|
||||
'Live stream — cannot seek',
|
||||
'That viewer is no longer here',
|
||||
'Only signed-in viewers can host',
|
||||
// connection state rendered via t(s.connection) in Sidebar.tsx
|
||||
'connected',
|
||||
'disconnected',
|
||||
@@ -48,8 +34,8 @@ const KNOWN_DYNAMIC = new Set([
|
||||
'Focus search',
|
||||
'This help',
|
||||
// HEADS view titles/subtitles (App.tsx)
|
||||
'Now Playing',
|
||||
'What Echoion is streaming to the channel',
|
||||
'Dashboard',
|
||||
'Live playback and TeamSpeak server activity',
|
||||
'Queue',
|
||||
'Reorder and manage upcoming tracks',
|
||||
'Search',
|
||||
@@ -58,10 +44,10 @@ const KNOWN_DYNAMIC = new Set([
|
||||
'Your favorites and saved playlists',
|
||||
'History & Stats',
|
||||
'Playback history and server insights',
|
||||
'Watch Together',
|
||||
'Synced viewing room — everyone in step',
|
||||
'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
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useEffect } from 'react';
|
||||
import { appStore, boot, getStoredToken, toast } from './lib/app';
|
||||
import { initWatch } from './lib/watch';
|
||||
import { appStore, boot } from './lib/app';
|
||||
import { initRouter } from './lib/router';
|
||||
import { initShortcuts } from './lib/shortcuts';
|
||||
import { initMediaSession } from './lib/mediaSession';
|
||||
@@ -11,23 +10,23 @@ import { Sidebar } from './components/Sidebar';
|
||||
import { MiniPlayer } from './components/MiniPlayer';
|
||||
import { DialogHost } from './components/DialogHost';
|
||||
import { ShortcutsHelp } from './components/ShortcutsHelp';
|
||||
import { NowView } from './views/NowView';
|
||||
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 { WatchView } from './views/WatchView';
|
||||
import { ServerView } from './views/ServerView';
|
||||
import { UpdatesView } from './views/UpdatesView';
|
||||
import { RpcView } from './views/RpcView';
|
||||
|
||||
const HEADS: Record<string, [string, string]> = {
|
||||
now: ['Now Playing', 'What Echoion is streaming to the channel'],
|
||||
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'],
|
||||
watch: ['Watch Together', 'Synced viewing room — everyone in step'],
|
||||
server: ['Server & Admin', 'Manage subscribers and broadcast'],
|
||||
updates: ['Updates', 'Runtime, Core, and plugin release control'],
|
||||
rpc: ['RPC / API', 'Connect to Echoion programmatically'],
|
||||
};
|
||||
|
||||
@@ -37,20 +36,12 @@ export function App() {
|
||||
|
||||
useEffect(() => {
|
||||
boot();
|
||||
initWatch({
|
||||
getName: () =>
|
||||
(appStore.get().identity &&
|
||||
appStore.get().identity!.nickname) ||
|
||||
null,
|
||||
getToken: getStoredToken,
|
||||
toast,
|
||||
});
|
||||
initRouter();
|
||||
initShortcuts();
|
||||
initMediaSession();
|
||||
}, []);
|
||||
|
||||
const [title, sub] = HEADS[s.view] || HEADS.now;
|
||||
const [title, sub] = HEADS[s.view] || HEADS.dashboard;
|
||||
|
||||
return (
|
||||
<div id="app">
|
||||
@@ -82,7 +73,7 @@ export function App() {
|
||||
<div className="header-right">
|
||||
<span className="pill">
|
||||
<span className="dot dot-green" />
|
||||
{s.onlineCount} {t('listening')}
|
||||
{s.onlineCount} {t('online')}
|
||||
</span>
|
||||
<button
|
||||
className="icon-btn"
|
||||
@@ -97,18 +88,13 @@ export function App() {
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{s.view === 'now' && <NowView />}
|
||||
{s.view === 'dashboard' && <DashboardView />}
|
||||
{s.view === 'queue' && <QueueView />}
|
||||
{s.view === 'search' && <SearchView />}
|
||||
{s.view === 'library' && <LibraryView />}
|
||||
{s.view === 'stats' && <StatsView />}
|
||||
{/* The watch view stays mounted so the embedded player and
|
||||
room connection survive view switches (the old UI only
|
||||
toggled `hidden`). */}
|
||||
<div hidden={s.view !== 'watch'}>
|
||||
<WatchView />
|
||||
</div>
|
||||
{s.view === 'server' && <ServerView />}
|
||||
{s.view === 'updates' && <UpdatesView />}
|
||||
{s.view === 'rpc' && <RpcView />}
|
||||
|
||||
<MiniPlayer />
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useStore } from '../lib/store';
|
||||
import { emojiStore, loadCustomEmojis } from '../lib/emoji';
|
||||
import { safeCall, toast } from '../lib/app';
|
||||
import { CloseIcon } from './icons';
|
||||
import { t } from '../i18n';
|
||||
|
||||
// Admin custom-emoji manager (item 16): upload an image (≤64KB) under a
|
||||
// shortcode name, list existing ones, and remove them. The image is sent as
|
||||
// base64 to AddCustomEmoji and served back at /emoji/<name>.
|
||||
export function EmojiManager() {
|
||||
const { custom } = useStore(emojiStore);
|
||||
const [name, setName] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
loadCustomEmojis();
|
||||
}, []);
|
||||
|
||||
const upload = async () => {
|
||||
const file = fileRef.current?.files?.[0];
|
||||
const clean = name.trim().toLowerCase();
|
||||
if (!/^[a-z0-9_]{1,32}$/.test(clean)) {
|
||||
toast(t('Emoji name must be 1-32 chars of a-z, 0-9, _'));
|
||||
return;
|
||||
}
|
||||
if (!file) {
|
||||
toast(t('Choose an image file'));
|
||||
return;
|
||||
}
|
||||
if (file.size > 64 * 1024) {
|
||||
toast(t('Emoji image too large (max ~64KB)'));
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
const dataBase64 = await new Promise<string>((resolve) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const res = String(reader.result);
|
||||
resolve(res.slice(res.indexOf(',') + 1)); // strip data: prefix
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
const res = await safeCall('AddCustomEmoji', {
|
||||
name: clean,
|
||||
mime: file.type,
|
||||
dataBase64,
|
||||
});
|
||||
setBusy(false);
|
||||
if (res) {
|
||||
toast(t('Emoji added'));
|
||||
setName('');
|
||||
if (fileRef.current) fileRef.current.value = '';
|
||||
loadCustomEmojis();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="card">
|
||||
<div className="card-head">
|
||||
<h2>
|
||||
{t('Custom emojis')}{' '}
|
||||
<span className="muted">
|
||||
{custom.length ? `· ${custom.length}` : ''}
|
||||
</span>
|
||||
</h2>
|
||||
</div>
|
||||
<div className="emoji-manage-row">
|
||||
<input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder={t('shortcode (a-z0-9_)')}
|
||||
maxLength={32}
|
||||
/>
|
||||
<input ref={fileRef} type="file" accept="image/*" />
|
||||
<button
|
||||
className="btn btn-accent"
|
||||
disabled={busy}
|
||||
onClick={upload}
|
||||
>
|
||||
{t('Add emoji')}
|
||||
</button>
|
||||
</div>
|
||||
<div className="emoji-manage-grid">
|
||||
{custom.map((c) => (
|
||||
<div key={c.name} className="emoji-manage-item">
|
||||
<img
|
||||
className="emoji-img-lg"
|
||||
src={`/emoji/${c.name}`}
|
||||
alt={c.name}
|
||||
/>
|
||||
<span className="mono">:{c.name}:</span>
|
||||
<button
|
||||
className="icon-btn danger"
|
||||
title={t('Remove')}
|
||||
onClick={async () => {
|
||||
await safeCall('RemoveCustomEmoji', {
|
||||
name: c.name,
|
||||
});
|
||||
toast(t('Emoji removed'));
|
||||
loadCustomEmojis();
|
||||
}}
|
||||
>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useStore } from '../lib/store';
|
||||
import {
|
||||
EMOJI_CATEGORIES,
|
||||
emojiStore,
|
||||
rememberEmoji,
|
||||
} from '../lib/emoji';
|
||||
import { t } from '../i18n';
|
||||
|
||||
// A popover emoji picker: recently-used, curated Unicode categories, and the
|
||||
// server's custom image emojis. `onPick` receives either a unicode char or a
|
||||
// :shortcode: for a custom emoji.
|
||||
export function EmojiPicker(props: {
|
||||
onPick: (token: string) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { custom, recent } = useStore(emojiStore);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const onDoc = (e: MouseEvent) => {
|
||||
if (ref.current && !ref.current.contains(e.target as Node)) {
|
||||
props.onClose();
|
||||
}
|
||||
};
|
||||
// Defer so the opening click doesn't immediately close it.
|
||||
const id = setTimeout(
|
||||
() => document.addEventListener('mousedown', onDoc),
|
||||
0
|
||||
);
|
||||
return () => {
|
||||
clearTimeout(id);
|
||||
document.removeEventListener('mousedown', onDoc);
|
||||
};
|
||||
}, [props]);
|
||||
|
||||
const pick = (token: string) => {
|
||||
rememberEmoji(token);
|
||||
props.onPick(token);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="emoji-picker" ref={ref}>
|
||||
{recent.length > 0 && (
|
||||
<div className="emoji-section">
|
||||
<div className="emoji-section-label">{t('Recent')}</div>
|
||||
<div className="emoji-grid">
|
||||
{recent.map((token, i) =>
|
||||
token.startsWith(':') ? (
|
||||
<button
|
||||
key={i}
|
||||
className="emoji-btn"
|
||||
onClick={() => pick(token)}
|
||||
>
|
||||
<img
|
||||
src={`/emoji/${token.slice(1, -1)}`}
|
||||
alt={token}
|
||||
className="emoji-img"
|
||||
/>
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
key={i}
|
||||
className="emoji-btn"
|
||||
onClick={() => pick(token)}
|
||||
>
|
||||
{token}
|
||||
</button>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{custom.length > 0 && (
|
||||
<div className="emoji-section">
|
||||
<div className="emoji-section-label">{t('Custom')}</div>
|
||||
<div className="emoji-grid">
|
||||
{custom.map((c) => (
|
||||
<button
|
||||
key={c.name}
|
||||
className="emoji-btn"
|
||||
title={`:${c.name}:`}
|
||||
onClick={() => pick(`:${c.name}:`)}
|
||||
>
|
||||
<img
|
||||
src={`/emoji/${c.name}`}
|
||||
alt={c.name}
|
||||
className="emoji-img"
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{EMOJI_CATEGORIES.map((cat) => (
|
||||
<div key={cat.label} className="emoji-section">
|
||||
<div className="emoji-section-label">{cat.label}</div>
|
||||
<div className="emoji-grid">
|
||||
{cat.emoji.map((e) => (
|
||||
<button
|
||||
key={e}
|
||||
className="emoji-btn"
|
||||
onClick={() => pick(e)}
|
||||
>
|
||||
{e}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -14,7 +14,7 @@ async function togglePlay() {
|
||||
// Mini player mirrors the current track on views other than Now Playing.
|
||||
export function MiniPlayer() {
|
||||
const s = useStore(appStore);
|
||||
if (s.view === 'now' || !s.current) return null;
|
||||
if (s.view === 'dashboard' || !s.current) return null;
|
||||
const playing = !!(s.status && s.status.isPlaying && !s.status.isPaused);
|
||||
const canForceSkip = !!(
|
||||
s.identity &&
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
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,5 +1,6 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { useEffect, useId, useRef, type KeyboardEvent, type ReactNode } from 'react';
|
||||
import { CloseIcon } from './icons';
|
||||
import { t } from '../i18n';
|
||||
|
||||
export function Modal(props: {
|
||||
title: string;
|
||||
@@ -8,15 +9,60 @@ export function Modal(props: {
|
||||
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>{props.title}</h2>
|
||||
<button className="icon-btn" onClick={props.onClose}>
|
||||
<h2 id={titleId}>{props.title}</h2>
|
||||
<button
|
||||
className="icon-btn"
|
||||
aria-label={t('Close')}
|
||||
onClick={props.onClose}
|
||||
>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -11,11 +11,9 @@ import {
|
||||
} from './icons';
|
||||
import { t } from '../i18n';
|
||||
|
||||
// The one custom player control bar, shared by Watch Together (room /ws
|
||||
// protocol) and Now Playing (bot RPC). Purely presentational: the two sync
|
||||
// channels differ only in the callbacks the views pass in. Embedded players
|
||||
// (YouTube/Twitch/HTML5) always run with native controls hidden; this bar is
|
||||
// the only playback UI.
|
||||
// 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;
|
||||
@@ -45,7 +43,7 @@ export function PlayerControls(props: {
|
||||
: 0;
|
||||
return (
|
||||
<div className="player-controls">
|
||||
<div className="watch-controls">
|
||||
<div className="player-control-row">
|
||||
<button
|
||||
className="ctrl ctrl-main"
|
||||
title={t('Play/Pause')}
|
||||
@@ -102,7 +100,7 @@ export function PlayerControls(props: {
|
||||
{props.extra}
|
||||
</div>
|
||||
{(props.showLocal ?? true) && (
|
||||
<div className="watch-controls watch-local">
|
||||
<div className="player-control-row player-local-row">
|
||||
<span className="muted">{t('Vol')}</span>
|
||||
<Bar
|
||||
slim
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { PlayerExtraControl } from '../lib/embedProtocols';
|
||||
import { t } from '../i18n';
|
||||
import { GearIcon } from './icons';
|
||||
|
||||
export function PlayerSettingsMenu(props: {
|
||||
extras: PlayerExtraControl[];
|
||||
rate: number;
|
||||
rateOptions?: number[];
|
||||
canControl: boolean;
|
||||
onExtra: (id: string, value: string) => void;
|
||||
onRate: (rate: number) => void;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const local = props.extras.filter((control) => control.scope === 'local');
|
||||
const room = props.extras.filter(
|
||||
(control) => control.scope === 'synced' && control.id !== 'speed'
|
||||
);
|
||||
const hasRoom = room.length > 0 || !!props.rateOptions?.length;
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const close = (event: MouseEvent) => {
|
||||
if (!rootRef.current?.contains(event.target as Node)) setOpen(false);
|
||||
};
|
||||
document.addEventListener('mousedown', close);
|
||||
return () => document.removeEventListener('mousedown', close);
|
||||
}, [open]);
|
||||
|
||||
if (local.length === 0 && !hasRoom) return null;
|
||||
const renderControl = (control: PlayerExtraControl) => (
|
||||
<label className="player-setting" key={control.id}>
|
||||
<span>{t(control.label)}</span>
|
||||
<select
|
||||
value={control.current ?? ''}
|
||||
disabled={control.scope === 'synced' && !props.canControl}
|
||||
title={
|
||||
control.scope === 'synced' && !props.canControl
|
||||
? t('Only the host can change this')
|
||||
: undefined
|
||||
}
|
||||
onChange={(event) => props.onExtra(control.id, event.target.value)}
|
||||
>
|
||||
{control.current == null && <option value="">{t('Choose')}</option>}
|
||||
{control.options.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{t(option.label)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="player-settings" ref={rootRef}>
|
||||
<button
|
||||
className="ctrl"
|
||||
title={t('Settings')}
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((value) => !value)}
|
||||
>
|
||||
<GearIcon />
|
||||
</button>
|
||||
{open && (
|
||||
<div className="player-settings-popover">
|
||||
{local.length > 0 && (
|
||||
<section>
|
||||
<div className="player-settings-heading">{t('Local')}</div>
|
||||
{local.map(renderControl)}
|
||||
</section>
|
||||
)}
|
||||
{hasRoom && (
|
||||
<section>
|
||||
<div className="player-settings-heading">{t('Room')}</div>
|
||||
{props.rateOptions && (
|
||||
<label className="player-setting">
|
||||
<span>{t('Speed')}</span>
|
||||
<select
|
||||
value={String(props.rate)}
|
||||
disabled={!props.canControl}
|
||||
onChange={(event) =>
|
||||
props.onRate(Number(event.target.value))
|
||||
}
|
||||
>
|
||||
{props.rateOptions.map((rate) => (
|
||||
<option key={rate} value={rate}>{rate}×</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{room.map(renderControl)}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -20,18 +20,19 @@ import {
|
||||
QueueIcon,
|
||||
SearchIcon,
|
||||
StatsIcon,
|
||||
UpdateIcon,
|
||||
WatchIcon,
|
||||
} from './icons';
|
||||
import { t, useLanguage } from '../i18n';
|
||||
|
||||
const NAV: Array<{ view: ViewName; icon: ReactNode; label: string }> = [
|
||||
{ view: 'now', icon: <PlayIcon />, label: 'Now Playing' },
|
||||
{ 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: 'watch', icon: <WatchIcon />, label: 'Watch Together' },
|
||||
{ view: 'server', icon: <GearIcon />, label: 'Server & Admin' },
|
||||
{ view: 'updates', icon: <UpdateIcon />, label: 'Updates' },
|
||||
{ view: 'rpc', icon: <CodeIcon />, label: 'RPC / API' },
|
||||
];
|
||||
|
||||
@@ -67,18 +68,22 @@ export function Sidebar() {
|
||||
|
||||
<nav className="nav">
|
||||
{NAV.filter(
|
||||
(item) => item.view !== 'server' || isAdmin
|
||||
(item) =>
|
||||
(item.view !== 'server' && item.view !== 'updates') ||
|
||||
isAdmin
|
||||
).map((item) => (
|
||||
<button
|
||||
key={item.view}
|
||||
className={
|
||||
'nav-item' + (s.view === item.view ? ' active' : '')
|
||||
'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 === 'now' && playing && (
|
||||
{item.view === 'dashboard' && playing && (
|
||||
<span className="live-dot" />
|
||||
)}
|
||||
{item.view === 'queue' && s.queue.length > 0 && (
|
||||
@@ -86,6 +91,22 @@ export function Sidebar() {
|
||||
)}
|
||||
</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">
|
||||
|
||||
@@ -0,0 +1,472 @@
|
||||
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';
|
||||
|
||||
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 }) {
|
||||
return (
|
||||
<div className="ts-admin-channel" style={{ marginLeft: depth * 16 }}>
|
||||
<div className="ts-admin-channel-head">
|
||||
<strong>{channel.name}</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,145 +0,0 @@
|
||||
import { useState } from 'react';
|
||||
import { rpc } from '../lib/rpc';
|
||||
import { send, watchStore } from '../lib/watch';
|
||||
import { toast } from '../lib/app';
|
||||
import { useStore } from '../lib/store';
|
||||
import { thumbFor } from '../lib/format';
|
||||
import type { Track } from '../lib/types';
|
||||
import { t, tf } from '../i18n';
|
||||
|
||||
// Normalize a Twitch channel entry: accept a bare login name, an @handle, or a
|
||||
// full twitch.tv URL, and reduce it to the channel login the embed player
|
||||
// expects. Numeric ids pass through (best effort — resolving them to a login
|
||||
// would need the Helix API, which isn't wired up).
|
||||
function normalizeTwitchChannel(input: string): string {
|
||||
let s = input.trim();
|
||||
const m = s.match(/twitch\.tv\/([^/?#]+)/i);
|
||||
if (m) s = m[1];
|
||||
s = s.replace(/^@/, '');
|
||||
return s.toLowerCase().replace(/[^a-z0-9_]/g, '');
|
||||
}
|
||||
|
||||
// Add tracks to a watch room from inside it. YouTube uses the unauthenticated
|
||||
// SearchTracks RPC (results added by title + thumbnail); Twitch has no search
|
||||
// backend, so it offers an add-by-channel-name/id field instead.
|
||||
export function WatchSearch({ disabled }: { disabled: boolean }) {
|
||||
const w = useStore(watchStore);
|
||||
const [query, setQuery] = useState('');
|
||||
const [channel, setChannel] = useState('');
|
||||
const [results, setResults] = useState<Track[]>([]);
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
if (w.sourceChoice === 'twitch') {
|
||||
return (
|
||||
<div className="watch-search">
|
||||
<form
|
||||
className="search-row"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const ch = normalizeTwitchChannel(channel);
|
||||
if (!ch) return;
|
||||
send({
|
||||
type: 'watch.queue.add',
|
||||
source: 'twitch',
|
||||
url: ch,
|
||||
title: ch,
|
||||
});
|
||||
toast(tf('Added “{0}” to queue', ch));
|
||||
setChannel('');
|
||||
}}
|
||||
>
|
||||
<input
|
||||
value={channel}
|
||||
onChange={(e) => setChannel(e.target.value)}
|
||||
placeholder={t(
|
||||
'Twitch channel name or id to queue…'
|
||||
)}
|
||||
autoComplete="off"
|
||||
disabled={disabled}
|
||||
/>
|
||||
<button
|
||||
className="btn btn-accent"
|
||||
type="submit"
|
||||
disabled={disabled}
|
||||
>
|
||||
{t('Add channel')}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="watch-search">
|
||||
<form
|
||||
className="search-row"
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
const q = query.trim();
|
||||
if (!q) return;
|
||||
try {
|
||||
const res = await rpc.call<{ tracks?: Track[] }>(
|
||||
'SearchTracks',
|
||||
{ query: q }
|
||||
);
|
||||
setResults((res && res.tracks) || []);
|
||||
setOpen(true);
|
||||
} catch (err) {
|
||||
toast((err as { message?: string }).message || 'error');
|
||||
}
|
||||
}}
|
||||
>
|
||||
<input
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder={t('Search YouTube to queue…')}
|
||||
autoComplete="off"
|
||||
disabled={disabled}
|
||||
/>
|
||||
<button className="btn btn-accent" type="submit" disabled={disabled}>
|
||||
{t('Search')}
|
||||
</button>
|
||||
</form>
|
||||
{open && results.length > 0 && (
|
||||
<div className="watch-search-results">
|
||||
{results.slice(0, 8).map((tr, i) => (
|
||||
<button
|
||||
key={tr.url || tr.id || i}
|
||||
className="watch-search-item"
|
||||
onClick={() => {
|
||||
send({
|
||||
type: 'watch.queue.add',
|
||||
source: 'youtube',
|
||||
url: tr.url || tr.id,
|
||||
title: tr.title || '',
|
||||
});
|
||||
toast(
|
||||
tf(
|
||||
'Added “{0}” to queue',
|
||||
tr.title || ''
|
||||
)
|
||||
);
|
||||
setOpen(false);
|
||||
setQuery('');
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="track-cover"
|
||||
style={
|
||||
thumbFor(tr)
|
||||
? {
|
||||
background: `url("${thumbFor(tr)}") center/cover`,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<span className="watch-search-title">
|
||||
{tr.title}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -57,9 +57,15 @@ export const StatsIcon = makeIcon(
|
||||
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'
|
||||
);
|
||||
@@ -76,6 +82,8 @@ 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'
|
||||
);
|
||||
|
||||
@@ -4,13 +4,14 @@
|
||||
|
||||
export const ru: Record<string, string> = {
|
||||
// Sidebar / navigation
|
||||
'Now Playing': 'Сейчас играет',
|
||||
'Dashboard': 'Панель',
|
||||
'Queue': 'Очередь',
|
||||
'Search': 'Поиск',
|
||||
'Library': 'Библиотека',
|
||||
'History & Stats': 'История и статистика',
|
||||
'Watch Together': 'Совместный просмотр',
|
||||
'Server & Admin': 'Сервер и админ',
|
||||
'Updates': 'Обновления',
|
||||
'RPC / API': 'RPC / API',
|
||||
'MUSIC BOT · TS3': 'МУЗЫКАЛЬНЫЙ БОТ · TS3',
|
||||
'Connect': 'Подключиться',
|
||||
@@ -23,18 +24,161 @@ export const ru: Record<string, string> = {
|
||||
'connected': 'подключено',
|
||||
'disconnected': 'отключено',
|
||||
'error': 'ошибка',
|
||||
'listening': 'слушают',
|
||||
|
||||
// View headers
|
||||
'What Echoion is streaming to the channel': 'Что Echoion стримит в канал',
|
||||
'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': 'История воспроизведения и статистика сервера',
|
||||
'Synced viewing room — everyone in step': 'Синхронный просмотр — все в ногу',
|
||||
'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': 'Далее',
|
||||
@@ -122,75 +266,31 @@ export const ru: Record<string, string> = {
|
||||
'{0}% skip rate': '{0}% пропусков',
|
||||
'{0} requests': '{0} запросов',
|
||||
|
||||
// Watch together
|
||||
'Nothing loaded — paste a URL above': 'Ничего не загружено — вставьте ссылку выше',
|
||||
'Twitch embeds require HTTPS — open the site via its https:// domain':
|
||||
'Встраивание Twitch требует HTTPS — откройте сайт по его https:// адресу',
|
||||
'YouTube URL to watch together': 'Ссылка YouTube для совместного просмотра',
|
||||
'Twitch channel or URL to watch together': 'Канал или ссылка Twitch для совместного просмотра',
|
||||
'Video URL': 'Видео по ссылке',
|
||||
'Embed': 'Встраивание',
|
||||
'Direct video or .m3u8 URL to watch together':
|
||||
'Прямая ссылка на видео или .m3u8 для совместного просмотра',
|
||||
'Embed URL (Kodik, etc.) to watch together':
|
||||
'Ссылка для встраивания (Kodik и др.) для совместного просмотра',
|
||||
// Shared playback and action labels
|
||||
'Load': 'Загрузить',
|
||||
'+ Queue': '+ В очередь',
|
||||
'Add to the watch queue': 'Добавить в очередь просмотра',
|
||||
'Guest — sign in to control': 'Гость — войдите, чтобы управлять',
|
||||
'You are hosting': 'Вы ведущий',
|
||||
'Viewer': 'Зритель',
|
||||
'Synced': 'Синхронно',
|
||||
'Resync': 'Синхронизировать',
|
||||
'Resynced to room': 'Синхронизировано с комнатой',
|
||||
'Live stream — cannot seek': 'Прямой эфир — перемотка недоступна',
|
||||
'LIVE': 'ЭФИР',
|
||||
'In the room': 'В комнате',
|
||||
'Room chat': 'Чат комнаты',
|
||||
'Say something…': 'Скажите что-нибудь…',
|
||||
'Send': 'Отправить',
|
||||
'Host': 'Ведущий',
|
||||
'Host only': 'Только ведущий',
|
||||
'Play next': 'Следующее',
|
||||
'(you)': '(вы)',
|
||||
'Buffering…': 'Буферизация…',
|
||||
'In sync': 'Синхронно',
|
||||
'Nothing queued — paste a URL and hit “+ Queue”': 'Очередь пуста — вставьте ссылку и нажмите «+ В очередь»',
|
||||
'Remove from queue': 'Убрать из очереди',
|
||||
'added by {0}': 'добавил {0}',
|
||||
'LIVE': 'ЭФИР',
|
||||
'Send': 'Отправить',
|
||||
'Fullscreen': 'Во весь экран',
|
||||
'Fullscreen unavailable': 'Полноэкранный режим недоступен',
|
||||
'Playback quality (best effort — YouTube may keep auto)':
|
||||
'Качество (по возможности — YouTube может оставить авто)',
|
||||
'Auto': 'Авто',
|
||||
'Not allowed': 'Недостаточно прав',
|
||||
// Watch Together protocol extensions (items 3, 4, 5)
|
||||
'New room name…': 'Название новой комнаты…',
|
||||
'Create / join': 'Создать / войти',
|
||||
'Make host': 'Назначить ведущим',
|
||||
'That viewer is no longer here': 'Этого зрителя уже нет',
|
||||
'Only signed-in viewers can host': 'Вести может только вошедший зритель',
|
||||
// Watch player & UX (items 7, 8, 16, 20)
|
||||
'Playback speed': 'Скорость воспроизведения',
|
||||
'Search YouTube to queue…': 'Найти на YouTube для очереди…',
|
||||
'Recent': 'Недавние',
|
||||
'Custom': 'Свои',
|
||||
'Custom emojis': 'Свои эмодзи',
|
||||
'Add emoji': 'Добавить эмодзи',
|
||||
'Emoji added': 'Эмодзи добавлено',
|
||||
'Emoji removed': 'Эмодзи удалено',
|
||||
'shortcode (a-z0-9_)': 'код (a-z0-9_)',
|
||||
'Choose an image file': 'Выберите файл изображения',
|
||||
'Emoji name must be 1-32 chars of a-z, 0-9, _': 'Имя: 1–32 символа a-z, 0-9, _',
|
||||
'Emoji image too large (max ~64KB)': 'Изображение слишком большое (макс ~64КБ)',
|
||||
|
||||
// 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': 'Перезапустить веб-интерфейс',
|
||||
'Stop and start the web server without touching the bot':
|
||||
'Остановить и запустить веб-сервер, не трогая бота',
|
||||
'Unsub all': 'Отписать всех',
|
||||
'No subscribers': 'Нет подписчиков',
|
||||
'Nobody online right now': 'Сейчас никого нет в сети',
|
||||
@@ -198,7 +298,6 @@ export const ru: Record<string, string> = {
|
||||
'Offline': 'Не в сети',
|
||||
'Unsub': 'Отписать',
|
||||
'Unsubscribe {0}?': 'Отписать {0}?',
|
||||
'Unsubscribed {0}': '{0} отписан',
|
||||
'Announcement to all subscribers:': 'Объявление всем подписчикам:',
|
||||
'Announcement sent': 'Объявление отправлено',
|
||||
'Configuration reloaded': 'Конфигурация перезагружена',
|
||||
@@ -210,11 +309,92 @@ export const ru: Record<string, string> = {
|
||||
'Удалить ВСЕ подписки? Это нельзя отменить.',
|
||||
'All subscriptions removed': 'Все подписки удалены',
|
||||
'Listening': 'Слушает',
|
||||
'Audit log': 'Журнал аудита',
|
||||
'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': 'Скопировать пример',
|
||||
@@ -259,22 +439,7 @@ export const ru: Record<string, string> = {
|
||||
'Menu': 'Меню',
|
||||
'Back 10 seconds': 'Назад на 10 секунд',
|
||||
'Forward 10 seconds': 'Вперёд на 10 секунд',
|
||||
'Leave room': 'Покинуть комнату',
|
||||
'Leave this room': 'Покинуть эту комнату',
|
||||
'Room': 'Комната',
|
||||
'Watch together': 'Смотреть вместе',
|
||||
'Refresh rooms': 'Обновить список комнат',
|
||||
'Join a room to watch in sync, or create your own.':
|
||||
'Войдите в комнату для синхронного просмотра или создайте свою.',
|
||||
'No active rooms yet — create one below.':
|
||||
'Активных комнат пока нет — создайте свою ниже.',
|
||||
'{0} watching': '{0} смотрят',
|
||||
'Tap to unmute': 'Нажмите, чтобы включить звук',
|
||||
'Add channel': 'Добавить канал',
|
||||
'Twitch channel name or id to queue…': 'Имя или ID Twitch-канала для очереди…',
|
||||
'Clear queue': 'Очистить очередь',
|
||||
'Watch queue is full': 'Очередь просмотра заполнена',
|
||||
'Watch queue is empty': 'Очередь просмотра пуста',
|
||||
'Confirm': 'Подтвердить',
|
||||
'OK': 'ОК',
|
||||
'Save': 'Сохранить',
|
||||
@@ -286,17 +451,5 @@ export const ru: Record<string, string> = {
|
||||
'Playlist name': 'Название плейлиста',
|
||||
'Save playlist': 'Сохранить плейлист',
|
||||
|
||||
// Controllable embeds (Kodik / Playerjs)
|
||||
'Embed synced': 'Встраиваемый плеер синхронизирован',
|
||||
'Embed is view-only': 'Встраиваемый плеер — только просмотр',
|
||||
'Settings': 'Настройки',
|
||||
'Local': 'Локально',
|
||||
'Quality': 'Качество',
|
||||
'Speed': 'Скорость',
|
||||
'Voiceover': 'Озвучка',
|
||||
'Episode': 'Серия',
|
||||
'Subtitles': 'Субтитры',
|
||||
'Off': 'Выкл.',
|
||||
'Choose': 'Выбрать',
|
||||
'Only the host can change this': 'Изменять может только ведущий',
|
||||
'Add': 'Добавить',
|
||||
};
|
||||
@@ -5,10 +5,9 @@
|
||||
import { rpc, type RpcMethodName } from './rpc';
|
||||
import { Store } from './store';
|
||||
import { t, tf, setLanguage, getLanguage } from '../i18n';
|
||||
import { setWatchName } from './watch';
|
||||
import { loadCustomEmojis } from './emoji';
|
||||
import type {
|
||||
Identity,
|
||||
PublicDashboard,
|
||||
QueueEntry,
|
||||
ServerInfo,
|
||||
Status,
|
||||
@@ -17,13 +16,13 @@ import type {
|
||||
} from './types';
|
||||
|
||||
export type ViewName =
|
||||
| 'now'
|
||||
| 'dashboard'
|
||||
| 'queue'
|
||||
| 'search'
|
||||
| 'library'
|
||||
| 'stats'
|
||||
| 'watch'
|
||||
| 'server'
|
||||
| 'updates'
|
||||
| 'rpc';
|
||||
|
||||
export interface AppState {
|
||||
@@ -41,6 +40,8 @@ export interface AppState {
|
||||
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.
|
||||
@@ -50,10 +51,14 @@ export interface AppState {
|
||||
// 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: 'now',
|
||||
view: 'dashboard',
|
||||
connection: 'disconnected',
|
||||
identity: null,
|
||||
status: null,
|
||||
@@ -67,10 +72,16 @@ export const appStore = new Store<AppState>({
|
||||
durationMs: 0,
|
||||
onlineCount: 0,
|
||||
listeners: [],
|
||||
publicDashboard: null,
|
||||
watchUrl: '',
|
||||
toast: null,
|
||||
nowPlayingVideoAllowed: true,
|
||||
shortcutsOpen: false,
|
||||
sidebarOpen: false,
|
||||
capabilities: {
|
||||
plugins: false,
|
||||
webExtensions: false,
|
||||
},
|
||||
});
|
||||
|
||||
// ── toast ────────────────────────────────────────────────────────────────────
|
||||
@@ -123,9 +134,7 @@ export async function changeLanguage(language: 'en' | 'ru') {
|
||||
export function applyIdentity(auth: Identity | null) {
|
||||
appStore.set({ identity: auth });
|
||||
if (auth) {
|
||||
setWatchName(auth.nickname || null);
|
||||
void loadUserPrefs();
|
||||
void loadCustomEmojis();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,6 +184,7 @@ export async function connectWithToken(tokenInput: string) {
|
||||
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();
|
||||
@@ -209,9 +219,6 @@ 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.
|
||||
// The watch view owns its own #watch/<room> hash (see watch.ts), so a
|
||||
// re-selection never clobbers an existing room deep link.
|
||||
if (view === 'watch' && location.hash.startsWith('#watch')) return;
|
||||
const target = `#${view}`;
|
||||
if (location.hash !== target) location.hash = target;
|
||||
}
|
||||
@@ -274,6 +281,47 @@ export async function loadFavorites() {
|
||||
// ── 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;
|
||||
@@ -282,24 +330,29 @@ export function boot() {
|
||||
// Apply the persisted language before anything renders text.
|
||||
setLanguage(getLanguage(), false);
|
||||
|
||||
// Server config: the Now Playing video preview can be disabled globally.
|
||||
// Server config: the video preview policy and external VoidWatch link.
|
||||
fetch('/config.json')
|
||||
.then((r) => r.json())
|
||||
.then((cfg) => {
|
||||
if (cfg && cfg.nowPlayingVideo === false) {
|
||||
appStore.set({ nowPlayingVideoAllowed: false });
|
||||
}
|
||||
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'));
|
||||
};
|
||||
@@ -334,6 +387,9 @@ export function boot() {
|
||||
});
|
||||
}
|
||||
});
|
||||
rpc.on('plugins.updated', () => {
|
||||
if (appStore.get().capabilities.webExtensions) void loadWebExtensions();
|
||||
});
|
||||
|
||||
// Local 1s ticker keeps the progress bar moving between server updates.
|
||||
setInterval(() => {
|
||||
@@ -360,6 +416,92 @@ export function boot() {
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -54,10 +54,53 @@ const RPC_METHOD_BY_INDEX: readonly string[] = [
|
||||
'ToggleAutoplay',
|
||||
'GetUserPrefs',
|
||||
'SetUserPrefs',
|
||||
'GetCustomEmojis',
|
||||
'AddCustomEmoji', // 50
|
||||
'RemoveCustomEmoji',
|
||||
'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 {
|
||||
|
||||
@@ -1,254 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { EMBED_PROTOCOLS, prepareEmbedUrl } from './embedProtocols';
|
||||
|
||||
const byName = (name: string) => EMBED_PROTOCOLS.find((p) => p.name === name)!;
|
||||
const kodik = byName('kodik');
|
||||
const playerjs = byName('playerjs');
|
||||
const alloha = byName('alloha');
|
||||
const vimeo = byName('vimeo');
|
||||
const playerjsSpec = byName('player.js');
|
||||
const rutube = byName('rutube');
|
||||
const dailymotion = byName('dailymotion');
|
||||
const vk = byName('vk');
|
||||
|
||||
describe('kodik parse', () => {
|
||||
it('parses JSON-string time updates', () => {
|
||||
expect(
|
||||
kodik.parse(
|
||||
JSON.stringify({ key: 'kodik_player_time_update', value: 42.5 })
|
||||
)
|
||||
).toEqual({ kind: 'time', seconds: 42.5 });
|
||||
});
|
||||
|
||||
it('parses duration and play/pause/ended state', () => {
|
||||
expect(
|
||||
kodik.parse({ key: 'kodik_player_duration_update', value: 1440 })
|
||||
).toEqual({ kind: 'duration', seconds: 1440 });
|
||||
expect(kodik.parse({ key: 'kodik_player_play' })).toEqual({ kind: 'play' });
|
||||
expect(kodik.parse({ key: 'kodik_player_pause' })).toEqual({
|
||||
kind: 'pause',
|
||||
});
|
||||
expect(kodik.parse({ key: 'kodik_player_video_ended' })).toEqual({
|
||||
kind: 'ended',
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects everything else', () => {
|
||||
expect(kodik.parse('garbage')).toBeNull();
|
||||
expect(kodik.parse('{"broken json')).toBeNull();
|
||||
expect(kodik.parse({ event: 'time', answer: 3 })).toBeNull();
|
||||
expect(kodik.parse(null)).toBeNull();
|
||||
expect(kodik.parse(42)).toBeNull();
|
||||
});
|
||||
|
||||
it('is hostname-pinned and seeks by reloading with start_from', () => {
|
||||
expect(kodik.matchUrl!('https://kodikplayer.com/seria/1/hash/720p')).toBe(
|
||||
true
|
||||
);
|
||||
expect(kodik.matchUrl!('https://kodik.info/video/1/hash/720p')).toBe(true);
|
||||
expect(kodik.matchUrl!('https://youtube.com/x')).toBe(false);
|
||||
// start_from is set (overwritten) while signed params are preserved.
|
||||
const seeked = kodik.reloadSeek!(
|
||||
'https://kodikplayer.com/seria/1/hash/720p?d_sign=abc&start_from=5',
|
||||
42.9
|
||||
);
|
||||
expect(seeked).toContain('start_from=42');
|
||||
expect(seeked).toContain('d_sign=abc');
|
||||
expect(seeked).not.toContain('start_from=5');
|
||||
});
|
||||
});
|
||||
|
||||
describe('playerjs.com parse', () => {
|
||||
it('parses object and JSON-string events', () => {
|
||||
expect(playerjs.parse({ event: 'time', answer: 12 })).toEqual({
|
||||
kind: 'time',
|
||||
seconds: 12,
|
||||
});
|
||||
expect(
|
||||
playerjs.parse(JSON.stringify({ event: 'duration', answer: 600 }))
|
||||
).toEqual({ kind: 'duration', seconds: 600 });
|
||||
expect(playerjs.parse({ event: 'end' })).toEqual({ kind: 'ended' });
|
||||
});
|
||||
|
||||
it('does not lock on player.js-spec or unknown shapes', () => {
|
||||
expect(playerjs.parse({ context: 'player.js', event: 'play' })).toBeNull();
|
||||
expect(playerjs.parse({ event: 'infoDelivery' })).toBeNull();
|
||||
expect(playerjs.parse({ key: 'kodik_player_play' })).toBeNull();
|
||||
});
|
||||
|
||||
it('normalizes quality, voiceover and subtitle capabilities', () => {
|
||||
expect(
|
||||
playerjs.parse({
|
||||
event: 'qualities',
|
||||
answer: [{ id: '720', name: '720p' }, '1080p'],
|
||||
})
|
||||
).toMatchObject({
|
||||
kind: 'extraList',
|
||||
control: { id: 'quality', scope: 'local' },
|
||||
});
|
||||
expect(
|
||||
playerjs.parse({
|
||||
event: 'audiotracks',
|
||||
answer: { ru: 'Russian', en: 'English' },
|
||||
})
|
||||
).toMatchObject({
|
||||
kind: 'extraList',
|
||||
control: { id: 'audiotrack', scope: 'synced' },
|
||||
});
|
||||
expect(playerjs.parse({ event: 'subtitle', answer: 1 })).toEqual({
|
||||
kind: 'extraCurrent',
|
||||
id: 'subtitle',
|
||||
value: '1',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('alloha detection', () => {
|
||||
it('pins known Alloha player hosts', () => {
|
||||
expect(alloha.matchUrl!('https://alloha.tv/embed/123')).toBe(true);
|
||||
expect(alloha.matchUrl!('https://cdn.allarknow.online/player')).toBe(true);
|
||||
expect(alloha.matchUrl!('https://example.com/player')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('vimeo parse', () => {
|
||||
it('parses timeupdate with bundled duration and the getDuration reply', () => {
|
||||
expect(
|
||||
vimeo.parse({ event: 'timeupdate', data: { seconds: 10, duration: 200 } })
|
||||
).toEqual({ kind: 'time', seconds: 10, duration: 200 });
|
||||
expect(vimeo.parse({ method: 'getDuration', value: 200 })).toEqual({
|
||||
kind: 'duration',
|
||||
seconds: 200,
|
||||
});
|
||||
expect(vimeo.parse({ event: 'play' })).toEqual({ kind: 'play' });
|
||||
});
|
||||
|
||||
it('does not lock on a playerjs.com message (has `answer`) or garbage', () => {
|
||||
expect(vimeo.parse({ event: 'play', answer: 1 })).toBeNull();
|
||||
expect(vimeo.parse('garbage')).toBeNull();
|
||||
expect(vimeo.parse({ event: 'infoDelivery' })).toBeNull();
|
||||
});
|
||||
|
||||
it('matchUrl selects vimeo hosts only', () => {
|
||||
expect(vimeo.matchUrl!('https://player.vimeo.com/video/123')).toBe(true);
|
||||
expect(vimeo.matchUrl!('https://vimeo.com/123')).toBe(true);
|
||||
expect(vimeo.matchUrl!('https://youtube.com/watch?v=x')).toBe(false);
|
||||
});
|
||||
|
||||
it('prepareUrl hides native chrome', () => {
|
||||
const p = vimeo.prepareUrl!('https://player.vimeo.com/video/123');
|
||||
expect(p).toContain('controls=0');
|
||||
expect(p).toContain('title=0');
|
||||
});
|
||||
});
|
||||
|
||||
describe('player.js (embedly spec) parse', () => {
|
||||
it('parses context-tagged events', () => {
|
||||
expect(
|
||||
playerjsSpec.parse({
|
||||
context: 'player.js',
|
||||
event: 'timeupdate',
|
||||
value: { seconds: 5, duration: 100 },
|
||||
})
|
||||
).toEqual({ kind: 'time', seconds: 5, duration: 100 });
|
||||
expect(
|
||||
playerjsSpec.parse({ context: 'player.js', event: 'pause' })
|
||||
).toEqual({ kind: 'pause' });
|
||||
expect(playerjsSpec.parse({ context: 'player.js', event: 'ready' })).toEqual(
|
||||
{ kind: 'hello' }
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects messages without the player.js context', () => {
|
||||
expect(playerjsSpec.parse({ event: 'play' })).toBeNull();
|
||||
expect(playerjsSpec.parse('garbage')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('rutube parse + matchUrl', () => {
|
||||
it('parses player:* events', () => {
|
||||
expect(
|
||||
rutube.parse(
|
||||
JSON.stringify({ type: 'player:currentTime', data: { time: 30 } })
|
||||
)
|
||||
).toEqual({ kind: 'time', seconds: 30 });
|
||||
expect(
|
||||
rutube.parse({ type: 'player:changeState', data: { state: 'playing' } })
|
||||
).toEqual({ kind: 'play' });
|
||||
expect(
|
||||
rutube.parse({ type: 'player:durationChange', data: { duration: 90 } })
|
||||
).toEqual({ kind: 'duration', seconds: 90 });
|
||||
});
|
||||
|
||||
it('ignores foreign messages', () => {
|
||||
expect(rutube.parse({ event: 'play', answer: 1 })).toBeNull();
|
||||
expect(rutube.parse({ key: 'kodik_player_play' })).toBeNull();
|
||||
expect(rutube.matchUrl!('https://rutube.ru/play/embed/123')).toBe(true);
|
||||
expect(rutube.matchUrl!('https://vimeo.com/1')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('dailymotion parse + prepareUrl', () => {
|
||||
it('parses classic querystring events', () => {
|
||||
expect(dailymotion.parse('event=timeupdate&time=12&duration=240')).toEqual(
|
||||
{ kind: 'time', seconds: 12, duration: 240 }
|
||||
);
|
||||
expect(dailymotion.parse('event=pause')).toEqual({ kind: 'pause' });
|
||||
expect(dailymotion.parse('event=video_end')).toEqual({ kind: 'ended' });
|
||||
expect(dailymotion.parse({ event: 'play' })).toBeNull();
|
||||
});
|
||||
|
||||
it('matchUrl + prepareUrl inject api=postMessage and preserve params', () => {
|
||||
expect(dailymotion.matchUrl!('https://www.dailymotion.com/embed/video/x'))
|
||||
.toBe(true);
|
||||
expect(dailymotion.matchUrl!('https://dai.ly/x')).toBe(true);
|
||||
const prepared = dailymotion.prepareUrl!(
|
||||
'https://www.dailymotion.com/embed/video/x?foo=1'
|
||||
);
|
||||
expect(prepared).toContain('api=postMessage');
|
||||
expect(prepared).toContain('controls=0');
|
||||
expect(prepared).toContain('foo=1');
|
||||
// idempotent
|
||||
expect(dailymotion.prepareUrl!(prepared)).toBe(prepared);
|
||||
});
|
||||
});
|
||||
|
||||
describe('vk parse + prepareUrl', () => {
|
||||
it('parses player_api events', () => {
|
||||
expect(
|
||||
vk.parse({ type: 'player_api', event: 'timeupdate', time: 8, duration: 60 })
|
||||
).toEqual({ kind: 'time', seconds: 8, duration: 60 });
|
||||
expect(vk.parse({ type: 'player_api', event: 'started' })).toEqual({
|
||||
kind: 'play',
|
||||
});
|
||||
expect(vk.parse({ type: 'player_api', event: 'paused' })).toEqual({
|
||||
kind: 'pause',
|
||||
});
|
||||
});
|
||||
|
||||
it('ignores foreign messages and injects js_api=1', () => {
|
||||
expect(vk.parse({ event: 'play', answer: 1 })).toBeNull();
|
||||
expect(vk.matchUrl!('https://vk.com/video_ext.php?oid=1')).toBe(true);
|
||||
expect(vk.matchUrl!('https://vkvideo.ru/video_ext.php?oid=1')).toBe(true);
|
||||
expect(vk.prepareUrl!('https://vk.com/video_ext.php?oid=1')).toContain(
|
||||
'js_api=1'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('registry order + prepareEmbedUrl', () => {
|
||||
it('generic (content-detected) set is player.js then playerjs', () => {
|
||||
expect(
|
||||
EMBED_PROTOCOLS.filter((p) => !p.matchUrl).map((p) => p.name)
|
||||
).toEqual(['player.js', 'playerjs']);
|
||||
});
|
||||
|
||||
it('prepareEmbedUrl applies hostname-matched params, leaves others alone', () => {
|
||||
expect(
|
||||
prepareEmbedUrl('https://www.dailymotion.com/embed/video/x')
|
||||
).toContain('api=postMessage');
|
||||
expect(prepareEmbedUrl('https://kodik.info/seria/1/hash/720p')).toBe(
|
||||
'https://kodik.info/seria/1/hash/720p'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,972 +0,0 @@
|
||||
// Adapters for postMessage-controllable embed players in the Watch view.
|
||||
//
|
||||
// A generic iframe can only be driven if the player inside exposes a
|
||||
// postMessage API — everything else stays view-only by browser design.
|
||||
// Protocols supported (each is one self-contained entry in EMBED_PROTOCOLS):
|
||||
// - kodik: JSON *strings* like {key:'kodik_player_time_update', value:sec};
|
||||
// commands {key:'kodik_player_api', value:{method}}.
|
||||
// - vimeo: {method:'play'|...} strings; events {event:'timeupdate',
|
||||
// data:{seconds,duration}}. Hostname-selected (player.vimeo.com).
|
||||
// - rutube / dailymotion / vk: hostname-selected; some need opt-in URL
|
||||
// params (prepareUrl) and their command/event shapes are community-
|
||||
// documented — flagged VERIFY, one-line fixes if a live embed differs.
|
||||
// - player.js (embedly spec): {context:'player.js', ...} — Wistia & co.
|
||||
// - playerjs (playerjs.com, many CIS hosters): {api:'play'|...} commands,
|
||||
// {event, answer} events.
|
||||
// Shapes marked VERIFY are community-documented, not official; dev builds
|
||||
// console.debug every unrecognized frame message to reverse-engineer them.
|
||||
//
|
||||
// Detection: for a hostname-matched player only that protocol is probed;
|
||||
// otherwise the generic set is probed until one `parse` recognizes a message
|
||||
// and locks the adapter. On timeout the embed is uncontrollable and the
|
||||
// caller keeps today's host-driven view-only behavior.
|
||||
|
||||
export interface EmbedAdapter {
|
||||
protocol: string;
|
||||
// True for players (Kodik) driven by reloading the iframe rather than
|
||||
// postMessage commands: the caller should avoid drift-reconcile churn and
|
||||
// not expect pause to work.
|
||||
reloadBased: boolean;
|
||||
play(): void;
|
||||
pause(): void;
|
||||
seekMs(ms: number): void;
|
||||
setVolume(v01: number): void; // 0..1
|
||||
positionMs(): number;
|
||||
durationMs(): number;
|
||||
paused(): boolean;
|
||||
extras(): PlayerExtraControl[];
|
||||
setExtra(id: string, value: string): void;
|
||||
destroy(): void;
|
||||
}
|
||||
|
||||
export interface ExtraControlOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface PlayerExtraControl {
|
||||
id: string;
|
||||
label: string;
|
||||
kind: 'select' | 'button';
|
||||
options: ExtraControlOption[];
|
||||
current: string | null;
|
||||
scope: 'local' | 'synced';
|
||||
}
|
||||
|
||||
// Fired only for events NOT caused by our own commands (see suppression
|
||||
// below) — i.e. gestures made inside the embed UI, which the host must relay
|
||||
// to the room.
|
||||
export interface EmbedCallbacks {
|
||||
onPlay(positionMs: number): void;
|
||||
onPause(positionMs: number): void;
|
||||
onSeek(positionMs: number): void;
|
||||
onDurationChange(durationMs: number): void;
|
||||
onEnded(): void;
|
||||
onExtraControls(controls: PlayerExtraControl[]): void;
|
||||
}
|
||||
|
||||
export type EmbedEvent =
|
||||
// `duration` piggybacks on time events for players (Vimeo, player.js, DM,
|
||||
// VK) that bundle it into their timeupdate payload.
|
||||
| { kind: 'time'; seconds: number; duration?: number }
|
||||
| { kind: 'duration'; seconds: number }
|
||||
| { kind: 'play' }
|
||||
| { kind: 'pause' }
|
||||
| { kind: 'ended' }
|
||||
| { kind: 'extraList'; control: PlayerExtraControl }
|
||||
| { kind: 'extraCurrent'; id: string; value: string }
|
||||
// Recognized the protocol but the event carries no state we track; enough
|
||||
// to lock detection.
|
||||
| { kind: 'hello' };
|
||||
|
||||
export interface ProtocolDef {
|
||||
name: string;
|
||||
// Hostname-based selection: when a URL matches, only this protocol is
|
||||
// probed (skips content-based detection). Left undefined for generic
|
||||
// protocols detected purely by the messages they emit (kodik, player.js).
|
||||
matchUrl?(url: string): boolean;
|
||||
// Inject opt-in query params the player needs before the iframe loads
|
||||
// (e.g. Dailymotion `?api=postMessage`, VK `?js_api=1`).
|
||||
prepareUrl?(url: string): string;
|
||||
// Some players (Kodik) expose no postMessage command API — the only way to
|
||||
// seek is to reload the iframe at a start offset. When present, the adapter
|
||||
// seeks by setting frame.src to this URL instead of posting a command.
|
||||
reloadSeek?(currentSrc: string, seconds: number): string;
|
||||
probe(win: Window): void;
|
||||
parse(data: unknown): EmbedEvent | null;
|
||||
play(win: Window): void;
|
||||
pause(win: Window): void;
|
||||
seek(win: Window, seconds: number): void;
|
||||
volume(win: Window, v01: number): void;
|
||||
probeExtras?(win: Window): void;
|
||||
setExtra?(win: Window, id: string, value: string): void;
|
||||
staticExtras?(url: string): PlayerExtraControl[];
|
||||
}
|
||||
|
||||
// Embeds are served from many mirror domains (esp. Kodik), so the target
|
||||
// origin can't be pinned; we never trust incoming data beyond parsing known
|
||||
// shapes into numbers.
|
||||
function post(win: Window, msg: unknown) {
|
||||
try {
|
||||
win.postMessage(msg, '*');
|
||||
} catch {
|
||||
/* frame navigating/gone */
|
||||
}
|
||||
}
|
||||
|
||||
const asNumber = (v: unknown): number =>
|
||||
typeof v === 'number' ? v : Number(v);
|
||||
|
||||
// Embed URLs are absolute, so no base is needed; guard `location` so the
|
||||
// helpers also work under the node test runner.
|
||||
const baseHref = (): string | undefined =>
|
||||
typeof location !== 'undefined' ? location.href : undefined;
|
||||
|
||||
function hostOf(url: string): string {
|
||||
try {
|
||||
return new URL(url, baseHref()).hostname.toLowerCase();
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function isHostOrSubdomain(host: string, domain: string): boolean {
|
||||
return host === domain || host.endsWith(`.${domain}`);
|
||||
}
|
||||
|
||||
function withParams(url: string, params: Record<string, string>): string {
|
||||
try {
|
||||
const u = new URL(url, baseHref());
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
if (!u.searchParams.has(k)) u.searchParams.set(k, v);
|
||||
}
|
||||
return u.toString();
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
// Overwrite a single query param (preserves the rest, incl. Kodik's signed
|
||||
// d_sign/ref_sign params).
|
||||
function setParam(url: string, key: string, value: string): string {
|
||||
try {
|
||||
const u = new URL(url, baseHref());
|
||||
u.searchParams.set(key, value);
|
||||
return u.toString();
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize an object-or-JSON-string payload into a plain object, or null.
|
||||
function asObj(data: unknown): Record<string, unknown> | null {
|
||||
let obj: unknown = data;
|
||||
if (typeof data === 'string') {
|
||||
const s = data.trim();
|
||||
if (!s.startsWith('{') && !s.startsWith('[')) return null;
|
||||
try {
|
||||
obj = JSON.parse(s);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return obj && typeof obj === 'object'
|
||||
? (obj as Record<string, unknown>)
|
||||
: null;
|
||||
}
|
||||
|
||||
function toOptions(value: unknown): ExtraControlOption[] {
|
||||
const entries = Array.isArray(value)
|
||||
? value.map((item, index) => [String(index), item] as const)
|
||||
: value && typeof value === 'object'
|
||||
? Object.entries(value as Record<string, unknown>)
|
||||
: [];
|
||||
return entries.flatMap(([fallback, item]) => {
|
||||
if (item && typeof item === 'object') {
|
||||
const option = item as Record<string, unknown>;
|
||||
const raw = option.value ?? option.id ?? option.index ?? fallback;
|
||||
const label = option.label ?? option.name ?? option.title ?? raw;
|
||||
return [{ value: String(raw), label: String(label) }];
|
||||
}
|
||||
return item == null
|
||||
? []
|
||||
: [{ value: fallback, label: String(item) }];
|
||||
});
|
||||
}
|
||||
|
||||
function extraControl(
|
||||
id: string,
|
||||
label: string,
|
||||
scope: PlayerExtraControl['scope'],
|
||||
options: ExtraControlOption[],
|
||||
current: string | null = null
|
||||
): PlayerExtraControl {
|
||||
return { id, label, scope, options, current, kind: 'select' };
|
||||
}
|
||||
|
||||
const kodik: ProtocolDef = {
|
||||
name: 'kodik',
|
||||
// Kodik (kodikplayer.com and its mirrors). Hostname-pinned so it always
|
||||
// locks as `kodik` and never falls back to view-only.
|
||||
matchUrl: (url) => {
|
||||
const host = hostOf(url);
|
||||
return ['kodik.info', 'kodik.cc', 'kodik.biz', 'kodik.online', 'kodikplayer.com']
|
||||
.some((domain) => isHostOrSubdomain(host, domain));
|
||||
},
|
||||
// Kodik has NO postMessage command API — the only way to seek is to reload
|
||||
// the iframe at a start offset (preserving its signed params). start_from
|
||||
// auto-resumes playback from that second.
|
||||
reloadSeek: (src, seconds) =>
|
||||
setParam(src, 'start_from', String(Math.max(0, Math.floor(seconds)))),
|
||||
probe(win) {
|
||||
// Community-documented; harmless if ignored by the player.
|
||||
post(win, { key: 'kodik_player_api', value: { method: 'get_duration' } });
|
||||
post(win, { key: 'kodik_player_api', value: { method: 'get_time' } });
|
||||
},
|
||||
parse(data) {
|
||||
let obj: unknown = data;
|
||||
if (typeof data === 'string') {
|
||||
if (!data.includes('kodik_player')) return null;
|
||||
try {
|
||||
obj = JSON.parse(data);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const m = obj as { key?: unknown; value?: unknown } | null;
|
||||
if (!m || typeof m.key !== 'string' || !m.key.startsWith('kodik_player')) {
|
||||
return null;
|
||||
}
|
||||
const n = asNumber(m.value);
|
||||
switch (m.key) {
|
||||
case 'kodik_player_time_update':
|
||||
case 'kodik_player_current_time':
|
||||
return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' };
|
||||
case 'kodik_player_duration_update':
|
||||
case 'kodik_player_duration':
|
||||
return isFinite(n) && n > 0
|
||||
? { kind: 'duration', seconds: n }
|
||||
: { kind: 'hello' };
|
||||
case 'kodik_player_play':
|
||||
return { kind: 'play' };
|
||||
case 'kodik_player_pause':
|
||||
return { kind: 'pause' };
|
||||
case 'kodik_player_video_ended':
|
||||
return { kind: 'ended' };
|
||||
default:
|
||||
// Unmapped kodik_player_* event — still unambiguously Kodik.
|
||||
return { kind: 'hello' };
|
||||
}
|
||||
},
|
||||
play: (win) => post(win, { key: 'kodik_player_api', value: { method: 'play' } }),
|
||||
pause: (win) => post(win, { key: 'kodik_player_api', value: { method: 'pause' } }),
|
||||
seek: (win, seconds) =>
|
||||
post(win, { key: 'kodik_player_api', value: { method: 'seek', seconds } }),
|
||||
volume: (win, v01) =>
|
||||
post(win, {
|
||||
key: 'kodik_player_api',
|
||||
value: { method: 'change_volume', volume: v01 },
|
||||
}),
|
||||
};
|
||||
|
||||
const playerjs: ProtocolDef = {
|
||||
name: 'playerjs',
|
||||
probe(win) {
|
||||
post(win, { api: 'duration' });
|
||||
post(win, { api: 'time' });
|
||||
},
|
||||
probeExtras(win) {
|
||||
for (const api of ['qualities', 'audiotracks', 'subtitles']) {
|
||||
post(win, { api });
|
||||
}
|
||||
},
|
||||
staticExtras() {
|
||||
return [
|
||||
extraControl(
|
||||
'speed',
|
||||
'Speed',
|
||||
'synced',
|
||||
[0.5, 0.75, 1, 1.25, 1.5, 1.75, 2].map((speed) => ({
|
||||
value: String(speed),
|
||||
label: `${speed}×`,
|
||||
})),
|
||||
'1'
|
||||
),
|
||||
];
|
||||
},
|
||||
parse(data) {
|
||||
let obj: unknown = data;
|
||||
if (typeof data === 'string') {
|
||||
if (!data.startsWith('{')) return null;
|
||||
try {
|
||||
obj = JSON.parse(data);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const m = obj as
|
||||
| { event?: unknown; answer?: unknown; context?: unknown }
|
||||
| null;
|
||||
if (!m || typeof m.event !== 'string') return null;
|
||||
// A {context:'player.js'} message belongs to the embedly spec adapter,
|
||||
// not this one.
|
||||
if (m.context === 'player.js') return null;
|
||||
const n = asNumber(m.answer);
|
||||
// Only lock on events Playerjs actually emits — a bare {event:...}
|
||||
// could belong to some other player's protocol.
|
||||
switch (m.event) {
|
||||
case 'qualities':
|
||||
return {
|
||||
kind: 'extraList',
|
||||
control: extraControl(
|
||||
'quality',
|
||||
'Quality',
|
||||
'local',
|
||||
toOptions(m.answer)
|
||||
),
|
||||
};
|
||||
case 'audiotracks':
|
||||
return {
|
||||
kind: 'extraList',
|
||||
control: extraControl(
|
||||
'audiotrack',
|
||||
'Voiceover',
|
||||
'synced',
|
||||
toOptions(m.answer)
|
||||
),
|
||||
};
|
||||
case 'subtitles':
|
||||
return {
|
||||
kind: 'extraList',
|
||||
control: extraControl(
|
||||
'subtitle',
|
||||
'Subtitles',
|
||||
'local',
|
||||
[
|
||||
{ value: '-1', label: 'Off' },
|
||||
...toOptions(m.answer),
|
||||
]
|
||||
),
|
||||
};
|
||||
case 'episodes':
|
||||
return {
|
||||
kind: 'extraList',
|
||||
control: extraControl(
|
||||
'episode',
|
||||
'Episode',
|
||||
'synced',
|
||||
toOptions(m.answer)
|
||||
),
|
||||
};
|
||||
case 'quality':
|
||||
case 'audiotrack':
|
||||
case 'subtitle':
|
||||
case 'speed':
|
||||
case 'episode':
|
||||
return {
|
||||
kind: 'extraCurrent',
|
||||
id: m.event,
|
||||
value: String(m.answer ?? ''),
|
||||
};
|
||||
case 'time':
|
||||
case 'updatetime':
|
||||
return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' };
|
||||
case 'duration':
|
||||
return isFinite(n) && n > 0
|
||||
? { kind: 'duration', seconds: n }
|
||||
: { kind: 'hello' };
|
||||
case 'play':
|
||||
return { kind: 'play' };
|
||||
case 'pause':
|
||||
return { kind: 'pause' };
|
||||
case 'end':
|
||||
case 'ended':
|
||||
return { kind: 'ended' };
|
||||
case 'init':
|
||||
case 'inited':
|
||||
case 'ready':
|
||||
case 'volume':
|
||||
return { kind: 'hello' };
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
},
|
||||
play: (win) => post(win, { api: 'play' }),
|
||||
pause: (win) => post(win, { api: 'pause' }),
|
||||
seek: (win, seconds) => post(win, { api: 'seek', set: seconds }),
|
||||
volume: (win, v01) => post(win, { api: 'volume', set: v01 }),
|
||||
setExtra: (win, id, value) => {
|
||||
if (!['quality', 'audiotrack', 'subtitle', 'speed', 'episode', 'next', 'prev'].includes(id)) {
|
||||
return;
|
||||
}
|
||||
post(win, { api: id, set: value });
|
||||
},
|
||||
};
|
||||
|
||||
const alloha: ProtocolDef = {
|
||||
...playerjs,
|
||||
name: 'alloha',
|
||||
matchUrl: (url) =>
|
||||
['alloha.tv', 'alloha.video', 'alloha.online', 'allarknow.online'].some(
|
||||
(domain) => isHostOrSubdomain(hostOf(url), domain)
|
||||
),
|
||||
};
|
||||
|
||||
// Vimeo (vimeo/player.js): well documented. Selected by hostname; disambiguated
|
||||
// from playerjs.com by carrying `data`, not `answer`.
|
||||
const vimeo: ProtocolDef = {
|
||||
name: 'vimeo',
|
||||
matchUrl: (url) => /(^|\.)vimeo\.com$/.test(hostOf(url)),
|
||||
// Our overlay bar is the only control surface, so hide Vimeo's native chrome.
|
||||
prepareUrl: (url) =>
|
||||
withParams(url, {
|
||||
controls: '0',
|
||||
title: '0',
|
||||
byline: '0',
|
||||
portrait: '0',
|
||||
}),
|
||||
probe(win) {
|
||||
for (const ev of ['timeupdate', 'play', 'pause', 'ended']) {
|
||||
post(win, JSON.stringify({ method: 'addEventListener', value: ev }));
|
||||
}
|
||||
post(win, JSON.stringify({ method: 'getDuration' }));
|
||||
},
|
||||
probeExtras(win) {
|
||||
post(win, JSON.stringify({ method: 'getQualities' }));
|
||||
},
|
||||
parse(data) {
|
||||
const m = asObj(data);
|
||||
if (!m) return null;
|
||||
if (m.method === 'getDuration') {
|
||||
const n = asNumber(m.value);
|
||||
return isFinite(n) && n > 0
|
||||
? { kind: 'duration', seconds: n }
|
||||
: { kind: 'hello' };
|
||||
}
|
||||
if (m.method === 'getQualities') {
|
||||
return {
|
||||
kind: 'extraList',
|
||||
control: extraControl(
|
||||
'quality',
|
||||
'Quality',
|
||||
'local',
|
||||
toOptions(m.value)
|
||||
),
|
||||
};
|
||||
}
|
||||
if (typeof m.event !== 'string') return null;
|
||||
if ('answer' in m) return null; // that's a playerjs.com message
|
||||
const d = (m.data ?? {}) as { seconds?: unknown; duration?: unknown };
|
||||
switch (m.event) {
|
||||
case 'timeupdate': {
|
||||
const sec = asNumber(d.seconds);
|
||||
const dur = asNumber(d.duration);
|
||||
return isFinite(sec)
|
||||
? {
|
||||
kind: 'time',
|
||||
seconds: sec,
|
||||
duration: isFinite(dur) && dur > 0 ? dur : undefined,
|
||||
}
|
||||
: { kind: 'hello' };
|
||||
}
|
||||
case 'play':
|
||||
return { kind: 'play' };
|
||||
case 'pause':
|
||||
return { kind: 'pause' };
|
||||
case 'ended':
|
||||
case 'finish':
|
||||
return { kind: 'ended' };
|
||||
case 'ready':
|
||||
case 'loaded':
|
||||
return { kind: 'hello' };
|
||||
default:
|
||||
return null; // bare {event} without vimeo markers → not ours
|
||||
}
|
||||
},
|
||||
play: (w) => post(w, JSON.stringify({ method: 'play' })),
|
||||
pause: (w) => post(w, JSON.stringify({ method: 'pause' })),
|
||||
seek: (w, s) =>
|
||||
post(w, JSON.stringify({ method: 'setCurrentTime', value: s })),
|
||||
volume: (w, v) => post(w, JSON.stringify({ method: 'setVolume', value: v })),
|
||||
setExtra: (w, id, value) => {
|
||||
if (id === 'quality') {
|
||||
post(w, JSON.stringify({ method: 'setQuality', value }));
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// embedly player.js SPEC (github.com/embedly/player.js): the `context` field
|
||||
// makes every message unambiguous. Generic (no matchUrl) — covers Wistia etc.
|
||||
const PJS = { context: 'player.js', version: '0.0.11' } as const;
|
||||
const playerjsSpec: ProtocolDef = {
|
||||
name: 'player.js',
|
||||
probe(win) {
|
||||
for (const ev of ['timeupdate', 'play', 'pause', 'ended']) {
|
||||
post(win, {
|
||||
...PJS,
|
||||
method: 'addEventListener',
|
||||
listener: `ec_${ev}`,
|
||||
value: ev,
|
||||
});
|
||||
}
|
||||
},
|
||||
parse(data) {
|
||||
const m = asObj(data);
|
||||
if (!m || m.context !== 'player.js' || typeof m.event !== 'string') {
|
||||
return null;
|
||||
}
|
||||
const v = (m.value ?? {}) as { seconds?: unknown; duration?: unknown };
|
||||
switch (m.event) {
|
||||
case 'timeupdate': {
|
||||
const sec = asNumber(v.seconds);
|
||||
const dur = asNumber(v.duration);
|
||||
return isFinite(sec)
|
||||
? {
|
||||
kind: 'time',
|
||||
seconds: sec,
|
||||
duration: isFinite(dur) && dur > 0 ? dur : undefined,
|
||||
}
|
||||
: { kind: 'hello' };
|
||||
}
|
||||
case 'play':
|
||||
return { kind: 'play' };
|
||||
case 'pause':
|
||||
return { kind: 'pause' };
|
||||
case 'ended':
|
||||
return { kind: 'ended' };
|
||||
default:
|
||||
return { kind: 'hello' }; // any context:'player.js' event is ours
|
||||
}
|
||||
},
|
||||
play: (w) => post(w, { ...PJS, method: 'play' }),
|
||||
pause: (w) => post(w, { ...PJS, method: 'pause' }),
|
||||
seek: (w, s) => post(w, { ...PJS, method: 'setCurrentTime', value: s }),
|
||||
volume: (w, v) => post(w, { ...PJS, method: 'setVolume', value: v }),
|
||||
};
|
||||
|
||||
// Rutube (RutubePlayerJSAPI). VERIFY command/subscribe shapes on a live embed.
|
||||
const rutube: ProtocolDef = {
|
||||
name: 'rutube',
|
||||
matchUrl: (url) => /(^|\.)rutube\.ru$/.test(hostOf(url)),
|
||||
probe(win) {
|
||||
// Rutube emits events only after an explicit subscribe. VERIFY payload.
|
||||
post(win, JSON.stringify({ type: 'player:subscribe', data: {} }));
|
||||
},
|
||||
parse(data) {
|
||||
const m = asObj(data);
|
||||
if (!m || typeof m.type !== 'string' || !m.type.startsWith('player:')) {
|
||||
return null;
|
||||
}
|
||||
const d = (m.data ?? {}) as {
|
||||
time?: unknown;
|
||||
duration?: unknown;
|
||||
state?: unknown;
|
||||
};
|
||||
switch (m.type) {
|
||||
case 'player:currentTime': {
|
||||
const n = asNumber(d.time);
|
||||
return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' };
|
||||
}
|
||||
case 'player:durationChange': {
|
||||
const n = asNumber(d.duration);
|
||||
return isFinite(n) && n > 0
|
||||
? { kind: 'duration', seconds: n }
|
||||
: { kind: 'hello' };
|
||||
}
|
||||
case 'player:changeState': {
|
||||
const st = String(d.state);
|
||||
if (st === 'playing') return { kind: 'play' };
|
||||
if (st === 'paused' || st === 'stopped') return { kind: 'pause' };
|
||||
if (st === 'ended') return { kind: 'ended' };
|
||||
return { kind: 'hello' };
|
||||
}
|
||||
default:
|
||||
return { kind: 'hello' }; // player:* is unambiguously Rutube
|
||||
}
|
||||
},
|
||||
play: (w) => post(w, JSON.stringify({ type: 'player:play', data: {} })),
|
||||
pause: (w) => post(w, JSON.stringify({ type: 'player:pause', data: {} })),
|
||||
seek: (w, s) =>
|
||||
post(w, JSON.stringify({ type: 'player:setCurrentTime', data: { time: s } })),
|
||||
volume: (w, v) =>
|
||||
post(w, JSON.stringify({ type: 'player:setVolume', data: { volume: v } })),
|
||||
};
|
||||
|
||||
// Dailymotion classic embed (?api=postMessage → querystring events). VERIFY;
|
||||
// the newer geo.dailymotion.com SDK uses JSON — add a branch here if needed.
|
||||
const dailymotion: ProtocolDef = {
|
||||
name: 'dailymotion',
|
||||
matchUrl: (url) => /(^|\.)(dailymotion\.com|dai\.ly)$/.test(hostOf(url)),
|
||||
// api=postMessage enables control; controls=0 + ui-* hide the native chrome
|
||||
// (our overlay bar drives playback instead).
|
||||
prepareUrl: (url) =>
|
||||
withParams(url, {
|
||||
api: 'postMessage',
|
||||
controls: '0',
|
||||
'ui-start-screen-info': 'false',
|
||||
'ui-logo': 'false',
|
||||
}),
|
||||
probe() {
|
||||
/* classic embed auto-emits once api=postMessage is set */
|
||||
},
|
||||
parse(data) {
|
||||
if (typeof data !== 'string' || !data.includes('event=')) return null;
|
||||
const p = new URLSearchParams(data);
|
||||
const ev = p.get('event');
|
||||
if (!ev) return null;
|
||||
const sec = Number(p.get('time'));
|
||||
const dur = Number(p.get('duration'));
|
||||
switch (ev) {
|
||||
case 'timeupdate':
|
||||
case 'progress':
|
||||
return isFinite(sec)
|
||||
? {
|
||||
kind: 'time',
|
||||
seconds: sec,
|
||||
duration: isFinite(dur) && dur > 0 ? dur : undefined,
|
||||
}
|
||||
: { kind: 'hello' };
|
||||
case 'durationchange':
|
||||
return isFinite(dur) && dur > 0
|
||||
? { kind: 'duration', seconds: dur }
|
||||
: { kind: 'hello' };
|
||||
case 'play':
|
||||
case 'playing':
|
||||
return { kind: 'play' };
|
||||
case 'pause':
|
||||
return { kind: 'pause' };
|
||||
case 'video_end':
|
||||
case 'ended':
|
||||
return { kind: 'ended' };
|
||||
default:
|
||||
return { kind: 'hello' };
|
||||
}
|
||||
},
|
||||
play: (w) => post(w, JSON.stringify({ command: 'play', parameters: [] })),
|
||||
pause: (w) => post(w, JSON.stringify({ command: 'pause', parameters: [] })),
|
||||
seek: (w, s) => post(w, JSON.stringify({ command: 'seek', parameters: [s] })),
|
||||
volume: (w, v) =>
|
||||
post(w, JSON.stringify({ command: 'setVolume', parameters: [v] })),
|
||||
};
|
||||
|
||||
// VK Video (?js_api=1 → {type:'player_api', event}). VERIFY command shapes.
|
||||
const vk: ProtocolDef = {
|
||||
name: 'vk',
|
||||
matchUrl: (url) => /(^|\.)(vk\.com|vkvideo\.ru|vk\.ru)$/.test(hostOf(url)),
|
||||
prepareUrl: (url) => withParams(url, { js_api: '1' }),
|
||||
probe(win) {
|
||||
post(win, JSON.stringify({ method: 'addEventListener', event: '*' }));
|
||||
},
|
||||
parse(data) {
|
||||
const m = asObj(data);
|
||||
if (!m || m.type !== 'player_api' || typeof m.event !== 'string') {
|
||||
return null;
|
||||
}
|
||||
const sec = asNumber(m.time ?? m.position);
|
||||
const dur = asNumber(m.duration);
|
||||
switch (m.event) {
|
||||
case 'timeupdate':
|
||||
return isFinite(sec)
|
||||
? {
|
||||
kind: 'time',
|
||||
seconds: sec,
|
||||
duration: isFinite(dur) && dur > 0 ? dur : undefined,
|
||||
}
|
||||
: { kind: 'hello' };
|
||||
case 'started':
|
||||
case 'resumed':
|
||||
return { kind: 'play' };
|
||||
case 'paused':
|
||||
return { kind: 'pause' };
|
||||
case 'ended':
|
||||
return { kind: 'ended' };
|
||||
default:
|
||||
return { kind: 'hello' }; // type:'player_api' is unambiguously VK
|
||||
}
|
||||
},
|
||||
play: (w) => post(w, JSON.stringify({ method: 'play' })),
|
||||
pause: (w) => post(w, JSON.stringify({ method: 'pause' })),
|
||||
seek: (w, s) => post(w, JSON.stringify({ method: 'seek', time: s })),
|
||||
volume: (w, v) => post(w, JSON.stringify({ method: 'setVolume', volume: v })),
|
||||
};
|
||||
|
||||
// Hostname-selected protocols first (they're picked by URL, never by content);
|
||||
// then the generic set probed by the messages they emit — kodik first (its
|
||||
// keys are unambiguous), the embedly spec before the looser playerjs.com.
|
||||
// Exported for the parse unit tests.
|
||||
export const EMBED_PROTOCOLS: ProtocolDef[] = [
|
||||
kodik,
|
||||
alloha,
|
||||
vimeo,
|
||||
rutube,
|
||||
dailymotion,
|
||||
vk,
|
||||
playerjsSpec,
|
||||
playerjs,
|
||||
];
|
||||
|
||||
// Inject any opt-in params a hostname-matched player needs, before iframe.src.
|
||||
export function prepareEmbedUrl(url: string): string {
|
||||
const p = EMBED_PROTOCOLS.find((x) => x.matchUrl?.(url));
|
||||
// Signed players such as Kodik depend on their own origin for scripts,
|
||||
// AJAX, cookies and anti-abuse checks. Keep them on the provider origin;
|
||||
// Echoion controls them only through their postMessage surface.
|
||||
return p?.prepareUrl ? p.prepareUrl(url) : url;
|
||||
}
|
||||
|
||||
const PROBE_INTERVAL_MS = 750;
|
||||
// Commands are echoed back as events by the player; ignore relay callbacks
|
||||
// for this long after each command we send.
|
||||
const SUPPRESS_MS = 800;
|
||||
// A time event this far off the extrapolated position counts as a user seek.
|
||||
const SEEK_JUMP_SEC = 2.5;
|
||||
// Minimum gap between reload-based (Kodik) iframe reloads.
|
||||
const RELOAD_DEBOUNCE_MS = 4000;
|
||||
|
||||
export function detectEmbedAdapter(
|
||||
frame: HTMLIFrameElement,
|
||||
cb: EmbedCallbacks,
|
||||
timeoutMs = 5000
|
||||
): Promise<EmbedAdapter | null> {
|
||||
return new Promise((resolve) => {
|
||||
let locked: ProtocolDef | null = null;
|
||||
|
||||
// A hostname-matched player is probed alone; otherwise probe the
|
||||
// generic (content-detected) set. frame.src is the prepared URL.
|
||||
const matched =
|
||||
EMBED_PROTOCOLS.find((p) => p.matchUrl?.(frame.src)) ?? null;
|
||||
const probeSet = matched
|
||||
? [matched]
|
||||
: EMBED_PROTOCOLS.filter((p) => !p.matchUrl);
|
||||
|
||||
// Normalized player state. Embeds push time updates rather than expose
|
||||
// getters, so position is the last event extrapolated by wall clock.
|
||||
let lastTimeSec = 0;
|
||||
let lastTimeAt = performance.now();
|
||||
let durationSec = 0;
|
||||
let playing = false;
|
||||
let suppressUntil = 0;
|
||||
const extraControls = new Map<string, PlayerExtraControl>();
|
||||
|
||||
const positionMs = () =>
|
||||
Math.floor(
|
||||
(lastTimeSec +
|
||||
(playing ? (performance.now() - lastTimeAt) / 1000 : 0)) *
|
||||
1000
|
||||
);
|
||||
const suppressed = () => performance.now() < suppressUntil;
|
||||
|
||||
const applyEvent = (ev: EmbedEvent) => {
|
||||
switch (ev.kind) {
|
||||
case 'time': {
|
||||
const jumped =
|
||||
Math.abs(ev.seconds - positionMs() / 1000) >
|
||||
SEEK_JUMP_SEC;
|
||||
// Advancing time implies playing even when the protocol
|
||||
// never sends an explicit play event.
|
||||
const advancing = ev.seconds > lastTimeSec + 0.05;
|
||||
lastTimeSec = ev.seconds;
|
||||
lastTimeAt = performance.now();
|
||||
// Some protocols bundle duration into the time event.
|
||||
if (
|
||||
ev.duration != null &&
|
||||
Math.abs(ev.duration - durationSec) > 0.5
|
||||
) {
|
||||
durationSec = ev.duration;
|
||||
cb.onDurationChange(Math.floor(ev.duration * 1000));
|
||||
}
|
||||
if (jumped && !suppressed()) {
|
||||
cb.onSeek(Math.floor(ev.seconds * 1000));
|
||||
}
|
||||
if (!playing && advancing) {
|
||||
playing = true;
|
||||
if (!suppressed()) cb.onPlay(positionMs());
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'duration':
|
||||
if (Math.abs(ev.seconds - durationSec) > 0.5) {
|
||||
durationSec = ev.seconds;
|
||||
cb.onDurationChange(Math.floor(ev.seconds * 1000));
|
||||
}
|
||||
break;
|
||||
case 'play':
|
||||
if (!playing) {
|
||||
playing = true;
|
||||
lastTimeAt = performance.now();
|
||||
if (!suppressed()) cb.onPlay(positionMs());
|
||||
}
|
||||
break;
|
||||
case 'pause':
|
||||
if (playing) {
|
||||
lastTimeSec = positionMs() / 1000;
|
||||
playing = false;
|
||||
if (!suppressed()) cb.onPause(positionMs());
|
||||
}
|
||||
break;
|
||||
case 'ended':
|
||||
playing = false;
|
||||
cb.onEnded();
|
||||
break;
|
||||
case 'extraList':
|
||||
if (ev.control.options.length > 0) {
|
||||
extraControls.set(ev.control.id, ev.control);
|
||||
cb.onExtraControls([...extraControls.values()]);
|
||||
}
|
||||
break;
|
||||
case 'extraCurrent': {
|
||||
const control = extraControls.get(ev.id);
|
||||
if (control && control.current !== ev.value) {
|
||||
extraControls.set(ev.id, { ...control, current: ev.value });
|
||||
cb.onExtraControls([...extraControls.values()]);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'hello':
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
// contentWindow is read live on every use: it changes when the frame
|
||||
// navigates, while ev.source comparison below stays valid because the
|
||||
// browsing context object is stable for the life of the element.
|
||||
const win = () => frame.contentWindow;
|
||||
|
||||
const makeAdapter = (p: ProtocolDef): EmbedAdapter => {
|
||||
for (const control of p.staticExtras?.(frame.src) ?? []) {
|
||||
extraControls.set(control.id, control);
|
||||
}
|
||||
if (extraControls.size > 0) {
|
||||
cb.onExtraControls([...extraControls.values()]);
|
||||
}
|
||||
const probeExtras = () => {
|
||||
const current = win();
|
||||
if (current) p.probeExtras?.(current);
|
||||
};
|
||||
probeExtras();
|
||||
const extraProbeTimers = [1500, 3000].map((delay) =>
|
||||
window.setTimeout(probeExtras, delay)
|
||||
);
|
||||
// Reload-based (Kodik) seeking: replace frame.src at a start offset,
|
||||
// debounced so drift-reconcile can't spam reloads (each reload
|
||||
// re-buffers and may replay an ad).
|
||||
let lastReloadAt = 0;
|
||||
const reloadTo = (sec: number) => {
|
||||
const now = performance.now();
|
||||
if (now - lastReloadAt < RELOAD_DEBOUNCE_MS) return;
|
||||
lastReloadAt = now;
|
||||
suppressUntil = now + SUPPRESS_MS;
|
||||
lastTimeSec = Math.max(0, sec);
|
||||
lastTimeAt = now;
|
||||
playing = true; // start_from auto-resumes
|
||||
frame.src = p.reloadSeek!(frame.src, sec);
|
||||
};
|
||||
return {
|
||||
protocol: p.name,
|
||||
reloadBased: !!p.reloadSeek,
|
||||
play() {
|
||||
// Commands update state optimistically so positionMs()/paused()
|
||||
// reflect intent immediately — otherwise the 3s sync heartbeat
|
||||
// would fight the slow embed acknowledgement.
|
||||
suppressUntil = performance.now() + SUPPRESS_MS;
|
||||
playing = true;
|
||||
lastTimeAt = performance.now();
|
||||
if (p.reloadSeek) {
|
||||
// No play command — resume by reloading at the current spot.
|
||||
reloadTo(lastTimeSec);
|
||||
return;
|
||||
}
|
||||
const w = win();
|
||||
if (w) p.play(w);
|
||||
},
|
||||
pause() {
|
||||
suppressUntil = performance.now() + SUPPRESS_MS;
|
||||
lastTimeSec = positionMs() / 1000;
|
||||
playing = false;
|
||||
// Reload-based players (Kodik) have no pause — best-effort no-op.
|
||||
if (p.reloadSeek) return;
|
||||
const w = win();
|
||||
if (w) p.pause(w);
|
||||
},
|
||||
seekMs(ms: number) {
|
||||
if (p.reloadSeek) {
|
||||
reloadTo(ms / 1000);
|
||||
return;
|
||||
}
|
||||
suppressUntil = performance.now() + SUPPRESS_MS;
|
||||
lastTimeSec = ms / 1000;
|
||||
lastTimeAt = performance.now();
|
||||
const w = win();
|
||||
if (w) p.seek(w, ms / 1000);
|
||||
},
|
||||
setVolume(v01: number) {
|
||||
const w = win();
|
||||
if (w) p.volume(w, Math.max(0, Math.min(1, v01)));
|
||||
},
|
||||
extras: () => [...extraControls.values()],
|
||||
setExtra(id, value) {
|
||||
const control = extraControls.get(id);
|
||||
if (!control || !p.setExtra) return;
|
||||
suppressUntil = performance.now() + 1500;
|
||||
extraControls.set(id, { ...control, current: value });
|
||||
cb.onExtraControls([...extraControls.values()]);
|
||||
const current = win();
|
||||
if (current) p.setExtra(current, id, value);
|
||||
},
|
||||
positionMs,
|
||||
durationMs: () => Math.floor(durationSec * 1000),
|
||||
paused: () => !playing,
|
||||
destroy() {
|
||||
window.removeEventListener('message', handler);
|
||||
clearInterval(probeTimer);
|
||||
clearTimeout(giveUp);
|
||||
for (const timer of extraProbeTimers) clearTimeout(timer);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const handler = (ev: MessageEvent) => {
|
||||
if (ev.source !== frame.contentWindow) return;
|
||||
if (locked) {
|
||||
const e = locked.parse(ev.data);
|
||||
if (e) applyEvent(e);
|
||||
else if (import.meta.env.DEV) {
|
||||
console.debug('[embed] unrecognized message', ev.data);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (const p of probeSet) {
|
||||
const e = p.parse(ev.data);
|
||||
if (e) {
|
||||
locked = p;
|
||||
clearInterval(probeTimer);
|
||||
clearTimeout(giveUp);
|
||||
applyEvent(e);
|
||||
resolve(makeAdapter(p));
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (import.meta.env.DEV) {
|
||||
console.debug('[embed] unrecognized message', ev.data);
|
||||
}
|
||||
};
|
||||
window.addEventListener('message', handler);
|
||||
|
||||
const sendProbes = () => {
|
||||
const w = win();
|
||||
if (!w || locked) return;
|
||||
for (const p of probeSet) p.probe(w);
|
||||
};
|
||||
// The inner player may boot slowly; keep probing until lock or timeout.
|
||||
const probeTimer = setInterval(sendProbes, PROBE_INTERVAL_MS);
|
||||
frame.addEventListener('load', sendProbes);
|
||||
sendProbes();
|
||||
|
||||
const giveUp = setTimeout(() => {
|
||||
if (locked) return;
|
||||
window.removeEventListener('message', handler);
|
||||
clearInterval(probeTimer);
|
||||
resolve(null);
|
||||
}, timeoutMs);
|
||||
});
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
// Emoji support for watch chat and reactions (item 16). A curated Unicode set
|
||||
// across categories (dependency-free — no multi-MB emoji-data bundle), plus
|
||||
// admin-managed custom image emojis served at /emoji/<name> and referenced by
|
||||
// :name: shortcodes. Recently-used emoji are remembered locally.
|
||||
|
||||
import { Store } from './store';
|
||||
import { rpc } from './rpc';
|
||||
|
||||
export interface CustomEmoji {
|
||||
name: string;
|
||||
mime: string;
|
||||
}
|
||||
|
||||
export const emojiStore = new Store<{
|
||||
custom: CustomEmoji[];
|
||||
recent: string[]; // unicode chars or :shortcode:
|
||||
}>({
|
||||
custom: [],
|
||||
recent: JSON.parse(localStorage.getItem('echoion.recentEmoji') || '[]'),
|
||||
});
|
||||
|
||||
export async function loadCustomEmojis() {
|
||||
try {
|
||||
const res = await rpc.call<{ emojis?: CustomEmoji[] }>(
|
||||
'GetCustomEmojis'
|
||||
);
|
||||
emojiStore.set({ custom: (res && res.emojis) || [] });
|
||||
} catch {
|
||||
/* not connected / not authed — leave empty */
|
||||
}
|
||||
}
|
||||
|
||||
export function rememberEmoji(token: string) {
|
||||
const recent = [
|
||||
token,
|
||||
...emojiStore.get().recent.filter((r) => r !== token),
|
||||
].slice(0, 24);
|
||||
emojiStore.set({ recent });
|
||||
localStorage.setItem('echoion.recentEmoji', JSON.stringify(recent));
|
||||
}
|
||||
|
||||
// Curated categories of common Unicode emoji.
|
||||
export const EMOJI_CATEGORIES: Array<{ label: string; emoji: string[] }> = [
|
||||
{
|
||||
label: 'Smileys',
|
||||
emoji: [
|
||||
'😀', '😁', '😂', '🤣', '😊', '😇', '🙂', '😉', '😍', '🥰',
|
||||
'😘', '😜', '🤪', '😎', '🤩', '🥳', '😏', '😒', '😔', '😞',
|
||||
'😢', '😭', '😤', '😠', '😡', '🤬', '🤯', '😳', '🥵', '🥶',
|
||||
'😱', '😨', '🤗', '🤔', '🤫', '🤥', '😴', '🤤', '😷', '🤒',
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'Gestures',
|
||||
emoji: [
|
||||
'👍', '👎', '👌', '✌️', '🤞', '🤟', '🤘', '👊', '✊', '🙌',
|
||||
'👏', '🙏', '💪', '👀', '👋', '🤙', '💅', '🖖', '🫶', '🤝',
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'Hearts',
|
||||
emoji: [
|
||||
'❤️', '🧡', '💛', '💚', '💙', '💜', '🖤', '🤍', '💔', '❣️',
|
||||
'💕', '💞', '💓', '💗', '💖', '💘', '💝', '✨', '💯', '🔥',
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'Fun',
|
||||
emoji: [
|
||||
'🎉', '🎊', '🥂', '🍻', '🍕', '🍿', '🎮', '🎧', '🎵', '🎸',
|
||||
'⚡', '🌟', '💥', '👑', '🚀', '🏆', '🎯', '💎', '🌈', '☀️',
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
// Render a chat message: plain text with :name: custom-emoji shortcodes
|
||||
// replaced by <img> tags. Returns React nodes (text is auto-escaped by React).
|
||||
export function renderChatText(text: string): (string | EmojiToken)[] {
|
||||
const out: (string | EmojiToken)[] = [];
|
||||
const re = /:([a-z0-9_]{1,32}):/g;
|
||||
const custom = new Set(emojiStore.get().custom.map((c) => c.name));
|
||||
let last = 0;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(text)) !== null) {
|
||||
if (!custom.has(m[1])) continue;
|
||||
if (m.index > last) out.push(text.slice(last, m.index));
|
||||
out.push({ emojiName: m[1] });
|
||||
last = m.index + m[0].length;
|
||||
}
|
||||
if (last < text.length) out.push(text.slice(last));
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface EmojiToken {
|
||||
emojiName: string;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -1,50 +1,41 @@
|
||||
// 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. The Watch view owns its own
|
||||
// `#watch/<room>` hash (see watch.ts joinRoom/leaveRoom); this router only
|
||||
// reads the room from it to auto-join a deep-linked room.
|
||||
// the app has a single flat set of views.
|
||||
|
||||
import { appStore, type ViewName } from './app';
|
||||
import { joinRoom, watchStore } from './watch';
|
||||
|
||||
const VIEWS: readonly ViewName[] = [
|
||||
'now',
|
||||
'dashboard',
|
||||
'queue',
|
||||
'search',
|
||||
'library',
|
||||
'stats',
|
||||
'watch',
|
||||
'server',
|
||||
'updates',
|
||||
'rpc',
|
||||
];
|
||||
|
||||
// The view named by the current hash, defaulting to `now`. Handles both
|
||||
// `#queue` and the watch form `#watch/<room>`.
|
||||
export function viewFromHash(): ViewName {
|
||||
const raw = location.hash.replace(/^#\/?/, '');
|
||||
// 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)
|
||||
: 'now';
|
||||
}
|
||||
|
||||
function roomFromHash(): string | null {
|
||||
const m = location.hash.match(/^#watch\/([\w-]{1,48})/);
|
||||
return m ? m[1] : null;
|
||||
: 'dashboard';
|
||||
}
|
||||
|
||||
export function initRouter() {
|
||||
// Initial view comes from the hash (refresh / shared link).
|
||||
appStore.set({ view: viewFromHash() });
|
||||
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 });
|
||||
// Auto-join a room that appears in the hash (pasted link, or
|
||||
// back/forward onto a different room). Leaving is always explicit.
|
||||
if (view === 'watch') {
|
||||
const room = roomFromHash();
|
||||
if (room && room !== watchStore.get().room) joinRoom(room);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -75,6 +75,18 @@ describe('RpcClient wire contract', () => {
|
||||
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();
|
||||
@@ -125,6 +137,21 @@ describe('RpcClient wire contract', () => {
|
||||
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();
|
||||
@@ -139,4 +166,18 @@ describe('RpcClient wire contract', () => {
|
||||
});
|
||||
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([]);
|
||||
});
|
||||
});
|
||||
@@ -62,9 +62,33 @@ export type RpcMethodName =
|
||||
| 'GetAuditLog'
|
||||
| 'GetUserPrefs'
|
||||
| 'SetUserPrefs'
|
||||
| 'GetCustomEmojis'
|
||||
| 'AddCustomEmoji'
|
||||
| 'RemoveCustomEmoji';
|
||||
| '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;
|
||||
@@ -226,6 +250,13 @@ export class RpcClient {
|
||||
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) {
|
||||
|
||||
@@ -28,5 +28,9 @@ export class Store<T> {
|
||||
}
|
||||
|
||||
export function useStore<T>(store: Store<T>): T {
|
||||
return useSyncExternalStore(store.subscribe, () => store.get());
|
||||
return useSyncExternalStore(
|
||||
store.subscribe,
|
||||
() => store.get(),
|
||||
() => store.get()
|
||||
);
|
||||
}
|
||||
@@ -12,6 +12,48 @@ export interface Track {
|
||||
source?: number; // TrackSource enum: 1 = YouTube, 6 = Yandex
|
||||
}
|
||||
|
||||
export interface PublicDashboardClient {
|
||||
nickname: string;
|
||||
talking: boolean;
|
||||
muted: boolean;
|
||||
deafened: boolean;
|
||||
away: boolean;
|
||||
}
|
||||
|
||||
export interface PublicDashboardChannel {
|
||||
id: number;
|
||||
name: string;
|
||||
parentId: number | null;
|
||||
order: number;
|
||||
default: boolean;
|
||||
permanent: boolean;
|
||||
semiPermanent: boolean;
|
||||
password: boolean;
|
||||
maxClients: number;
|
||||
currentClients: number;
|
||||
clients: PublicDashboardClient[];
|
||||
channels: PublicDashboardChannel[];
|
||||
}
|
||||
|
||||
export interface PublicDashboard {
|
||||
server: {
|
||||
name: string;
|
||||
connected: boolean;
|
||||
clientCount: number;
|
||||
maxClients: number;
|
||||
channelCount: number;
|
||||
revision: number;
|
||||
};
|
||||
channels: PublicDashboardChannel[];
|
||||
playback: {
|
||||
isPlaying: boolean;
|
||||
isPaused: boolean;
|
||||
positionMs: number;
|
||||
volume: number;
|
||||
track: (Track & { durationMs?: number; album?: string }) | null;
|
||||
};
|
||||
}
|
||||
|
||||
export interface QueueEntry {
|
||||
queueId: number;
|
||||
track: Track;
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
configForSave,
|
||||
isValidSourceId,
|
||||
normalizeUpdateConfig,
|
||||
normalizeUpdateStatus,
|
||||
} from './updates';
|
||||
|
||||
describe('update payload normalization', () => {
|
||||
it('normalizes direct config and strips read-only secret presence on save', () => {
|
||||
const config = normalizeUpdateConfig({
|
||||
enabled: true,
|
||||
checkInterval: '12h',
|
||||
sources: {
|
||||
private: {
|
||||
url: ' https://updates.example/feed.json ',
|
||||
publicKeys: [{ id: ' key-1 ', ed25519: ' abc123 ' }],
|
||||
allowUnsigned: false,
|
||||
bearerTokenEnv: ' UPDATE_TOKEN ',
|
||||
bearerTokenPresent: true,
|
||||
bearerToken: 'must-not-enter-browser-state',
|
||||
},
|
||||
},
|
||||
runtime: { source: 'private', channel: 'stable' },
|
||||
plugins: { managedOnly: false },
|
||||
});
|
||||
|
||||
expect(config.checkInterval).toBe('12h');
|
||||
expect(config.sources.private.bearerTokenPresent).toBe(true);
|
||||
expect(config.sources.private).not.toHaveProperty('bearerToken');
|
||||
expect(config.runtime.source).toBe('private');
|
||||
expect(config.plugins.managedOnly).toBe(true);
|
||||
const writable = configForSave(config);
|
||||
expect(writable.sources.private).not.toHaveProperty(
|
||||
'bearerTokenPresent'
|
||||
);
|
||||
expect(writable.sources.private.bearerTokenEnv).toBe('UPDATE_TOKEN');
|
||||
expect(writable.sources.private.url).toBe(
|
||||
'https://updates.example/feed.json'
|
||||
);
|
||||
expect(writable.sources.private.publicKeys).toEqual([
|
||||
{ id: 'key-1', ed25519: 'abc123' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('normalizes component candidates, plugin inventory, and history', () => {
|
||||
const status = normalizeUpdateStatus({
|
||||
enabled: true,
|
||||
checking: false,
|
||||
components: {
|
||||
runtime: {
|
||||
installedVersion: '1.0.0',
|
||||
availableVersion: '1.1.0',
|
||||
signed: false,
|
||||
requiresRestart: true,
|
||||
},
|
||||
core: { currentVersion: '4.0.0', state: 'healthy' },
|
||||
plugins: { state: 'current' },
|
||||
},
|
||||
pluginEntries: [
|
||||
{
|
||||
pluginId: 'weather',
|
||||
managed: true,
|
||||
installedVersion: '2.0.0',
|
||||
candidate: { version: '2.1.0', signed: true },
|
||||
},
|
||||
],
|
||||
history: [{ timestamp: 42, component: 'runtime', result: 'success' }],
|
||||
});
|
||||
|
||||
expect(status.components.runtime.currentVersion).toBe('1.0.0');
|
||||
expect(status.components.runtime.candidate).toMatchObject({
|
||||
version: '1.1.0',
|
||||
signed: false,
|
||||
requiresRestart: true,
|
||||
});
|
||||
expect(status.plugins[0]).toMatchObject({
|
||||
id: 'weather',
|
||||
managed: true,
|
||||
currentVersion: '2.0.0',
|
||||
});
|
||||
expect(status.history).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('accepts safe source identifiers only', () => {
|
||||
expect(isValidSourceId('private-beta_2')).toBe(true);
|
||||
expect(isValidSourceId('../escape')).toBe(false);
|
||||
expect(isValidSourceId('has spaces')).toBe(false);
|
||||
expect(isValidSourceId('')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,481 @@
|
||||
export type UpdateComponent = 'runtime' | 'core' | 'plugins';
|
||||
|
||||
export interface UpdatePublicKey {
|
||||
id: string;
|
||||
ed25519: string;
|
||||
}
|
||||
|
||||
export interface UpdateSourceConfig {
|
||||
url: string;
|
||||
publicKeys: UpdatePublicKey[];
|
||||
allowUnsigned: boolean;
|
||||
bearerTokenEnv: string;
|
||||
// Read-only status supplied by the server. It is stripped before save so
|
||||
// the browser can never turn secret-presence metadata into configuration.
|
||||
bearerTokenPresent?: boolean;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ComponentUpdatePolicy {
|
||||
enabled: boolean;
|
||||
source: string;
|
||||
channel: string;
|
||||
autoApply: boolean;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface PluginOverridePolicy {
|
||||
source: string;
|
||||
channel: string;
|
||||
autoApply: boolean;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface PluginUpdatePolicy extends ComponentUpdatePolicy {
|
||||
managedOnly: boolean;
|
||||
overrides: Record<string, PluginOverridePolicy>;
|
||||
}
|
||||
|
||||
export interface UpdateConfig {
|
||||
enabled: boolean;
|
||||
checkInterval: string;
|
||||
jitter: string;
|
||||
maintenanceWindowUtc: {
|
||||
start: string;
|
||||
duration: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
maxRuntimeDeferral: string;
|
||||
retainHealthyVersions: number;
|
||||
sources: Record<string, UpdateSourceConfig>;
|
||||
runtime: ComponentUpdatePolicy;
|
||||
core: ComponentUpdatePolicy;
|
||||
plugins: PluginUpdatePolicy;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface UpdateCandidate {
|
||||
id?: string;
|
||||
version: string;
|
||||
channel?: string;
|
||||
source?: string;
|
||||
signed?: boolean;
|
||||
compatible?: boolean;
|
||||
downgrade?: boolean;
|
||||
requiresRestart?: boolean;
|
||||
cohort?: string;
|
||||
message?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ComponentUpdateStatus {
|
||||
component: UpdateComponent;
|
||||
currentVersion?: string;
|
||||
state?: string;
|
||||
message?: string;
|
||||
channel?: string;
|
||||
source?: string;
|
||||
candidate?: UpdateCandidate;
|
||||
rollbackVersion?: string;
|
||||
lastChangedAt?: string | number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface PluginUpdateStatus {
|
||||
id: string;
|
||||
name?: string;
|
||||
managed: boolean;
|
||||
currentVersion?: string;
|
||||
state?: string;
|
||||
channel?: string;
|
||||
source?: string;
|
||||
candidate?: UpdateCandidate;
|
||||
rollbackVersion?: string;
|
||||
message?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface UpdateHistoryEntry {
|
||||
timestamp?: string | number;
|
||||
component?: UpdateComponent | string;
|
||||
pluginId?: string;
|
||||
action?: string;
|
||||
version?: string;
|
||||
result?: string;
|
||||
message?: string;
|
||||
actor?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface UpdateStatus {
|
||||
enabled: boolean;
|
||||
checking: boolean;
|
||||
lastCheckAt?: string | number;
|
||||
nextCheckAt?: string | number;
|
||||
components: Record<UpdateComponent, ComponentUpdateStatus>;
|
||||
plugins: PluginUpdateStatus[];
|
||||
history: UpdateHistoryEntry[];
|
||||
message?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
const DEFAULT_COMPONENT_POLICY: ComponentUpdatePolicy = {
|
||||
enabled: true,
|
||||
source: 'official',
|
||||
channel: 'stable',
|
||||
autoApply: true,
|
||||
};
|
||||
|
||||
export const DEFAULT_UPDATE_CONFIG: UpdateConfig = {
|
||||
enabled: true,
|
||||
checkInterval: '6h',
|
||||
jitter: '30m',
|
||||
maintenanceWindowUtc: {
|
||||
start: '03:00',
|
||||
duration: '2h',
|
||||
},
|
||||
maxRuntimeDeferral: '24h',
|
||||
retainHealthyVersions: 2,
|
||||
sources: {
|
||||
official: {
|
||||
url: '',
|
||||
publicKeys: [],
|
||||
allowUnsigned: false,
|
||||
bearerTokenEnv: '',
|
||||
},
|
||||
},
|
||||
runtime: { ...DEFAULT_COMPONENT_POLICY },
|
||||
core: { ...DEFAULT_COMPONENT_POLICY },
|
||||
plugins: {
|
||||
...DEFAULT_COMPONENT_POLICY,
|
||||
managedOnly: true,
|
||||
overrides: {},
|
||||
},
|
||||
};
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === 'object' && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
|
||||
function stringValue(value: unknown, fallback = ''): string {
|
||||
return typeof value === 'string' ? value : fallback;
|
||||
}
|
||||
|
||||
function booleanValue(value: unknown, fallback: boolean): boolean {
|
||||
return typeof value === 'boolean' ? value : fallback;
|
||||
}
|
||||
|
||||
function numberValue(value: unknown, fallback: number): number {
|
||||
return typeof value === 'number' && Number.isFinite(value)
|
||||
? value
|
||||
: fallback;
|
||||
}
|
||||
|
||||
function unwrap(payload: unknown, key: string): Record<string, unknown> {
|
||||
const outer = record(payload);
|
||||
const nested = record(outer[key]);
|
||||
return Object.keys(nested).length ? nested : outer;
|
||||
}
|
||||
|
||||
function sourceFieldsWithoutSecrets(
|
||||
source: Record<string, unknown>
|
||||
): Record<string, unknown> {
|
||||
return Object.fromEntries(
|
||||
Object.entries(source).filter(([key]) => {
|
||||
if (key === 'bearerTokenEnv' || key === 'bearerTokenPresent') {
|
||||
return true;
|
||||
}
|
||||
return !/(token|secret|password|authorization|privatekey)/i.test(key);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeComponentPolicy(
|
||||
value: unknown,
|
||||
fallback: ComponentUpdatePolicy
|
||||
): ComponentUpdatePolicy {
|
||||
const raw = record(value);
|
||||
return {
|
||||
...raw,
|
||||
enabled: booleanValue(raw.enabled, fallback.enabled),
|
||||
source: stringValue(raw.source, fallback.source),
|
||||
channel: stringValue(raw.channel, fallback.channel),
|
||||
autoApply: booleanValue(raw.autoApply, fallback.autoApply),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizePluginOverride(
|
||||
value: unknown,
|
||||
fallback: ComponentUpdatePolicy
|
||||
): PluginOverridePolicy {
|
||||
const raw = record(value);
|
||||
return {
|
||||
...raw,
|
||||
source: stringValue(raw.source, fallback.source),
|
||||
channel: stringValue(raw.channel, fallback.channel),
|
||||
autoApply: booleanValue(raw.autoApply, fallback.autoApply),
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeUpdateConfig(payload: unknown): UpdateConfig {
|
||||
const raw = unwrap(payload, 'config');
|
||||
const rawSources = record(raw.sources);
|
||||
const sources: Record<string, UpdateSourceConfig> = {};
|
||||
|
||||
for (const [id, value] of Object.entries(rawSources)) {
|
||||
const source = record(value);
|
||||
const safeSource = sourceFieldsWithoutSecrets(source);
|
||||
const rawKeys = Array.isArray(source.publicKeys)
|
||||
? source.publicKeys
|
||||
: [];
|
||||
sources[id] = {
|
||||
...safeSource,
|
||||
url: stringValue(source.url),
|
||||
publicKeys: rawKeys.map((key) => {
|
||||
const rawKey = record(key);
|
||||
return {
|
||||
id: stringValue(rawKey.id),
|
||||
ed25519: stringValue(rawKey.ed25519),
|
||||
};
|
||||
}),
|
||||
allowUnsigned: booleanValue(source.allowUnsigned, false),
|
||||
bearerTokenEnv: stringValue(source.bearerTokenEnv),
|
||||
...(typeof source.bearerTokenPresent === 'boolean'
|
||||
? { bearerTokenPresent: source.bearerTokenPresent }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
if (!Object.keys(sources).length) {
|
||||
sources.official = { ...DEFAULT_UPDATE_CONFIG.sources.official };
|
||||
}
|
||||
|
||||
const runtime = normalizeComponentPolicy(
|
||||
raw.runtime,
|
||||
DEFAULT_UPDATE_CONFIG.runtime
|
||||
);
|
||||
const core = normalizeComponentPolicy(raw.core, DEFAULT_UPDATE_CONFIG.core);
|
||||
const rawPlugins = record(raw.plugins);
|
||||
const pluginBase = normalizeComponentPolicy(
|
||||
rawPlugins,
|
||||
DEFAULT_UPDATE_CONFIG.plugins
|
||||
);
|
||||
const overrides: Record<string, PluginOverridePolicy> = {};
|
||||
for (const [id, value] of Object.entries(record(rawPlugins.overrides))) {
|
||||
overrides[id] = normalizePluginOverride(value, pluginBase);
|
||||
}
|
||||
|
||||
const rawWindow = record(raw.maintenanceWindowUtc);
|
||||
return {
|
||||
...raw,
|
||||
enabled: booleanValue(raw.enabled, DEFAULT_UPDATE_CONFIG.enabled),
|
||||
checkInterval: stringValue(
|
||||
raw.checkInterval,
|
||||
DEFAULT_UPDATE_CONFIG.checkInterval
|
||||
),
|
||||
jitter: stringValue(raw.jitter, DEFAULT_UPDATE_CONFIG.jitter),
|
||||
maintenanceWindowUtc: {
|
||||
...rawWindow,
|
||||
start: stringValue(
|
||||
rawWindow.start,
|
||||
DEFAULT_UPDATE_CONFIG.maintenanceWindowUtc.start
|
||||
),
|
||||
duration: stringValue(
|
||||
rawWindow.duration,
|
||||
DEFAULT_UPDATE_CONFIG.maintenanceWindowUtc.duration
|
||||
),
|
||||
},
|
||||
maxRuntimeDeferral: stringValue(
|
||||
raw.maxRuntimeDeferral,
|
||||
DEFAULT_UPDATE_CONFIG.maxRuntimeDeferral
|
||||
),
|
||||
retainHealthyVersions: numberValue(
|
||||
raw.retainHealthyVersions,
|
||||
DEFAULT_UPDATE_CONFIG.retainHealthyVersions
|
||||
),
|
||||
sources,
|
||||
runtime,
|
||||
core,
|
||||
plugins: {
|
||||
...rawPlugins,
|
||||
...pluginBase,
|
||||
// Loose local shared objects are never updater-owned. Keep this an
|
||||
// invariant even if an older or hand-written config says otherwise.
|
||||
managedOnly: true,
|
||||
overrides,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeCandidate(value: unknown): UpdateCandidate | undefined {
|
||||
const raw = record(value);
|
||||
const version = stringValue(raw.version || raw.availableVersion);
|
||||
if (!version) return undefined;
|
||||
return {
|
||||
...raw,
|
||||
id: stringValue(raw.id || raw.candidateId) || undefined,
|
||||
version,
|
||||
channel: stringValue(raw.channel) || undefined,
|
||||
source: stringValue(raw.source) || undefined,
|
||||
...(typeof raw.signed === 'boolean' ? { signed: raw.signed } : {}),
|
||||
...(typeof raw.compatible === 'boolean'
|
||||
? { compatible: raw.compatible }
|
||||
: {}),
|
||||
...(typeof raw.downgrade === 'boolean'
|
||||
? { downgrade: raw.downgrade }
|
||||
: {}),
|
||||
...(typeof raw.requiresRestart === 'boolean'
|
||||
? { requiresRestart: raw.requiresRestart }
|
||||
: {}),
|
||||
cohort: stringValue(raw.cohort) || undefined,
|
||||
message: stringValue(raw.message) || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeComponent(
|
||||
component: UpdateComponent,
|
||||
value: unknown
|
||||
): ComponentUpdateStatus {
|
||||
const raw = record(value);
|
||||
const candidate =
|
||||
normalizeCandidate(raw.candidate) ||
|
||||
normalizeCandidate({
|
||||
version: raw.availableVersion,
|
||||
id: raw.candidateId,
|
||||
channel: raw.availableChannel,
|
||||
source: raw.availableSource,
|
||||
signed: raw.signed,
|
||||
compatible: raw.compatible,
|
||||
downgrade: raw.downgrade,
|
||||
requiresRestart: raw.requiresRestart,
|
||||
});
|
||||
return {
|
||||
...raw,
|
||||
component,
|
||||
currentVersion:
|
||||
stringValue(raw.currentVersion || raw.installedVersion) || undefined,
|
||||
state: stringValue(raw.state || raw.status) || undefined,
|
||||
message: stringValue(raw.message) || undefined,
|
||||
channel: stringValue(raw.channel) || undefined,
|
||||
source: stringValue(raw.source) || undefined,
|
||||
candidate,
|
||||
rollbackVersion: stringValue(raw.rollbackVersion) || undefined,
|
||||
lastChangedAt:
|
||||
typeof raw.lastChangedAt === 'string' ||
|
||||
typeof raw.lastChangedAt === 'number'
|
||||
? raw.lastChangedAt
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizePlugin(value: unknown): PluginUpdateStatus | null {
|
||||
const raw = record(value);
|
||||
const id = stringValue(raw.id || raw.pluginId);
|
||||
if (!id) return null;
|
||||
return {
|
||||
...raw,
|
||||
id,
|
||||
name: stringValue(raw.name) || undefined,
|
||||
managed: booleanValue(raw.managed, false),
|
||||
currentVersion:
|
||||
stringValue(raw.currentVersion || raw.installedVersion) || undefined,
|
||||
state: stringValue(raw.state || raw.status) || undefined,
|
||||
channel: stringValue(raw.channel) || undefined,
|
||||
source: stringValue(raw.source) || undefined,
|
||||
candidate:
|
||||
normalizeCandidate(raw.candidate) ||
|
||||
normalizeCandidate({
|
||||
version: raw.availableVersion,
|
||||
id: raw.candidateId,
|
||||
signed: raw.signed,
|
||||
compatible: raw.compatible,
|
||||
downgrade: raw.downgrade,
|
||||
requiresRestart: raw.requiresRestart,
|
||||
}),
|
||||
rollbackVersion: stringValue(raw.rollbackVersion) || undefined,
|
||||
message: stringValue(raw.message) || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeUpdateStatus(payload: unknown): UpdateStatus {
|
||||
const raw = unwrap(payload, 'status');
|
||||
const rawComponents = record(raw.components);
|
||||
const pluginComponent = record(
|
||||
rawComponents.plugins ||
|
||||
(!Array.isArray(raw.plugins) ? raw.plugins : undefined)
|
||||
);
|
||||
const rawPluginEntries =
|
||||
(Array.isArray(raw.pluginEntries) && raw.pluginEntries) ||
|
||||
(Array.isArray(raw.managedPlugins) && raw.managedPlugins) ||
|
||||
(Array.isArray(raw.plugins) && raw.plugins) ||
|
||||
(Array.isArray(pluginComponent.items) && pluginComponent.items) ||
|
||||
[];
|
||||
const rawHistory = Array.isArray(raw.history) ? raw.history : [];
|
||||
|
||||
return {
|
||||
...raw,
|
||||
enabled: booleanValue(raw.enabled, true),
|
||||
checking: booleanValue(raw.checking, false),
|
||||
lastCheckAt:
|
||||
typeof raw.lastCheckAt === 'string' ||
|
||||
typeof raw.lastCheckAt === 'number'
|
||||
? raw.lastCheckAt
|
||||
: undefined,
|
||||
nextCheckAt:
|
||||
typeof raw.nextCheckAt === 'string' ||
|
||||
typeof raw.nextCheckAt === 'number'
|
||||
? raw.nextCheckAt
|
||||
: undefined,
|
||||
components: {
|
||||
runtime: normalizeComponent(
|
||||
'runtime',
|
||||
rawComponents.runtime || raw.runtime
|
||||
),
|
||||
core: normalizeComponent('core', rawComponents.core || raw.core),
|
||||
plugins: normalizeComponent('plugins', pluginComponent),
|
||||
},
|
||||
plugins: rawPluginEntries
|
||||
.map(normalizePlugin)
|
||||
.filter((plugin): plugin is PluginUpdateStatus => plugin !== null),
|
||||
history: rawHistory.map((entry) => record(entry) as UpdateHistoryEntry),
|
||||
message: stringValue(raw.message) || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function configForSave(config: UpdateConfig): UpdateConfig {
|
||||
const normalized = normalizeUpdateConfig(config);
|
||||
const sources: Record<string, UpdateSourceConfig> = {};
|
||||
for (const [id, source] of Object.entries(normalized.sources)) {
|
||||
const { bearerTokenPresent: _present, ...writable } = source;
|
||||
sources[id] = {
|
||||
...sourceFieldsWithoutSecrets(writable),
|
||||
url: source.url.trim(),
|
||||
allowUnsigned: source.allowUnsigned,
|
||||
bearerTokenEnv: source.bearerTokenEnv.trim(),
|
||||
publicKeys: source.publicKeys
|
||||
.map((key) => ({
|
||||
id: key.id.trim(),
|
||||
ed25519: key.ed25519.trim(),
|
||||
}))
|
||||
.filter((key) => key.id || key.ed25519),
|
||||
};
|
||||
}
|
||||
return {
|
||||
...normalized,
|
||||
sources,
|
||||
retainHealthyVersions: Math.max(
|
||||
1,
|
||||
Math.min(10, Math.trunc(normalized.retainHealthyVersions))
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function isValidSourceId(value: string): boolean {
|
||||
return /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(value);
|
||||
}
|
||||
|
||||
export function cloneUpdateConfig(config: UpdateConfig): UpdateConfig {
|
||||
return normalizeUpdateConfig(JSON.parse(JSON.stringify(config)));
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
import { useEffect, useState, type RefObject } from 'react';
|
||||
|
||||
// Auto-hides the Watch player's overlay controls (and the mouse cursor) after
|
||||
// `idleMs` of no input while a video is PLAYING, and reveals them instantly on
|
||||
// any input — like a regular video player, in both windowed and fullscreen.
|
||||
// Hover / keyboard-focus reveal (and keeping controls up while a dropdown is
|
||||
// open) is left to CSS (:hover / :focus-within); this hook only owns the idle
|
||||
// timeout and the "always visible while paused" rule. Returns the hidden flag.
|
||||
export function useControlsAutoHide(
|
||||
shellRef: RefObject<HTMLElement | null>,
|
||||
opts: { playing: boolean; enabled?: boolean; idleMs?: number }
|
||||
): boolean {
|
||||
const { playing, enabled = true, idleMs = 3000 } = opts;
|
||||
const [hidden, setHidden] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const shell = shellRef.current;
|
||||
// Paused, disabled, or no element: always show, no timer.
|
||||
if (!shell || !enabled || !playing) {
|
||||
setHidden(false);
|
||||
return;
|
||||
}
|
||||
let timer: number | undefined;
|
||||
const arm = () => {
|
||||
if (timer) window.clearTimeout(timer);
|
||||
timer = window.setTimeout(() => setHidden(true), idleMs);
|
||||
};
|
||||
const reveal = () => {
|
||||
setHidden(false); // React bails when already false → no churn
|
||||
arm();
|
||||
};
|
||||
const events = [
|
||||
'mousemove',
|
||||
'pointerdown',
|
||||
'touchstart',
|
||||
'keydown',
|
||||
'focusin',
|
||||
] as const;
|
||||
for (const e of events) {
|
||||
shell.addEventListener(e, reveal, { passive: true });
|
||||
}
|
||||
// Entering/leaving fullscreen counts as activity.
|
||||
document.addEventListener('fullscreenchange', reveal);
|
||||
arm();
|
||||
return () => {
|
||||
if (timer) window.clearTimeout(timer);
|
||||
for (const e of events) shell.removeEventListener(e, reveal);
|
||||
document.removeEventListener('fullscreenchange', reveal);
|
||||
};
|
||||
}, [shellRef, playing, enabled, idleMs]);
|
||||
|
||||
return hidden;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,5 @@
|
||||
// Shared loader for the YouTube IFrame API. Both Watch Together and the Now
|
||||
// Playing video preview use it; the script is injected once and callers await
|
||||
// the same readiness promise.
|
||||
// Shared loader for the dashboard's muted YouTube preview. The script is
|
||||
// injected once and callers await the same readiness promise.
|
||||
//
|
||||
// Console-error triage for the YouTube embeds (as seen in production behind
|
||||
// the reverse proxy):
|
||||
|
||||
@@ -5,7 +5,7 @@ import './styles/style.css';
|
||||
// Human-readable fingerprint for deployment/debugging. Vite's filename hash
|
||||
// can legitimately match an older backup when the emitted code becomes
|
||||
// byte-identical after a revert, so expose an explicit release identity too.
|
||||
export const WEB_BUILD_ID = '2026.07.10-player-fix.3';
|
||||
export const WEB_BUILD_ID = '2026.07.13-external-player-fix.1';
|
||||
document.documentElement.dataset.echoionBuild = WEB_BUILD_ID;
|
||||
console.info(`[Echoion] web build ${WEB_BUILD_ID}`);
|
||||
|
||||
|
||||
@@ -166,7 +166,7 @@ select:focus:not(:focus-visible) { outline: none; }
|
||||
|
||||
/* Inline SVG icons (components/icons.tsx) baseline-align inside text buttons
|
||||
and never shrink in flex rows. */
|
||||
.btn svg, .icon-btn svg, .ctrl svg, .pill svg, .room-chip svg, .link svg {
|
||||
.btn svg, .icon-btn svg, .ctrl svg, .pill svg, .link svg {
|
||||
vertical-align: -0.125em; flex: none;
|
||||
}
|
||||
|
||||
@@ -186,6 +186,8 @@ select:focus:not(:focus-visible) { outline: none; }
|
||||
.btn-ghost:hover { color: var(--text-2); background: rgba(255, 255, 255, 0.04); }
|
||||
.btn-danger-ghost { background: transparent; border-color: rgba(255, 92, 92, 0.3); color: var(--red-text); }
|
||||
.btn-danger-ghost:hover { background: rgba(255, 92, 92, 0.1); }
|
||||
.btn-danger { background: #c8434b; color: #fff; }
|
||||
.btn-danger:hover { background: #dc5059; }
|
||||
/* Leave-room button: prominent but not alarming; pushed to the right of the
|
||||
room header so it reads as the primary in-room action. */
|
||||
.btn-leave {
|
||||
@@ -398,145 +400,15 @@ select:focus:not(:focus-visible) { outline: none; }
|
||||
.split-legend span { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.split-legend b { color: var(--text-2); margin-left: 2px; }
|
||||
|
||||
/* ── Watch Together ───────────────────────────────────────────────────── */
|
||||
.watch-grid { display: grid; grid-template-columns: 1.6fr 1fr; gap: 18px; align-items: start; }
|
||||
.src-yt.active { background: rgba(255, 92, 92, 0.16); border-color: rgba(255, 92, 92, 0.4); color: var(--red-text); }
|
||||
.src-tw.active { background: rgba(169, 112, 255, 0.18); border-color: rgba(169, 112, 255, 0.4); color: #c3a3ff; }
|
||||
.src-direct.active { background: rgba(95, 224, 148, 0.16); border-color: rgba(95, 224, 148, 0.4); color: var(--green-text); }
|
||||
.src-iframe.active { background: rgba(255, 217, 119, 0.16); border-color: rgba(255, 217, 119, 0.4); color: #ffd977; }
|
||||
/* The direct <video> and generic <iframe> fill the player box like the embeds. */
|
||||
#watchPlayer video, #watchPlayer iframe { width: 100%; height: 100%; display: block; background: #000; }
|
||||
.player-box {
|
||||
position: relative; width: 100%; aspect-ratio: 16 / 9;
|
||||
border-radius: 12px; overflow: hidden;
|
||||
background: linear-gradient(135deg, #2a1a4a, #0d0d1f);
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.player-box iframe, .player-box > div:first-child { position: absolute; inset: 0; width: 100%; height: 100%; }
|
||||
|
||||
/* The shell owns the outer spacing; the control bar overlays the video bottom
|
||||
(windowed and fullscreen) so it can fade out when idle. */
|
||||
.player-shell { position: relative; margin-bottom: 14px; }
|
||||
.player-shell .player-box { margin-bottom: 0; }
|
||||
.player-shell.youtube-native .player-overlay { bottom: 42px; }
|
||||
.player-overlay {
|
||||
position: absolute; left: 0; right: 0; bottom: 0; z-index: 5;
|
||||
padding: 34px 14px 8px;
|
||||
background: linear-gradient(to top,
|
||||
rgba(0,0,0,0.82) 0%, rgba(0,0,0,0.45) 46%, rgba(0,0,0,0) 100%);
|
||||
opacity: 1; transition: opacity 0.25s ease;
|
||||
}
|
||||
.player-overlay .watch-controls { margin-bottom: 8px; }
|
||||
.player-overlay .watch-controls:last-child { margin-bottom: 0; }
|
||||
/* Lift muted/mono text for legibility over video. */
|
||||
.player-overlay .muted, .player-overlay .mono { color: #e9e9f2; }
|
||||
|
||||
/* Idle-hidden while playing (the hook removes the class when paused). Hover /
|
||||
keyboard focus (incl. an open quality/speed dropdown) reveals regardless. */
|
||||
.player-shell.controls-hidden .player-overlay { opacity: 0; pointer-events: none; }
|
||||
.player-shell.controls-hidden { cursor: none; }
|
||||
.player-shell.controls-hidden:hover .player-overlay,
|
||||
.player-shell.controls-hidden:focus-within .player-overlay {
|
||||
opacity: 1; pointer-events: auto;
|
||||
}
|
||||
.player-shell.controls-hidden:hover,
|
||||
.player-shell.controls-hidden:focus-within { cursor: auto; }
|
||||
|
||||
/* Fullscreen targets the shell: the player fills the screen and the overlay
|
||||
floats at the bottom (controls stay usable while fullscreen). */
|
||||
.player-shell:fullscreen { background: #000; padding: 0; }
|
||||
.player-shell:fullscreen .player-box {
|
||||
width: 100%; height: 100%; aspect-ratio: auto;
|
||||
border-radius: 0; margin: 0;
|
||||
}
|
||||
.player-shell:fullscreen .player-overlay { padding: 46px 24px 18px; }
|
||||
.player-empty {
|
||||
position: absolute; inset: 0;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
color: var(--faint); font-size: 13.5px;
|
||||
pointer-events: none;
|
||||
text-align: center; padding: 0 24px;
|
||||
}
|
||||
.player-empty[hidden] { display: none; }
|
||||
/* Muted-autoplay affordance overlaid on the player until the user unmutes. */
|
||||
.unmute-btn {
|
||||
position: absolute; left: 50%; bottom: 16px; transform: translateX(-50%);
|
||||
z-index: 6; box-shadow: 0 4px 16px rgba(0,0,0,0.5);
|
||||
}
|
||||
/* Watch lobby (no room joined). */
|
||||
.watch-lobby { max-width: 640px; margin: 0 auto; }
|
||||
.watch-lobby .rooms-list { display: flex; flex-direction: column; gap: 8px; margin: 12px 0; }
|
||||
.watch-lobby .room-chip { justify-content: flex-start; text-align: left; }
|
||||
.room-now { font-style: italic; }
|
||||
.watch-controls { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
|
||||
.watch-controls .ctrl-main { width: 42px; height: 42px; }
|
||||
.watch-local .bar { flex: 0 0 130px; }
|
||||
.watch-local[hidden] { display: none; }
|
||||
.quality-select {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid var(--line);
|
||||
color: var(--text-2);
|
||||
border-radius: 8px;
|
||||
padding: 6px 8px;
|
||||
font: inherit;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.player-settings { position: relative; }
|
||||
.player-settings-popover {
|
||||
position: absolute; right: 0; bottom: calc(100% + 10px); z-index: 20;
|
||||
width: min(290px, 80vw); padding: 10px;
|
||||
border: 1px solid rgba(255,255,255,0.14); border-radius: 12px;
|
||||
background: rgba(14, 14, 28, 0.96);
|
||||
box-shadow: 0 18px 46px rgba(0,0,0,0.5);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
.player-settings-popover section + section {
|
||||
margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--line);
|
||||
}
|
||||
.player-settings-heading {
|
||||
margin: 0 2px 7px; color: var(--faint); font-size: 10px;
|
||||
font-weight: 800; letter-spacing: .13em; text-transform: uppercase;
|
||||
}
|
||||
.player-setting {
|
||||
display: grid; grid-template-columns: minmax(80px, 1fr) minmax(110px, 1.35fr);
|
||||
align-items: center; gap: 10px; padding: 5px 2px;
|
||||
color: var(--text-2); font-size: 12.5px;
|
||||
}
|
||||
.player-setting select {
|
||||
min-width: 0; width: 100%; padding: 6px 8px;
|
||||
border: 1px solid var(--line); border-radius: 8px;
|
||||
background: #1b1b31; color: var(--text-2); font: inherit;
|
||||
}
|
||||
/* ── Shared playback controls ─────────────────────────────────────────── */
|
||||
.player-control-row { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
|
||||
.player-control-row .ctrl-main { width: 42px; height: 42px; }
|
||||
.player-local-row .bar { flex: 0 0 130px; }
|
||||
.player-local-row[hidden] { display: none; }
|
||||
.ctrl:disabled, .btn:disabled, .icon-btn:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.reactions { display: flex; gap: 8px; }
|
||||
.reaction {
|
||||
padding: 8px 14px; border-radius: 10px;
|
||||
border: 1px solid var(--line); background: transparent;
|
||||
cursor: pointer; font-size: 16px;
|
||||
}
|
||||
.reaction:hover { background: rgba(255, 255, 255, 0.06); }
|
||||
.reaction-fly {
|
||||
position: fixed; font-size: 26px; pointer-events: none;
|
||||
animation: fly-up 1.6s ease-out forwards; z-index: 60;
|
||||
}
|
||||
@keyframes fly-up { to { transform: translateY(-120px); opacity: 0; } }
|
||||
|
||||
.chat-card { display: flex; flex-direction: column; }
|
||||
.chat-log {
|
||||
display: flex; flex-direction: column; gap: 10px;
|
||||
max-height: 320px; overflow-y: auto;
|
||||
margin-bottom: 12px; padding-right: 4px;
|
||||
}
|
||||
.chat-msg { display: flex; gap: 10px; align-items: flex-start; }
|
||||
.chat-body { min-width: 0; }
|
||||
.chat-name { font-weight: 700; font-size: 12.5px; color: var(--accent-2); }
|
||||
.chat-time { color: var(--faint); font-size: 11px; margin-left: 6px; }
|
||||
.chat-text { font-size: 13px; color: var(--text-2); margin-top: 1px; word-break: break-word; }
|
||||
.chat-row { display: flex; gap: 8px; }
|
||||
.chat-row input { flex: 1; }
|
||||
|
||||
/* ── RPC view ─────────────────────────────────────────────────────────── */
|
||||
.rpc-fields { display: flex; flex-direction: column; gap: 12px; margin-bottom: 16px; }
|
||||
@@ -587,7 +459,7 @@ select:focus:not(:focus-visible) { outline: none; }
|
||||
.drawer-backdrop { display: none; }
|
||||
|
||||
@media (max-width: 1080px) {
|
||||
.now-grid, .stats-grid, .watch-grid { grid-template-columns: 1fr; }
|
||||
.now-grid, .stats-grid { grid-template-columns: 1fr; }
|
||||
}
|
||||
|
||||
/* Tablet and below: the sidebar becomes a slide-in drawer. */
|
||||
@@ -620,10 +492,10 @@ select:focus:not(:focus-visible) { outline: none; }
|
||||
.header h1 { font-size: 20px; }
|
||||
.card { padding: 14px; }
|
||||
.np-title { font-size: 19px; }
|
||||
.search-row, .chat-row, .rooms-create, .row-gap { flex-wrap: wrap; }
|
||||
.search-row input, .chat-row input { min-width: 0; flex: 1 1 160px; }
|
||||
.watch-controls { flex-wrap: wrap; row-gap: 8px; }
|
||||
.watch-local .bar { flex: 1 1 100px; }
|
||||
.search-row, .row-gap { flex-wrap: wrap; }
|
||||
.search-row input { min-width: 0; flex: 1 1 160px; }
|
||||
.player-control-row { flex-wrap: wrap; row-gap: 8px; }
|
||||
.player-local-row .bar { flex: 1 1 100px; }
|
||||
.tabs { overflow-x: auto; }
|
||||
.audit-row { grid-template-columns: 1fr auto; }
|
||||
.audit-time { grid-column: 1 / -1; }
|
||||
@@ -653,9 +525,6 @@ select:focus:not(:focus-visible) { outline: none; }
|
||||
|
||||
/* Reactions rendered inside the player box (the vanilla UI appended them
|
||||
to <body> at fixed coordinates). */
|
||||
.reaction-layer { position: absolute; inset: 0; pointer-events: none; overflow: hidden; }
|
||||
.reaction-fly-abs { position: absolute; bottom: 50px; }
|
||||
.player-box { position: relative; }
|
||||
|
||||
/* Drop indicator for queue drag-and-drop (item 9). */
|
||||
.drop-indicator {
|
||||
@@ -675,6 +544,104 @@ select:focus:not(:focus-visible) { outline: none; }
|
||||
.np-video-toggle { align-self: flex-start; margin-bottom: 8px; }
|
||||
.np-video-toggle.on { color: #b28dff; }
|
||||
|
||||
/* Public TeamSpeak directory. Nested channels keep their server order while
|
||||
the guide line makes deep trees readable without turning them into tables. */
|
||||
.ts-directory-card { min-height: 360px; }
|
||||
.ts-server-head { align-items: flex-start; }
|
||||
.ts-server-head h2 { margin-bottom: 2px; }
|
||||
.ts-connected { color: #74e5a2; border-color: rgba(95, 224, 148, 0.3); }
|
||||
.ts-disconnected { color: #ef8a8a; border-color: rgba(239, 99, 99, 0.28); }
|
||||
.ts-summary {
|
||||
display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px;
|
||||
margin: 14px 0 16px;
|
||||
}
|
||||
.ts-summary > div {
|
||||
display: flex; flex-direction: column; gap: 2px;
|
||||
padding: 10px 12px; border: 1px solid var(--line); border-radius: 10px;
|
||||
background: rgba(255, 255, 255, 0.025);
|
||||
}
|
||||
.ts-summary strong { font-size: 18px; }
|
||||
.ts-summary span { color: var(--muted-2); font-size: 11px; }
|
||||
.ts-tree { display: flex; flex-direction: column; gap: 3px; }
|
||||
.ts-channel {
|
||||
position: relative;
|
||||
margin-left: calc(var(--tree-depth, 0) * 18px);
|
||||
}
|
||||
.ts-channel::before {
|
||||
content: ''; position: absolute; left: -10px; top: 0; bottom: 0;
|
||||
border-left: 1px solid rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
.ts-channel-row, .ts-client-row {
|
||||
display: flex; align-items: center; min-width: 0;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.ts-channel-row { min-height: 34px; padding: 4px 7px; gap: 7px; }
|
||||
.ts-channel-row:hover, .ts-client-row:hover { background: rgba(255, 255, 255, 0.035); }
|
||||
.ts-channel-caret { width: 14px; color: var(--faint); text-align: center; }
|
||||
.ts-channel-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; font-weight: 650; }
|
||||
.ts-capacity { margin-left: auto; color: var(--faint); font: 11px var(--font-mono); }
|
||||
.ts-tag {
|
||||
padding: 2px 6px; border-radius: 999px; color: var(--muted-2);
|
||||
background: rgba(255, 255, 255, 0.06); font-size: 9px;
|
||||
letter-spacing: 0.04em; text-transform: uppercase;
|
||||
}
|
||||
.ts-client-row { min-height: 30px; margin-left: 26px; padding: 3px 8px; gap: 8px; }
|
||||
.ts-presence { width: 7px; height: 7px; flex: none; border-radius: 50%; background: #687080; }
|
||||
.ts-presence.talking { background: #5fe094; box-shadow: 0 0 0 4px rgba(95, 224, 148, 0.1); }
|
||||
.ts-client-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; font-size: 13px; }
|
||||
.ts-client-flags { display: flex; gap: 5px; margin-left: auto; }
|
||||
.ts-client-flags span {
|
||||
color: var(--faint); font-size: 9px; text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
.nav-external { margin-left: auto; color: var(--faint); }
|
||||
|
||||
/* Guarded administration surface. */
|
||||
.admin-tabs {
|
||||
display: flex; gap: 4px; overflow-x: auto; margin-bottom: 14px;
|
||||
padding: 4px; border: 1px solid var(--line); border-radius: 12px;
|
||||
background: rgba(255, 255, 255, 0.025);
|
||||
}
|
||||
.admin-tab {
|
||||
flex: none; border: 0; border-radius: 8px; padding: 8px 13px;
|
||||
background: transparent; color: var(--muted-2); cursor: pointer;
|
||||
font: inherit; font-size: 12px; font-weight: 650;
|
||||
}
|
||||
.admin-tab.active { background: rgba(124, 92, 255, 0.16); color: #c9bfff; }
|
||||
.admin-stack { display: flex; flex-direction: column; gap: 14px; }
|
||||
.admin-action-grid { display: flex; flex-wrap: wrap; gap: 10px; }
|
||||
.admin-guard { max-width: 620px; }
|
||||
.ts-admin-tree { display: flex; flex-direction: column; gap: 7px; }
|
||||
.ts-admin-channel {
|
||||
border-left: 1px solid rgba(255, 255, 255, 0.08);
|
||||
padding: 7px 0 2px 10px;
|
||||
}
|
||||
.ts-admin-channel-head {
|
||||
display: flex; align-items: center; gap: 7px; flex-wrap: wrap;
|
||||
min-height: 34px;
|
||||
}
|
||||
.ts-admin-channel-head .ts-capacity { margin-left: 0; margin-right: auto; }
|
||||
.ts-admin-client {
|
||||
display: grid; grid-template-columns: minmax(180px, 0.8fr) minmax(250px, 1.2fr) auto;
|
||||
gap: 10px; align-items: center; margin: 5px 0 5px 20px; padding: 8px 10px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.055); border-radius: 9px;
|
||||
background: rgba(255, 255, 255, 0.018);
|
||||
}
|
||||
.ts-admin-client-main, .ts-admin-private, .ts-admin-actions {
|
||||
display: flex; align-items: center; gap: 7px; min-width: 0; flex-wrap: wrap;
|
||||
}
|
||||
.ts-admin-private { font: 10px var(--font-mono); }
|
||||
.ts-admin-actions { justify-content: flex-end; }
|
||||
.ts-admin-actions .btn, .ts-admin-channel-head .btn { padding: 5px 8px; font-size: 10px; }
|
||||
.ts-ban-row {
|
||||
display: grid; grid-template-columns: 1fr auto auto; gap: 12px;
|
||||
align-items: center; padding: 9px 0; border-bottom: 1px solid var(--line);
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.ts-admin-client { grid-template-columns: 1fr; }
|
||||
.ts-admin-actions { justify-content: flex-start; }
|
||||
}
|
||||
|
||||
/* Announce composer modal (item 14). */
|
||||
.modal-backdrop {
|
||||
position: fixed; inset: 0; z-index: 100; display: flex;
|
||||
@@ -721,66 +688,240 @@ select:focus:not(:focus-visible) { outline: none; }
|
||||
.ts-markup details { margin: 0.4em 0; }
|
||||
.ts-markup summary { cursor: pointer; font-weight: 600; }
|
||||
|
||||
/* Watch Together room switcher (item 3). */
|
||||
.pill-room { cursor: pointer; border: none; font: inherit; }
|
||||
.rooms-panel {
|
||||
display: flex; flex-direction: column; gap: 10px;
|
||||
padding: 12px; margin: 4px 0 2px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 12px;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
/* ── Updates control plane ──────────────────────────────────────────────
|
||||
The update surface keeps the dashboard's violet language, but uses a
|
||||
denser instrument-panel rhythm: version rails, status lamps, and a faint
|
||||
technical grid make trust and activation state scannable at a glance. */
|
||||
.updates-view {
|
||||
position: relative;
|
||||
}
|
||||
.rooms-list { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.room-chip {
|
||||
background: rgba(255, 255, 255, 0.06); border: 1px solid transparent;
|
||||
border-radius: 8px; padding: 5px 10px; cursor: pointer;
|
||||
color: inherit; font: inherit; font-size: 13px;
|
||||
.updates-view::before {
|
||||
content: ''; position: absolute; inset: -8px 0 auto; height: 250px;
|
||||
pointer-events: none; opacity: .18;
|
||||
background-image:
|
||||
linear-gradient(rgba(124, 92, 255, .12) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(124, 92, 255, .12) 1px, transparent 1px);
|
||||
background-size: 28px 28px;
|
||||
mask-image: linear-gradient(to bottom, #000, transparent);
|
||||
}
|
||||
.room-chip.active { border-color: #7c5cff; color: #b28dff; }
|
||||
.rooms-create { display: flex; gap: 8px; }
|
||||
.rooms-create input { flex: 1; }
|
||||
.update-command-bar {
|
||||
position: relative; display: flex; align-items: center;
|
||||
justify-content: space-between; gap: 16px; margin-bottom: 16px;
|
||||
padding: 14px 16px; border: 1px solid rgba(124, 92, 255, .23);
|
||||
border-radius: 13px;
|
||||
background: linear-gradient(110deg, rgba(124, 92, 255, .11), rgba(255, 255, 255, .025) 58%);
|
||||
}
|
||||
.update-command-state { display: flex; align-items: center; gap: 12px; min-width: 0; }
|
||||
.update-command-state p { margin-top: 2px; font-size: 12px; }
|
||||
.update-beacon {
|
||||
width: 11px; height: 11px; border-radius: 50%; flex: none;
|
||||
background: var(--faint); box-shadow: 0 0 0 6px rgba(106, 106, 120, .1);
|
||||
}
|
||||
.update-beacon.active {
|
||||
background: var(--green);
|
||||
box-shadow: 0 0 0 6px rgba(63, 208, 122, .1), 0 0 18px rgba(63, 208, 122, .4);
|
||||
}
|
||||
.update-live-region { min-height: 18px; color: var(--muted-2); font-size: 12px; }
|
||||
.update-component-grid {
|
||||
position: relative; display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 12px; margin: 2px 0 18px;
|
||||
}
|
||||
.update-component-card {
|
||||
position: relative; overflow: hidden; display: flex; flex-direction: column;
|
||||
min-height: 260px; padding: 16px; border: 1px solid var(--line);
|
||||
border-radius: var(--radius); background: rgba(14, 14, 21, .93);
|
||||
}
|
||||
.update-component-card::after {
|
||||
content: ''; position: absolute; right: -32px; top: -32px;
|
||||
width: 110px; height: 110px; border-radius: 50%;
|
||||
background: rgba(124, 92, 255, .08); filter: blur(4px);
|
||||
}
|
||||
.update-component-head {
|
||||
position: relative; z-index: 1; display: grid;
|
||||
grid-template-columns: auto 1fr auto; align-items: center; gap: 10px;
|
||||
}
|
||||
.update-component-head h2 { font-size: 15px; }
|
||||
.update-component-head p { margin-top: 2px; font-size: 10px; }
|
||||
.update-component-mark {
|
||||
width: 35px; height: 35px; border-radius: 10px;
|
||||
display: grid; place-items: center; font: 700 13px var(--font-mono);
|
||||
color: #d7d0ff; border: 1px solid rgba(124, 92, 255, .28);
|
||||
background: rgba(124, 92, 255, .13);
|
||||
}
|
||||
.update-component-mark.core { color: #8fe8b4; border-color: rgba(63, 208, 122, .25); background: rgba(63, 208, 122, .1); }
|
||||
.update-component-mark.plugins { color: #ffe08d; border-color: rgba(255, 207, 74, .25); background: rgba(255, 207, 74, .1); }
|
||||
.update-version-line {
|
||||
display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
|
||||
align-items: center; gap: 10px; margin: 20px 0 12px;
|
||||
}
|
||||
.update-version-line > div { min-width: 0; }
|
||||
.update-version-line span {
|
||||
display: block; color: var(--faint); font-size: 9px; font-weight: 700;
|
||||
letter-spacing: .09em; text-transform: uppercase;
|
||||
}
|
||||
.update-version-line strong {
|
||||
display: block; overflow: hidden; margin-top: 3px;
|
||||
font: 700 14px var(--font-mono); text-overflow: ellipsis;
|
||||
}
|
||||
.update-version-arrow { color: var(--accent-text) !important; font-size: 16px !important; }
|
||||
.update-badges { display: flex; flex-wrap: wrap; gap: 5px; }
|
||||
.update-badge {
|
||||
display: inline-flex; align-items: center; width: fit-content;
|
||||
padding: 3px 7px; border-radius: 999px;
|
||||
font: 700 9px var(--font-mono); letter-spacing: .03em;
|
||||
text-transform: uppercase; white-space: nowrap;
|
||||
color: var(--muted); border: 1px solid rgba(255, 255, 255, .08);
|
||||
background: rgba(255, 255, 255, .04);
|
||||
}
|
||||
.update-badge.success { color: var(--green-text); border-color: rgba(63, 208, 122, .22); background: rgba(63, 208, 122, .09); }
|
||||
.update-badge.warning { color: var(--yellow-text); border-color: rgba(255, 207, 74, .22); background: rgba(255, 207, 74, .09); }
|
||||
.update-badge.danger { color: var(--red-text); border-color: rgba(255, 92, 92, .24); background: rgba(255, 92, 92, .09); }
|
||||
.update-card-message { margin-top: 10px; color: var(--muted-2); font-size: 12px; line-height: 1.45; }
|
||||
.update-card-actions { display: flex; flex-wrap: wrap; gap: 7px; margin-top: auto; padding-top: 18px; }
|
||||
.update-card-actions .btn { padding: 7px 10px; font-size: 11px; }
|
||||
.updates-two-column {
|
||||
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
||||
gap: 18px; align-items: start;
|
||||
}
|
||||
.update-plugin-list { display: flex; flex-direction: column; }
|
||||
.update-plugin-row {
|
||||
display: grid; grid-template-columns: minmax(120px, 1.2fr) auto minmax(105px, .7fr) auto;
|
||||
align-items: center; gap: 10px; padding: 9px 2px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.update-plugin-row:last-child { border-bottom: 0; }
|
||||
.update-plugin-main { display: flex; flex-direction: column; min-width: 0; }
|
||||
.update-plugin-main strong, .update-plugin-main span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.update-plugin-main span { font-size: 10px; margin-top: 2px; }
|
||||
.update-plugin-version { color: var(--muted); font-size: 11px; }
|
||||
.update-plugin-actions { display: flex; gap: 5px; }
|
||||
.update-plugin-actions .btn { padding: 5px 8px; font-size: 10px; }
|
||||
.update-history-scroll { max-height: 350px; overflow: auto; }
|
||||
.update-history-table { width: 100%; border-collapse: collapse; font-size: 11px; }
|
||||
.update-history-table th {
|
||||
position: sticky; top: 0; z-index: 1; padding: 7px 8px;
|
||||
text-align: left; color: var(--faint); background: #111119;
|
||||
font-size: 9px; letter-spacing: .08em; text-transform: uppercase;
|
||||
}
|
||||
.update-history-table td { padding: 8px; border-bottom: 1px solid var(--line); vertical-align: middle; }
|
||||
.update-history-table td:first-child { white-space: nowrap; color: var(--muted-2); }
|
||||
.update-history-table td small { display: block; margin-top: 2px; color: var(--faint); font: 9px var(--font-mono); }
|
||||
.update-config { margin-top: 8px; }
|
||||
.update-config-title, .update-sources-head {
|
||||
display: flex; align-items: flex-end; justify-content: space-between;
|
||||
gap: 16px; margin: 27px 0 13px;
|
||||
}
|
||||
.update-config-title h2 { font-size: 22px; margin: 2px 0 3px; }
|
||||
.update-kicker {
|
||||
color: var(--accent-text); font: 700 9px var(--font-mono);
|
||||
letter-spacing: .16em;
|
||||
}
|
||||
.update-automation-card { border-color: rgba(124, 92, 255, .18); }
|
||||
.update-automation-grid {
|
||||
display: grid; grid-template-columns: repeat(6, minmax(100px, 1fr));
|
||||
gap: 12px; align-items: end;
|
||||
}
|
||||
.update-master-switch { grid-column: span 2; align-self: center; }
|
||||
.update-field { display: flex; flex-direction: column; gap: 5px; min-width: 0; }
|
||||
.update-field > span {
|
||||
color: var(--muted-2); font-size: 10px; font-weight: 700;
|
||||
letter-spacing: .035em;
|
||||
}
|
||||
.update-field input, .update-field select, .update-override-row input,
|
||||
.update-override-row select {
|
||||
width: 100%; min-width: 0; color: var(--text);
|
||||
background: rgba(255, 255, 255, .045); border: 1px solid var(--line);
|
||||
border-radius: 9px; padding: 9px 10px; outline: none; font: inherit;
|
||||
font-size: 12px;
|
||||
}
|
||||
.update-field input:focus, .update-field select:focus,
|
||||
.update-override-row input:focus, .update-override-row select:focus {
|
||||
border-color: rgba(124, 92, 255, .48);
|
||||
}
|
||||
.update-field select option, .update-override-row select option { color: #111; }
|
||||
.update-field small { color: var(--faint); font-size: 10px; line-height: 1.35; }
|
||||
.update-switch { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; color: var(--muted); font-size: 11px; }
|
||||
.update-switch input { width: 15px; height: 15px; accent-color: var(--accent); }
|
||||
.update-policy-list { display: flex; flex-direction: column; }
|
||||
.update-policy-row {
|
||||
display: grid; grid-template-columns: minmax(150px, .8fr) minmax(130px, .8fr) minmax(130px, 1fr) auto;
|
||||
align-items: end; gap: 12px; padding: 12px 2px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.update-policy-row:last-child { border-bottom: 0; }
|
||||
.update-policy-name { display: flex; flex-direction: column; gap: 6px; align-self: center; }
|
||||
.update-auto-switch { min-height: 36px; align-self: end; }
|
||||
.update-managed-only { margin-top: 12px; }
|
||||
.update-override-list { display: flex; flex-direction: column; }
|
||||
.update-override-row {
|
||||
display: grid; grid-template-columns: minmax(140px, 1fr) minmax(120px, .7fr) minmax(120px, .8fr) auto auto;
|
||||
align-items: center; gap: 9px; padding: 8px 0; border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.update-override-id { overflow: hidden; text-overflow: ellipsis; }
|
||||
.update-empty-inline { padding: 10px 2px; font-size: 12px; }
|
||||
.update-source-list { display: flex; flex-direction: column; gap: 13px; }
|
||||
.update-source-card {
|
||||
min-width: 0; padding: 16px; border: 1px solid var(--line);
|
||||
border-radius: var(--radius); background: var(--panel);
|
||||
}
|
||||
.update-source-card legend {
|
||||
display: flex; align-items: center; gap: 8px; padding: 0 8px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.update-source-grid {
|
||||
display: grid; grid-template-columns: minmax(240px, 1.4fr) minmax(220px, 1fr) auto;
|
||||
align-items: start; gap: 12px; margin-bottom: 17px;
|
||||
}
|
||||
.update-unsigned-switch { min-height: 55px; align-self: end; color: var(--yellow-text); }
|
||||
.update-key-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 8px; }
|
||||
.update-key-head p { margin-top: 2px; font-size: 11px; }
|
||||
.update-key-list { display: flex; flex-direction: column; }
|
||||
.update-key-row {
|
||||
display: grid; grid-template-columns: minmax(130px, .45fr) minmax(220px, 1.55fr) auto;
|
||||
align-items: end; gap: 8px; padding: 7px 0;
|
||||
}
|
||||
.update-key-remove { margin-bottom: 1px; }
|
||||
.update-source-foot { display: flex; justify-content: flex-end; margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--line); }
|
||||
|
||||
/* Watch search (item 20). */
|
||||
.watch-search { position: relative; margin-bottom: 8px; }
|
||||
.watch-search-results {
|
||||
position: absolute; z-index: 30; left: 0; right: 0; top: 100%;
|
||||
background: #14141f; border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
border-radius: 10px; margin-top: 4px; max-height: 320px; overflow: auto;
|
||||
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.5);
|
||||
@media (max-width: 1200px) {
|
||||
.update-component-grid { grid-template-columns: 1fr; }
|
||||
.update-component-card { min-height: 0; }
|
||||
.update-automation-grid { grid-template-columns: repeat(3, minmax(120px, 1fr)); }
|
||||
.update-master-switch { grid-column: span 1; }
|
||||
}
|
||||
.watch-search-item {
|
||||
display: flex; align-items: center; gap: 10px; width: 100%;
|
||||
padding: 6px 10px; background: transparent; border: none; cursor: pointer;
|
||||
color: inherit; text-align: left; font: inherit;
|
||||
}
|
||||
.watch-search-item:hover { background: rgba(255, 255, 255, 0.06); }
|
||||
.watch-search-item .track-cover { width: 48px; height: 27px; flex: none; border-radius: 4px; }
|
||||
.watch-search-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
/* Emoji picker + custom emojis (item 16). */
|
||||
.emoji-anchor { position: relative; display: inline-flex; }
|
||||
.emoji-trigger { padding: 6px 8px; }
|
||||
.emoji-picker {
|
||||
position: absolute; bottom: 100%; left: 0; z-index: 40; width: 300px;
|
||||
max-height: 320px; overflow-y: auto; margin-bottom: 6px; padding: 8px;
|
||||
background: #14141f; border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
border-radius: 12px; box-shadow: 0 16px 40px rgba(0, 0, 0, 0.5);
|
||||
@media (max-width: 1000px) {
|
||||
.updates-two-column { grid-template-columns: 1fr; }
|
||||
.update-source-grid { grid-template-columns: 1fr 1fr; }
|
||||
.update-unsigned-switch { grid-column: 1 / -1; min-height: auto; }
|
||||
}
|
||||
.emoji-section { margin-bottom: 8px; }
|
||||
.emoji-section-label {
|
||||
font-size: 10px; letter-spacing: 0.08em; text-transform: uppercase;
|
||||
color: #8a8a98; margin: 4px 2px;
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.update-command-bar, .update-config-title, .update-sources-head {
|
||||
align-items: stretch; flex-direction: column;
|
||||
}
|
||||
.update-command-bar .row-gap, .update-config-title .row-gap { justify-content: flex-end; }
|
||||
.update-automation-grid, .update-source-grid { grid-template-columns: 1fr; }
|
||||
.update-policy-row { grid-template-columns: 1fr 1fr; }
|
||||
.update-policy-name { grid-column: 1 / -1; }
|
||||
.update-override-row { grid-template-columns: 1fr 1fr; }
|
||||
.update-override-id { grid-column: 1 / -1; }
|
||||
.update-key-row { grid-template-columns: 1fr; padding: 11px 0; }
|
||||
.update-key-remove { justify-self: start; }
|
||||
.update-plugin-row { grid-template-columns: minmax(0, 1fr) auto; }
|
||||
.update-plugin-version { grid-column: 1; }
|
||||
.update-plugin-actions { grid-column: 2; grid-row: 2; }
|
||||
}
|
||||
.emoji-grid { display: grid; grid-template-columns: repeat(8, 1fr); gap: 2px; }
|
||||
.emoji-btn {
|
||||
background: transparent; border: none; cursor: pointer; font-size: 20px;
|
||||
line-height: 1; padding: 4px; border-radius: 6px;
|
||||
|
||||
@media (max-width: 460px) {
|
||||
.update-policy-row, .update-override-row { grid-template-columns: 1fr; }
|
||||
.update-policy-name, .update-override-id { grid-column: auto; }
|
||||
.update-version-line { grid-template-columns: 1fr; }
|
||||
.update-version-arrow { transform: rotate(90deg); width: fit-content; }
|
||||
.update-history-table th:nth-child(3), .update-history-table td:nth-child(3) { display: none; }
|
||||
}
|
||||
.emoji-btn:hover { background: rgba(255, 255, 255, 0.08); }
|
||||
.emoji-img { width: 20px; height: 20px; vertical-align: middle; object-fit: contain; }
|
||||
.emoji-img-lg { width: 30px; height: 30px; object-fit: contain; }
|
||||
.emoji-manage-row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin-bottom: 12px; }
|
||||
.emoji-manage-grid { display: flex; flex-wrap: wrap; gap: 12px; }
|
||||
.emoji-manage-item {
|
||||
display: flex; align-items: center; gap: 6px;
|
||||
background: rgba(255, 255, 255, 0.05); border-radius: 8px; padding: 6px 10px;
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.update-beacon { box-shadow: none; }
|
||||
}
|
||||
+123
-12
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, type CSSProperties } from 'react';
|
||||
import { appStore, loadFavorites, safeCall, showView, toast } from '../lib/app';
|
||||
import { useStore } from '../lib/store';
|
||||
import { PlayerControls } from '../components/PlayerControls';
|
||||
@@ -15,8 +15,9 @@ import {
|
||||
SkipPrevIcon,
|
||||
} from '../components/icons';
|
||||
import { t, tf } from '../i18n';
|
||||
import type { PublicDashboardChannel } from '../lib/types';
|
||||
|
||||
const VIDEO_PREF_KEY = 'echoion.npVideo';
|
||||
const DASHBOARD_VIDEO_PREF_KEY = 'echoion.npVideo';
|
||||
|
||||
async function togglePlay() {
|
||||
const st = appStore.get().status || {};
|
||||
@@ -24,10 +25,62 @@ async function togglePlay() {
|
||||
else await safeCall('Resume');
|
||||
}
|
||||
|
||||
export function NowView() {
|
||||
function ChannelNode({
|
||||
channel,
|
||||
depth = 0,
|
||||
}: {
|
||||
channel: PublicDashboardChannel;
|
||||
depth?: number;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className="ts-channel"
|
||||
style={{ '--tree-depth': depth } as CSSProperties}
|
||||
>
|
||||
<div className="ts-channel-row">
|
||||
<span className="ts-channel-caret" aria-hidden="true">
|
||||
{channel.channels.length || channel.clients.length ? '⌄' : '·'}
|
||||
</span>
|
||||
<span className="ts-channel-name">{channel.name}</span>
|
||||
{channel.default && <span className="ts-tag">{t('default')}</span>}
|
||||
{channel.password && (
|
||||
<span className="ts-tag" title={t('Password protected')}>
|
||||
{t('locked')}
|
||||
</span>
|
||||
)}
|
||||
<span className="ts-capacity">
|
||||
{channel.currentClients}/
|
||||
{channel.maxClients > 0 ? channel.maxClients : '∞'}
|
||||
</span>
|
||||
</div>
|
||||
{channel.clients.map((client, index) => (
|
||||
<div
|
||||
className="ts-client-row"
|
||||
key={`${client.nickname}-${index}`}
|
||||
>
|
||||
<span
|
||||
className={'ts-presence' + (client.talking ? ' talking' : '')}
|
||||
aria-label={client.talking ? t('Talking') : t('Online')}
|
||||
/>
|
||||
<span className="ts-client-name">{client.nickname}</span>
|
||||
<div className="ts-client-flags">
|
||||
{client.away && <span title={t('Away')}>away</span>}
|
||||
{client.muted && <span title={t('Muted')}>mic off</span>}
|
||||
{client.deafened && <span title={t('Deafened')}>sound off</span>}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{channel.channels.map((child) => (
|
||||
<ChannelNode key={child.id} channel={child} depth={depth + 1} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DashboardView() {
|
||||
const s = useStore(appStore);
|
||||
const [videoOn, setVideoOn] = useState(
|
||||
localStorage.getItem(VIDEO_PREF_KEY) === '1'
|
||||
localStorage.getItem(DASHBOARD_VIDEO_PREF_KEY) === '1'
|
||||
);
|
||||
const track = s.current;
|
||||
const videoId = youtubeIdFromUrl(track?.url);
|
||||
@@ -50,7 +103,7 @@ export function NowView() {
|
||||
const needed = st.skipVotesNeeded || 0;
|
||||
|
||||
return (
|
||||
<section className="view" id="view-now">
|
||||
<section className="view" id="view-dashboard">
|
||||
<div className="now-grid">
|
||||
<div className="card np-card">
|
||||
{showVideo && videoId ? (
|
||||
@@ -72,7 +125,7 @@ export function NowView() {
|
||||
const next = !videoOn;
|
||||
setVideoOn(next);
|
||||
localStorage.setItem(
|
||||
VIDEO_PREF_KEY,
|
||||
DASHBOARD_VIDEO_PREF_KEY,
|
||||
next ? '1' : '0'
|
||||
);
|
||||
}}
|
||||
@@ -94,7 +147,7 @@ export function NowView() {
|
||||
playing={playing}
|
||||
positionMs={s.positionMs}
|
||||
durationMs={durationMs}
|
||||
canControl
|
||||
canControl={!!s.identity}
|
||||
volumePct={volumePct}
|
||||
onTogglePlay={togglePlay}
|
||||
onSeekMs={(ms) =>
|
||||
@@ -108,7 +161,7 @@ export function NowView() {
|
||||
? () => safeCall('Skip', { count: 1 })
|
||||
: undefined
|
||||
}
|
||||
extra={
|
||||
extra={s.identity ? (
|
||||
<>
|
||||
<button
|
||||
className={
|
||||
@@ -210,8 +263,8 @@ export function NowView() {
|
||||
</span>
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
extraLocal={
|
||||
) : undefined}
|
||||
extraLocal={s.identity ? (
|
||||
<label className="toggle-row">
|
||||
<span className="muted">{t('Radio')}</span>
|
||||
<button
|
||||
@@ -251,11 +304,66 @@ export function NowView() {
|
||||
<span className="knob" />
|
||||
</button>
|
||||
</label>
|
||||
}
|
||||
) : undefined}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col">
|
||||
<div className="card ts-directory-card">
|
||||
<div className="card-head ts-server-head">
|
||||
<div>
|
||||
<h2>
|
||||
{s.publicDashboard?.server.name ||
|
||||
t('TeamSpeak server')}
|
||||
</h2>
|
||||
<span className="muted">
|
||||
{t('Complete channel directory')}
|
||||
</span>
|
||||
</div>
|
||||
<span
|
||||
className={
|
||||
'pill ' +
|
||||
(s.publicDashboard?.server.connected
|
||||
? 'ts-connected'
|
||||
: 'ts-disconnected')
|
||||
}
|
||||
>
|
||||
{s.publicDashboard?.server.connected
|
||||
? t('Connected')
|
||||
: t('Disconnected')}
|
||||
</span>
|
||||
</div>
|
||||
<div className="ts-summary">
|
||||
<div>
|
||||
<strong>
|
||||
{s.publicDashboard?.server.clientCount || 0}
|
||||
</strong>
|
||||
<span>{t('clients')}</span>
|
||||
</div>
|
||||
<div>
|
||||
<strong>
|
||||
{s.publicDashboard?.server.channelCount || 0}
|
||||
</strong>
|
||||
<span>{t('channels')}</span>
|
||||
</div>
|
||||
<div>
|
||||
<strong>
|
||||
{s.publicDashboard?.server.maxClients || '∞'}
|
||||
</strong>
|
||||
<span>{t('capacity')}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="ts-tree">
|
||||
{s.publicDashboard?.channels.length ? (
|
||||
s.publicDashboard.channels.map((channel) => (
|
||||
<ChannelNode key={channel.id} channel={channel} />
|
||||
))
|
||||
) : (
|
||||
<EmptyRow text={t('No channels available')} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{s.identity && (
|
||||
<div className="card">
|
||||
<div className="card-head">
|
||||
<h2>{t('Up Next')}</h2>
|
||||
@@ -286,7 +394,9 @@ export function NowView() {
|
||||
})()}
|
||||
</div>
|
||||
</div>
|
||||
<LyricsPanel />
|
||||
)}
|
||||
{s.identity && <LyricsPanel />}
|
||||
{s.identity && (
|
||||
<div className="card">
|
||||
<div className="card-head">
|
||||
<h3>{t('Listening now')}</h3>
|
||||
@@ -311,6 +421,7 @@ export function NowView() {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -4,25 +4,36 @@ import { useStore } from '../lib/store';
|
||||
import { EmptyRow } from '../components/TrackRow';
|
||||
import { PersonRow } from '../components/PersonRow';
|
||||
import { AnnounceModal } from '../components/AnnounceModal';
|
||||
import { EmojiManager } from '../components/EmojiManager';
|
||||
import { TeamSpeakAdmin } from '../components/TeamSpeakAdmin';
|
||||
import type { AuditEntry, Subscriber } from '../lib/types';
|
||||
import { auditMethodName } from '../lib/auditMethods';
|
||||
import { confirmDialog } from '../lib/dialog';
|
||||
import { t, tf } from '../i18n';
|
||||
|
||||
type AdminTab = 'teamspeak' | 'echoion' | 'subscribers' | 'emojis' | 'audit';
|
||||
|
||||
const TABS: Array<{ id: AdminTab; label: string }> = [
|
||||
{ id: 'teamspeak', label: 'TeamSpeak' },
|
||||
{ id: 'echoion', label: 'Echoion' },
|
||||
{ id: 'subscribers', label: 'Subscribers' },
|
||||
{ id: 'emojis', label: 'Emojis' },
|
||||
{ id: 'audit', label: 'Audit history' },
|
||||
];
|
||||
|
||||
export function ServerView() {
|
||||
const s = useStore(appStore);
|
||||
const [tab, setTab] = useState<AdminTab>('teamspeak');
|
||||
const [users, setUsers] = useState<Subscriber[]>([]);
|
||||
const [audit, setAudit] = useState<AuditEntry[]>([]);
|
||||
const [announceOpen, setAnnounceOpen] = useState(false);
|
||||
const isAdmin = !!(s.identity && s.identity.isAdmin);
|
||||
const isAdmin = !!s.identity?.isAdmin;
|
||||
|
||||
const loadSubscribers = useCallback(async () => {
|
||||
if (!isAdmin) return;
|
||||
const res = await safeCall<{ users?: Subscriber[] }>('ManageUsers', {
|
||||
action: 'list',
|
||||
});
|
||||
const list = (res && res.users) || [];
|
||||
const list = res?.users || [];
|
||||
setUsers(list);
|
||||
appStore.set({ listeners: list });
|
||||
}, [isAdmin]);
|
||||
@@ -30,186 +41,179 @@ export function ServerView() {
|
||||
const loadAudit = useCallback(async () => {
|
||||
if (!isAdmin) return;
|
||||
const res = await safeCall<{ entries?: AuditEntry[] }>('GetAuditLog');
|
||||
// Newest first — the server keeps a bounded ring in insertion order.
|
||||
setAudit(((res && res.entries) || []).slice().reverse());
|
||||
setAudit((res?.entries || []).slice().reverse());
|
||||
}, [isAdmin]);
|
||||
|
||||
useEffect(() => {
|
||||
loadSubscribers();
|
||||
loadAudit();
|
||||
}, [loadSubscribers, loadAudit]);
|
||||
if (tab === 'subscribers') void loadSubscribers();
|
||||
if (tab === 'audit') void loadAudit();
|
||||
}, [tab, loadSubscribers, loadAudit]);
|
||||
|
||||
if (!isAdmin) {
|
||||
return (
|
||||
<section className="view" id="view-server">
|
||||
<div className="card admin-guard">
|
||||
<h2>{t('Administrator authentication required')}</h2>
|
||||
<p className="muted">
|
||||
{t('Sign in with an account in a configured TeamSpeak admin group.')}
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="view" id="view-server">
|
||||
<div className="card">
|
||||
<div className="card-head">
|
||||
<h2>
|
||||
{t('Subscribers')}{' '}
|
||||
<span className="muted">
|
||||
{users.length ? `· ${users.length}` : ''}
|
||||
</span>
|
||||
</h2>
|
||||
<div className="row-gap">
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={() => setAnnounceOpen(true)}
|
||||
>
|
||||
<div className="admin-tabs" role="tablist" aria-label={t('Administration')}>
|
||||
{TABS.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
className={'admin-tab' + (tab === item.id ? ' active' : '')}
|
||||
role="tab"
|
||||
aria-selected={tab === item.id}
|
||||
onClick={() => setTab(item.id)}
|
||||
>
|
||||
{t(item.label)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{tab === 'teamspeak' && <TeamSpeakAdmin />}
|
||||
|
||||
{tab === 'echoion' && (
|
||||
<div className="card">
|
||||
<div className="card-head">
|
||||
<div>
|
||||
<h2>{t('Echoion service')}</h2>
|
||||
<p className="muted">{t('Bot messaging and runtime operations')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin-action-grid">
|
||||
<button className="btn btn-ghost" onClick={() => setAnnounceOpen(true)}>
|
||||
{t('Announce…')}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={async () => {
|
||||
await safeCall('ReloadConfig');
|
||||
toast(t('Configuration reloaded'));
|
||||
if (await safeCall('ReloadConfig')) toast(t('Configuration reloaded'));
|
||||
}}
|
||||
>
|
||||
{t('Reload config')}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
title={t(
|
||||
'Stop and start the web server without touching the bot'
|
||||
)}
|
||||
onClick={async () => {
|
||||
if (
|
||||
!(await confirmDialog({
|
||||
title: t('Restart web UI'),
|
||||
message: t(
|
||||
'Restart the web interface? Everyone disconnects briefly.'
|
||||
),
|
||||
message: t('Restart the web interface? Everyone disconnects briefly.'),
|
||||
confirmLabel: t('Restart'),
|
||||
}))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const res = await safeCall(
|
||||
'RestartWebInterface'
|
||||
);
|
||||
if (res) {
|
||||
toast(
|
||||
t(
|
||||
'Web interface restarting — this page will reconnect'
|
||||
)
|
||||
);
|
||||
}
|
||||
) return;
|
||||
if (await safeCall('RestartWebInterface'))
|
||||
toast(t('Web interface restarting — this page will reconnect'));
|
||||
}}
|
||||
>
|
||||
{t('Restart web UI')}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-danger-ghost"
|
||||
onClick={async () => {
|
||||
if (
|
||||
!(await confirmDialog({
|
||||
title: t('Unsub all'),
|
||||
message: t(
|
||||
'Remove ALL subscriptions? This cannot be undone.'
|
||||
),
|
||||
confirmLabel: t('Remove all'),
|
||||
danger: true,
|
||||
}))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
await safeCall('ManageUsers', {
|
||||
action: 'clearAll',
|
||||
});
|
||||
toast(t('All subscriptions removed'));
|
||||
loadSubscribers();
|
||||
}}
|
||||
>
|
||||
{t('Unsub all')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="people">
|
||||
{!users.length ? (
|
||||
<EmptyRow text={t('No subscribers')} />
|
||||
) : (
|
||||
users.map((u) => (
|
||||
)}
|
||||
|
||||
{tab === 'subscribers' && (
|
||||
<div className="card">
|
||||
<div className="card-head">
|
||||
<h2>{t('Subscribers')} <span className="muted">· {users.length}</span></h2>
|
||||
<div className="row-gap">
|
||||
<button className="btn btn-ghost" onClick={loadSubscribers}>{t('Refresh')}</button>
|
||||
<button
|
||||
className="btn btn-danger-ghost"
|
||||
onClick={async () => {
|
||||
if (
|
||||
!(await confirmDialog({
|
||||
title: t('Unsub all'),
|
||||
message: t('Remove ALL subscriptions? This cannot be undone.'),
|
||||
confirmLabel: t('Remove all'),
|
||||
danger: true,
|
||||
}))
|
||||
) return;
|
||||
if (await safeCall('ManageUsers', { action: 'clearAll' })) {
|
||||
toast(t('All subscriptions removed'));
|
||||
void loadSubscribers();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t('Unsub all')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="people">
|
||||
{users.length ? users.map((user) => (
|
||||
<PersonRow
|
||||
key={u.uid}
|
||||
name={u.nickname || u.uid}
|
||||
uid={u.uid}
|
||||
sub={u.uid}
|
||||
status={u.online ? t('Online') : t('Offline')}
|
||||
statusColor={u.online ? '#5fe094' : '#6a6a78'}
|
||||
key={user.uid}
|
||||
name={user.nickname || user.uid}
|
||||
uid={user.uid}
|
||||
sub={user.uid}
|
||||
status={user.online ? t('Online') : t('Offline')}
|
||||
statusColor={user.online ? '#5fe094' : '#6a6a78'}
|
||||
>
|
||||
<button
|
||||
className="btn btn-danger-ghost"
|
||||
onClick={async () => {
|
||||
const who = u.nickname || u.uid;
|
||||
const who = user.nickname || user.uid;
|
||||
if (
|
||||
!(await confirmDialog({
|
||||
title: t('Unsubscribe'),
|
||||
message: tf(
|
||||
'Unsubscribe {0}?',
|
||||
who
|
||||
),
|
||||
message: tf('Unsubscribe {0}?', who),
|
||||
confirmLabel: t('Unsub'),
|
||||
danger: true,
|
||||
}))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
await safeCall('ManageUsers', {
|
||||
action: 'remove',
|
||||
uid: u.uid,
|
||||
});
|
||||
toast(tf('Unsubscribed {0}', who));
|
||||
loadSubscribers();
|
||||
) return;
|
||||
if (await safeCall('ManageUsers', { action: 'remove', uid: user.uid }))
|
||||
void loadSubscribers();
|
||||
}}
|
||||
>
|
||||
{t('Unsub')}
|
||||
</button>
|
||||
</PersonRow>
|
||||
))
|
||||
)}
|
||||
)) : <EmptyRow text={t('No subscribers')} />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="card">
|
||||
<div className="card-head">
|
||||
<h2>
|
||||
{t('Audit log')}{' '}
|
||||
<span className="muted">
|
||||
{audit.length ? `· ${audit.length}` : ''}
|
||||
</span>
|
||||
</h2>
|
||||
<button className="btn btn-ghost" onClick={loadAudit}>
|
||||
{t('Refresh')}
|
||||
</button>
|
||||
</div>
|
||||
{/* Cap the rendered rows; the header still shows the full count
|
||||
and the container scrolls instead of growing endlessly. */}
|
||||
<div className="tracklist audit-scroll">
|
||||
{!audit.length ? (
|
||||
<EmptyRow text={t('No audit entries yet')} />
|
||||
) : (
|
||||
audit.slice(0, 200).map((e, i) => (
|
||||
<div
|
||||
key={`${e.timestamp}-${i}`}
|
||||
className="audit-row"
|
||||
>
|
||||
<span className="audit-method">
|
||||
{auditMethodName(e.method)}
|
||||
</span>
|
||||
<span className="audit-client muted">
|
||||
{tf('client #{0}', e.clientId)}
|
||||
</span>
|
||||
<span className="audit-time muted">
|
||||
{new Date(
|
||||
e.timestamp * 1000
|
||||
).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<EmojiManager />
|
||||
{announceOpen && (
|
||||
<AnnounceModal onClose={() => setAnnounceOpen(false)} />
|
||||
)}
|
||||
|
||||
{tab === 'emojis' && (
|
||||
<div className="card">
|
||||
<h2>{t('Emojis')}</h2>
|
||||
<p className="muted">
|
||||
{t('Room emojis moved to VoidWatch and are managed from its administration page.')}
|
||||
</p>
|
||||
{s.watchUrl && (
|
||||
<a className="btn btn-ghost" href={`${s.watchUrl.replace(/\/$/, '')}/admin.html`}>
|
||||
{t('Open VoidWatch admin ↗')}
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tab === 'audit' && (
|
||||
<div className="card">
|
||||
<div className="card-head">
|
||||
<h2>{t('Audit history')} <span className="muted">· {audit.length}</span></h2>
|
||||
<button className="btn btn-ghost" onClick={loadAudit}>{t('Refresh')}</button>
|
||||
</div>
|
||||
<div className="tracklist audit-scroll">
|
||||
{audit.length ? audit.slice(0, 200).map((entry, index) => (
|
||||
<div key={`${entry.timestamp}-${index}`} className="audit-row">
|
||||
<span className="audit-method">{auditMethodName(entry.method)}</span>
|
||||
<span className="audit-client muted">{tf('client #{0}', entry.clientId)}</span>
|
||||
<span className="audit-time muted">{new Date(entry.timestamp * 1000).toLocaleString()}</span>
|
||||
</div>
|
||||
)) : <EmptyRow text={t('No audit entries yet')} />}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{announceOpen && <AnnounceModal onClose={() => setAnnounceOpen(false)} />}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { appStore } from '../lib/app';
|
||||
import { UpdatesView } from './UpdatesView';
|
||||
|
||||
afterEach(() => appStore.set({ identity: null }));
|
||||
|
||||
describe('UpdatesView authorization', () => {
|
||||
it('shows an authorization guard to non-administrators', () => {
|
||||
appStore.set({ identity: { nickname: 'listener', isAdmin: false } });
|
||||
const html = renderToStaticMarkup(<UpdatesView />);
|
||||
expect(html).toContain('Administrator authentication required');
|
||||
expect(html).not.toContain('Check now');
|
||||
});
|
||||
|
||||
it('renders the update controls only for an administrator', () => {
|
||||
appStore.set({ identity: { nickname: 'operator', isAdmin: true } });
|
||||
const html = renderToStaticMarkup(<UpdatesView />);
|
||||
expect(html).toContain('Check now');
|
||||
expect(html).toContain('Update history');
|
||||
expect(html).not.toContain('Administrator authentication required');
|
||||
expect(html).toContain('aria-live="polite"');
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,789 +0,0 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { toast } from '../lib/app';
|
||||
import { useStore } from '../lib/store';
|
||||
import {
|
||||
attachPlayerMount,
|
||||
applyExtraControl,
|
||||
applyLocalVolume,
|
||||
currentPlayerPositionMs,
|
||||
isHost,
|
||||
joinRoom,
|
||||
leaveRoom,
|
||||
livePositionMs,
|
||||
playerBufferedFraction,
|
||||
refreshRooms,
|
||||
seekRelative,
|
||||
send,
|
||||
setRate,
|
||||
setSourceChoice,
|
||||
transferHost,
|
||||
unmuteAutoplay,
|
||||
voteSkip,
|
||||
watchStore,
|
||||
} from '../lib/watch';
|
||||
import { Avatar } from '../components/Avatar';
|
||||
import { PlayerControls } from '../components/PlayerControls';
|
||||
import { PlayerSettingsMenu } from '../components/PlayerSettingsMenu';
|
||||
import { EmptyRow } from '../components/TrackRow';
|
||||
import { WatchSearch } from '../components/WatchSearch';
|
||||
import { EmojiPicker } from '../components/EmojiPicker';
|
||||
import { renderChatText } from '../lib/emoji';
|
||||
import { useControlsAutoHide } from '../lib/useControlsAutoHide';
|
||||
import {
|
||||
CloseIcon,
|
||||
CrownIcon,
|
||||
PlusIcon,
|
||||
PowerIcon,
|
||||
RefreshIcon,
|
||||
SkipNextIcon,
|
||||
VolumeMuteIcon,
|
||||
WatchIcon,
|
||||
} from '../components/icons';
|
||||
import { t, tf } from '../i18n';
|
||||
|
||||
const REACTION_EMOJI = ['🔥', '😂', '👀', '❤️'];
|
||||
|
||||
export function WatchView() {
|
||||
const w = useStore(watchStore);
|
||||
const playerRef = useRef<HTMLDivElement>(null);
|
||||
const playerShellRef = useRef<HTMLDivElement>(null);
|
||||
const chatLogRef = useRef<HTMLDivElement>(null);
|
||||
const [url, setUrl] = useState('');
|
||||
const [chatText, setChatText] = useState('');
|
||||
const [newRoom, setNewRoom] = useState('');
|
||||
const [chatPicker, setChatPicker] = useState(false);
|
||||
const [reactPicker, setReactPicker] = useState(false);
|
||||
// Re-render every 500ms while mounted so the position readout ticks
|
||||
// (mirrors the old renderPositions interval).
|
||||
const [, setTick] = useState(0);
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => setTick((n) => n + 1), 500);
|
||||
return () => clearInterval(id);
|
||||
}, []);
|
||||
|
||||
// Re-attach when entering/leaving a room: the player div unmounts in the
|
||||
// lobby (w.room === null) and remounts on join, so the mount must follow it.
|
||||
useEffect(() => {
|
||||
attachPlayerMount(playerRef.current);
|
||||
return () => attachPlayerMount(null);
|
||||
}, [w.room]);
|
||||
|
||||
useEffect(() => {
|
||||
const log = chatLogRef.current;
|
||||
if (log) log.scrollTop = log.scrollHeight;
|
||||
}, [w.chat.length]);
|
||||
|
||||
// "Live" = no position authority / no seek: Twitch, and generic embeds
|
||||
// unless the embed answered the postMessage handshake (server-confirmed
|
||||
// via the room's `controllable` flag).
|
||||
const live =
|
||||
w.source === 'twitch' ||
|
||||
(w.source === 'iframe' && !w.embedControlled);
|
||||
const hosting = isHost();
|
||||
const canControl = w.authenticated && hosting;
|
||||
const choice = w.sourceChoice;
|
||||
const hasPlayer = !!(w.videoId || w.url);
|
||||
const pos = livePositionMs();
|
||||
// Idle-hide the overlay controls + cursor while a video plays (windowed
|
||||
// and fullscreen). Called before the early return below to keep hook order.
|
||||
const controlsHidden = useControlsAutoHide(playerShellRef, {
|
||||
playing: !w.paused,
|
||||
enabled: hasPlayer,
|
||||
});
|
||||
|
||||
// Lobby: no room joined by default. Pick an existing room or create one.
|
||||
if (w.room == null) {
|
||||
return (
|
||||
<WatchLobby
|
||||
rooms={w.rooms}
|
||||
newRoom={newRoom}
|
||||
setNewRoom={setNewRoom}
|
||||
onRefresh={refreshRooms}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="view" id="view-watch">
|
||||
<div className="watch-grid">
|
||||
<div className="col">
|
||||
<div className="card">
|
||||
<div className="card-head">
|
||||
<div className="row-gap">
|
||||
<button
|
||||
className={
|
||||
'btn src-yt' +
|
||||
(choice === 'youtube' ? ' active' : '')
|
||||
}
|
||||
onClick={() => setSourceChoice('youtube')}
|
||||
>
|
||||
YouTube
|
||||
</button>
|
||||
<button
|
||||
className={
|
||||
'btn src-tw' +
|
||||
(choice === 'twitch' ? ' active' : '')
|
||||
}
|
||||
onClick={() => setSourceChoice('twitch')}
|
||||
>
|
||||
Twitch
|
||||
</button>
|
||||
<button
|
||||
className={
|
||||
'btn src-direct' +
|
||||
(choice === 'direct' ? ' active' : '')
|
||||
}
|
||||
onClick={() => setSourceChoice('direct')}
|
||||
>
|
||||
{t('Video URL')}
|
||||
</button>
|
||||
<button
|
||||
className={
|
||||
'btn src-iframe' +
|
||||
(choice === 'iframe' ? ' active' : '')
|
||||
}
|
||||
onClick={() => setSourceChoice('iframe')}
|
||||
>
|
||||
{t('Embed')}
|
||||
</button>
|
||||
</div>
|
||||
<div className="row-gap">
|
||||
<span className="pill pill-room" title={t('Room')}>
|
||||
<WatchIcon /> {w.room}
|
||||
</span>
|
||||
<span
|
||||
className={
|
||||
'pill' + (hosting ? ' pill-yellow' : '')
|
||||
}
|
||||
>
|
||||
{!w.authenticated
|
||||
? t('Guest — sign in to control')
|
||||
: hosting
|
||||
? t('You are hosting')
|
||||
: t('Viewer')}
|
||||
</span>
|
||||
<span className="pill pill-green">
|
||||
{t('Synced')}
|
||||
</span>
|
||||
{w.source === 'iframe' && hasPlayer && (
|
||||
<span
|
||||
className={
|
||||
'pill' +
|
||||
(w.embedControlled
|
||||
? ' pill-green'
|
||||
: '')
|
||||
}
|
||||
>
|
||||
{w.embedControlled
|
||||
? w.embedProtocol
|
||||
? `${t('Embed synced')} · ${w.embedProtocol}`
|
||||
: t('Embed synced')
|
||||
: t('Embed is view-only')}
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
className="btn btn-leave"
|
||||
title={t('Leave this room')}
|
||||
onClick={() => leaveRoom()}
|
||||
>
|
||||
<PowerIcon /> {t('Leave room')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<form
|
||||
className="search-row"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const input = url.trim();
|
||||
if (!input) return;
|
||||
if (choice === 'twitch') {
|
||||
send({
|
||||
type: 'watch.load',
|
||||
source: 'twitch',
|
||||
channel: input,
|
||||
url: input,
|
||||
});
|
||||
} else {
|
||||
send({
|
||||
type: 'watch.load',
|
||||
source: choice,
|
||||
url: input,
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
<input
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
placeholder={
|
||||
choice === 'twitch'
|
||||
? t(
|
||||
'Twitch channel or URL to watch together'
|
||||
)
|
||||
: choice === 'direct'
|
||||
? t(
|
||||
'Direct video or .m3u8 URL to watch together'
|
||||
)
|
||||
: choice === 'iframe'
|
||||
? t(
|
||||
'Embed URL (Kodik, etc.) to watch together'
|
||||
)
|
||||
: t(
|
||||
'YouTube URL to watch together'
|
||||
)
|
||||
}
|
||||
autoComplete="off"
|
||||
disabled={!w.authenticated}
|
||||
/>
|
||||
<button className="btn btn-accent" type="submit">
|
||||
{t('Load')}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
type="button"
|
||||
title={t('Add to the watch queue')}
|
||||
disabled={!w.authenticated}
|
||||
onClick={async () => {
|
||||
const input = url.trim();
|
||||
if (!input) return;
|
||||
const source = w.sourceChoice;
|
||||
let title = '';
|
||||
if (source === 'youtube') {
|
||||
// Best-effort title so the queue shows
|
||||
// names instead of URLs.
|
||||
try {
|
||||
const res = await fetch(
|
||||
`https://www.youtube.com/oembed?url=${encodeURIComponent(input)}&format=json`
|
||||
);
|
||||
if (res.ok) {
|
||||
title =
|
||||
(await res.json()).title ||
|
||||
'';
|
||||
}
|
||||
} catch {
|
||||
/* offline or blocked */
|
||||
}
|
||||
}
|
||||
send({
|
||||
type: 'watch.queue.add',
|
||||
source,
|
||||
url: input,
|
||||
title,
|
||||
});
|
||||
setUrl('');
|
||||
}}
|
||||
>
|
||||
{t('+ Queue')}
|
||||
</button>
|
||||
</form>
|
||||
{/* The shell (player + custom bar) is what goes
|
||||
fullscreen, so the controls stay available; the bar
|
||||
overlays the video and idle-hides during playback. */}
|
||||
<div
|
||||
className={
|
||||
'player-shell' +
|
||||
(w.source === 'youtube' ? ' youtube-native' : '') +
|
||||
(controlsHidden ? ' controls-hidden' : '')
|
||||
}
|
||||
ref={playerShellRef}
|
||||
>
|
||||
<div className="player-box">
|
||||
<div ref={playerRef} id="watchPlayer" />
|
||||
{w.playerEmpty && (
|
||||
<div className="player-empty">
|
||||
{t(w.playerEmpty)}
|
||||
</div>
|
||||
)}
|
||||
{w.mutedAutoplay && (
|
||||
<button
|
||||
className="btn btn-accent unmute-btn"
|
||||
title={t('Tap to unmute')}
|
||||
onClick={() => unmuteAutoplay()}
|
||||
>
|
||||
<VolumeMuteIcon /> {t('Tap to unmute')}
|
||||
</button>
|
||||
)}
|
||||
<div className="reaction-layer">
|
||||
{w.reactions.map((r) => (
|
||||
<span
|
||||
key={r.id}
|
||||
className="reaction-fly reaction-fly-abs"
|
||||
style={{
|
||||
left: `${10 + ((r.id * 37) % 80)}%`,
|
||||
}}
|
||||
>
|
||||
{/^:[a-z0-9_]+:$/.test(r.emoji) ? (
|
||||
<img
|
||||
className="emoji-img-lg"
|
||||
src={`/emoji/${r.emoji.slice(1, -1)}`}
|
||||
alt={r.emoji}
|
||||
/>
|
||||
) : (
|
||||
r.emoji
|
||||
)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="player-overlay">
|
||||
<PlayerControls
|
||||
playing={!w.paused}
|
||||
positionMs={pos}
|
||||
durationMs={w.durationMs}
|
||||
live={live}
|
||||
canControl={canControl}
|
||||
bufferedPct={playerBufferedFraction() * 100}
|
||||
volumePct={w.localVolume}
|
||||
volumeLive
|
||||
onTogglePlay={() =>
|
||||
send({
|
||||
type: w.paused
|
||||
? 'watch.play'
|
||||
: 'watch.pause',
|
||||
positionMs: currentPlayerPositionMs(),
|
||||
})
|
||||
}
|
||||
onSeekMs={(ms) =>
|
||||
send({
|
||||
type: 'watch.seek',
|
||||
positionMs: ms,
|
||||
})
|
||||
}
|
||||
onSeekBy={seekRelative}
|
||||
onVolume={(pct) => applyLocalVolume(pct)}
|
||||
onSkip={() =>
|
||||
send({ type: 'watch.queue.next' })
|
||||
}
|
||||
skipDisabled={!w.queue.length}
|
||||
settings={
|
||||
<PlayerSettingsMenu
|
||||
extras={w.extraControls}
|
||||
rate={w.rate}
|
||||
rateOptions={
|
||||
w.source === 'youtube' ||
|
||||
w.extraControls.some((c) => c.id === 'speed')
|
||||
? [0.5, 0.75, 1, 1.25, 1.5, 2]
|
||||
: undefined
|
||||
}
|
||||
canControl={canControl}
|
||||
onExtra={applyExtraControl}
|
||||
onRate={setRate}
|
||||
/>
|
||||
}
|
||||
onFullscreen={() => {
|
||||
if (document.fullscreenElement) {
|
||||
document.exitFullscreen();
|
||||
} else {
|
||||
playerShellRef.current
|
||||
?.requestFullscreen()
|
||||
.catch(() =>
|
||||
toast(
|
||||
t('Fullscreen unavailable')
|
||||
)
|
||||
);
|
||||
}
|
||||
}}
|
||||
showLocal={hasPlayer}
|
||||
extra={
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={() => {
|
||||
send({ type: 'watch.state' });
|
||||
toast(t('Resynced to room'));
|
||||
}}
|
||||
>
|
||||
{t('Resync')}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="reactions">
|
||||
{REACTION_EMOJI.map((emoji) => (
|
||||
<button
|
||||
key={emoji}
|
||||
className="reaction"
|
||||
onClick={() =>
|
||||
send({ type: 'watch.reaction', emoji })
|
||||
}
|
||||
>
|
||||
{emoji}
|
||||
</button>
|
||||
))}
|
||||
<div className="emoji-anchor">
|
||||
<button
|
||||
className="reaction"
|
||||
onClick={() => setReactPicker((o) => !o)}
|
||||
>
|
||||
<PlusIcon />
|
||||
</button>
|
||||
{reactPicker && (
|
||||
<EmojiPicker
|
||||
onClose={() => setReactPicker(false)}
|
||||
onPick={(token) => {
|
||||
send({
|
||||
type: 'watch.reaction',
|
||||
emoji: token,
|
||||
});
|
||||
setReactPicker(false);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="card">
|
||||
<div className="card-head">
|
||||
<h3>
|
||||
{t('Up Next')}{' '}
|
||||
<span className="muted">
|
||||
{w.queue.length
|
||||
? `· ${w.queue.length}`
|
||||
: ''}
|
||||
</span>
|
||||
</h3>
|
||||
<div className="row-gap">
|
||||
{hasPlayer && (
|
||||
<button
|
||||
className={
|
||||
'btn btn-ghost voteskip' +
|
||||
(w.skipVoted ? ' on' : '')
|
||||
}
|
||||
onClick={voteSkip}
|
||||
>
|
||||
{w.skipVotes > 0
|
||||
? tf(
|
||||
'Vote skip {0}/{1}',
|
||||
w.skipVotes,
|
||||
w.skipNeeded
|
||||
)
|
||||
: t('Vote skip')}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
title={t('Host only')}
|
||||
disabled={!canControl || !w.queue.length}
|
||||
onClick={() =>
|
||||
send({ type: 'watch.queue.next' })
|
||||
}
|
||||
>
|
||||
{t('Play next')} <SkipNextIcon />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<WatchSearch disabled={!w.authenticated} />
|
||||
<div className="tracklist">
|
||||
{!w.queue.length ? (
|
||||
<EmptyRow
|
||||
text={t(
|
||||
'Nothing queued — paste a URL and hit “+ Queue”'
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
w.queue.map((item, i) => (
|
||||
<div key={i} className="track-row">
|
||||
<span className="track-num">
|
||||
{String(i + 1).padStart(2, '0')}
|
||||
</span>
|
||||
<div
|
||||
className="track-cover"
|
||||
style={
|
||||
item.thumbnailUrl
|
||||
? {
|
||||
background: `url("${item.thumbnailUrl}") center/cover`,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<div className="track-main">
|
||||
<div className="track-title">
|
||||
{item.title ||
|
||||
item.url ||
|
||||
item.videoId}
|
||||
</div>
|
||||
<div className="track-sub">
|
||||
{[
|
||||
item.source === 'twitch'
|
||||
? 'Twitch'
|
||||
: 'YouTube',
|
||||
item.addedBy
|
||||
? tf(
|
||||
'added by {0}',
|
||||
item.addedBy
|
||||
)
|
||||
: '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ')}
|
||||
</div>
|
||||
</div>
|
||||
{w.authenticated && (
|
||||
<div className="track-actions">
|
||||
<button
|
||||
className="icon-btn danger"
|
||||
title={t(
|
||||
'Remove from queue'
|
||||
)}
|
||||
onClick={() =>
|
||||
send({
|
||||
type: 'watch.queue.remove',
|
||||
index: i,
|
||||
})
|
||||
}
|
||||
>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col">
|
||||
<div className="card">
|
||||
<div className="card-head">
|
||||
<h3>
|
||||
{t('In the room')}{' '}
|
||||
<span className="muted">
|
||||
· {w.participantCount}
|
||||
</span>
|
||||
</h3>
|
||||
</div>
|
||||
<div className="people">
|
||||
{w.participants.map((p) => {
|
||||
let status = '—';
|
||||
let color = '#6a6a78';
|
||||
if (p.buffering) {
|
||||
status = t('Buffering…');
|
||||
color = '#ffcf4a';
|
||||
} else if (
|
||||
p.offsetMs != null &&
|
||||
p.offsetMs !== -1
|
||||
) {
|
||||
const off = Math.round(p.offsetMs);
|
||||
status =
|
||||
Math.abs(off) < 200
|
||||
? t('In sync')
|
||||
: `${off > 0 ? '+' : ''}${off}ms`;
|
||||
color =
|
||||
Math.abs(off) < 200
|
||||
? '#5fe094'
|
||||
: Math.abs(off) > 800
|
||||
? '#ff9090'
|
||||
: '#8a8a98';
|
||||
}
|
||||
return (
|
||||
<div key={p.id} className="person">
|
||||
<Avatar name={p.name} uid={p.uid} />
|
||||
<div className="person-main">
|
||||
<div className="person-name">
|
||||
{p.name}
|
||||
{p.id === w.selfId
|
||||
? ` ${t('(you)')}`
|
||||
: ''}
|
||||
</div>
|
||||
{p.host && (
|
||||
<div className="person-sub">
|
||||
{t('Host')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{hosting &&
|
||||
p.id !== w.selfId &&
|
||||
!p.host && (
|
||||
<button
|
||||
className="icon-btn"
|
||||
title={t('Make host')}
|
||||
onClick={() =>
|
||||
transferHost(p.id)
|
||||
}
|
||||
>
|
||||
<CrownIcon />
|
||||
</button>
|
||||
)}
|
||||
<span
|
||||
className="person-status"
|
||||
style={{ color }}
|
||||
>
|
||||
{status}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className="card chat-card">
|
||||
<div className="card-head">
|
||||
<h3>{t('Room chat')}</h3>
|
||||
</div>
|
||||
<div className="chat-log" ref={chatLogRef}>
|
||||
{w.chat.map((m, i) => (
|
||||
<div key={i} className="chat-msg">
|
||||
<Avatar name={m.name} size={26} />
|
||||
<div className="chat-body">
|
||||
<span className="chat-name">
|
||||
{m.name}
|
||||
</span>
|
||||
<span className="chat-time">
|
||||
{new Date(
|
||||
m.at
|
||||
).toLocaleTimeString([], {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
})}
|
||||
</span>
|
||||
<div className="chat-text">
|
||||
{renderChatText(m.text).map(
|
||||
(part, j) =>
|
||||
typeof part ===
|
||||
'string' ? (
|
||||
<span key={j}>
|
||||
{part}
|
||||
</span>
|
||||
) : (
|
||||
<img
|
||||
key={j}
|
||||
className="emoji-img"
|
||||
src={`/emoji/${part.emojiName}`}
|
||||
alt={`:${part.emojiName}:`}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<form
|
||||
className="chat-row"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const text = chatText.trim();
|
||||
if (!text) return;
|
||||
send({ type: 'watch.chat', text });
|
||||
setChatText('');
|
||||
}}
|
||||
>
|
||||
<div className="emoji-anchor">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost emoji-trigger"
|
||||
onClick={() => setChatPicker((o) => !o)}
|
||||
>
|
||||
😊
|
||||
</button>
|
||||
{chatPicker && (
|
||||
<EmojiPicker
|
||||
onClose={() => setChatPicker(false)}
|
||||
onPick={(token) => {
|
||||
setChatText(
|
||||
(prev) =>
|
||||
prev +
|
||||
(token.startsWith(':')
|
||||
? token
|
||||
: token)
|
||||
);
|
||||
setChatPicker(false);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<input
|
||||
value={chatText}
|
||||
onChange={(e) => setChatText(e.target.value)}
|
||||
placeholder={t('Say something…')}
|
||||
autoComplete="off"
|
||||
maxLength={500}
|
||||
/>
|
||||
<button className="btn btn-accent" type="submit">
|
||||
{t('Send')}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// The lobby shown when no room is joined (the default). Lists active rooms and
|
||||
// lets the user join one or create a new room by name.
|
||||
function WatchLobby(props: {
|
||||
rooms: ReturnType<typeof watchStore.get>['rooms'];
|
||||
newRoom: string;
|
||||
setNewRoom: (v: string) => void;
|
||||
onRefresh: () => void;
|
||||
}) {
|
||||
const { rooms, newRoom, setNewRoom, onRefresh } = props;
|
||||
useEffect(() => {
|
||||
onRefresh();
|
||||
}, [onRefresh]);
|
||||
return (
|
||||
<section className="view" id="view-watch">
|
||||
<div className="card watch-lobby">
|
||||
<div className="card-head">
|
||||
<h3>{t('Watch together')}</h3>
|
||||
<button
|
||||
className="pill"
|
||||
title={t('Refresh rooms')}
|
||||
onClick={() => onRefresh()}
|
||||
>
|
||||
<RefreshIcon /> {t('Refresh')}
|
||||
</button>
|
||||
</div>
|
||||
<p className="muted">
|
||||
{t('Join a room to watch in sync, or create your own.')}
|
||||
</p>
|
||||
<div className="rooms-list">
|
||||
{rooms.length === 0 && (
|
||||
<span className="muted">
|
||||
{t('No active rooms yet — create one below.')}
|
||||
</span>
|
||||
)}
|
||||
{rooms.map((r) => (
|
||||
<button
|
||||
key={r.name}
|
||||
className="room-chip"
|
||||
onClick={() => joinRoom(r.name)}
|
||||
title={r.nowTitle || undefined}
|
||||
>
|
||||
<WatchIcon /> {r.name}
|
||||
<span className="muted">
|
||||
{' '}
|
||||
· {tf('{0} watching', r.participants)}
|
||||
</span>
|
||||
{r.nowTitle && (
|
||||
<span className="room-now muted">
|
||||
{' '}
|
||||
· {r.nowTitle}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<form
|
||||
className="rooms-create"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (!newRoom.trim()) return;
|
||||
joinRoom(newRoom);
|
||||
setNewRoom('');
|
||||
}}
|
||||
>
|
||||
<input
|
||||
value={newRoom}
|
||||
onChange={(e) => setNewRoom(e.target.value)}
|
||||
placeholder={t('New room name…')}
|
||||
maxLength={48}
|
||||
/>
|
||||
<button className="btn btn-accent" type="submit">
|
||||
{t('Create / join')}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -17,9 +17,9 @@ export default defineConfig({
|
||||
server: {
|
||||
proxy: {
|
||||
'/config.json': 'http://127.0.0.1:8080',
|
||||
'/api': 'http://127.0.0.1:8080',
|
||||
'/avatar': 'http://127.0.0.1:8080',
|
||||
'/rpc': { target: 'ws://127.0.0.1:8080', ws: true },
|
||||
'/ws': { target: 'ws://127.0.0.1:8080', ws: true },
|
||||
},
|
||||
cors: true
|
||||
},
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
#pragma once
|
||||
|
||||
#include <boost/asio/ip/address.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <expected>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Web::Security
|
||||
{
|
||||
namespace asio = boost::asio;
|
||||
|
||||
class CidrBlock
|
||||
{
|
||||
public:
|
||||
|
||||
CidrBlock(asio::ip::address network, unsigned int prefixLength);
|
||||
|
||||
[[nodiscard]] bool contains(
|
||||
const asio::ip::address& address) const noexcept;
|
||||
|
||||
private:
|
||||
|
||||
asio::ip::address network_;
|
||||
unsigned int prefixLength_ = 0;
|
||||
};
|
||||
|
||||
using ParsedCidrs = std::expected<std::vector<CidrBlock>, std::string>;
|
||||
|
||||
[[nodiscard]] ParsedCidrs parseTrustedProxyCidrs(
|
||||
std::span<const std::string> cidrs);
|
||||
|
||||
[[nodiscard]] std::string effectiveClientAddress(
|
||||
const asio::ip::address& immediatePeer,
|
||||
std::optional<std::string_view> forwardedFor,
|
||||
std::span<const CidrBlock> trustedProxies);
|
||||
|
||||
[[nodiscard]] bool validShortSlug(std::string_view slug) noexcept;
|
||||
[[nodiscard]] bool validRedirectLocation(std::string_view location) noexcept;
|
||||
|
||||
class ShortLinkRateLimiter
|
||||
{
|
||||
public:
|
||||
|
||||
using Clock = std::chrono::steady_clock;
|
||||
using TimePoint = Clock::time_point;
|
||||
|
||||
struct Config {
|
||||
double globalRate = 200.0;
|
||||
double globalBurst = 400.0;
|
||||
double peerRate = 10.0;
|
||||
double peerBurst = 20.0;
|
||||
std::size_t maxPeers = 4096;
|
||||
Clock::duration idleTimeout = std::chrono::minutes(10);
|
||||
Clock::duration sweepInterval = std::chrono::minutes(1);
|
||||
};
|
||||
|
||||
ShortLinkRateLimiter();
|
||||
explicit ShortLinkRateLimiter(Config config);
|
||||
|
||||
[[nodiscard]] bool allow(std::string_view peer);
|
||||
[[nodiscard]] bool allow(std::string_view peer, TimePoint now);
|
||||
void reset();
|
||||
[[nodiscard]] std::size_t trackedPeerCount() const;
|
||||
|
||||
private:
|
||||
|
||||
struct TokenBucket {
|
||||
double tokens = 0.0;
|
||||
TimePoint updated{};
|
||||
bool initialized = false;
|
||||
};
|
||||
|
||||
struct PeerBucket {
|
||||
TokenBucket bucket;
|
||||
TimePoint lastSeen{};
|
||||
};
|
||||
|
||||
static void refill(TokenBucket& bucket, double rate, double burst,
|
||||
TimePoint now) noexcept;
|
||||
void evictIdle(TimePoint now, bool force);
|
||||
|
||||
Config config_;
|
||||
mutable std::mutex mutex_;
|
||||
TokenBucket global_;
|
||||
std::unordered_map<std::string, PeerBucket> peers_;
|
||||
TimePoint nextSweep_{};
|
||||
bool sweepInitialized_ = false;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Web::Security
|
||||
@@ -1,35 +1,34 @@
|
||||
#pragma once
|
||||
|
||||
#include "echoion/web/WatchSession.hpp"
|
||||
#include "echoion/web/HttpSecurity.hpp"
|
||||
|
||||
#include <Void/Async/ThreadPool.hpp>
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/beast.hpp>
|
||||
#include <boost/beast/http.hpp>
|
||||
#include <boost/beast/websocket.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <stop_token>
|
||||
#include <shared_mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Web
|
||||
{
|
||||
namespace asio = boost::asio;
|
||||
namespace beast = boost::beast;
|
||||
namespace http = beast::http;
|
||||
namespace websocket = beast::websocket;
|
||||
|
||||
// Serves the static browser UI over HTTP, hosts the independent
|
||||
// sync-watch WebSocket at GET /ws, and tunnels GET /rpc upgrades to the
|
||||
// local RPC server so only the web port ever needs to be exposed. It has
|
||||
// no handle on the music bot itself.
|
||||
// Serves the static browser UI over HTTP and tunnels GET /rpc upgrades to
|
||||
// the local RPC server so only the web port ever needs to be exposed. It
|
||||
// has no handle on the music bot itself.
|
||||
class HttpServer
|
||||
{
|
||||
public:
|
||||
@@ -41,10 +40,15 @@ namespace Echoion::Web
|
||||
// Explicit RPC URL served to the browser; when empty the UI
|
||||
// derives ws://<page-host>:<rpcPort>.
|
||||
std::string rpcUrl;
|
||||
// External VoidWatch deployment used by the temporary
|
||||
// /watch redirect and exposed to the browser in
|
||||
// /config.json.
|
||||
std::string watchUrl;
|
||||
uint16_t rpcPort = 8765;
|
||||
// Server-wide switch for the Now Playing video preview,
|
||||
// surfaced to the browser via /config.json.
|
||||
bool nowPlayingVideo = true;
|
||||
std::vector<std::string> trustedProxyCidrs;
|
||||
};
|
||||
|
||||
HttpServer();
|
||||
@@ -54,19 +58,16 @@ namespace Echoion::Web
|
||||
void stop();
|
||||
[[nodiscard]] bool isRunning() const { return running_; }
|
||||
|
||||
// Token → identity lookup for the watch feature; installed by
|
||||
// Core, which owns the credential store. May be set before or
|
||||
// after start() and survives stop()/start() cycles.
|
||||
void setIdentityResolver(
|
||||
WatchSessionManager::IdentityResolver resolver)
|
||||
{
|
||||
watch_.setIdentityResolver(std::move(resolver));
|
||||
}
|
||||
using TrustedProxyUpdate = std::expected<void, std::string>;
|
||||
[[nodiscard]] static TrustedProxyUpdate validateTrustedProxyCidrs(
|
||||
const std::vector<std::string>& cidrs);
|
||||
[[nodiscard]] TrustedProxyUpdate setTrustedProxyCidrs(
|
||||
const std::vector<std::string>& cidrs);
|
||||
|
||||
// A user's avatar image, served at GET /avatar/<uid>. Installed
|
||||
// by Core (which owns the TeamSpeak plugin handle); best-effort —
|
||||
// nullopt yields a 404 and the UI falls back to initials. Same
|
||||
// lifetime rules as the identity resolver.
|
||||
// nullopt yields a 404 and the UI falls back to initials. It may be
|
||||
// installed before or after start() and survives restarts.
|
||||
struct AvatarImage {
|
||||
std::string contentType;
|
||||
std::string bytes;
|
||||
@@ -79,15 +80,34 @@ namespace Echoion::Web
|
||||
avatarProvider_ = std::move(provider);
|
||||
}
|
||||
|
||||
// A custom emoji image, served at GET /emoji/<name>. Same shape
|
||||
// and lifetime rules as the avatar provider; installed by Core
|
||||
// (which owns the emoji database).
|
||||
using EmojiProvider = std::function<std::optional<AvatarImage>(
|
||||
const std::string& name)>;
|
||||
void setEmojiProvider(EmojiProvider provider)
|
||||
struct DashboardSnapshot {
|
||||
std::string body;
|
||||
std::string etag;
|
||||
};
|
||||
using DashboardProvider = std::function<DashboardSnapshot()>;
|
||||
void setDashboardProvider(DashboardProvider provider)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(avatarProviderMutex_);
|
||||
emojiProvider_ = std::move(provider);
|
||||
std::lock_guard<std::mutex> lock(dashboardProviderMutex_);
|
||||
dashboardProvider_ = std::move(provider);
|
||||
}
|
||||
|
||||
enum class ShortLinkStatus {
|
||||
found,
|
||||
notFound,
|
||||
gone,
|
||||
rateLimited,
|
||||
unavailable,
|
||||
};
|
||||
struct ShortLinkResolution {
|
||||
ShortLinkStatus status = ShortLinkStatus::notFound;
|
||||
std::string location;
|
||||
};
|
||||
using ShortLinkResolver =
|
||||
std::function<ShortLinkResolution(std::string_view key)>;
|
||||
void setShortLinkResolver(ShortLinkResolver resolver)
|
||||
{
|
||||
std::lock_guard lock(shortLinkResolverMutex_);
|
||||
shortLinkResolver_ = std::move(resolver);
|
||||
}
|
||||
|
||||
private:
|
||||
@@ -95,9 +115,8 @@ namespace Echoion::Web
|
||||
void acceptLoop();
|
||||
void doAccept();
|
||||
void onAccept(asio::ip::tcp::socket socket);
|
||||
void handleConnection(std::shared_ptr<asio::ip::tcp::socket> socket);
|
||||
void handleWatch(
|
||||
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws);
|
||||
void
|
||||
handleConnection(std::shared_ptr<asio::ip::tcp::socket> socket);
|
||||
// Tunnel a browser WebSocket upgrade at /rpc to the local RPC
|
||||
// server as raw TCP: the original upgrade request is replayed
|
||||
// upstream and bytes are pumped in both directions, so the real
|
||||
@@ -108,11 +127,12 @@ namespace Echoion::Web
|
||||
// Serves one request; returns true when the connection should be
|
||||
// kept open for the next request (HTTP keep-alive).
|
||||
bool serveHttp(asio::ip::tcp::socket& socket,
|
||||
const http::request<http::string_body>& req);
|
||||
bool serveWatchProxy(asio::ip::tcp::socket& socket,
|
||||
const http::request<http::string_body>& req);
|
||||
void sendToWatcher(uint64_t connId, const std::string& json);
|
||||
void syncLoop(std::stop_token stopToken);
|
||||
const http::request<http::string_body>& req,
|
||||
std::string_view clientAddress);
|
||||
[[nodiscard]] std::string clientAddress(
|
||||
const asio::ip::tcp::socket& socket,
|
||||
const http::request<http::string_body>& req) const;
|
||||
[[nodiscard]] bool allowShortLinkRequest(std::string_view peer);
|
||||
|
||||
Config config_;
|
||||
asio::io_context ioContext_;
|
||||
@@ -125,29 +145,28 @@ namespace Echoion::Web
|
||||
static constexpr std::size_t POOL_SIZE = 32;
|
||||
std::unique_ptr<Void::Concurrency::ThreadPool> pool_;
|
||||
|
||||
std::unordered_map<
|
||||
uint64_t,
|
||||
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>>>
|
||||
watchers_;
|
||||
std::mutex watchersMutex_;
|
||||
std::atomic<uint64_t> nextConnId_{1};
|
||||
|
||||
// Live /rpc bridges (browser, upstream); shut down on stop() so
|
||||
// the blocking pump loops unblock and the pool can join.
|
||||
std::unordered_map<uint64_t,
|
||||
std::pair<std::shared_ptr<asio::ip::tcp::socket>,
|
||||
std::shared_ptr<asio::ip::tcp::socket>>>
|
||||
std::unordered_map<
|
||||
uint64_t,
|
||||
std::pair<std::shared_ptr<asio::ip::tcp::socket>,
|
||||
std::shared_ptr<asio::ip::tcp::socket>>>
|
||||
bridges_;
|
||||
std::mutex bridgesMutex_;
|
||||
|
||||
WatchSessionManager watch_;
|
||||
std::jthread syncThread_;
|
||||
|
||||
// Called from pool threads; guarded so Core can (re)install them
|
||||
// at any time. Both share one mutex (installed together at start).
|
||||
// Called from pool threads; guarded so Core can (re)install it at
|
||||
// any time.
|
||||
AvatarProvider avatarProvider_;
|
||||
EmojiProvider emojiProvider_;
|
||||
std::mutex avatarProviderMutex_;
|
||||
DashboardProvider dashboardProvider_;
|
||||
std::mutex dashboardProviderMutex_;
|
||||
ShortLinkResolver shortLinkResolver_;
|
||||
std::mutex shortLinkResolverMutex_;
|
||||
mutable std::shared_mutex trustedProxyMutex_;
|
||||
std::vector<Security::CidrBlock> trustedProxyNetworks_;
|
||||
Security::ShortLinkRateLimiter shortLinkRateLimiter_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Web
|
||||
@@ -1,200 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace Echoion::Web
|
||||
{
|
||||
|
||||
// Authoritative state for synchronized video watching. This is entirely
|
||||
// independent of the music bot's playback pipeline: browsers play the video
|
||||
// locally and the server is only the timing authority for each room.
|
||||
//
|
||||
// The manager owns room state and participant membership. It never writes to
|
||||
// sockets directly -- HttpServer installs a `sender` callback and the manager
|
||||
// asks it to deliver JSON text to individual connections. That keeps all
|
||||
// Boost.Beast/socket concerns in HttpServer and makes this unit trivially
|
||||
// testable.
|
||||
//
|
||||
// Roles: the first *authenticated* participant to join a room is its host;
|
||||
// only the host may load/play/pause/seek and advance the queue, and every
|
||||
// control message additionally requires authentication (guests can watch,
|
||||
// chat and react but never manipulate). The host role migrates to another
|
||||
// authenticated participant when the host leaves. Twitch rooms are live:
|
||||
// there is no position authority, seek is refused, and everyone simply
|
||||
// embeds the same channel.
|
||||
//
|
||||
// Rooms with a loaded video survive everyone leaving: playback is paused
|
||||
// in place and the next authenticated joiner becomes host, so a page
|
||||
// refresh does not wipe the session. Abandoned rooms are pruned after
|
||||
// kEmptyRoomTtl.
|
||||
class WatchSessionManager
|
||||
{
|
||||
public:
|
||||
|
||||
// Delivers one JSON text frame to a single connection id.
|
||||
using Sender = std::function<void(uint64_t connId,
|
||||
const std::string& json)>;
|
||||
|
||||
// Authenticated identity behind an RPC token. The resolver is
|
||||
// installed by Core (it owns the token database); the manager
|
||||
// itself never sees credentials storage.
|
||||
struct Identity {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
bool isAdmin = false;
|
||||
};
|
||||
using IdentityResolver =
|
||||
std::function<std::optional<Identity>(const std::string& token)>;
|
||||
|
||||
// Best-effort title lookup for a queued video, so the watch queue
|
||||
// shows real names server-side instead of relying on the browser.
|
||||
// Installed by Core (which owns the YouTube metadata stack); when
|
||||
// unset or it returns nullopt, the client-supplied title (or the
|
||||
// Twitch channel name) is used. Called on the message thread, so
|
||||
// it must be quick / cached.
|
||||
using MetadataResolver = std::function<std::optional<std::string>(
|
||||
const std::string& source, const std::string& videoId,
|
||||
const std::string& url)>;
|
||||
|
||||
void setSender(Sender sender) { sender_ = std::move(sender); }
|
||||
void setIdentityResolver(IdentityResolver resolver)
|
||||
{
|
||||
identityResolver_ = std::move(resolver);
|
||||
}
|
||||
void setMetadataResolver(MetadataResolver resolver)
|
||||
{
|
||||
metadataResolver_ = std::move(resolver);
|
||||
}
|
||||
|
||||
// A watch WebSocket connected / disconnected. onDisconnect removes
|
||||
// the connection from whatever room it had joined and notifies the
|
||||
// remaining participants.
|
||||
void onConnect(uint64_t connId);
|
||||
void onDisconnect(uint64_t connId);
|
||||
|
||||
// Handle one inbound JSON message from a connection. Unknown or
|
||||
// malformed messages are ignored.
|
||||
void onMessage(uint64_t connId, const std::string& json);
|
||||
|
||||
// Broadcast a periodic sync heartbeat (position + participants) to
|
||||
// every room. HttpServer drives this on a timer so drifting
|
||||
// clients can re-align.
|
||||
void broadcastSync();
|
||||
|
||||
private:
|
||||
|
||||
struct Participant {
|
||||
std::string name;
|
||||
// TeamSpeak unique id when authenticated (empty for guests),
|
||||
// so the web UI can fetch the persisted avatar at /avatar.
|
||||
std::string uid;
|
||||
// Set when the join/rename carried a valid RPC token;
|
||||
// required for any control message and for hosting.
|
||||
bool authenticated = false;
|
||||
// Last client-reported playback position and the room
|
||||
// authority position at that moment (for drift display).
|
||||
long long reportedMs = -1;
|
||||
long long authorityMs = -1;
|
||||
bool buffering = false;
|
||||
};
|
||||
|
||||
struct ChatMessage {
|
||||
std::string name;
|
||||
std::string text;
|
||||
long long timestampMs = 0;
|
||||
};
|
||||
|
||||
// One queued-up video waiting to be watched after the current one.
|
||||
struct QueueEntry {
|
||||
std::string source; // youtube|twitch|direct|iframe
|
||||
std::string url;
|
||||
std::string videoId;
|
||||
std::string title; // resolved server-side, best effort
|
||||
std::string thumbnailUrl; // derived from source + id
|
||||
std::string addedBy;
|
||||
};
|
||||
|
||||
struct Room {
|
||||
std::string source = "youtube"; // youtube|twitch|direct|iframe
|
||||
std::string url;
|
||||
std::string videoId; // YouTube id / Twitch channel; empty
|
||||
// for direct & iframe (url carries it)
|
||||
// Host-reported (watch.embed.caps): the iframe embed answered
|
||||
// a postMessage handshake, so the room has real position
|
||||
// authority (seek allowed, position freezes when emptied).
|
||||
// Reset on every load until the host re-handshakes.
|
||||
bool controllable = false;
|
||||
bool paused = true;
|
||||
// Host-selected playback rate (YouTube only); 1.0 = normal.
|
||||
double rate = 1.0;
|
||||
// Host-selected provider media settings. Local-only settings
|
||||
// (volume, quality, subtitles) never enter room state.
|
||||
std::map<std::string, std::string> embedControls;
|
||||
// Position (ms) captured at `anchor`. While playing, the
|
||||
// live position is positionMs + (now - anchor).
|
||||
long long positionMs = 0;
|
||||
std::chrono::steady_clock::time_point anchor{
|
||||
std::chrono::steady_clock::now()};
|
||||
uint64_t host = 0;
|
||||
std::map<uint64_t, Participant> participants;
|
||||
std::deque<ChatMessage> chat; // last kChatBacklog kept
|
||||
std::deque<QueueEntry> queue; // up-next, kQueueMax cap
|
||||
// Connection ids that voted to skip the current video;
|
||||
// cleared whenever the video changes or a voter leaves.
|
||||
std::set<uint64_t> skipVotes;
|
||||
// When the room last had participants; drives pruning of
|
||||
// empty-but-persisted rooms.
|
||||
std::chrono::steady_clock::time_point lastActive{
|
||||
std::chrono::steady_clock::now()};
|
||||
};
|
||||
|
||||
static constexpr size_t kChatBacklog = 50;
|
||||
static constexpr size_t kQueueMax = 100;
|
||||
static constexpr size_t kEmbedControlsMax = 16;
|
||||
static constexpr std::chrono::hours kEmptyRoomTtl{24};
|
||||
|
||||
[[nodiscard]] long long livePosition(const Room& room) const;
|
||||
void send(uint64_t connId, const std::string& json) const;
|
||||
void broadcast(const Room& room, const std::string& json) const;
|
||||
void sendParticipants(const Room& room) const;
|
||||
void sendSnapshot(uint64_t connId, const Room& room) const;
|
||||
void sendDenied(uint64_t connId, const std::string& reason) const;
|
||||
void sendQueue(const Room& room, uint64_t onlyTo = 0) const;
|
||||
// Broadcast the vote-skip tally (votes / needed) for the room.
|
||||
void sendSkipState(const Room& room) const;
|
||||
// Votes needed to skip in a room: majority of participants.
|
||||
[[nodiscard]] static std::size_t skipThreshold(const Room& room);
|
||||
// Reply to watch.rooms.list with the lobby of active rooms.
|
||||
void sendRoomsList(uint64_t connId) const;
|
||||
// Deterministic thumbnail URL for a queued/loaded video.
|
||||
[[nodiscard]] static std::string
|
||||
thumbnailFor(const std::string& source,
|
||||
const std::string& videoId);
|
||||
// Point the room at a new video (shared by watch.load and
|
||||
// queue advancement) and broadcast watch.loaded.
|
||||
void loadIntoRoom(Room& room, const std::string& source,
|
||||
const std::string& url,
|
||||
const std::string& channel, uint64_t byConnId);
|
||||
// First authenticated participant, or 0 when only guests remain.
|
||||
[[nodiscard]] static uint64_t pickHost(const Room& room);
|
||||
void leaveCurrentRoom(uint64_t connId);
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
std::unordered_map<std::string, Room> rooms_;
|
||||
// connId -> room name it currently belongs to.
|
||||
std::unordered_map<uint64_t, std::string> connRoom_;
|
||||
Sender sender_;
|
||||
IdentityResolver identityResolver_;
|
||||
MetadataResolver metadataResolver_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Web
|
||||
@@ -0,0 +1,351 @@
|
||||
#include "echoion/web/HttpSecurity.hpp"
|
||||
|
||||
#include <boost/asio/ip/address_v6.hpp>
|
||||
#include <boost/url/parse.hpp>
|
||||
#include <boost/url/scheme.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <charconv>
|
||||
#include <cmath>
|
||||
#include <format>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace Echoion::Web::Security
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr std::size_t MAX_FORWARDED_HOPS = 64;
|
||||
constexpr std::size_t MAX_REDIRECT_LENGTH = 8192;
|
||||
|
||||
asio::ip::address
|
||||
normalizeMappedAddress(const asio::ip::address& address)
|
||||
{
|
||||
if (address.is_v6() && address.to_v6().is_v4_mapped()) {
|
||||
return asio::ip::make_address_v4(asio::ip::v4_mapped,
|
||||
address.to_v6());
|
||||
}
|
||||
return address;
|
||||
}
|
||||
|
||||
bool isTrusted(const asio::ip::address& address,
|
||||
std::span<const CidrBlock>
|
||||
trustedProxies) noexcept
|
||||
{
|
||||
return std::ranges::any_of(trustedProxies,
|
||||
[&address](const CidrBlock& network) {
|
||||
return network.contains(address);
|
||||
});
|
||||
}
|
||||
|
||||
std::string_view trimForwardedToken(std::string_view token) noexcept
|
||||
{
|
||||
while (!token.empty() &&
|
||||
(token.front() == ' ' || token.front() == '\t')) {
|
||||
token.remove_prefix(1);
|
||||
}
|
||||
while (!token.empty() &&
|
||||
(token.back() == ' ' || token.back() == '\t')) {
|
||||
token.remove_suffix(1);
|
||||
}
|
||||
return token;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
CidrBlock::CidrBlock(asio::ip::address network, unsigned int prefixLength)
|
||||
: network_(std::move(network)), prefixLength_(prefixLength)
|
||||
{
|
||||
}
|
||||
|
||||
bool CidrBlock::contains(const asio::ip::address& address) const noexcept
|
||||
{
|
||||
asio::ip::address candidate = address;
|
||||
if (network_.is_v4() && candidate.is_v6()) {
|
||||
if (!candidate.to_v6().is_v4_mapped()) {
|
||||
return false;
|
||||
}
|
||||
candidate = asio::ip::make_address_v4(asio::ip::v4_mapped,
|
||||
candidate.to_v6());
|
||||
} else if (network_.is_v6() && candidate.is_v4()) {
|
||||
candidate = asio::ip::make_address_v6(asio::ip::v4_mapped,
|
||||
candidate.to_v4());
|
||||
}
|
||||
if (network_.is_v4() != candidate.is_v4()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto matches = [this](const auto& lhs, const auto& rhs) {
|
||||
for (std::size_t index = 0; index < lhs.size(); ++index) {
|
||||
const auto consumed = static_cast<unsigned int>(index * 8);
|
||||
const auto remaining =
|
||||
prefixLength_ > consumed ? prefixLength_ - consumed : 0U;
|
||||
const auto mask = static_cast<unsigned char>(
|
||||
remaining >= 8 ? 0xffU
|
||||
: remaining == 0 ? 0U
|
||||
: 0xffU << (8 - remaining));
|
||||
if ((lhs[index] & mask) != (rhs[index] & mask)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
return network_.is_v4() ? matches(network_.to_v4().to_bytes(),
|
||||
candidate.to_v4().to_bytes())
|
||||
: matches(network_.to_v6().to_bytes(),
|
||||
candidate.to_v6().to_bytes());
|
||||
}
|
||||
|
||||
ParsedCidrs parseTrustedProxyCidrs(std::span<const std::string> cidrs)
|
||||
{
|
||||
std::vector<CidrBlock> parsed;
|
||||
parsed.reserve(cidrs.size());
|
||||
for (std::size_t index = 0; index < cidrs.size(); ++index) {
|
||||
const std::string_view cidr = cidrs[index];
|
||||
const auto slash = cidr.find('/');
|
||||
if (cidr.empty() || slash == 0 ||
|
||||
(slash != std::string_view::npos &&
|
||||
(slash + 1 == cidr.size() ||
|
||||
cidr.find('/', slash + 1) != std::string_view::npos))) {
|
||||
return std::unexpected(
|
||||
std::format("trusted proxy CIDR #{} ('{}') is malformed",
|
||||
index + 1, cidr));
|
||||
}
|
||||
|
||||
const std::string_view addressText = cidr.substr(0, slash);
|
||||
if (addressText.contains('%')) {
|
||||
return std::unexpected(std::format(
|
||||
"trusted proxy CIDR #{} ('{}') must not contain an IPv6 "
|
||||
"scope identifier",
|
||||
index + 1, cidr));
|
||||
}
|
||||
boost::system::error_code error;
|
||||
const auto network = asio::ip::make_address(addressText, error);
|
||||
if (error) {
|
||||
return std::unexpected(std::format(
|
||||
"trusted proxy CIDR #{} ('{}') has an invalid address",
|
||||
index + 1, cidr));
|
||||
}
|
||||
|
||||
const unsigned int maxBits = network.is_v4() ? 32U : 128U;
|
||||
unsigned int prefixLength = maxBits;
|
||||
if (slash != std::string_view::npos) {
|
||||
const std::string_view prefix = cidr.substr(slash + 1);
|
||||
const auto [end, code] = std::from_chars(
|
||||
prefix.data(), prefix.data() + prefix.size(), prefixLength);
|
||||
if (code != std::errc{} ||
|
||||
end != prefix.data() + prefix.size() ||
|
||||
prefixLength > maxBits) {
|
||||
return std::unexpected(std::format(
|
||||
"trusted proxy CIDR #{} ('{}') has an invalid prefix",
|
||||
index + 1, cidr));
|
||||
}
|
||||
}
|
||||
parsed.emplace_back(network, prefixLength);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
std::string effectiveClientAddress(const asio::ip::address& immediatePeer,
|
||||
std::optional<std::string_view>
|
||||
forwardedFor,
|
||||
std::span<const CidrBlock>
|
||||
trustedProxies)
|
||||
{
|
||||
const auto directAddress = normalizeMappedAddress(immediatePeer);
|
||||
if (!forwardedFor || !isTrusted(immediatePeer, trustedProxies)) {
|
||||
return directAddress.to_string();
|
||||
}
|
||||
|
||||
std::vector<asio::ip::address> hops;
|
||||
hops.reserve(8);
|
||||
std::string_view remaining = *forwardedFor;
|
||||
for (;;) {
|
||||
if (hops.size() == MAX_FORWARDED_HOPS) {
|
||||
return directAddress.to_string();
|
||||
}
|
||||
const auto comma = remaining.find(',');
|
||||
const auto token = trimForwardedToken(remaining.substr(0, comma));
|
||||
if (token.empty() || token.contains('%')) {
|
||||
return directAddress.to_string();
|
||||
}
|
||||
boost::system::error_code error;
|
||||
auto hop = asio::ip::make_address(token, error);
|
||||
if (error || (hop.is_v6() && hop.to_v6().scope_id() != 0)) {
|
||||
return directAddress.to_string();
|
||||
}
|
||||
hops.push_back(std::move(hop));
|
||||
if (comma == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
remaining.remove_prefix(comma + 1);
|
||||
}
|
||||
|
||||
asio::ip::address effective = immediatePeer;
|
||||
for (auto hop = hops.rbegin(); hop != hops.rend(); ++hop) {
|
||||
if (!isTrusted(effective, trustedProxies)) {
|
||||
break;
|
||||
}
|
||||
effective = *hop;
|
||||
}
|
||||
return normalizeMappedAddress(effective).to_string();
|
||||
}
|
||||
|
||||
bool validShortSlug(std::string_view slug) noexcept
|
||||
{
|
||||
return slug.size() == 10 &&
|
||||
std::ranges::all_of(slug, [](unsigned char character) {
|
||||
return (character >= '0' && character <= '9') ||
|
||||
(character >= 'A' && character <= 'Z') ||
|
||||
(character >= 'a' && character <= 'z');
|
||||
});
|
||||
}
|
||||
|
||||
bool validRedirectLocation(std::string_view location) noexcept
|
||||
{
|
||||
if (location.empty() || location.size() > MAX_REDIRECT_LENGTH ||
|
||||
std::ranges::any_of(location, [](unsigned char character) {
|
||||
return character <= 0x20U || character >= 0x7fU;
|
||||
})) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto parsed = boost::urls::parse_uri(location);
|
||||
if (!parsed) {
|
||||
return false;
|
||||
}
|
||||
const auto& url = *parsed;
|
||||
if ((url.scheme_id() != boost::urls::scheme::http &&
|
||||
url.scheme_id() != boost::urls::scheme::https) ||
|
||||
!url.has_authority() || url.has_userinfo() ||
|
||||
url.encoded_host().empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (url.has_port()) {
|
||||
const auto port = url.port();
|
||||
unsigned int number = 0;
|
||||
const auto [end, code] =
|
||||
std::from_chars(port.data(), port.data() + port.size(), number);
|
||||
if (port.empty() || code != std::errc{} ||
|
||||
end != port.data() + port.size() || number == 0 ||
|
||||
number > 65535) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
ShortLinkRateLimiter::ShortLinkRateLimiter()
|
||||
: ShortLinkRateLimiter(Config{})
|
||||
{
|
||||
}
|
||||
|
||||
ShortLinkRateLimiter::ShortLinkRateLimiter(Config config) : config_(config)
|
||||
{
|
||||
if (!std::isfinite(config_.globalRate) || config_.globalRate < 0.0 ||
|
||||
!std::isfinite(config_.globalBurst) || config_.globalBurst < 1.0 ||
|
||||
!std::isfinite(config_.peerRate) || config_.peerRate < 0.0 ||
|
||||
!std::isfinite(config_.peerBurst) || config_.peerBurst < 1.0 ||
|
||||
config_.maxPeers == 0 ||
|
||||
config_.idleTimeout < Clock::duration::zero() ||
|
||||
config_.sweepInterval < Clock::duration::zero()) {
|
||||
throw std::invalid_argument(
|
||||
"invalid short-link rate limiter settings");
|
||||
}
|
||||
peers_.reserve(config_.maxPeers);
|
||||
}
|
||||
|
||||
bool ShortLinkRateLimiter::allow(std::string_view peer)
|
||||
{
|
||||
return allow(peer, Clock::now());
|
||||
}
|
||||
|
||||
bool ShortLinkRateLimiter::allow(std::string_view peer, TimePoint now)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
evictIdle(now, false);
|
||||
refill(global_, config_.globalRate, config_.globalBurst, now);
|
||||
if (global_.tokens < 1.0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::string peerKey{peer};
|
||||
auto found = peers_.find(peerKey);
|
||||
if (found == peers_.end()) {
|
||||
if (peers_.size() >= config_.maxPeers) {
|
||||
evictIdle(now, true);
|
||||
}
|
||||
if (peers_.size() >= config_.maxPeers) {
|
||||
return false;
|
||||
}
|
||||
found =
|
||||
peers_
|
||||
.emplace(peerKey, PeerBucket{.bucket = {}, .lastSeen = now})
|
||||
.first;
|
||||
}
|
||||
|
||||
found->second.lastSeen = now;
|
||||
refill(found->second.bucket, config_.peerRate, config_.peerBurst, now);
|
||||
if (found->second.bucket.tokens < 1.0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Commit both token deductions together. A peer-local rejection never
|
||||
// consumes global capacity and cannot starve unrelated clients.
|
||||
global_.tokens -= 1.0;
|
||||
found->second.bucket.tokens -= 1.0;
|
||||
return true;
|
||||
}
|
||||
|
||||
void ShortLinkRateLimiter::reset()
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
global_ = {};
|
||||
peers_.clear();
|
||||
nextSweep_ = {};
|
||||
sweepInitialized_ = false;
|
||||
}
|
||||
|
||||
std::size_t ShortLinkRateLimiter::trackedPeerCount() const
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
return peers_.size();
|
||||
}
|
||||
|
||||
void ShortLinkRateLimiter::refill(TokenBucket& bucket, double rate,
|
||||
double burst, TimePoint now) noexcept
|
||||
{
|
||||
if (!bucket.initialized) {
|
||||
bucket.tokens = burst;
|
||||
bucket.updated = now;
|
||||
bucket.initialized = true;
|
||||
return;
|
||||
}
|
||||
const auto elapsed =
|
||||
now > bucket.updated
|
||||
? std::chrono::duration<double>(now - bucket.updated).count()
|
||||
: 0.0;
|
||||
bucket.tokens = std::min(burst, bucket.tokens + elapsed * rate);
|
||||
bucket.updated = now;
|
||||
}
|
||||
|
||||
void ShortLinkRateLimiter::evictIdle(TimePoint now, bool force)
|
||||
{
|
||||
if (!force && sweepInitialized_ && now < nextSweep_) {
|
||||
return;
|
||||
}
|
||||
for (auto peer = peers_.begin(); peer != peers_.end();) {
|
||||
const bool expired =
|
||||
now >= peer->second.lastSeen &&
|
||||
now - peer->second.lastSeen >= config_.idleTimeout;
|
||||
if (expired) {
|
||||
peer = peers_.erase(peer);
|
||||
} else {
|
||||
++peer;
|
||||
}
|
||||
}
|
||||
nextSweep_ = now + config_.sweepInterval;
|
||||
sweepInitialized_ = true;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Web::Security
|
||||
+243
-387
@@ -2,10 +2,9 @@
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <boost/beast/websocket.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <cctype>
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
@@ -13,8 +12,14 @@
|
||||
#include <sstream>
|
||||
#include <string_view>
|
||||
|
||||
#if defined(__unix__) || defined(__APPLE__)
|
||||
#include <sys/socket.h>
|
||||
#endif
|
||||
|
||||
namespace Echoion::Web
|
||||
{
|
||||
namespace websocket = beast::websocket;
|
||||
|
||||
namespace
|
||||
{
|
||||
std::string_view contentType(const std::filesystem::path& path)
|
||||
@@ -91,105 +96,6 @@ namespace Echoion::Web
|
||||
return out;
|
||||
}
|
||||
|
||||
struct ProxyUrl {
|
||||
std::string url;
|
||||
std::string scheme;
|
||||
std::string host;
|
||||
};
|
||||
|
||||
std::optional<ProxyUrl> parseProxyUrl(std::string url)
|
||||
{
|
||||
const auto schemeEnd = url.find("://");
|
||||
if (schemeEnd == std::string::npos) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const std::string scheme = url.substr(0, schemeEnd);
|
||||
if (scheme != "https" && scheme != "http") {
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto authorityStart = schemeEnd + 3;
|
||||
const auto authorityEnd = url.find_first_of("/?#", authorityStart);
|
||||
std::string authority =
|
||||
url.substr(authorityStart, authorityEnd == std::string::npos
|
||||
? std::string::npos
|
||||
: authorityEnd - authorityStart);
|
||||
if (authority.empty() || authority.find('@') != std::string::npos) {
|
||||
return std::nullopt;
|
||||
}
|
||||
if (const auto colon = authority.rfind(':');
|
||||
colon != std::string::npos) {
|
||||
authority.resize(colon);
|
||||
}
|
||||
for (char& c : authority) {
|
||||
c = static_cast<char>(std::tolower(c));
|
||||
}
|
||||
const auto domain = [&](std::string_view base) {
|
||||
return authority == base ||
|
||||
(authority.size() > base.size() &&
|
||||
authority.ends_with(base) &&
|
||||
authority[authority.size() - base.size() - 1] == '.');
|
||||
};
|
||||
const bool allowed =
|
||||
domain("kodik.info") || domain("kodik.cc") ||
|
||||
domain("kodik.biz") || domain("kodik.online") ||
|
||||
domain("kodikplayer.com") || domain("alloha.tv") ||
|
||||
domain("alloha.video") || domain("alloha.online") ||
|
||||
domain("allarknow.online");
|
||||
if (!allowed) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return ProxyUrl{std::move(url), scheme, std::move(authority)};
|
||||
}
|
||||
|
||||
bool isPrivateAddress(const asio::ip::address& address)
|
||||
{
|
||||
if (address.is_loopback() || address.is_unspecified() ||
|
||||
address.is_multicast()) {
|
||||
return true;
|
||||
}
|
||||
if (address.is_v4()) {
|
||||
const auto bytes = address.to_v4().to_bytes();
|
||||
return bytes[0] == 10 || bytes[0] == 127 ||
|
||||
(bytes[0] == 169 && bytes[1] == 254) ||
|
||||
(bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31) ||
|
||||
(bytes[0] == 192 && bytes[1] == 168) || bytes[0] == 0;
|
||||
}
|
||||
const auto bytes = address.to_v6().to_bytes();
|
||||
return (bytes[0] & 0xfe) == 0xfc ||
|
||||
(bytes[0] == 0xfe && (bytes[1] & 0xc0) == 0x80);
|
||||
}
|
||||
|
||||
void absolutizeRootReferences(std::string& html,
|
||||
std::string_view origin)
|
||||
{
|
||||
// Kodik uses root-relative URLs both in tag attributes and inline
|
||||
// JavaScript. A <base> element cannot affect fetch("/...") and was
|
||||
// observed to be ignored for already-tokenized tags, so rewrite
|
||||
// every quoted single-slash reference before returning the
|
||||
// document.
|
||||
for (std::size_t i = 0; i + 2 < html.size(); ++i) {
|
||||
if ((html[i] != '\'' && html[i] != '"') || html[i + 1] != '/' ||
|
||||
html[i + 2] == '/') {
|
||||
continue;
|
||||
}
|
||||
html.insert(i + 1, origin);
|
||||
i += origin.size();
|
||||
}
|
||||
}
|
||||
|
||||
constexpr std::string_view kPlayerBridge =
|
||||
R"JS(<script data-echoion-bridge>
|
||||
(()=>{if(window.__echoionBridge)return;window.__echoionBridge=1;
|
||||
const send=(event,answer)=>parent.postMessage({event,answer},'*');
|
||||
const label=e=>(e.getAttribute('aria-label')||e.name||e.id||e.closest('label')?.textContent||'').toLowerCase();
|
||||
const kind=e=>{const s=label(e);if(/quality|качест/.test(s))return'qualities';if(/audio|voice|озвуч|перевод/.test(s))return'audiotracks';if(/subtitle|субтит/.test(s))return'subtitles';if(/episode|сер/.test(s))return'episodes';return''};
|
||||
const scan=()=>document.querySelectorAll('select').forEach(e=>{const k=kind(e);if(!k)return;send(k,[...e.options].map((o,i)=>({value:o.value||String(i),label:o.textContent||o.value})));if(!e.dataset.echoionBound){e.dataset.echoionBound='1';e.addEventListener('change',()=>send(k.replace(/ies$/,'y').replace(/s$/,''),e.value))}});
|
||||
const video=()=>document.querySelector('video');
|
||||
addEventListener('message',e=>{const m=e.data||{};if(!m.api)return;const v=video();if(m.api==='play')v?.play();else if(m.api==='pause')v?.pause();else if(m.api==='seek'&&v)v.currentTime=Number(m.set)||0;else if(m.api==='volume'&&v)v.volume=Math.max(0,Math.min(1,Number(m.set)));else if(m.api==='speed'&&v)v.playbackRate=Number(m.set)||1;else{document.querySelectorAll('select').forEach(s=>{const k=kind(s);const id=k==='qualities'?'quality':k==='audiotracks'?'audiotrack':k==='subtitles'?'subtitle':k==='episodes'?'episode':'';if(id===m.api){s.value=String(m.set);s.dispatchEvent(new Event('change',{bubbles:true}))}})}});
|
||||
const bind=()=>{const v=video();if(!v||v.dataset.echoionBound)return;v.dataset.echoionBound='1';v.addEventListener('play',()=>send('play'));v.addEventListener('pause',()=>send('pause'));v.addEventListener('ended',()=>send('ended'));v.addEventListener('timeupdate',()=>send('time',v.currentTime));send('duration',v.duration)};
|
||||
new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subtree:true,childList:true});setInterval(()=>{bind();scan()},1500);send('ready');})();
|
||||
</script>)JS";
|
||||
|
||||
// One direction of a raw TCP tunnel. On any error both sockets are
|
||||
// shut down so the opposite pump unblocks too.
|
||||
void pumpBytes(boost::asio::ip::tcp::socket& from,
|
||||
@@ -212,19 +118,77 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
|
||||
from.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignore);
|
||||
to.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignore);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
HttpServer::HttpServer() = default;
|
||||
HttpServer::~HttpServer() { stop(); }
|
||||
|
||||
HttpServer::TrustedProxyUpdate HttpServer::validateTrustedProxyCidrs(
|
||||
const std::vector<std::string>& cidrs)
|
||||
{
|
||||
try {
|
||||
auto parsed = Security::parseTrustedProxyCidrs(cidrs);
|
||||
if (!parsed) {
|
||||
return std::unexpected(std::move(parsed.error()));
|
||||
}
|
||||
return {};
|
||||
} catch (const std::exception& exception) {
|
||||
return std::unexpected(
|
||||
std::format("failed to validate trusted proxy CIDRs: {}",
|
||||
exception.what()));
|
||||
}
|
||||
}
|
||||
|
||||
HttpServer::TrustedProxyUpdate
|
||||
HttpServer::setTrustedProxyCidrs(const std::vector<std::string>& cidrs)
|
||||
{
|
||||
try {
|
||||
auto parsed = Security::parseTrustedProxyCidrs(cidrs);
|
||||
if (!parsed) {
|
||||
return std::unexpected(std::move(parsed.error()));
|
||||
}
|
||||
{
|
||||
std::unique_lock lock(trustedProxyMutex_);
|
||||
// A trust-policy change changes the peer identity used by the
|
||||
// limiter. Reset while new address calculations are blocked,
|
||||
// then publish the already-parsed policy with a no-throw swap.
|
||||
shortLinkRateLimiter_.reset();
|
||||
trustedProxyNetworks_.swap(*parsed);
|
||||
}
|
||||
return {};
|
||||
} catch (const std::exception& exception) {
|
||||
return std::unexpected(std::format(
|
||||
"failed to update trusted proxy CIDRs: {}", exception.what()));
|
||||
}
|
||||
}
|
||||
|
||||
bool HttpServer::start(const Config& config)
|
||||
{
|
||||
if (running_.exchange(true)) {
|
||||
if (running_.load()) {
|
||||
return false;
|
||||
}
|
||||
config_ = config;
|
||||
|
||||
try {
|
||||
auto trustedProxies =
|
||||
Security::parseTrustedProxyCidrs(config.trustedProxyCidrs);
|
||||
if (!trustedProxies) {
|
||||
Void::Log::error(
|
||||
"HttpServer", "{}",
|
||||
std::format("Failed to start web interface: {}",
|
||||
trustedProxies.error()));
|
||||
return false;
|
||||
}
|
||||
bool expected = false;
|
||||
if (!running_.compare_exchange_strong(expected, true)) {
|
||||
return false;
|
||||
}
|
||||
config_ = config;
|
||||
{
|
||||
std::unique_lock lock(trustedProxyMutex_);
|
||||
trustedProxyNetworks_ = std::move(*trustedProxies);
|
||||
}
|
||||
shortLinkRateLimiter_.reset();
|
||||
ioContext_.restart();
|
||||
|
||||
asio::ip::tcp::endpoint endpoint(
|
||||
@@ -237,13 +201,7 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
|
||||
|
||||
pool_ = std::make_unique<Void::Concurrency::ThreadPool>(POOL_SIZE);
|
||||
|
||||
watch_.setSender([this](uint64_t connId, const std::string& json) {
|
||||
sendToWatcher(connId, json);
|
||||
});
|
||||
|
||||
serverThread_ = std::thread(&HttpServer::acceptLoop, this);
|
||||
syncThread_ =
|
||||
std::jthread([this](std::stop_token st) { syncLoop(st); });
|
||||
|
||||
// A wrong webRoot only surfaces as bare 404s in the browser —
|
||||
// call it out at startup instead.
|
||||
@@ -285,23 +243,6 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
|
||||
}
|
||||
ioContext_.stop();
|
||||
|
||||
// Stop the heartbeat first so it can't write to sockets we close.
|
||||
syncThread_ = std::jthread{};
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(watchersMutex_);
|
||||
for (auto& [id, ws] : watchers_) {
|
||||
// Leave rooms properly so they pause/persist instead of
|
||||
// keeping ghost participants across a stop()/start().
|
||||
watch_.onDisconnect(id);
|
||||
if (ws->is_open()) {
|
||||
beast::error_code ec;
|
||||
ws->close(websocket::close_code::normal, ec);
|
||||
}
|
||||
}
|
||||
watchers_.clear();
|
||||
}
|
||||
|
||||
// Unblock every /rpc bridge pump so the pool workers can return.
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(bridgesMutex_);
|
||||
@@ -393,41 +334,79 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
|
||||
{
|
||||
beast::error_code ec;
|
||||
beast::flat_buffer buffer;
|
||||
// Serve requests on this connection until the peer closes, an error
|
||||
// occurs, or the request asks not to keep the connection alive.
|
||||
while (running_.load()) {
|
||||
http::request<http::string_body> req;
|
||||
http::read(*socket, buffer, req, ec);
|
||||
if (ec) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (websocket::is_upgrade(req)) {
|
||||
if (req.target() == "/rpc") {
|
||||
bridgeRpc(socket, req, buffer);
|
||||
return;
|
||||
}
|
||||
if (req.target() != "/ws") {
|
||||
return; // /ws (watch) and /rpc (bridge) only
|
||||
}
|
||||
auto ws =
|
||||
std::make_shared<websocket::stream<asio::ip::tcp::socket>>(
|
||||
std::move(*socket));
|
||||
ws->accept(req, ec);
|
||||
if (ec) {
|
||||
Void::Log::debug("HttpServer", "{}",
|
||||
std::format("Watch handshake failed: {}",
|
||||
ec.message()));
|
||||
return;
|
||||
}
|
||||
handleWatch(ws);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!serveHttp(*socket, req)) {
|
||||
// Bound slow clients and parser memory. Every accepted connection
|
||||
// serves exactly one request; browsers simply open another connection.
|
||||
#if defined(__unix__) || defined(__APPLE__)
|
||||
timeval timeout{.tv_sec = 5, .tv_usec = 0};
|
||||
(void)::setsockopt(socket->native_handle(), SOL_SOCKET, SO_RCVTIMEO,
|
||||
&timeout, sizeof(timeout));
|
||||
#endif
|
||||
http::request_parser<http::string_body> parser;
|
||||
parser.header_limit(32 * 1024);
|
||||
parser.body_limit(0);
|
||||
http::read(*socket, buffer, parser, ec);
|
||||
if (ec) {
|
||||
return;
|
||||
}
|
||||
auto req = parser.release();
|
||||
for (const auto& field : req) {
|
||||
if (field.name_string().size() + field.value().size() > 8 * 1024) {
|
||||
http::response<http::string_body> response{
|
||||
http::status::request_header_fields_too_large,
|
||||
req.version()};
|
||||
response.set(http::field::server, "Echoion");
|
||||
response.body() = "Request Header Fields Too Large";
|
||||
response.prepare_payload();
|
||||
response.keep_alive(false);
|
||||
http::write(*socket, response, ec);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (websocket::is_upgrade(req)) {
|
||||
if (req.target() == "/rpc") {
|
||||
bridgeRpc(socket, req, buffer);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
(void)serveHttp(*socket, req, clientAddress(*socket, req));
|
||||
}
|
||||
|
||||
std::string HttpServer::clientAddress(
|
||||
const asio::ip::tcp::socket& socket,
|
||||
const http::request<http::string_body>& req) const
|
||||
{
|
||||
boost::system::error_code error;
|
||||
const auto endpoint = socket.remote_endpoint(error);
|
||||
if (error) {
|
||||
return {};
|
||||
}
|
||||
|
||||
std::optional<std::string_view> forwardedFor;
|
||||
for (const auto& field : req) {
|
||||
if (!beast::iequals(field.name_string(), "X-Forwarded-For")) {
|
||||
continue;
|
||||
}
|
||||
// Multiple field-lines have ambiguous intermediary semantics.
|
||||
// Ignore all of them instead of choosing an attacker-controlled
|
||||
// value.
|
||||
if (forwardedFor) {
|
||||
forwardedFor.reset();
|
||||
break;
|
||||
}
|
||||
forwardedFor =
|
||||
std::string_view{field.value().data(), field.value().size()};
|
||||
}
|
||||
|
||||
std::shared_lock lock(trustedProxyMutex_);
|
||||
return Security::effectiveClientAddress(
|
||||
endpoint.address(), forwardedFor, trustedProxyNetworks_);
|
||||
}
|
||||
|
||||
bool HttpServer::allowShortLinkRequest(std::string_view peer)
|
||||
{
|
||||
return shortLinkRateLimiter_.allow(peer);
|
||||
}
|
||||
|
||||
void HttpServer::bridgeRpc(std::shared_ptr<asio::ip::tcp::socket> browser,
|
||||
@@ -451,25 +430,10 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
|
||||
|
||||
// Forward the browser's effective IP so the RPC server can offer
|
||||
// address-based autologin. Never trust a client-supplied value; a
|
||||
// reverse proxy's X-Forwarded-For (first hop) wins over the socket
|
||||
// address because the proxy connects from its own host.
|
||||
// X-Forwarded-For is accepted only from configured proxies and walked
|
||||
// from right to left, stopping at the nearest untrusted hop.
|
||||
req.erase("X-Echoion-Client-Ip");
|
||||
std::string clientIp;
|
||||
if (auto xff = req.find("X-Forwarded-For"); xff != req.end()) {
|
||||
clientIp = std::string(xff->value());
|
||||
if (auto comma = clientIp.find(','); comma != std::string::npos) {
|
||||
clientIp = clientIp.substr(0, comma);
|
||||
}
|
||||
while (!clientIp.empty() && clientIp.front() == ' ') {
|
||||
clientIp.erase(clientIp.begin());
|
||||
}
|
||||
}
|
||||
if (clientIp.empty()) {
|
||||
boost::system::error_code epEc;
|
||||
if (auto ep = browser->remote_endpoint(epEc); !epEc) {
|
||||
clientIp = ep.address().to_string();
|
||||
}
|
||||
}
|
||||
const std::string clientIp = clientAddress(*browser, req);
|
||||
if (!clientIp.empty()) {
|
||||
req.set("X-Echoion-Client-Ip", clientIp);
|
||||
}
|
||||
@@ -508,44 +472,18 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
|
||||
std::format("RPC bridge {} closed", connId));
|
||||
}
|
||||
|
||||
void HttpServer::handleWatch(
|
||||
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws)
|
||||
{
|
||||
const uint64_t connId = nextConnId_++;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(watchersMutex_);
|
||||
watchers_[connId] = ws;
|
||||
}
|
||||
watch_.onConnect(connId);
|
||||
|
||||
beast::flat_buffer buffer;
|
||||
while (running_.load() && ws->is_open()) {
|
||||
beast::error_code ec;
|
||||
ws->read(buffer, ec);
|
||||
if (ec == websocket::error::closed || ec) {
|
||||
break;
|
||||
}
|
||||
std::string message = beast::buffers_to_string(buffer.data());
|
||||
buffer.consume(buffer.size());
|
||||
watch_.onMessage(connId, message);
|
||||
}
|
||||
|
||||
watch_.onDisconnect(connId);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(watchersMutex_);
|
||||
watchers_.erase(connId);
|
||||
}
|
||||
}
|
||||
|
||||
bool HttpServer::serveHttp(asio::ip::tcp::socket& socket,
|
||||
const http::request<http::string_body>& req)
|
||||
const http::request<http::string_body>& req,
|
||||
std::string_view requestAddress)
|
||||
{
|
||||
beast::error_code ec;
|
||||
const bool isHead = req.method() == http::verb::head;
|
||||
|
||||
auto respond = [&](http::status status, std::string_view type,
|
||||
std::string body, std::string_view cacheControl = {},
|
||||
std::string_view lastModified = {}) {
|
||||
std::string_view lastModified = {},
|
||||
std::string_view etag = {},
|
||||
std::string_view location = {}) {
|
||||
http::response<http::string_body> res{status, req.version()};
|
||||
res.set(http::field::server, "Echoion");
|
||||
res.set(http::field::content_type, type);
|
||||
@@ -555,7 +493,13 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
|
||||
if (!lastModified.empty()) {
|
||||
res.set(http::field::last_modified, lastModified);
|
||||
}
|
||||
res.keep_alive(req.keep_alive());
|
||||
if (!etag.empty()) {
|
||||
res.set(http::field::etag, etag);
|
||||
}
|
||||
if (!location.empty()) {
|
||||
res.set(http::field::location, location);
|
||||
}
|
||||
res.keep_alive(false);
|
||||
// HEAD advertises the real Content-Length but carries no body.
|
||||
res.content_length(
|
||||
status == http::status::not_modified ? 0 : body.size());
|
||||
@@ -589,10 +533,101 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
|
||||
{{"rpcUrl", Value{rpcUrl}},
|
||||
{"rpcPort",
|
||||
Value{static_cast<long long>(config_.rpcPort)}},
|
||||
{"watchUrl", Value{config_.watchUrl}},
|
||||
{"nowPlayingVideo", Value{config_.nowPlayingVideo}}})));
|
||||
return !ec && req.keep_alive();
|
||||
}
|
||||
|
||||
if (target == "/api/public/dashboard") {
|
||||
DashboardProvider provider;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(dashboardProviderMutex_);
|
||||
provider = dashboardProvider_;
|
||||
}
|
||||
if (!provider) {
|
||||
respond(http::status::service_unavailable, "application/json",
|
||||
R"({"error":"Dashboard snapshot unavailable"})",
|
||||
"no-cache");
|
||||
return !ec && req.keep_alive();
|
||||
}
|
||||
auto snapshot = provider();
|
||||
if (auto current = req.find(http::field::if_none_match);
|
||||
current != req.end() && current->value() == snapshot.etag) {
|
||||
respond(http::status::not_modified, "application/json", "",
|
||||
"no-cache", {}, snapshot.etag);
|
||||
return !ec && req.keep_alive();
|
||||
}
|
||||
respond(http::status::ok, "application/json",
|
||||
std::move(snapshot.body), "no-cache", {}, snapshot.etag);
|
||||
return !ec && req.keep_alive();
|
||||
}
|
||||
|
||||
if ((target == "/watch" || target == "/watch/") &&
|
||||
!config_.watchUrl.empty()) {
|
||||
respond(http::status::temporary_redirect, "text/plain", "",
|
||||
"no-store", {}, {}, config_.watchUrl);
|
||||
return !ec && req.keep_alive();
|
||||
}
|
||||
|
||||
constexpr std::string_view kShortPrefix = "/s/";
|
||||
if (target.starts_with(kShortPrefix)) {
|
||||
const std::string key = target.substr(kShortPrefix.size());
|
||||
if (!Security::validShortSlug(key)) {
|
||||
respond(http::status::not_found, "text/plain", "Not Found",
|
||||
"no-store");
|
||||
return false;
|
||||
}
|
||||
if (!allowShortLinkRequest(requestAddress)) {
|
||||
respond(http::status::too_many_requests, "text/plain",
|
||||
"Too Many Requests", "no-store");
|
||||
return false;
|
||||
}
|
||||
ShortLinkResolver resolver;
|
||||
{
|
||||
std::lock_guard lock(shortLinkResolverMutex_);
|
||||
resolver = shortLinkResolver_;
|
||||
}
|
||||
const auto resolution =
|
||||
resolver ? resolver(key)
|
||||
: ShortLinkResolution{.status =
|
||||
ShortLinkStatus::unavailable,
|
||||
.location = {}};
|
||||
http::status status = http::status::not_found;
|
||||
switch (resolution.status) {
|
||||
case ShortLinkStatus::found:
|
||||
status = http::status::found;
|
||||
break;
|
||||
case ShortLinkStatus::gone:
|
||||
status = http::status::gone;
|
||||
break;
|
||||
case ShortLinkStatus::rateLimited:
|
||||
status = http::status::too_many_requests;
|
||||
break;
|
||||
case ShortLinkStatus::unavailable:
|
||||
status = http::status::service_unavailable;
|
||||
break;
|
||||
case ShortLinkStatus::notFound:
|
||||
break;
|
||||
}
|
||||
http::response<http::string_body> response{status, req.version()};
|
||||
response.set(http::field::server, "Echoion");
|
||||
response.set(http::field::cache_control, "no-store");
|
||||
response.set("Referrer-Policy", "no-referrer");
|
||||
response.set("X-Robots-Tag", "noindex, nofollow");
|
||||
response.set("X-Content-Type-Options", "nosniff");
|
||||
response.set("Content-Security-Policy", "default-src 'none'");
|
||||
if (status == http::status::found &&
|
||||
Security::validRedirectLocation(resolution.location)) {
|
||||
response.set(http::field::location, resolution.location);
|
||||
} else if (status == http::status::found) {
|
||||
response.result(http::status::service_unavailable);
|
||||
}
|
||||
response.content_length(0);
|
||||
response.keep_alive(false);
|
||||
http::write(socket, response, ec);
|
||||
return false;
|
||||
}
|
||||
|
||||
// User avatar images, resolved through Core's provider (TeamSpeak
|
||||
// avatar cache). Best-effort: 404 lets the UI fall back to its
|
||||
// initial-letter avatars; short private caching keeps reloads cheap
|
||||
@@ -630,28 +665,6 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
|
||||
return !ec && req.keep_alive();
|
||||
}
|
||||
|
||||
// Custom emoji images, resolved through Core's provider (emoji DB).
|
||||
constexpr std::string_view kEmojiPrefix = "/emoji/";
|
||||
if (target.starts_with(kEmojiPrefix)) {
|
||||
const std::string name =
|
||||
urlDecode(target.substr(kEmojiPrefix.size()));
|
||||
EmojiProvider provider;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(avatarProviderMutex_);
|
||||
provider = emojiProvider_;
|
||||
}
|
||||
if (!name.empty() && provider) {
|
||||
if (auto image = provider(name)) {
|
||||
respond(http::status::ok, image->contentType,
|
||||
std::move(image->bytes), "public, max-age=86400");
|
||||
return !ec && req.keep_alive();
|
||||
}
|
||||
}
|
||||
respond(http::status::not_found, "text/plain", "Not Found",
|
||||
"private, max-age=60");
|
||||
return !ec && req.keep_alive();
|
||||
}
|
||||
|
||||
if (target.empty() || target == "/") {
|
||||
target = "/index.html";
|
||||
}
|
||||
@@ -699,161 +712,4 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
|
||||
return !ec && req.keep_alive();
|
||||
}
|
||||
|
||||
bool
|
||||
HttpServer::serveWatchProxy(asio::ip::tcp::socket& socket,
|
||||
const http::request<http::string_body>& req)
|
||||
{
|
||||
beast::error_code ec;
|
||||
auto fail = [&](http::status status, std::string body) {
|
||||
http::response<http::string_body> res{status, req.version()};
|
||||
res.set(http::field::server, "Echoion");
|
||||
res.set(http::field::content_type, "text/plain; charset=utf-8");
|
||||
res.set(http::field::cache_control, "no-store");
|
||||
res.keep_alive(req.keep_alive());
|
||||
res.body() = std::move(body);
|
||||
res.prepare_payload();
|
||||
http::write(socket, res, ec);
|
||||
return !ec && req.keep_alive();
|
||||
};
|
||||
|
||||
if (req.method() != http::verb::get &&
|
||||
req.method() != http::verb::head) {
|
||||
return fail(http::status::method_not_allowed, "Method Not Allowed");
|
||||
}
|
||||
const std::string target(req.target());
|
||||
const auto marker = target.find("url=");
|
||||
if (marker == std::string::npos) {
|
||||
return fail(http::status::bad_request, "Missing upstream URL");
|
||||
}
|
||||
std::string encoded = target.substr(marker + 4);
|
||||
if (const auto amp = encoded.find('&'); amp != std::string::npos) {
|
||||
encoded.resize(amp);
|
||||
}
|
||||
auto upstream = parseProxyUrl(urlDecode(encoded));
|
||||
if (!upstream) {
|
||||
return fail(http::status::forbidden, "Provider is not allowlisted");
|
||||
}
|
||||
|
||||
// Resolve and inspect every address before connecting. Redirects are
|
||||
// not followed; the browser must request the validated destination
|
||||
// anew.
|
||||
asio::io_context resolverContext;
|
||||
asio::ip::tcp::resolver resolver(resolverContext);
|
||||
boost::system::error_code resolveEc;
|
||||
const auto endpoints = resolver.resolve(
|
||||
upstream->host, upstream->scheme == "https" ? "443" : "80",
|
||||
resolveEc);
|
||||
if (resolveEc || endpoints.empty()) {
|
||||
return fail(http::status::bad_gateway, "Provider lookup failed");
|
||||
}
|
||||
for (const auto& endpoint : endpoints) {
|
||||
if (isPrivateAddress(endpoint.endpoint().address())) {
|
||||
return fail(http::status::forbidden, "Private upstream denied");
|
||||
}
|
||||
}
|
||||
|
||||
Void::Net::HttpClient client;
|
||||
client.set_verify_tls(true);
|
||||
client.set_max_redirects(0);
|
||||
client.set_max_body_size(32ull * 1024 * 1024);
|
||||
Void::Net::Request upstreamReq;
|
||||
upstreamReq.method = req.method() == http::verb::head
|
||||
? Void::Net::Method::Head
|
||||
: Void::Net::Method::Get;
|
||||
upstreamReq.url = upstream->url;
|
||||
upstreamReq.timeout = std::chrono::seconds{15};
|
||||
if (const auto range = req.find(http::field::range);
|
||||
range != req.end()) {
|
||||
upstreamReq.headers.push_back(
|
||||
{"Range", std::string(range->value())});
|
||||
}
|
||||
upstreamReq.headers.push_back({"Access-Control-Allow-Origin", "*"});
|
||||
auto fetched = client.send(upstreamReq);
|
||||
if (!fetched) {
|
||||
return fail(http::status::bad_gateway, "Provider request failed");
|
||||
}
|
||||
if (fetched->status >= 300 && fetched->status < 400) {
|
||||
return fail(http::status::bad_gateway,
|
||||
"Provider redirect requires allowlist validation");
|
||||
}
|
||||
|
||||
std::string body = std::move(fetched->body);
|
||||
std::string contentType = fetched->header("Content-Type")
|
||||
.transform([](std::string_view value) {
|
||||
return std::string(value);
|
||||
})
|
||||
.value_or("application/octet-stream");
|
||||
if (contentType.starts_with("text/html")) {
|
||||
const std::string origin =
|
||||
std::format("{}://{}", upstream->scheme, upstream->host);
|
||||
absolutizeRootReferences(body, origin);
|
||||
const std::string base =
|
||||
std::format("<base href=\"{}\">", upstream->url);
|
||||
// The base must precede provider CSS/JS tags. Appending it at
|
||||
// </head> is too late: the HTML parser has already resolved
|
||||
// /assets/* against Echoion, producing 404s and leaving the player
|
||||
// unstyled/unbooted.
|
||||
if (const auto openHead = body.find("<head");
|
||||
openHead != std::string::npos) {
|
||||
const auto end = body.find('>', openHead);
|
||||
body.insert(end == std::string::npos ? openHead : end + 1,
|
||||
base);
|
||||
} else {
|
||||
body.insert(0, base);
|
||||
}
|
||||
const auto closeHead = body.find("</head>");
|
||||
body.insert(closeHead == std::string::npos ? 0 : closeHead,
|
||||
std::string(kPlayerBridge));
|
||||
}
|
||||
|
||||
http::response<http::string_body> res{
|
||||
static_cast<http::status>(fetched->status), req.version()};
|
||||
res.set(http::field::server, "Echoion");
|
||||
res.set(http::field::content_type, contentType);
|
||||
res.set(http::field::cache_control, "no-store");
|
||||
res.set("X-Content-Type-Options", "nosniff");
|
||||
for (const auto name : {"Accept-Ranges", "Content-Range"}) {
|
||||
if (auto value = fetched->header(name)) {
|
||||
res.set(name, *value);
|
||||
}
|
||||
}
|
||||
res.keep_alive(req.keep_alive());
|
||||
const auto bodySize = body.size();
|
||||
if (req.method() != http::verb::head) {
|
||||
res.body() = std::move(body);
|
||||
}
|
||||
res.content_length(bodySize);
|
||||
http::write(socket, res, ec);
|
||||
return !ec && req.keep_alive();
|
||||
}
|
||||
|
||||
void HttpServer::sendToWatcher(uint64_t connId, const std::string& json)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(watchersMutex_);
|
||||
auto it = watchers_.find(connId);
|
||||
if (it == watchers_.end() || !it->second->is_open()) {
|
||||
return;
|
||||
}
|
||||
beast::error_code ec;
|
||||
it->second->text(true);
|
||||
it->second->write(asio::buffer(json), ec);
|
||||
}
|
||||
|
||||
void HttpServer::syncLoop(std::stop_token stopToken)
|
||||
{
|
||||
using namespace std::chrono_literals;
|
||||
while (!stopToken.stop_requested() && running_.load()) {
|
||||
// Sleep in short slices so stop() is prompt.
|
||||
for (int i = 0;
|
||||
i < 30 && !stopToken.stop_requested() && running_.load();
|
||||
++i) {
|
||||
std::this_thread::sleep_for(100ms);
|
||||
}
|
||||
if (stopToken.stop_requested() || !running_.load()) {
|
||||
break;
|
||||
}
|
||||
watch_.broadcastSync();
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Echoion::Web
|
||||
@@ -1,849 +0,0 @@
|
||||
#include "echoion/web/WatchSession.hpp"
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
|
||||
#include <format>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Web
|
||||
{
|
||||
namespace
|
||||
{
|
||||
using Void::Json::Value;
|
||||
|
||||
long long nowMillis()
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now().time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
// Extract the YouTube video id from common URL shapes so clients that
|
||||
// use the iframe player get a bare id. Falls back to the whole string.
|
||||
std::string videoIdFromUrl(const std::string& url)
|
||||
{
|
||||
auto pick = [&](std::string_view marker) -> std::string {
|
||||
auto pos = url.find(marker);
|
||||
if (pos == std::string::npos) {
|
||||
return {};
|
||||
}
|
||||
pos += marker.size();
|
||||
auto end = url.find_first_of("&?#", pos);
|
||||
return url.substr(pos, end == std::string::npos
|
||||
? std::string::npos
|
||||
: end - pos);
|
||||
};
|
||||
if (auto id = pick("v="); !id.empty()) {
|
||||
return id;
|
||||
}
|
||||
if (auto id = pick("youtu.be/"); !id.empty()) {
|
||||
return id;
|
||||
}
|
||||
if (auto id = pick("/embed/"); !id.empty()) {
|
||||
return id;
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
// Twitch channel from a URL or a bare channel name.
|
||||
std::string twitchChannelFrom(const std::string& input)
|
||||
{
|
||||
auto pos = input.find("twitch.tv/");
|
||||
std::string channel =
|
||||
pos == std::string::npos
|
||||
? input
|
||||
: input.substr(pos + std::string_view("twitch.tv/").size());
|
||||
if (auto end = channel.find_first_of("/&?#");
|
||||
end != std::string::npos) {
|
||||
channel = channel.substr(0, end);
|
||||
}
|
||||
return channel;
|
||||
}
|
||||
|
||||
// Canonicalize a client-supplied source to one of the known kinds,
|
||||
// defaulting anything unrecognized to "youtube".
|
||||
std::string canonicalSource(const std::string& s)
|
||||
{
|
||||
if (s == "twitch" || s == "direct" || s == "iframe") {
|
||||
return s;
|
||||
}
|
||||
return "youtube";
|
||||
}
|
||||
|
||||
// Live sources have no position authority and refuse seeks: Twitch
|
||||
// streams, and generic embeds (Kodik & co.) unless the host's client
|
||||
// reported the embed as controllable (watch.embed.caps).
|
||||
bool isLiveSource(const std::string& s, bool controllable)
|
||||
{
|
||||
return s == "twitch" || (s == "iframe" && !controllable);
|
||||
}
|
||||
|
||||
Value embedControlsValue(
|
||||
const std::map<std::string, std::string>& controls)
|
||||
{
|
||||
Value::Object_t object;
|
||||
for (const auto& [id, value] : controls) {
|
||||
object.emplace_back(id, Value{value});
|
||||
}
|
||||
return Value{std::move(object)};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
long long WatchSessionManager::livePosition(const Room& room) const
|
||||
{
|
||||
if (room.paused) {
|
||||
return room.positionMs;
|
||||
}
|
||||
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now() - room.anchor)
|
||||
.count();
|
||||
return room.positionMs + elapsed;
|
||||
}
|
||||
|
||||
void WatchSessionManager::send(uint64_t connId, const std::string& json) const
|
||||
{
|
||||
if (sender_) {
|
||||
sender_(connId, json);
|
||||
}
|
||||
}
|
||||
|
||||
void WatchSessionManager::broadcast(const Room& room,
|
||||
const std::string& json) const
|
||||
{
|
||||
for (const auto& [id, participant] : room.participants) {
|
||||
send(id, json);
|
||||
}
|
||||
}
|
||||
|
||||
void WatchSessionManager::sendDenied(uint64_t connId,
|
||||
const std::string& reason) const
|
||||
{
|
||||
send(connId, Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.denied"}},
|
||||
{"reason", Value{reason}}})));
|
||||
}
|
||||
|
||||
void WatchSessionManager::sendParticipants(const Room& room) const
|
||||
{
|
||||
Value::Array_t list;
|
||||
list.reserve(room.participants.size());
|
||||
for (const auto& [id, p] : room.participants) {
|
||||
// Drift vs the authority at the time of the client's last report;
|
||||
// -1 while nothing has been reported yet.
|
||||
long long offsetMs = -1;
|
||||
if (p.reportedMs >= 0 && p.authorityMs >= 0) {
|
||||
offsetMs = p.reportedMs - p.authorityMs;
|
||||
}
|
||||
list.emplace_back(Void::Json::object(
|
||||
{{"id", Value{static_cast<long long>(id)}},
|
||||
{"name", Value{p.name}},
|
||||
{"uid", Value{p.uid}},
|
||||
{"host", Value{id == room.host}},
|
||||
{"offsetMs", Value{offsetMs}},
|
||||
{"buffering", Value{p.buffering}}}));
|
||||
}
|
||||
const std::string msg = Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.participants"}},
|
||||
{"count", Value{static_cast<long long>(room.participants.size())}},
|
||||
{"host", Value{static_cast<long long>(room.host)}},
|
||||
{"participants", Value{std::move(list)}}}));
|
||||
broadcast(room, msg);
|
||||
}
|
||||
|
||||
void WatchSessionManager::sendQueue(const Room& room, uint64_t onlyTo) const
|
||||
{
|
||||
Value::Array_t items;
|
||||
items.reserve(room.queue.size());
|
||||
for (const auto& e : room.queue) {
|
||||
items.emplace_back(Void::Json::object(
|
||||
{{"source", Value{e.source}},
|
||||
{"url", Value{e.url}},
|
||||
{"videoId", Value{e.videoId}},
|
||||
{"title", Value{e.title}},
|
||||
{"thumbnailUrl", Value{e.thumbnailUrl}},
|
||||
{"addedBy", Value{e.addedBy}}}));
|
||||
}
|
||||
const std::string msg = Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.queue"}},
|
||||
{"items", Value{std::move(items)}}}));
|
||||
if (onlyTo != 0) {
|
||||
send(onlyTo, msg);
|
||||
} else {
|
||||
broadcast(room, msg);
|
||||
}
|
||||
}
|
||||
|
||||
std::string WatchSessionManager::thumbnailFor(const std::string& source,
|
||||
const std::string& videoId)
|
||||
{
|
||||
if (videoId.empty()) {
|
||||
return {};
|
||||
}
|
||||
// Direct/iframe sources carry no deterministic thumbnail.
|
||||
if (source == "direct" || source == "iframe") {
|
||||
return {};
|
||||
}
|
||||
if (source == "twitch") {
|
||||
// Twitch's live-preview CDN (undocumented but stable); shows a
|
||||
// placeholder when the channel is offline.
|
||||
return std::format(
|
||||
"https://static-cdn.jtvnw.net/previews-ttv/live_user_{}"
|
||||
"-320x180.jpg",
|
||||
videoId);
|
||||
}
|
||||
return std::format("https://i.ytimg.com/vi/{}/mqdefault.jpg", videoId);
|
||||
}
|
||||
|
||||
std::size_t WatchSessionManager::skipThreshold(const Room& room)
|
||||
{
|
||||
// Majority of current participants (ceil(n/2)); at least one.
|
||||
const std::size_t n = room.participants.size();
|
||||
return n == 0 ? 1 : (n / 2) + 1;
|
||||
}
|
||||
|
||||
void WatchSessionManager::sendSkipState(const Room& room) const
|
||||
{
|
||||
const std::string msg = Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.skip.updated"}},
|
||||
{"votes",
|
||||
Value{static_cast<long long>(room.skipVotes.size())}},
|
||||
{"needed",
|
||||
Value{static_cast<long long>(skipThreshold(room))}}}));
|
||||
broadcast(room, msg);
|
||||
}
|
||||
|
||||
void WatchSessionManager::sendRoomsList(uint64_t connId) const
|
||||
{
|
||||
Value::Array_t list;
|
||||
for (const auto& [name, room] : rooms_) {
|
||||
list.emplace_back(Void::Json::object(
|
||||
{{"name", Value{name}},
|
||||
{"participants",
|
||||
Value{static_cast<long long>(room.participants.size())}},
|
||||
{"source", Value{room.source}},
|
||||
{"videoId", Value{room.videoId}},
|
||||
{"nowTitle", Value{room.url}},
|
||||
{"hasHost", Value{room.host != 0}}}));
|
||||
}
|
||||
send(connId, Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.rooms"}},
|
||||
{"rooms", Value{std::move(list)}}})));
|
||||
}
|
||||
|
||||
uint64_t WatchSessionManager::pickHost(const Room& room)
|
||||
{
|
||||
for (const auto& [id, p] : room.participants) {
|
||||
if (p.authenticated) {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void WatchSessionManager::loadIntoRoom(Room& room, const std::string& source,
|
||||
const std::string& url,
|
||||
const std::string& channel,
|
||||
uint64_t byConnId)
|
||||
{
|
||||
room.url = url;
|
||||
const std::string src = canonicalSource(source);
|
||||
if (src == "twitch") {
|
||||
room.source = "twitch";
|
||||
room.videoId = !channel.empty() ? twitchChannelFrom(channel)
|
||||
: twitchChannelFrom(url);
|
||||
room.paused = false; // live — always "playing"
|
||||
} else if (src == "direct" || src == "iframe") {
|
||||
// The URL carries the whole media/embed; there is no video id.
|
||||
// `direct` (HTML5 <video>) is seekable; `iframe` (generic embed)
|
||||
// is live-like (no position authority).
|
||||
room.source = src;
|
||||
room.videoId.clear();
|
||||
room.paused = false;
|
||||
} else {
|
||||
room.source = "youtube";
|
||||
room.videoId = videoIdFromUrl(url);
|
||||
// Auto-play on load: the room starts playing immediately rather
|
||||
// than waiting for someone to press play (the client handles the
|
||||
// browser autoplay policy by starting muted when needed).
|
||||
room.paused = false;
|
||||
}
|
||||
room.positionMs = 0;
|
||||
room.anchor = std::chrono::steady_clock::now();
|
||||
// A new video resets any in-flight skip vote, and any embed capability
|
||||
// until the host's client re-handshakes with the new embed.
|
||||
room.skipVotes.clear();
|
||||
room.controllable = false;
|
||||
room.embedControls.clear();
|
||||
const std::string msg = Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.loaded"}},
|
||||
{"source", Value{room.source}},
|
||||
{"url", Value{room.url}},
|
||||
{"videoId", Value{room.videoId}},
|
||||
{"controllable", Value{room.controllable}},
|
||||
{"by", Value{static_cast<long long>(byConnId)}}}));
|
||||
broadcast(room, msg);
|
||||
sendSkipState(room);
|
||||
}
|
||||
|
||||
void WatchSessionManager::sendSnapshot(uint64_t connId, const Room& room) const
|
||||
{
|
||||
const std::string msg = Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.sync"}},
|
||||
{"source", Value{room.source}},
|
||||
{"url", Value{room.url}},
|
||||
{"videoId", Value{room.videoId}},
|
||||
{"controllable", Value{room.controllable}},
|
||||
{"paused", Value{room.paused}},
|
||||
{"rate", Value{room.rate}},
|
||||
{"embedControls", embedControlsValue(room.embedControls)},
|
||||
{"positionMs", Value{livePosition(room)}},
|
||||
{"serverTimeMs", Value{nowMillis()}},
|
||||
{"host", Value{static_cast<long long>(room.host)}}}));
|
||||
send(connId, msg);
|
||||
}
|
||||
|
||||
void WatchSessionManager::onConnect(uint64_t connId)
|
||||
{
|
||||
Void::Log::debug("WatchSession", "{}",
|
||||
std::format("watch connection {} opened", connId));
|
||||
}
|
||||
|
||||
void WatchSessionManager::leaveCurrentRoom(uint64_t connId)
|
||||
{
|
||||
auto it = connRoom_.find(connId);
|
||||
if (it == connRoom_.end()) {
|
||||
return;
|
||||
}
|
||||
auto roomIt = rooms_.find(it->second);
|
||||
connRoom_.erase(it);
|
||||
if (roomIt == rooms_.end()) {
|
||||
return;
|
||||
}
|
||||
Room& room = roomIt->second;
|
||||
room.participants.erase(connId);
|
||||
room.skipVotes.erase(connId);
|
||||
if (room.participants.empty()) {
|
||||
// A room with nothing loaded (no video id and no url) is discarded.
|
||||
if (room.videoId.empty() && room.url.empty()) {
|
||||
rooms_.erase(roomIt);
|
||||
return;
|
||||
}
|
||||
// Persist the session: freeze playback where it was so the next
|
||||
// joiner (who becomes host) resumes in place. Live sources
|
||||
// (Twitch / generic embeds) have no position to freeze.
|
||||
room.positionMs = livePosition(room);
|
||||
if (!isLiveSource(room.source, room.controllable)) {
|
||||
room.paused = true;
|
||||
}
|
||||
room.anchor = std::chrono::steady_clock::now();
|
||||
room.host = 0;
|
||||
room.lastActive = std::chrono::steady_clock::now();
|
||||
return;
|
||||
}
|
||||
// Host migration: hand the room to the longest-standing authenticated
|
||||
// participant; guests never host (host stays vacant until an
|
||||
// authenticated user joins or signs in).
|
||||
if (room.host == connId) {
|
||||
room.host = pickHost(room);
|
||||
}
|
||||
sendParticipants(room);
|
||||
// A departure changes the majority threshold and may complete a
|
||||
// pending skip; re-broadcast the tally so clients stay accurate.
|
||||
if (!room.videoId.empty() || !room.url.empty()) {
|
||||
if (!room.skipVotes.empty() &&
|
||||
room.skipVotes.size() >= skipThreshold(room)) {
|
||||
room.skipVotes.clear();
|
||||
if (!room.queue.empty()) {
|
||||
QueueEntry next = std::move(room.queue.front());
|
||||
room.queue.pop_front();
|
||||
loadIntoRoom(room, next.source, next.url, next.videoId, 0);
|
||||
sendQueue(room);
|
||||
}
|
||||
} else {
|
||||
sendSkipState(room);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void WatchSessionManager::onDisconnect(uint64_t connId)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
leaveCurrentRoom(connId);
|
||||
}
|
||||
|
||||
void WatchSessionManager::onMessage(uint64_t connId, const std::string& json)
|
||||
{
|
||||
auto parsed = Void::Json::parse(json);
|
||||
if (!parsed || !parsed->is_object()) {
|
||||
return;
|
||||
}
|
||||
const std::string type = parsed->get_str("type");
|
||||
if (type.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
// A valid RPC token upgrades the participant: server-trusted nickname
|
||||
// and the right to control playback / host the room.
|
||||
std::optional<Identity> identity;
|
||||
if (const std::string token = parsed->get_str("token");
|
||||
!token.empty() && identityResolver_) {
|
||||
identity = identityResolver_(token);
|
||||
}
|
||||
|
||||
if (type == "watch.join") {
|
||||
const std::string roomName = parsed->get_str("room", "main");
|
||||
std::string name = identity ? identity->nickname
|
||||
: parsed->get_str("name");
|
||||
if (name.empty()) {
|
||||
name = std::format("guest-{}", connId);
|
||||
}
|
||||
leaveCurrentRoom(connId);
|
||||
connRoom_[connId] = roomName;
|
||||
Room& room = rooms_[roomName];
|
||||
room.participants[connId] =
|
||||
Participant{.name = name,
|
||||
.uid = identity ? identity->uid : std::string{},
|
||||
.authenticated = identity.has_value()};
|
||||
if (room.host == 0 && identity) {
|
||||
room.host = connId;
|
||||
}
|
||||
// Ack with the caller's own id so the client can recognize
|
||||
// itself in participant lists and host announcements.
|
||||
send(connId,
|
||||
Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.joined"}},
|
||||
{"selfId", Value{static_cast<long long>(connId)}},
|
||||
{"authenticated", Value{identity.has_value()}},
|
||||
{"room", Value{roomName}}})));
|
||||
sendSnapshot(connId, room);
|
||||
sendQueue(room, connId);
|
||||
// Replay the recent chat backlog to the newcomer only.
|
||||
for (const auto& msg : room.chat) {
|
||||
send(connId,
|
||||
Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.chat"}},
|
||||
{"name", Value{msg.name}},
|
||||
{"text", Value{msg.text}},
|
||||
{"timestampMs", Value{msg.timestampMs}}})));
|
||||
}
|
||||
sendParticipants(room);
|
||||
sendSkipState(room);
|
||||
return;
|
||||
}
|
||||
|
||||
// Lobby query: list active rooms. Valid without having joined one.
|
||||
if (type == "watch.rooms.list") {
|
||||
sendRoomsList(connId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Leave the current room and return to the lobby without joining
|
||||
// another one. leaveCurrentRoom migrates/vacates host and prunes an
|
||||
// empty room; we then ack and refresh the caller's lobby list.
|
||||
if (type == "watch.leave") {
|
||||
leaveCurrentRoom(connId);
|
||||
send(connId, Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.left"}}})));
|
||||
sendRoomsList(connId);
|
||||
return;
|
||||
}
|
||||
|
||||
// All remaining messages act on the caller's current room.
|
||||
auto roomNameIt = connRoom_.find(connId);
|
||||
if (roomNameIt == connRoom_.end()) {
|
||||
return;
|
||||
}
|
||||
auto roomIt = rooms_.find(roomNameIt->second);
|
||||
if (roomIt == rooms_.end()) {
|
||||
return;
|
||||
}
|
||||
Room& room = roomIt->second;
|
||||
auto selfIt = room.participants.find(connId);
|
||||
if (selfIt == room.participants.end()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Manipulation requires an authenticated participant; playback and
|
||||
// queue advancement additionally require the host role. Guests only
|
||||
// watch, chat and react.
|
||||
const bool isHost = (connId == room.host);
|
||||
const bool isControl =
|
||||
(type == "watch.load" || type == "watch.play" ||
|
||||
type == "watch.pause" || type == "watch.seek" ||
|
||||
type == "watch.rate" || type == "watch.queue.add" ||
|
||||
type == "watch.queue.remove" || type == "watch.queue.next" ||
|
||||
type == "watch.host.transfer" || type == "watch.embed.caps" ||
|
||||
type == "watch.embed.control");
|
||||
const bool needsHost =
|
||||
(type == "watch.load" || type == "watch.play" ||
|
||||
type == "watch.pause" || type == "watch.seek" ||
|
||||
type == "watch.rate" || type == "watch.queue.next" ||
|
||||
type == "watch.host.transfer" || type == "watch.embed.caps" ||
|
||||
type == "watch.embed.control");
|
||||
if (isControl && !selfIt->second.authenticated) {
|
||||
sendDenied(connId, "Sign in to control playback");
|
||||
return;
|
||||
}
|
||||
if (needsHost && !isHost) {
|
||||
sendDenied(connId, "Only the host controls playback");
|
||||
return;
|
||||
}
|
||||
|
||||
if (type == "watch.load") {
|
||||
loadIntoRoom(room, parsed->get_str("source", "youtube"),
|
||||
parsed->get_str("url"), parsed->get_str("channel"),
|
||||
connId);
|
||||
sendSnapshot(connId, room);
|
||||
} else if (type == "watch.queue.add") {
|
||||
if (room.queue.size() >= kQueueMax) {
|
||||
sendDenied(connId, "Watch queue is full");
|
||||
return;
|
||||
}
|
||||
const std::string url = parsed->get_str("url");
|
||||
if (url.empty()) {
|
||||
return;
|
||||
}
|
||||
QueueEntry entry;
|
||||
entry.source = canonicalSource(parsed->get_str("source", "youtube"));
|
||||
entry.url = url;
|
||||
if (entry.source == "twitch") {
|
||||
entry.videoId = twitchChannelFrom(url);
|
||||
} else if (entry.source == "youtube") {
|
||||
entry.videoId = videoIdFromUrl(url);
|
||||
} else {
|
||||
entry.videoId.clear(); // direct/iframe carry the whole url
|
||||
}
|
||||
entry.thumbnailUrl = thumbnailFor(entry.source, entry.videoId);
|
||||
// Title: server-side resolver first (real YouTube titles), then
|
||||
// the client's best-effort title, then a sensible default (the
|
||||
// Twitch channel name / the bare video id / the url).
|
||||
if (metadataResolver_) {
|
||||
if (auto resolved = metadataResolver_(
|
||||
entry.source, entry.videoId, entry.url)) {
|
||||
entry.title = *resolved;
|
||||
}
|
||||
}
|
||||
if (entry.title.empty()) {
|
||||
entry.title = parsed->get_str("title");
|
||||
}
|
||||
if (entry.title.empty()) {
|
||||
entry.title =
|
||||
entry.videoId.empty() ? entry.url : entry.videoId;
|
||||
}
|
||||
if (entry.title.size() > 200) {
|
||||
entry.title.resize(200);
|
||||
}
|
||||
entry.addedBy = selfIt->second.name;
|
||||
// Nothing playing yet: start this item immediately instead of
|
||||
// parking it in the queue.
|
||||
if (room.videoId.empty() && room.url.empty()) {
|
||||
loadIntoRoom(room, entry.source, entry.url, entry.videoId,
|
||||
connId);
|
||||
return;
|
||||
}
|
||||
room.queue.push_back(std::move(entry));
|
||||
sendQueue(room);
|
||||
} else if (type == "watch.queue.remove") {
|
||||
const auto index =
|
||||
static_cast<long long>(parsed->get_num("index", -1));
|
||||
if (index < 0 ||
|
||||
index >= static_cast<long long>(room.queue.size())) {
|
||||
return;
|
||||
}
|
||||
room.queue.erase(room.queue.begin() + index);
|
||||
sendQueue(room);
|
||||
} else if (type == "watch.queue.next") {
|
||||
if (room.queue.empty()) {
|
||||
// End of playback with nothing queued: clear the current video
|
||||
// so every client shows the empty placeholder. (The manual
|
||||
// "Play next" button is disabled when the queue is empty, so
|
||||
// this is reached only by the auto-advance-on-end path.)
|
||||
room.videoId.clear();
|
||||
room.url.clear();
|
||||
room.paused = true;
|
||||
room.controllable = false;
|
||||
room.embedControls.clear();
|
||||
room.skipVotes.clear();
|
||||
const std::string msg = Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.loaded"}},
|
||||
{"source", Value{room.source}},
|
||||
{"url", Value{std::string{}}},
|
||||
{"videoId", Value{std::string{}}},
|
||||
{"controllable", Value{false}},
|
||||
{"by", Value{static_cast<long long>(connId)}}}));
|
||||
broadcast(room, msg);
|
||||
sendSkipState(room);
|
||||
return;
|
||||
}
|
||||
QueueEntry next = std::move(room.queue.front());
|
||||
room.queue.pop_front();
|
||||
loadIntoRoom(room, next.source, next.url, next.videoId, connId);
|
||||
sendQueue(room);
|
||||
sendSnapshot(connId, room);
|
||||
} else if (type == "watch.play") {
|
||||
room.positionMs = parsed->has("positionMs")
|
||||
? static_cast<long long>(
|
||||
parsed->get_num("positionMs"))
|
||||
: livePosition(room);
|
||||
room.paused = false;
|
||||
room.anchor = std::chrono::steady_clock::now();
|
||||
const std::string msg = Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.play"}},
|
||||
{"positionMs", Value{room.positionMs}},
|
||||
{"serverTimeMs", Value{nowMillis()}}}));
|
||||
broadcast(room, msg);
|
||||
} else if (type == "watch.pause") {
|
||||
room.positionMs = parsed->has("positionMs")
|
||||
? static_cast<long long>(
|
||||
parsed->get_num("positionMs"))
|
||||
: livePosition(room);
|
||||
room.paused = true;
|
||||
room.anchor = std::chrono::steady_clock::now();
|
||||
const std::string msg = Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.pause"}},
|
||||
{"positionMs", Value{room.positionMs}}}));
|
||||
broadcast(room, msg);
|
||||
} else if (type == "watch.seek") {
|
||||
if (isLiveSource(room.source, room.controllable)) {
|
||||
sendDenied(connId, "Live stream — cannot seek");
|
||||
return;
|
||||
}
|
||||
room.positionMs = static_cast<long long>(
|
||||
parsed->get_num("positionMs"));
|
||||
room.anchor = std::chrono::steady_clock::now();
|
||||
const std::string msg = Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.seek"}},
|
||||
{"positionMs", Value{room.positionMs}},
|
||||
{"serverTimeMs", Value{nowMillis()}}}));
|
||||
broadcast(room, msg);
|
||||
} else if (type == "watch.rate") {
|
||||
// Host sets the shared playback rate (YouTube only). Clamp to the
|
||||
// values the YouTube player accepts.
|
||||
double rate = parsed->get_num("rate", 1.0);
|
||||
if (rate < 0.25) {
|
||||
rate = 0.25;
|
||||
}
|
||||
if (rate > 2.0) {
|
||||
rate = 2.0;
|
||||
}
|
||||
room.rate = rate;
|
||||
const std::string msg = Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.rate"}}, {"rate", Value{room.rate}}}));
|
||||
broadcast(room, msg);
|
||||
} else if (type == "watch.embed.control") {
|
||||
if (room.source != "iframe") {
|
||||
return;
|
||||
}
|
||||
const std::string id = parsed->get_str("id");
|
||||
const std::string value = parsed->get_str("value");
|
||||
if (id.empty() || id.size() > 32 || value.size() > 200 ||
|
||||
id.find_first_not_of(
|
||||
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_") !=
|
||||
std::string::npos) {
|
||||
return;
|
||||
}
|
||||
const bool syncedControl =
|
||||
id == "audiotrack" || id == "episode" || id == "playlist" ||
|
||||
id == "playlist-next" || id == "playlist-prev" ||
|
||||
id == "translation";
|
||||
if (!syncedControl) {
|
||||
return;
|
||||
}
|
||||
if (!room.embedControls.contains(id) &&
|
||||
room.embedControls.size() >= kEmbedControlsMax) {
|
||||
return;
|
||||
}
|
||||
room.embedControls[id] = value;
|
||||
const std::string msg = Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.embed.control"}},
|
||||
{"id", Value{id}},
|
||||
{"value", Value{value}}}));
|
||||
broadcast(room, msg);
|
||||
} else if (type == "watch.embed.caps") {
|
||||
// Host's client reports whether the loaded iframe embed answered
|
||||
// the postMessage handshake; flips the room between view-only
|
||||
// live and fully seekable. Meaningless for other sources.
|
||||
if (room.source != "iframe") {
|
||||
return;
|
||||
}
|
||||
const bool controllable = parsed->get_bool("controllable", false);
|
||||
if (room.controllable == controllable) {
|
||||
return;
|
||||
}
|
||||
room.controllable = controllable;
|
||||
// Snapshot everyone immediately so timelines flip without waiting
|
||||
// for the 3s heartbeat.
|
||||
for (const auto& [pid, p] : room.participants) {
|
||||
sendSnapshot(pid, room);
|
||||
}
|
||||
} else if (type == "watch.state") {
|
||||
sendSnapshot(connId, room);
|
||||
} else if (type == "watch.host.transfer") {
|
||||
// Host hands control to another authenticated participant.
|
||||
const auto targetId =
|
||||
static_cast<uint64_t>(parsed->get_num("targetId", 0));
|
||||
auto targetIt = room.participants.find(targetId);
|
||||
if (targetIt == room.participants.end()) {
|
||||
sendDenied(connId, "That viewer is no longer here");
|
||||
return;
|
||||
}
|
||||
if (!targetIt->second.authenticated) {
|
||||
sendDenied(connId, "Only signed-in viewers can host");
|
||||
return;
|
||||
}
|
||||
room.host = targetId;
|
||||
sendParticipants(room);
|
||||
} else if (type == "watch.skip.vote") {
|
||||
// Any participant may vote to skip the current video; a majority
|
||||
// advances the queue (or clears the video when the queue is
|
||||
// empty). Toggling removes the vote.
|
||||
if (room.videoId.empty() && room.url.empty()) {
|
||||
return;
|
||||
}
|
||||
if (room.skipVotes.count(connId)) {
|
||||
room.skipVotes.erase(connId);
|
||||
} else {
|
||||
room.skipVotes.insert(connId);
|
||||
}
|
||||
if (room.skipVotes.size() >= skipThreshold(room)) {
|
||||
room.skipVotes.clear();
|
||||
if (!room.queue.empty()) {
|
||||
QueueEntry next = std::move(room.queue.front());
|
||||
room.queue.pop_front();
|
||||
loadIntoRoom(room, next.source, next.url, next.videoId,
|
||||
connId);
|
||||
sendQueue(room);
|
||||
} else {
|
||||
// Nothing queued: clear the current video.
|
||||
room.videoId.clear();
|
||||
room.url.clear();
|
||||
room.paused = true;
|
||||
const std::string msg =
|
||||
Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.loaded"}},
|
||||
{"source", Value{room.source}},
|
||||
{"url", Value{std::string{}}},
|
||||
{"videoId", Value{std::string{}}},
|
||||
{"by", Value{static_cast<long long>(connId)}}}));
|
||||
broadcast(room, msg);
|
||||
sendSkipState(room);
|
||||
}
|
||||
} else {
|
||||
sendSkipState(room);
|
||||
}
|
||||
} else if (type == "watch.rename") {
|
||||
// In-place rename (e.g. the user authenticated after joining);
|
||||
// keeps chat history. A valid token upgrades the participant to
|
||||
// authenticated and lets them claim a vacant host slot.
|
||||
std::string name = identity ? identity->nickname
|
||||
: parsed->get_str("name");
|
||||
if (name.empty() || name.size() > 64) {
|
||||
return;
|
||||
}
|
||||
selfIt->second.name = name;
|
||||
if (identity) {
|
||||
selfIt->second.authenticated = true;
|
||||
selfIt->second.uid = identity->uid;
|
||||
if (room.host == 0) {
|
||||
room.host = connId;
|
||||
}
|
||||
}
|
||||
// Re-ack so the client sees its (possibly upgraded) standing.
|
||||
send(connId,
|
||||
Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.joined"}},
|
||||
{"selfId", Value{static_cast<long long>(connId)}},
|
||||
{"authenticated",
|
||||
Value{selfIt->second.authenticated}},
|
||||
{"room", Value{roomNameIt->second}}})));
|
||||
sendParticipants(room);
|
||||
} else if (type == "watch.report") {
|
||||
// Client progress report (drift display; no authority change).
|
||||
auto pIt = room.participants.find(connId);
|
||||
if (pIt == room.participants.end()) {
|
||||
return;
|
||||
}
|
||||
pIt->second.reportedMs = parsed->has("positionMs")
|
||||
? static_cast<long long>(
|
||||
parsed->get_num("positionMs"))
|
||||
: -1;
|
||||
pIt->second.authorityMs = livePosition(room);
|
||||
pIt->second.buffering = parsed->get_bool("buffering", false);
|
||||
} else if (type == "watch.chat") {
|
||||
const std::string text = parsed->get_str("text");
|
||||
if (text.empty() || text.size() > 500) {
|
||||
return;
|
||||
}
|
||||
auto pIt = room.participants.find(connId);
|
||||
const std::string name = pIt != room.participants.end()
|
||||
? pIt->second.name
|
||||
: std::format("guest-{}", connId);
|
||||
room.chat.push_back(ChatMessage{
|
||||
.name = name, .text = text, .timestampMs = nowMillis()});
|
||||
while (room.chat.size() > kChatBacklog) {
|
||||
room.chat.pop_front();
|
||||
}
|
||||
const std::string msg = Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.chat"}},
|
||||
{"name", Value{name}},
|
||||
{"text", Value{text}},
|
||||
{"timestampMs", Value{room.chat.back().timestampMs}}}));
|
||||
broadcast(room, msg);
|
||||
} else if (type == "watch.reaction") {
|
||||
// Unicode emoji (a few bytes) or a :custom-emoji: shortcode.
|
||||
const std::string emoji = parsed->get_str("emoji");
|
||||
if (emoji.empty() || emoji.size() > 48) {
|
||||
return;
|
||||
}
|
||||
auto pIt = room.participants.find(connId);
|
||||
const std::string name = pIt != room.participants.end()
|
||||
? pIt->second.name
|
||||
: std::format("guest-{}", connId);
|
||||
const std::string msg = Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.reaction"}},
|
||||
{"name", Value{name}},
|
||||
{"emoji", Value{emoji}}}));
|
||||
broadcast(room, msg);
|
||||
}
|
||||
}
|
||||
|
||||
void WatchSessionManager::broadcastSync()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
// Prune persisted-but-abandoned rooms that nobody rejoined.
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
for (auto it = rooms_.begin(); it != rooms_.end();) {
|
||||
if (it->second.participants.empty() &&
|
||||
now - it->second.lastActive > kEmptyRoomTtl) {
|
||||
it = rooms_.erase(it);
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
for (const auto& [name, room] : rooms_) {
|
||||
if (room.participants.empty()) {
|
||||
continue;
|
||||
}
|
||||
const std::string msg = Void::Json::serialize(Void::Json::object(
|
||||
{{"type", Value{"watch.sync"}},
|
||||
{"source", Value{room.source}},
|
||||
{"url", Value{room.url}},
|
||||
{"videoId", Value{room.videoId}},
|
||||
{"controllable", Value{room.controllable}},
|
||||
{"paused", Value{room.paused}},
|
||||
{"rate", Value{room.rate}},
|
||||
{"embedControls", embedControlsValue(room.embedControls)},
|
||||
{"positionMs", Value{livePosition(room)}},
|
||||
{"serverTimeMs", Value{nowMillis()}},
|
||||
{"host", Value{static_cast<long long>(room.host)}}}));
|
||||
broadcast(room, msg);
|
||||
// Participants ride the same 3s heartbeat so drift/buffering
|
||||
// badges stay fresh without per-report broadcasts.
|
||||
sendParticipants(room);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Echoion::Web
|
||||
@@ -0,0 +1,300 @@
|
||||
#include "echoion/web/HttpSecurity.hpp"
|
||||
#include "echoion/web/HttpServer.hpp"
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Echoion::Web::Security::ShortLinkRateLimiter;
|
||||
namespace asio = boost::asio;
|
||||
|
||||
bool expect(bool condition, std::string_view message)
|
||||
{
|
||||
if (!condition) {
|
||||
std::cerr << message << '\n';
|
||||
}
|
||||
return condition;
|
||||
}
|
||||
|
||||
bool testShortSlugs()
|
||||
{
|
||||
using Echoion::Web::Security::validShortSlug;
|
||||
std::string nonAscii(9, 'a');
|
||||
nonAscii.push_back(static_cast<char>(0xe9));
|
||||
return expect(validShortSlug("aZ019BcDeF"),
|
||||
"ASCII short slug was rejected") &&
|
||||
expect(!validShortSlug("aZ019BcDe_"),
|
||||
"punctuation was accepted in a short slug") &&
|
||||
expect(!validShortSlug("short"),
|
||||
"short slug length was not enforced") &&
|
||||
expect(!validShortSlug(nonAscii),
|
||||
"locale-dependent non-ASCII alphanumeric was accepted");
|
||||
}
|
||||
|
||||
bool testCidrsAndForwarding()
|
||||
{
|
||||
using Echoion::Web::Security::effectiveClientAddress;
|
||||
using Echoion::Web::Security::parseTrustedProxyCidrs;
|
||||
|
||||
const std::vector<std::string> trustedTexts{"10.0.0.0/8",
|
||||
"192.0.2.0/24"};
|
||||
auto trusted = parseTrustedProxyCidrs(trustedTexts);
|
||||
if (!expect(trusted.has_value(), "valid trusted proxy CIDRs failed")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::vector<std::string> invalidCidrs{"",
|
||||
"10.0.0.0/",
|
||||
"10.0.0.0/33",
|
||||
"10.0.0.0/-1",
|
||||
"10.0.0.0/+8",
|
||||
"10.0.0.0/8 ",
|
||||
" 10.0.0.0/8",
|
||||
"2001:db8::/129",
|
||||
"fe80::1%1/128",
|
||||
"10.0.0.0/8/9",
|
||||
"not-an-address"};
|
||||
for (const auto& invalid : invalidCidrs) {
|
||||
const std::vector<std::string> one{invalid};
|
||||
if (!expect(!parseTrustedProxyCidrs(one),
|
||||
"invalid trusted proxy CIDR was accepted: " +
|
||||
invalid)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const std::vector<std::string> mappedV4Text{"192.0.2.0/24"};
|
||||
auto mappedV4 = parseTrustedProxyCidrs(mappedV4Text);
|
||||
const std::vector<std::string> mappedV6Text{"::ffff:192.0.2.0/120"};
|
||||
auto mappedV6 = parseTrustedProxyCidrs(mappedV6Text);
|
||||
if (!expect(mappedV4 && mappedV6,
|
||||
"IPv4-mapped test networks did not parse") ||
|
||||
!expect((*mappedV4)[0].contains(
|
||||
asio::ip::make_address("::ffff:192.0.2.42")),
|
||||
"IPv4 CIDR did not match an IPv4-mapped peer") ||
|
||||
!expect(
|
||||
(*mappedV6)[0].contains(asio::ip::make_address("192.0.2.42")),
|
||||
"IPv4-mapped IPv6 CIDR did not match an IPv4 peer")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto immediate = asio::ip::make_address("10.0.0.10");
|
||||
if (!expect(effectiveClientAddress(
|
||||
immediate, "203.0.113.9, 198.51.100.7, 192.0.2.20",
|
||||
*trusted) == "198.51.100.7",
|
||||
"X-Forwarded-For was not walked from right to left") ||
|
||||
!expect(effectiveClientAddress(immediate,
|
||||
"203.0.113.9, 198.51.100.7",
|
||||
*trusted) == "198.51.100.7",
|
||||
"spoofed leftmost forwarded hop was trusted") ||
|
||||
!expect(effectiveClientAddress(asio::ip::make_address("172.16.0.2"),
|
||||
"203.0.113.9",
|
||||
*trusted) == "172.16.0.2",
|
||||
"untrusted direct peer supplied a forwarded address") ||
|
||||
!expect(effectiveClientAddress(immediate,
|
||||
"203.0.113.9, invalid, 192.0.2.20",
|
||||
*trusted) == "10.0.0.10",
|
||||
"malformed forwarded chain was partially accepted") ||
|
||||
!expect(effectiveClientAddress(
|
||||
asio::ip::make_address("::ffff:10.0.0.10"),
|
||||
"198.51.100.7", *trusted) == "198.51.100.7",
|
||||
"IPv4-mapped trusted peer was not recognized") ||
|
||||
!expect(effectiveClientAddress(immediate,
|
||||
"203.0.113.9, ::ffff:192.0.2.20",
|
||||
*trusted) == "203.0.113.9",
|
||||
"IPv4-mapped trusted intermediary was not recognized") ||
|
||||
!expect(effectiveClientAddress(
|
||||
asio::ip::make_address("::ffff:172.16.0.2"),
|
||||
std::nullopt, *trusted) == "172.16.0.2",
|
||||
"IPv4-mapped direct address was not normalized")) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool testRedirectLocations()
|
||||
{
|
||||
using Echoion::Web::Security::validRedirectLocation;
|
||||
const std::vector<std::string_view> valid{
|
||||
"https://example.test/watch?v=abc%201#fragment",
|
||||
"HTTP://example.test/", "http://[2001:db8::1]:8080/path"};
|
||||
for (const auto location : valid) {
|
||||
if (!expect(validRedirectLocation(location),
|
||||
"valid HTTP redirect was rejected")) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const std::vector<std::string_view> invalid{
|
||||
"",
|
||||
"ftp://example.test/file",
|
||||
"/relative/path",
|
||||
"http:///missing-host",
|
||||
"https://user@example.test/",
|
||||
"https://example.test:",
|
||||
"https://example.test:0/",
|
||||
"https://example.test:65536/",
|
||||
"https://example.test/a b"};
|
||||
for (const auto location : invalid) {
|
||||
if (!expect(!validRedirectLocation(location),
|
||||
"unsafe redirect location was accepted")) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
for (unsigned int control = 0; control <= 0x20; ++control) {
|
||||
std::string location = "https://example.test/path";
|
||||
location.push_back(static_cast<char>(control));
|
||||
if (!expect(!validRedirectLocation(location),
|
||||
"ASCII control was accepted in redirect location")) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (const unsigned int control : {0x7fU, 0x80U, 0x9fU}) {
|
||||
std::string location = "https://example.test/path";
|
||||
location.push_back(static_cast<char>(control));
|
||||
if (!expect(!validRedirectLocation(location),
|
||||
"DEL/C1 control was accepted in redirect location")) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool testTrustedProxyRuntimeUpdates()
|
||||
{
|
||||
Echoion::Web::HttpServer server;
|
||||
const std::vector<std::string> initial{"127.0.0.0/8"};
|
||||
const std::vector<std::string> replacement{"::1/128"};
|
||||
const std::vector<std::string> invalid{"127.0.0.1/129"};
|
||||
const std::vector<std::string> none;
|
||||
return expect(server.setTrustedProxyCidrs(initial).has_value(),
|
||||
"initial live trusted-proxy update failed") &&
|
||||
expect(server.setTrustedProxyCidrs(replacement).has_value(),
|
||||
"replacement live trusted-proxy update failed") &&
|
||||
expect(!server.setTrustedProxyCidrs(invalid),
|
||||
"invalid live trusted-proxy update was accepted") &&
|
||||
expect(server.setTrustedProxyCidrs(none).has_value(),
|
||||
"clearing live trusted proxies failed");
|
||||
}
|
||||
|
||||
bool testRateLimiterFairnessAndBounds()
|
||||
{
|
||||
using namespace std::chrono_literals;
|
||||
const auto now = ShortLinkRateLimiter::TimePoint{} + 1s;
|
||||
ShortLinkRateLimiter fair({
|
||||
.globalRate = 0.0,
|
||||
.globalBurst = 2.0,
|
||||
.peerRate = 0.0,
|
||||
.peerBurst = 1.0,
|
||||
.maxPeers = 4,
|
||||
.idleTimeout = 1min,
|
||||
.sweepInterval = 1min,
|
||||
});
|
||||
if (!expect(fair.allow("peer-a", now),
|
||||
"first peer request was rejected") ||
|
||||
!expect(!fair.allow("peer-a", now),
|
||||
"peer burst limit was not enforced") ||
|
||||
!expect(fair.allow("peer-b", now),
|
||||
"peer rejection consumed unrelated global capacity")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
ShortLinkRateLimiter bounded({
|
||||
.globalRate = 100.0,
|
||||
.globalBurst = 100.0,
|
||||
.peerRate = 100.0,
|
||||
.peerBurst = 2.0,
|
||||
.maxPeers = 2,
|
||||
.idleTimeout = 100ms,
|
||||
.sweepInterval = 1h,
|
||||
});
|
||||
if (!expect(bounded.allow("peer-a", now) &&
|
||||
bounded.allow("peer-b", now),
|
||||
"bounded limiter rejected initial peers") ||
|
||||
!expect(!bounded.allow("peer-c", now),
|
||||
"bounded limiter exceeded its peer cap") ||
|
||||
!expect(bounded.trackedPeerCount() == 2,
|
||||
"bounded limiter retained too many peers") ||
|
||||
!expect(bounded.allow("peer-c", now + 200ms),
|
||||
"idle peer entries were not evicted") ||
|
||||
!expect(bounded.trackedPeerCount() <= 2,
|
||||
"idle eviction broke the peer cap")) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool testRateLimiterConcurrency()
|
||||
{
|
||||
using namespace std::chrono_literals;
|
||||
ShortLinkRateLimiter limiter({
|
||||
.globalRate = 0.0,
|
||||
.globalBurst = 100.0,
|
||||
.peerRate = 0.0,
|
||||
.peerBurst = 5.0,
|
||||
.maxPeers = 16,
|
||||
.idleTimeout = 1min,
|
||||
.sweepInterval = 1min,
|
||||
});
|
||||
const auto now = ShortLinkRateLimiter::TimePoint{} + 1s;
|
||||
std::atomic<unsigned int> allowed{0};
|
||||
std::vector<std::thread> workers;
|
||||
workers.reserve(32);
|
||||
for (int index = 0; index < 32; ++index) {
|
||||
workers.emplace_back([&] {
|
||||
if (limiter.allow("one-peer", now)) {
|
||||
++allowed;
|
||||
}
|
||||
});
|
||||
}
|
||||
for (auto& worker : workers) {
|
||||
worker.join();
|
||||
}
|
||||
if (!expect(allowed.load() == 5,
|
||||
"concurrent limiter admitted beyond the peer burst")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
ShortLinkRateLimiter global({
|
||||
.globalRate = 0.0,
|
||||
.globalBurst = 7.0,
|
||||
.peerRate = 0.0,
|
||||
.peerBurst = 1.0,
|
||||
.maxPeers = 64,
|
||||
.idleTimeout = 1min,
|
||||
.sweepInterval = 1min,
|
||||
});
|
||||
allowed = 0;
|
||||
workers.clear();
|
||||
for (int index = 0; index < 32; ++index) {
|
||||
workers.emplace_back([&, index] {
|
||||
if (global.allow("peer-" + std::to_string(index), now)) {
|
||||
++allowed;
|
||||
}
|
||||
});
|
||||
}
|
||||
for (auto& worker : workers) {
|
||||
worker.join();
|
||||
}
|
||||
return expect(allowed.load() == 7,
|
||||
"concurrent limiter admitted beyond the global burst");
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
return testShortSlugs() && testCidrsAndForwarding() &&
|
||||
testRedirectLocations() &&
|
||||
testTrustedProxyRuntimeUpdates() &&
|
||||
testRateLimiterFairnessAndBounds() &&
|
||||
testRateLimiterConcurrency()
|
||||
? 0
|
||||
: 1;
|
||||
}
|
||||
@@ -14,40 +14,67 @@ A modern music bot for TeamSpeak 3, featuring YouTube integration, playlist supp
|
||||
- ⭐ **History & Favorites** - `!history`, `!stats`, `!fav add|list|play` backed by SQLite
|
||||
- 📋 **Playlist Support** - Queue management with shuffle, repeat, and skip functionality
|
||||
- 🎧 **High Quality Audio** - 192kHz stereo internal pipeline
|
||||
- 🔄 **Hot Reload** - Update the bot without disconnecting from the server
|
||||
- 🔄 **Transactional Updates** - Validate a complete daemon/Core/protocol
|
||||
release, checkpoint playback, re-exec, reconnect, and restore playback
|
||||
- ⚙️ **Configurable** - JSON-based configuration system
|
||||
- 🔊 **TeamSpeak Native** - Uses TeamSpeak's native audio system for best quality
|
||||
- 🧩 **VoidTeamspeak SDK** - Native protocol support is an independently
|
||||
consumable modern C++ library rather than an Echoion-internal component
|
||||
- 🌐 **Public Dashboard** - Current playback plus the complete sanitized
|
||||
TeamSpeak channel/client tree, with authenticated administration for admins
|
||||
- 🎬 **VoidWatch Link** - Watch Together is deployed independently from the
|
||||
`EchoionWatch` repository and linked through `web.watchUrl`
|
||||
|
||||
## Building
|
||||
|
||||
### Requirements
|
||||
### Developer requirements
|
||||
|
||||
- C++26 compatible compiler with reflections (GCC 16+)
|
||||
- CMake 4.0+
|
||||
- Qt6 (for desktop client)
|
||||
- FFmpeg (for audio decoding)
|
||||
- Qt6 (only when building the desktop client)
|
||||
- FFmpeg 5+ (for audio decoding and the modern channel-layout API)
|
||||
- Boost (system installation preferred; the build vendors one only when absent — mixing a vendored and a system Boost in one process breaks boost.url)
|
||||
- TeamSpeak 3 Client SDK
|
||||
- OpenSSL, libsodium, Opus, FFmpeg, and Boost development packages
|
||||
|
||||
### Build Instructions
|
||||
### Local build
|
||||
|
||||
```bash
|
||||
mkdir build && cd build
|
||||
cmake ..
|
||||
cmake --build .
|
||||
cmake -S . -B build -DBUILD_TESTS=ON
|
||||
cmake --build build -j2
|
||||
ctest --test-dir build --output-on-failure
|
||||
```
|
||||
|
||||
### Tests
|
||||
The supported Linux release is dynamically linked. Static GCC runtime linking
|
||||
is disabled by default; the release process collects the non-glibc shared
|
||||
library closure into the bundle and assigns relocatable `$ORIGIN` RUNPATHs.
|
||||
|
||||
### Clean containerized Linux release
|
||||
|
||||
Docker is the only host requirement for the default release command:
|
||||
|
||||
```bash
|
||||
cmake .. -DBUILD_TESTS=ON
|
||||
cmake --build . && ctest
|
||||
scripts/release.sh --version 1.2.3
|
||||
```
|
||||
|
||||
The suite covers the decoder (against generated audio fixtures), the queue
|
||||
and shuffle bookkeeping, the gapless playback engine (asserting a seamless
|
||||
track boundary), and the source router (fall-through, hedging and stream
|
||||
caching).
|
||||
When validating coordinated, not-yet-published dependency changes, pass
|
||||
`--void-source ../VoidLibrary --void-teamspeak-source ../VoidTeamspeak`. The
|
||||
container builder mounts those source trees read-only and still builds into a
|
||||
clean directory; normal published releases omit the overrides and use the
|
||||
version-pinned dependencies.
|
||||
|
||||
It builds with a version-pinned GCC 16/FFmpeg 8.0.3 toolchain on Ubuntu 22.04,
|
||||
runs the C++ and frontend test suites, installs into a clean staging tree,
|
||||
bundles dynamic dependencies, validates the ELF closure with `readelf`, and
|
||||
produces both `.tar.zst` and self-extracting `.run` artifacts under `dist/`.
|
||||
The bot is never initialized or started during release creation. Use `--host`
|
||||
only on a Debian-family build host with `dpkg-query`, `ldconfig`, and a glibc
|
||||
ABI no newer than the supported 2.35 floor; incompatible host artifacts are
|
||||
rejected.
|
||||
|
||||
The Linux x86-64 bundle targets glibc 2.35 or newer (Ubuntu 22.04+, Debian 12+,
|
||||
and current Arch Linux). glibc and the ELF loader come from the target system;
|
||||
libstdc++, libgcc, FFmpeg, OpenSSL, Opus, and the remaining runtime closure are
|
||||
carried in `lib/`.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -61,7 +88,7 @@ Edit the configuration file with your server details:
|
||||
|
||||
```json
|
||||
{
|
||||
"server": {
|
||||
"teamspeak": {
|
||||
"address": "your.server.com",
|
||||
"port": 9987,
|
||||
"nickname": "MusicBot",
|
||||
@@ -72,13 +99,113 @@ Edit the configuration file with your server details:
|
||||
|
||||
## Installation
|
||||
|
||||
### TeamSpeak Plugin
|
||||
The `.run` artifact is the recommended installer. It supports system, user,
|
||||
and portable layouts and never starts the bot unless `--start` is explicitly
|
||||
supplied.
|
||||
|
||||
1. Build the project
|
||||
2. Copy the plugin to your TeamSpeak plugins folder:
|
||||
- **Linux**: `~/.ts3client/plugins/`
|
||||
- **Windows**: `%APPDATA%\TS3Client\plugins\`
|
||||
3. Enable the plugin in TeamSpeak's plugins menu
|
||||
```bash
|
||||
# User install; registers a disabled/stopped user service.
|
||||
./echoion-1.2.3-linux-x86_64.run \
|
||||
--mode user --non-interactive
|
||||
|
||||
# System install and explicit activation.
|
||||
sudo ./echoion-1.2.3-linux-x86_64.run \
|
||||
--mode system --register-service system --start --non-interactive
|
||||
|
||||
# Fully self-contained portable install, without a service.
|
||||
./echoion-1.2.3-linux-x86_64.run \
|
||||
--mode portable --prefix /srv/echoion-portable \
|
||||
--data-layout self-contained --register-service none --non-interactive
|
||||
|
||||
# A portable tree may also register a stable user service.
|
||||
./echoion-1.2.3-linux-x86_64.run \
|
||||
--mode portable --prefix "$HOME/echoion-portable" \
|
||||
--data-layout self-contained --register-service user --non-interactive
|
||||
```
|
||||
|
||||
Portable service registration rejects temporary, world-writable, or
|
||||
service-inaccessible prefixes, including group/world-writable ancestors. Run
|
||||
user-service registration as the intended non-root user; root user services are
|
||||
rejected. Use `--register-service system` with root when a portable tree must
|
||||
run as a system service. Its complete runtime path must be root-owned and not
|
||||
writable by the service account. Registration alone performs a daemon reload
|
||||
and leaves the unit disabled and stopped; add `--start` to enable and start it.
|
||||
|
||||
Every installation uses immutable `versions/<version>/` payloads and an atomic
|
||||
`current` symlink. Configuration is created once and is not overwritten by an
|
||||
upgrade. The default `self-contained` layout keeps everything needed by the bot
|
||||
under one prefix:
|
||||
|
||||
| Path | Contents |
|
||||
|---|---|
|
||||
| `<prefix>/versions/<version>` | immutable executable, Core, shared libraries, web assets, service templates, and manifest |
|
||||
| `<prefix>/current` | atomic link to the selected immutable version |
|
||||
| `<prefix>/libexec/updater/<installer-version>` | installer-managed helper plus its private dynamic library closure; never selected through `current` |
|
||||
| `<prefix>/config` | configuration |
|
||||
| `<prefix>/state` | identity, database, update journals, and durable state |
|
||||
| `<prefix>/cache`, `<prefix>/logs`, `<prefix>/incoming` | cache, logs, and operator-supplied local update input |
|
||||
|
||||
Select `--data-layout standard` to use conventional external mutable paths:
|
||||
`$XDG_CONFIG_HOME/echoion`, `$XDG_STATE_HOME/echoion`, and
|
||||
`$XDG_CACHE_HOME/echoion` for a user service, or `/etc/echoion`,
|
||||
`/var/lib/echoion`, `/var/cache/echoion`, and `/var/log/echoion` for a system
|
||||
service. `--config-dir` and `--state-dir` remain available as explicit
|
||||
overrides.
|
||||
|
||||
A self-contained portable install also creates `<prefix>/echoion`; use that
|
||||
launcher instead of invoking `current/bin/echoiond` directly. It derives the
|
||||
config and state paths from its own location, so a stopped, service-free tree
|
||||
can be moved as one folder and run from the new path. If a portable service was
|
||||
registered, uninstall or re-register its unit before moving the tree because
|
||||
systemd stores an absolute executable path.
|
||||
|
||||
The installer does not execute `echoiond`, `Echoion.ts`, plugins, or the updater.
|
||||
Its standalone manifest validator verifies every immutable file, symlink, mode,
|
||||
and SHA-256 before switching `current`. Service registration renders both the
|
||||
bot unit and a hardened local updater timer, but leaves them disabled and
|
||||
stopped unless `--start` is supplied.
|
||||
|
||||
### Updates
|
||||
|
||||
The daemon checks signed feeds and applies independent policies for the runtime
|
||||
bundle, Core, and managed plugins. Each component can select its own source URL
|
||||
and channel through the `updates` object in `config.json`; bearer tokens are
|
||||
read only from named environment variables. HTTPS is required for remote custom
|
||||
sources. A `file://` source is accepted only below the installation's managed
|
||||
`incoming` directory.
|
||||
|
||||
The privileged updater helper never downloads content and never launches the
|
||||
bot. For a system service, the timer executes a fixed root-owned helper bundle
|
||||
below `<prefix>/libexec/updater/`; both its executable and dynamic libraries are
|
||||
independent of the candidate-controlled `current` link. The helper consumes fixed-schema local
|
||||
requests, validates a staged runtime into a new immutable version, atomically
|
||||
changes `current`, and leaves a durable health journal. The new daemon must run
|
||||
successfully for 30 seconds before its commit request makes the version healthy.
|
||||
Helper passes inside the durable grace period leave the candidate pending, and
|
||||
a matching commit request is processed before rollback. After the deadline, an
|
||||
unconfirmed candidate is restored to the previous version and recorded as
|
||||
failed. `retainHealthyVersions` keeps the active version plus the configured
|
||||
number of previously committed healthy versions; interrupted or failed
|
||||
candidates do not consume that rollback allowance.
|
||||
|
||||
To remove an install, run `<prefix>/uninstall.sh`. Configuration and state are
|
||||
preserved by default. Add `--purge` to remove directories that this installer
|
||||
created and marked as dedicated Echoion data. Pre-existing override directories
|
||||
are preserved and must be removed manually.
|
||||
|
||||
To preserve the permissions and UID of an existing TeamSpeak client identity,
|
||||
export it from TeamSpeak's Identity Manager and import it before first start:
|
||||
|
||||
```bash
|
||||
<prefix>/current/bin/echoiond --import-identity identity.ini \
|
||||
--state-dir <state-directory>
|
||||
# Choose a non-default destination or replace an existing identity explicitly:
|
||||
<prefix>/current/bin/echoiond --import-identity identity.ini \
|
||||
--identity-path /path/to/identity.txt --force
|
||||
```
|
||||
|
||||
The identity file contains a private key. Keep both the TeamSpeak export and
|
||||
the converted file private.
|
||||
|
||||
## Commands
|
||||
|
||||
@@ -111,31 +238,66 @@ All commands use the configured prefix (default: `!`)
|
||||
|
||||
## Architecture
|
||||
|
||||
The bot consists of three main components:
|
||||
The supported runtime consists of four main components:
|
||||
|
||||
1. **EchoionApi** - Shared interfaces and types
|
||||
2. **EchoionCore** - Core music playback logic (hot-reloadable)
|
||||
3. **EchoionPlugin** - TeamSpeak plugin wrapper
|
||||
3. **VoidTeamspeak** - Reusable native TeamSpeak SDK-compatible client library
|
||||
4. **EchoionStandalone** - Daemon host and Core API adapter
|
||||
|
||||
The legacy TeamSpeak client plugin was removed. TeamSpeak protocol behavior is
|
||||
implemented once in `VoidTeamspeak`; `EchoionStandalone` is Echoion's only host
|
||||
adapter.
|
||||
|
||||
Watch Together is the independent **VoidWatch** product in the sibling
|
||||
`EchoionWatch` repository. Echoion has no Watch runtime, WebSocket session,
|
||||
provider resolver, or extra TeamSpeak identity; it only exposes the configured
|
||||
external link and a temporary `/watch` redirect.
|
||||
|
||||
### Audio Flow
|
||||
|
||||
```
|
||||
query → SourceRouter (innertube → Yandex → direct URL → yt-dlp) → PlaybackEngine
|
||||
(dual AudioDecoder, gapless handoff) → Core → PluginInterface → TeamSpeak
|
||||
(dual AudioDecoder, gapless handoff) → Core → Standalone interface
|
||||
→ VoidTeamspeak → TeamSpeak
|
||||
```
|
||||
|
||||
Audio is decoded using FFmpeg at 192kHz stereo and emitted in 20ms chunks to
|
||||
TeamSpeak's custom audio device by a single real-time engine thread. See
|
||||
`docs/09-audio-pipeline.md` for details.
|
||||
TeamSpeak's Opus voice protocol through the bot's single playback engine and
|
||||
visible TeamSpeak identity.
|
||||
|
||||
## Development
|
||||
|
||||
### Hot Reload
|
||||
### Development hot reload
|
||||
|
||||
The core library can be hot-reloaded without disconnecting from the server:
|
||||
|
||||
1. Build the new core: `cmake --build . --target EchoionCore`
|
||||
2. Use the "Reload Core" menu item or send plugin command `reload`
|
||||
2. Replace `Echoion.ts`; the daemon's host watcher reloads it automatically.
|
||||
|
||||
This developer-only watcher is enabled for writable build trees. Installed
|
||||
release payloads are immutable and use installer upgrades plus service restart
|
||||
instead of writing temporary libraries beside Core.
|
||||
|
||||
Protocol or host changes can use the daemon's opt-in transactional re-exec API.
|
||||
The process must be started with `ECHOION_RELEASE_MANIFEST` set to the absolute
|
||||
manifest path before a release is staged:
|
||||
|
||||
```bash
|
||||
export ECHOION_RELEASE_MANIFEST="$HOME/echoion/releases/pending-release.json"
|
||||
# Start the development daemon with its normal --config/--state-dir arguments.
|
||||
scripts/stage-release.sh "$HOME/echoion/releases" 1.2.3 \
|
||||
build-release/runtime-stage
|
||||
```
|
||||
|
||||
The staging command rejects unsafe version names and existing release
|
||||
directories, verifies the bundle's v2 whole-payload manifest, copies the full
|
||||
runtime tree, and then renames `pending-release.json` into place. The running
|
||||
daemon validates every declared file in a child process, checkpoints Core
|
||||
state, disconnects cleanly, and re-execs the staged binary. The installer does
|
||||
not enable this development watcher; installed upgrades are performed by the
|
||||
signed updater. Running a new `.run` artifact against the same prefix remains
|
||||
the offline/manual upgrade path.
|
||||
|
||||
### Adding Commands
|
||||
|
||||
@@ -158,41 +320,68 @@ public:
|
||||
};
|
||||
```
|
||||
|
||||
For independently reloadable native extensions, use the trusted plugin ABI
|
||||
instead of compiling commands into Core. See [Native plugins](docs/plugins.md).
|
||||
|
||||
## Packaging and Distribution
|
||||
|
||||
### Using CPack
|
||||
The supported Linux distribution path is `scripts/release.sh`. Each release
|
||||
contains:
|
||||
|
||||
The project includes CPack configuration for creating installers:
|
||||
- `echoion-<version>-linux-x86_64.tar.zst` with one top-level directory;
|
||||
- `echoion-<version>-linux-x86_64.run`, which accepts the installer flags above;
|
||||
- the external v2 manifest and ELF dependency report;
|
||||
- `SHA256SUMS` for all published artifacts.
|
||||
|
||||
Pass `--update-url` to emit a matching unsigned runtime feed payload, with
|
||||
optional `--update-channel`, `--update-feed-id`, and `--update-sequence`
|
||||
overrides:
|
||||
|
||||
```bash
|
||||
cd build
|
||||
|
||||
# Create tarball
|
||||
cpack -G TGZ
|
||||
|
||||
# Create DEB package (Debian/Ubuntu)
|
||||
cpack -G DEB
|
||||
|
||||
# Create RPM package (Fedora/RHEL)
|
||||
cpack -G RPM
|
||||
|
||||
# Create ZIP (Windows)
|
||||
cpack -G ZIP
|
||||
|
||||
# Create NSIS installer (Windows)
|
||||
cpack -G NSIS
|
||||
scripts/release.sh --version 1.2.3 \
|
||||
--update-url https://updates.example.org/echoion-1.2.3-linux-x86_64.tar.zst \
|
||||
--update-channel stable --update-sequence 123
|
||||
```
|
||||
|
||||
### Static Linking
|
||||
|
||||
For a standalone distribution without external dependencies:
|
||||
Production feeds should be wrapped in an Ed25519 envelope. The generator signs
|
||||
the exact payload bytes and never places the private key in the release. It
|
||||
generates runtime feeds by default; use `--component core` for a Core shared
|
||||
library or `--component plugin --artifact-id ID` for a managed plugin. Core and
|
||||
plugin feeds do not require a runtime release manifest:
|
||||
|
||||
```bash
|
||||
cmake .. -DECHOION_STATIC_LINK=ON
|
||||
cmake --build .
|
||||
scripts/generate-update-feed.py \
|
||||
--artifact dist/echoion-1.2.3-linux-x86_64.tar.zst \
|
||||
--manifest dist/echoion-1.2.3-linux-x86_64.manifest.json \
|
||||
--version 1.2.3 \
|
||||
--url https://updates.example.org/echoion-1.2.3-linux-x86_64.tar.zst \
|
||||
--sequence 123 \
|
||||
--output-payload dist/echoion-1.2.3.update-payload.json \
|
||||
--output-envelope dist/echoion-1.2.3.update.json \
|
||||
--key-id production-2026 --private-key /secure/echoion-update.pem
|
||||
```
|
||||
|
||||
Note: Some dependencies (Qt6, FFmpeg) may still require bundling. See `packaging/README.md` for detailed instructions.
|
||||
For example, a plugin feed can be produced independently:
|
||||
|
||||
```bash
|
||||
scripts/generate-update-feed.py \
|
||||
--component plugin --artifact-id lyrics \
|
||||
--artifact dist/lyrics-2.0.0.so --version 2.0.0 \
|
||||
--url https://updates.example.org/plugins/lyrics-2.0.0.so \
|
||||
--output-payload dist/lyrics-2.0.0.update-payload.json
|
||||
```
|
||||
|
||||
The archive and installer contain the same relocatable dynamic payload. They do
|
||||
not depend on DEB/RPM metadata or static linking, so one build can be installed
|
||||
on the supported Ubuntu, Debian, and Arch targets.
|
||||
|
||||
When unpacking the `.tar.zst` form directly, preserve the release modes even
|
||||
under a restrictive shell umask:
|
||||
|
||||
```bash
|
||||
tar --same-permissions --no-same-owner --zstd \
|
||||
-xf echoion-1.2.3-linux-x86_64.tar.zst
|
||||
```
|
||||
|
||||
### CMake Package Support
|
||||
|
||||
|
||||
+7
-7
@@ -1,6 +1,6 @@
|
||||
# VoidLibrary — work needed to fully migrate Echoion (+ upgrade ideas)
|
||||
|
||||
## STATUS (round 2 complete)
|
||||
## STATUS (migration complete)
|
||||
|
||||
Almost everything below has now landed. Echoion uses Void for **Json, Logging,
|
||||
Process, Retry, Configuration, EventBus (async), ThreadPool, Cache, Resilience,
|
||||
@@ -20,11 +20,11 @@ implemented in VoidLibrary as universal primitives and consumed by Echoion:
|
||||
- **A6 done** — `Void::BufferPool::BufferPool<T>` added; AudioBufferPool wraps it;
|
||||
bespoke MemoryPool deleted. New `Void::System` metrics (process_memory/cpu) added.
|
||||
|
||||
**Remaining (one item):** the plugin loader is still Echoion's dylib-based
|
||||
`CoreLoader`, not `Void::Plugin`. This is **not** a Void gap — it's an
|
||||
Echoion-side rewrite gated on a live hot-reload test (impedance mismatch: Core
|
||||
implements `ICoreInterface`, `Void::Plugin::Loader` hands back `IPlugin*`). See
|
||||
section B.
|
||||
**Remaining:** none from the migration list. `CoreLoader` now uses
|
||||
`Void::Plugin::PluginManager` with pinned handles, host-side interface
|
||||
validation, explicit activation readiness, state checkpoint/restore, and
|
||||
rollback to a reactivated previous Core. Successful and rejected replacement
|
||||
paths are covered by an end-to-end reload test.
|
||||
|
||||
The historical analysis below is retained for reference.
|
||||
|
||||
@@ -111,7 +111,7 @@ high-water stats), or confirm `Pool<std::vector<int16_t>>` is an acceptable fit.
|
||||
|
||||
## B. Already replaceable — no VoidLibrary change needed (Echoion-side work only)
|
||||
|
||||
- **Plugin loader → `Void::Plugin`.** `Loader::reload()` + `Manager` (FileWatcher,
|
||||
- **Plugin loader → `Void::Plugin` (done).** `Loader::reload()` + `Manager` (FileWatcher,
|
||||
RCU-pinned handles so "work never stops for a reload") + the v2
|
||||
`serialize_state`/`deserialize_state` C-ABI protocol already cover — and improve
|
||||
on — Echoion's `CoreLoader`/dylib/`FileWatcher`. The "defer reload until the
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
cmake_minimum_required(VERSION 4.0)
|
||||
|
||||
if(NOT CMAKE_HOST_SYSTEM_NAME STREQUAL "Linux")
|
||||
message(FATAL_ERROR "Echoion runtime dependency bundling currently supports Linux only")
|
||||
endif()
|
||||
if(NOT DEFINED BUNDLE_ROOT OR BUNDLE_ROOT STREQUAL "")
|
||||
message(FATAL_ERROR "BUNDLE_ROOT must name the staged runtime tree")
|
||||
endif()
|
||||
if(NOT DEFINED PATCHELF_EXECUTABLE OR PATCHELF_EXECUTABLE STREQUAL "")
|
||||
find_program(PATCHELF_EXECUTABLE NAMES patchelf REQUIRED)
|
||||
endif()
|
||||
if(NOT DEFINED BUNDLE_SEED_FILES OR BUNDLE_SEED_FILES STREQUAL "")
|
||||
message(FATAL_ERROR
|
||||
"BUNDLE_SEED_FILES must contain the exact compiler runtime libraries")
|
||||
endif()
|
||||
|
||||
cmake_path(ABSOLUTE_PATH BUNDLE_ROOT NORMALIZE OUTPUT_VARIABLE _bundle_root)
|
||||
set(_executable "${_bundle_root}/bin/echoiond")
|
||||
set(_updater "${_bundle_root}/bin/echoion-updater")
|
||||
set(_core "${_bundle_root}/lib/Echoion.ts")
|
||||
set(_library_dir "${_bundle_root}/lib")
|
||||
if(NOT DEFINED BUNDLE_RESOLVER_EXECUTABLES OR
|
||||
BUNDLE_RESOLVER_EXECUTABLES STREQUAL "")
|
||||
if(DEFINED BUNDLE_RESOLVER_EXECUTABLE AND
|
||||
NOT BUNDLE_RESOLVER_EXECUTABLE STREQUAL "")
|
||||
set(BUNDLE_RESOLVER_EXECUTABLES "${BUNDLE_RESOLVER_EXECUTABLE}")
|
||||
else()
|
||||
set(BUNDLE_RESOLVER_EXECUTABLES "${_executable}")
|
||||
if(EXISTS "${_updater}")
|
||||
list(APPEND BUNDLE_RESOLVER_EXECUTABLES "${_updater}")
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
if(NOT DEFINED BUNDLE_RESOLVER_LIBRARIES OR
|
||||
BUNDLE_RESOLVER_LIBRARIES STREQUAL "")
|
||||
set(BUNDLE_RESOLVER_LIBRARIES "${_core}")
|
||||
endif()
|
||||
|
||||
if(NOT EXISTS "${_executable}")
|
||||
message(FATAL_ERROR "Missing staged daemon: ${_executable}")
|
||||
endif()
|
||||
if(NOT EXISTS "${_core}")
|
||||
message(FATAL_ERROR "Missing staged Core library: ${_core}")
|
||||
endif()
|
||||
foreach(_resolver_executable IN LISTS BUNDLE_RESOLVER_EXECUTABLES)
|
||||
if(NOT IS_ABSOLUTE "${_resolver_executable}" OR
|
||||
NOT EXISTS "${_resolver_executable}" OR
|
||||
IS_DIRECTORY "${_resolver_executable}")
|
||||
message(FATAL_ERROR
|
||||
"Missing absolute dependency resolver executable: ${_resolver_executable}")
|
||||
endif()
|
||||
endforeach()
|
||||
foreach(_resolver_library IN LISTS BUNDLE_RESOLVER_LIBRARIES)
|
||||
if(NOT IS_ABSOLUTE "${_resolver_library}" OR
|
||||
NOT EXISTS "${_resolver_library}" OR
|
||||
IS_DIRECTORY "${_resolver_library}")
|
||||
message(FATAL_ERROR
|
||||
"Missing absolute dependency resolver library: ${_resolver_library}")
|
||||
endif()
|
||||
endforeach()
|
||||
file(MAKE_DIRECTORY "${_library_dir}")
|
||||
|
||||
# Linux dependency resolution checks RUNPATH and then ldconfig before consulting
|
||||
# DIRECTORIES. Seed the exact compiler runtimes into $ORIGIN first so an older
|
||||
# host libstdc++/libgcc with the same SONAME cannot be selected accidentally.
|
||||
foreach(_seed IN LISTS BUNDLE_SEED_FILES)
|
||||
if(NOT IS_ABSOLUTE "${_seed}" OR NOT EXISTS "${_seed}" OR IS_DIRECTORY "${_seed}")
|
||||
message(FATAL_ERROR "Missing absolute runtime seed: ${_seed}")
|
||||
endif()
|
||||
file(COPY "${_seed}"
|
||||
DESTINATION "${_library_dir}"
|
||||
FOLLOW_SYMLINK_CHAIN)
|
||||
endforeach()
|
||||
|
||||
# glibc and the ELF loader define the portable ABI floor and must be supplied
|
||||
# by the target host. Everything else, including libgcc_s and libstdc++, is
|
||||
# resolved recursively and copied into lib/.
|
||||
set(_system_dependency_regexes
|
||||
"^linux-vdso\\.so\\.1$"
|
||||
"^ld-linux-x86-64\\.so\\.2$"
|
||||
"^libc\\.so\\.6$"
|
||||
"^libm\\.so\\.6$"
|
||||
"^libmvec\\.so\\.1$"
|
||||
"^libdl\\.so\\.2$"
|
||||
"^libpthread\\.so\\.0$"
|
||||
"^librt\\.so\\.1$"
|
||||
"^libresolv\\.so\\.2$"
|
||||
"^libutil\\.so\\.1$"
|
||||
"^libanl\\.so\\.1$"
|
||||
"^libBrokenLocale\\.so\\.1$"
|
||||
"^libthread_db\\.so\\.1$")
|
||||
|
||||
# These runtimes are explicit, compiler-derived seed files. Never let the
|
||||
# resolver select a different host copy with the same SONAME through ldconfig.
|
||||
set(_seed_dependency_regexes
|
||||
"^libstdc\\+\\+\\.so.*$"
|
||||
"^libgcc_s\\.so.*$")
|
||||
|
||||
file(GET_RUNTIME_DEPENDENCIES
|
||||
RESOLVED_DEPENDENCIES_VAR _resolved_dependencies
|
||||
UNRESOLVED_DEPENDENCIES_VAR _unresolved_dependencies
|
||||
CONFLICTING_DEPENDENCIES_PREFIX _conflicts
|
||||
EXECUTABLES ${BUNDLE_RESOLVER_EXECUTABLES}
|
||||
LIBRARIES ${BUNDLE_RESOLVER_LIBRARIES}
|
||||
DIRECTORIES ${BUNDLE_SEARCH_DIRECTORIES}
|
||||
PRE_EXCLUDE_REGEXES
|
||||
${_system_dependency_regexes}
|
||||
${_seed_dependency_regexes})
|
||||
|
||||
if(_unresolved_dependencies)
|
||||
list(SORT _unresolved_dependencies)
|
||||
list(JOIN _unresolved_dependencies ", " _unresolved_text)
|
||||
message(FATAL_ERROR "Unresolved runtime dependencies: ${_unresolved_text}")
|
||||
endif()
|
||||
if(_conflicts_FILENAMES)
|
||||
list(SORT _conflicts_FILENAMES)
|
||||
list(JOIN _conflicts_FILENAMES ", " _conflict_text)
|
||||
message(FATAL_ERROR "Conflicting runtime dependency names: ${_conflict_text}")
|
||||
endif()
|
||||
|
||||
list(REMOVE_DUPLICATES _resolved_dependencies)
|
||||
list(SORT _resolved_dependencies)
|
||||
foreach(_dependency IN LISTS _resolved_dependencies)
|
||||
if(NOT EXISTS "${_dependency}")
|
||||
message(FATAL_ERROR "Resolved dependency disappeared: ${_dependency}")
|
||||
endif()
|
||||
cmake_path(GET _dependency PARENT_PATH _dependency_directory)
|
||||
cmake_path(NORMAL_PATH _dependency_directory)
|
||||
if(_dependency_directory STREQUAL _library_dir)
|
||||
continue()
|
||||
endif()
|
||||
cmake_path(GET _dependency FILENAME _dependency_name)
|
||||
if(EXISTS "${_library_dir}/${_dependency_name}" OR
|
||||
IS_SYMLINK "${_library_dir}/${_dependency_name}")
|
||||
continue()
|
||||
endif()
|
||||
file(COPY "${_dependency}"
|
||||
DESTINATION "${_library_dir}"
|
||||
FOLLOW_SYMLINK_CHAIN)
|
||||
endforeach()
|
||||
|
||||
function(_echoion_is_elf path result_var)
|
||||
if(IS_SYMLINK "${path}" OR NOT EXISTS "${path}")
|
||||
set(${result_var} FALSE PARENT_SCOPE)
|
||||
return()
|
||||
endif()
|
||||
file(READ "${path}" _magic OFFSET 0 LIMIT 4 HEX)
|
||||
string(TOLOWER "${_magic}" _magic)
|
||||
if(_magic STREQUAL "7f454c46")
|
||||
set(${result_var} TRUE PARENT_SCOPE)
|
||||
else()
|
||||
set(${result_var} FALSE PARENT_SCOPE)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
# Ensure a SONAME link exists even when CMake resolved a dependency directly to
|
||||
# its real versioned file instead of the symlink used by DT_NEEDED.
|
||||
file(GLOB _library_entries LIST_DIRECTORIES FALSE "${_library_dir}/*")
|
||||
list(SORT _library_entries)
|
||||
foreach(_entry IN LISTS _library_entries)
|
||||
_echoion_is_elf("${_entry}" _is_elf)
|
||||
if(NOT _is_elf)
|
||||
continue()
|
||||
endif()
|
||||
|
||||
execute_process(
|
||||
COMMAND "${PATCHELF_EXECUTABLE}" --print-soname "${_entry}"
|
||||
RESULT_VARIABLE _soname_result
|
||||
OUTPUT_VARIABLE _soname
|
||||
ERROR_VARIABLE _soname_error
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
if(NOT _soname_result EQUAL 0)
|
||||
message(FATAL_ERROR
|
||||
"Cannot read SONAME from ${_entry}: ${_soname_error}")
|
||||
endif()
|
||||
if(NOT _soname STREQUAL "")
|
||||
if(NOT _soname MATCHES "^[A-Za-z0-9][A-Za-z0-9._+~-]*$")
|
||||
message(FATAL_ERROR "Unsafe SONAME '${_soname}' in ${_entry}")
|
||||
endif()
|
||||
get_filename_component(_entry_name "${_entry}" NAME)
|
||||
set(_soname_path "${_library_dir}/${_soname}")
|
||||
if(NOT _entry_name STREQUAL _soname
|
||||
AND NOT EXISTS "${_soname_path}"
|
||||
AND NOT IS_SYMLINK "${_soname_path}")
|
||||
file(CREATE_LINK "${_entry_name}" "${_soname_path}" SYMBOLIC)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
execute_process(
|
||||
COMMAND "${PATCHELF_EXECUTABLE}" --set-rpath "$ORIGIN" "${_entry}"
|
||||
RESULT_VARIABLE _patch_result
|
||||
ERROR_VARIABLE _patch_error)
|
||||
if(NOT _patch_result EQUAL 0)
|
||||
message(FATAL_ERROR "Cannot set RUNPATH on ${_entry}: ${_patch_error}")
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
file(GLOB _bundle_executable_entries LIST_DIRECTORIES FALSE
|
||||
"${_bundle_root}/bin/*")
|
||||
list(SORT _bundle_executable_entries)
|
||||
foreach(_entry IN LISTS _bundle_executable_entries)
|
||||
_echoion_is_elf("${_entry}" _is_elf)
|
||||
if(NOT _is_elf)
|
||||
continue()
|
||||
endif()
|
||||
execute_process(
|
||||
COMMAND "${PATCHELF_EXECUTABLE}" --set-rpath "$ORIGIN/../lib" "${_entry}"
|
||||
RESULT_VARIABLE _patch_executable_result
|
||||
ERROR_VARIABLE _patch_executable_error)
|
||||
if(NOT _patch_executable_result EQUAL 0)
|
||||
message(FATAL_ERROR
|
||||
"Cannot set RUNPATH on ${_entry}: ${_patch_executable_error}")
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
list(LENGTH _resolved_dependencies _dependency_count)
|
||||
message(STATUS "Bundled ${_dependency_count} resolved runtime dependencies")
|
||||
@@ -0,0 +1,8 @@
|
||||
# Immutable dependency revisions used by clean and release builds. Local
|
||||
# development may still override either package with CPM_<name>_SOURCE.
|
||||
set(ECHOION_VOID_REVISION
|
||||
"053ee5b296d1f41b0653b4301bbea1e857be2279"
|
||||
CACHE STRING "VoidLibrary commit used by Echoion")
|
||||
set(ECHOION_VOID_TEAMSPEAK_REVISION
|
||||
"cb43116da643fb6584f91f108f384cc5e3cb658c"
|
||||
CACHE STRING "VoidTeamspeak commit used by Echoion")
|
||||
+69
-7
@@ -33,9 +33,22 @@
|
||||
"ytDlpMaxConcurrent": 4,
|
||||
"ytDlpAsyncEnabled": true,
|
||||
|
||||
"_urlShortening": "Shorten YouTube links using faumaray.ru",
|
||||
"enableUrlShortening": true
|
||||
},
|
||||
"_urlShortening": "Legacy compatibility flag. Used only when the top-level urlShortening section is absent.",
|
||||
"enableUrlShortening": true
|
||||
},
|
||||
|
||||
"urlShortening": {
|
||||
"_section": "Provider-neutral URL shortening. The internal provider requires web.publicUrl and is disabled safely when it is empty; external providers do not require web.publicUrl. Failures leave shortenedUrl empty and never change originalUrl.",
|
||||
"enabled": false,
|
||||
"provider": "url-shortener-internal",
|
||||
"sources": ["youtube"],
|
||||
"timeout": "3s"
|
||||
},
|
||||
|
||||
"plugins": {
|
||||
"_section": "Per-plugin JSON configuration files. An empty path uses plugins.d beside this file.",
|
||||
"configDirectory": ""
|
||||
},
|
||||
|
||||
"network": {
|
||||
"_section": "Network & Proxy Settings",
|
||||
@@ -49,7 +62,7 @@
|
||||
},
|
||||
|
||||
"web": {
|
||||
"_section": "Browser web interface (EchoionWeb): serves the UI, the sync-watch WebSocket (/ws), and bridges browser RPC through /rpc — only this port needs to be reachable; the RPC server can stay on 127.0.0.1.",
|
||||
"_section": "Browser web interface (EchoionWeb): serves the public dashboard and bridges authenticated browser RPC through /rpc — only this port needs to be reachable; the RPC server can stay on 127.0.0.1.",
|
||||
"enabled": false,
|
||||
"port": 8080,
|
||||
"_bindAddress": "Use 0.0.0.0 to allow access from other machines.",
|
||||
@@ -57,11 +70,15 @@
|
||||
"webRoot": "./web",
|
||||
"_rpcUrl": "RPC WebSocket URL for the browser. Empty = same-origin /rpc bridge (recommended); an absolute ws:// URL overrides.",
|
||||
"rpcUrl": "",
|
||||
"_publicUrl": "Public address users reach the web interface at, e.g. https://bot.example.com. When set (and the web interface is enabled), !help links to it.",
|
||||
"_publicUrl": "Public address users reach the web interface at, e.g. https://bot.example.com. Required when url-shortener-internal is enabled; also used by !help when the web interface is enabled.",
|
||||
"publicUrl": "",
|
||||
"_watchUrl": "External VoidWatch deployment linked from Echoion. The retired /watch path redirects here when set.",
|
||||
"watchUrl": "",
|
||||
"_nowPlayingVideo": "Allow the Now Playing view to show the current song's video (muted, synced). Users can still disable it locally; set false to turn it off for everyone.",
|
||||
"nowPlayingVideo": true
|
||||
},
|
||||
"nowPlayingVideo": true,
|
||||
"_trustedProxyCidrs": "Trust X-Forwarded-For only from these immediate proxy CIDRs. Empty ignores it.",
|
||||
"trustedProxyCidrs": []
|
||||
},
|
||||
|
||||
"sources": {
|
||||
"_section": "Music source resolution chain (native paths first, proxied yt-dlp last)",
|
||||
@@ -135,6 +152,51 @@
|
||||
"voteSkipThreshold": 0
|
||||
},
|
||||
|
||||
"updates": {
|
||||
"_section": "Signed component updates for the runtime bundle, Core, and already-installed managed plugins",
|
||||
"enabled": true,
|
||||
"checkInterval": "6h",
|
||||
"jitter": "30m",
|
||||
"maintenanceWindowUtc": {
|
||||
"start": "03:00",
|
||||
"duration": "2h"
|
||||
},
|
||||
"maxRuntimeDeferral": "24h",
|
||||
"_retainHealthyVersions": "Previous committed healthy versions kept in addition to the active version",
|
||||
"retainHealthyVersions": 2,
|
||||
"sources": {
|
||||
"official": {
|
||||
"_url": "Empty uses the URL embedded by the release build. Custom sources must use HTTPS (or a local file source under incoming/).",
|
||||
"url": "",
|
||||
"_publicKeys": "Ed25519 trust roots. Empty inherits the official keys embedded by the release build.",
|
||||
"publicKeys": [],
|
||||
"allowUnsigned": false,
|
||||
"_bearerTokenEnv": "Environment variable name only; the token value is never stored in this file or returned to the web UI.",
|
||||
"bearerTokenEnv": ""
|
||||
}
|
||||
},
|
||||
"runtime": {
|
||||
"enabled": true,
|
||||
"source": "official",
|
||||
"channel": "stable",
|
||||
"autoApply": true
|
||||
},
|
||||
"core": {
|
||||
"enabled": true,
|
||||
"source": "official",
|
||||
"channel": "stable",
|
||||
"autoApply": true
|
||||
},
|
||||
"plugins": {
|
||||
"enabled": true,
|
||||
"source": "official",
|
||||
"channel": "stable",
|
||||
"autoApply": true,
|
||||
"managedOnly": true,
|
||||
"overrides": {}
|
||||
}
|
||||
},
|
||||
|
||||
"advanced": {
|
||||
"_section": "Advanced Settings (Modify with caution)",
|
||||
"_cache": "Local audio track cache (files reused across plays and restarts)",
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
FROM ubuntu:22.04@sha256:0d779ea97881505f5ef0039336ee85edba27519bdba968c284c86ee066a973c8 AS gcc-builder
|
||||
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
ARG GCC_VERSION=16.1.0
|
||||
ARG GCC_SHA512=b3454958891ab47e1e5b6cb9396c0ad3b04f32fe2a7bf1153a143f21013fdb6b295ca94c98964698a688e4c1d7555ffd8ffbc20187507cce6b1c32cbcc09897a
|
||||
ARG GCC_BUILD_JOBS=2
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
binutils \
|
||||
bison \
|
||||
build-essential \
|
||||
ca-certificates \
|
||||
curl \
|
||||
file \
|
||||
flex \
|
||||
libgmp-dev \
|
||||
libisl-dev \
|
||||
libmpc-dev \
|
||||
libmpfr-dev \
|
||||
libzstd-dev \
|
||||
texinfo \
|
||||
xz-utils \
|
||||
zlib1g-dev \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /tmp/gcc
|
||||
RUN curl -fsSLO \
|
||||
"https://ftp.gnu.org/gnu/gcc/gcc-${GCC_VERSION}/gcc-${GCC_VERSION}.tar.xz" \
|
||||
&& echo "${GCC_SHA512} gcc-${GCC_VERSION}.tar.xz" | sha512sum -c - \
|
||||
&& tar -xf "gcc-${GCC_VERSION}.tar.xz" \
|
||||
&& mkdir build \
|
||||
&& cd build \
|
||||
&& "../gcc-${GCC_VERSION}/configure" \
|
||||
--prefix="/opt/gcc-${GCC_VERSION}" \
|
||||
--disable-bootstrap \
|
||||
--disable-multilib \
|
||||
--enable-default-pie \
|
||||
--enable-default-ssp \
|
||||
--enable-languages=c,c++ \
|
||||
--with-system-zlib \
|
||||
&& make -j"${GCC_BUILD_JOBS}"
|
||||
|
||||
RUN cd build \
|
||||
&& make install-strip \
|
||||
&& install -d -m 0755 "/opt/gcc-${GCC_VERSION}/share/licenses/gcc" \
|
||||
&& install -m 0644 \
|
||||
"../gcc-${GCC_VERSION}/COPYING3" \
|
||||
"../gcc-${GCC_VERSION}/COPYING.RUNTIME" \
|
||||
"/opt/gcc-${GCC_VERSION}/share/licenses/gcc/"
|
||||
|
||||
|
||||
FROM ubuntu:22.04@sha256:0d779ea97881505f5ef0039336ee85edba27519bdba968c284c86ee066a973c8 AS release-builder
|
||||
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
ARG GCC_VERSION=16.1.0
|
||||
ARG CMAKE_VERSION=4.0.3
|
||||
ARG CMAKE_SHA256=585ae9e013107bc8e7c7c9ce872cbdcbdff569e675b07ef57aacfb88c886faac
|
||||
ARG NODE_VERSION=22.17.0
|
||||
ARG NODE_SHA256=325c0f1261e0c61bcae369a1274028e9cfb7ab7949c05512c5b1e630f7e80e12
|
||||
ARG FFMPEG_VERSION=8.0.3
|
||||
ARG FFMPEG_SHA256=6136812ea6d4e68bdba27e33c2a94382711cdf4f8602ffef056ff792bd6f9818
|
||||
ARG FFMPEG_BUILD_JOBS=2
|
||||
ARG BOOST_VERSION=1.87.0
|
||||
ARG BOOST_VERSION_UNDERSCORE=1_87_0
|
||||
ARG BOOST_SHA256=af57be25cb4c4f4b413ed692fe378affb4352ea50fbe294a11ef548f4d527d89
|
||||
ARG BOOST_BUILD_JOBS=2
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
binutils \
|
||||
bzip2 \
|
||||
ca-certificates \
|
||||
curl \
|
||||
file \
|
||||
git \
|
||||
gzip \
|
||||
jq \
|
||||
libarchive-dev \
|
||||
libcurl4-openssl-dev \
|
||||
libgmp10 \
|
||||
libisl23 \
|
||||
libmpc3 \
|
||||
libmpfr6 \
|
||||
libopus-dev \
|
||||
libsodium-dev \
|
||||
libsqlite3-dev \
|
||||
libssl-dev \
|
||||
libtbb-dev \
|
||||
libzstd1 \
|
||||
make \
|
||||
nasm \
|
||||
ninja-build \
|
||||
openssl \
|
||||
patchelf \
|
||||
pkg-config \
|
||||
python3 \
|
||||
tar \
|
||||
xz-utils \
|
||||
zstd \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=gcc-builder "/opt/gcc-${GCC_VERSION}" "/opt/gcc-${GCC_VERSION}"
|
||||
|
||||
RUN curl --retry 5 --retry-delay 2 --retry-all-errors -fsSLO \
|
||||
"https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}/cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" \
|
||||
&& echo "${CMAKE_SHA256} cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" | sha256sum -c - \
|
||||
&& tar -xzf "cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" \
|
||||
-C /usr/local --strip-components=1 \
|
||||
&& rm "cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" \
|
||||
&& curl --retry 5 --retry-delay 2 --retry-all-errors -fsSLO \
|
||||
"https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-x64.tar.xz" \
|
||||
&& echo "${NODE_SHA256} node-v${NODE_VERSION}-linux-x64.tar.xz" | sha256sum -c - \
|
||||
&& tar -xJf "node-v${NODE_VERSION}-linux-x64.tar.xz" \
|
||||
-C /usr/local --strip-components=1 \
|
||||
&& rm "node-v${NODE_VERSION}-linux-x64.tar.xz"
|
||||
|
||||
ENV GCC_ROOT="/opt/gcc-${GCC_VERSION}"
|
||||
ENV PATH="${GCC_ROOT}/bin:${PATH}" \
|
||||
LD_LIBRARY_PATH="${GCC_ROOT}/lib64:${GCC_ROOT}/lib" \
|
||||
CC="${GCC_ROOT}/bin/gcc" \
|
||||
CXX="${GCC_ROOT}/bin/g++"
|
||||
|
||||
RUN test "$(uname -m)" = x86_64 \
|
||||
&& gcc --version | grep -F "gcc (GCC) 16.1.0"
|
||||
|
||||
RUN curl --retry 5 --retry-delay 2 --retry-all-errors -fsSLO \
|
||||
"https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz" \
|
||||
&& echo "${FFMPEG_SHA256} ffmpeg-${FFMPEG_VERSION}.tar.xz" | sha256sum -c - \
|
||||
&& tar -xJf "ffmpeg-${FFMPEG_VERSION}.tar.xz" \
|
||||
&& cd "ffmpeg-${FFMPEG_VERSION}" \
|
||||
&& ./configure \
|
||||
--prefix="/opt/ffmpeg-${FFMPEG_VERSION}" \
|
||||
--cc="${CC}" \
|
||||
--cxx="${CXX}" \
|
||||
--disable-static \
|
||||
--enable-shared \
|
||||
--disable-autodetect \
|
||||
--disable-programs \
|
||||
--disable-doc \
|
||||
--disable-debug \
|
||||
--disable-avdevice \
|
||||
--disable-avfilter \
|
||||
--disable-swscale \
|
||||
--disable-encoders \
|
||||
--disable-muxers \
|
||||
--disable-hwaccels \
|
||||
--enable-openssl \
|
||||
&& make -j"${FFMPEG_BUILD_JOBS}" \
|
||||
&& make install \
|
||||
&& install -D -m 0644 COPYING.LGPLv2.1 \
|
||||
"/opt/ffmpeg-${FFMPEG_VERSION}/share/licenses/ffmpeg/COPYING.LGPLv2.1" \
|
||||
&& cd / \
|
||||
&& rm -rf \
|
||||
"ffmpeg-${FFMPEG_VERSION}" \
|
||||
"ffmpeg-${FFMPEG_VERSION}.tar.xz"
|
||||
|
||||
ENV FFMPEG_ROOT="/opt/ffmpeg-${FFMPEG_VERSION}" \
|
||||
PKG_CONFIG_PATH="/opt/ffmpeg-${FFMPEG_VERSION}/lib/pkgconfig" \
|
||||
LD_LIBRARY_PATH="/opt/ffmpeg-${FFMPEG_VERSION}/lib:${LD_LIBRARY_PATH}"
|
||||
|
||||
RUN test "$(pkg-config --modversion libavcodec)" = 62.11.103 \
|
||||
&& test "$(pkg-config --modversion libavformat)" = 62.3.103 \
|
||||
&& test "$(pkg-config --modversion libavutil)" = 60.8.103 \
|
||||
&& test "$(pkg-config --modversion libswresample)" = 6.1.103
|
||||
|
||||
RUN curl --retry 5 --retry-delay 2 --retry-all-errors -fsSLO \
|
||||
"https://archives.boost.io/release/${BOOST_VERSION}/source/boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2" \
|
||||
&& echo "${BOOST_SHA256} boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2" | sha256sum -c - \
|
||||
&& tar -xjf "boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2" \
|
||||
&& cd "boost_${BOOST_VERSION_UNDERSCORE}" \
|
||||
&& ./bootstrap.sh --prefix="/usr" \
|
||||
&& ./b2 -j"${BOOST_BUILD_JOBS}" \
|
||||
cxxstd=23 \
|
||||
link=shared \
|
||||
runtime-link=shared \
|
||||
threading=multi \
|
||||
variant=release \
|
||||
--with-container \
|
||||
--with-stacktrace \
|
||||
--with-system \
|
||||
--with-thread \
|
||||
--with-url \
|
||||
--layout=system \
|
||||
install \
|
||||
&& install -D -m 0644 \
|
||||
LICENSE_1_0.txt \
|
||||
"/usr/share/licenses/boost/LICENSE_1_0.txt" \
|
||||
&& cd / \
|
||||
&& rm -rf \
|
||||
"boost_${BOOST_VERSION_UNDERSCORE}" \
|
||||
"boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2"
|
||||
|
||||
# Installer regressions exercise root-owned portable service registration and
|
||||
# validate generated units without booting systemd inside the build container.
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends fakeroot systemd \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
ENV BOOST_ROOT="/usr" \
|
||||
CMAKE_PREFIX_PATH="${FFMPEG_ROOT}"
|
||||
|
||||
WORKDIR /workspace
|
||||
-1
Submodule docs deleted from 128e0a8044.
@@ -0,0 +1,89 @@
|
||||
# Linux installer layout
|
||||
|
||||
`install.sh` and `uninstall.sh` are copied into each Linux release payload.
|
||||
The installer renders the bot service plus the updater service/timer for user or
|
||||
system systemd scope. `tests/installer_test.sh` exercises portable installation,
|
||||
service opt-in, rollback, tamper protection, preservation, and purge behavior.
|
||||
System-scoped payloads are normalized to root ownership. Registered-service
|
||||
prefixes require a trusted path not writable by other identities. Purge uses
|
||||
recorded directory identity plus an installer marker before removing custom
|
||||
mutable paths.
|
||||
Install and uninstall also take a nonblocking advisory lock on the prefix
|
||||
directory so concurrent lifecycle operations fail before changing the runtime.
|
||||
Self-contained portable installs add a managed `echoion` launcher and relative
|
||||
install metadata, allowing a service-free tree to be moved and uninstalled as
|
||||
one directory.
|
||||
|
||||
The default installed tree is:
|
||||
|
||||
```text
|
||||
<prefix>/
|
||||
current -> versions/<version>
|
||||
versions/<version>/
|
||||
bin/ echoiond and echoion-updater
|
||||
lib/ Core and dynamic dependency closure
|
||||
service/ service templates
|
||||
share/echoion/ web, config template, licenses, validation tool
|
||||
bootstrap-plugins/ immutable first-party plugin artifacts
|
||||
manifest.json
|
||||
libexec/updater/<installer-version>/
|
||||
bin/echoion-updater stable installer-managed privileged helper
|
||||
lib/ private dynamic dependency closure
|
||||
config/
|
||||
plugins.d/ per-plugin JSON configuration, preserved on upgrade
|
||||
state/
|
||||
plugins/.managed/ versioned managed plugins and current links
|
||||
plugins/data/ plugin-owned persistent data, preserved on upgrade
|
||||
cache/ logs/ incoming/
|
||||
install.json .echoion-install
|
||||
install.sh uninstall.sh
|
||||
echoion portable launcher (portable mode)
|
||||
```
|
||||
|
||||
Payload validation is data-only: the installer runs the bundled Python manifest
|
||||
validator and never executes the daemon, Core, plugins, or updater. The updater
|
||||
also never performs network I/O or starts a service. It consumes bounded typed
|
||||
requests written below `state/updates`, with a root-owned system timer providing
|
||||
the privileged activation boundary. The timer executes only a fixed versioned
|
||||
helper and private library closure in `libexec`, never candidate code or
|
||||
libraries below `current`. Runtime activation remains
|
||||
pending until a daemon health commit. Helper passes inside the durable grace
|
||||
period preserve it and prioritize a matching commit; after the deadline an
|
||||
unconfirmed candidate is rolled back. Retention counts only committed healthy
|
||||
versions in addition to the active release.
|
||||
|
||||
First-party URL shorteners ship as immutable bootstrap artifacts in each
|
||||
release. During installation they are copied into
|
||||
`state/plugins/.managed/<id>/versions/<plugin-version>/` and a missing
|
||||
`current` link is initialized. Upgrades add new immutable plugin versions
|
||||
without replacing an existing `current` selection, per-plugin configuration,
|
||||
or plugin data. The
|
||||
operation is idempotent and participates in installer rollback. The service and
|
||||
portable launcher expose only the active release's bundled shared-library
|
||||
directory through `LD_LIBRARY_PATH`; release builds keep `BUILD_SHARED_LIBS=ON`
|
||||
and `ECHOION_STATIC_LINK=OFF`. Installed configurations use the relocatable
|
||||
`./share/echoion/web` asset path; systemd units and the portable launcher set
|
||||
the active release as their working directory. An upgrade rewrites only the
|
||||
exact legacy installer default `./web`; custom web roots remain untouched and
|
||||
the migration participates in transaction rollback.
|
||||
|
||||
Create publishable artifacts from the repository root:
|
||||
|
||||
```bash
|
||||
scripts/release.sh --version 1.2.3
|
||||
```
|
||||
|
||||
For a coordinated pre-publication build, add `--void-source ../VoidLibrary`
|
||||
and `--void-teamspeak-source ../VoidTeamspeak`. Container builds mount these
|
||||
explicit source overrides read-only; published releases use the pinned remote
|
||||
versions.
|
||||
|
||||
The default command uses the version-pinned release toolchain container and
|
||||
does not start the bot. Installation flags and data layouts are documented in
|
||||
the root README.
|
||||
|
||||
Use `scripts/release.sh --update-url URL` to add an unsigned feed payload to the
|
||||
release checksums. `scripts/generate-update-feed.py` can additionally produce an
|
||||
Ed25519-signed envelope from a key held outside the repository. The generator
|
||||
also accepts `--component core` and `--component plugin --artifact-id ID` for
|
||||
independently published Core and managed-plugin artifacts.
|
||||
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user