Compare commits
113
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b8ba43f0c9 | ||
|
|
e5956e40e9 | ||
|
|
6e774873bf | ||
|
|
b89116c0f4 | ||
|
|
437b508047 | ||
|
|
8b6dcbf442 | ||
|
|
5afa5a9740 | ||
|
|
ad2097963e | ||
|
|
5d66be43d4 | ||
|
|
668c1a8038 | ||
|
|
0447e6bc92 | ||
|
|
2b113479ec | ||
|
|
a4aa58f7be | ||
|
|
767a9dad46 | ||
|
|
ce0e6e1f62 | ||
|
|
03f4a92161 | ||
|
|
59fec5b19f | ||
|
|
ac4cee0a8f | ||
|
|
670ed9f29b | ||
|
|
0ac4095143 | ||
|
|
ce7ec3afb7 | ||
|
|
8e6838a00f | ||
|
|
4dc8272c64 | ||
|
|
2e026a043c | ||
|
|
3c59f24608 | ||
|
|
248955b85c | ||
|
|
4944a0694b | ||
|
|
7c6d149f78 | ||
|
|
4ab019fcb8 | ||
|
|
71edc7cc2f | ||
|
|
f3345bccf2 | ||
|
|
143bc945f7 | ||
|
|
b68aeb6829 | ||
|
|
87f4a574e6 | ||
|
|
526e59d5ca | ||
|
|
2898281d35 | ||
|
|
0137d03d5b | ||
|
|
015c938212 | ||
|
|
cb595a0621 | ||
|
|
ff054008c3 | ||
|
|
cfd9cba2dd | ||
|
|
e0ac95ee79 | ||
|
|
a5125b3998 | ||
|
|
ac4464db7b | ||
|
|
6c1898bf5a | ||
|
|
da372dfe10 | ||
|
|
b0f95a384f | ||
|
|
df7be67d4c | ||
|
|
1bee9c94e8 | ||
|
|
259bdee6e1 | ||
|
|
011044d9d0 | ||
|
|
5ca22fbe66 | ||
|
|
29ee56662c | ||
|
|
a9bcb7f7bc | ||
|
|
c40b23b894 | ||
|
|
4fcea5f173 | ||
|
|
d7390f4450 | ||
|
|
352640de34 | ||
|
|
d0cd3f6cfd | ||
|
|
22fac502fa | ||
|
|
034ee44e60 | ||
|
|
a6caffa579 | ||
|
|
d404cb06a7 | ||
|
|
0aee710c19 | ||
|
|
e1b4a207c5 | ||
|
|
26c7d9c97c | ||
|
|
923f119ff6 | ||
|
|
7ab43bbf60 | ||
|
|
48bc99a594 | ||
|
|
2e3ddc11ec | ||
|
|
14ea206521 | ||
|
|
65ff5f6693 | ||
|
|
7965187d2c | ||
|
|
a3b61bca70 | ||
|
|
95d86af627 | ||
|
|
4940966538 | ||
|
|
2f3c2433b4 | ||
|
|
1435d9c909 | ||
|
|
531334d826 | ||
|
|
9e0f0e05ad | ||
|
|
68dd48d607 | ||
|
|
79a12654c8 | ||
|
|
42639fd206 | ||
|
|
7e43178e04 | ||
|
|
e441156ee6 | ||
|
|
61636b23c8 | ||
|
|
3c47bc682f | ||
|
|
cdedb86b9c | ||
|
|
1c2d5efd3a | ||
|
|
47f5e2d9aa | ||
|
|
07038c58c3 | ||
|
|
db94e21e27 | ||
|
|
259a23a165 | ||
|
|
c2e345c67f | ||
|
|
f9243d3cad | ||
|
|
d114444c04 | ||
|
|
656bc5f6dd | ||
|
|
266148d9cd | ||
|
|
f8dcfaf0f5 | ||
|
|
019f5be81c | ||
|
|
7cd258d9a5 | ||
|
|
c212e07665 | ||
|
|
0b9164cc4c | ||
|
|
69fbc374b9 | ||
|
|
aa12c653f1 | ||
|
|
ac187fe39e | ||
|
|
eafa67cfe9 | ||
|
|
a88d267937 | ||
|
|
7433b5a568 | ||
|
|
219e554efe | ||
|
|
60b8e95661 | ||
|
|
4d04c992a3 | ||
|
|
a69b465886 |
No files matched your search
@@ -0,0 +1,48 @@
|
||||
---
|
||||
name: mao-designer
|
||||
description: Produces designs and acceptance criteria for a task, and handles escalations from mao-implementer after 3 failed attempts. Use before delegating non-trivial work and whenever an implementation is stuck.
|
||||
model: opus
|
||||
effort: xhigh
|
||||
---
|
||||
|
||||
You are **mao-designer**, the design and escalation role of the Voelin
|
||||
multi-agent workflow. You do not implement features yourself unless the
|
||||
orchestrator asks for a spike; you produce the artefacts others build from.
|
||||
|
||||
## Your job
|
||||
|
||||
1. **Design.** For the task you are given, read the relevant code first,
|
||||
then deliver: the approach (what changes, where, why this way), the
|
||||
module/type/function names to create or change, the data flow, the
|
||||
failure modes, and the **acceptance criteria**: the exact checks that must
|
||||
pass (`cargo fmt --check`, `cargo clippy -D warnings` for the touched
|
||||
crates, named tests, integration or smoke scenarios, manual checks) and
|
||||
the behaviour that must hold. Name the files to touch and the files that
|
||||
must not change.
|
||||
2. **Escalations.** When `mao-implementer` reports 3 failed attempts, read
|
||||
the evidence (what was tried, failing output, diff). Diagnose the root
|
||||
cause and give a corrected design or a narrowed task. Each correction you
|
||||
issue is one *design attempt*. After **3 unsuccessful design/correction
|
||||
attempts of your own**, stop and escalate to the main orchestrator with
|
||||
the evidence and a recommendation (change approach, narrow scope, or ask
|
||||
the user).
|
||||
|
||||
## Rules
|
||||
|
||||
- You perform this role; you do not delegate it or spawn further
|
||||
orchestration. Project hosting is Gitea (`https://git.faumaray.com`) via the
|
||||
Gitea MCP connector, never GitHub.
|
||||
- Separate observations (what the code does, cited as `path:line`),
|
||||
inferences, and open questions.
|
||||
- Keep designs small enough to implement in one attempt where possible; split
|
||||
otherwise and say in which order.
|
||||
- Communication: use `SendMessage` to reach `mao-implementer` or the
|
||||
orchestrator when it is available; otherwise put everything in your report.
|
||||
Use `ListAgents` only if it is actually exposed.
|
||||
|
||||
## Report format
|
||||
|
||||
**Result** (design ready / corrected design / escalated), **Design** (approach,
|
||||
files, names, data flow), **Acceptance criteria** (checks + behaviour),
|
||||
**Risks and open questions**, **Attempt count** (design attempts used on this
|
||||
task), **Unavailable tools or agents** and the fallback used.
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: mao-helper
|
||||
description: Fast helper for focused file searches, short summaries of files or logs, and routine git operations the user has authorized (status, log, diff, fetch, branch listing, staging, straightforward commits when told to). Use for small, well-defined chores so larger agents keep their context.
|
||||
model: haiku
|
||||
effort: medium
|
||||
---
|
||||
|
||||
You are **mao-helper**, the utility role of the Voelin multi-agent workflow.
|
||||
You do small, well-defined chores quickly and report precisely.
|
||||
|
||||
## What you do
|
||||
|
||||
- **Searches:** find files, symbols, call sites, config keys; return
|
||||
`path:line` tables, not prose, and say what you searched (patterns,
|
||||
directories) so negative results are bounded.
|
||||
- **Summaries:** condense a file, a log, a diff or a test output into the
|
||||
facts the caller asked for; quote exact error text; never invent detail.
|
||||
- **Routine git:** `status`, `log`, `diff`, `fetch`, branch and tag listing,
|
||||
staging, and commits or pushes **only when the task explicitly authorizes
|
||||
them**, with the attribution trailer the session prescribes. Never force
|
||||
push, rewrite history, delete branches or change remotes unless the task
|
||||
says so verbatim. Hosting is Gitea (`https://git.faumaray.com`); repository
|
||||
operations beyond plain git go through the Gitea MCP connector, never
|
||||
`gh` or GitHub.
|
||||
|
||||
## Rules
|
||||
|
||||
- Stay within the task; do not fix code or redesign. If a chore turns out to
|
||||
need judgement, stop and report what you found.
|
||||
- You perform this role; you do not delegate it.
|
||||
- Use `SendMessage` to answer the agent that asked when it is available;
|
||||
otherwise report to the orchestrator.
|
||||
|
||||
## Report format
|
||||
|
||||
**Result**, **Findings or changed files**, **Commands actually run** (with
|
||||
outcome), **Unresolved issues**, **Attempt count** (normally 1),
|
||||
**Unavailable tools** and the fallback.
|
||||
@@ -0,0 +1,50 @@
|
||||
---
|
||||
name: mao-implementer
|
||||
description: Implements a designed task, runs the relevant checks, self-reviews, and reports; escalates to mao-designer after 3 unsuccessful attempts. Use for all code changes once objective, scope, acceptance criteria and files are defined.
|
||||
model: sonnet
|
||||
effort: xhigh
|
||||
---
|
||||
|
||||
You are **mao-implementer**, the implementation role of the Voelin
|
||||
multi-agent workflow. You receive an objective, a scope, acceptance criteria,
|
||||
the relevant files and the expected report. If any of these is missing, ask
|
||||
the orchestrator (or `mao-designer`) before writing code.
|
||||
|
||||
## How you work
|
||||
|
||||
1. Read the design and the files in scope. Reuse existing utilities and
|
||||
patterns in the repository; do not add new abstractions the design did
|
||||
not ask for.
|
||||
2. Implement within scope only. Do not touch files assigned to another agent.
|
||||
3. **Run the checks** named in the acceptance criteria, at least: `cargo fmt
|
||||
--check`, `cargo clippy -D warnings` for the crates you touched (the
|
||||
crates this repository owns; its CLAUDE.md says how to list them), and the tests of every
|
||||
crate you touched. Run the integration or smoke scenarios the task names.
|
||||
4. **Self-review** the diff as a reviewer would: correctness, error paths,
|
||||
concurrency, unchanged public behaviour, docs/comments that now lie.
|
||||
5. Report.
|
||||
|
||||
## Attempts and escalation
|
||||
|
||||
- An *attempt* is a complete proposed solution checked against the
|
||||
acceptance criteria. Tool calls, compiles and test runs inside one attempt
|
||||
do not count separately.
|
||||
- Keep an explicit attempt counter for the task. After **3 unsuccessful
|
||||
attempts**, stop. Do not try a fourth variation. Escalate to
|
||||
`mao-designer` (via `SendMessage` when available, otherwise through your
|
||||
report to the orchestrator) with the evidence: what each attempt changed,
|
||||
the failing check output verbatim, and the current diff.
|
||||
|
||||
## Rules
|
||||
|
||||
- Hosting is Gitea (`https://git.faumaray.com`) through the Gitea MCP
|
||||
connector; never use `gh` or GitHub. Commit only when the task says so,
|
||||
with the attribution trailer the session prescribes.
|
||||
- You perform this role; you do not delegate it or orchestrate others.
|
||||
- Never claim a check passed that you did not run; paste the relevant output.
|
||||
|
||||
## Report format
|
||||
|
||||
**Result** (done / partially done / escalated), **Changed files** (paths),
|
||||
**Checks actually run** (command + outcome, failures verbatim), **Unresolved
|
||||
issues**, **Attempt count**, **Unavailable tools or agents** and the fallback.
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
name: mao-opus-reviewer
|
||||
description: Final, fresh and independent review of substantive code changes for correctness, architecture and unresolved risks. Reports concrete defects; does not fix code. Use after the sonnet review, in a new agent, never in the design agent's conversation.
|
||||
model: opus
|
||||
effort: xhigh
|
||||
tools: Read, Grep, Glob, Bash
|
||||
---
|
||||
|
||||
You are **mao-opus-reviewer**, the final independent reviewer of the Voelin
|
||||
multi-agent workflow. You review; you do not design, implement or edit. You
|
||||
start with no shared context on purpose: form your own model of the change
|
||||
from the code.
|
||||
|
||||
## How you review
|
||||
|
||||
1. Establish what the change is supposed to do (task, acceptance criteria)
|
||||
and what it actually does (diff plus the code it touches and the callers
|
||||
it affects). Trace at least one end-to-end path through the change.
|
||||
2. Judge **correctness** (logic, invariants, error and edge paths,
|
||||
concurrency and ordering, resource lifetimes, protocol/wire compatibility,
|
||||
data migration), **architecture** (does it fit the crate boundaries and
|
||||
the project's direction: client speaks only the Voelin protocol, TS types
|
||||
stay in the gateway, no Slint/Android in client crates; duplicated logic;
|
||||
leaky abstractions; dependencies that should not exist), and **unresolved
|
||||
risks** (untested paths, performance on the hot audio/video paths,
|
||||
security, licensing, operational impact).
|
||||
3. Re-run the decisive checks yourself when feasible rather than trusting
|
||||
earlier reports.
|
||||
4. Report concrete findings with `path:line`, the failure scenario and the
|
||||
fix direction. Rank by severity. Say explicitly what you did **not**
|
||||
verify.
|
||||
|
||||
## Rules
|
||||
|
||||
- Read-only on the code base; running checks is fine, editing is not.
|
||||
- You perform this role; you do not delegate it or orchestrate.
|
||||
- Use `SendMessage` to reach the orchestrator when available; otherwise
|
||||
report.
|
||||
|
||||
## Report format
|
||||
|
||||
**Verdict** (ship / do not ship / ship with listed follow-ups), **Findings**
|
||||
(severity, location, scenario, fix direction), **Architecture notes**,
|
||||
**Unresolved risks**, **Checks actually run**, **Not verified**,
|
||||
**Unavailable tools** and the fallback.
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
name: mao-sonnet-reviewer
|
||||
description: Fresh, independent review of an implementation against its acceptance criteria. Reports concrete defects with file and line; does not fix code. Use after mao-implementer reports done.
|
||||
model: sonnet
|
||||
effort: xhigh
|
||||
tools: Read, Grep, Glob, Bash
|
||||
---
|
||||
|
||||
You are **mao-sonnet-reviewer**, the first independent reviewer of the
|
||||
Voelin multi-agent workflow. You review; you do not edit, redesign or
|
||||
implement. You start fresh: do not assume the implementer's report is
|
||||
accurate; verify it.
|
||||
|
||||
## How you review
|
||||
|
||||
1. Read the task's objective, scope and acceptance criteria, then the diff
|
||||
(`git diff`, or the files named) and the surrounding code it depends on.
|
||||
2. Check, in this order: does it meet the acceptance criteria; correctness
|
||||
(logic, error paths, concurrency, resource cleanup, unchanged public
|
||||
behaviour); scope (nothing outside the task changed); tests (do the named
|
||||
checks exist and cover the change; re-run them yourself when feasible);
|
||||
clarity of names and comments; docs that must change with the code.
|
||||
3. Report **concrete defects** only: `path:line`, what is wrong, why it
|
||||
matters, how it fails (input/state -> wrong outcome), and the fix
|
||||
direction in one sentence. No praise, no style nits that do not change
|
||||
meaning.
|
||||
|
||||
## Rules
|
||||
|
||||
- Read-only on the code base. Running `cargo test`, `cargo clippy` or the
|
||||
smoke scripts is encouraged; editing files is not your role.
|
||||
- You perform this role; you do not delegate it.
|
||||
- Address the implementer or orchestrator with `SendMessage` when it is
|
||||
available; otherwise everything goes in the report.
|
||||
|
||||
## Report format
|
||||
|
||||
**Verdict** (accept / changes needed), **Defects** (ordered by severity, each
|
||||
with location, failure scenario, fix direction), **Checks actually run**
|
||||
(command + outcome), **Acceptance criteria status** (met / not met, per
|
||||
criterion), **Unresolved risks**, **Unavailable tools** and the fallback.
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/claude-code-settings.json",
|
||||
"model": "fable",
|
||||
"effortLevel": "xhigh",
|
||||
"maxEffortLevel": "xhigh"
|
||||
}
|
||||
@@ -2,6 +2,10 @@
|
||||
# the sources only. Builds keep target/ in cache mounts, never in the context.
|
||||
.git
|
||||
.claude
|
||||
# The per-developer .cargo/config.toml (docs/building.md, a [patch] to a sibling
|
||||
# VoelinProtocol checkout): never part of a build. Only the root one; the
|
||||
# committed third_party/dimpl/.cargo stays.
|
||||
.cargo
|
||||
target
|
||||
dist
|
||||
fuzz/target
|
||||
|
||||
@@ -1,9 +1,118 @@
|
||||
name: Linux checks
|
||||
description: Shared Linux validation for Gitea CI and release packaging.
|
||||
inputs:
|
||||
protocol-deploy-key:
|
||||
description: >
|
||||
Private half of the read-only deploy key registered on the private
|
||||
Voelin/VoelinProtocol repository (the repository secret
|
||||
VOELIN_PROTOCOL_DEPLOY_KEY, passed in by the workflow: secrets are not
|
||||
visible inside a composite action). The action fails when it is empty.
|
||||
required: true
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
# The workspace depends on the private VoelinProtocol repository over SSH
|
||||
# (docs/ci.md, "VoelinProtocol access"). First, so that a missing key fails
|
||||
# in seconds and before anything runs cargo.
|
||||
- name: Install the VoelinProtocol deploy key
|
||||
# The key reaches this step through the environment only: never in the
|
||||
# script text, never echoed, no `set -x`.
|
||||
env:
|
||||
PROTOCOL_DEPLOY_KEY: ${{ inputs.protocol-deploy-key }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
if [[ -z "${PROTOCOL_DEPLOY_KEY//[[:space:]]/}" ]]; then
|
||||
echo "::error::The VoelinProtocol deploy key is empty. Set the repository secret VOELIN_PROTOCOL_DEPLOY_KEY to the private key of the read-only deploy key on Voelin/VoelinProtocol (docs/ci.md, VoelinProtocol access). Pull requests from forks get no secrets." >&2
|
||||
exit 1
|
||||
fi
|
||||
for tool in ssh ssh-keygen; do
|
||||
command -v "$tool" > /dev/null || {
|
||||
echo "::error::The job image needs the OpenSSH client: $tool is missing." >&2
|
||||
exit 1
|
||||
}
|
||||
done
|
||||
ssh_dir="$HOME/.ssh"
|
||||
key_file="$ssh_dir/voelin_protocol"
|
||||
mkdir -p "$ssh_dir"
|
||||
chmod 700 "$ssh_dir"
|
||||
|
||||
# Whatever the secret store did to the line ends and the final newline,
|
||||
# OpenSSH needs LF lines, the BEGIN line first and a newline at the end.
|
||||
printf '%s\n' "$PROTOCOL_DEPLOY_KEY" | tr -d '\r' | sed '/^[[:space:]]*$/d' > "$key_file"
|
||||
unset PROTOCOL_DEPLOY_KEY
|
||||
chmod 600 "$key_file"
|
||||
if ! public=$(ssh-keygen -y -f "$key_file" < /dev/null); then
|
||||
rm -f "$key_file"
|
||||
echo "::error::VOELIN_PROTOCOL_DEPLOY_KEY is not an unencrypted OpenSSH or PEM private key." >&2
|
||||
exit 1
|
||||
fi
|
||||
# The fingerprint of the public half, to compare with the deploy key in
|
||||
# the VoelinProtocol settings.
|
||||
printf 'Deploy key installed: %s\n' "$(ssh-keygen -lf - <<< "$public")"
|
||||
|
||||
# The reviewed host key from the repository, never one fetched now.
|
||||
known_hosts="$ssh_dir/known_hosts"
|
||||
touch "$known_hosts"
|
||||
chmod 600 "$known_hosts"
|
||||
[[ -s "${GITHUB_WORKSPACE:-.}/.gitea/known_hosts" ]] || {
|
||||
echo "::error::.gitea/known_hosts is missing from the checkout." >&2
|
||||
exit 1
|
||||
}
|
||||
while IFS= read -r line; do
|
||||
case "$line" in '' | '#'*) continue ;; esac
|
||||
grep -qxF -- "$line" "$known_hosts" || printf '%s\n' "$line" >> "$known_hosts"
|
||||
done < "${GITHUB_WORKSPACE:-.}/.gitea/known_hosts"
|
||||
|
||||
# Use this key, and only this one, for the Gitea server; fail rather than
|
||||
# ask when its host key is unknown or changed. The block goes first: ssh
|
||||
# takes the first value it finds for each option.
|
||||
config="$ssh_dir/config"
|
||||
marker="# VoelinProtocol deploy key (.gitea/actions/checks)"
|
||||
touch "$config"
|
||||
if ! grep -qxF -- "$marker" "$config"; then
|
||||
{
|
||||
cat << EOF
|
||||
$marker
|
||||
Host git.faumaray.com
|
||||
User gitea
|
||||
IdentityFile $key_file
|
||||
IdentitiesOnly yes
|
||||
UserKnownHostsFile $known_hosts
|
||||
StrictHostKeyChecking yes
|
||||
BatchMode yes
|
||||
ConnectTimeout 30
|
||||
|
||||
EOF
|
||||
cat "$config"
|
||||
} > "$config.new"
|
||||
mv "$config.new" "$config"
|
||||
fi
|
||||
chmod 600 "$config"
|
||||
|
||||
# Cargo's built-in git client (libgit2) cannot use IdentityFile; the
|
||||
# system git runs ssh, which reads the config above. `-F` names it
|
||||
# outright: ssh looks for ~/.ssh in the passwd entry's home directory, not
|
||||
# in $HOME, and a job image may set the two apart.
|
||||
{
|
||||
echo "CARGO_NET_GIT_FETCH_WITH_CLI=true"
|
||||
echo "GIT_SSH_COMMAND=ssh -F '$config'"
|
||||
} >> "$GITHUB_ENV"
|
||||
shell: bash
|
||||
- uses: ./.github/actions/system-deps
|
||||
- name: Check read access to VoelinProtocol
|
||||
# The first thing cargo does, with the same git and ssh configuration, so
|
||||
# that a wrong key or a changed host key fails here with a clear message
|
||||
# and not minutes later inside a cargo command.
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if ! GIT_TERMINAL_PROMPT=0 timeout 120 git ls-remote --exit-code \
|
||||
ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git HEAD > /dev/null; then
|
||||
echo "::error::git cannot read Voelin/VoelinProtocol over SSH with the deploy key. 'Permission denied (publickey)' above: the key is not registered on that repository (or is not the one in VOELIN_PROTOCOL_DEPLOY_KEY). 'Host key verification failed': .gitea/known_hosts no longer matches the server (docs/ci.md, VoelinProtocol access)." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Voelin/VoelinProtocol is readable with the deploy key."
|
||||
shell: bash
|
||||
- name: Install pinned Rust toolchain
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# SSH host key of git.faumaray.com (Gitea's built-in SSH server, which offers an
|
||||
# RSA host key only). Fingerprint SHA256:fugBYnqAnqmTLsGpafVgQF9gPQzJqps7uHvs48blg2A,
|
||||
# recorded on 2026-10-24 with `ssh-keyscan -t rsa git.faumaray.com`.
|
||||
#
|
||||
# Committed, never fetched while a job runs, so a CI or release build trusts the
|
||||
# key reviewed here and not whatever answers on the network at that moment.
|
||||
# Read by .gitea/actions/checks (appended to ~/.ssh/known_hosts) and COPYed by
|
||||
# docker/*.Dockerfile and crates/voelin-gateway/Dockerfile. How to re-check it
|
||||
# and how to rotate it: docs/ci.md, "VoelinProtocol access".
|
||||
git.faumaray.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw==
|
||||
+23
-3
@@ -3,13 +3,28 @@ name: CI
|
||||
# Linux checks for Gitea act_runner; runner setup and scope: docs/ci.md.
|
||||
# Off for pushes and pull requests: run by hand only.
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
paths:
|
||||
- "**"
|
||||
- "!docs/**"
|
||||
- "!**/*.md"
|
||||
- "THIRD_PARTY_NOTICES.md"
|
||||
pull_request:
|
||||
paths:
|
||||
- "**"
|
||||
- "!docs/**"
|
||||
- "!**/*.md"
|
||||
- "THIRD_PARTY_NOTICES.md"
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_BUILD_JOBS: "1"
|
||||
CARGO_INCREMENTAL: "0"
|
||||
RUST_BACKTRACE: "0"
|
||||
# Cargo fetches the private VoelinProtocol dependency with the system git and
|
||||
# ssh (docs/ci.md, "VoelinProtocol access"). The checks action exports this
|
||||
# too; set here as well, it does not depend on the runner handing a composite
|
||||
# action's GITHUB_ENV on to the later steps.
|
||||
CARGO_NET_GIT_FETCH_WITH_CLI: "true"
|
||||
|
||||
jobs:
|
||||
linux:
|
||||
@@ -22,3 +37,8 @@ jobs:
|
||||
steps:
|
||||
- uses: https://github.com/actions/checkout@v4
|
||||
- uses: ./.gitea/actions/checks
|
||||
with:
|
||||
# A repository secret is not visible inside the composite action, so
|
||||
# it is passed in. Pull requests from forks get no secrets: the
|
||||
# action then fails at once with a message that says so.
|
||||
protocol-deploy-key: ${{ secrets.VOELIN_PROTOCOL_DEPLOY_KEY }}
|
||||
@@ -9,8 +9,6 @@ on:
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_BUILD_JOBS: "1"
|
||||
CARGO_INCREMENTAL: "0"
|
||||
RUST_BACKTRACE: "0"
|
||||
|
||||
jobs:
|
||||
@@ -34,6 +32,38 @@ jobs:
|
||||
docker info >/dev/null
|
||||
# Remove only output owned by this workflow in its checkout.
|
||||
rm -rf dist
|
||||
# The workspace depends on the private VoelinProtocol repository over SSH
|
||||
# (docs/ci.md, "VoelinProtocol access"). The Docker builds fetch it with
|
||||
# this agent (`docker build --ssh default`): the key lives in the agent's
|
||||
# memory, never on disk and never in an image layer. Stopped by the last
|
||||
# step; the lifetime below ends the key anyway if the runner dies first.
|
||||
- name: Start ssh-agent with the VoelinProtocol deploy key
|
||||
env:
|
||||
PROTOCOL_DEPLOY_KEY: ${{ secrets.VOELIN_PROTOCOL_DEPLOY_KEY }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ -z "${PROTOCOL_DEPLOY_KEY//[[:space:]]/}" ]]; then
|
||||
echo "::error::The repository secret VOELIN_PROTOCOL_DEPLOY_KEY is missing or empty. It holds the private key of the read-only deploy key on Voelin/VoelinProtocol (docs/ci.md, VoelinProtocol access)." >&2
|
||||
exit 1
|
||||
fi
|
||||
for tool in ssh-agent ssh-add; do
|
||||
command -v "$tool" > /dev/null || { echo "::error::The runner needs the OpenSSH client: $tool is missing." >&2; exit 1; }
|
||||
done
|
||||
eval "$(ssh-agent -s -t 32400)" > /dev/null
|
||||
started=
|
||||
trap '[[ -n "$started" ]] || ssh-agent -k > /dev/null' EXIT
|
||||
# LF lines and one final newline, whatever the secret store did.
|
||||
printf '%s\n' "$PROTOCOL_DEPLOY_KEY" | tr -d '\r' | sed '/^[[:space:]]*$/d' | ssh-add -q -
|
||||
unset PROTOCOL_DEPLOY_KEY
|
||||
# The fingerprint of the public half, to compare with the deploy key.
|
||||
ssh-add -l
|
||||
{
|
||||
echo "SSH_AUTH_SOCK=$SSH_AUTH_SOCK"
|
||||
echo "SSH_AGENT_PID=$SSH_AGENT_PID"
|
||||
# Only an agent this job started is stopped at the end.
|
||||
echo "VOELIN_AGENT_STARTED=1"
|
||||
} >> "$GITHUB_ENV"
|
||||
started=1
|
||||
- name: Linux packages
|
||||
run: scripts/docker-build.sh linux --progress=plain
|
||||
- name: Windows packages (MinGW)
|
||||
@@ -74,21 +104,19 @@ jobs:
|
||||
--build-arg "SIGNING_CACHE_BUST=$(basename "$signing")" \
|
||||
--secret "id=keystore,src=$signing/release.jks" \
|
||||
--secret "id=signing,src=$SIGNING_ENV"
|
||||
- name: Flatpak bundle
|
||||
run: scripts/flatpak-build.sh dist/flatpak
|
||||
- name: Gateway container image
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version=$(sed -n 's/^version = "\(.*\)"$/\1/p' crates/voelin-gateway/Cargo.toml | head -n 1)
|
||||
test -n "$version"
|
||||
docker build -f crates/voelin-gateway/Dockerfile -t "tsgw:$version" -t tsgw:latest .
|
||||
DOCKER_BUILDKIT=1 docker build --ssh default -f crates/voelin-gateway/Dockerfile -t "tsgw:$version" -t tsgw:latest .
|
||||
mkdir -p dist/gateway
|
||||
docker save "tsgw:$version" tsgw:latest | gzip > dist/gateway/tsgw-image.tar.gz
|
||||
- name: Collect packages and checksums
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p dist/release
|
||||
for file in dist/{linux,windows,android,flatpak,gateway}/*; do
|
||||
for file in dist/{linux,windows,android,gateway}/*; do
|
||||
[[ -f "$file" && ! -L "$file" ]] || { echo "Missing package: $file" >&2; exit 1; }
|
||||
name=$(basename "$file")
|
||||
[[ "$name" != SHA256SUMS* ]] || continue
|
||||
@@ -108,3 +136,9 @@ jobs:
|
||||
# Gitea refuses secret names starting with GITEA_ or GITHUB_.
|
||||
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
run: scripts/gitea-release.sh dist/release
|
||||
- name: Stop the ssh-agent
|
||||
if: always()
|
||||
run: |
|
||||
if [[ -n "${VOELIN_AGENT_STARTED:-}" && -n "${SSH_AGENT_PID:-}" ]]; then
|
||||
ssh-agent -k > /dev/null || true
|
||||
fi
|
||||
@@ -1,12 +1,13 @@
|
||||
name: System dependencies
|
||||
description: >
|
||||
Native libraries and tools the workspace builds against: apt packages on
|
||||
Linux; NASM and libvpx (vcpkg, cached) on Windows, exporting VPX_LIB_DIR,
|
||||
VPX_INCLUDE_DIR, VPX_VERSION and VPX_STATIC for libvpx-native-sys.
|
||||
Linux; NASM, libvpx and dav1d (vcpkg, cached) on Windows, exporting
|
||||
VPX_LIB_DIR, VPX_INCLUDE_DIR, VPX_VERSION and VPX_STATIC for
|
||||
libvpx-native-sys and SYSTEM_DEPS_DAV1D_* for dav1d-sys.
|
||||
|
||||
inputs:
|
||||
vpx-triplet:
|
||||
description: vcpkg triplet for libvpx on Windows (static library, dynamic CRT like Rust's default)
|
||||
description: vcpkg triplet for libvpx and dav1d on Windows (static libraries, dynamic CRT like Rust's default)
|
||||
default: x64-windows-static-md
|
||||
|
||||
runs:
|
||||
@@ -47,8 +48,8 @@ runs:
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ${{ runner.temp }}\vcpkg-archives
|
||||
key: vcpkg-libvpx-${{ inputs.vpx-triplet }}-${{ steps.vcpkg.outputs.commit }}
|
||||
restore-keys: vcpkg-libvpx-${{ inputs.vpx-triplet }}-
|
||||
key: vcpkg-libvpx-dav1d-${{ inputs.vpx-triplet }}-${{ steps.vcpkg.outputs.commit }}
|
||||
restore-keys: vcpkg-libvpx-dav1d-${{ inputs.vpx-triplet }}-
|
||||
|
||||
- name: libvpx
|
||||
if: runner.os == 'Windows'
|
||||
@@ -60,7 +61,7 @@ runs:
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$vcpkg = Join-Path $env:VCPKG_INSTALLATION_ROOT 'vcpkg.exe'
|
||||
New-Item -ItemType Directory -Force (Join-Path $env:RUNNER_TEMP 'vcpkg-archives') | Out-Null
|
||||
& $vcpkg install "libvpx:$env:TRIPLET"
|
||||
& $vcpkg install "libvpx:$env:TRIPLET" "dav1d:$env:TRIPLET"
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
|
||||
# "libvpx:x64-windows-static-md 1.15.2#1 The reference ..."
|
||||
@@ -85,3 +86,19 @@ runs:
|
||||
"VPX_VERSION=$version" >> $env:GITHUB_ENV
|
||||
"VPX_STATIC=1" >> $env:GITHUB_ENV
|
||||
Write-Host "libvpx $version from $libdir"
|
||||
|
||||
# dav1d-sys (AV1 decoding) through system-deps, without pkg-config:
|
||||
# the static library, linked as dav1d.lib.
|
||||
$davdir = Join-Path $root 'lib'
|
||||
if (-not (Test-Path (Join-Path $davdir 'dav1d.lib'))) {
|
||||
$lib = Get-ChildItem $davdir -Filter '*dav1d*.lib' | Select-Object -First 1
|
||||
if (-not $lib) { Get-ChildItem $davdir; throw "no dav1d library in $davdir" }
|
||||
$davdir = Join-Path $env:RUNNER_TEMP 'dav1d-lib'
|
||||
New-Item -ItemType Directory -Force $davdir | Out-Null
|
||||
Copy-Item $lib.FullName (Join-Path $davdir 'dav1d.lib')
|
||||
}
|
||||
"SYSTEM_DEPS_DAV1D_NO_PKG_CONFIG=1" >> $env:GITHUB_ENV
|
||||
"SYSTEM_DEPS_DAV1D_SEARCH_NATIVE=$davdir" >> $env:GITHUB_ENV
|
||||
"SYSTEM_DEPS_DAV1D_LIB=dav1d" >> $env:GITHUB_ENV
|
||||
"SYSTEM_DEPS_DAV1D_LINK=static" >> $env:GITHUB_ENV
|
||||
Write-Host "dav1d from $davdir"
|
||||
@@ -20,6 +20,10 @@ permissions:
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
RUST_BACKTRACE: "0"
|
||||
# GitHub's runners have 16 GB: the generated UI library does not fit
|
||||
# in that next to other crates, and the runner is killed. The Gitea
|
||||
# workflow keeps Cargo's default job count. The Flatpak job sets it in
|
||||
# the manifest too.
|
||||
CARGO_BUILD_JOBS: "1"
|
||||
CARGO_INCREMENTAL: "0"
|
||||
|
||||
@@ -37,10 +41,11 @@ jobs:
|
||||
key: release
|
||||
- name: Build
|
||||
run: cargo build --release --locked -p voelin-ui -p voelin-gateway
|
||||
# dpkg-shlibdeps works out the .deb's dependencies.
|
||||
# dpkg-shlibdeps works out the .deb's dependencies; patchelf points
|
||||
# the .tar.gz's binary at the libraries it carries.
|
||||
- name: Package (.tar.gz, .deb)
|
||||
run: |
|
||||
sudo apt-get install -y --no-install-recommends dpkg-dev
|
||||
sudo apt-get install -y --no-install-recommends dpkg-dev patchelf
|
||||
scripts/package.sh linux dist
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
@@ -72,6 +77,12 @@ jobs:
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
}
|
||||
"MAKENSIS=$($makensis.Replace('\', '/'))" >> $env:GITHUB_ENV
|
||||
# FFmpeg's LGPL DLLs, shipped next to voelin.exe.
|
||||
- name: FFmpeg
|
||||
shell: bash
|
||||
run: |
|
||||
scripts/fetch-ffmpeg-windows.sh "$RUNNER_TEMP/ffmpeg"
|
||||
echo "FFMPEG_DLL_DIR=$RUNNER_TEMP/ffmpeg" >> "$GITHUB_ENV"
|
||||
- name: Package (.zip, installer)
|
||||
shell: bash
|
||||
run: scripts/package.sh windows dist
|
||||
@@ -103,6 +114,13 @@ jobs:
|
||||
python3 -m venv /tmp/venv
|
||||
/tmp/venv/bin/pip install --quiet "aiohttp>=3.9.5,<4" "tomlkit>=0.13.3,<1" "PyYAML>=6.0.2,<7"
|
||||
/tmp/venv/bin/python /tmp/flatpak-cargo-generator.py Cargo.lock -o packaging/flatpak/cargo-sources.json
|
||||
# flatpak-builder does not pass the job's environment into its sandbox,
|
||||
# and the manifest keeps Cargo's default job count for Gitea: one job
|
||||
# here, as for the other packages.
|
||||
- name: One Cargo job
|
||||
run: |
|
||||
sed -i 's/^ CARGO_NET_OFFLINE: "true"$/&\n CARGO_BUILD_JOBS: "1"/' packaging/flatpak/io.github.faumaray.Voelin.yml
|
||||
grep -q '^ CARGO_BUILD_JOBS: "1"$' packaging/flatpak/io.github.faumaray.Voelin.yml
|
||||
- uses: flatpak/flatpak-github-actions/flatpak-builder@v6
|
||||
with:
|
||||
bundle: voelin.flatpak
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/target/
|
||||
/dev/.state/
|
||||
/dist/
|
||||
/.cargo/
|
||||
+224
@@ -6,6 +6,230 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- Log files: each run logs to `<state>/voelin/logs/voelin.log`, the previous
|
||||
four runs are kept; `VOELIN_LOG` sets what is logged. Settings → Advanced
|
||||
opens the folder.
|
||||
- Linux `.tar.gz`: libvpx and libdav1d in `lib/`, and `bin/voelin-install-deps`
|
||||
for FFmpeg, VA-API drivers, PipeWire, the desktop portal and a keyring.
|
||||
- Windows packages ship FFmpeg's LGPL libraries, so hardware encoders and
|
||||
decoders work without installing FFmpeg.
|
||||
- AV1 decoding through dav1d in every desktop build.
|
||||
- 122 more signed client versions (`Versions.csv`).
|
||||
- Icon buttons show their name on hover (desktop), also while they are
|
||||
disabled.
|
||||
- The voice channel view on desktop can copy an invite link to the channel,
|
||||
as the phone's Invite button does.
|
||||
- Other people's myTeamSpeak badges: up to three pictures after their name
|
||||
in the channel tree and the members panel, and their names on the member
|
||||
card (what each is for on hover). On TeamSpeak 6 the badges the server
|
||||
verified come first.
|
||||
- Links in chat open in the browser; one whose text is not its address
|
||||
first shows where it goes. A right-click on a link opens or copies it.
|
||||
- `ts3server://` and `teamspeak://` links in chat (and `tmspk.gg/s/…`)
|
||||
open the server dialog filled in from the link, its channel and key
|
||||
included, or move you into the link's channel when you are in voice on
|
||||
that server. Nothing connects before Connect, and a saved server keeps
|
||||
its nickname. `tmspk.gg` invite codes can't be opened yet.
|
||||
- Every message can be quoted into the composer (`> ` lines) and its text
|
||||
copied, from the actions on hover or a right-click menu, also on servers
|
||||
without a gateway.
|
||||
- A "New" line above the first unread message of a chat, and a bar that
|
||||
counts the new messages with a jump to the first; unread counts survive
|
||||
restarts. Messages count as read only while their chat is on screen in
|
||||
the focused window.
|
||||
- Other users' myTeamSpeak avatars (TeamSpeak 6), as the official client
|
||||
shows them: where the server has no avatar of them, its avatar could not
|
||||
be downloaded, or the server is only observed.
|
||||
- Pictures (banners, avatars) go through the desktop's proxy where the
|
||||
desktop portal names one (Linux), and through the system proxy on
|
||||
Windows and macOS; SOCKS proxies work too.
|
||||
- tsgw logs what it does: a startup summary, the address the TeamSpeak
|
||||
server sees for its queries (with a hint when that address is not
|
||||
allowlisted), every app connection with its logins and how long they
|
||||
took, refused logins, slow requests, ServerQuery failures, relays and the
|
||||
observer. `log.level` (`TSGW_LOG_LEVEL`) sets what is logged, `log.file`
|
||||
(`TSGW_LOG_FILE`) also writes to a file that is rotated at 20 MB (five
|
||||
kept); colour only on a terminal.
|
||||
- Every gateway a server publishes is tried in turn (TLS first, 20 seconds
|
||||
each) before waiting to try again, so a TLS proxy that fails falls back to
|
||||
the plain gateway published next to it.
|
||||
- A call bar on the desktop's voice channel page: mute, deafen, share, the
|
||||
voice settings and Leave, under the people and streams (Voice Settings
|
||||
and Leave left the header). A smaller stage, one row of people and the
|
||||
streams as rows, leaves about 200 px more for the chat; it is remembered,
|
||||
and windows under 800 px tall always have it.
|
||||
- A theatre mode for streams: the stream viewer's new button fills the
|
||||
window with the stream and its chat, without the servers, the channels
|
||||
and the members. Escape leaves it, and full screen too.
|
||||
- Streams pop out into a window of their own on the desktop, optionally
|
||||
kept on top of other windows, while the main window goes on; closing it
|
||||
brings the stream back.
|
||||
|
||||
### Changed
|
||||
|
||||
- The view models, the app's state and the decisions of the settings pages and
|
||||
of the Stream Studio moved out of `voelin-ui` into a new crate,
|
||||
`voelin-ui-vm`, which depends on no UI toolkit (a second front end can use
|
||||
it); `voelin-ui` converts its plain rows into Slint's and keeps the window,
|
||||
the Bridge writes and the engine's tasks. The chat formatting reader and the
|
||||
Twemoji archive moved with them. Nothing changes on screen. See
|
||||
docs/ui.md, "Two crates".
|
||||
- The identity store keeps identities of more than one kind (TeamSpeak, a Voelin
|
||||
key, the signed-in account) with the account each belongs to, as a
|
||||
`voelin-identity` key store, in two database migrations. Existing
|
||||
databases migrate on first start and every identity stays what it was (kind
|
||||
TeamSpeak, no account, same key, name, origin and default); nothing changes
|
||||
on screen yet. The build now fetches `voelin-identity` from the private
|
||||
VoelinProtocol repository, so a fresh checkout needs read access to it
|
||||
(see docs/building.md).
|
||||
- Selecting a server observes it through its gateway at once; the Observe
|
||||
button is gone. The server dialog asks only for the address, password,
|
||||
name and nickname: the gateway is found from the address.
|
||||
- Relayed messages appear in TeamSpeak under the author's own nickname
|
||||
(`Nick1` while the name is taken), not as `[Nick] text` from the relay.
|
||||
- The client reports itself as TeamSpeak 6 (`6.0.0-beta4.1` on Linux,
|
||||
`6.0.0-beta2` on Windows) instead of `3.?.?`; `--client-version generic`
|
||||
claims the old version.
|
||||
- Watching streams: VP8 decodes on one thread (FFmpeg's slice threads made
|
||||
multi-partition streams 40-80 % slower), pictures are converted for the
|
||||
window on their own thread into reused buffers, and libvpx and dav1d use
|
||||
fewer threads. A 1440p60 VP8 stream from a 6-8 core sender showed 35-49
|
||||
fps; FFmpeg decodes it at 95-101 fps on one thread against 54-60 on four.
|
||||
- Release builds no longer limit Cargo to one job.
|
||||
- The gateway is invisible: relayed messages look like everyone else's (no
|
||||
"via relay"), and a gateway that is away is tried again quietly instead
|
||||
of showing a WebSocket error; only what the user did and failed is
|
||||
told, in plain words. A server whose gateway is away no longer shows as
|
||||
connecting, so it can always be joined.
|
||||
- A server's published gateway replaces one stored before (found or typed
|
||||
into an older version), so a gateway that moved is followed.
|
||||
- zbus's warnings about desktop portal requests are left out of the logs.
|
||||
- Pop-ups, menus and tooltips have a clearer edge, and the member card, the
|
||||
emoji picker and the notifications panel dim the window behind them.
|
||||
- Double-clicking a channel of a server without voice connects into it
|
||||
(it said "not connected with voice").
|
||||
- Older chat messages load when scrolling up, above the messages on screen,
|
||||
which stay in place; the Older messages button remains for a chat that
|
||||
fits on the screen.
|
||||
- One dialog adds a server, with Save and Connect (Enter connects).
|
||||
Connect connects only a server it saved (Join connected the server shown
|
||||
before when saving failed).
|
||||
- A slimmer top bar on desktop: only the search and the bell. The bell's
|
||||
panel opens under the bell and is as tall as its notices; the members
|
||||
button is in the voice channel's header (as in the chat's), About in
|
||||
Settings. The user card has no settings gear (the rail's stays); its
|
||||
avatar and name open your account.
|
||||
- Home shows where you left off (the last voice channel, joined in one
|
||||
click) and your unread mentions; the welcome banner shows only before the
|
||||
first server. Friends show once, the quick actions are gone, and the
|
||||
sidebar lists your recent private chats.
|
||||
- Each server has a colour of its own (two often shared a blue), and small
|
||||
server icons are drawn sharp at twice their size instead of stretched.
|
||||
Small avatars, as in the channel tree, show one letter.
|
||||
- Channels have one icon everywhere, the speaker, and are named without a
|
||||
`#` in tabs and elsewhere.
|
||||
- The members panel shows a hand on those who need talk power to speak,
|
||||
instead of everyone's talk power as a bare number (the member card still
|
||||
has it).
|
||||
- The chat header's pinned messages and topics are icon buttons with a
|
||||
count, so the channel's topic has room.
|
||||
- Private chats live on the Direct Messages page, not in the server's chat
|
||||
tabs, and their unread messages count there (on the phone, on the Home
|
||||
tab) instead of on the server rail.
|
||||
- Stream cards show the streamer: their avatar on a painted scene in their
|
||||
colour, with what they share, instead of a bare screen icon (TeamSpeak
|
||||
streams have no preview pictures). Your own stream from the Stream Studio
|
||||
shows its picture.
|
||||
- The stream viewer's controls hide while you watch, 2.5 s after the
|
||||
pointer last moved over the picture (in full screen the cursor too; on a
|
||||
touch screen a tap shows or hides them), and the streamer, the title and
|
||||
LIVE are in the header above the picture instead of over it.
|
||||
- The phone's voice screen has one header: the top bar shows the channel on
|
||||
its banner, the server below it instead of the channel's topic, and Back;
|
||||
Leave is only in the bottom bar. Pinned messages and topics are in the
|
||||
More menu and the row of people is smaller, so the chat has about 130 px
|
||||
more room. With push-to-talk, Hold to talk is the bottom bar's middle
|
||||
button instead of the microphone button by the composer; Go Live and
|
||||
Share are one Share button that opens the share menu (a screen, or the
|
||||
Stream Studio) as on desktop. The microphone button says Mic on or Mic
|
||||
off.
|
||||
- The phone's Servers tab is titled Servers; the server's name and counts
|
||||
are only in the server card below the server icons, no longer in the top
|
||||
bar too. The voice card shows only your channel, on desktop too.
|
||||
- Banners: up to 128 MiB, more time on slow hosts, BMP and ICO too, and
|
||||
SVG after a comment or DOCTYPE; pictures larger than 4096 pixels on a
|
||||
side are scaled down. A banner that fails is tried again for as long as
|
||||
it is shown (every 15 minutes at most), and the log says why it is
|
||||
missing (HTTP status, an HTML page, a video, too large). The picture
|
||||
cache defaults to 1 GiB, the decoded images to 256 MB.
|
||||
- Banners that fail: the log names the URL (without its query) the first
|
||||
time, says when a connection stalled and after how much data, and when it
|
||||
could not connect at all. A banner that is not there (HTTP 400, 404, 410)
|
||||
is tried again after 15 minutes and then hourly; a host that asks to wait
|
||||
(429, 503) is waited for. A banner shown again is only checked for
|
||||
changes (ETag, Last-Modified), not downloaded again. At most 6 downloads
|
||||
run per host, so a slow host cannot hold up the others.
|
||||
- The gateway: only a refused login stops observing; anything else is tried
|
||||
again after 1, 2, 5, 10, 20, then every 30 seconds, and at once when voice
|
||||
connects. A connection that stops answering is noticed within 90 seconds.
|
||||
Finding a server's gateway asks DNS and the gateway at once instead of one
|
||||
after the other. The log says what was found, which gateway was tried,
|
||||
how long each step took and why one failed.
|
||||
- tsgw answers faster: each ServerQuery command takes under 2 ms instead of
|
||||
about 45 ms (TCP_QUICKACK), so logins and startup take milliseconds.
|
||||
TeamSpeak's flood protection is shared by all of tsgw's query
|
||||
connections, so tsgw no longer earns a 600 second ban. It starts while
|
||||
the TeamSpeak server is still down and connects once it is up, its
|
||||
`/health` says what is missing, and it stops cleanly on SIGTERM.
|
||||
|
||||
### Removed
|
||||
|
||||
- myTeamSpeak account sign-in, profile, avatar, badges and User Tag: the
|
||||
login page at start, the sign-in form and profile in Settings → My Account
|
||||
(it says "Account sign-in is not available in this build"), and the account
|
||||
presented to voice servers. They return through the gateway. A session an
|
||||
earlier build saved stays in the system keyring (item `myts/session`)
|
||||
until you delete it there.
|
||||
|
||||
### Fixed
|
||||
|
||||
- A deleted identity key no longer stays in the database file: SQLite overwrites
|
||||
what it deletes, and the log is truncated after a key is deleted (an identity
|
||||
you delete, a key a sign-out deletes).
|
||||
- Hover help in the Stream Studio (a source's error, the status details)
|
||||
shows each time and closes when the pointer leaves; it showed only once,
|
||||
and stayed open until a click.
|
||||
- Spacer channels: `[spacer]`, `[lspacer]`, `[rspacer]` and `[*spacer]` lines
|
||||
are drawn as TeamSpeak draws them, like `[cspacer]` was, and chats, search
|
||||
results, notifications and the other screens show a spacer's text instead
|
||||
of its raw name.
|
||||
- Locked channels ask for their password (kept until voice disconnects, and
|
||||
asked again when it is wrong), and joining a full channel or one the
|
||||
server refuses says why; joining did nothing before.
|
||||
- Pokes can carry a message (up to 100 characters); they were always sent
|
||||
empty.
|
||||
- While a priority speaker talks, everyone else (watched streams too) is
|
||||
dimmed by the server's setting, as in TeamSpeak; nobody was dimmed before.
|
||||
- BBCode from other clients shows as formatting (bold, colours, links,
|
||||
quotes, lists, code, pictures) instead of raw tags, and the server's
|
||||
welcome message opens the server chat. Messages with emoji keep their
|
||||
line breaks.
|
||||
- Joining a friend in a subchannel of a server without voice connects into
|
||||
that subchannel; it connected into the default channel.
|
||||
- Closing a chat tab left of the selected one keeps the selected chat; the
|
||||
one after it was selected.
|
||||
- Connecting with voice from a private chat (Direct Messages) keeps that
|
||||
conversation open; it turned into the voice channel's chat, and the
|
||||
composer sent there.
|
||||
- Observing no longer stops for the whole run the first time a server is
|
||||
joined with a new identity (the gateway did not know it yet).
|
||||
- tsgw reconnects its query connection for logins when the TeamSpeak server
|
||||
restarts; before, every login was refused until tsgw was restarted.
|
||||
- Push-to-talk controls (Hold to talk) showed in voice activation and
|
||||
continuous mode until the settings had been opened once.
|
||||
|
||||
## [0.0.1-alpha] - 2026-10-04
|
||||
|
||||
The first alpha.
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
# Voelin — working agreements for Claude Code
|
||||
|
||||
Voelin is a Rust voice/chat client that is becoming a complete alternative to
|
||||
TeamSpeak 6 and Discord. The project is being split into four repositories
|
||||
(VoelinClient, VoelinProtocol, VoelinServer, VoelinGateWay) under the Gitea
|
||||
org `Voelin`; the current plan lives in the approved plan file referenced in
|
||||
`docs/` once committed. Keep the Rust toolchain in `rust-toolchain.toml`,
|
||||
`cargo fmt` (hard tabs, `rustfmt.toml`) and `cargo clippy -D warnings` on the
|
||||
project's own crates (`scripts/own-crates.sh`) green.
|
||||
|
||||
## Hosting: Gitea, not GitHub
|
||||
|
||||
- The source of truth is **https://git.faumaray.com** (Gitea). Pull requests,
|
||||
issues, releases, labels and repository creation go through the **Gitea MCP
|
||||
connector** (`mcp__claude_ai_gitea__*`). Do not use `gh`, the GitHub API or
|
||||
GitHub Actions assumptions; `.github/workflows` are kept only as reference.
|
||||
- Git remotes are `gitea@git.faumaray.com:<owner>/<repo>.git`. CI runs on
|
||||
Gitea Actions (`.gitea/workflows`).
|
||||
- Report when the connector is unavailable instead of silently falling back
|
||||
to another host or to raw `curl`.
|
||||
|
||||
## Multi-agent orchestration (MAO) policy
|
||||
|
||||
**Scope: these orchestration rules apply only to the MAIN SESSION.** A
|
||||
subagent that reads this file performs its assigned role (design, implement,
|
||||
review, help) and does not delegate it again or spawn further orchestration.
|
||||
|
||||
### Roles
|
||||
|
||||
| Agent | Model / effort | Job |
|
||||
|---|---|---|
|
||||
| main session | (settings) | **Orchestrator**: decomposes work, delegates, tracks progress and attempt counts, resolves escalations, reports results. Delegates implementation, investigation, testing and review rather than doing them inline. |
|
||||
| `mao-designer` | opus / xhigh | Designs, acceptance criteria, escalation handling |
|
||||
| `mao-implementer` | sonnet / xhigh | Implements, runs checks, self-reviews; escalates after 3 failed attempts |
|
||||
| `mao-sonnet-reviewer` | sonnet / xhigh | Fresh, independent implementation review |
|
||||
| `mao-opus-reviewer` | opus / xhigh | Fresh, final independent review of substantive code changes (correctness, architecture, unresolved risks) |
|
||||
| `mao-helper` | haiku | Focused file searches, summaries, routine git operations within the user's authorization |
|
||||
|
||||
### Before delegating
|
||||
|
||||
Define, in the delegation prompt: the **objective**, the **scope** (what is
|
||||
in and out, which files), the **acceptance criteria** (checks that must pass,
|
||||
behaviour that must hold), the **relevant files** and the **expected report**.
|
||||
Use named agents (`name:` in the Agent call) so collaborators can address
|
||||
each other.
|
||||
|
||||
### Parallelism
|
||||
|
||||
Parallelize **independent** work only. Never give two agents the same files
|
||||
to edit at the same time; split by crate, module or file set, or serialize.
|
||||
|
||||
### Implementation and review chain
|
||||
|
||||
1. `mao-implementer` implements, runs the relevant checks (`cargo fmt
|
||||
--check`, `cargo clippy -D warnings` on the touched crates, the crate's
|
||||
tests, and the integration/smoke scenarios named in the task) and
|
||||
self-reviews before reporting.
|
||||
2. A **fresh** `mao-sonnet-reviewer` reviews the implementation independently.
|
||||
3. For substantive code changes, a **fresh** `mao-opus-reviewer` performs the
|
||||
final independent review. Do not reuse the design agent's conversation
|
||||
for this review; start a new agent.
|
||||
4. The orchestrator decides: accept, send back with the findings, or escalate.
|
||||
|
||||
### Attempts and escalation
|
||||
|
||||
- Track failed attempts **per task**. An *attempt* is a proposed solution
|
||||
checked against the acceptance criteria, not an individual tool call.
|
||||
- After **3 unsuccessful implementation attempts**, stop Sonnet retries and
|
||||
escalate to `mao-designer` (Opus) with the evidence: what was tried, the
|
||||
failing check output, the diff.
|
||||
- After **3 unsuccessful design/correction attempts by Opus**, escalate to
|
||||
the main orchestrator.
|
||||
- The orchestrator must then **change the approach, narrow the task, or ask
|
||||
the user for the missing input**. Do not reset counters and repeat the
|
||||
same loop.
|
||||
|
||||
### Communication
|
||||
|
||||
- Use `SendMessage` for direct agent-to-agent or agent-to-orchestrator
|
||||
messages when it is available. Use `ListAgents` only if it is actually
|
||||
exposed; otherwise address agents by their known names, or relay through
|
||||
the orchestrator.
|
||||
- Reports (every agent, every task) must include: **result**, **changed
|
||||
files**, **checks actually run** (with their outcome), **unresolved
|
||||
issues**, and the **attempt count**.
|
||||
- Report unavailable agents, models or tools explicitly, together with the
|
||||
fallback that was used (for example "mao-opus-reviewer unavailable, review
|
||||
done by mao-sonnet-reviewer").
|
||||
|
||||
### Models and effort
|
||||
|
||||
Model and effort live in `.claude/settings.json` (session default) and in
|
||||
each agent's frontmatter (per role). Do not set `CLAUDE_CODE_EFFORT_LEVEL`
|
||||
globally: the roles need different effort levels.
|
||||
Generated
+89
-241
@@ -1996,7 +1996,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
||||
dependencies = [
|
||||
"const-oid 0.9.6",
|
||||
"der_derive",
|
||||
"der_derive 0.7.3",
|
||||
"flagset",
|
||||
"pem-rfc7468 0.7.0",
|
||||
"zeroize",
|
||||
@@ -2009,6 +2009,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a"
|
||||
dependencies = [
|
||||
"const-oid 0.10.2",
|
||||
"der_derive 0.8.0",
|
||||
"flagset",
|
||||
"pem-rfc7468 1.0.0",
|
||||
"zeroize",
|
||||
]
|
||||
@@ -2038,6 +2040,17 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "der_derive"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59600e2c2d636fde9b65e99cc6445ac770c63d3628195ff39932b8d6d7409903"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.5.8"
|
||||
@@ -2134,7 +2147,7 @@ dependencies = [
|
||||
"spki 0.7.3",
|
||||
"subtle",
|
||||
"time",
|
||||
"x509-cert",
|
||||
"x509-cert 0.2.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3502,19 +3515,6 @@ dependencies = [
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper-timeout"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0"
|
||||
dependencies = [
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper-util"
|
||||
version = "0.1.21"
|
||||
@@ -3534,9 +3534,11 @@ dependencies = [
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"socket2",
|
||||
"system-configuration",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
"windows-registry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4877,12 +4879,6 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multimap"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084"
|
||||
|
||||
[[package]]
|
||||
name = "multiversion_no_op"
|
||||
version = "1.0.0"
|
||||
@@ -5861,7 +5857,6 @@ checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629"
|
||||
dependencies = [
|
||||
"digest 0.11.3",
|
||||
"hmac 0.13.0",
|
||||
"sha2 0.11.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6340,27 +6335,6 @@ dependencies = [
|
||||
"prost-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prost-build"
|
||||
version = "0.14.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "03da047801ff44bb6a4d407d4860c05fd70bb81714e6b2f3812603d5b145b042"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"itertools 0.14.0",
|
||||
"log",
|
||||
"multimap",
|
||||
"petgraph",
|
||||
"prettyplease",
|
||||
"prost",
|
||||
"prost-types",
|
||||
"pulldown-cmark",
|
||||
"pulldown-cmark-to-cmark",
|
||||
"regex",
|
||||
"syn 2.0.119",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prost-derive"
|
||||
version = "0.14.4"
|
||||
@@ -6374,79 +6348,6 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prost-types"
|
||||
version = "0.14.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a"
|
||||
dependencies = [
|
||||
"prost",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "protoc-bin-vendored"
|
||||
version = "3.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d1c381df33c98266b5f08186583660090a4ffa0889e76c7e9a5e175f645a67fa"
|
||||
dependencies = [
|
||||
"protoc-bin-vendored-linux-aarch_64",
|
||||
"protoc-bin-vendored-linux-ppcle_64",
|
||||
"protoc-bin-vendored-linux-s390_64",
|
||||
"protoc-bin-vendored-linux-x86_32",
|
||||
"protoc-bin-vendored-linux-x86_64",
|
||||
"protoc-bin-vendored-macos-aarch_64",
|
||||
"protoc-bin-vendored-macos-x86_64",
|
||||
"protoc-bin-vendored-win32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "protoc-bin-vendored-linux-aarch_64"
|
||||
version = "3.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c350df4d49b5b9e3ca79f7e646fde2377b199e13cfa87320308397e1f37e1a4c"
|
||||
|
||||
[[package]]
|
||||
name = "protoc-bin-vendored-linux-ppcle_64"
|
||||
version = "3.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a55a63e6c7244f19b5c6393f025017eb5d793fd5467823a099740a7a4222440c"
|
||||
|
||||
[[package]]
|
||||
name = "protoc-bin-vendored-linux-s390_64"
|
||||
version = "3.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1dba5565db4288e935d5330a07c264a4ee8e4a5b4a4e6f4e83fad824cc32f3b0"
|
||||
|
||||
[[package]]
|
||||
name = "protoc-bin-vendored-linux-x86_32"
|
||||
version = "3.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8854774b24ee28b7868cd71dccaae8e02a2365e67a4a87a6cd11ee6cdbdf9cf5"
|
||||
|
||||
[[package]]
|
||||
name = "protoc-bin-vendored-linux-x86_64"
|
||||
version = "3.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b38b07546580df720fa464ce124c4b03630a6fb83e05c336fea2a241df7e5d78"
|
||||
|
||||
[[package]]
|
||||
name = "protoc-bin-vendored-macos-aarch_64"
|
||||
version = "3.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "89278a9926ce312e51f1d999fee8825d324d603213344a9a706daa009f1d8092"
|
||||
|
||||
[[package]]
|
||||
name = "protoc-bin-vendored-macos-x86_64"
|
||||
version = "3.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "81745feda7ccfb9471d7a4de888f0652e806d5795b61480605d4943176299756"
|
||||
|
||||
[[package]]
|
||||
name = "protoc-bin-vendored-win32"
|
||||
version = "3.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "95067976aca6421a523e491fce939a3e65249bac4b977adee0ee9771568e8aa3"
|
||||
|
||||
[[package]]
|
||||
name = "pulldown-cmark"
|
||||
version = "0.13.4"
|
||||
@@ -6458,15 +6359,6 @@ dependencies = [
|
||||
"unicase",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pulldown-cmark-to-cmark"
|
||||
version = "22.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "84bbb29c624230c4bd1047bbdb2aa47e41c860e9665ce62ba9504eebe91bf867"
|
||||
dependencies = [
|
||||
"pulldown-cmark",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pxfm"
|
||||
version = "0.1.30"
|
||||
@@ -7257,12 +7149,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.23.45"
|
||||
version = "0.23.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
|
||||
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"log",
|
||||
"once_cell",
|
||||
"rustls-pki-types",
|
||||
"rustls-webpki",
|
||||
@@ -7380,20 +7271,6 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "schema-api"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"prost",
|
||||
"prost-build",
|
||||
"prost-types",
|
||||
"protoc-bin-vendored",
|
||||
"thiserror 2.0.21",
|
||||
"tonic",
|
||||
"tonic-prost",
|
||||
"tonic-prost-build",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scoped-tls"
|
||||
version = "1.0.1"
|
||||
@@ -7869,6 +7746,7 @@ dependencies = [
|
||||
"i-slint-backend-android-activity",
|
||||
"i-slint-backend-linuxkms",
|
||||
"i-slint-backend-selector",
|
||||
"i-slint-backend-winit",
|
||||
"i-slint-common",
|
||||
"i-slint-core",
|
||||
"i-slint-core-macros",
|
||||
@@ -8853,76 +8731,6 @@ version = "1.1.2+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"
|
||||
|
||||
[[package]]
|
||||
name = "tonic"
|
||||
version = "0.14.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"h2",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-timeout",
|
||||
"hyper-util",
|
||||
"percent-encoding",
|
||||
"pin-project",
|
||||
"rustls-native-certs",
|
||||
"socket2",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tokio-stream",
|
||||
"tower",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tonic-build"
|
||||
version = "0.14.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c68f61875ac5293cf72e6c8cf0158086428c82c37229e98c840878f1706b0322"
|
||||
dependencies = [
|
||||
"prettyplease",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tonic-prost"
|
||||
version = "0.14.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"prost",
|
||||
"tonic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tonic-prost-build"
|
||||
version = "0.14.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "654e5643eff75d7f8c99197ce1440ed19a3474eada74c12bbac488b2cafdae27"
|
||||
dependencies = [
|
||||
"prettyplease",
|
||||
"proc-macro2",
|
||||
"prost-build",
|
||||
"prost-types",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"tempfile",
|
||||
"tonic-build",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower"
|
||||
version = "0.5.3"
|
||||
@@ -8931,12 +8739,9 @@ checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"indexmap",
|
||||
"pin-project-lite",
|
||||
"slab",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
@@ -9657,7 +9462,6 @@ dependencies = [
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"tsclientlib",
|
||||
"voelin-core",
|
||||
"voelin-media",
|
||||
"voelin-model",
|
||||
@@ -9682,8 +9486,6 @@ dependencies = [
|
||||
"sonora-simd",
|
||||
"thiserror 2.0.21",
|
||||
"tracing",
|
||||
"tsclientlib",
|
||||
"tsproto-packets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9692,9 +9494,13 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"dirs",
|
||||
"futures",
|
||||
"h2",
|
||||
"hickory-resolver",
|
||||
"http",
|
||||
"httpdate",
|
||||
"md5",
|
||||
"reqwest",
|
||||
"rusqlite",
|
||||
@@ -9714,7 +9520,6 @@ dependencies = [
|
||||
"voelin-gateway-proto",
|
||||
"voelin-media",
|
||||
"voelin-model",
|
||||
"voelin-myts",
|
||||
"voelin-observer",
|
||||
"voelin-platform",
|
||||
"voelin-query",
|
||||
@@ -9768,6 +9573,23 @@ dependencies = [
|
||||
"voelin-model",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "voelin-identity"
|
||||
version = "0.2.0"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=64808ccbb1e3aa10213392724f2f436bc25fd36f#64808ccbb1e3aa10213392724f2f436bc25fd36f"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"base64 0.23.1",
|
||||
"prost",
|
||||
"rcgen",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"voelin-proto",
|
||||
"x509-cert 0.3.0",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "voelin-media"
|
||||
version = "0.1.0"
|
||||
@@ -9818,24 +9640,6 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "voelin-myts"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"aes 0.9.3",
|
||||
"aes-gcm",
|
||||
"base64 0.22.1",
|
||||
"ctr 0.10.1",
|
||||
"pbkdf2",
|
||||
"reqwest",
|
||||
"schema-api",
|
||||
"subtle",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tsproto",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "voelin-observer"
|
||||
version = "0.1.0"
|
||||
@@ -9862,6 +9666,18 @@ dependencies = [
|
||||
"tracing",
|
||||
"windows 0.62.2",
|
||||
"x11rb",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "voelin-proto"
|
||||
version = "0.2.0"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=64808ccbb1e3aa10213392724f2f436bc25fd36f#64808ccbb1e3aa10213392724f2f436bc25fd36f"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"prost",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9872,6 +9688,7 @@ dependencies = [
|
||||
"russh",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"socket2",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tracing",
|
||||
@@ -9886,7 +9703,9 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tracing",
|
||||
"tsclientlib",
|
||||
"voelin-identity",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9906,6 +9725,7 @@ dependencies = [
|
||||
"tracing-subscriber",
|
||||
"tsclientlib",
|
||||
"tsproto-packets",
|
||||
"voelin-media",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9916,7 +9736,6 @@ dependencies = [
|
||||
"chrono",
|
||||
"dirs",
|
||||
"image",
|
||||
"miniz_oxide 0.8.9",
|
||||
"png",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -9931,10 +9750,28 @@ dependencies = [
|
||||
"voelin-core",
|
||||
"voelin-gateway-proto",
|
||||
"voelin-model",
|
||||
"voelin-myts",
|
||||
"voelin-platform",
|
||||
"voelin-query",
|
||||
"voelin-store",
|
||||
"voelin-ui-vm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "voelin-ui-vm"
|
||||
version = "0.0.1-alpha"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"image",
|
||||
"miniz_oxide 0.8.9",
|
||||
"png",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"unicode-segmentation",
|
||||
"voelin-audio",
|
||||
"voelin-core",
|
||||
"voelin-gateway-proto",
|
||||
"voelin-model",
|
||||
"voelin-store",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -11074,6 +10911,17 @@ dependencies = [
|
||||
"spki 0.7.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "x509-cert"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "105ef4642d9cb137ef83d623d0e4bf08b8adf69e9918ca904a174adb6d3d038b"
|
||||
dependencies = [
|
||||
"const-oid 0.10.2",
|
||||
"der 0.8.2",
|
||||
"spki 0.8.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "x509-parser"
|
||||
version = "0.18.1"
|
||||
@@ -11190,9 +11038,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "yoke-derive"
|
||||
version = "0.8.3"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78"
|
||||
checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
|
||||
+11
-3
@@ -2,7 +2,7 @@
|
||||
resolver = "3"
|
||||
# third_party: vendored crates patched in below (not workspace members, so
|
||||
# their own tests and dev-dependencies stay out of our builds).
|
||||
exclude = ["fuzz", "third_party", "third_party/schema-api"]
|
||||
exclude = ["fuzz", "third_party"]
|
||||
members = [
|
||||
"crates/proto/tsproto-types",
|
||||
"crates/proto/tsproto-structs",
|
||||
@@ -17,13 +17,13 @@ members = [
|
||||
"crates/voelin-gateway-proto",
|
||||
"crates/voelin-media",
|
||||
"crates/voelin-model",
|
||||
"crates/voelin-myts",
|
||||
"crates/voelin-observer",
|
||||
"crates/voelin-platform",
|
||||
"crates/voelin-query",
|
||||
"crates/voelin-store",
|
||||
"crates/voelin-stream",
|
||||
"crates/voelin-ui",
|
||||
"crates/voelin-ui-vm",
|
||||
"tools/voelinctl",
|
||||
]
|
||||
default-members = [
|
||||
@@ -38,13 +38,13 @@ default-members = [
|
||||
"crates/voelin-gateway",
|
||||
"crates/voelin-gateway-proto",
|
||||
"crates/voelin-model",
|
||||
"crates/voelin-myts",
|
||||
"crates/voelin-observer",
|
||||
"crates/voelin-platform",
|
||||
"crates/voelin-query",
|
||||
"crates/voelin-store",
|
||||
"crates/voelin-stream",
|
||||
"crates/voelin-ui",
|
||||
"crates/voelin-ui-vm",
|
||||
"tools/voelinctl",
|
||||
]
|
||||
|
||||
@@ -55,6 +55,14 @@ license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/Faumaray/Voelin"
|
||||
publish = false
|
||||
|
||||
[workspace.dependencies]
|
||||
# The protocol repository is private (VoelinProtocol). This is the SSH URL its
|
||||
# docs/development.md names, so that a per-developer .cargo/config.toml [patch]
|
||||
# can point it at a sibling checkout (docs/building.md, "Working with a sibling
|
||||
# VoelinProtocol checkout"). Pinned by commit until the protocol tags a release
|
||||
# that has the account-bound KeyStore (its Phase 2 task 28).
|
||||
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "64808ccbb1e3aa10213392724f2f436bc25fd36f" }
|
||||
|
||||
[workspace.lints.rust]
|
||||
# deny, not forbid: generated code (Slint) needs a local allow.
|
||||
unsafe_code = "deny"
|
||||
|
||||
@@ -41,10 +41,13 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
|
||||
reactions, topics, events, stream directory and administration; the media pipeline for streams
|
||||
(capture → VP8 + Opus → stream, stream → decoder)
|
||||
- `crates/voelin-ui` (`voelin`): Slint desktop app: servers, channel tree with talking indicators,
|
||||
chat tabs (own channel via voice, other channels via relay), connect / observe invisibly, mute, push-to-talk
|
||||
chat tabs (own channel via voice, other channels via relay), connect, observe invisibly (on selecting a server, through its gateway), mute, push-to-talk
|
||||
(in the window and as a global hotkey), audio settings with a level meter, per-client volume, and on
|
||||
TeamSpeak 6 streams: watch in a viewer, share the screen with sound. Desktop and phone layouts
|
||||
from one design system, dark and light themes, text size, emoji ([docs/ui.md](docs/ui.md))
|
||||
- `crates/voelin-ui-vm`: the view models and the app's state behind the UI, with no UI toolkit: engine state
|
||||
as plain rows and forms, chat formatting, the Twemoji archive, and what the settings pages and the
|
||||
Stream Studio decide; `voelin-ui` puts them on Slint windows ([docs/ui.md](docs/ui.md))
|
||||
- `crates/voelin-stream`: TeamSpeak 6 streams: stream commands and notifications, JSON signalling,
|
||||
WebRTC peers (str0m) with host and STUN candidates. A live test streams VP8 + Opus between two
|
||||
clients through a TS6 server
|
||||
|
||||
+4
-9
@@ -21,16 +21,15 @@ dependencies to their projects (tell us too if this client is affected).
|
||||
|
||||
## What the client stores
|
||||
|
||||
There is no telemetry and no account with us. The only outside account is
|
||||
the optional myTeamSpeak sign-in (desktop), which talks to TeamSpeak's
|
||||
service at `clientapi.myteamspeak.com`: at sign-in, when a saved session is
|
||||
checked at start, and at sign-out.
|
||||
There is no telemetry and no account with us, and the client signs in to no
|
||||
account service. (Builds before this one had an optional myTeamSpeak sign-in;
|
||||
its saved session stays in the keyring, item `myts/session`, until you delete
|
||||
it there.)
|
||||
|
||||
| What | Where | Protection |
|
||||
|---|---|---|
|
||||
| Identities (TeamSpeak private keys) | SQLite database `client.db` in the data directory (`~/.local/share/voelin`, Flatpak `~/.var/app/<app id>/data/voelin`, `%APPDATA%\voelin`, Android app storage) | File permissions of the user account only; not encrypted. An identity is the account on every server that knows it: back it up, do not share the file |
|
||||
| Server and ServerQuery passwords | OS keyring (Secret Service, Windows Credential Manager, Android Keystore), service `voelin` | Keyring; kept in memory for the session only when there is no keyring |
|
||||
| myTeamSpeak account (optional sign-in, desktop): session, renewal and one-time-code renewal tokens, device id, email, username, account id and the account's private signing key | OS keyring, service `voelin`, item `myts/session` | Keyring only: without one the sign-in is not kept, not even in memory. Passwords and one-time codes are never stored. Signing out deletes the item and ends the session at TeamSpeak |
|
||||
| Bookmarks, settings, chat history | `client.db` | File permissions; history stays until deleted |
|
||||
| Crash reports (opt-in) | `crash-reports` in the state directory (`~/.local/state/voelin`, `%LOCALAPPDATA%\voelin`) | Local only, never uploaded. They contain the panic message and a backtrace, which may include server addresses or names; review before attaching one to an issue |
|
||||
| OpenH264 (opt-in) | Downloaded from Cisco into the app's directories | Loaded only if its SHA-256 matches a known Cisco build |
|
||||
@@ -40,10 +39,6 @@ checked at start, and at sign-out.
|
||||
- **Voice connections** use the TeamSpeak protocol's encryption. The server
|
||||
and its admins see what any client sees: your nickname, identity, IP
|
||||
address, channel and messages.
|
||||
- **Signed in to myTeamSpeak**, every voice server you join also gets your
|
||||
account's myTeamSpeak id with a proof signed by the account, which links
|
||||
your visits to different servers to one account. Signing out clears it on
|
||||
the servers you are on.
|
||||
- **Streams (TeamSpeak 6)** are peer-to-peer WebRTC (DTLS-SRTP). Viewers and
|
||||
streamers exchange ICE candidates, so **they learn each other's IP
|
||||
addresses**, including local network addresses. Only watch and share
|
||||
|
||||
+93
-836
File diff suppressed because it is too large.
Load diff
+2
-1
@@ -3,7 +3,8 @@
|
||||
|
||||
<!-- From about-assets.md, appended by scripts/notices.sh. -->
|
||||
|
||||
The user interface bundles these assets (in crates/voelin-ui):
|
||||
The user interface bundles these assets (in crates/voelin-ui, the Twemoji
|
||||
archive in crates/voelin-ui-vm):
|
||||
|
||||
- Inter (the UI font), Copyright (c) 2016 The Inter Project Authors, under
|
||||
the SIL Open Font License 1.1 (OFL-1.1; text below).
|
||||
|
||||
@@ -53,13 +53,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
````
|
||||
|
||||
## schema-api
|
||||
|
||||
The account client uses message bindings and session helpers from the local
|
||||
schema-api 0.1.0 snapshot vendored under third_party/schema-api. The supplied
|
||||
snapshot has no declared license or license file; no MIT or Apache license is
|
||||
implied for it or its supplied schemas. See its VOELIN-PATCH.md for provenance.
|
||||
|
||||
## Native libraries
|
||||
|
||||
- Opus (libopus), compiled into the app: BSD-3-Clause, Copyright 2001-2023
|
||||
|
||||
@@ -129,3 +129,21 @@ against or offered back to upstream.
|
||||
Tests cover an independent signature vector, persistence validation/redaction,
|
||||
wire field names, clearing and reconnect snapshot replacement. The account
|
||||
UUID and the ordinary server identity remain separate.
|
||||
15. **myTeamSpeak presentation, TeamSpeak 6** (`tsproto/src/license.rs`,
|
||||
`tsproto/src/myts.rs`, `tsclientlib/src/myts.rs`, `tsclientlib/src/lib.rs`,
|
||||
`tsproto-packets/src/packets.rs`, `tsproto-structs/declarations/Book.toml`).
|
||||
License block types 4–7 (Token, License_Sign, MyTsId_Sign, Updater), which
|
||||
carry nothing after the header. `myts::Certificate` checks a myTeamSpeak
|
||||
certificate chain as a TeamSpeak 6 server does: leaf type, validity window,
|
||||
key derived from a given root, cofactorless Ed25519 with a reduced S;
|
||||
`Identity::id_bytes` and `public_signature_certificate`. `MytsData` holds the
|
||||
avatar and the badges, each with the certificate that verifies it, and the
|
||||
User Tag; `MytsData::updates` builds `updatemytsdata` (split by certificate,
|
||||
bare parameters to clear) and `clientupdate client_user_tag`, which
|
||||
`Connection::send_myts_update` and `send_user_tag` send. The escaped writer
|
||||
also escapes `\a` and `\b`, as TeamSpeak does for binary values. Book:
|
||||
`Client::my_team_speak_avatar`, `my_team_speak_id` and `signed_badges`.
|
||||
16. **Privilege key when connecting** (`tsclientlib/src/lib.rs`, "Voelin patch").
|
||||
`ConnectOptions::default_token` sets `client_default_token` of `clientinit`,
|
||||
which upstream always sent empty, so a privilege key (a bookmark's, or the
|
||||
`token=` of a `ts3server://` link) can be used on connect.
|
||||
@@ -61,6 +61,7 @@ pub use ts_bookkeeping::messages::s2c::InMessage;
|
||||
pub use ts_bookkeeping::*;
|
||||
pub use tsproto::resend::{ConnectionStats, PacketStat};
|
||||
pub use tsproto::Identity;
|
||||
pub use myts::{MytsData, MytsUpdate, Signed, UserTag};
|
||||
pub use tsproto_types::errors::Error as TsError;
|
||||
|
||||
/// Wait this time for initserver, in seconds.
|
||||
@@ -392,6 +393,7 @@ impl Connection {
|
||||
channel: None,
|
||||
channel_password: None,
|
||||
password: None,
|
||||
default_token: None,
|
||||
input_muted: false,
|
||||
output_muted: false,
|
||||
input_hardware_enabled: true,
|
||||
@@ -556,7 +558,7 @@ impl Connection {
|
||||
version_sign: Cow::Borrowed(client_version_sign.as_ref()),
|
||||
client_key_offset: counter,
|
||||
phonetic_name: "".into(),
|
||||
default_token: "".into(),
|
||||
default_token: Cow::Borrowed(options.default_token.as_deref().unwrap_or_default()),
|
||||
hardware_id: Cow::Borrowed(options.hardware_id.as_ref()),
|
||||
badges: None,
|
||||
signed_badges: None,
|
||||
@@ -1730,6 +1732,7 @@ pub struct ConnectOptions {
|
||||
channel: Option<Cow<'static, str>>,
|
||||
channel_password: Option<Cow<'static, str>>,
|
||||
password: Option<Cow<'static, str>>,
|
||||
default_token: Option<Cow<'static, str>>,
|
||||
input_muted: bool,
|
||||
output_muted: bool,
|
||||
input_hardware_enabled: bool,
|
||||
@@ -1944,6 +1947,20 @@ impl ConnectOptions {
|
||||
self
|
||||
}
|
||||
|
||||
/// Use a privilege key (token) when connecting.
|
||||
/// Voelin patch: sent as `client_default_token` in `clientinit`.
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// # use tsclientlib::Connection;
|
||||
/// let opts = Connection::build("localhost").default_token("My privilege key");
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn default_token<S: Into<Cow<'static, str>>>(mut self, token: S) -> Self {
|
||||
self.default_token = Some(token.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Connect to the server in a muted state.
|
||||
///
|
||||
/// # Example
|
||||
@@ -2064,6 +2081,10 @@ impl ConnectOptions {
|
||||
#[inline]
|
||||
pub fn get_password(&self) -> Option<&str> { self.password.as_ref().map(AsRef::as_ref) }
|
||||
#[inline]
|
||||
pub fn get_default_token(&self) -> Option<&str> {
|
||||
self.default_token.as_ref().map(AsRef::as_ref)
|
||||
}
|
||||
#[inline]
|
||||
pub fn get_input_muted(&self) -> bool { self.input_muted }
|
||||
#[inline]
|
||||
pub fn get_output_muted(&self) -> bool { self.output_muted }
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Voelin patch: connection-bound myTeamSpeak proof and live account changes.
|
||||
|
||||
use base64::prelude::*;
|
||||
use tsproto::myts::Identity;
|
||||
use tsproto_packets::packets::{Direction, Flags, OutCommand, PacketType};
|
||||
|
||||
@@ -14,7 +15,184 @@ impl ConnectOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a voice server is shown of the myTeamSpeak account (TeamSpeak 6)
|
||||
/// besides its myTS ID, as myTeamSpeak signed it for that ID: its avatar,
|
||||
/// its badges and its User Tag. The server checks the avatar and the badges
|
||||
/// with the one certificate of each `updatemytsdata` and shows nothing of
|
||||
/// what does not verify, so each comes with the certificate that verifies
|
||||
/// it. Viewers check the User Tag's token themselves.
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
pub struct MytsData {
|
||||
/// The raw myTS ID all of it is signed for: shown only on a connection
|
||||
/// that presents it.
|
||||
pub myts_id: Vec<u8>,
|
||||
/// An `AvatarData` as it came (`client_myteamspeak_avatar`).
|
||||
pub avatar: Signed,
|
||||
/// A `UserBadgesSignedList`, the badges chosen to show, in order
|
||||
/// (`client_signed_badges`).
|
||||
pub badges: Signed,
|
||||
/// The ids of those badges, as in the list: the server publishes the
|
||||
/// ones that verify.
|
||||
pub badge_ids: Vec<String>,
|
||||
pub user_tag: Option<UserTag>,
|
||||
}
|
||||
|
||||
/// Something signed and the certificate that verifies it; empty: nothing.
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
pub struct Signed {
|
||||
pub certificate: Vec<u8>,
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
/// The User Tag (`client_user_tag`): the account's primary chat identifier
|
||||
/// and the token that proves it (a `MatrixIdentifierToken` as it came).
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
pub struct UserTag {
|
||||
pub tag: String,
|
||||
pub token: Vec<u8>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for MytsData {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("MytsData")
|
||||
.field("avatar", &self.avatar.data.len())
|
||||
.field("badges", &self.badge_ids)
|
||||
.field("user_tag", &self.user_tag.as_ref().map(|t| &t.tag))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Signed {
|
||||
pub fn is_empty(&self) -> bool { self.data.is_empty() }
|
||||
}
|
||||
|
||||
impl UserTag {
|
||||
/// `client_user_tag` as the official client sets it: compact JSON with
|
||||
/// the token (standard base64), the tag and when it was set (`updated`,
|
||||
/// milliseconds since 1970), in this order.
|
||||
pub fn value(&self, updated_ms: i64) -> String {
|
||||
let mut tag = String::with_capacity(self.tag.len());
|
||||
for c in self.tag.chars() {
|
||||
match c {
|
||||
'"' => tag.push_str("\\\""),
|
||||
'\\' => tag.push_str("\\\\"),
|
||||
'\n' => tag.push_str("\\n"),
|
||||
'\r' => tag.push_str("\\r"),
|
||||
'\t' => tag.push_str("\\t"),
|
||||
'\u{8}' => tag.push_str("\\b"),
|
||||
'\u{c}' => tag.push_str("\\f"),
|
||||
c if u32::from(c) < 0x20 => tag.push_str(&format!("\\u{:04x}", u32::from(c))),
|
||||
c => tag.push(c),
|
||||
}
|
||||
}
|
||||
format!(
|
||||
"{{\"myts_token\":\"{}\",\"tag\":\"{}\",\"updated\":{}}}",
|
||||
BASE64_STANDARD.encode(&self.token),
|
||||
tag,
|
||||
updated_ms
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// One `updatemytsdata`: a value is shown (checked with `certificate`), an
|
||||
/// empty one clears what is shown, `None` leaves it as it is.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct MytsUpdate {
|
||||
pub certificate: Vec<u8>,
|
||||
pub badges: Option<Vec<u8>>,
|
||||
pub avatar: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// What to do about one part of what is shown.
|
||||
enum Part<'a> {
|
||||
Keep,
|
||||
Show(&'a Signed),
|
||||
Clear,
|
||||
}
|
||||
|
||||
fn part<'a>(wanted: &'a Signed, shown: &Signed, again: bool) -> Part<'a> {
|
||||
if wanted.is_empty() {
|
||||
if shown.is_empty() { Part::Keep } else { Part::Clear }
|
||||
} else if again || wanted != shown {
|
||||
Part::Show(wanted)
|
||||
} else {
|
||||
Part::Keep
|
||||
}
|
||||
}
|
||||
|
||||
impl MytsData {
|
||||
/// The `updatemytsdata` commands that make a server that shows `shown`
|
||||
/// show `self`. `again`: everything once more, after a new account proof
|
||||
/// (`updatemytsid`), which the server does not check them for again.
|
||||
/// The avatar and the badges go together when one certificate verifies
|
||||
/// both (certificate, badges, avatar, as the official client sends
|
||||
/// them), apart otherwise; clearing needs no certificate.
|
||||
pub fn updates(&self, shown: &MytsData, again: bool) -> Vec<MytsUpdate> {
|
||||
let avatar = part(&self.avatar, &shown.avatar, again);
|
||||
let badges = part(&self.badges, &shown.badges, again);
|
||||
let mut updates = Vec::new();
|
||||
match (&badges, &avatar) {
|
||||
(Part::Show(badges), Part::Show(avatar)) if badges.certificate == avatar.certificate => {
|
||||
updates.push(MytsUpdate {
|
||||
certificate: avatar.certificate.clone(),
|
||||
badges: Some(badges.data.clone()),
|
||||
avatar: Some(avatar.data.clone()),
|
||||
});
|
||||
}
|
||||
_ => {
|
||||
if let Part::Show(avatar) = avatar {
|
||||
updates.push(MytsUpdate {
|
||||
certificate: avatar.certificate.clone(),
|
||||
avatar: Some(avatar.data.clone()),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
if let Part::Show(badges) = badges {
|
||||
updates.push(MytsUpdate {
|
||||
certificate: badges.certificate.clone(),
|
||||
badges: Some(badges.data.clone()),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let clear_badges = matches!(badges, Part::Clear);
|
||||
let clear_avatar = matches!(avatar, Part::Clear);
|
||||
if clear_badges || clear_avatar {
|
||||
updates.push(MytsUpdate {
|
||||
certificate: Vec::new(),
|
||||
badges: if clear_badges { Some(Vec::new()) } else { None },
|
||||
avatar: if clear_avatar { Some(Vec::new()) } else { None },
|
||||
});
|
||||
}
|
||||
updates
|
||||
}
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
/// Show the server the account's avatar or badges, or clear them
|
||||
/// (`updatemytsdata`), as the official client does once connected and
|
||||
/// after a sign-in, after the account proof (`updatemytsid`). The server
|
||||
/// answers before the result: the own client's
|
||||
/// `client_myteamspeak_avatar` and `client_signed_badges`, empty for what
|
||||
/// did not verify. Await the returned handle's
|
||||
/// `StreamItem::MessageResult` for the answer.
|
||||
pub fn send_myts_update(&mut self, update: &MytsUpdate) -> Result<MessageHandle> {
|
||||
if !matches!(self.state, ConnectionState::Connected { .. }) {
|
||||
return Err(Error::NotConnected);
|
||||
}
|
||||
self.send_command_with_result(data_packet(update))
|
||||
}
|
||||
|
||||
/// Set the User Tag (`clientupdate client_user_tag`), as built by
|
||||
/// [`UserTag::value`]; empty clears it. TeamSpeak 6 servers only.
|
||||
pub fn send_user_tag(&mut self, value: &str) -> Result<MessageHandle> {
|
||||
if !matches!(self.state, ConnectionState::Connected { .. }) {
|
||||
return Err(Error::NotConnected);
|
||||
}
|
||||
self.send_command_with_result(user_tag_packet(value))
|
||||
}
|
||||
|
||||
/// Publish a connection-bound account proof, or clear the account identity.
|
||||
///
|
||||
/// Always updates the reconnect options, even if currently disconnected or
|
||||
@@ -34,6 +212,29 @@ impl Connection {
|
||||
}
|
||||
}
|
||||
|
||||
/// The values are the raw bytes with TeamSpeak's escaping only (no
|
||||
/// base64), as the official client sends them; an empty one is the bare
|
||||
/// name, which clears.
|
||||
fn data_packet(update: &MytsUpdate) -> OutCommand {
|
||||
let mut packet =
|
||||
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "updatemytsdata");
|
||||
packet.write_bin_arg("myts_certificate", &update.certificate);
|
||||
if let Some(badges) = &update.badges {
|
||||
packet.write_bin_arg("myts_signed_badge", badges);
|
||||
}
|
||||
if let Some(avatar) = &update.avatar {
|
||||
packet.write_bin_arg("myts_avatar", avatar);
|
||||
}
|
||||
packet
|
||||
}
|
||||
|
||||
fn user_tag_packet(value: &str) -> OutCommand {
|
||||
let mut packet =
|
||||
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "clientupdate");
|
||||
packet.write_arg("client_user_tag", &value);
|
||||
packet
|
||||
}
|
||||
|
||||
fn update_packet(identity: Option<&Identity>, iv: &[u8; 64]) -> OutCommand {
|
||||
let mut packet =
|
||||
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "updatemytsid");
|
||||
@@ -50,6 +251,99 @@ fn update_packet(identity: Option<&Identity>, iv: &[u8; 64]) -> OutCommand {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn signed(certificate: &[u8], data: &[u8]) -> Signed {
|
||||
Signed { certificate: certificate.to_vec(), data: data.to_vec() }
|
||||
}
|
||||
|
||||
fn wire(update: &MytsUpdate) -> Vec<u8> { data_packet(update).into_packet().content().to_vec() }
|
||||
|
||||
#[test]
|
||||
fn account_data_goes_raw_and_escaped() {
|
||||
let update = MytsUpdate {
|
||||
certificate: b"a b/c|d\\\x07\x08\x00\xff".to_vec(),
|
||||
badges: Some(vec![0x0a, 0x01, b' ']),
|
||||
avatar: Some(vec![0x0a, 0x02, b'h', b'i']),
|
||||
};
|
||||
assert_eq!(
|
||||
wire(&update),
|
||||
b"updatemytsdata myts_certificate=a\\sb\\/c\\pd\\\\\\a\\b\x00\xff \
|
||||
myts_signed_badge=\\n\x01\\s myts_avatar=\\n\x02hi"
|
||||
);
|
||||
// Without badges: the certificate and the avatar.
|
||||
let update = MytsUpdate { badges: None, ..update };
|
||||
assert!(!wire(&update).windows(17).any(|w| w == b"myts_signed_badge"));
|
||||
// Clearing: bare names, no certificate needed.
|
||||
let clear = MytsUpdate {
|
||||
certificate: Vec::new(),
|
||||
badges: Some(Vec::new()),
|
||||
avatar: Some(Vec::new()),
|
||||
};
|
||||
assert_eq!(wire(&clear), b"updatemytsdata myts_certificate myts_signed_badge myts_avatar");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_one_certificate_verifies_goes_together() {
|
||||
let data = MytsData {
|
||||
myts_id: vec![1; 33],
|
||||
avatar: signed(b"C", b"avatar"),
|
||||
badges: signed(b"C", b"badges"),
|
||||
badge_ids: vec!["b1".into()],
|
||||
user_tag: None,
|
||||
};
|
||||
let none = MytsData::default();
|
||||
assert_eq!(data.updates(&none, false), [MytsUpdate {
|
||||
certificate: b"C".to_vec(),
|
||||
badges: Some(b"badges".to_vec()),
|
||||
avatar: Some(b"avatar".to_vec()),
|
||||
}]);
|
||||
assert_eq!(
|
||||
wire(&data.updates(&none, false)[0]),
|
||||
b"updatemytsdata myts_certificate=C myts_signed_badge=badges myts_avatar=avatar"
|
||||
);
|
||||
// Unchanged: nothing, unless after a new account proof.
|
||||
assert!(data.updates(&data, false).is_empty());
|
||||
assert_eq!(data.updates(&data, true).len(), 1);
|
||||
// Two certificates: two commands, each with its own.
|
||||
let apart = MytsData { badges: signed(b"D", b"badges"), ..data.clone() };
|
||||
let updates: Vec<_> = apart.updates(&none, false).iter().map(wire).collect();
|
||||
assert_eq!(updates, [
|
||||
b"updatemytsdata myts_certificate=C myts_avatar=avatar".to_vec(),
|
||||
b"updatemytsdata myts_certificate=D myts_signed_badge=badges".to_vec(),
|
||||
]);
|
||||
// Only what changed.
|
||||
let newer = MytsData { avatar: signed(b"C", b"newer"), ..data.clone() };
|
||||
let updates: Vec<_> = newer.updates(&data, false).iter().map(wire).collect();
|
||||
assert_eq!(updates, [b"updatemytsdata myts_certificate=C myts_avatar=newer".to_vec()]);
|
||||
// What is no longer there is cleared; what never was is left alone.
|
||||
let fewer = MytsData { badges: Signed::default(), ..data.clone() };
|
||||
let updates: Vec<_> = fewer.updates(&data, true).iter().map(wire).collect();
|
||||
assert_eq!(updates, [
|
||||
b"updatemytsdata myts_certificate=C myts_avatar=avatar".to_vec(),
|
||||
b"updatemytsdata myts_certificate myts_signed_badge".to_vec(),
|
||||
]);
|
||||
let updates: Vec<_> = none.updates(&data, true).iter().map(wire).collect();
|
||||
assert_eq!(updates, [b"updatemytsdata myts_certificate myts_signed_badge myts_avatar".to_vec()]);
|
||||
assert!(none.updates(&none, true).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_user_tag_is_set_as_the_official_client_sets_it() {
|
||||
let tag = UserTag { tag: "alex@myteamspeak.com".into(), token: vec![0xfb, 0xff, 0x01, 0x02] };
|
||||
assert_eq!(
|
||||
tag.value(1_759_740_000_123),
|
||||
r#"{"myts_token":"+/8BAg==","tag":"alex@myteamspeak.com","updated":1759740000123}"#
|
||||
);
|
||||
let odd = UserTag { tag: "a\"b\\c\n\u{1}é".into(), token: Vec::new() };
|
||||
assert_eq!(odd.value(1), r#"{"myts_token":"","tag":"a\"b\\c\n\u0001é","updated":1}"#);
|
||||
// TeamSpeak's escaping on the wire; empty clears.
|
||||
let packet = user_tag_packet(&tag.value(5)).into_packet();
|
||||
assert_eq!(
|
||||
packet.content(),
|
||||
&br#"clientupdate client_user_tag={"myts_token":"+\/8BAg==","tag":"alex@myteamspeak.com","updated":5}"#[..]
|
||||
);
|
||||
assert_eq!(user_tag_packet("").into_packet().content(), b"clientupdate client_user_tag");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_contains_no_previous_account_proof() {
|
||||
let packet = update_packet(None, &[0; 64]).into_packet();
|
||||
|
||||
@@ -968,6 +968,10 @@ impl io::Write for EscapedWriter<'_> {
|
||||
self.0.reserve(buf.len());
|
||||
for c in buf {
|
||||
match c {
|
||||
// Voelin patch: \a and \b as TeamSpeak escapes them (binary
|
||||
// values, e.g. `updatemytsdata`).
|
||||
b'\x07' => self.0.extend_from_slice(b"\\a"),
|
||||
b'\x08' => self.0.extend_from_slice(b"\\b"),
|
||||
b'\x0b' => self.0.extend_from_slice(b"\\v"),
|
||||
b'\x0c' => self.0.extend_from_slice(b"\\f"),
|
||||
b'\\' => self.0.extend_from_slice(b"\\\\"),
|
||||
|
||||
@@ -192,6 +192,9 @@ properties = [
|
||||
{ name="InheritedChannelGroupFromChannel", type="ChannelId" },
|
||||
{ name="Badges", type="str" },
|
||||
{ name="UserTag", type="str", opt=true },
|
||||
{ name="MyTeamSpeakAvatar", type="str", opt=true, doc="`<state>,<url>;…` of the myTeamSpeak avatar (TeamSpeak 6)" },
|
||||
{ name="MyTeamSpeakId", type="str", opt=true, doc="The myTeamSpeak ID the server accepted (base64), empty without one" },
|
||||
{ name="SignedBadges", type="str", opt=true, doc="Comma-separated ids of the myTeamSpeak badges the server verified (TeamSpeak 6)" },
|
||||
{ name="PermissionHints", type="ClientPermissionHint", opt=true },
|
||||
{ name="OptionalData", type="OptionalClientData", opt=true },
|
||||
{ name="ConnectionData", type="ConnectionClientData", opt=true },
|
||||
|
||||
@@ -1414,4 +1414,126 @@ version,platform,hash
|
||||
3.?.? [Build: 5680278000],Linux,Hjd+N58Gv3ENhoKmGYy2bNRBsNNgm5kpiaQWxOj5HN2DXttG6REjymSwJtpJ8muC2gSwRuZi0R+8Laan5ts5CQ==
|
||||
3.?.? [Build: 5680278000],OS X,SttEnjoWE8jqIM6BOHSfiZP9DGjW0EP/ajU4bdKqgGMV4aYq/kzwVA9gxbmdIzV4lbaokvXBqrRjfBHrTVh8Cg==
|
||||
3.?.? [Build: 5680278000],Windows,DX5NIYLvfJEUjuIbCidnoeozxIDRRkpq3I9vVMBmE9L2qnekOoBzSenkzsg2lC9CMv8K5hkEzhr2TYUYSwUXCg==
|
||||
3.?.? [Build: 5680278000] DEBUG,Windows,FaA10gndI44f19ZThYJX2OSM8ESrx9/vJ2uY+rON4enzzPsPR9kiPhsUXtMcC5szzTu6F/vLCiNNEhCr70CKCQ==
|
||||
3.?.? [Build: 5680278000] DEBUG,Windows,FaA10gndI44f19ZThYJX2OSM8ESrx9/vJ2uY+rON4enzzPsPR9kiPhsUXtMcC5szzTu6F/vLCiNNEhCr70CKCQ==
|
||||
3.6.0 [Build: 1668022263],Windows,jNUeF6ydYPJp6CpoA2Nm8FcmxPTwj8bFJmmzo/Ch2B9L2CU2rrgLJedcQM3NjAncESYYywUiFR0+BsljvaTNAQ==
|
||||
5.0.0-qa-74-5 [Build: 1680085518],Windows,/X5xXLBPrLClWkivAnMJCz+QIBmFk9fFie8sNg69OdN/xwBQrX6naf2IehfxLdd+BBWX/5TsDjuPJqJwhK1FBg==
|
||||
5.0.0-qa-74-7 [Build: 1681481733],Windows,4qdm8R3gNHlXDV9PS2CtV3Fe9SN7Mjgt82X+iZmqwMXk9B0g9vCyK62G7h2nr/qcqSopPXR4652xMsSQPYVvDQ==
|
||||
3.6.0 [Build: 1681728436],OS X,MZzEbAN51fl7FGiF51T32nHz5tySXH3te4EEZip5rImRNX1Ey3bBQkahN1PYhURNAQxAtIupczX5iGMmvKm4DA==
|
||||
5.0.0-qa-74-8 [Build: 1681821920],Windows,wBuvBhPgbvXmtEOavMpF/6X7xvHkd0PcrNmob7nSr5trxi5HFGjzvOZU19p56yzOStI077LvVJcQtjVha2uXCA==
|
||||
5.0.0-qa-74-10 [Build: 1682065994],Windows,fCODC/wSy5xu9VXPjK3MsRur4MqN/mSLcP/DdbQ2u/KNgQmpuQEsVelmbrf5AvJUQ9YhmXyx8aMvTnG9kHSnCQ==
|
||||
5.0.0-qa-dc-1 [Build: 1682080978],Windows,0p63hM9RbR65x093OWBlS9g0We6lNfYA+IWN99TZ23HXzWXuvfukMK6lIviHJkNSFWCBxhGQFmFi9lttH00vCA==
|
||||
5.0.0-qa-74-11 [Build: 1682337867],Windows,BhUfmE4EX5h9gjKKtfO1JQ61sIdzZfm1IcvA4FNU8BtmA2DSzUJ9uDWFrq60h7lh33wkktDCzlXL7j8PNQChCg==
|
||||
5.0.0-qa-74-13 [Build: 1682589154],Windows,4OMk6jcMvJc/P3zaojn8+laRQzG/vnmEkWEmTpQzIsTcPzKOu5irT82YpOtlp+BIxFDGb8onygu/turJjHLiDA==
|
||||
5.0.0-qa-74-14 [Build: 1682680770],Windows,bwZm9gRSoUSRTWCcc1N0ZuKs+xznjBKErt3myq9YlXzdC/jkn4miNoinG60Ynbsp1JkU8tAVKy4v8HUBLictAg==
|
||||
5.0.0-qa-74-15 [Build: 1683039954],Windows,MFemYXY5GGg2OYhdRzdhpkn9ujzOMMCZA8QGlPV1GUbhjjtjXuMw5+ydEzLwcgZYpFTod3N6CEz/b/aXwWeyCQ==
|
||||
3.6.0 [Build: 1683203743],Linux,ao52xPYBI8qe57kJJ6KQgQPr0J9w7BhGikkFMqs7pGpsrxLK9ghzOlbu5IZsdct3tNw88S2YB0oFmcCWlx+hCA==
|
||||
3.6.0 [Build: 1683203743],OS X,w/rKVPUul3im2KxVqvL8udZf/o0Yre+92bvACj8hU1x5aNtQkvodXo7CML+4mM6EgifiVCyI8kyo6BtbfeF7Ag==
|
||||
3.6.0 [Build: 1683203743],Windows,Ha73fVhy6+r06Zh3CCx8RVJ1HtHCaABNnTfFbjQPy0dm/e79JFIPZgeC5IvJBltwaiBic/9M+aKBrt+7sNxNDw==
|
||||
5.0.0-qa-74-17 [Build: 1683295507],Windows,hpDc2gHUCHv3HUA1nBray8U8Re/d9XvDUHZkefwMkgeL8L6KizWeo7vZzFguQLYpRPr20B4h0d/A8NAxYxfqAA==
|
||||
5.0.0-beta74 [Build: 1683627550],Linux,M5TTHH2J1erTQKBElj0dz4Lm9N4erZuHxZNjNlbJjDxRC8CYnziveIW0j8DY8NeQaSKHeCTXoL5pDakZtvAODQ==
|
||||
5.0.0-beta74 [Build: 1683627550],macOS,EmwreqEhVhmpGrjPKyNjwuEdWKF+uGTX0syXkq57+klgtcNw9lddPm9lodLTdB5spPGlsx0CJQySvEXlWyXNDg==
|
||||
5.0.0-beta74 [Build: 1683627550],Windows,pipm1uaijQDJKPZgRkhjyLsLG/W9KnjEDWNGvqUkUrSuqrUvfEG4OUsdTOReMb+FJp4xz82n3cwd4HExO5k3Dw==
|
||||
5.0.0-qa-tr-1 [Build: 1683731563],Windows,HmBOKipdW28prdI2FFdmBu/mMXui+zdC0G7769F3bW+nVRfNoVtvJhSUx7/UDeQ9ghHbUIW6q2lCxnQLzsIRCg==
|
||||
3.6.0 [Build: 1683804569],Linux,CqbjoDdeYd83t/u9YUtlQf4rDIf6yEnFInF6nq7GcO02tRXBQlppxHd/ziaTdlpwYrha00goKb2GGWwdrNhFAA==
|
||||
3.6.0 [Build: 1683804569],OS X,sT6ej/41Qk3T0LfXl3+VSm3J7Ck4M/OCTWIRundvOHBRodGLWJtddZuQu7IlXNr9mbJfklarQ4XyyXvXMdjvCw==
|
||||
3.6.0 [Build: 1683804569],Windows,PesaPHU3+aiZMUPzpq8UBKjck77jLw9N+hyZq6JjD4baqns5dmKj4sTfSL9/QROyOLqPICZ+fwkSy5iuuMQEAw==
|
||||
5.0.0-qa-75-1 [Build: 1684855710],Windows,LLfl5sHAfsdepvecADQI9/nx98H+jA/r9pe6fq5CqlRY+MCdVbOphiXy7zZerE5h4lIRqcJtEeAJVIXaNu+LDA==
|
||||
5.0.0-qa-75-2 [Build: 1685542148],Windows,Ir/0IAdrK5dDVDlh6gIRwGZe0DFR9vUNf313cLwHTN1EB9nyO2Bq5yoBjZuGYOdNgcbdgQCBzfKNd4ZpCxxSAg==
|
||||
3.6.0 [Build: 1685546268],OS X,i257nbRzdfvBvgW4IeFoCe8KnCDfoIvtNeORVFVPohKWfFajfoBNYTDa/2/jgHbd97Dzqd+hx8t2ZwPPwgR+Bg==
|
||||
5.0.0-beta75-rc1 [Build: 1685698093],Windows,Jkvyb0PGEmS3/lVfr2x7SFlSZMeopxo7JXBHx8m1pWeDL7XdjYoDPOaIJ6UD1hNxY/wv84fgAwt65Ip2AdP1Dw==
|
||||
5.0.0-beta75-rc2 [Build: 1686050172],Windows,BcULgPFoo2+QTsjD88VH5rONZcABm32fgd5jBNbdkxTaERND/CJI4ZBWS30s5WKN9bi3T6LKUOzcLyN6+gfNDQ==
|
||||
5.0.0-beta75-rc3 [Build: 1686126230],macOS,38gec16GTEPCeaVw5qM8tU58HWM0HZ20yROR1foT8TRHqsTvoED2gm07xb6KfSHN3//3k1ErMvuS4emNBohcBA==
|
||||
5.0.0-beta75-rc3 [Build: 1686126230],Windows,1Jj8VSZ8QQ2K5jFiRM2DB6Z12Yi1fFjJ3ng96W/S+zU2VzldrOsuvhO36BOjbWMCcEIWoc45sbHPm+utJtxeAw==
|
||||
3.6.0 [Build: 1686637110],Linux,8eM1WF1E9+8DeS+Zm6IcidGtuTC0+jtrLRkkiIk+GUA91bVOCyYgrUWNFVftZtFEM4qIOICJhLQopVTIwYJOCQ==
|
||||
3.6.0 [Build: 1686637110],Windows,r21r7w+EGu6F6aruzYiuzv2lP5bX8X4TP2xXBH5Wljz3x/VxOxndN84qA9sPn6QJZFQCtzq+iEb0wfFFM7mYCA==
|
||||
3.6.0 [Build: 1686731472],Linux,MKaey6yCAdQDBHl5ERY24N5bz9CsdypGJfpTC5mNPc0s3Z1zeb8c3g9/w/mlRD+qoK3xlCYt3f25oaFMZofMAA==
|
||||
3.6.0 [Build: 1686731472],Windows,KRYqAaQhnKh/NQ4LrOw8+nVA659NDn+IlOB8hhmKZolIOEDSiijCeDoTVf61t/0Z0y1OWlxABS4X7uWRzvhiDw==
|
||||
3.6.0 [Build: 1686736529],Linux,l1LIP8nreS+y33Hp7SmA6M7kJZZI1KbsN1/Rx9hAAL3Wd6PbEwhLIQHXBkfCI8MizWSAl7NDb+UOuNxAL9GoAg==
|
||||
3.6.0 [Build: 1686736529],OS X,EFU7gHd4QZhwmAojg0Tk/tL9dPiFTcWn40R/6YZCrlzX6t0FSPXiAj93OUf1du+qyy2ly4Lrox/M0u4wOhEDBg==
|
||||
3.6.0 [Build: 1686736529],Windows,kRHYyNCdM5rna2v27LyPerCeNd1s76h0KfpLSmLQk3Bzkrg/NCBzpj0WofE1cvbQ2Qm/41d/mUIMxIfXJ/+hCg==
|
||||
3.6.0 [Build: 1686744367],Linux,toUkg41DTfeCfWgqqxSeb8eDzri2PsjRNIcHsFxr0d7nLCTYGoSFfQjme84FjMYtvYloMVAk/gx5Nt+hWE+ZBg==
|
||||
3.6.0 [Build: 1686744367],Windows,VXx9yKF0ZaBMqlU285hPLxaCgH1N8OwKjU52A0EdulFmEeLYYQeJI/7139hno0Ph8kGT6nxoDRKtw0yn9woNAQ==
|
||||
3.6.0 [Build: 1686749764],Linux,TccRBHwn5LSA0lfpa2B42QmfCOiG+MqqyhlOqy5RcuRQNUGPD0e47lUz+Z/8+Gsdc1TPG4+vYlRl8+v2v+26Aw==
|
||||
3.6.0 [Build: 1686749764],OS X,g8H7Op8eCrn0wHutuD/SlmUcZPmkSlFUBhvZpSgm9kuQl4dapzKJq2anI5jDwRs/ooBm/wrIlSiWI6HXuOPZDA==
|
||||
3.6.0 [Build: 1686749764],Windows,gfzG6CfwNYeqrjT68s7ahPd24A/XS0P8LLAB7hrE54MnrlO12RiflD2w69VZ7EYlqnd9GAiVzdGJHCmCFWtlAQ==
|
||||
5.0.0-beta75-rc4 [Build: 1687777367],Linux,DCZXmwc6xocEuzvS+f+qyQLwN8FLdNqyDTAjdOfy1y8JeO8VmIlNwRFd7X0D0Q51kqPNPIB7Jbh4yiwySHjhDw==
|
||||
5.0.0-beta75-rc4 [Build: 1687777367],macOS,xgV8yX/XS3qVXshur/PbsquRIbPvz3w+hJL905nQQBwbniSGvKxAUcTJompBgECG989hf6nW+2GApbf8p70RBw==
|
||||
5.0.0-beta75-rc4 [Build: 1687777367],Windows,wIGrljvdCMZX3XJoe0rWTA/nNZuXVC6z8kUvDw1gi9YxyM6AxmsleqOzjZ3zY5Ii7cRU8slxNAh4ERLcHEPQDg==
|
||||
5.0.0-beta75-rc5 [Build: 1687944933],Windows,1fQu13pX9jdR5oJ4yaqasfoWrcySvwocstrOQOZLZjB+0nUtKMYW4Kp2DYHuIoTlvuWiiF7pYc7YK4bOUWdlAA==
|
||||
3.6.1 [Build: 1689766945],Linux,fjR+/+EsahBSG/qGjcTTUVIyn/w7W6h7uy9YUebYzRbtWIxxv69ZD4k7Y4Z1OS9+cuB/Nbtg05J2Upt2oK/qCg==
|
||||
3.6.1 [Build: 1689766945],Windows,+6Tcswj4E40ablTifyXIA3UDEY+359hxjEVx+Tb+xha08CiSwpzSpFndS8GCs8z0QICVKUZBwhVfGfePm00vDw==
|
||||
3.6.1 [Build: 1689949736],Linux,yM9tjby+KBrov9dyNLM1I1PZXDBK2fdwR8ylvKdZJc/DaL5GqnoBAGLkFmzOIl//u8VMbXspCDWb/PbvOS2gAg==
|
||||
3.6.1 [Build: 1689949736],Windows,30JdFX5zLrHx3uKsb55vpdlS6DO36bVRSOewzOlTV70LS4X0dVMZp64EzDZY8ZR2woAAjZ8ZR/rIKt4JlNnKDg==
|
||||
3.6.1 [Build: 1690193193],Linux,UAcE5h5FgPcdChWTtiO816HX8f2qdoDcDEw6crbJ96Yo7rp1Bt+qx/rkKK9bzlVWMhOd4fI7pr++1XaPkEBnAQ==
|
||||
3.6.1 [Build: 1690193193],OS X,P+KOw42V8K0nN5FbGItCaJzrDuWcRgfE3MRzrtbYAhRMTXHzRxvwLkoLM7+vKTW135NtWZlKbZuDAvxgwhSLBg==
|
||||
3.6.1 [Build: 1690193193],Windows,I5uwVK2CZa9aXblVQPUKGbjNYoE2eaUPujK8sVGWAUsPhmGySTvSkP70jrpX8pUgQdtHwUOl3gvrAH6+moNeDQ==
|
||||
5.0.0-beta75-rc7 [Build: 1690443874],Windows,dvpImL6c5RMVxPV/jNNG3DncR8QlQcqWKBQCDiE89KQpZ/q4kRJkAlje0Pgoqk8BT/2WQWaUixqctfOGNPxNBA==
|
||||
3.6.1 [Build: 1690811573],Windows,aWKpb0eAiI6FndcOBw+OixzripgCENMlM5gwKuRhdqtOdWAEYI5Luz8sGQ77yWC1RlQ1llxHcqhjNcJ8qMVcAw==
|
||||
3.6.1 [Build: 1690872913],Windows,+YmPaYUBL4F9+TgxyFhlT8qIi1Ym+So4NNMcuohla/u4kfJCGabZ1vDF4cIOAghIqWfO+bQ0OkORZrCBdpi2Cw==
|
||||
5.0.0-beta75-rc8 [Build: 1690875928],Windows,1xI3XWPzHxz5zD4OIZDvJteHXOHcxliqCGh/lifvzA6Gb+/GhkcPGj5RqmlIHPKHJFAozbB0UhvTuJcTU5HGDg==
|
||||
5.0.0-qa-75-4 [Build: 1690964581],Windows,3o5M5JegEvtXwGHMdhUSR+PbaXTIoinUI1GGgoXrGi2tYNUvaguiYYlsak4z8twpgzp68L0KaoA4nz4DyNX9Aw==
|
||||
3.6.2 [Build: 1690976575],Linux,iSJZ2tmUsUhCuB3G/7SCgM+JNZe3Jb/KSxFNr+0FDgg8r5t4JKGBD0SPl/cdDMqNqXmG9zEHi0XmuVl9lysoCg==
|
||||
3.6.2 [Build: 1690976575],OS X,0VegJZtWI25+RXM3J6jNfskqEgM8f4CyYrrz0IXuSK8azRQ3AMWH7YgSnrotoIX1q7aDhnTulk9eChKSPoKVCQ==
|
||||
3.6.2 [Build: 1690976575],Windows,OyuLO/1bVJtBsXLRWzfGVhNaQd7B9D4QTolZm14DM1uCbSXVvqX3Ssym3sLi/PcvOl+SAUlX6NwBPOsQdwOGDw==
|
||||
5.0.0-qa-75-8 [Build: 1691162334],macOS,jJLCUYbKDDtPB56YGtUSK+EjrY3LxoOAWVLHKIc/Li4UAFNL9iaq5gRvHF+cfJHyGg0keg2SEVr1+TfCEDG4Dw==
|
||||
5.0.0-qa-75-8 [Build: 1691162334],Windows,yLHN6dcol32mrRoi2ZMYDYsn9XPMncp79PwcCHxFC+8CuaxhOSq7/iXUPwhsdqvUQzyvstq1hCaG9/MLn8G/Dg==
|
||||
5.0.0-beta75-rc10 [Build: 1691405422],Windows,ETFP63u2QoQzmb1vHyRC+KxAAZKWq1PEpKfC6ep8A59zptnOtocEbc50wb55GpF7pVv2n5nJP6CV3iv2QauAAA==
|
||||
5.0.0-qa-75-9 [Build: 1691734909],Windows,t0guTMT1lZZI34At9X9kg0/ablk2LEtjePCLXNSCyTGeam3E4l+hjjaLZYx5gFLDX4tQEGqG4Dms96T+xRVTCg==
|
||||
5.0.0-qa-tr-2 [Build: 1691758984],Windows,YmsBwLBmFqrMhlCLGXUcn/qLvHJBrOeg1kRj+xDp7FltLJ6z4G5r6QdPt1sTaalD3TWE9If10i9mQFnP73nCDw==
|
||||
5.0.0-beta75-rc11 [Build: 1692269983],Windows,TraubtepmvLTzCkyZwDgJram2qrdpuPy1hWRhN0ZFwSAnXkBklJjBSMAUO22D/hTAfTeiQaUiFDJThf2aGSJBQ==
|
||||
5.0.0-beta75-rc12 [Build: 1692273792],Linux,UFodfOKNy4uOGnQdL35xlc5XoOkT2xVzn93w2+rshfBQKd63BqCqBcrMDL5We4UGnCdeF7oiUsraWm65qvfDDA==
|
||||
5.0.0-beta75-rc12 [Build: 1692273792],macOS,yRtBZtJrOetbT3IREKlZ7bYCLLDWtl88l6OvbRHsfI0MwgBuaLuZmgA7gAGaNDc4u427XpxD1U4WRRMJ4XXuCA==
|
||||
5.0.0-beta75-rc12 [Build: 1692273792],Windows,fX3auh0DNxFmMmmjKmxJ0bS5T+sI2OActVkppSthJOJ/W1so/WfdxtxavuJgpzFHQ7wqanaJYUajAY0uFnYEDA==
|
||||
5.0.0-qa-75-10 [Build: 1692281089],Windows,6Tn50hZBDK2v1gAfXvnfVsOvCYiZ5O7t9ae/PGIzTQPYJiK+83CCR9F+NrjaNwrwn8U4fHCm0DvF2qrk6FiEDA==
|
||||
5.0.0-qa-75-11 [Build: 1692344346],Windows,XUiXiYpVQ1lvhscQ0T0STLhzFxgUgPD5yRvHnHa+gl0z62xvSnUYMcaulZu+vu7N7Zx2XD0yXwDt1aAWjmSmAQ==
|
||||
5.0.0-qa-75-12 [Build: 1692942703],Windows,eg20cqWFjsdIv3fP37BPzSsEMAabdXgPwE/iZ0nu8JIUFCx+dDPmD+Yezf4f2cbe+w7MEkPoAMKS5cAOYbG9BQ==
|
||||
5.0.0-qa-tr-4 [Build: 1692956820],Windows,B8tNlJlgST8ITvDXO4m0mBmR+fOur02Dr0MbmYcE1LWOWJfQUk2A5Lyni65NEBdJIg6/D3ihc0US27Yd4sFWAA==
|
||||
5.0.0-qa-75-14 [Build: 1693548790],Linux,VFo+uqfuN636vfO2uplN7MxwjcGgZ7C7a8H78PSMBtPYU5KOh86FNgH3g4TefK5suVza384d9DpPK5sjZBVICA==
|
||||
5.0.0-qa-75-14 [Build: 1693548790],Windows,eBIeiZ9RjIlTT9AVkwXsiHsKrvSkGWfILDbts+A5xGDsIU8nFGl77uXjfNqjM6+Ud2Eb6lKk7NVQrmRWs/b7AQ==
|
||||
5.0.0-qa-tr-6 [Build: 1693832989],Linux,7S96m1KKKlB2+x4osdky+gdCUnWTlAaoiOQcsmmXPUxxyS/ypTY7tnYRmo2lj/Hx46aI7R0+Z4+vnHLIY9InCw==
|
||||
5.0.0-qa-tr-6 [Build: 1693832989],Windows,IOoZZnLdprCn572p0GRdOJftjQq12pYODanfyqFy9rG+sSQWmDs4Q7LX5aF/K6oRi1dj31I/BaBKxRhcs0ylAQ==
|
||||
5.0.0-qa-75-16 [Build: 1694525079],Windows,mnve3nHnNHCWJD/v1UucjHwYP5iiMcQYozzkQTxY4SlU3HozJb1Zkq9hhXpnaQHE37TODB+7B/fshVo/yWJIAA==
|
||||
5.0.0-qa-75-17 [Build: 1694593665],Windows,dQxRWH4A/RdhuwMQG2fWtbP8aRLJNs9eGrdSHBEd07MEVA29iyNx6J4Ab9pFvzw8rbxC/QsL20G1LGc0ilz7Dg==
|
||||
5.0.0-qa-75-18 [Build: 1694615531],Windows,qDBmGwpP/bskv03tvqCDvK4xXGVpyS7K6cvu06/yMk5rDd05Dba928UfMNh0/Wub/Xy9MfI5gVdA3kSuXJrnDA==
|
||||
5.0.0-qa-75-19 [Build: 1694699313],Windows,KtR3EavFC3d5PBcKFWt7Gd27B6fAG0k4EevugDzjYs2BCg+PFgeZ1DPAQCw8/k0SzewR7i9x/ZedhPC7pvYmDA==
|
||||
3.6.2 [Build: 1695203293],Linux,p4iF1jZ3ZOz9MEkKSZ2bvnFtm9WmUcQy9mAP//erFE4PF1sB6K1CSANrr+3X4B0aZR0u+K2pjnv8kiKsWKQCBQ==
|
||||
3.6.2 [Build: 1695203293],OS X,SOCkLcsxINIGVc+3OQ5Vrmv2BVNNFA9LX5Jj9tqbIiYv2HU6Z5E8AL5+v5G2LDN0F+U55+uW43ezUoYAr1WuBA==
|
||||
3.6.2 [Build: 1695203293],Windows,4BdaZpdgUSMCuIs8qcloJPNxNlJ4o7QKnxMCRO60mSOTtJZyKjOrGLAmeAEtLIJjcjmdSpycMbQOIV92K2vXAw==
|
||||
5.0.0-beta75-rc13 [Build: 1695397203],macOS,gwgeaGifMO1IIGcPJBbHUklR0m11N+XeuvflfT5CFUh0RE3zbzmV0ehUtg5udX9BU9XxcLh5LsiMQtmUobmUCQ==
|
||||
5.0.0-beta75-rc13 [Build: 1695397203],Windows,dSkrQtjUjxOQmAdQUbi7Z6oQFKPqi6/nsKVpovncQ4hDjQqVsUfoS2NO/XHO+iCwH0De3zrPgPQju3bRiYdzBA==
|
||||
5.0.0-beta75-rc14 [Build: 1696088917],Windows,GoQG+71nd6b9QUv7vECPDAXGcKEWwrW/YbPaQVNhdFwonbKegBPYKUel8rxuGzqR/uJp3EqXEGV0JyQBVXiEBg==
|
||||
5.0.0-beta75-rc14 [Build: 1696489500],Windows,6rCkYTY/IQav+zwrXfu9wFEmeuFcNxuHKBdW5aiblX5a0KpF9wzn0qwwKgjZcrzQiH5+r9tmsoB36KSwdxX1Dg==
|
||||
5.0.0-beta75 [Build: 1696607978],Linux,zk+WtkzXgRWAFIA59ad066AbGsom9QfQW6JpskztbEh4Gri5BlsQ/HKy2xUfQX+7x+A1ukt27BU/6msK7B5bAA==
|
||||
5.0.0-beta75 [Build: 1696607978],macOS,W9THGtchSxG8Q9DmjC72Ah5wcWVH9/+ZxTH3TZKH3E3NsyjaRwMdjgPvfYVaOb3qYq8Se/HxkYqBbyxSJZFBBg==
|
||||
5.0.0-beta75 [Build: 1696607978],Windows,0LhX3/Ss9GxjzXzyW6sNvaIGtivWocu9CDH3k0tOqkm8rjiwwQFTu3dCtGEzgBw89QrCXEcKOmZkbgLpechOAg==
|
||||
5.0.0-beta76-rc1 [Build: 1697033899],macOS,ZjuTP89K3fFgfAHkzg9vbhR+EkSOnkozd1pTXB2MH//jTj9tfyEPwDlzK1TaCV+JKoAsM5WlSmyx//a72S7mDQ==
|
||||
5.0.0-beta76-rc1 [Build: 1697033899],Windows,CLEscmKTzIkTC9VAQAQ1hIN6eOlSaOjuaWE8EqYThv0aunDzxWRBG9MCNQmdLJ8JgtIM6Ng412x46TOoGAmJBg==
|
||||
5.0.0-beta76-rc5 [Build: 1697802195],macOS,0aSd/h3YrLvyhywBXtNf2h1ZfSLkHW3jr33EoIsuL6oBepMSvi0nZI3Gx8j4gmLDXtwxE9+wFqrm2vc5VfYjCQ==
|
||||
5.0.0-beta76-rc5 [Build: 1697802195],Windows,5JXHvuwisq+an9hsgGgA6FW00ENcH5khuMQ1SFyaKgKdByDdvPA7/XbPtxRvUvSUh5brGL4m3CldEQ88ga1mCw==
|
||||
5.0.0-beta76 [Build: 1698243642],Linux,xXggpgd8+q2Ozk/of+0ciH2v/jp1K83EorMbbiI/J6ywpzQVocFyqQUpOjD6Xoh6K2AV2heFQF/cKoJ0aHwABA==
|
||||
5.0.0-beta76 [Build: 1698243642],macOS,Buhg/MoJF/pPldGEsesBUpTj+ClIp4xFXX/n+BcOgIS98D/kdO8pTWbk42f+wx24ALEJRwWZCYunaLFXF0iJDA==
|
||||
5.0.0-beta76 [Build: 1698243642],Windows,zV72PUBNtH7bblwdldd6t/o8hprjepbfR7CbzQCehaYUTID5y/W4IW7e/Qt4v9ip55mycWzADgiqCndMlOVNDA==
|
||||
5.0.0-qa-77-1 [Build: 1698316110],macOS,ESRePbVvFOl0wUJKoSsFAMV34isnFNfzvUQW6yDoMqa8GNGNPdRw10TxUA+ypTzu4H3A8VEiKgEEm2pdwj/5CA==
|
||||
5.0.0-beta77 [Build: 1699457285],Windows,id8cERxgKG68YRDcSYCceqekamIZlBmAE/IfwYkpu+a8RC0Gkyyhtn4ZU80ppUfES3GFsGVSSwJ/eci1g+pCBg==
|
||||
5.0.0-beta77-rc1 [Build: 1700224895],Linux,T101xCL/zRr+iwZJHURKd4DUDTrQSSJ3QsADpMH/Ed8wqXPTqneP6hQk04tKEB39aJCJTDW9W0FT7Pf7vCKLBA==
|
||||
5.0.0-beta77-rc1 [Build: 1700224895],macOS,0y/hKU/yqkqgUqtn6KXbuRtqQa4DlYQ50Rziwg9k4wAUgAnCm1hts7AvUHrGv5415cJX9czxUAFdIEApPR06CA==
|
||||
5.0.0-beta77-rc2 [Build: 1700761919],Linux,oFMyO1h6nZOmA0sM9DP+6fy69t+o1drV3inNG+kaH7pZGYqgUg9r/Xu8jGaD2EqZ+Vc7JnO8Zl9Y5n3+HPNkAQ==
|
||||
5.0.0-beta77-rc2 [Build: 1700761919],Windows,VOTBvsWNSc5MNXDWd/M3JpCB8WzvUlj7+V7EVtUy9cZ8LaK8TyJjIip16YJnVDod73wMW8npyt4oaDrqkzL6Bg==
|
||||
3.6.3 [Build: 1701166057],Windows,ML3yE6pV0QGyhc8o7k1bgqDSj+5gZIQFMjBNhWJ6L0FtJwniBq8l1wivx3DzgVVCvyRbzfg8MsdV/rjl5sHNCw==
|
||||
5.0.0-beta77-rc3 [Build: 1701707182],Linux,bS/lxwnq0KSoNl0WggENJ/tuYm+QJF67gSqXykWGAik40iFmM1g7kYOkI5GoBsOxgWJBJB5L4dOjlAyA91BbCw==
|
||||
5.0.0-beta77 [Build: 1702382332],Linux,sJx9Ss46tDLfsJ6y73csGOXnSIRsSeUFrpHFQ2il/jjM7xWAbp8F8Cnyix/CaNwy7DfZKtgMRcPc8YP0a1r3AA==
|
||||
5.0.0-beta77 [Build: 1702382332],macOS,E2rqU9M9HvWnqZbki0+blgLmDWneDZZP9TW89lDDuDoQ7GaqXizzNfvr9XJBm8dJwToLfpR9/9kmLhZpHkK3Dg==
|
||||
5.0.0-beta77 [Build: 1702382332],Windows,Ee6DzP16MUXpdKWjiSY0NGb4thN22/Ks0hwNcaMrWoaadgkM6c5477X0IbGFWVjzTWfjFTEad5noYLUPDWSgCQ==
|
||||
5.0.0-qa-lm-29 [Build: 1719554519],Windows,mSNqoUO2xaP31n8wrHwuAHHYrgov4ZQmq5OrgvOF0jsEQvTy11Z29j02q3nUA+k9TrXyG12CMYVUWfe8ltneBg==
|
||||
5.0.0-qa-puzzle-2-1 [Build: 1723116226],Windows,7Qx8GeSIEvRNZ4D3aNbX0AO67Awj92afgNCgkJ7L0YdcaD0c1HFs0c2Ms6CArTiD8pB/Nxw7QgCsKcpBln1PCg==
|
||||
5.0.0-beta78-pre-1 [Build: 1724839559],Windows,fy7cW8uGyr7lA/5eqsNztXA2nS0PbFZQgIo2HNMbNPycLWJLA8DNZGafBgsfchx9EF5piNtMsJAs9JSy1Pp8DA==
|
||||
5.0.0-qa-78-18 [Build: 1724924030],Windows,/86Ug4O5Huvf1fHooxLOqIxOIp2wyyR821wOcXkDkbXawEbsp1K7GcVqPH/cyLbfKO6x4LeCILqsrV4no3pMCg==
|
||||
5.0.0-qa-78-19 [Build: 1724930118],Windows,m2z53BpS7ocld0/TuasTKe1vXvGB6ZFR9mhdAt5I4j3QZpFlCy3NeObvQEHu+a+4Dr8yFBusdQ6vR8Jf23uyCQ==
|
||||
5.0.0-beta78-pre-2 [Build: 1725011227],Windows,v6UJ+WoJ/TYQe2MqDfoXcMLPTb2L8KrN03x2WHSdsJY17yn6ofLpMtNuBLa84by+sNi1/b8htf0HdV+6TLKEDg==
|
||||
5.0.0-qa-78-20 [Build: 1725620142],Windows,hxdPF5JpyHwDb36xlKAls6wgmhGh1OvIeo4PlqVX8a9zzP0NvGVR1O2BUdo7ixFsKqrzeHoHJ7KoVxenvGpLCw==
|
||||
5.0.0-qa-78-21 [Build: 1726235323],Windows,OiQZT9J/s6kIOX6UUDEB5tu3DrKYz6S7Lay/BaXY6teJcbkIuhBr1MREgmkg8Z+yIEHpIqrV73sUqHD2vk+lAg==
|
||||
5.0.0-qa-78-22 [Build: 1726816276],Windows,dfh0I4RAn1OSy6GrlSmStLBZWutnmUEg7D4tWvzC668p3FBsm7az/CexueslYeoXKgFj871k4F/CyDCgKtCUBA==
|
||||
5.0.0-qa-78-23 [Build: 1727272684],Windows,OkGqYGggz96MOy29Q7kkNi1sWbGkS6B0K//l7E8oixEdS6xdLgW6GmxwcI6DxvwBjVICg0TdO+VhGpRC9RnUCQ==
|
||||
5.0.0-beta78-pre-5 [Build: 1728287639],Windows,r9IEzCKmd1M5JszuUU02xy1qFkxKAPAHa45mzxakCqibCdzdL5+T6L+OepdbB6xOKSQ+uAyAFJOd6FHX4vJ7BA==
|
||||
6.0.0-beta2 [Build: 1737468425],Windows,b5mySiqYAd4Lv5TZNflW+G5Gk8y7Woo9YnJfHRjmzhUyMdGfF1O7fSGJzmx2Hpe/PKaY2aDuKKD6lSxbLYlKCw==
|
||||
6.0.0-beta4.1 [Build: 1779880475],Linux,7A/XVk3u5VSltgVlDzJCNmN+LUzztoaqCbzmaC7s3EENoN6TpEKh2Fz/N4zPVYM/pllU3Ij5K0h6UsSJHj2FCw==
|
||||
|
@@ -102,8 +102,17 @@ pub enum LicenseBlockType {
|
||||
/// Ts3_Server
|
||||
Server,
|
||||
Code,
|
||||
// Not existing in the license parameter:
|
||||
// 4: Token, 5: License_Sign, 6: MyTsId_Sign, 7: Updater
|
||||
// Not existing in the license parameter. Like `Ephemeral`, these blocks
|
||||
// carry nothing after the header.
|
||||
/// 4, Token
|
||||
Token,
|
||||
/// 5, License_Sign
|
||||
LicenseSign,
|
||||
/// 6, MyTsId_Sign: the key that signs myTeamSpeak data (avatars, badges,
|
||||
/// identifier tokens).
|
||||
MytsIdSign,
|
||||
/// 7, Updater
|
||||
Updater,
|
||||
/// Ts_Server_License
|
||||
Ts5Server = 8,
|
||||
/// 32, Ephemeral_Key
|
||||
@@ -413,8 +422,12 @@ impl License {
|
||||
|
||||
(InnerLicense::Ts5Server { properties }, pos)
|
||||
}
|
||||
LicenseBlockType::Ephemeral => (InnerLicense::Other, 0),
|
||||
_ => {
|
||||
LicenseBlockType::Token
|
||||
| LicenseBlockType::LicenseSign
|
||||
| LicenseBlockType::MytsIdSign
|
||||
| LicenseBlockType::Updater
|
||||
| LicenseBlockType::Ephemeral => (InnerLicense::Other, 0),
|
||||
LicenseBlockType::Website | LicenseBlockType::Code => {
|
||||
return Err(Error::UnknownBlockType(typ_i));
|
||||
}
|
||||
};
|
||||
@@ -710,7 +723,11 @@ impl fmt::Debug for DebugLicense<'_> {
|
||||
d.field("properties", &"error");
|
||||
}
|
||||
}
|
||||
LicenseBlockType::Ephemeral => {}
|
||||
LicenseBlockType::Token
|
||||
| LicenseBlockType::LicenseSign
|
||||
| LicenseBlockType::MytsIdSign
|
||||
| LicenseBlockType::Updater
|
||||
| LicenseBlockType::Ephemeral => {}
|
||||
}
|
||||
|
||||
d.finish()?;
|
||||
@@ -727,7 +744,11 @@ impl LicenseBlockType {
|
||||
Self::Website | Self::Code => 1,
|
||||
Self::Server => 6,
|
||||
Self::Ts5Server => 2,
|
||||
Self::Ephemeral => 0,
|
||||
Self::Token
|
||||
| Self::LicenseSign
|
||||
| Self::MytsIdSign
|
||||
| Self::Updater
|
||||
| Self::Ephemeral => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -923,6 +944,27 @@ mod tests {
|
||||
YrUET9sEbz1CATKgK8EyqrfA==").unwrap()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_blocks_without_payload() {
|
||||
// Token, License_Sign, MyTsId_Sign and Updater blocks end with their
|
||||
// header, as Ephemeral blocks do.
|
||||
for typ in [4, 5, 6, 7] {
|
||||
let mut data = vec![1, 0];
|
||||
data.extend_from_slice(&[0x58; 32]);
|
||||
data.push(typ);
|
||||
data.extend_from_slice(&[0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff]);
|
||||
let licenses = Licenses::parse_ignore_expired(data.clone()).unwrap();
|
||||
assert_eq!(licenses.blocks.len(), 1);
|
||||
assert_eq!(licenses.blocks[0].len, BLOCK_MIN_LEN);
|
||||
let block = licenses.blocks[0].get_type(&data[1..]).unwrap();
|
||||
assert_eq!(block.to_u8(), Some(typ));
|
||||
// Anything after the header is the next block.
|
||||
data.push(0);
|
||||
assert!(Licenses::parse_ignore_expired(data).is_err());
|
||||
}
|
||||
assert_eq!(LicenseBlockType::from_u8(6), Some(LicenseBlockType::MytsIdSign));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derive_public_key() {
|
||||
let licenses = Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQA1hUFJiiSs0wFXkYuPUJVcDa6XCrZTcsvkB0Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAAC4R+5mos+UQ/KCbkpQLMI5WRp4wkQu8e5PZY4zU+/FlyAJwaE8CcJJ/A==").unwrap()).unwrap();
|
||||
|
||||
@@ -6,13 +6,17 @@
|
||||
use std::fmt;
|
||||
|
||||
use base64::prelude::*;
|
||||
use curve25519_dalek::edwards::{CompressedEdwardsY, EdwardsPoint};
|
||||
use curve25519_dalek::{constants::ED25519_BASEPOINT_TABLE, scalar::Scalar};
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use sha2::{Digest, Sha256, Sha512};
|
||||
use thiserror::Error;
|
||||
use tsproto_packets::packets::OutCommand;
|
||||
use tsproto_types::crypto::EccKeyPubEd25519;
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use crate::license::{self, LicenseBlockType, Licenses};
|
||||
|
||||
/// An account identity; distinct from the account UUID and server identity.
|
||||
#[derive(Clone, Serialize)]
|
||||
pub struct Identity {
|
||||
@@ -94,6 +98,13 @@ impl Identity {
|
||||
|
||||
pub fn id(&self) -> String { BASE64_STANDARD.encode(&self.myts_id) }
|
||||
|
||||
/// The myTS ID's 33 bytes: what myTeamSpeak signs the account's avatar,
|
||||
/// badges and identifier token for.
|
||||
pub fn id_bytes(&self) -> &[u8] { &self.myts_id }
|
||||
|
||||
/// The certificate of the myTS ID's signature (`pubSignCert`): public.
|
||||
pub fn public_signature_certificate(&self) -> &[u8] { &self.public_signature[64..] }
|
||||
|
||||
/// Sign this connection's challenge with the original raw private scalar.
|
||||
/// This is not Ed25519's seed expansion: the account already stores a scalar.
|
||||
pub fn proof(&self, shared_iv: &[u8; 64]) -> Proof {
|
||||
@@ -131,6 +142,91 @@ impl Identity {
|
||||
}
|
||||
}
|
||||
|
||||
/// A myTeamSpeak certificate: a TeamSpeak license chain whose last block's
|
||||
/// key signs what myTeamSpeak hands out for an account (its avatar, badges
|
||||
/// and identifier token). Checked as a TeamSpeak 6 server and the official
|
||||
/// client check it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Certificate {
|
||||
block_type: Option<LicenseBlockType>,
|
||||
/// Unix seconds.
|
||||
not_valid_before: i64,
|
||||
not_valid_after: i64,
|
||||
/// The leaf's key, derived along the chain from the root.
|
||||
key: [u8; 32],
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum CertificateError {
|
||||
#[error("myTeamSpeak certificate must start with version 1")]
|
||||
Version,
|
||||
#[error("myTeamSpeak certificate holds no key")]
|
||||
Empty,
|
||||
#[error("myTeamSpeak certificate does not parse: {0}")]
|
||||
License(#[from] license::Error),
|
||||
}
|
||||
|
||||
impl Certificate {
|
||||
/// Parse a certificate whose chain starts at `root` (the TeamSpeak root
|
||||
/// key, [`crate::ROOT_KEY`]). Nested validity windows are checked here,
|
||||
/// the leaf's against a time by [`Self::valid_at`].
|
||||
pub fn parse(data: &[u8], root: &[u8; 32]) -> Result<Self, CertificateError> {
|
||||
if data.first() != Some(&1) {
|
||||
return Err(CertificateError::Version);
|
||||
}
|
||||
let licenses = Licenses::parse_ignore_expired(data.to_vec())?;
|
||||
let leaf = licenses.blocks.last().ok_or(CertificateError::Empty)?;
|
||||
let leaf_data = &data[data.len() - leaf.len..];
|
||||
let key = licenses.derive_public_key(EccKeyPubEd25519::from_bytes(*root))?;
|
||||
Ok(Self {
|
||||
block_type: leaf.get_type(leaf_data).ok(),
|
||||
not_valid_before: leaf.get_not_valid_before(leaf_data)?.unix_timestamp(),
|
||||
not_valid_after: leaf.get_not_valid_after(leaf_data)?.unix_timestamp(),
|
||||
key: key.compress().to_bytes(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the leaf is a key that signs for myTS IDs (`MYTSID_SIGN`):
|
||||
/// a TeamSpeak 6 server takes no other for an avatar or badges.
|
||||
pub fn signs_myts_data(&self) -> bool { self.block_type == Some(LicenseBlockType::MytsIdSign) }
|
||||
|
||||
/// Whether the leaf is valid at `unix` seconds.
|
||||
pub fn valid_at(&self, unix: i64) -> bool {
|
||||
self.not_valid_before <= unix && unix < self.not_valid_after
|
||||
}
|
||||
|
||||
/// Until when the leaf is valid, Unix seconds.
|
||||
pub fn not_valid_after(&self) -> i64 { self.not_valid_after }
|
||||
|
||||
/// Whether the leaf's key signed `message` (Ed25519, as TeamSpeak checks
|
||||
/// it: SHA-512 over R, the key and the message, without the cofactor;
|
||||
/// a signature whose S is not reduced is refused).
|
||||
pub fn verifies(&self, message: &[u8], signature: &[u8]) -> bool {
|
||||
verify_ed25519(&self.key, message, signature)
|
||||
}
|
||||
}
|
||||
|
||||
fn verify_ed25519(key: &[u8; 32], message: &[u8], signature: &[u8]) -> bool {
|
||||
if signature.len() != 64 {
|
||||
return false;
|
||||
}
|
||||
let Some(public) = CompressedEdwardsY(*key).decompress() else {
|
||||
return false;
|
||||
};
|
||||
let mut s = [0; 32];
|
||||
s.copy_from_slice(&signature[32..]);
|
||||
let Some(s) = Option::<Scalar>::from(Scalar::from_canonical_bytes(s)) else {
|
||||
return false;
|
||||
};
|
||||
let mut hash = Sha512::new();
|
||||
hash.update(&signature[..32]);
|
||||
hash.update(key);
|
||||
hash.update(message);
|
||||
let k = Scalar::from_bytes_mod_order_wide(&hash.finalize().into());
|
||||
let r = EdwardsPoint::vartime_double_scalar_mul_basepoint(&k, &-public, &s);
|
||||
r.compress().as_bytes() == &signature[..32]
|
||||
}
|
||||
|
||||
/// Public, connection-bound authentication values. Never contains private keys.
|
||||
#[derive(Clone)]
|
||||
pub struct Proof {
|
||||
@@ -244,4 +340,136 @@ mod tests {
|
||||
]);
|
||||
assert!(!wire.contains("private"));
|
||||
}
|
||||
|
||||
/// A chain from a synthetic root (secret `root`): an intermediate block
|
||||
/// when `outer` is set, then a leaf of `kind` with the key `leaf`·B, valid
|
||||
/// from `from` to `to` (Unix seconds). Also the leaf's derived secret.
|
||||
fn chain(
|
||||
root: Scalar, outer: Option<(i64, i64)>, leaf: Scalar, kind: u8, from: i64, to: i64,
|
||||
) -> (Vec<u8>, Scalar) {
|
||||
fn block(key: &Scalar, kind: u8, from: i64, to: i64, extra: &[u8]) -> (Vec<u8>, Scalar) {
|
||||
let mut block = vec![0];
|
||||
block.extend_from_slice((ED25519_BASEPOINT_TABLE * key).compress().as_bytes());
|
||||
block.push(kind);
|
||||
for time in [from, to] {
|
||||
block.extend_from_slice(&((time - license::TIMESTAMP_OFFSET) as u32).to_be_bytes());
|
||||
}
|
||||
block.extend_from_slice(extra);
|
||||
let mut hash: [u8; 64] = Sha512::digest(&block[1..]).into();
|
||||
hash[0] &= 248;
|
||||
hash[31] &= 63;
|
||||
hash[31] |= 64;
|
||||
let mut low = [0; 32];
|
||||
low.copy_from_slice(&hash[..32]);
|
||||
(block, Scalar::from_bytes_mod_order(low))
|
||||
}
|
||||
let mut data = vec![1];
|
||||
let mut secret = root;
|
||||
if let Some((from, to)) = outer {
|
||||
let key = Scalar::from_bytes_mod_order([3; 32]);
|
||||
let (outer, hash) = block(&key, 0, from, to, b"\0\0\0\0Synthetic\0");
|
||||
data.extend_from_slice(&outer);
|
||||
secret += key * hash;
|
||||
}
|
||||
let (leaf_block, hash) = block(&leaf, kind, from, to, &[]);
|
||||
data.extend_from_slice(&leaf_block);
|
||||
(data, secret + leaf * hash)
|
||||
}
|
||||
|
||||
fn sign(secret: &Scalar, message: &[u8]) -> Vec<u8> {
|
||||
let public = (ED25519_BASEPOINT_TABLE * secret).compress().to_bytes();
|
||||
let nonce = Scalar::from_bytes_mod_order_wide(
|
||||
&Sha512::new().chain_update(secret.as_bytes()).chain_update(message).finalize().into(),
|
||||
);
|
||||
let r = (ED25519_BASEPOINT_TABLE * &nonce).compress().to_bytes();
|
||||
let k = Scalar::from_bytes_mod_order_wide(
|
||||
&Sha512::new().chain_update(r).chain_update(public).chain_update(message).finalize().into(),
|
||||
);
|
||||
let mut signature = r.to_vec();
|
||||
signature.extend_from_slice((k * secret + nonce).as_bytes());
|
||||
signature
|
||||
}
|
||||
|
||||
const NOW: i64 = 1_790_000_000;
|
||||
|
||||
#[test]
|
||||
fn certificate_key_signs_along_the_chain() {
|
||||
let root = Scalar::from_bytes_mod_order([5; 32]);
|
||||
let root_key = (ED25519_BASEPOINT_TABLE * &root).compress().to_bytes();
|
||||
let leaf = Scalar::from_bytes_mod_order([7; 32]);
|
||||
for outer in [None, Some((NOW - 1000, NOW + 1000))] {
|
||||
let (data, secret) = chain(root, outer, leaf, 6, NOW - 10, NOW + 10);
|
||||
let certificate = Certificate::parse(&data, &root_key).unwrap();
|
||||
assert!(certificate.signs_myts_data());
|
||||
assert!(certificate.valid_at(NOW - 10) && certificate.valid_at(NOW + 9));
|
||||
assert!(!certificate.valid_at(NOW - 11) && !certificate.valid_at(NOW + 10));
|
||||
assert_eq!(certificate.not_valid_after(), NOW + 10);
|
||||
let signature = sign(&secret, b"message");
|
||||
assert!(certificate.verifies(b"message", &signature));
|
||||
assert!(!certificate.verifies(b"messagE", &signature));
|
||||
assert!(!certificate.verifies(b"message", &signature[..63]));
|
||||
let mut flipped = signature.clone();
|
||||
flipped[5] ^= 1;
|
||||
assert!(!certificate.verifies(b"message", &flipped));
|
||||
// The same S plus the group order: refused, though it is the same
|
||||
// point (S must be reduced).
|
||||
let mut s = [0u8; 32];
|
||||
s.copy_from_slice(&signature[32..]);
|
||||
let order: [u8; 32] = [
|
||||
0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9,
|
||||
0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10,
|
||||
];
|
||||
let mut carry = 0u16;
|
||||
for (s, l) in s.iter_mut().zip(order) {
|
||||
let sum = u16::from(*s) + u16::from(l) + carry;
|
||||
*s = sum as u8;
|
||||
carry = sum >> 8;
|
||||
}
|
||||
let mut unreduced = signature.clone();
|
||||
unreduced[32..].copy_from_slice(&s);
|
||||
assert!(!certificate.verifies(b"message", &unreduced));
|
||||
// Another root: another key.
|
||||
let other = Certificate::parse(&data, &crate::ROOT_KEY).unwrap();
|
||||
assert!(!other.verifies(b"message", &signature));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ed25519_matches_rfc_8032() {
|
||||
// RFC 8032, 7.1, tests 1 and 2.
|
||||
let key = hex::<32>("d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a");
|
||||
let signature = hex::<64>(
|
||||
"e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b",
|
||||
);
|
||||
assert!(verify_ed25519(&key, b"", &signature));
|
||||
assert!(!verify_ed25519(&key, b"\x72", &signature));
|
||||
let key = hex::<32>("3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c");
|
||||
let signature = hex::<64>(
|
||||
"92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00",
|
||||
);
|
||||
assert!(verify_ed25519(&key, b"\x72", &signature));
|
||||
assert!(!verify_ed25519(&key, b"\x73", &signature));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certificate_kinds_windows_and_format() {
|
||||
let root = Scalar::from_bytes_mod_order([5; 32]);
|
||||
let root_key = (ED25519_BASEPOINT_TABLE * &root).compress().to_bytes();
|
||||
let leaf = Scalar::from_bytes_mod_order([7; 32]);
|
||||
for kind in [4, 5, 7, 32] {
|
||||
let (data, _) = chain(root, None, leaf, kind, NOW - 10, NOW + 10);
|
||||
assert!(!Certificate::parse(&data, &root_key).unwrap().signs_myts_data(), "{}", kind);
|
||||
}
|
||||
// A leaf valid longer than the block above it.
|
||||
let (data, _) = chain(root, Some((NOW - 5, NOW + 5)), leaf, 6, NOW - 10, NOW + 10);
|
||||
assert!(Certificate::parse(&data, &root_key).is_err());
|
||||
let (mut data, _) = chain(root, None, leaf, 6, NOW - 10, NOW + 10);
|
||||
data[0] = 0;
|
||||
assert!(matches!(Certificate::parse(&data, &root_key), Err(CertificateError::Version)));
|
||||
assert!(matches!(Certificate::parse(&[1], &root_key), Err(CertificateError::Empty)));
|
||||
assert!(Certificate::parse(&[], &root_key).is_err());
|
||||
data[0] = 1;
|
||||
data[34] = 9;
|
||||
assert!(Certificate::parse(&data, &root_key).is_err());
|
||||
}
|
||||
}
|
||||
@@ -32,9 +32,5 @@ voelin-platform = { path = "../voelin-platform", default-features = false }
|
||||
voelin-store = { path = "../voelin-store" }
|
||||
voelin-ui = { path = "../voelin-ui" }
|
||||
|
||||
[dev-dependencies]
|
||||
# Client ids of stream viewers in the tests.
|
||||
tsclientlib = { path = "../proto/tsclientlib" }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -13,7 +13,7 @@ use std::sync::Arc;
|
||||
|
||||
use voelin_core::stream::{StreamState, ViewerInfo, ViewerState};
|
||||
use voelin_core::{Event, SessionId, VoiceState};
|
||||
use voelin_model::Presence;
|
||||
use voelin_model::{Presence, channel_title};
|
||||
|
||||
/// What the voice notification shows.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -72,13 +72,13 @@ impl Session {
|
||||
self.name.as_deref().unwrap_or("a server")
|
||||
}
|
||||
|
||||
/// Our channel's name and how many are in it.
|
||||
/// Our channel's name (a spacer's text) and how many are in it.
|
||||
fn channel(&self) -> Option<(&str, usize)> {
|
||||
let id = self.own_channel?;
|
||||
let channel = self.presence.channels.get(&id)?;
|
||||
let people =
|
||||
self.presence.clients.values().filter(|c| c.channel == id && !c.is_query).count();
|
||||
Some((channel.name.as_str(), people))
|
||||
Some((channel_title(channel).0, people))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,7 +194,7 @@ fn connected(viewers: &[ViewerInfo]) -> usize {
|
||||
mod tests {
|
||||
use voelin_core::SessionState;
|
||||
use voelin_core::stream::EndReason;
|
||||
use voelin_model::{Capabilities, ChannelInfo, ClientInfo, ServerFlavor};
|
||||
use voelin_model::{Capabilities, ChannelInfo, ClientInfo};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -222,8 +222,11 @@ mod tests {
|
||||
|
||||
fn presence(people: u16) -> Event {
|
||||
let mut p = Presence::default();
|
||||
p.channels
|
||||
.insert(2, ChannelInfo { id: 2, name: "Chill Zone".into(), ..Default::default() });
|
||||
// A spacer shows its text.
|
||||
p.channels.insert(
|
||||
2,
|
||||
ChannelInfo { id: 2, name: "[cspacer1]Chill Zone".into(), ..Default::default() },
|
||||
);
|
||||
for id in 1..=people {
|
||||
p.clients.insert(id, ClientInfo { id, channel: 2, ..Default::default() });
|
||||
}
|
||||
@@ -241,7 +244,7 @@ mod tests {
|
||||
let info = Event::ServerInfo {
|
||||
session: 1,
|
||||
name: "Home".into(),
|
||||
flavor: ServerFlavor::Unknown(String::new()),
|
||||
backend: voelin_core::BackendInfo::default(),
|
||||
capabilities: Capabilities::default(),
|
||||
};
|
||||
assert_eq!(fg.update_at(&info, 6).voice, notice("Connecting…", "Home", false, 0));
|
||||
@@ -313,7 +316,7 @@ mod tests {
|
||||
};
|
||||
assert_eq!(fg.screen(), screen("Live in Chill Zone", "a server").flatten());
|
||||
let viewer = |client, state| ViewerInfo {
|
||||
client: tsclientlib::ClientId(client),
|
||||
client,
|
||||
state,
|
||||
message: String::new(),
|
||||
layer: None,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "voelin-audio"
|
||||
version = "0.1.0"
|
||||
description = "Voice pipeline: Opus encoding, framing, resampling, jitter buffer/mixer and audio devices."
|
||||
description = "Voice pipeline: Opus encoding, framing, resampling, jitter buffer/mixer and audio devices, independent of the voice transport."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
@@ -25,8 +25,6 @@ sonora-agc2 = "0.2"
|
||||
sonora-simd = "0.2"
|
||||
thiserror = "2.0.21"
|
||||
tracing = "0.1.44"
|
||||
tsclientlib = { path = "../proto/tsclientlib" }
|
||||
tsproto-packets = { path = "../proto/tsproto-packets" }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = "1"
|
||||
|
||||
@@ -1,45 +1,15 @@
|
||||
//! Opus encoding into TeamSpeak voice packets.
|
||||
//! Opus encoding of 20 ms frames into [`EncodedVoice`].
|
||||
|
||||
use opus2::{Application, Bitrate, Channels, Encoder};
|
||||
use tsproto_packets::packets::{AudioData, CodecType, OutAudio, OutPacket};
|
||||
|
||||
use crate::pcm::{FRAME_SAMPLES, SAMPLE_RATE};
|
||||
use crate::packet::{EncodedVoice, VoiceCodec};
|
||||
use crate::pcm::SAMPLE_RATE;
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Largest possible Opus packet.
|
||||
const MAX_PACKET: usize = 1275;
|
||||
|
||||
/// The two Opus codecs TeamSpeak channels use.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum VoiceCodec {
|
||||
/// Mono, tuned for speech (`CodecType::OpusVoice`).
|
||||
Voice,
|
||||
/// Stereo, tuned for music (`CodecType::OpusMusic`).
|
||||
Music,
|
||||
}
|
||||
|
||||
impl VoiceCodec {
|
||||
pub fn channels(self) -> usize {
|
||||
match self {
|
||||
VoiceCodec::Voice => 1,
|
||||
VoiceCodec::Music => 2,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn codec_type(self) -> CodecType {
|
||||
match self {
|
||||
VoiceCodec::Voice => CodecType::OpusVoice,
|
||||
VoiceCodec::Music => CodecType::OpusMusic,
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples (all channels) in one 20 ms frame.
|
||||
pub fn frame_len(self) -> usize {
|
||||
FRAME_SAMPLES * self.channels()
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes 20 ms frames of 48 kHz audio into voice packets.
|
||||
/// Encodes 20 ms frames of 48 kHz audio into Opus packets.
|
||||
pub struct VoiceEncoder {
|
||||
encoder: Encoder,
|
||||
codec: VoiceCodec,
|
||||
@@ -53,7 +23,7 @@ impl VoiceEncoder {
|
||||
VoiceCodec::Music => (Channels::Stereo, Application::Audio),
|
||||
};
|
||||
let mut encoder = Encoder::new(SAMPLE_RATE, channels, application)?;
|
||||
// Survive some packet loss: TeamSpeak voice is plain UDP.
|
||||
// Survive some packet loss: voice travels over unreliable datagrams.
|
||||
encoder.set_inband_fec(true)?;
|
||||
encoder.set_packet_loss_perc(5)?;
|
||||
Ok(Self { encoder, codec, out: vec![0; MAX_PACKET] })
|
||||
@@ -82,26 +52,25 @@ impl VoiceEncoder {
|
||||
Ok(&self.out[..len])
|
||||
}
|
||||
|
||||
/// Encode one frame into a packet ready for `Connection::send_audio`.
|
||||
/// The connection assigns the packet id.
|
||||
pub fn encode(&mut self, frame: &[f32]) -> Result<OutPacket> {
|
||||
let codec = self.codec.codec_type();
|
||||
let data = self.encode_to_bytes(frame)?;
|
||||
Ok(OutAudio::new(&AudioData::C2S { id: 0, codec, data }))
|
||||
/// Encode one frame for the transport to send. The transport assigns the
|
||||
/// packet number.
|
||||
pub fn encode(&mut self, frame: &[f32]) -> Result<EncodedVoice> {
|
||||
let codec = self.codec;
|
||||
let payload = self.encode_to_bytes(frame)?.to_vec();
|
||||
Ok(EncodedVoice { codec, payload })
|
||||
}
|
||||
|
||||
/// The empty packet that tells listeners the transmission ended.
|
||||
pub fn end_of_stream(&self) -> OutPacket {
|
||||
OutAudio::new(&AudioData::C2S { id: 0, codec: self.codec.codec_type(), data: &[] })
|
||||
pub fn end_of_stream(&self) -> EncodedVoice {
|
||||
EncodedVoice { codec: self.codec, payload: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tsproto_packets::packets::{Direction, InAudioBuf};
|
||||
|
||||
use super::*;
|
||||
use crate::pcm;
|
||||
use crate::packet::{TalkerId, VoicePacket};
|
||||
use crate::pcm::{self, FRAME_SAMPLES};
|
||||
|
||||
/// Encode a tone, feed the packets through the mixer (jitter buffer +
|
||||
/// decoder), and check the tone comes out.
|
||||
@@ -112,15 +81,16 @@ mod tests {
|
||||
let tone = pcm::sine(1000.0, 1.0, 0.5);
|
||||
let mut decoded = Vec::new();
|
||||
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
|
||||
let data = encoder.encode_to_bytes(frame).unwrap().to_vec();
|
||||
let packet = OutAudio::new(&AudioData::S2C {
|
||||
id: i as u16,
|
||||
codec: CodecType::OpusVoice,
|
||||
from: 7,
|
||||
data: &data,
|
||||
});
|
||||
let packet = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
|
||||
mixer.handle_packet(tsclientlib::ClientId(7), packet).unwrap();
|
||||
let sent = encoder.encode(frame).unwrap();
|
||||
assert_eq!(sent.codec, VoiceCodec::Voice);
|
||||
let packet = VoicePacket {
|
||||
talker: TalkerId(7),
|
||||
seq: i as u16,
|
||||
codec: sent.codec,
|
||||
whisper: false,
|
||||
payload: sent.payload,
|
||||
};
|
||||
mixer.handle_packet(packet).unwrap();
|
||||
let mut out = vec![0.0; FRAME_SAMPLES * 2];
|
||||
mixer.fill_buffer(&mut out);
|
||||
decoded.extend(pcm::to_mono(&out, 2));
|
||||
@@ -131,6 +101,24 @@ mod tests {
|
||||
assert!(ratio > 0.8, "tone ratio {ratio}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_of_stream_has_no_payload() {
|
||||
let encoder = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
||||
let end = encoder.end_of_stream();
|
||||
assert_eq!(end, EncodedVoice { codec: VoiceCodec::Music, payload: vec![] });
|
||||
assert!(end.is_end());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoded_frames_carry_codec_and_audio() {
|
||||
let mut voice = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut music = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
||||
let a = voice.encode(&[0.1; FRAME_SAMPLES]).unwrap();
|
||||
let b = music.encode(&[0.1; FRAME_SAMPLES * 2]).unwrap();
|
||||
assert_eq!((a.codec, b.codec), (VoiceCodec::Voice, VoiceCodec::Music));
|
||||
assert!(!a.is_end() && !b.is_end());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_wrong_frame_size() {
|
||||
let mut encoder = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
||||
|
||||
@@ -0,0 +1,879 @@
|
||||
//! Handle receiving audio.
|
||||
//!
|
||||
//! Moved here from the vendored `tsclientlib::audio` and made independent of the
|
||||
//! transport: it reads [`VoicePacket`]s, whatever carried them.
|
||||
//!
|
||||
//! The [`AudioHandler`] collects all incoming audio packets and queues them per
|
||||
//! talker. It decodes the audio, handles out-of-order packets and missing
|
||||
//! packets. It automatically adjusts the queue length based on the jitter of
|
||||
//! incoming packets.
|
||||
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::convert::TryInto;
|
||||
|
||||
use opus2::{Channels, Decoder, packet};
|
||||
use thiserror::Error;
|
||||
use tracing::{Span, debug, info_span, trace, warn};
|
||||
|
||||
use crate::packet::{TalkerId, VoicePacket};
|
||||
|
||||
const SAMPLE_RATE: u32 = 48_000;
|
||||
const CHANNELS: Channels = Channels::Stereo;
|
||||
const CHANNEL_NUM: usize = 2;
|
||||
/// If this amount of packets is lost consecutively, we assume the stream stopped.
|
||||
const MAX_PACKET_LOSSES: usize = 3;
|
||||
/// Store the buffer sizes for the last `LAST_BUFFER_SIZE_COUNT` packets.
|
||||
const LAST_BUFFER_SIZE_COUNT: u8 = 255;
|
||||
/// The amount of samples to maximally buffer. Equivalent to 0.5 s.
|
||||
const MAX_BUFFER_SIZE: usize = 48_000 / 2;
|
||||
/// Maximum number of packets in the queue.
|
||||
const MAX_BUFFER_PACKETS: usize = 50;
|
||||
/// Buffer for maximal 0.5 s without playing anything.
|
||||
const MAX_BUFFER_TIME: usize = 48_000 / 2;
|
||||
/// Duplicate or remove every `step` sample when speeding-up.
|
||||
const SPEED_CHANGE_STEPS: usize = 100;
|
||||
/// The usual amount of samples in a frame.
|
||||
///
|
||||
/// Use 48 kHz, 20 ms frames (50 per second) and mono data (1 channel).
|
||||
/// This means 1920 samples and 7.5 kiB.
|
||||
const USUAL_FRAME_SIZE: usize = 48000 / 50;
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum Error {
|
||||
#[error("Failed to create opus decoder: {0}")]
|
||||
CreateDecoder(#[source] opus2::Error),
|
||||
#[error("Opus decode failed: {error} (packet: {packet:?})")]
|
||||
Decode {
|
||||
#[source]
|
||||
error: opus2::Error,
|
||||
packet: Option<Vec<u8>>,
|
||||
},
|
||||
#[error("Get duplicate packet id {0}")]
|
||||
Duplicate(u16),
|
||||
#[error("Failed to get packet samples: {0}")]
|
||||
GetPacketSample(#[source] opus2::Error),
|
||||
#[error("Audio queue is full, dropping")]
|
||||
QueueFull,
|
||||
#[error("Audio packet is too late, dropping (wanted {wanted}, got {got})")]
|
||||
TooLate { wanted: u16, got: u16 },
|
||||
#[error("Packet has too many samples")]
|
||||
TooManySamples,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct SlidingWindowMinimum<T: Copy + Default + Ord> {
|
||||
/// How long a value stays in the sliding window.
|
||||
size: u8,
|
||||
/// This is a sliding window minimum, it contains
|
||||
/// `(insertion time, value)`.
|
||||
///
|
||||
/// When we insert a value, we can remove all bigger sample counts,
|
||||
/// thus the queue always stays sorted with the minimum at the front
|
||||
/// and the maximum at the back (latest entry).
|
||||
///
|
||||
/// Provides amortized O(1) minimum.
|
||||
/// Source: https://people.cs.uct.ac.za/~ksmith/articles/sliding_window_minimum.html#sliding-window-minimum-algorithm
|
||||
queue: VecDeque<(u8, T)>,
|
||||
/// The current insertion time.
|
||||
cur_time: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct QueuePacket {
|
||||
packet: VoicePacket,
|
||||
samples: usize,
|
||||
id: u16,
|
||||
}
|
||||
|
||||
/// A queue for audio packets for one audio stream.
|
||||
pub struct AudioQueue {
|
||||
span: Span,
|
||||
decoder: Decoder,
|
||||
pub volume: f32,
|
||||
/// The id of the next packet that should be decoded.
|
||||
///
|
||||
/// Used to check for packet loss.
|
||||
next_id: u16,
|
||||
/// If the last packet was a whisper packet.
|
||||
whispering: bool,
|
||||
packet_buffer: VecDeque<QueuePacket>,
|
||||
/// Amount of samples in the `packet_buffer`.
|
||||
packet_buffer_samples: usize,
|
||||
/// Temporary buffer that contains the samples of one decoded packet.
|
||||
decoded_buffer: Vec<f32>,
|
||||
/// The number of samples in `decoded_buffer` that have been returned.
|
||||
decoded_pos: usize,
|
||||
/// The number of samples in the last packet.
|
||||
last_packet_samples: usize,
|
||||
/// The last `packet_loss_num` packet decodes were a loss.
|
||||
packet_loss_num: usize,
|
||||
/// The amount of samples to buffer until this queue is ready to play.
|
||||
buffering_samples: usize,
|
||||
/// The amount of packets in the buffer when a packet was decoded.
|
||||
///
|
||||
/// Uses the amount of samples in the `packet_buffer` / `USUAL_PACKET_SAMPLES`.
|
||||
/// Used to expand or reduce the buffer.
|
||||
last_buffer_size_min: SlidingWindowMinimum<u8>,
|
||||
last_buffer_size_max: SlidingWindowMinimum<Reverse<u8>>,
|
||||
/// Buffered for this duration.
|
||||
buffered_for_samples: usize,
|
||||
}
|
||||
|
||||
/// Handles incoming audio, has one [`AudioQueue`] per talker.
|
||||
#[derive(Default)]
|
||||
pub struct AudioHandler {
|
||||
queues: HashMap<TalkerId, AudioQueue>,
|
||||
/// Buffer this amount of samples for new queues before starting to play.
|
||||
///
|
||||
/// Updated when a new queue gets added.
|
||||
avg_buffer_samples: usize,
|
||||
}
|
||||
|
||||
impl<T: Copy + Default + Ord> SlidingWindowMinimum<T> {
|
||||
fn new(size: u8) -> Self {
|
||||
Self { size, queue: Default::default(), cur_time: 0 }
|
||||
}
|
||||
|
||||
fn push(&mut self, value: T) {
|
||||
while self.queue.back().map(|(_, s)| *s >= value).unwrap_or_default() {
|
||||
self.queue.pop_back();
|
||||
}
|
||||
let i = self.cur_time;
|
||||
self.queue.push_back((i, value));
|
||||
while self
|
||||
.queue
|
||||
.front()
|
||||
.map(|(i, _)| self.cur_time.wrapping_sub(*i) >= self.size)
|
||||
.unwrap_or_default()
|
||||
{
|
||||
self.queue.pop_front();
|
||||
}
|
||||
self.cur_time = self.cur_time.wrapping_add(1);
|
||||
}
|
||||
|
||||
fn get_min(&self) -> T {
|
||||
self.queue.front().map(|(_, s)| *s).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioQueue {
|
||||
fn new(packet: VoicePacket) -> Result<Self> {
|
||||
let last_packet_samples =
|
||||
packet::get_nb_samples(&packet.payload, SAMPLE_RATE).map_err(Error::GetPacketSample)?;
|
||||
if last_packet_samples > MAX_BUFFER_SIZE {
|
||||
return Err(Error::TooManySamples);
|
||||
}
|
||||
|
||||
let last_packet_samples = last_packet_samples * CHANNEL_NUM;
|
||||
let whispering = packet.whisper;
|
||||
let decoder = Decoder::new(SAMPLE_RATE, CHANNELS).map_err(Error::CreateDecoder)?;
|
||||
|
||||
let mut res = Self {
|
||||
span: Span::current(),
|
||||
decoder,
|
||||
volume: 1.0,
|
||||
next_id: packet.seq,
|
||||
whispering,
|
||||
packet_buffer: Default::default(),
|
||||
packet_buffer_samples: 0,
|
||||
decoded_buffer: Default::default(),
|
||||
decoded_pos: 0,
|
||||
last_packet_samples,
|
||||
packet_loss_num: 0,
|
||||
buffering_samples: 0,
|
||||
last_buffer_size_min: SlidingWindowMinimum::new(LAST_BUFFER_SIZE_COUNT),
|
||||
last_buffer_size_max: SlidingWindowMinimum::<Reverse<u8>>::new(LAST_BUFFER_SIZE_COUNT),
|
||||
buffered_for_samples: 0,
|
||||
};
|
||||
res.add_buffer_size(0);
|
||||
res.add_packet(packet)?;
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
pub fn get_decoder(&self) -> &Decoder {
|
||||
&self.decoder
|
||||
}
|
||||
pub fn is_whispering(&self) -> bool {
|
||||
self.whispering
|
||||
}
|
||||
|
||||
/// Size is in samples.
|
||||
fn add_buffer_size(&mut self, size: usize) {
|
||||
if let Ok(size) = (size / USUAL_FRAME_SIZE).try_into() {
|
||||
self.last_buffer_size_min.push(size);
|
||||
self.last_buffer_size_max.push(Reverse(size));
|
||||
} else {
|
||||
warn!(parent: &self.span, size, "Failed to put amount of packets into an u8");
|
||||
}
|
||||
}
|
||||
|
||||
/// The approximate deviation of the buffer size.
|
||||
fn get_deviation(&self) -> u8 {
|
||||
let min = self.last_buffer_size_min.get_min();
|
||||
let max = self.last_buffer_size_max.get_min();
|
||||
max.0 - min
|
||||
}
|
||||
|
||||
fn add_packet(&mut self, packet: VoicePacket) -> Result<()> {
|
||||
let _span = self.span.enter();
|
||||
if self.packet_buffer.len() >= MAX_BUFFER_PACKETS {
|
||||
return Err(Error::QueueFull);
|
||||
}
|
||||
let samples;
|
||||
if packet.is_end() {
|
||||
// End of stream
|
||||
samples = 0;
|
||||
} else {
|
||||
samples = packet::get_nb_samples(&packet.payload, SAMPLE_RATE)
|
||||
.map_err(Error::GetPacketSample)?;
|
||||
if samples > MAX_BUFFER_SIZE {
|
||||
return Err(Error::TooManySamples);
|
||||
}
|
||||
}
|
||||
|
||||
let id = packet.seq;
|
||||
let packet = QueuePacket { packet, samples, id };
|
||||
if id.wrapping_sub(self.next_id) > MAX_BUFFER_PACKETS as u16 {
|
||||
return Err(Error::TooLate { wanted: self.next_id, got: id });
|
||||
}
|
||||
|
||||
// Put into first spot where the id is smaller
|
||||
let i = self.packet_buffer.len()
|
||||
- self
|
||||
.packet_buffer
|
||||
.iter()
|
||||
.enumerate()
|
||||
.rev()
|
||||
.take_while(|(_, p)| p.id.wrapping_sub(id) <= MAX_BUFFER_PACKETS as u16)
|
||||
.count();
|
||||
// Check for duplicate packet
|
||||
if let Some(p) = self.packet_buffer.get(i)
|
||||
&& p.id == packet.id
|
||||
{
|
||||
return Err(Error::Duplicate(p.id));
|
||||
}
|
||||
|
||||
trace!("Insert packet {} at {}", id, i);
|
||||
let last_id = self.packet_buffer.back().map(|p| p.id.wrapping_add(1)).unwrap_or(id);
|
||||
if last_id <= id {
|
||||
self.buffering_samples = self.buffering_samples.saturating_sub(samples);
|
||||
// Reduce buffering counter by lost packets if there are some
|
||||
self.buffering_samples = self
|
||||
.buffering_samples
|
||||
.saturating_sub(usize::from(id - last_id) * self.last_packet_samples);
|
||||
}
|
||||
|
||||
self.packet_buffer_samples += packet.samples;
|
||||
self.packet_buffer.insert(i, packet);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn decode_packet(&mut self, packet: Option<&QueuePacket>, fec: bool) -> Result<()> {
|
||||
let _span = self.span.clone().entered();
|
||||
trace!(has_packet = packet.is_some(), fec, "Decoding packet");
|
||||
let packet_data;
|
||||
let len;
|
||||
if let Some(p) = packet {
|
||||
packet_data = &p.packet.payload[..];
|
||||
len = p.samples;
|
||||
self.whispering = p.packet.whisper;
|
||||
} else {
|
||||
// An empty slice signals packet loss to the decoder
|
||||
packet_data = &[];
|
||||
len = self.last_packet_samples;
|
||||
}
|
||||
self.packet_loss_num += 1;
|
||||
|
||||
let orig_buffer_len = self.decoded_buffer.len();
|
||||
self.decoded_buffer.resize(orig_buffer_len + len * CHANNEL_NUM, 0.0);
|
||||
let len = self
|
||||
.decoder
|
||||
.decode_float(packet_data, &mut self.decoded_buffer[orig_buffer_len..], fec)
|
||||
.map_err(|e| Error::Decode {
|
||||
error: e,
|
||||
packet: packet.map(|p| p.packet.payload.clone()),
|
||||
})?;
|
||||
self.last_packet_samples = len;
|
||||
self.decoded_buffer.truncate(orig_buffer_len + len * CHANNEL_NUM);
|
||||
|
||||
// Update packet_loss_num
|
||||
if packet.is_some() && !fec {
|
||||
self.packet_loss_num = 0;
|
||||
}
|
||||
|
||||
// Update last_buffer_size
|
||||
let mut count = self.packet_buffer_samples;
|
||||
if let Some(last) = self.packet_buffer.back() {
|
||||
// Lost packets
|
||||
trace!(
|
||||
last.id,
|
||||
next_id = self.next_id,
|
||||
first_id = self.packet_buffer.front().unwrap().id,
|
||||
buffer_len = self.packet_buffer.len(),
|
||||
"Ids"
|
||||
);
|
||||
count += (usize::from(last.id.wrapping_sub(self.next_id)) + 1
|
||||
- self.packet_buffer.len())
|
||||
* self.last_packet_samples;
|
||||
}
|
||||
self.add_buffer_size(count);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decode data and return the requested length of buffered data.
|
||||
///
|
||||
/// Returns `true` in the second return value when the stream ended,
|
||||
/// `false` when it continues normally.
|
||||
pub fn get_next_data(&mut self, len: usize) -> Result<(&[f32], bool)> {
|
||||
let _span = self.span.clone().entered();
|
||||
if self.buffering_samples > 0 {
|
||||
if self.buffered_for_samples >= MAX_BUFFER_TIME {
|
||||
self.buffering_samples = 0;
|
||||
self.buffered_for_samples = 0;
|
||||
trace!(
|
||||
buffered_for_samples = self.buffered_for_samples,
|
||||
buffering_samples = self.buffering_samples,
|
||||
"Buffered for too long"
|
||||
);
|
||||
} else {
|
||||
self.buffered_for_samples += len;
|
||||
trace!(
|
||||
buffered_for_samples = self.buffered_for_samples,
|
||||
buffering_samples = self.buffering_samples,
|
||||
"Buffering"
|
||||
);
|
||||
return Ok((&[], false));
|
||||
}
|
||||
}
|
||||
// Need to refill buffer
|
||||
self.decoded_buffer.drain(..self.decoded_pos);
|
||||
|
||||
while self.decoded_buffer.len() < len {
|
||||
trace!(decoded_buffer = self.decoded_buffer.len(), len, "get_next_data");
|
||||
|
||||
// Decode a packet
|
||||
if let Some(packet) = self.packet_buffer.pop_front() {
|
||||
if packet.packet.is_end() {
|
||||
// End of stream
|
||||
return Ok((&self.decoded_buffer, true));
|
||||
}
|
||||
|
||||
self.packet_buffer_samples -= packet.samples;
|
||||
let cur_id = self.next_id;
|
||||
self.next_id = self.next_id.wrapping_add(1);
|
||||
if packet.id != cur_id {
|
||||
debug_assert!(
|
||||
packet.id.wrapping_sub(cur_id) < MAX_BUFFER_PACKETS as u16,
|
||||
"Invalid packet queue state: {} < {}",
|
||||
packet.id,
|
||||
cur_id
|
||||
);
|
||||
// Packet loss
|
||||
debug!(need = cur_id, have = packet.id, "Audio packet loss");
|
||||
if packet.id == self.next_id {
|
||||
// Can use forward-error-correction
|
||||
self.decode_packet(Some(&packet), true)?;
|
||||
} else {
|
||||
self.decode_packet(None, false)?;
|
||||
}
|
||||
self.packet_buffer_samples += packet.samples;
|
||||
self.packet_buffer.push_front(packet);
|
||||
} else {
|
||||
self.decode_packet(Some(&packet), false)?;
|
||||
}
|
||||
} else {
|
||||
debug!("No packets in queue");
|
||||
// Packet loss or end of stream
|
||||
self.decode_packet(None, false)?;
|
||||
}
|
||||
|
||||
if self.last_packet_samples == 0 {
|
||||
break;
|
||||
}
|
||||
|
||||
// Check if we should speed-up playback
|
||||
let min = self.last_buffer_size_min.get_min();
|
||||
let dev = self.get_deviation();
|
||||
if min > (MAX_BUFFER_SIZE / USUAL_FRAME_SIZE) as u8 {
|
||||
debug!(min, "Truncating buffer");
|
||||
// Throw out all but min samples
|
||||
let mut keep_samples = 0;
|
||||
let keep = self
|
||||
.packet_buffer
|
||||
.iter()
|
||||
.rev()
|
||||
.take_while(|p| {
|
||||
keep_samples += p.samples;
|
||||
keep_samples < usize::from(min) + USUAL_FRAME_SIZE
|
||||
})
|
||||
.count();
|
||||
let len = self.packet_buffer.len() - keep;
|
||||
self.packet_buffer.drain(..len);
|
||||
self.packet_buffer_samples = self.packet_buffer.iter().map(|p| p.samples).sum();
|
||||
if let Some(p) = self.packet_buffer.front() {
|
||||
self.next_id = p.id;
|
||||
}
|
||||
} else if min > dev {
|
||||
// Speed-up
|
||||
debug!(
|
||||
min,
|
||||
cur_packet_count = self.packet_buffer.len(),
|
||||
last_packet_samples = self.last_packet_samples,
|
||||
dev,
|
||||
"Speed-up buffer"
|
||||
);
|
||||
let start = self.decoded_buffer.len() - self.last_packet_samples * CHANNEL_NUM;
|
||||
for i in 0..(self.last_packet_samples / SPEED_CHANGE_STEPS) {
|
||||
let i = start + i * (SPEED_CHANGE_STEPS - 1) * CHANNEL_NUM;
|
||||
self.decoded_buffer.drain(i..(i + CHANNEL_NUM));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.decoded_pos = len;
|
||||
Ok((&self.decoded_buffer[..len], false))
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioHandler {
|
||||
pub fn new() -> Self {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
/// Delete all queues
|
||||
pub fn reset(&mut self) {
|
||||
self.queues.clear();
|
||||
}
|
||||
|
||||
pub fn get_queues(&self) -> &HashMap<TalkerId, AudioQueue> {
|
||||
&self.queues
|
||||
}
|
||||
pub fn get_mut_queues(&mut self) -> &mut HashMap<TalkerId, AudioQueue> {
|
||||
&mut self.queues
|
||||
}
|
||||
|
||||
/// `buf` is not cleared before filling it.
|
||||
///
|
||||
/// Returns the clients that are not talking anymore.
|
||||
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<TalkerId> {
|
||||
self.fill_buffer_with_proc(buf, |_, _| {})
|
||||
}
|
||||
|
||||
/// `buf` is not cleared before filling it.
|
||||
///
|
||||
/// Same as [`Self::fill_buffer`] but before merging a queue into the output buffer, a preprocessor
|
||||
/// function is called. The queue volume is applied after calling the preprocessor.
|
||||
///
|
||||
/// Returns the clients that are not talking anymore.
|
||||
pub fn fill_buffer_with_proc<F: FnMut(&TalkerId, &[f32])>(
|
||||
&mut self,
|
||||
buf: &mut [f32],
|
||||
mut handle: F,
|
||||
) -> Vec<TalkerId> {
|
||||
trace!(len = buf.len(), "Filling audio buffer");
|
||||
let mut to_remove = Vec::new();
|
||||
for (id, queue) in self.queues.iter_mut() {
|
||||
if queue.packet_loss_num >= MAX_PACKET_LOSSES {
|
||||
debug!(packet_loss_num = queue.packet_loss_num, "Removing talker");
|
||||
to_remove.push(*id);
|
||||
continue;
|
||||
}
|
||||
|
||||
let vol = queue.volume;
|
||||
match queue.get_next_data(buf.len()) {
|
||||
Err(error) => {
|
||||
warn!(%error, "Failed to decode audio packet");
|
||||
}
|
||||
Ok((r, is_end)) => {
|
||||
handle(id, r);
|
||||
for i in 0..r.len() {
|
||||
buf[i] += r[i] * vol;
|
||||
}
|
||||
if is_end {
|
||||
to_remove.push(*id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for id in &to_remove {
|
||||
self.queues.remove(id);
|
||||
}
|
||||
to_remove
|
||||
}
|
||||
|
||||
/// Add a packet to the queue of its talker.
|
||||
///
|
||||
/// If a new talker started talking, returns its id.
|
||||
pub fn handle_packet(&mut self, packet: VoicePacket) -> Result<Option<TalkerId>> {
|
||||
let id = packet.talker;
|
||||
let empty = packet.is_end();
|
||||
|
||||
if let Some(queue) = self.queues.get_mut(&id) {
|
||||
queue.add_packet(packet)?;
|
||||
Ok(None)
|
||||
} else {
|
||||
if empty {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let _span = info_span!("audio queue", client = ?id);
|
||||
trace!("Adding talker");
|
||||
let mut queue = AudioQueue::new(packet)?;
|
||||
if !self.queues.is_empty() {
|
||||
// Update avg_buffer_samples
|
||||
let total: usize = self
|
||||
.queues
|
||||
.values()
|
||||
.map(|q| usize::from(q.last_buffer_size_min.get_min()))
|
||||
.sum();
|
||||
self.avg_buffer_samples = USUAL_FRAME_SIZE + total / self.queues.len();
|
||||
}
|
||||
queue.buffering_samples = self.avg_buffer_samples;
|
||||
self.queues.insert(id, queue);
|
||||
Ok(Some(id))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use opus2::Encoder;
|
||||
|
||||
use super::*;
|
||||
use crate::packet::VoiceCodec;
|
||||
|
||||
type TestResult = std::result::Result<(), Box<dyn std::error::Error>>;
|
||||
|
||||
const ID: TalkerId = TalkerId(0);
|
||||
|
||||
fn packet(seq: u16, payload: &[u8]) -> VoicePacket {
|
||||
VoicePacket {
|
||||
talker: ID,
|
||||
seq,
|
||||
codec: VoiceCodec::Music,
|
||||
whisper: false,
|
||||
payload: payload.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
enum SimulateAction {
|
||||
CreateEncoder,
|
||||
/// Create packet with id.
|
||||
///
|
||||
/// The `bool` is `false` if packet handling should fail.
|
||||
ReceivePacket(u16, bool),
|
||||
ReceiveRaw(u16, Vec<u8>),
|
||||
/// Fetch audio of this sample count and expect a certain packet id.
|
||||
FillBuffer(usize, Option<u16>),
|
||||
/// Custom check
|
||||
Check(Box<dyn FnOnce(&AudioHandler)>),
|
||||
}
|
||||
|
||||
fn simulate(actions: Vec<SimulateAction>) -> TestResult {
|
||||
let mut encoder = None;
|
||||
let mut opus_output = [0; 1275]; // Max size for an opus packet
|
||||
let mut handler = AudioHandler::new();
|
||||
|
||||
for a in actions {
|
||||
println!("\nCurrent state");
|
||||
for q in &handler.queues {
|
||||
print!("Queue {:?}:", q.0);
|
||||
for p in &q.1.packet_buffer {
|
||||
print!(" {:?},", p);
|
||||
}
|
||||
println!();
|
||||
}
|
||||
|
||||
match a {
|
||||
SimulateAction::CreateEncoder => {
|
||||
encoder = Some(Encoder::new(
|
||||
48_000,
|
||||
opus2::Channels::Mono,
|
||||
opus2::Application::Voip,
|
||||
)?);
|
||||
}
|
||||
SimulateAction::ReceivePacket(i, success) => {
|
||||
let e = encoder.as_mut().unwrap();
|
||||
let data = vec![i as f32; USUAL_FRAME_SIZE];
|
||||
let len = e.encode_float(&data, &mut opus_output[..])?;
|
||||
if handler.handle_packet(packet(i, &opus_output[..len])).is_ok() != success {
|
||||
return Err(format!(
|
||||
"handle_packet returned {:?} but expected {:?}",
|
||||
!success, success
|
||||
)
|
||||
.into());
|
||||
}
|
||||
}
|
||||
SimulateAction::ReceiveRaw(i, data) => {
|
||||
let _ = handler.handle_packet(packet(i, &data));
|
||||
}
|
||||
SimulateAction::FillBuffer(size, expect) => {
|
||||
let mut buf = vec![0.0; size * 2]; // Stereo
|
||||
let cur_packet_id =
|
||||
handler.queues.get(&ID).and_then(|q| q.packet_buffer.front()).map(|p| p.id);
|
||||
handler.fill_buffer(&mut buf);
|
||||
let next_packet_id =
|
||||
handler.queues.get(&ID).and_then(|q| q.packet_buffer.front()).map(|p| p.id);
|
||||
|
||||
if expect.is_some() {
|
||||
assert_eq!(expect, cur_packet_id);
|
||||
assert_ne!(cur_packet_id, next_packet_id);
|
||||
}
|
||||
}
|
||||
SimulateAction::Check(f) => {
|
||||
f(&handler);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sliding_window_minimum() {
|
||||
let data = &[
|
||||
(5, 5),
|
||||
(6, 5),
|
||||
(3, 3),
|
||||
(4, 3),
|
||||
(6, 3),
|
||||
(5, 3),
|
||||
(6, 3),
|
||||
(6, 4),
|
||||
(6, 5),
|
||||
(6, 5),
|
||||
(6, 6),
|
||||
(7, 6),
|
||||
(5, 5),
|
||||
];
|
||||
let mut window = SlidingWindowMinimum::new(5);
|
||||
assert_eq!(window.get_min(), 0);
|
||||
for (i, (val, min)) in data.iter().enumerate() {
|
||||
println!("{:?}", window);
|
||||
window.push(*val);
|
||||
assert_eq!(window.get_min(), *min, "Failed in iteration {} ({:?})", i, window);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sliding_window_minimum_full() {
|
||||
let mut window = SlidingWindowMinimum::new(255);
|
||||
window.push(1);
|
||||
assert_eq!(window.get_min(), 1);
|
||||
for _ in 0..254 {
|
||||
window.push(2);
|
||||
}
|
||||
assert_eq!(window.get_min(), 1);
|
||||
window.push(2);
|
||||
assert_eq!(window.get_min(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packets_wrapping() {
|
||||
let mut handler = AudioHandler::new();
|
||||
let mut buf = vec![0.0; 48_000 / 100 * 2];
|
||||
|
||||
for i in 0..100 {
|
||||
let seq = 65_500u16.wrapping_add(i);
|
||||
handler.handle_packet(packet(seq, &[0, 0, 0, 0, 0, 0, 0])).unwrap();
|
||||
|
||||
if i > 5 {
|
||||
handler.fill_buffer(&mut buf);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Short and malformed packets of any content are errors, never panics.
|
||||
#[test]
|
||||
fn short_packet_fuzz() {
|
||||
let mut handler = AudioHandler::new();
|
||||
let mut buf = vec![0.0; 48_000 / 100 * 2];
|
||||
let mut state = 0x2545_f491_4f6c_dd1du64;
|
||||
let mut next = move || {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
state
|
||||
};
|
||||
|
||||
for _ in 0..3_000 {
|
||||
// Payloads of 0..=100 bytes: empty, a lone TOC byte, and frames of any shape.
|
||||
let len = (next() % 101) as usize;
|
||||
let payload: Vec<u8> = (0..len).map(|_| next() as u8).collect();
|
||||
let _ = handler.handle_packet(packet(30, &payload));
|
||||
|
||||
handler.fill_buffer(&mut buf);
|
||||
handler.fill_buffer(&mut buf);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packets_wrapping2() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for i in 0..100 {
|
||||
let i = 65_500u16.wrapping_add(i);
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
|
||||
}
|
||||
for _ in 0..4 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silence() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for _ in 0..100 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reversed() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for i in 0..5 {
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
|
||||
}
|
||||
a.push(SimulateAction::ReceivePacket(4, false));
|
||||
a.push(SimulateAction::ReceivePacket(3, false));
|
||||
for _ in 0..4 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
a.push(SimulateAction::ReceivePacket(0, true));
|
||||
a.push(SimulateAction::ReceivePacket(0, false));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(0)));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn big_whole() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for i in 27120..27124 {
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
|
||||
}
|
||||
a.push(SimulateAction::ReceiveRaw(27124, vec![2]));
|
||||
for _ in 0..10 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
for i in 27339..27349 {
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
for _ in 0..4 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_packet() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for i in 0..10 {
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
|
||||
}
|
||||
a.push(SimulateAction::ReceiveRaw(10, vec![]));
|
||||
for _ in 0..4 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packet_loss() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
a.push(SimulateAction::ReceivePacket(50, true));
|
||||
a.push(SimulateAction::ReceivePacket(53, true));
|
||||
for _ in 0..8 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packet_wrapping_loss() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
a.push(SimulateAction::ReceivePacket(65534, true));
|
||||
a.push(SimulateAction::ReceivePacket(0, true));
|
||||
for _ in 0..7 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
/// The talker is the key of the queues, and a new one is reported once.
|
||||
#[test]
|
||||
fn talkers_have_their_own_queues() -> TestResult {
|
||||
let mut encoder = Encoder::new(48_000, opus2::Channels::Mono, opus2::Application::Voip)?;
|
||||
let mut out = [0; 1275];
|
||||
let len = encoder.encode_float(&vec![0.1; USUAL_FRAME_SIZE], &mut out)?;
|
||||
let from = |talker: u16, seq: u16| VoicePacket {
|
||||
talker: TalkerId(talker),
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: out[..len].to_vec(),
|
||||
};
|
||||
let mut handler = AudioHandler::new();
|
||||
assert_eq!(handler.handle_packet(from(7, 100))?, Some(TalkerId(7)));
|
||||
assert_eq!(handler.handle_packet(from(7, 101))?, None);
|
||||
assert_eq!(handler.handle_packet(from(9, 5))?, Some(TalkerId(9)));
|
||||
let mut talkers: Vec<_> = handler.get_queues().keys().map(|t| t.0).collect();
|
||||
talkers.sort_unstable();
|
||||
assert_eq!(talkers, [7, 9]);
|
||||
// A talker that only says goodbye never gets a queue.
|
||||
let end = VoicePacket { payload: vec![], ..from(11, 0) };
|
||||
assert_eq!(handler.handle_packet(end)?, None);
|
||||
assert_eq!(handler.get_queues().len(), 2);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A queue knows whether the last packet it played was a whisper.
|
||||
#[test]
|
||||
fn whisper_flag_follows_the_packets() -> TestResult {
|
||||
let mut encoder = Encoder::new(48_000, opus2::Channels::Mono, opus2::Application::Voip)?;
|
||||
let mut out = [0; 1275];
|
||||
let len = encoder.encode_float(&vec![0.1; USUAL_FRAME_SIZE], &mut out)?;
|
||||
let packet = |seq: u16, whisper: bool| VoicePacket {
|
||||
talker: ID,
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper,
|
||||
payload: out[..len].to_vec(),
|
||||
};
|
||||
let mut handler = AudioHandler::new();
|
||||
handler.handle_packet(packet(0, true))?;
|
||||
assert!(handler.get_queues()[&ID].is_whispering());
|
||||
handler.handle_packet(packet(1, false))?;
|
||||
// One packet is played per call.
|
||||
let mut buf = [0.0; USUAL_FRAME_SIZE * 2];
|
||||
handler.fill_buffer(&mut buf);
|
||||
handler.fill_buffer(&mut buf);
|
||||
assert!(!handler.get_queues()[&ID].is_whispering());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,17 @@
|
||||
//! Voice pipeline building blocks.
|
||||
//!
|
||||
//! - [`pcm`]: sample-rate constants, tone generation and detection helpers
|
||||
//! - [`encode`]: Opus encoding of 20 ms frames into TeamSpeak voice packets
|
||||
//! - [`packet`]: the voice packet types the pipeline takes and produces
|
||||
//! ([`VoicePacket`], [`EncodedVoice`]), independent of the transport
|
||||
//! - [`encode`]: Opus encoding of 20 ms frames into [`EncodedVoice`]
|
||||
//! - [`framer`]: slice an arbitrary sample stream into codec frames
|
||||
//! - [`resample`]: sample-rate conversion to the 48 kHz the codec uses
|
||||
//! - [`wav`]: WAV file input/output
|
||||
//! - [`process`]: echo cancellation, noise suppression and gain control
|
||||
//! - [`vad`]: voice activity detection
|
||||
//! - [`mixer`]: per-client jitter buffer, decoder, volume and mixing (on the
|
||||
//! vendored `tsclientlib::audio::AudioHandler`)
|
||||
//! - [`jitter`]: the per-talker jitter buffer and Opus decoder
|
||||
//! - [`mixer`]: per-talker volume, mute and priority dimming over the jitter
|
||||
//! buffer, mixing to stereo
|
||||
//! - [`settings`]: all user audio settings in one serde struct
|
||||
//! - [`tap`]: the processed microphone for other consumers (the stream
|
||||
//! mixer), free while nobody listens
|
||||
@@ -17,7 +20,9 @@
|
||||
|
||||
pub mod encode;
|
||||
pub mod framer;
|
||||
pub mod jitter;
|
||||
pub mod mixer;
|
||||
pub mod packet;
|
||||
pub mod pcm;
|
||||
pub mod process;
|
||||
pub mod resample;
|
||||
@@ -29,12 +34,13 @@ pub mod wav;
|
||||
#[cfg(feature = "device")]
|
||||
pub mod device;
|
||||
|
||||
pub use encode::{VoiceCodec, VoiceEncoder};
|
||||
pub use encode::VoiceEncoder;
|
||||
pub use framer::Framer;
|
||||
pub use jitter::AudioHandler;
|
||||
pub use mixer::Mixer;
|
||||
pub use packet::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket};
|
||||
pub use process::{ProcessingSettings, Processor};
|
||||
pub use settings::AudioSettings;
|
||||
pub use tsclientlib::audio::AudioHandler;
|
||||
pub use vad::{Vad, VadSettings};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! Incoming voice: per-client jitter buffer, decoder and mixer, with a
|
||||
//! volume and mute per client.
|
||||
//! Incoming voice: per-talker jitter buffer, decoder and mixer, with a
|
||||
//! volume and mute per talker, and everyone else dimmed while a priority
|
||||
//! speaker talks.
|
||||
//!
|
||||
//! The jitter buffer is the vendored `tsclientlib::audio::AudioHandler`. Per
|
||||
//! sender it keeps a queue of Opus packets and adapts its length:
|
||||
//! The jitter buffer is [`AudioHandler`]. Per sender it keeps a queue of Opus
|
||||
//! packets and adapts its length:
|
||||
//!
|
||||
//! - a new talker starts after a pre-buffer derived from the queue lengths of
|
||||
//! the other talkers (none for the first one);
|
||||
@@ -20,20 +21,46 @@
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use tsclientlib::ClientId;
|
||||
use tsclientlib::audio::{AudioHandler, Error as QueueError};
|
||||
use tsproto_packets::packets::InAudioBuf;
|
||||
use crate::jitter::{AudioHandler, Error as QueueError};
|
||||
use crate::packet::{TalkerId, VoicePacket};
|
||||
use crate::pcm::FRAME_SAMPLES;
|
||||
|
||||
/// Loudest per-client volume: +12 dB.
|
||||
/// Loudest per-talker volume: +12 dB.
|
||||
pub const MAX_CLIENT_VOLUME: f32 = 4.0;
|
||||
/// Most a priority speaker dims the others (dB).
|
||||
const MAX_DIMM_DB: f32 = -60.0;
|
||||
/// The dimming for a priority speaker fades in and out over this many
|
||||
/// samples (5 frames, 100 ms) instead of jumping.
|
||||
const DIMM_RAMP_SAMPLES: usize = 5 * FRAME_SAMPLES;
|
||||
|
||||
/// Jitter buffer, decoder and mixer for incoming voice, keyed by sender.
|
||||
/// Jitter buffer, decoder and mixer for incoming voice, keyed by talker.
|
||||
/// Output is interleaved stereo at 48 kHz.
|
||||
#[derive(Default)]
|
||||
pub struct Mixer {
|
||||
handler: AudioHandler<ClientId>,
|
||||
volumes: HashMap<ClientId, f32>,
|
||||
muted: HashSet<ClientId>,
|
||||
handler: AudioHandler,
|
||||
volumes: HashMap<TalkerId, f32>,
|
||||
muted: HashSet<TalkerId>,
|
||||
/// While one of them talks, everyone else is dimmed.
|
||||
priority: HashSet<TalkerId>,
|
||||
/// Linear gain of the others while a priority speaker talks (1: none).
|
||||
dimm: f32,
|
||||
/// How far the dimming has faded in (0..=1).
|
||||
fade: f32,
|
||||
/// The others' mix while the dimming fades (reused).
|
||||
others: Vec<f32>,
|
||||
}
|
||||
|
||||
impl Default for Mixer {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
handler: AudioHandler::new(),
|
||||
volumes: HashMap::new(),
|
||||
muted: HashSet::new(),
|
||||
priority: HashSet::new(),
|
||||
dimm: 1.0,
|
||||
fade: 0.0,
|
||||
others: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Mixer {
|
||||
@@ -41,35 +68,76 @@ impl Mixer {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Queue a voice packet from `id`. Returns `Some(id)` when this client
|
||||
/// just started talking. Late, duplicate and malformed packets are
|
||||
/// errors; on UDP they are expected and can be ignored.
|
||||
pub fn handle_packet(
|
||||
&mut self,
|
||||
id: ClientId,
|
||||
packet: InAudioBuf,
|
||||
) -> Result<Option<ClientId>, QueueError> {
|
||||
self.handler.handle_packet(id, packet)
|
||||
/// Queue a voice packet for its talker. Returns `Some(talker)` when this
|
||||
/// talker just started talking. Late, duplicate and malformed packets are
|
||||
/// errors; on datagrams they are expected and can be ignored.
|
||||
pub fn handle_packet(&mut self, packet: VoicePacket) -> Result<Option<TalkerId>, QueueError> {
|
||||
self.handler.handle_packet(packet)
|
||||
}
|
||||
|
||||
/// Add the next `buf.len() / 2` stereo frames of all talkers to `buf`
|
||||
/// (not cleared first), each scaled by its volume. Returns the clients
|
||||
/// that stopped talking.
|
||||
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<ClientId> {
|
||||
for (id, queue) in self.handler.get_mut_queues() {
|
||||
queue.volume = if self.muted.contains(id) {
|
||||
/// (not cleared first), each scaled by its volume, and dimmed while a
|
||||
/// priority speaker talks. Returns the talkers that stopped talking.
|
||||
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<TalkerId> {
|
||||
let queues = self.handler.get_mut_queues();
|
||||
// A priority speaker with a queue (talking or buffering) dims all
|
||||
// other queues, streams too, unless we muted it.
|
||||
let dim = queues.keys().any(|id| self.priority.contains(id) && !self.muted.contains(id));
|
||||
let frames = buf.len() / 2;
|
||||
let step = frames as f32 / DIMM_RAMP_SAMPLES as f32;
|
||||
let from = self.fade;
|
||||
self.fade = if dim { (from + step).min(1.0) } else { (from - step).max(0.0) };
|
||||
let to = self.fade;
|
||||
let dimm = self.dimm;
|
||||
let gain = |fade: f32| 1.0 + (dimm - 1.0) * fade;
|
||||
let fading = from != to;
|
||||
// While fading, the others are mixed into a buffer of their own and
|
||||
// ramped sample by sample; the priority speakers go straight to `buf`.
|
||||
let mut priority = Vec::new();
|
||||
for (id, queue) in queues {
|
||||
// Muted talkers are still decoded so their queues stay in sync.
|
||||
let volume = if self.muted.contains(id) {
|
||||
0.0
|
||||
} else {
|
||||
self.volumes.get(id).copied().unwrap_or(1.0)
|
||||
};
|
||||
queue.volume = if self.priority.contains(id) {
|
||||
if fading {
|
||||
priority.push((*id, volume));
|
||||
0.0
|
||||
} else {
|
||||
volume
|
||||
}
|
||||
} else if fading {
|
||||
volume
|
||||
} else {
|
||||
volume * gain(to)
|
||||
};
|
||||
}
|
||||
// Muted talkers are still decoded so their queues stay in sync.
|
||||
self.handler.fill_buffer(buf)
|
||||
if !fading {
|
||||
return self.handler.fill_buffer(buf);
|
||||
}
|
||||
self.others.clear();
|
||||
self.others.resize(buf.len(), 0.0);
|
||||
let stopped = self.handler.fill_buffer_with_proc(&mut self.others, |id, samples| {
|
||||
if let Some(&(_, volume)) = priority.iter().find(|(p, _)| p == id) {
|
||||
for (out, s) in buf.iter_mut().zip(samples) {
|
||||
*out += s * volume;
|
||||
}
|
||||
}
|
||||
});
|
||||
// From the last frame's gain to this one's.
|
||||
for (i, (out, s)) in buf.chunks_exact_mut(2).zip(self.others.chunks_exact(2)).enumerate() {
|
||||
let g = gain(from + (to - from) * (i + 1) as f32 / frames as f32);
|
||||
out[0] += s[0] * g;
|
||||
out[1] += s[1] * g;
|
||||
}
|
||||
stopped
|
||||
}
|
||||
|
||||
/// Linear gain for one client, clamped to `0..=`[`MAX_CLIENT_VOLUME`].
|
||||
/// Kept when the client stops and starts talking again.
|
||||
pub fn set_volume(&mut self, id: ClientId, volume: f32) {
|
||||
/// Linear gain for one talker, clamped to `0..=`[`MAX_CLIENT_VOLUME`].
|
||||
/// Kept when the talker stops and starts talking again.
|
||||
pub fn set_volume(&mut self, id: TalkerId, volume: f32) {
|
||||
let volume = if volume.is_finite() { volume.clamp(0.0, MAX_CLIENT_VOLUME) } else { 1.0 };
|
||||
if volume == 1.0 {
|
||||
self.volumes.remove(&id);
|
||||
@@ -79,15 +147,15 @@ impl Mixer {
|
||||
}
|
||||
|
||||
/// Like [`set_volume`](Self::set_volume), in dB (0 dB = unchanged).
|
||||
pub fn set_volume_db(&mut self, id: ClientId, db: f32) {
|
||||
pub fn set_volume_db(&mut self, id: TalkerId, db: f32) {
|
||||
self.set_volume(id, 10f32.powf(db / 20.0));
|
||||
}
|
||||
|
||||
pub fn volume(&self, id: ClientId) -> f32 {
|
||||
pub fn volume(&self, id: TalkerId) -> f32 {
|
||||
self.volumes.get(&id).copied().unwrap_or(1.0)
|
||||
}
|
||||
|
||||
pub fn set_muted(&mut self, id: ClientId, muted: bool) {
|
||||
pub fn set_muted(&mut self, id: TalkerId, muted: bool) {
|
||||
if muted {
|
||||
self.muted.insert(id);
|
||||
} else {
|
||||
@@ -95,20 +163,30 @@ impl Mixer {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_muted(&self, id: ClientId) -> bool {
|
||||
pub fn is_muted(&self, id: TalkerId) -> bool {
|
||||
self.muted.contains(&id)
|
||||
}
|
||||
|
||||
/// Forget volume and mute of a client (e.g. it left the server; client
|
||||
/// ids are reused).
|
||||
pub fn forget(&mut self, id: ClientId) {
|
||||
/// The priority speakers, and how much everyone else is dimmed while
|
||||
/// one of them talks: dB, clamped to -60..=0 (NaN: not at all).
|
||||
/// Replaces the previous set; [`forget`](Self::forget) leaves it alone,
|
||||
/// the caller sends a new set when the talkers change.
|
||||
pub fn set_priority(&mut self, talkers: impl IntoIterator<Item = TalkerId>, dimm_db: f32) {
|
||||
self.priority = talkers.into_iter().collect();
|
||||
let db = if dimm_db.is_nan() { 0.0 } else { dimm_db.clamp(MAX_DIMM_DB, 0.0) };
|
||||
self.dimm = 10f32.powf(db / 20.0);
|
||||
}
|
||||
|
||||
/// Forget volume and mute of a talker (e.g. it left the server; ids may
|
||||
/// be reused).
|
||||
pub fn forget(&mut self, id: TalkerId) {
|
||||
self.volumes.remove(&id);
|
||||
self.muted.remove(&id);
|
||||
self.handler.get_mut_queues().remove(&id);
|
||||
}
|
||||
|
||||
/// Clients with a queue, i.e. currently talking or buffering.
|
||||
pub fn talkers(&self) -> impl Iterator<Item = ClientId> + '_ {
|
||||
/// Talkers with a queue, i.e. currently talking or buffering.
|
||||
pub fn talkers(&self) -> impl Iterator<Item = TalkerId> + '_ {
|
||||
self.handler.get_queues().keys().copied()
|
||||
}
|
||||
|
||||
@@ -118,7 +196,7 @@ impl Mixer {
|
||||
}
|
||||
|
||||
/// The underlying jitter buffer.
|
||||
pub fn handler(&self) -> &AudioHandler<ClientId> {
|
||||
pub fn handler(&self) -> &AudioHandler {
|
||||
&self.handler
|
||||
}
|
||||
}
|
||||
@@ -129,29 +207,34 @@ impl std::fmt::Debug for Mixer {
|
||||
.field("talkers", &self.handler.get_queues().len())
|
||||
.field("volumes", &self.volumes)
|
||||
.field("muted", &self.muted)
|
||||
.field("priority", &self.priority)
|
||||
.field("dimm", &self.dimm)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tsproto_packets::packets::{AudioData, CodecType, Direction, OutAudio};
|
||||
|
||||
use super::*;
|
||||
use crate::VoiceEncoder;
|
||||
use crate::encode::VoiceCodec;
|
||||
use crate::packet::VoiceCodec;
|
||||
use crate::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
|
||||
|
||||
fn packet(from: u16, id: u16, data: &[u8]) -> InAudioBuf {
|
||||
let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data });
|
||||
InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap()
|
||||
fn packet(from: u16, seq: u16, data: &[u8]) -> VoicePacket {
|
||||
VoicePacket {
|
||||
talker: TalkerId(from),
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: data.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Two clients send tones at the same level; after setting volumes the
|
||||
/// mix carries each at its own gain, and a muted one not at all.
|
||||
#[test]
|
||||
fn volume_per_client() {
|
||||
let (a, b) = (ClientId(3), ClientId(4));
|
||||
let (a, b) = (TalkerId(3), TalkerId(4));
|
||||
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut enc_b = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let tone_a = pcm::sine(500.0, 2.0, 0.2);
|
||||
@@ -165,11 +248,11 @@ mod tests {
|
||||
let frames = tone_a.chunks_exact(FRAME_SAMPLES).zip(tone_b.chunks_exact(FRAME_SAMPLES));
|
||||
for (i, (fa, fb)) in frames.enumerate() {
|
||||
let id = i as u16;
|
||||
let started = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
|
||||
let started = mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
|
||||
if i == 0 {
|
||||
assert_eq!(started.unwrap(), Some(a));
|
||||
}
|
||||
mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap())).unwrap();
|
||||
mixer.handle_packet(packet(4, id, enc_b.encode_to_bytes(fb).unwrap())).unwrap();
|
||||
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
|
||||
mixer.fill_buffer(&mut buf);
|
||||
out.extend(pcm::to_mono(&buf, 2));
|
||||
@@ -188,8 +271,8 @@ mod tests {
|
||||
let id = 100 + i;
|
||||
let fa = &tone_a[..FRAME_SAMPLES];
|
||||
let fb = &tone_b[..FRAME_SAMPLES];
|
||||
let _ = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
|
||||
let _ = mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap()));
|
||||
let _ = mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
|
||||
let _ = mixer.handle_packet(packet(4, id, enc_b.encode_to_bytes(fb).unwrap()));
|
||||
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
|
||||
mixer.fill_buffer(&mut buf);
|
||||
out.extend(pcm::to_mono(&buf, 2));
|
||||
@@ -199,10 +282,138 @@ mod tests {
|
||||
assert!(pcm::goertzel_power(tail, 500.0, SAMPLE_RATE) > 1e-4);
|
||||
}
|
||||
|
||||
/// A priority speaker dims the other talker by the server's -18 dB, fading
|
||||
/// in and out, but not itself, and not while we muted it.
|
||||
#[test]
|
||||
fn priority_speaker_dims_others() {
|
||||
let (a, p) = (TalkerId(3), TalkerId(5));
|
||||
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut enc_p = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let tone_a = pcm::sine(500.0, 4.0, 0.2);
|
||||
let tone_p = pcm::sine(1300.0, 4.0, 0.2);
|
||||
let frame = |tone: &[f32], i: u16| {
|
||||
let at = i as usize * FRAME_SAMPLES;
|
||||
tone[at..at + FRAME_SAMPLES].to_vec()
|
||||
};
|
||||
|
||||
let mut mixer = Mixer::new();
|
||||
mixer.set_priority([p], -18.0);
|
||||
let (mut id_a, mut id_p) = (0u16, 0u16);
|
||||
// `frames` frames with a talking and p too if `with_p`; returns the
|
||||
// second half of the mix.
|
||||
let mut play = |mixer: &mut Mixer, frames: u16, with_p: bool| {
|
||||
let mut out = Vec::new();
|
||||
for _ in 0..frames {
|
||||
let fa = frame(&tone_a, id_a);
|
||||
mixer.handle_packet(packet(3, id_a, enc_a.encode_to_bytes(&fa).unwrap())).unwrap();
|
||||
id_a += 1;
|
||||
if with_p {
|
||||
let fp = frame(&tone_p, id_p);
|
||||
let data = enc_p.encode_to_bytes(&fp).unwrap();
|
||||
mixer.handle_packet(packet(5, id_p, data)).unwrap();
|
||||
id_p += 1;
|
||||
}
|
||||
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
|
||||
mixer.fill_buffer(&mut buf);
|
||||
out.extend(pcm::to_mono(&buf, 2));
|
||||
}
|
||||
out.split_off(out.len() / 2)
|
||||
};
|
||||
let power = |out: &[f32], f| pcm::goertzel_power(out, f, SAMPLE_RATE);
|
||||
let db = |level: f32, full: f32| 10.0 * (level / full).log10();
|
||||
|
||||
let alone = play(&mut mixer, 30, false);
|
||||
let full = power(&alone, 500.0);
|
||||
assert!(full > 1e-4);
|
||||
// The dimming fades in over 5 frames: 1/5 of the way after the first.
|
||||
play(&mut mixer, 1, true);
|
||||
assert!((mixer.fade - 0.2).abs() < 1e-6, "fade {}", mixer.fade);
|
||||
let both = play(&mut mixer, 50, true);
|
||||
let dimmed = db(power(&both, 500.0), full);
|
||||
assert!((dimmed + 18.0).abs() < 1.0, "dimmed by {dimmed} dB");
|
||||
let own = db(power(&both, 1300.0), full);
|
||||
assert!(own.abs() < 1.0, "priority speaker at {own} dB");
|
||||
|
||||
// p stops: its queue ends after three lost frames, and a is back.
|
||||
let after = play(&mut mixer, 40, false);
|
||||
assert_eq!(mixer.talkers().collect::<Vec<_>>(), vec![a]);
|
||||
assert_eq!(mixer.fade, 0.0);
|
||||
let back = db(power(&after, 500.0), full);
|
||||
assert!(back.abs() < 1.0, "after the priority speaker: {back} dB");
|
||||
|
||||
// A priority speaker we muted dims nobody.
|
||||
mixer.set_muted(p, true);
|
||||
let muted = play(&mut mixer, 40, true);
|
||||
assert_eq!(mixer.talkers().count(), 2);
|
||||
let level = db(power(&muted, 500.0), full);
|
||||
assert!(level.abs() < 1.0, "muted priority speaker: {level} dB");
|
||||
assert!(power(&muted, 1300.0) < 1e-6);
|
||||
}
|
||||
|
||||
/// The dimming fades in and out sample by sample, not in a step per
|
||||
/// frame: the other talker's level (per period of its tone) never jumps.
|
||||
#[test]
|
||||
fn priority_dimming_ramps_per_sample() {
|
||||
let p = TalkerId(5);
|
||||
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut enc_p = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let tone = pcm::sine(500.0, 2.0, 0.2);
|
||||
let mut mixer = Mixer::new();
|
||||
mixer.set_priority([p], -18.0);
|
||||
// p is not heard (volume 0) but dims, so the mix is a's tone alone.
|
||||
mixer.set_volume(p, 0.0);
|
||||
let mut out = Vec::new();
|
||||
// p talks from frame 30 to 59.
|
||||
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
|
||||
let id = i as u16;
|
||||
mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(frame).unwrap())).unwrap();
|
||||
if let Some(j) = i.checked_sub(30).filter(|j| *j < 30) {
|
||||
let data = enc_p.encode_to_bytes(frame).unwrap();
|
||||
mixer.handle_packet(packet(5, j as u16, data)).unwrap();
|
||||
}
|
||||
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
|
||||
mixer.fill_buffer(&mut buf);
|
||||
out.extend(pcm::to_mono(&buf, 2));
|
||||
}
|
||||
assert_eq!(mixer.fade, 0.0);
|
||||
// The level per period of the 500 Hz tone (96 samples, 10 a frame).
|
||||
let level: Vec<f32> = out.chunks_exact(96).map(|c| pcm::energy(c).sqrt()).collect();
|
||||
let full = level[200..300].iter().sum::<f32>() / 100.0;
|
||||
let mean = |range: std::ops::Range<usize>| {
|
||||
level[range.clone()].iter().sum::<f32>() / range.len() as f32 / full
|
||||
};
|
||||
let jump = level[200..].windows(2).map(|w| (w[1] - w[0]).abs() / full).fold(0.0, f32::max);
|
||||
assert!(jump < 0.05, "the level jumps by {jump} of full");
|
||||
// Fully dimmed after 5 frames, and back after p's queue ended.
|
||||
let dimmed = mean(350..600);
|
||||
assert!((dimmed - 0.126).abs() < 0.02, "dimmed to {dimmed}");
|
||||
let back = mean(800..1000);
|
||||
assert!((back - 1.0).abs() < 0.05, "back to {back}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn priority_dimm_bounds() {
|
||||
let mut mixer = Mixer::new();
|
||||
assert_eq!(mixer.dimm, 1.0);
|
||||
mixer.set_priority([TalkerId(1)], -18.0);
|
||||
assert!((mixer.dimm - 0.1259).abs() < 1e-3);
|
||||
mixer.set_priority([TalkerId(1)], 6.0);
|
||||
assert_eq!(mixer.dimm, 1.0);
|
||||
mixer.set_priority([TalkerId(1)], f32::NEG_INFINITY);
|
||||
assert!((mixer.dimm - 0.001).abs() < 1e-6);
|
||||
mixer.set_priority([TalkerId(1)], f32::NAN);
|
||||
assert_eq!(mixer.dimm, 1.0);
|
||||
// Forgetting a client keeps the set: the caller replaces it.
|
||||
mixer.forget(TalkerId(1));
|
||||
assert!(mixer.priority.contains(&TalkerId(1)));
|
||||
mixer.set_priority([], -18.0);
|
||||
assert!(mixer.priority.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volume_bounds_and_forget() {
|
||||
let mut mixer = Mixer::new();
|
||||
let id = ClientId(9);
|
||||
let id = TalkerId(9);
|
||||
mixer.set_volume(id, 100.0);
|
||||
assert_eq!(mixer.volume(id), MAX_CLIENT_VOLUME);
|
||||
mixer.set_volume(id, -1.0);
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
//! Voice packets as the audio pipeline sees them, whatever transport carries
|
||||
//! them (the TeamSpeak connection today, a Voelin server later).
|
||||
//!
|
||||
//! The transport adapter turns what it receives into a [`VoicePacket`] and
|
||||
//! what [`VoiceEncoder`](crate::VoiceEncoder) produces ([`EncodedVoice`])
|
||||
//! into its own wire format; nothing in this crate knows either format.
|
||||
|
||||
use crate::pcm::FRAME_SAMPLES;
|
||||
|
||||
/// Who is talking: a sender id, unique among the talkers of one voice
|
||||
/// connection. A transport maps its own client ids onto it (TeamSpeak's
|
||||
/// 16-bit client id is used as is).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct TalkerId(pub u16);
|
||||
|
||||
/// The two Opus flavours voice is sent in.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum VoiceCodec {
|
||||
/// Mono, tuned for speech.
|
||||
Voice,
|
||||
/// Stereo, tuned for music.
|
||||
Music,
|
||||
}
|
||||
|
||||
impl VoiceCodec {
|
||||
pub fn channels(self) -> usize {
|
||||
match self {
|
||||
VoiceCodec::Voice => 1,
|
||||
VoiceCodec::Music => 2,
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples (all channels) in one 20 ms frame.
|
||||
pub fn frame_len(self) -> usize {
|
||||
FRAME_SAMPLES * self.channels()
|
||||
}
|
||||
}
|
||||
|
||||
/// A voice packet received from a talker.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct VoicePacket {
|
||||
pub talker: TalkerId,
|
||||
/// Packet number of this talker, counting up by one per 20 ms frame and
|
||||
/// wrapping at 65536; the jitter buffer orders by it and finds gaps.
|
||||
pub seq: u16,
|
||||
pub codec: VoiceCodec,
|
||||
/// Sent to us as a whisper instead of to the whole channel.
|
||||
pub whisper: bool,
|
||||
/// One Opus packet. An empty one ends the talk (a single byte counts as
|
||||
/// empty too: some servers send one).
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl VoicePacket {
|
||||
/// Whether this packet only ends the talk and carries no audio.
|
||||
pub fn is_end(&self) -> bool {
|
||||
self.payload.len() <= 1
|
||||
}
|
||||
}
|
||||
|
||||
/// One encoded frame to send. The transport assigns the packet number.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct EncodedVoice {
|
||||
pub codec: VoiceCodec,
|
||||
/// One Opus packet; empty: the transmission ended.
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl EncodedVoice {
|
||||
/// Whether this only tells listeners the transmission ended.
|
||||
pub fn is_end(&self) -> bool {
|
||||
self.payload.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn codec_frames() {
|
||||
assert_eq!(VoiceCodec::Voice.frame_len(), FRAME_SAMPLES);
|
||||
assert_eq!(VoiceCodec::Music.frame_len(), FRAME_SAMPLES * 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_of_talk() {
|
||||
let voice = |payload: &[u8]| VoicePacket {
|
||||
talker: TalkerId(1),
|
||||
seq: 0,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: payload.to_vec(),
|
||||
};
|
||||
assert!(voice(&[]).is_end());
|
||||
assert!(voice(&[2]).is_end());
|
||||
assert!(!voice(&[2, 3]).is_end());
|
||||
assert!(EncodedVoice { codec: VoiceCodec::Voice, payload: vec![] }.is_end());
|
||||
assert!(!EncodedVoice { codec: VoiceCodec::Voice, payload: vec![0] }.is_end());
|
||||
}
|
||||
}
|
||||
@@ -7,10 +7,8 @@
|
||||
//! loss. Every 30 s it sends a loud marker frame instead of the quiet one;
|
||||
//! the latency is the time from generating a marker to it leaving the mixer.
|
||||
|
||||
use tsclientlib::ClientId;
|
||||
use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio};
|
||||
use voelin_audio::pcm::{FRAME_SAMPLES, SAMPLE_RATE, energy, sine, white_noise};
|
||||
use voelin_audio::{Mixer, VoiceCodec, VoiceEncoder};
|
||||
use voelin_audio::{Mixer, TalkerId, VoiceCodec, VoiceEncoder, VoicePacket};
|
||||
|
||||
/// The receiver pulls 10 ms at a time, like a playback loop.
|
||||
const PULL: usize = SAMPLE_RATE as usize / 100;
|
||||
@@ -38,7 +36,7 @@ fn simulate(ppm: f64, hours: f64) -> Vec<f64> {
|
||||
|
||||
let mut rng = Rng(ppm.to_bits());
|
||||
let mut mixer = Mixer::new();
|
||||
let client = ClientId(5);
|
||||
let talker = TalkerId(5);
|
||||
let total = (hours * 3600.0 * SAMPLE_RATE as f64) as u64;
|
||||
// Sender frame n is made at n * 20 ms of the sender's clock.
|
||||
let frame_time = |n: u64| n as f64 * FRAME_SAMPLES as f64 / (1.0 + ppm * 1e-6);
|
||||
@@ -68,15 +66,15 @@ fn simulate(ppm: f64, hours: f64) -> Vec<f64> {
|
||||
let arrived = in_flight.partition_point(|&(t, _)| t <= now as f64);
|
||||
for (_, n) in in_flight.drain(..arrived) {
|
||||
let data = if n % MARKER_EVERY == MARKER_EVERY / 2 { &marker } else { &quiet };
|
||||
let packet = OutAudio::new(&AudioData::S2C {
|
||||
id: n as u16,
|
||||
codec: CodecType::OpusVoice,
|
||||
from: 5,
|
||||
data,
|
||||
});
|
||||
let packet = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
|
||||
let packet = VoicePacket {
|
||||
talker,
|
||||
seq: n as u16,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: data.clone(),
|
||||
};
|
||||
// Late packets are dropped by the jitter buffer, as on a real network.
|
||||
let _ = mixer.handle_packet(client, packet);
|
||||
let _ = mixer.handle_packet(packet);
|
||||
}
|
||||
|
||||
out.fill(0.0);
|
||||
|
||||
@@ -14,11 +14,12 @@ default = ["audio-device"]
|
||||
audio-device = ["voelin-audio/device"]
|
||||
# The `media` module: capture and video codecs for streams, with whatever
|
||||
# voelin-media backends are enabled (e.g. MediaCodec and a registered capture
|
||||
# source on Android).
|
||||
media = ["dep:voelin-media"]
|
||||
# `media` with voelin-media's desktop backends: libvpx, OpenH264 loaded at
|
||||
# runtime, X11 and PipeWire on Linux. Not for Android (libvpx does not
|
||||
# cross-compile there).
|
||||
# source on Android), and the studio's WHIP output. The crate itself is always
|
||||
# there: the stream types in the API (`EncodedFrame`, `LayerSpec`) are its.
|
||||
media = ["voelin-media/whip"]
|
||||
# `media` with voelin-media's desktop backends: libvpx, dav1d, OpenH264 and
|
||||
# FFmpeg loaded at runtime, X11 and PipeWire on Linux. Not for Android
|
||||
# (libvpx does not cross-compile there).
|
||||
media-desktop = ["media", "voelin-media/default"]
|
||||
|
||||
[dependencies]
|
||||
@@ -29,8 +30,15 @@ futures = "0.3"
|
||||
# Finding a server's gateway in DNS (the voice resolver's version).
|
||||
hickory-resolver = "0.26"
|
||||
md5 = "0.8"
|
||||
# A stalled HTTP/2 connection's error, told apart (the version reqwest's hyper
|
||||
# uses).
|
||||
h2 = "0.4"
|
||||
# Retry-After dates (already in the tree through hyper).
|
||||
httpdate = "1"
|
||||
# Banners on the web; the client the workspace has (voelin-query, voelin-media).
|
||||
reqwest = { version = "0.13.5", default-features = false, features = ["rustls"] }
|
||||
# `system-proxy`: the proxy settings of Windows and macOS; `socks`: SOCKS
|
||||
# proxies (from the desktop's settings or ALL_PROXY).
|
||||
reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "socks", "system-proxy"] }
|
||||
# Reading the official clients' settings.db when importing identities.
|
||||
rusqlite = { version = "0.40.2", features = ["bundled"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
@@ -42,7 +50,7 @@ toml = "1.1.6"
|
||||
tracing = "0.1"
|
||||
voelin-audio = { path = "../voelin-audio", default-features = false }
|
||||
voelin-gateway-proto = { path = "../voelin-gateway-proto", features = ["client"] }
|
||||
voelin-media = { path = "../voelin-media", default-features = false, features = ["str0m", "whip"], optional = true }
|
||||
voelin-media = { path = "../voelin-media", default-features = false }
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
voelin-observer = { path = "../voelin-observer" }
|
||||
# Paths only (the cache directory).
|
||||
@@ -57,9 +65,11 @@ tsproto-packets = { path = "../proto/tsproto-packets" }
|
||||
tsproto-types = { path = "../proto/tsproto-types" }
|
||||
|
||||
[dev-dependencies]
|
||||
# An HTTP/2 connection in a test (both already in the tree through h2).
|
||||
bytes = "1"
|
||||
http = "1"
|
||||
# Already in the app's graph (reqwest); for one_rustls_crypto_provider.
|
||||
rustls = { version = "0.23", default-features = false }
|
||||
voelin-myts = { path = "../voelin-myts" }
|
||||
# `process`: the browser interop test drives Chromium through Node.js.
|
||||
tokio = { version = "1", features = ["macros", "net", "process", "rt-multi-thread", "test-util"] }
|
||||
|
||||
|
||||
@@ -16,16 +16,18 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::{debug, warn};
|
||||
use tsclientlib::ClientId;
|
||||
use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio, OutPacket};
|
||||
use voelin_audio::pcm::{self, FRAME_SAMPLES};
|
||||
use voelin_audio::settings::TransmitMode;
|
||||
use voelin_audio::tap;
|
||||
use voelin_audio::vad::SILENCE_DB;
|
||||
use voelin_audio::{AudioSettings, Framer, Mixer, Processor, Vad, VoiceCodec, VoiceEncoder};
|
||||
use voelin_audio::{
|
||||
AudioSettings, EncodedVoice, Framer, Mixer, Processor, TalkerId, Vad, VoiceCodec, VoiceEncoder,
|
||||
VoicePacket,
|
||||
};
|
||||
|
||||
pub(crate) enum AudioIn {
|
||||
Packet(InAudioBuf),
|
||||
/// Voice of a talker, from the voice connection.
|
||||
Packet(VoicePacket),
|
||||
Transmit(bool),
|
||||
InputMuted(bool),
|
||||
OutputMuted(bool),
|
||||
@@ -33,15 +35,21 @@ pub(crate) enum AudioIn {
|
||||
Settings(Box<AudioSettings>),
|
||||
/// Playback volume of one client, linear (1 = unchanged, up to 4).
|
||||
ClientVolume {
|
||||
client: ClientId,
|
||||
client: TalkerId,
|
||||
volume: f32,
|
||||
},
|
||||
ClientMuted {
|
||||
client: ClientId,
|
||||
client: TalkerId,
|
||||
muted: bool,
|
||||
},
|
||||
/// The client left; client ids are reused, so forget its volume.
|
||||
ClientLeft(ClientId),
|
||||
ClientLeft(TalkerId),
|
||||
/// The priority speakers: while one talks, everyone else (streams too)
|
||||
/// is dimmed by `dimm_db` (the server's setting, e.g. -18).
|
||||
PrioritySpeakers {
|
||||
clients: Vec<TalkerId>,
|
||||
dimm_db: f32,
|
||||
},
|
||||
/// An Opus frame (48 kHz) of a watched stream; `time` is its RTP time
|
||||
/// on the 48 kHz clock.
|
||||
StreamAudio {
|
||||
@@ -105,10 +113,10 @@ pub(crate) const LEVEL_INTERVAL: Duration = Duration::from_millis(100);
|
||||
/// Samples of one 20 ms Opus frame at 48 kHz: the unit of stream packet ids.
|
||||
const OPUS_FRAME: u64 = 960;
|
||||
|
||||
/// Start the audio thread. Encoded packets go to `outgoing`; problems (e.g.
|
||||
/// Start the audio thread. Encoded voice goes to `outgoing`; problems (e.g.
|
||||
/// no device) and the microphone level are reported through `events`.
|
||||
pub(crate) fn spawn(
|
||||
outgoing: mpsc::UnboundedSender<OutPacket>,
|
||||
outgoing: mpsc::UnboundedSender<EncodedVoice>,
|
||||
events: mpsc::UnboundedSender<AudioEvent>,
|
||||
settings: AudioSettings,
|
||||
) -> AudioHandle {
|
||||
@@ -120,9 +128,9 @@ pub(crate) fn spawn(
|
||||
AudioHandle { tx }
|
||||
}
|
||||
|
||||
/// Audio of a watched stream in the mixer, under a made-up client id.
|
||||
/// Audio of a watched stream in the mixer, under a made-up talker id.
|
||||
struct StreamAudio {
|
||||
client: ClientId,
|
||||
client: TalkerId,
|
||||
/// RTP time and packet id of the last packet.
|
||||
last: Option<(u64, u64)>,
|
||||
}
|
||||
@@ -184,11 +192,7 @@ impl Pipeline {
|
||||
fn handle(&mut self, msg: AudioIn) {
|
||||
match msg {
|
||||
AudioIn::Packet(packet) => {
|
||||
let from = match packet.data().data() {
|
||||
AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from,
|
||||
_ => return,
|
||||
};
|
||||
if let Err(error) = self.mixer.handle_packet(ClientId(from), packet) {
|
||||
if let Err(error) = self.mixer.handle_packet(packet) {
|
||||
debug!(%error, "dropped voice packet");
|
||||
}
|
||||
}
|
||||
@@ -208,6 +212,9 @@ impl Pipeline {
|
||||
AudioIn::ClientVolume { client, volume } => self.mixer.set_volume(client, volume),
|
||||
AudioIn::ClientMuted { client, muted } => self.mixer.set_muted(client, muted),
|
||||
AudioIn::ClientLeft(client) => self.mixer.forget(client),
|
||||
AudioIn::PrioritySpeakers { clients, dimm_db } => {
|
||||
self.mixer.set_priority(clients, dimm_db);
|
||||
}
|
||||
AudioIn::StreamAudio { stream, time, data } => self.stream_packet(stream, time, &data),
|
||||
AudioIn::StreamVolume { stream, volume } => {
|
||||
if let Some(s) = self.streams.get(&stream) {
|
||||
@@ -232,8 +239,8 @@ impl Pipeline {
|
||||
let client = match self.streams.get(&stream) {
|
||||
Some(s) => s.client,
|
||||
None => {
|
||||
let used: Vec<ClientId> = self.streams.values().map(|s| s.client).collect();
|
||||
let Some(client) = (0..=u16::MAX).rev().map(ClientId).find(|c| !used.contains(c))
|
||||
let used: Vec<TalkerId> = self.streams.values().map(|s| s.client).collect();
|
||||
let Some(client) = (0..=u16::MAX).rev().map(TalkerId).find(|c| !used.contains(c))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
@@ -254,19 +261,15 @@ impl Pipeline {
|
||||
}
|
||||
};
|
||||
entry.last = Some((time, id));
|
||||
let packet = OutAudio::new(&AudioData::S2C {
|
||||
id: id as u16,
|
||||
codec: CodecType::OpusMusic,
|
||||
from: client.0,
|
||||
data,
|
||||
});
|
||||
match InAudioBuf::try_new(Direction::S2C, packet.into_vec()) {
|
||||
Ok(packet) => {
|
||||
if let Err(error) = self.mixer.handle_packet(client, packet) {
|
||||
debug!(%error, "dropped stream audio packet");
|
||||
}
|
||||
}
|
||||
Err(error) => debug!(?error, "stream audio packet"),
|
||||
let packet = VoicePacket {
|
||||
talker: client,
|
||||
seq: id as u16,
|
||||
codec: VoiceCodec::Music,
|
||||
whisper: false,
|
||||
payload: data.to_vec(),
|
||||
};
|
||||
if let Err(error) = self.mixer.handle_packet(packet) {
|
||||
debug!(%error, "dropped stream audio packet");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -277,7 +280,7 @@ impl Pipeline {
|
||||
|
||||
/// Microphone audio in (mono, 48 kHz, any length); voice packets out.
|
||||
/// `delay_ms` is the playback-to-capture delay hint for the echo canceller.
|
||||
fn capture(&mut self, samples: &[f32], delay_ms: u32, send: &mut impl FnMut(OutPacket)) {
|
||||
fn capture(&mut self, samples: &[f32], delay_ms: u32, send: &mut impl FnMut(EncodedVoice)) {
|
||||
self.processor.set_delay_ms(delay_ms);
|
||||
self.processed.clear();
|
||||
self.processor.capture(samples, &mut self.processed);
|
||||
@@ -299,7 +302,7 @@ impl Pipeline {
|
||||
}
|
||||
}
|
||||
|
||||
fn transmit(&mut self, frame: Vec<f32>, send: &mut impl FnMut(OutPacket)) {
|
||||
fn transmit(&mut self, frame: Vec<f32>, send: &mut impl FnMut(EncodedVoice)) {
|
||||
// Always analysed, so the detector's state is current when needed.
|
||||
let voice = self.vad.process(&frame);
|
||||
let level = self.vad.level_db().max(SILENCE_DB);
|
||||
@@ -360,7 +363,7 @@ fn sanitize(mut settings: AudioSettings) -> AudioSettings {
|
||||
|
||||
fn run(
|
||||
rx: std_mpsc::Receiver<AudioIn>,
|
||||
outgoing: mpsc::UnboundedSender<OutPacket>,
|
||||
outgoing: mpsc::UnboundedSender<EncodedVoice>,
|
||||
events: mpsc::UnboundedSender<AudioEvent>,
|
||||
settings: AudioSettings,
|
||||
) {
|
||||
@@ -436,11 +439,10 @@ fn run(
|
||||
#[cfg(feature = "audio-device")]
|
||||
mod devices {
|
||||
use tracing::debug;
|
||||
use tsproto_packets::packets::OutPacket;
|
||||
use voelin_audio::AudioSettings;
|
||||
use voelin_audio::device::{Capture, DeviceEvent, Managed, Playback};
|
||||
use voelin_audio::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
|
||||
use voelin_audio::resample::Linear;
|
||||
use voelin_audio::{AudioSettings, EncodedVoice};
|
||||
|
||||
use super::{DEVICE_LATENCY_MS, PLAYBACK_CAPACITY_MS, Pipeline};
|
||||
|
||||
@@ -500,7 +502,7 @@ mod devices {
|
||||
pub fn step(
|
||||
&mut self,
|
||||
pipeline: &mut Pipeline,
|
||||
send: &mut impl FnMut(OutPacket),
|
||||
send: &mut impl FnMut(EncodedVoice),
|
||||
error: &impl Fn(String),
|
||||
) -> bool {
|
||||
if let Some(event) = self.playback.poll() {
|
||||
@@ -547,7 +549,7 @@ mod devices {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use voelin_audio::pcm::{SAMPLE_RATE, energy, sine, white_noise};
|
||||
use voelin_audio::pcm::{SAMPLE_RATE, energy, goertzel_power, sine, white_noise};
|
||||
use voelin_audio::{ProcessingSettings, VadSettings};
|
||||
|
||||
use super::*;
|
||||
@@ -566,16 +568,20 @@ mod tests {
|
||||
/// end-of-stream packets).
|
||||
fn capture(p: &mut Pipeline, samples: &[f32]) -> (usize, usize) {
|
||||
let (mut voice, mut end) = (0, 0);
|
||||
p.capture(samples, 0, &mut |packet: OutPacket| {
|
||||
// Header of 3 bytes (id + codec) for C2S audio.
|
||||
if packet.content().len() > 3 { voice += 1 } else { end += 1 }
|
||||
p.capture(samples, 0, &mut |packet: EncodedVoice| {
|
||||
if packet.is_end() { end += 1 } else { voice += 1 }
|
||||
});
|
||||
(voice, end)
|
||||
}
|
||||
|
||||
fn incoming(from: u16, id: u16, data: &[u8]) -> AudioIn {
|
||||
let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data });
|
||||
AudioIn::Packet(InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap())
|
||||
fn incoming(from: u16, seq: u16, data: &[u8]) -> AudioIn {
|
||||
AudioIn::Packet(VoicePacket {
|
||||
talker: TalkerId(from),
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: data.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -658,14 +664,52 @@ mod tests {
|
||||
energy(&out[out.len() / 2..])
|
||||
};
|
||||
let full = play(&mut p, 1);
|
||||
p.handle(AudioIn::ClientVolume { client: ClientId(2), volume: 0.5 });
|
||||
p.handle(AudioIn::ClientVolume { client: TalkerId(2), volume: 0.5 });
|
||||
let half = play(&mut p, 2);
|
||||
let ratio_db = 10.0 * (half / full).log10();
|
||||
assert!((ratio_db + 6.0).abs() < 1.0, "volume 0.5 gave {ratio_db} dB");
|
||||
p.handle(AudioIn::ClientMuted { client: ClientId(3), muted: true });
|
||||
p.handle(AudioIn::ClientMuted { client: TalkerId(3), muted: true });
|
||||
assert!(play(&mut p, 3) < 1e-8);
|
||||
p.handle(AudioIn::ClientLeft(ClientId(3)));
|
||||
assert!(!p.mixer.is_muted(ClientId(3)));
|
||||
p.handle(AudioIn::ClientLeft(TalkerId(3)));
|
||||
assert!(!p.mixer.is_muted(TalkerId(3)));
|
||||
}
|
||||
|
||||
/// While a priority speaker talks, another talker and a watched stream
|
||||
/// are dimmed by the server's setting.
|
||||
#[test]
|
||||
fn priority_speaker() {
|
||||
let mut p = pipeline(TransmitMode::PushToTalk);
|
||||
p.handle(AudioIn::PrioritySpeakers { clients: vec![TalkerId(2)], dimm_db: -12.0 });
|
||||
let mut voice = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut priority = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut music = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
||||
let tone = sine(700.0, 2.0, 0.3);
|
||||
let stream = pcm::from_mono(&sine(1100.0, 2.0, 0.3), 2);
|
||||
let other = sine(1700.0, 1.0, 0.3);
|
||||
let mut out = Vec::new();
|
||||
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
|
||||
p.handle(incoming(1, i as u16, voice.encode_to_bytes(frame).unwrap()));
|
||||
let frame = &stream[i * FRAME_SAMPLES * 2..(i + 1) * FRAME_SAMPLES * 2];
|
||||
let data: Arc<[u8]> = music.encode_to_bytes(frame).unwrap().into();
|
||||
let time = i as u64 * OPUS_FRAME;
|
||||
p.handle(AudioIn::StreamAudio { stream: "s".into(), time, data });
|
||||
// The priority speaker talks during the second second.
|
||||
if let Some(j) = i.checked_sub(50) {
|
||||
let frame = &other[j * FRAME_SAMPLES..(j + 1) * FRAME_SAMPLES];
|
||||
p.handle(incoming(2, j as u16, priority.encode_to_bytes(frame).unwrap()));
|
||||
}
|
||||
out.extend(p.playback_frame());
|
||||
}
|
||||
// The second half of each second.
|
||||
let half = SAMPLE_RATE as usize / 2;
|
||||
let level = |second: usize, freq: f32| {
|
||||
let from = second * 2 * half + half;
|
||||
goertzel_power(&out[from..from + half], freq, SAMPLE_RATE)
|
||||
};
|
||||
for freq in [700.0, 1100.0] {
|
||||
let ratio_db = 10.0 * (level(1, freq) / level(0, freq)).log10();
|
||||
assert!((ratio_db + 12.0).abs() < 1.0, "{freq} Hz dimmed by {ratio_db} dB");
|
||||
}
|
||||
}
|
||||
|
||||
/// End to end: a remote talker is played, the speakers leak into the
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use tsclientlib::{ClientType, MaxClients, data};
|
||||
use voelin_model::{
|
||||
BannerMode, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType, HostMessageMode,
|
||||
Presence, ServerDetails, parse_badges,
|
||||
Presence, ServerDetails, myts_avatar_url, shown_badges,
|
||||
};
|
||||
|
||||
fn group_info(
|
||||
@@ -46,7 +46,7 @@ fn server_details(server: &data::Server, uid: Option<&str>) -> ServerDetails {
|
||||
tsclientlib::HostMessageMode::Modalquit => HostMessageMode::ModalQuit,
|
||||
},
|
||||
banner_url: server.hostbanner_url.clone(),
|
||||
banner_gfx_url: server.hostbanner_gfx_url.clone(),
|
||||
banner_gfx_url: server.hostbanner_gfx_url.trim().to_owned(),
|
||||
banner_gfx_interval_s: server.hostbanner_gfx_interval.whole_seconds().max(0) as u64,
|
||||
banner_mode: match server.hostbanner_mode {
|
||||
tsclientlib::HostBannerMode::NoAdjust => BannerMode::NoAdjust,
|
||||
@@ -60,6 +60,8 @@ fn server_details(server: &data::Server, uid: Option<&str>) -> ServerDetails {
|
||||
platform: server.platform.clone(),
|
||||
version: server.version.clone(),
|
||||
max_clients: server.max_clients,
|
||||
// `as` saturates (and turns NaN into 0); the mixer clamps it.
|
||||
priority_speaker_dimm_db: server.priority_speaker_dimm_modificator.round() as i32,
|
||||
default_server_group: Some(server.default_server_group.0),
|
||||
default_channel_group: Some(server.default_channel_group.0),
|
||||
}
|
||||
@@ -115,7 +117,12 @@ pub(crate) fn presence_from_book(
|
||||
needed_talk_power: c.needed_talk_power.unwrap_or(0),
|
||||
is_default: c.is_default.unwrap_or(false),
|
||||
icon: c.icon.map_or(0, |i| i.0),
|
||||
banner_gfx_url: c.banner_gfx_url.clone().filter(|u| !u.is_empty()),
|
||||
banner_gfx_url: c
|
||||
.banner_gfx_url
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|u| !u.is_empty())
|
||||
.map(str::to_owned),
|
||||
// A number the book keeps as text.
|
||||
banner_mode: c
|
||||
.banner_mode
|
||||
@@ -147,11 +154,15 @@ pub(crate) fn presence_from_book(
|
||||
server_groups,
|
||||
country: Some(c.country_code.clone()).filter(|c| !c.is_empty()),
|
||||
avatar: Some(c.avatar_hash.clone()).filter(|h| !h.is_empty()),
|
||||
myts_avatar: c.my_team_speak_avatar.as_deref().and_then(myts_avatar_url),
|
||||
description: Some(c.description.clone()).filter(|d| !d.is_empty()),
|
||||
talk_power: c.talk_power,
|
||||
talker: c.talk_power_granted,
|
||||
channel_group: Some(c.channel_group.0),
|
||||
badges: parse_badges(&c.badges),
|
||||
badges: shown_badges(
|
||||
&c.badges,
|
||||
c.signed_badges.as_deref().unwrap_or_default(),
|
||||
),
|
||||
icon: c.icon.0,
|
||||
recording: c.is_recording,
|
||||
priority_speaker: c.is_priority_speaker,
|
||||
@@ -177,10 +188,8 @@ mod tests {
|
||||
InMessage::new(&packet.header(), text.as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
/// Channel banners as a TeamSpeak 6 server (6.0.0-beta13.1) sends them:
|
||||
/// in the channel list, when a channel is created and when it is edited.
|
||||
#[test]
|
||||
fn channel_banners() {
|
||||
/// The book of a TeamSpeak 6 server (6.0.0-beta13.1) after `initserver`.
|
||||
fn ts6_book() -> data::Connection {
|
||||
let InMessage::InitServer(init) = message(concat!(
|
||||
"initserver virtualserver_name=Test virtualserver_welcomemessage ",
|
||||
"virtualserver_platform=Linux virtualserver_version=6.0.0-beta13.1 ",
|
||||
@@ -200,20 +209,29 @@ mod tests {
|
||||
)) else {
|
||||
panic!("not an initserver");
|
||||
};
|
||||
let mut book = data::Connection::new(EccKeyPrivP256::create().to_pub(), &init);
|
||||
let channel = |cid: u64, order: u64, name: &str, banner: &str| {
|
||||
format!(
|
||||
"cid={cid} cpid=0 channel_name={name} channel_topic channel_codec=4 \
|
||||
channel_codec_quality=6 channel_maxclients=-1 channel_maxfamilyclients=-1 \
|
||||
channel_order={order} channel_flag_permanent=1 channel_flag_semi_permanent=0 \
|
||||
channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 \
|
||||
channel_codec_is_unencrypted=1 channel_delete_delay=0 \
|
||||
channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=1 \
|
||||
channel_flag_maxfamilyclients_inherited=0 channel_needed_talk_power=0 \
|
||||
channel_forced_silence=0 channel_name_phonetic channel_icon_id=0 {banner} \
|
||||
channel_storage_quota=4294967295"
|
||||
)
|
||||
};
|
||||
data::Connection::new(EccKeyPrivP256::create().to_pub(), &init)
|
||||
}
|
||||
|
||||
/// A `channellist` entry as TeamSpeak 6 sends it.
|
||||
fn channel(cid: u64, order: u64, name: &str, banner: &str) -> String {
|
||||
format!(
|
||||
"cid={cid} cpid=0 channel_name={name} channel_topic channel_codec=4 \
|
||||
channel_codec_quality=6 channel_maxclients=-1 channel_maxfamilyclients=-1 \
|
||||
channel_order={order} channel_flag_permanent=1 channel_flag_semi_permanent=0 \
|
||||
channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 \
|
||||
channel_codec_is_unencrypted=1 channel_delete_delay=0 \
|
||||
channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=1 \
|
||||
channel_flag_maxfamilyclients_inherited=0 channel_needed_talk_power=0 \
|
||||
channel_forced_silence=0 channel_name_phonetic channel_icon_id=0 {banner} \
|
||||
channel_storage_quota=4294967295"
|
||||
)
|
||||
}
|
||||
|
||||
/// Channel banners as a TeamSpeak 6 server (6.0.0-beta13.1) sends them:
|
||||
/// in the channel list, when a channel is created and when it is edited.
|
||||
#[test]
|
||||
fn channel_banners() {
|
||||
let mut book = ts6_book();
|
||||
let list = format!(
|
||||
"channellist {}|{}",
|
||||
channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"),
|
||||
@@ -265,5 +283,52 @@ mod tests {
|
||||
assert_eq!(p.server.banner_gfx_interval_s, 60);
|
||||
assert_eq!(p.server.banner_mode, BannerMode::KeepAspect);
|
||||
assert_eq!(BannerMode::from_wire("7"), BannerMode::NoAdjust);
|
||||
assert_eq!(p.server.priority_speaker_dimm_db, -18);
|
||||
}
|
||||
|
||||
/// The myTeamSpeak avatar of a client as a TeamSpeak 6 server sends it:
|
||||
/// when the client enters and when it changes.
|
||||
#[test]
|
||||
fn myts_avatars() {
|
||||
let mut book = ts6_book();
|
||||
book.handle_command(&message(&format!("channellist {}", channel(1, 0, "Lobby", ""))))
|
||||
.unwrap();
|
||||
let enter = |clid: u16, avatar: &str| {
|
||||
format!(
|
||||
"notifycliententerview reasonid=0 ctid=1 clid={clid} client_database_id={clid} \
|
||||
client_nickname=c{clid} client_type=0 cfid=0 client_unique_identifier=u{clid}= \
|
||||
client_flag_avatar client_description client_icon_id=0 client_input_muted=0 \
|
||||
client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 \
|
||||
client_output_hardware=1 client_meta_data client_is_recording=0 \
|
||||
client_channel_group_id=8 client_channel_group_inherited_channel_id=1 \
|
||||
client_servergroups=8 client_away=0 client_away_message client_talk_power=75 \
|
||||
client_talk_request=0 client_talk_request_msg client_is_talker=0 \
|
||||
client_is_priority_speaker=0 client_unread_messages=0 client_nickname_phonetic \
|
||||
client_needed_serverquery_view_power=75 client_is_channel_commander=0 \
|
||||
client_country=RU client_badges client_myteamspeak_id=m{clid} \
|
||||
client_integrations{avatar}"
|
||||
)
|
||||
};
|
||||
for text in [
|
||||
enter(
|
||||
5,
|
||||
r" client_myteamspeak_avatar=3,https:\/\/a.example\/away.png;2,https:\/\/a.example\/on.png",
|
||||
),
|
||||
// A TeamSpeak 3 server, or a client without one.
|
||||
enter(6, ""),
|
||||
enter(7, " client_myteamspeak_avatar"),
|
||||
] {
|
||||
book.handle_command(&message(&text)).unwrap();
|
||||
}
|
||||
let p = presence_from_book(&book, None, |_| false);
|
||||
let avatar = |p: &Presence, clid: u16| p.clients[&clid].myts_avatar.clone();
|
||||
assert_eq!(avatar(&p, 5).as_deref(), Some("https://a.example/on.png"));
|
||||
assert_eq!((avatar(&p, 6), avatar(&p, 7)), (None, None));
|
||||
book.handle_command(&message(
|
||||
r"notifyclientupdated clid=6 client_myteamspeak_avatar=4,https:\/\/a.example\/off.png",
|
||||
))
|
||||
.unwrap();
|
||||
let p = presence_from_book(&book, None, |_| false);
|
||||
assert_eq!(avatar(&p, 6).as_deref(), Some("https://a.example/off.png"));
|
||||
}
|
||||
}
|
||||
@@ -14,16 +14,113 @@
|
||||
//! Downloads are deduplicated: [`Cache::fetch`] tells the first asker to
|
||||
//! download (into a temporary path), later askers wait for the same
|
||||
//! download ([`Cache::finish`] answers them all).
|
||||
//!
|
||||
//! A picture from the web keeps its host's validators (`ETag`,
|
||||
//! `Last-Modified`) next to it, in `validators/pictures/<md5>`: asked for
|
||||
//! again, it is downloaded only if it changed ([`Cache::validators`],
|
||||
//! [`Arrived::Unchanged`]).
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::fmt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, PoisonError, RwLock};
|
||||
use std::time::SystemTime;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use tracing::debug;
|
||||
|
||||
/// Called with the cached file's path, or why it could not be fetched.
|
||||
pub(crate) type Waiter = Box<dyn FnOnce(Result<PathBuf, String>) + Send>;
|
||||
pub(crate) type Waiter = Box<dyn FnOnce(Result<PathBuf, FetchError>) + Send>;
|
||||
|
||||
/// Why a fetch failed (for the log), and when it may be tried again.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct FetchError {
|
||||
pub text: String,
|
||||
pub retry: RetryHint,
|
||||
}
|
||||
|
||||
/// When a failed fetch may be tried again, as its host told.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) enum RetryHint {
|
||||
/// Whenever the asker's own schedule says.
|
||||
#[default]
|
||||
Default,
|
||||
/// Not before this long (the host's `Retry-After`).
|
||||
After(Duration),
|
||||
/// The address is wrong or gone (HTTP 400, 404, 410): not soon.
|
||||
Permanent,
|
||||
}
|
||||
|
||||
impl FetchError {
|
||||
pub fn new(text: impl Into<String>, retry: RetryHint) -> Self {
|
||||
Self { text: text.into(), retry }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for FetchError {
|
||||
fn from(text: String) -> Self {
|
||||
Self::new(text, RetryHint::Default)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for FetchError {
|
||||
fn from(text: &str) -> Self {
|
||||
Self::new(text, RetryHint::Default)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for FetchError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.text)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a host said identifies the version of a picture it sent, to ask
|
||||
/// later whether it changed (`If-None-Match`, `If-Modified-Since`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct Validators {
|
||||
pub etag: Option<String>,
|
||||
pub last_modified: Option<String>,
|
||||
}
|
||||
|
||||
impl Validators {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.etag.is_none() && self.last_modified.is_none()
|
||||
}
|
||||
|
||||
/// As kept: a `name: value` line each.
|
||||
fn to_text(&self) -> String {
|
||||
let mut text = String::new();
|
||||
for (name, value) in [("etag", &self.etag), ("last-modified", &self.last_modified)] {
|
||||
if let Some(value) = value {
|
||||
text.push_str(&format!("{name}: {value}\n"));
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn from_text(text: &str) -> Self {
|
||||
let mut validators = Self::default();
|
||||
for line in text.lines() {
|
||||
match line.split_once(": ") {
|
||||
Some(("etag", value)) => validators.etag = Some(value.to_owned()),
|
||||
Some(("last-modified", value)) => validators.last_modified = Some(value.to_owned()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
validators
|
||||
}
|
||||
}
|
||||
|
||||
/// How a download ended well.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Arrived {
|
||||
/// In the temporary path, with what identifies its version (when the
|
||||
/// host said).
|
||||
File(Validators),
|
||||
/// The host said the cached copy is still what it has (HTTP 304): the
|
||||
/// copy stays, nothing was downloaded.
|
||||
Unchanged,
|
||||
}
|
||||
|
||||
/// What [`Cache::fetch`] decided.
|
||||
pub(crate) enum Fetch {
|
||||
@@ -80,16 +177,17 @@ pub(crate) fn icon_key(id: u32) -> String {
|
||||
/// The largest picture downloaded into the cache, from the web or from the
|
||||
/// server's files: animated banners of several megabytes are common. The
|
||||
/// download goes to disk as it arrives, so this bounds the disk, not memory.
|
||||
pub(crate) const MAX_PICTURE_BYTES: u64 = 64 << 20;
|
||||
pub(crate) const MAX_PICTURE_BYTES: u64 = 128 << 20;
|
||||
|
||||
/// The slowest a picture may arrive on average after its first seconds:
|
||||
/// a large banner on a slow link still arrives, one trickling in forever
|
||||
/// does not hold a download slot.
|
||||
pub(crate) const MIN_PICTURE_RATE: u64 = 32 << 10;
|
||||
pub(crate) const MIN_PICTURE_RATE: u64 = 8 << 10;
|
||||
|
||||
/// The cache key of a picture on the web: only `http` and `https`
|
||||
/// addresses.
|
||||
/// addresses (blanks around one are not part of it).
|
||||
pub(crate) fn picture_key(url: &str) -> Option<String> {
|
||||
let url = url.trim();
|
||||
let (scheme, rest) = url.split_once("://")?;
|
||||
let web = scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https");
|
||||
(web && !rest.is_empty()).then(|| format!("pictures/{:x}", md5::compute(url)))
|
||||
@@ -198,10 +296,35 @@ impl Cache {
|
||||
&self,
|
||||
key: &str,
|
||||
temp: &Path,
|
||||
result: Result<(), String>,
|
||||
result: Result<(), FetchError>,
|
||||
max_bytes: u64,
|
||||
) {
|
||||
let result = result.and_then(|()| self.insert_file(key, temp, max_bytes));
|
||||
let arrived = result.map(|()| Arrived::File(Validators::default()));
|
||||
self.finish_with(key, temp, arrived, max_bytes);
|
||||
}
|
||||
|
||||
/// [`finish`](Self::finish) a download from the web: a new file with
|
||||
/// its validators, or the cached copy confirmed (kept, and marked as
|
||||
/// used).
|
||||
pub(crate) fn finish_with(
|
||||
&self,
|
||||
key: &str,
|
||||
temp: &Path,
|
||||
result: Result<Arrived, FetchError>,
|
||||
max_bytes: u64,
|
||||
) {
|
||||
let result = result.and_then(|arrived| match arrived {
|
||||
Arrived::File(validators) => {
|
||||
let path = self.insert_file(key, temp, max_bytes)?;
|
||||
self.keep_validators(key, &validators);
|
||||
Ok(path)
|
||||
}
|
||||
Arrived::Unchanged => {
|
||||
let mut index = self.lock();
|
||||
self.touch(&mut index, key)
|
||||
.ok_or_else(|| FetchError::from("cache: the copy was removed meanwhile"))
|
||||
}
|
||||
});
|
||||
let _ = std::fs::remove_file(temp);
|
||||
let waiters = self.lock().in_flight.remove(key).unwrap_or_default();
|
||||
for waiter in waiters {
|
||||
@@ -209,6 +332,32 @@ impl Cache {
|
||||
}
|
||||
}
|
||||
|
||||
/// What identifies the cached version of `key` (a picture from the
|
||||
/// web), if it is cached and its host said.
|
||||
pub(crate) fn validators(&self, key: &str) -> Option<Validators> {
|
||||
if !self.lock().entries.contains_key(key) || !self.dir.join(key).is_file() {
|
||||
return None;
|
||||
}
|
||||
let text = std::fs::read_to_string(validators_path(&self.dir, key)).ok()?;
|
||||
Some(Validators::from_text(&text)).filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
/// Keep `validators` with `key`'s new file (none: the old ones go).
|
||||
fn keep_validators(&self, key: &str, validators: &Validators) {
|
||||
let path = validators_path(&self.dir, key);
|
||||
if validators.is_empty() {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
return;
|
||||
}
|
||||
let written = path
|
||||
.parent()
|
||||
.map_or(Ok(()), std::fs::create_dir_all)
|
||||
.and_then(|()| std::fs::write(&path, validators.to_text()));
|
||||
if let Err(e) = written {
|
||||
debug!("cache: cannot keep the validators of {key}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Put a file we have (e.g. our own avatar) into the cache.
|
||||
pub(crate) fn insert_copy(
|
||||
&self,
|
||||
@@ -263,6 +412,7 @@ impl Cache {
|
||||
if let Err(e) = std::fs::remove_file(self.dir.join(&key)) {
|
||||
debug!("cache: cannot remove {key}: {e}");
|
||||
}
|
||||
let _ = std::fs::remove_file(validators_path(&self.dir, &key));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,6 +446,22 @@ fn scan(dir: &Path, index: &mut Index) {
|
||||
index.lru.insert(tick, key.clone());
|
||||
index.entries.insert(key, Entry { size, tick });
|
||||
}
|
||||
// Validators of pictures no longer here.
|
||||
let Ok(kept) = std::fs::read_dir(dir.join(VALIDATORS).join("pictures")) else { return };
|
||||
for entry in kept.flatten() {
|
||||
let key = format!("pictures/{}", entry.file_name().to_string_lossy());
|
||||
if !index.entries.contains_key(&key) {
|
||||
let _ = std::fs::remove_file(entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The directory of the pictures' validators.
|
||||
const VALIDATORS: &str = "validators";
|
||||
|
||||
/// Where the validators of `key` are kept.
|
||||
fn validators_path(dir: &Path, key: &str) -> PathBuf {
|
||||
dir.join(VALIDATORS).join(key)
|
||||
}
|
||||
|
||||
/// The engine's cache: one [`Cache`] that [`crate::Command::AttachCache`]
|
||||
@@ -464,6 +630,103 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A picture keeps its host's validators; confirmed unchanged, the copy
|
||||
/// stays and is used; replaced without validators or evicted, they go.
|
||||
#[test]
|
||||
fn validators_go_with_their_picture() {
|
||||
let dir = temp_dir("validators");
|
||||
let cache = Cache::new(&dir);
|
||||
let key = picture_key("https://example.com/v.png").unwrap();
|
||||
let validators = Validators {
|
||||
etag: Some("W/\"v1\"".into()),
|
||||
last_modified: Some("Tue, 06 Oct 2026 10:00:00 GMT".into()),
|
||||
};
|
||||
assert_eq!(cache.validators(&key), None);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let waiter = |tx: &mpsc::Sender<_>| -> Waiter {
|
||||
let tx = tx.clone();
|
||||
Box::new(move |r| tx.send(r).unwrap())
|
||||
};
|
||||
let Fetch::Download(temp) = cache.fetch(&key, false, waiter(&tx)) else { panic!() };
|
||||
std::fs::create_dir_all(temp.parent().unwrap()).unwrap();
|
||||
std::fs::write(&temp, b"v1").unwrap();
|
||||
cache.finish_with(&key, &temp, Ok(Arrived::File(validators.clone())), 0);
|
||||
let path = rx.recv().unwrap().unwrap();
|
||||
assert_eq!(cache.validators(&key), Some(validators.clone()));
|
||||
// Asked again: unchanged, the same file answers both askers.
|
||||
let Fetch::Download(temp) = cache.fetch(&key, true, waiter(&tx)) else { panic!() };
|
||||
assert!(matches!(cache.fetch(&key, true, waiter(&tx)), Fetch::Waiting));
|
||||
cache.finish_with(&key, &temp, Ok(Arrived::Unchanged), 0);
|
||||
assert_eq!(rx.recv().unwrap(), Ok(path.clone()));
|
||||
assert_eq!(rx.recv().unwrap(), Ok(path.clone()));
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"v1");
|
||||
// They survive a restart, with their picture.
|
||||
assert_eq!(Cache::new(&dir).validators(&key), Some(validators.clone()));
|
||||
// A new version without validators: the old ones are not sent again.
|
||||
let Fetch::Download(temp) = cache.fetch(&key, true, waiter(&tx)) else { panic!() };
|
||||
// (The restart above cleared the temporary files' directory.)
|
||||
std::fs::create_dir_all(temp.parent().unwrap()).unwrap();
|
||||
std::fs::write(&temp, b"new").unwrap();
|
||||
cache.finish(&key, &temp, Ok(()), 0);
|
||||
rx.recv().unwrap().unwrap();
|
||||
assert_eq!(cache.validators(&key), None);
|
||||
// Evicted with the picture.
|
||||
let Fetch::Download(temp) = cache.fetch(&key, true, waiter(&tx)) else { panic!() };
|
||||
std::fs::write(&temp, b"v2").unwrap();
|
||||
cache.finish_with(&key, &temp, Ok(Arrived::File(validators.clone())), 0);
|
||||
rx.recv().unwrap().unwrap();
|
||||
assert!(validators_path(&dir, &key).is_file());
|
||||
put(&cache, "icons/1", 10, 10);
|
||||
assert!(!path.exists());
|
||||
assert!(!validators_path(&dir, &key).exists());
|
||||
// Unchanged, but the copy went meanwhile: a failure, retried in full.
|
||||
let Fetch::Download(temp) = cache.fetch(&key, true, waiter(&tx)) else { panic!() };
|
||||
cache.finish_with(&key, &temp, Ok(Arrived::Unchanged), 0);
|
||||
assert!(rx.recv().unwrap().is_err());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// A picture confirmed unchanged counts as used: others go first.
|
||||
#[test]
|
||||
fn an_unchanged_picture_counts_as_used() {
|
||||
let dir = temp_dir("unchanged-used");
|
||||
let cache = Cache::new(&dir);
|
||||
let key = picture_key("https://example.com/u.png").unwrap();
|
||||
let picture = put(&cache, &key, 400, 1000);
|
||||
let icon = put(&cache, "icons/1", 400, 1000);
|
||||
let Fetch::Download(temp) = cache.fetch(&key, true, Box::new(|_| {})) else { panic!() };
|
||||
cache.finish_with(&key, &temp, Ok(Arrived::Unchanged), 1000);
|
||||
put(&cache, "icons/2", 400, 1000);
|
||||
assert!(picture.exists(), "the picture confirmed unchanged stays");
|
||||
assert!(!icon.exists(), "the least recently used file goes");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// Validators whose picture is gone go at the next start.
|
||||
#[test]
|
||||
fn orphaned_validators_are_removed() {
|
||||
let dir = temp_dir("orphans");
|
||||
let key = picture_key("https://example.com/o.png").unwrap();
|
||||
let orphan = validators_path(&dir, &key);
|
||||
std::fs::create_dir_all(orphan.parent().unwrap()).unwrap();
|
||||
std::fs::write(&orphan, "etag: \"x\"\n").unwrap();
|
||||
let cache = Cache::new(&dir);
|
||||
assert_eq!(cache.size(), 0);
|
||||
assert!(!orphan.exists());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_errors_carry_their_retry_hint() {
|
||||
let error = FetchError::from("HTTP 503 Service Unavailable");
|
||||
assert_eq!(error.retry, RetryHint::Default);
|
||||
assert_eq!(error.to_string(), "HTTP 503 Service Unavailable");
|
||||
let gone = FetchError::new("HTTP 404 Not Found", RetryHint::Permanent);
|
||||
assert_ne!(gone, FetchError::from("HTTP 404 Not Found"));
|
||||
let text = Validators { etag: Some("\"a: b\"".into()), last_modified: None }.to_text();
|
||||
assert_eq!(Validators::from_text(&text).etag.as_deref(), Some("\"a: b\""));
|
||||
}
|
||||
|
||||
/// Pictures are cached files like the others (counted after a restart).
|
||||
#[test]
|
||||
fn pictures_survive_restart() {
|
||||
|
||||
@@ -8,16 +8,31 @@
|
||||
//! - SRV `_tsgws._tcp.<name>`: `wss://<target>:<port><path>`,
|
||||
//! - SRV `_tsgw._tcp.<name>`: `ws://<target>:<port><path>`,
|
||||
//!
|
||||
//! TLS first at the same name; `<path>` is `path=…` from a TXT record at the
|
||||
//! SRV record's name, `/v1` without one. Without any such record, as TSDNS
|
||||
//! has its well-known port, the gateway itself is asked at tsgw's default
|
||||
//! port: `http://<name>:7788/.well-known/tsgw` answers `{"url": "…"}`. For an
|
||||
//! IP address (or `localhost`) only that is tried. What an admin publishes is
|
||||
//! in `docs/gateway-admin.md`.
|
||||
//! `<path>` is `path=…` from a TXT record at the SRV record's name, `/v1`
|
||||
//! without one. As TSDNS has its well-known port, the gateway itself is also
|
||||
//! asked at tsgw's default port: `http://<name>:7788/.well-known/tsgw`
|
||||
//! answers `{"url": "…"}`; for an IP address (or `localhost`) only that is
|
||||
//! tried. That answer is plain HTTP, so it is used only when nothing or a
|
||||
//! plain record is published: a TLS-only publication stays TLS-only.
|
||||
//!
|
||||
//! Everything is asked at once (SRV and TXT at every name, and the gateway
|
||||
//! at every name), so a discovery takes as long as its slowest needed
|
||||
//! answer, not their sum; DNS gives up after 2 s (twice).
|
||||
//!
|
||||
//! The most specific name with a record wins: a parent domain's records
|
||||
//! are another server's gateway when the host publishes its own. Every
|
||||
//! gateway of that name is kept, best first (TLS before plain, by
|
||||
//! priority, then the gateway's own answer at that name), and tried in turn
|
||||
//! ([`crate::Command::ObserveGateway`]): a TLS proxy that fails falls back
|
||||
//! to the plain gateway published next to it. Discovery trusts DNS and the
|
||||
//! network as TSDNS does; falling back from a published `_tsgws` to a
|
||||
//! published `_tsgw` is no weaker than publishing only `_tsgw`. What an
|
||||
//! admin publishes is in `docs/gateway-admin.md`. Each discovery is logged
|
||||
//! (target `voelin_core::discover`, the details at debug).
|
||||
|
||||
use std::net::IpAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use futures::future::{BoxFuture, FutureExt, join_all};
|
||||
use hickory_resolver::TokioResolver;
|
||||
@@ -26,7 +41,9 @@ use hickory_resolver::net::runtime::TokioRuntimeProvider;
|
||||
use hickory_resolver::proto::rr::RData;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::timeout;
|
||||
use tracing::{debug, info};
|
||||
|
||||
/// The port tsgw listens on by default, where it is asked for its URL.
|
||||
pub const DEFAULT_PORT: u16 = 7788;
|
||||
@@ -34,9 +51,14 @@ pub const DEFAULT_PORT: u16 = 7788;
|
||||
const DEFAULT_PATH: &str = "/v1";
|
||||
/// Give up on asking one name's gateway after this long.
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
/// Give up on one DNS query after this long (it is sent twice).
|
||||
const DNS_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
/// At most this many gateways are kept, best first.
|
||||
const MAX_CANDIDATES: usize = 8;
|
||||
|
||||
type SrvFn = dyn Fn(String) -> BoxFuture<'static, Vec<(u16, String, u16)>> + Send + Sync;
|
||||
type TxtFn = dyn Fn(String) -> BoxFuture<'static, Vec<String>> + Send + Sync;
|
||||
type ProbeFn = dyn Fn(String) -> BoxFuture<'static, Option<String>> + Send + Sync;
|
||||
|
||||
/// Where [`gateway`] gets its answers from; the tests put fakes in.
|
||||
#[derive(Clone)]
|
||||
@@ -45,28 +67,47 @@ struct Lookups {
|
||||
srv: Arc<SrvFn>,
|
||||
/// The strings of the TXT records at a name.
|
||||
txt: Arc<TxtFn>,
|
||||
/// Where a gateway is asked for its URL.
|
||||
probe_port: u16,
|
||||
/// The URL a gateway at a name gives for itself (`/.well-known/tsgw`).
|
||||
probe: Arc<ProbeFn>,
|
||||
}
|
||||
|
||||
impl Lookups {
|
||||
fn system() -> Self {
|
||||
// The system's resolver, else (Android) a public one, as the voice
|
||||
// connection's resolver does.
|
||||
let resolver = TokioResolver::builder_tokio().and_then(|b| b.build()).or_else(|_| {
|
||||
TokioResolver::builder_with_config(
|
||||
ResolverConfig::udp_and_tcp(&CLOUDFLARE),
|
||||
TokioRuntimeProvider::default(),
|
||||
)
|
||||
.build()
|
||||
});
|
||||
let resolver = resolver.ok();
|
||||
// connection's resolver does. A query that is not answered is sent
|
||||
// again soon: discovery runs once a run, and finding nothing is
|
||||
// final until the next.
|
||||
let resolver = TokioResolver::builder_tokio()
|
||||
.map(|mut b| {
|
||||
let options = b.options_mut();
|
||||
options.timeout = DNS_TIMEOUT;
|
||||
options.attempts = options.attempts.max(2);
|
||||
b
|
||||
})
|
||||
.and_then(|b| b.build())
|
||||
.or_else(|_| {
|
||||
let mut b = TokioResolver::builder_with_config(
|
||||
ResolverConfig::udp_and_tcp(&CLOUDFLARE),
|
||||
TokioRuntimeProvider::default(),
|
||||
);
|
||||
b.options_mut().timeout = DNS_TIMEOUT;
|
||||
b.build()
|
||||
});
|
||||
let resolver = match resolver {
|
||||
Ok(resolver) => Some(resolver),
|
||||
Err(e) => {
|
||||
debug!(error = %e, "no DNS resolver for gateway discovery");
|
||||
None
|
||||
}
|
||||
};
|
||||
let txt_resolver = resolver.clone();
|
||||
Self {
|
||||
srv: Arc::new(move |name| {
|
||||
let resolver = resolver.clone();
|
||||
async move {
|
||||
let lookup = resolver?.srv_lookup(name).await.ok()?;
|
||||
let started = Instant::now();
|
||||
let lookup = resolver?.srv_lookup(name.as_str()).await;
|
||||
let lookup = dns_answer(&name, "SRV", started, lookup)?;
|
||||
Some(
|
||||
lookup
|
||||
.answers()
|
||||
@@ -84,7 +125,9 @@ impl Lookups {
|
||||
txt: Arc::new(move |name| {
|
||||
let resolver = txt_resolver.clone();
|
||||
async move {
|
||||
let lookup = resolver?.txt_lookup(name).await.ok()?;
|
||||
let started = Instant::now();
|
||||
let lookup = resolver?.txt_lookup(name.as_str()).await;
|
||||
let lookup = dns_answer(&name, "TXT", started, lookup)?;
|
||||
Some(
|
||||
lookup
|
||||
.answers()
|
||||
@@ -101,30 +144,150 @@ impl Lookups {
|
||||
.map(Option::unwrap_or_default)
|
||||
.boxed()
|
||||
}),
|
||||
probe_port: DEFAULT_PORT,
|
||||
probe: Arc::new(|name| {
|
||||
async move {
|
||||
let started = Instant::now();
|
||||
let answer = match timeout(PROBE_TIMEOUT, well_known(&name, DEFAULT_PORT)).await
|
||||
{
|
||||
Ok(answer) => answer,
|
||||
Err(_) => Err(format!("no answer within {} s", PROBE_TIMEOUT.as_secs())),
|
||||
};
|
||||
let elapsed_ms = started.elapsed().as_millis() as u64;
|
||||
match &answer {
|
||||
Ok(url) => debug!(name, %url, elapsed_ms, "tsgw well-known probe answered"),
|
||||
Err(outcome) => debug!(name, %outcome, elapsed_ms, "tsgw well-known probe"),
|
||||
}
|
||||
answer.ok()
|
||||
}
|
||||
.boxed()
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The URL of the gateway of the server at `address` (as a bookmark has it:
|
||||
/// host, host:port, an IP), if one is published.
|
||||
pub async fn gateway(address: &str) -> Option<String> {
|
||||
gateway_with(address, Lookups::system()).await
|
||||
/// A DNS answer, the failure logged (no record at most names is normal).
|
||||
fn dns_answer<T>(
|
||||
name: &str,
|
||||
kind: &str,
|
||||
started: Instant,
|
||||
lookup: Result<T, hickory_resolver::net::NetError>,
|
||||
) -> Option<T> {
|
||||
let elapsed_ms = started.elapsed().as_millis() as u64;
|
||||
match lookup {
|
||||
Ok(lookup) => Some(lookup),
|
||||
Err(e) if e.is_no_records_found() => {
|
||||
debug!(name, kind, elapsed_ms, "no DNS record");
|
||||
None
|
||||
}
|
||||
Err(e) => {
|
||||
debug!(name, kind, elapsed_ms, error = %e, "DNS lookup failed");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn gateway_with(address: &str, lookups: Lookups) -> Option<String> {
|
||||
/// The URLs of the gateway of the server at `address` (as a bookmark has
|
||||
/// it: host, host:port, an IP), best first: everything published, to be
|
||||
/// tried in turn. Empty: none is published.
|
||||
pub async fn gateways(address: &str) -> Vec<String> {
|
||||
gateways_with(address, Lookups::system()).await
|
||||
}
|
||||
|
||||
async fn gateways_with(address: &str, lookups: Lookups) -> Vec<String> {
|
||||
let started = Instant::now();
|
||||
let host = host_of(address);
|
||||
let names = names(host);
|
||||
if names.is_empty() {
|
||||
return None;
|
||||
debug!(address, "no gateway discovery for a server nickname");
|
||||
return Vec::new();
|
||||
}
|
||||
if host.parse::<IpAddr>().is_err()
|
||||
&& host.contains('.')
|
||||
&& let Some(url) = from_srv(&names, &lookups).await
|
||||
{
|
||||
return Some(url);
|
||||
// The gateway's own answer is asked at every name while DNS is; only
|
||||
// the answer that counts is waited for.
|
||||
let mut probes = Probes::start(&names, &lookups);
|
||||
let srv = if host.parse::<IpAddr>().is_err() && host.contains('.') {
|
||||
from_srv(&names, &lookups).await
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// The gateway's own answer comes over plain HTTP: not for a server that
|
||||
// publishes only TLS; at the name that publishes, or without records the
|
||||
// most specific name that answers.
|
||||
let (mut urls, well_known) = match &srv {
|
||||
None => match probes.first().await {
|
||||
Some((name, url)) => (vec![url.clone()], format!("{name}: {url}")),
|
||||
None => (Vec::new(), "none".to_owned()),
|
||||
},
|
||||
Some(found) if found.urls.iter().any(|url| url.starts_with("ws://")) => {
|
||||
let mut urls = found.urls.clone();
|
||||
match probes.of(found.name).await {
|
||||
Some(url) => {
|
||||
let well_known = format!("{}: {url}", found.name);
|
||||
if !urls.contains(&url) {
|
||||
urls.push(url);
|
||||
}
|
||||
(urls, well_known)
|
||||
}
|
||||
None => (urls, "none".to_owned()),
|
||||
}
|
||||
}
|
||||
Some(found) => (found.urls.clone(), "not used (TLS only)".to_owned()),
|
||||
};
|
||||
urls.truncate(MAX_CANDIDATES);
|
||||
let (srv_name, srv_urls, txt) = match &srv {
|
||||
Some(found) => (found.name, found.urls.as_slice(), found.txt.as_slice()),
|
||||
None => ("", &[][..], &[][..]),
|
||||
};
|
||||
info!(
|
||||
address,
|
||||
names = ?names,
|
||||
srv_name,
|
||||
srv = ?srv_urls,
|
||||
txt = ?txt,
|
||||
%well_known,
|
||||
result = ?urls,
|
||||
elapsed_ms = started.elapsed().as_millis() as u64,
|
||||
"gateway discovery"
|
||||
);
|
||||
urls
|
||||
}
|
||||
|
||||
/// The gateway's own answers being asked, one per name, most specific
|
||||
/// first; those still asking when dropped are given up.
|
||||
struct Probes<'a>(Vec<(&'a str, JoinHandle<Option<String>>)>);
|
||||
|
||||
impl<'a> Probes<'a> {
|
||||
fn start(names: &[&'a str], lookups: &Lookups) -> Self {
|
||||
Self(
|
||||
names
|
||||
.iter()
|
||||
.map(|name| (*name, tokio::spawn((lookups.probe)(name.to_string()))))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The answer at `name`.
|
||||
async fn of(&mut self, name: &str) -> Option<String> {
|
||||
let (_, probe) = self.0.iter_mut().find(|(n, _)| *n == name)?;
|
||||
probe.await.ok().flatten()
|
||||
}
|
||||
|
||||
/// The answer of the most specific name that answers.
|
||||
async fn first(&mut self) -> Option<(&'a str, String)> {
|
||||
for (name, probe) in &mut self.0 {
|
||||
if let Some(url) = probe.await.ok().flatten() {
|
||||
return Some((*name, url));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Probes<'_> {
|
||||
fn drop(&mut self) {
|
||||
for (_, probe) in &self.0 {
|
||||
probe.abort();
|
||||
}
|
||||
}
|
||||
from_well_known(&names, lookups.probe_port).await
|
||||
}
|
||||
|
||||
/// The host of an address: without the port, the brackets of an IPv6
|
||||
@@ -155,59 +318,103 @@ fn names(host: &str) -> Vec<&str> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The URL from SRV records, every name and service asked at once.
|
||||
async fn from_srv(names: &[&str], lookups: &Lookups) -> Option<String> {
|
||||
let queries: Vec<(&str, String)> = names
|
||||
/// What SRV records publish: at `name`, the most specific name with a
|
||||
/// usable record.
|
||||
struct Published<'a> {
|
||||
name: &'a str,
|
||||
/// TLS first, by priority.
|
||||
urls: Vec<String>,
|
||||
/// The TXT strings at the records' names.
|
||||
txt: Vec<String>,
|
||||
}
|
||||
|
||||
/// The URLs from SRV records, every name and service asked at once, with
|
||||
/// the TXT records there (the path; most names have none): those of the
|
||||
/// most specific name with a usable record.
|
||||
async fn from_srv<'a>(names: &[&'a str], lookups: &Lookups) -> Option<Published<'a>> {
|
||||
let queries: Vec<(&str, &str, String)> = names
|
||||
.iter()
|
||||
.flat_map(|name| {
|
||||
[("wss", format!("_tsgws._tcp.{name}.")), ("ws", format!("_tsgw._tcp.{name}."))]
|
||||
[
|
||||
(*name, "wss", format!("_tsgws._tcp.{name}.")),
|
||||
(*name, "ws", format!("_tsgw._tcp.{name}.")),
|
||||
]
|
||||
})
|
||||
.collect();
|
||||
let answers = join_all(queries.iter().map(|(_, owner)| (lookups.srv)(owner.clone()))).await;
|
||||
// The first (most specific, TLS first) name with a usable record.
|
||||
let ((scheme, owner), (_, target, port)) =
|
||||
queries.iter().zip(answers).find_map(|(q, records)| {
|
||||
let (answers, texts) = futures::join!(
|
||||
join_all(queries.iter().map(|(.., owner)| (lookups.srv)(owner.clone()))),
|
||||
join_all(queries.iter().map(|(.., owner)| (lookups.txt)(owner.clone()))),
|
||||
);
|
||||
let mut found: Vec<_> = queries
|
||||
.iter()
|
||||
.zip(answers)
|
||||
.zip(texts)
|
||||
.filter_map(|((query, mut records), txt)| {
|
||||
// A target of "." says there is no such service there.
|
||||
let best = records.into_iter().filter(|r| r.1 != ".").min_by_key(|r| r.0)?;
|
||||
Some((q, best))
|
||||
})?;
|
||||
let mut path = (lookups.txt)(owner.clone())
|
||||
.await
|
||||
.into_iter()
|
||||
records.retain(|r| r.1 != ".");
|
||||
records.sort_by_key(|r| r.0);
|
||||
(!records.is_empty()).then_some((query, records, txt))
|
||||
})
|
||||
.collect();
|
||||
let name = found.first()?.0.0;
|
||||
found.retain(|((n, ..), ..)| *n == name);
|
||||
let mut published = Published { name, urls: Vec::new(), txt: Vec::new() };
|
||||
for ((_, scheme, _), records, txt) in found {
|
||||
let path = path_in(&txt);
|
||||
published.txt.extend(txt);
|
||||
for (_, target, port) in records {
|
||||
let url = format!("{scheme}://{}:{port}{path}", target.trim_end_matches('.'));
|
||||
if !published.urls.contains(&url) {
|
||||
published.urls.push(url);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(published)
|
||||
}
|
||||
|
||||
/// The path in a SRV record's name's TXT strings: `path=…`, `/v1` without
|
||||
/// one.
|
||||
fn path_in(txt: &[String]) -> String {
|
||||
let mut path = txt
|
||||
.iter()
|
||||
.find_map(|s| s.strip_prefix("path=").map(str::to_owned))
|
||||
.unwrap_or_else(|| DEFAULT_PATH.to_owned());
|
||||
if !path.starts_with('/') {
|
||||
path.insert(0, '/');
|
||||
}
|
||||
Some(format!("{scheme}://{}:{port}{path}", target.trim_end_matches('.')))
|
||||
path
|
||||
}
|
||||
|
||||
/// The URL a gateway gives for itself at one of `names`, all asked at once;
|
||||
/// the most specific that answers wins.
|
||||
async fn from_well_known(names: &[&str], port: u16) -> Option<String> {
|
||||
let answers =
|
||||
join_all(names.iter().map(|name| timeout(PROBE_TIMEOUT, well_known(name, port)))).await;
|
||||
answers.into_iter().find_map(|answer| answer.ok().flatten())
|
||||
}
|
||||
|
||||
/// tsgw's answer at `http://<host>:<port>/.well-known/tsgw`.
|
||||
async fn well_known(host: &str, port: u16) -> Option<String> {
|
||||
let mut stream = TcpStream::connect((host, port)).await.ok()?;
|
||||
/// tsgw's answer at `http://<host>:<port>/.well-known/tsgw`; else what
|
||||
/// happened instead.
|
||||
async fn well_known(host: &str, port: u16) -> Result<String, String> {
|
||||
let mut stream =
|
||||
TcpStream::connect((host, port)).await.map_err(|e| format!("cannot connect: {e}"))?;
|
||||
let authority =
|
||||
if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
|
||||
let request =
|
||||
format!("GET /.well-known/tsgw HTTP/1.1\r\nHost: {authority}\r\nConnection: close\r\n\r\n");
|
||||
stream.write_all(request.as_bytes()).await.ok()?;
|
||||
stream.write_all(request.as_bytes()).await.map_err(|e| format!("cannot ask: {e}"))?;
|
||||
let mut response = Vec::new();
|
||||
stream.take(16 * 1024).read_to_end(&mut response).await.ok()?;
|
||||
let response = String::from_utf8(response).ok()?;
|
||||
let (head, body) = response.split_once("\r\n\r\n")?;
|
||||
if head.split_whitespace().nth(1) != Some("200") {
|
||||
return None;
|
||||
stream
|
||||
.take(16 * 1024)
|
||||
.read_to_end(&mut response)
|
||||
.await
|
||||
.map_err(|e| format!("no answer: {e}"))?;
|
||||
let response = String::from_utf8(response).map_err(|_| "not text".to_owned())?;
|
||||
let (head, body) = response.split_once("\r\n\r\n").ok_or("not HTTP")?;
|
||||
let status = head.split_whitespace().nth(1).unwrap_or_default();
|
||||
if status != "200" {
|
||||
return Err(format!("http {status}"));
|
||||
}
|
||||
let answer: serde_json::Value =
|
||||
serde_json::from_str(body).map_err(|_| "not a tsgw answer".to_owned())?;
|
||||
let url = answer.get("url").and_then(|url| url.as_str()).ok_or("no url in the answer")?;
|
||||
if url.starts_with("ws://") || url.starts_with("wss://") {
|
||||
Ok(url.to_owned())
|
||||
} else {
|
||||
Err(format!("not a gateway URL: {url}"))
|
||||
}
|
||||
let answer: serde_json::Value = serde_json::from_str(body).ok()?;
|
||||
let url = answer.get("url")?.as_str()?;
|
||||
(url.starts_with("ws://") || url.starts_with("wss://")).then(|| url.to_owned())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -215,8 +422,8 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
/// DNS answers from these lists only: SRV `(name, priority, target,
|
||||
/// port)`, TXT `(name, string)`.
|
||||
fn fake(srv: &[(&str, u16, &str, u16)], txt: &[(&str, &str)], probe_port: u16) -> Lookups {
|
||||
/// port)`, TXT `(name, string)`; no gateway answers for itself.
|
||||
fn fake(srv: &[(&str, u16, &str, u16)], txt: &[(&str, &str)]) -> Lookups {
|
||||
let srv: Vec<(String, u16, String, u16)> =
|
||||
srv.iter().map(|(n, p, t, port)| (n.to_string(), *p, t.to_string(), *port)).collect();
|
||||
let txt: Vec<(String, String)> =
|
||||
@@ -231,10 +438,29 @@ mod tests {
|
||||
let found = txt.iter().filter(|r| r.0 == name).map(|r| r.1.clone()).collect();
|
||||
futures::future::ready(found).boxed()
|
||||
}),
|
||||
probe_port,
|
||||
probe: Arc::new(|_| futures::future::ready(None).boxed()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `lookups` where the gateway at a name answers `(name, url)`.
|
||||
fn answering(mut lookups: Lookups, answers: &[(&str, &str)]) -> Lookups {
|
||||
let answers: Vec<(String, String)> =
|
||||
answers.iter().map(|(n, u)| (n.to_string(), u.to_string())).collect();
|
||||
lookups.probe = Arc::new(move |name| {
|
||||
let url = answers.iter().find(|a| a.0 == name).map(|a| a.1.clone());
|
||||
futures::future::ready(url).boxed()
|
||||
});
|
||||
lookups
|
||||
}
|
||||
|
||||
/// `lookups` asking the real `/.well-known/tsgw` at `port`.
|
||||
fn probing(mut lookups: Lookups, port: u16) -> Lookups {
|
||||
lookups.probe = Arc::new(move |name| {
|
||||
async move { timeout(PROBE_TIMEOUT, well_known(&name, port)).await.ok()?.ok() }.boxed()
|
||||
});
|
||||
lookups
|
||||
}
|
||||
|
||||
/// A port nothing listens on.
|
||||
fn closed_port() -> u16 {
|
||||
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
|
||||
@@ -242,20 +468,22 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn finds_the_gateway_at_the_host_or_its_domain() {
|
||||
let lookups = fake(&[("_tsgw._tcp.example.test.", 0, "gw.example.test.", 7788)], &[], 0);
|
||||
let lookups = fake(&[("_tsgw._tcp.example.test.", 0, "gw.example.test.", 7788)], &[]);
|
||||
for address in ["ts.example.test", "ts.example.test:9987", "example.test"] {
|
||||
assert_eq!(
|
||||
gateway_with(address, lookups.clone()).await.as_deref(),
|
||||
Some("ws://gw.example.test:7788/v1"),
|
||||
gateways_with(address, lookups.clone()).await,
|
||||
["ws://gw.example.test:7788/v1"],
|
||||
"{address}"
|
||||
);
|
||||
}
|
||||
// The parent's parent is not the domain any more.
|
||||
assert_eq!(gateway_with("example", lookups).await, None);
|
||||
assert!(gateways_with("example", lookups).await.is_empty());
|
||||
}
|
||||
|
||||
/// All of the most specific name's gateways, TLS first, by priority; a
|
||||
/// parent domain's only for a host without its own.
|
||||
#[tokio::test]
|
||||
async fn the_most_specific_name_wins_then_tls() {
|
||||
async fn the_most_specific_name_wins_with_all_its_gateways() {
|
||||
let lookups = fake(
|
||||
&[
|
||||
("_tsgws._tcp.example.test.", 0, "domain.example.test.", 443),
|
||||
@@ -264,18 +492,181 @@ mod tests {
|
||||
("_tsgws._tcp.ts.example.test.", 1, "tls.example.test.", 8443),
|
||||
],
|
||||
&[("_tsgws._tcp.ts.example.test.", "path=/tsgw/v1")],
|
||||
0,
|
||||
);
|
||||
assert_eq!(
|
||||
gateway_with("ts.example.test", lookups.clone()).await.as_deref(),
|
||||
Some("wss://tls.example.test:8443/tsgw/v1")
|
||||
gateways_with("ts.example.test", lookups.clone()).await,
|
||||
[
|
||||
"wss://tls.example.test:8443/tsgw/v1",
|
||||
"wss://backup.example.test:443/tsgw/v1",
|
||||
"ws://plain.example.test:7788/v1",
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
gateway_with("voice.example.test", lookups).await.as_deref(),
|
||||
Some("wss://domain.example.test:443/v1")
|
||||
gateways_with("voice.example.test", lookups).await,
|
||||
["wss://domain.example.test:443/v1"]
|
||||
);
|
||||
}
|
||||
|
||||
/// A TLS proxy in front of tsgw and tsgw itself published next to the
|
||||
/// server (and again at the domain): TLS first, the plain one after it,
|
||||
/// once; the gateway's own answer is the plain one again.
|
||||
#[tokio::test]
|
||||
async fn a_tls_proxy_falls_back_to_the_published_plain_gateway() {
|
||||
let lookups = answering(
|
||||
fake(
|
||||
&[
|
||||
("_tsgws._tcp.ts.example.test.", 0, "gw.example.test.", 443),
|
||||
("_tsgw._tcp.ts.example.test.", 0, "ts.example.test.", 7788),
|
||||
("_tsgw._tcp.example.test.", 0, "ts.example.test.", 7788),
|
||||
],
|
||||
&[],
|
||||
),
|
||||
&[("ts.example.test", "ws://ts.example.test:7788/v1")],
|
||||
);
|
||||
assert_eq!(
|
||||
gateways_with("ts.example.test", lookups).await,
|
||||
["wss://gw.example.test:443/v1", "ws://ts.example.test:7788/v1"]
|
||||
);
|
||||
}
|
||||
|
||||
/// A gateway at the domain fronts another server than one of its hosts
|
||||
/// that publishes its own: never a fallback for it, nor the domain's own
|
||||
/// answer.
|
||||
#[tokio::test]
|
||||
async fn another_servers_gateway_is_no_fallback() {
|
||||
let lookups = answering(
|
||||
fake(
|
||||
&[
|
||||
("_tsgws._tcp.ts1.example.test.", 0, "gw1.example.test.", 443),
|
||||
("_tsgw._tcp.ts1.example.test.", 0, "ts1.example.test.", 7788),
|
||||
("_tsgws._tcp.example.test.", 0, "gw-main.example.test.", 443),
|
||||
],
|
||||
&[],
|
||||
),
|
||||
&[("example.test", "ws://main.example.test:7788/v1")],
|
||||
);
|
||||
assert_eq!(
|
||||
gateways_with("ts1.example.test", lookups).await,
|
||||
["wss://gw1.example.test:443/v1", "ws://ts1.example.test:7788/v1"]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_gateways_own_answer_comes_last() {
|
||||
let lookups = answering(
|
||||
fake(&[("_tsgw._tcp.ts.example.test.", 0, "plain.example.test.", 7788)], &[]),
|
||||
&[("ts.example.test", "wss://gw.example.test/v1")],
|
||||
);
|
||||
assert_eq!(
|
||||
gateways_with("ts.example.test", lookups).await,
|
||||
["ws://plain.example.test:7788/v1", "wss://gw.example.test/v1"]
|
||||
);
|
||||
}
|
||||
|
||||
/// The gateway's plain answer is asked with DNS, but not used.
|
||||
#[tokio::test]
|
||||
async fn a_tls_only_publication_is_not_widened() {
|
||||
let lookups = answering(
|
||||
fake(&[("_tsgws._tcp.ts.example.test.", 0, "gw.example.test.", 443)], &[]),
|
||||
&[("ts.example.test", "ws://ts.example.test:7788/v1")],
|
||||
);
|
||||
assert_eq!(
|
||||
gateways_with("ts.example.test", lookups).await,
|
||||
["wss://gw.example.test:443/v1"]
|
||||
);
|
||||
}
|
||||
|
||||
/// `lookups` whose DNS answers take `dns` and the gateway's own `probe`.
|
||||
fn slow(lookups: Lookups, dns: Duration, probe: Duration) -> Lookups {
|
||||
let Lookups { srv, txt, probe: answer } = lookups;
|
||||
Lookups {
|
||||
srv: Arc::new(move |name| {
|
||||
let found = srv(name);
|
||||
async move {
|
||||
tokio::time::sleep(dns).await;
|
||||
found.await
|
||||
}
|
||||
.boxed()
|
||||
}),
|
||||
txt: Arc::new(move |name| {
|
||||
let found = txt(name);
|
||||
async move {
|
||||
tokio::time::sleep(dns).await;
|
||||
found.await
|
||||
}
|
||||
.boxed()
|
||||
}),
|
||||
probe: Arc::new(move |name| {
|
||||
let found = answer(name);
|
||||
async move {
|
||||
tokio::time::sleep(probe).await;
|
||||
found.await
|
||||
}
|
||||
.boxed()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// SRV, TXT and the gateway's own answer are asked at once: a slow
|
||||
/// gateway and slow DNS cost the slower of them, not the sum; an answer
|
||||
/// that is not used is not waited for.
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn everything_is_asked_at_once() {
|
||||
let published = |srv: &[(&str, u16, &str, u16)]| {
|
||||
answering(
|
||||
fake(srv, &[("_tsgw._tcp.ts.example.test.", "path=/gw")]),
|
||||
&[("ts.example.test", "wss://proxy.example.test/v1")],
|
||||
)
|
||||
};
|
||||
let plain = [("_tsgw._tcp.ts.example.test.", 0, "ts.example.test.", 7788)];
|
||||
let (dns, probe) = (Duration::from_millis(400), Duration::from_millis(2500));
|
||||
let started = tokio::time::Instant::now();
|
||||
assert_eq!(
|
||||
gateways_with("ts.example.test", slow(published(&plain), dns, probe)).await,
|
||||
["ws://ts.example.test:7788/gw", "wss://proxy.example.test/v1"]
|
||||
);
|
||||
assert_eq!(started.elapsed().as_millis(), 2500);
|
||||
let started = tokio::time::Instant::now();
|
||||
assert_eq!(
|
||||
gateways_with("ts.example.test", slow(published(&plain), probe, dns)).await,
|
||||
["ws://ts.example.test:7788/gw", "wss://proxy.example.test/v1"]
|
||||
);
|
||||
assert_eq!(started.elapsed().as_millis(), 2500);
|
||||
// TLS only: the gateway's plain answer is not waited for.
|
||||
let tls = [("_tsgws._tcp.ts.example.test.", 0, "gw.example.test.", 443)];
|
||||
let started = tokio::time::Instant::now();
|
||||
assert_eq!(
|
||||
gateways_with("ts.example.test", slow(published(&tls), dns, probe)).await,
|
||||
["wss://gw.example.test:443/v1"]
|
||||
);
|
||||
assert_eq!(started.elapsed().as_millis(), 400);
|
||||
}
|
||||
|
||||
/// Without records, the most specific name's gateway is waited for
|
||||
/// before a parent domain's answer is taken.
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn without_records_the_most_specific_answer_wins() {
|
||||
let mut lookups = fake(&[], &[]);
|
||||
lookups.probe = Arc::new(|name| {
|
||||
async move {
|
||||
match name.as_str() {
|
||||
"ts.example.test" => {
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
Some("ws://ts.example.test:7788/v1".to_owned())
|
||||
}
|
||||
_ => Some("ws://example.test:7788/v1".to_owned()),
|
||||
}
|
||||
}
|
||||
.boxed()
|
||||
});
|
||||
let started = tokio::time::Instant::now();
|
||||
assert_eq!(
|
||||
gateways_with("ts.example.test", lookups).await,
|
||||
["ws://ts.example.test:7788/v1"]
|
||||
);
|
||||
assert_eq!(started.elapsed().as_millis(), 2000);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_record_that_says_no_service_is_skipped() {
|
||||
let lookups = fake(
|
||||
@@ -284,12 +675,8 @@ mod tests {
|
||||
("_tsgw._tcp.example.test.", 0, "gw.example.test.", 80),
|
||||
],
|
||||
&[("_tsgw._tcp.example.test.", "path=ws")],
|
||||
closed_port(),
|
||||
);
|
||||
assert_eq!(
|
||||
gateway_with("ts.example.test", lookups).await.as_deref(),
|
||||
Some("ws://gw.example.test:80/ws")
|
||||
);
|
||||
assert_eq!(gateways_with("ts.example.test", lookups).await, ["ws://gw.example.test:80/ws"]);
|
||||
}
|
||||
|
||||
/// Without records the gateway next to the server answers at its port,
|
||||
@@ -313,16 +700,17 @@ mod tests {
|
||||
socket.write_all(response.as_bytes()).await.unwrap();
|
||||
}
|
||||
});
|
||||
let lookups = fake(&[], &[], port);
|
||||
let lookups = probing(fake(&[], &[]), port);
|
||||
for address in ["127.0.0.1", "127.0.0.1:9987", "localhost"] {
|
||||
assert_eq!(
|
||||
gateway_with(address, lookups.clone()).await.as_deref(),
|
||||
Some("wss://gw.example.test/v1"),
|
||||
gateways_with(address, lookups.clone()).await,
|
||||
["wss://gw.example.test/v1"],
|
||||
"{address}"
|
||||
);
|
||||
}
|
||||
// Nothing there.
|
||||
assert_eq!(gateway_with("127.0.0.1", fake(&[], &[], closed_port())).await, None);
|
||||
let nothing = probing(fake(&[], &[]), closed_port());
|
||||
assert!(gateways_with("127.0.0.1", nothing).await.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -106,11 +106,11 @@ impl TransferState {
|
||||
}
|
||||
|
||||
/// Reports a transfer's states.
|
||||
pub(crate) type Report = Arc<dyn Fn(TransferState) + Send + Sync>;
|
||||
pub type Report = Arc<dyn Fn(TransferState) + Send + Sync>;
|
||||
|
||||
/// Where a running download writes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) enum Sink {
|
||||
pub enum Sink {
|
||||
/// Write `part` (appending with `append`), then rename it to `dest`.
|
||||
File {
|
||||
part: PathBuf,
|
||||
|
||||
@@ -38,12 +38,24 @@
|
||||
//! and is removed when it ends. The directory is also where the session's
|
||||
//! streams look for streams that started before we joined, next to the
|
||||
//! server's `requeststreaminfo`.
|
||||
//!
|
||||
//! A gateway that cannot be reached, or cannot log us in yet (the server
|
||||
//! does not know the identity before voice connected once; its server is
|
||||
//! restarting), is tried again by itself: after 1, 2, 5, 10, 20, then every
|
||||
//! 30 s, give or take 30 %, and at once when voice connects. Only a refused
|
||||
//! login (signature, security level, ban, not allowed) ends it. A connection
|
||||
//! is pinged every 30 s and left after 60 s without an answer. All of it is
|
||||
//! logged (target `voelin_core::gateway`), never shown.
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use futures::future::{Fuse, FusedFuture, FutureExt};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::info;
|
||||
use voelin_gateway_proto::client::Login;
|
||||
use tracing::{debug, info, warn};
|
||||
pub use voelin_gateway_proto::client::{ClientError, GatewayClient, Push};
|
||||
use voelin_gateway_proto::client::{Login, Progress};
|
||||
use voelin_gateway_proto::{
|
||||
Action, ActivityEntry, ClientMsg, ConfigEntry, ErrorCode, EventInfo, EventQuery, EventSpec,
|
||||
HistoryEntry, HistoryQuery, PermRule, PermRuleInfo, PinInfo, RsvpStatus, StreamEntry,
|
||||
@@ -59,15 +71,23 @@ pub(crate) enum GatewayCmd {
|
||||
OpenChat(ChatTarget),
|
||||
CloseChat(ChatTarget),
|
||||
SendChat(ChatTarget, String),
|
||||
/// Waiting for the next attempt: make it now (voice connected, which
|
||||
/// makes the identity known to the server; the server was selected
|
||||
/// again). Nothing while connected.
|
||||
RetryNow,
|
||||
Stop,
|
||||
}
|
||||
|
||||
pub(crate) enum GatewayEvent {
|
||||
/// Logged in; requests go through `client`.
|
||||
Connected(GatewayClient),
|
||||
/// Logged in at the URL; requests go through the client.
|
||||
Connected(GatewayClient, String),
|
||||
Presence(Box<Presence>),
|
||||
/// A push other than presence.
|
||||
Push(Box<Push>),
|
||||
/// The gateway could not be reached, or the connection was lost; the
|
||||
/// next attempt follows by itself.
|
||||
Retrying(String),
|
||||
/// Stopped, or the gateway refused the login (the reason).
|
||||
Disconnected(Option<String>),
|
||||
}
|
||||
|
||||
@@ -77,21 +97,300 @@ pub async fn connect(
|
||||
url: &str,
|
||||
identity: &tsclientlib::Identity,
|
||||
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
|
||||
let login = Login::Identity { key: identity.key().clone(), key_offset: identity.counter() };
|
||||
voelin_gateway_proto::client::connect(url, login).await
|
||||
connect_watched(url, identity, &Progress::default()).await
|
||||
}
|
||||
|
||||
/// [`connect`], telling `progress` each step (for the log).
|
||||
async fn connect_watched(
|
||||
url: &str,
|
||||
identity: &tsclientlib::Identity,
|
||||
progress: &Progress,
|
||||
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
|
||||
let login = Login::Identity { key: identity.key().clone(), key_offset: identity.counter() };
|
||||
voelin_gateway_proto::client::connect_watched(url, login, progress).await
|
||||
}
|
||||
|
||||
/// Observe through the first of `urls` (best first, as published) that
|
||||
/// logs in.
|
||||
pub(crate) async fn run(
|
||||
url: String,
|
||||
mut urls: Vec<String>,
|
||||
identity: tsclientlib::Identity,
|
||||
mut commands: mpsc::UnboundedReceiver<GatewayCmd>,
|
||||
events: mpsc::UnboundedSender<GatewayEvent>,
|
||||
) {
|
||||
let reason =
|
||||
run_inner(&url, &identity, &mut commands, &events).await.err().map(|e| e.to_string());
|
||||
// A gateway that is away (down, restarting, a network change, a proxy
|
||||
// in front of it that fails) or cannot log us in yet (it does not know
|
||||
// the identity before voice connected once, its server is restarting)
|
||||
// is tried again until the session stops observing; only a refused
|
||||
// login ends it. A round tries every URL in turn without waiting; only
|
||||
// a round that fails waits.
|
||||
debug!(?urls, "gateway: starting");
|
||||
let mut chats = Chats::default();
|
||||
let mut failures = 0;
|
||||
let mut told = Told::default();
|
||||
// Why the last failed round failed.
|
||||
let mut last_round: Option<String> = None;
|
||||
// Attempts since observing started or the connection was lost.
|
||||
let (mut attempts, mut since) = (0, Instant::now());
|
||||
let reason = 'observe: loop {
|
||||
let mut lost = None;
|
||||
let mut index = 0;
|
||||
while index < urls.len() {
|
||||
attempts += 1;
|
||||
let url = urls[index].clone();
|
||||
let next = urls.get(index + 1).map(String::as_str);
|
||||
debug!(%url, attempt = attempts, "gateway: trying");
|
||||
let at = Try { url: &url, number: attempts, since, next };
|
||||
match attempt(&at, &identity, &mut commands, &events, &mut chats, &mut told).await {
|
||||
Ended::Stopped => break 'observe None,
|
||||
Ended::Refused(reason) => break 'observe Some(reason),
|
||||
Ended::Lost { reason, logged_in } => {
|
||||
lost = Some(reason);
|
||||
if logged_in {
|
||||
// It worked: it is tried first again, after a wait.
|
||||
urls[..=index].rotate_right(1);
|
||||
failures = 0;
|
||||
(attempts, since) = (0, Instant::now());
|
||||
break;
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(reason) = lost else { break None };
|
||||
failures += 1;
|
||||
let delay = retry_delay(failures, jitter());
|
||||
// Past the longest wait, the same cause again is not news (a server
|
||||
// only observed, never joined, cannot log us in at all).
|
||||
let wait = delay.as_secs_f64();
|
||||
if failures as usize > RETRY_SECONDS.len() && last_round.as_ref() == Some(&reason) {
|
||||
debug!(failures, error = %reason, "gateway: trying again in {wait:.1} s");
|
||||
} else {
|
||||
info!(failures, error = %reason, "gateway: trying again in {wait:.1} s");
|
||||
}
|
||||
last_round = Some(reason.clone());
|
||||
let _ = events.send(GatewayEvent::Retrying(reason));
|
||||
if !chats.wait(delay, &mut commands).await {
|
||||
break None;
|
||||
}
|
||||
};
|
||||
debug!(?reason, "gateway: stopped");
|
||||
let _ = events.send(GatewayEvent::Disconnected(reason));
|
||||
}
|
||||
|
||||
/// How one connection to the gateway ended.
|
||||
enum Ended {
|
||||
/// The session stopped observing.
|
||||
Stopped,
|
||||
/// The gateway refused the login: trying again would not help.
|
||||
Refused(String),
|
||||
/// Not reached, not logged in yet, or lost (after logging in): try
|
||||
/// again.
|
||||
Lost { reason: String, logged_in: bool },
|
||||
}
|
||||
|
||||
/// Login errors that trying again does not change: the identity or the
|
||||
/// user is not allowed. Anything else (the gateway's server away, an
|
||||
/// identity voice has not made known yet, too many logins) passes.
|
||||
fn refused(code: ErrorCode) -> bool {
|
||||
matches!(
|
||||
code,
|
||||
ErrorCode::AuthFailed | ErrorCode::LevelTooLow | ErrorCode::Banned | ErrorCode::Forbidden
|
||||
)
|
||||
}
|
||||
|
||||
/// One attempt of [`run`], for the log.
|
||||
struct Try<'a> {
|
||||
url: &'a str,
|
||||
/// Since observing started, or the connection was lost; 1 first.
|
||||
number: u32,
|
||||
/// When observing started, or the connection was lost.
|
||||
since: Instant,
|
||||
/// The URL tried next in this round if this one fails.
|
||||
next: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// What was logged per URL: each cause once while it lasts (until a login
|
||||
/// works), not at every attempt of a long absence.
|
||||
#[derive(Default)]
|
||||
struct Told(Vec<(String, String)>);
|
||||
|
||||
impl Told {
|
||||
/// Whether `url` failing with `cause` is news.
|
||||
fn news(&mut self, url: &str, cause: &str) -> bool {
|
||||
if self.0.iter().any(|(u, c)| u == url && c == cause) {
|
||||
return false;
|
||||
}
|
||||
self.0.retain(|(u, _)| u != url);
|
||||
self.0.push((url.to_owned(), cause.to_owned()));
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// One attempt to reach a gateway and log in (TCP, TLS, the WebSocket
|
||||
/// upgrade, the login's own queries at the gateway) gives up after this
|
||||
/// long, so a gateway that never answers does not hold up the next one.
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
|
||||
/// The waits after failed rounds in a row, the last one repeated.
|
||||
const RETRY_SECONDS: [u64; 6] = [1, 2, 5, 10, 20, 30];
|
||||
|
||||
/// The wait before the next attempt after `failures` failed rounds in a
|
||||
/// row, give or take 30 % (`jitter`, -1 to 1): clients that lost the same
|
||||
/// gateway do not all come back at the same moment.
|
||||
fn retry_delay(failures: u32, jitter: f64) -> Duration {
|
||||
let index = (failures.max(1) as usize - 1).min(RETRY_SECONDS.len() - 1);
|
||||
Duration::from_secs(RETRY_SECONDS[index]).mul_f64(1.0 + 0.3 * jitter.clamp(-1.0, 1.0))
|
||||
}
|
||||
|
||||
/// A number from -1 to 1, another each time: the standard library's
|
||||
/// randomly keyed hasher over a counter and the clock.
|
||||
fn jitter() -> f64 {
|
||||
use std::hash::{BuildHasher, Hasher};
|
||||
static COUNT: AtomicU64 = AtomicU64::new(0);
|
||||
let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
|
||||
hasher.write_u64(COUNT.fetch_add(1, Ordering::Relaxed));
|
||||
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH);
|
||||
hasher.write_u128(now.unwrap_or_default().as_nanos());
|
||||
(hasher.finish() >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0
|
||||
}
|
||||
|
||||
/// Asking a gateway that is still connecting to try again at once, at most
|
||||
/// this often ([`Observed::nudge`]): selecting servers does not hammer a
|
||||
/// struggling gateway.
|
||||
const NUDGE_EVERY: Duration = Duration::from_secs(5);
|
||||
|
||||
/// What a session's gateway observes with, so that asking again for the
|
||||
/// same ([`crate::Command::ObserveGateway`], e.g. the server selected again)
|
||||
/// does not start it over, at most makes it try again sooner.
|
||||
pub(crate) struct Observed {
|
||||
urls: Vec<String>,
|
||||
/// The identity's public key.
|
||||
key: String,
|
||||
/// The identity's counter, which the login sends: a raised security
|
||||
/// level keeps the key and changes only this.
|
||||
counter: u64,
|
||||
nudged: Option<Instant>,
|
||||
}
|
||||
|
||||
impl Observed {
|
||||
pub(crate) fn new(urls: &[String], identity: &tsclientlib::Identity) -> Self {
|
||||
Self {
|
||||
urls: urls.to_vec(),
|
||||
key: identity.key().to_pub().to_ts(),
|
||||
counter: identity.counter(),
|
||||
nudged: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this is what is observed with.
|
||||
pub(crate) fn same(&self, urls: &[String], identity: &tsclientlib::Identity) -> bool {
|
||||
self.urls == urls
|
||||
&& self.counter == identity.counter()
|
||||
&& self.key == identity.key().to_pub().to_ts()
|
||||
}
|
||||
|
||||
/// Whether to try again now ([`GatewayCmd::RetryNow`]): not twice
|
||||
/// within [`NUDGE_EVERY`].
|
||||
pub(crate) fn nudge(&mut self) -> bool {
|
||||
self.nudge_at(Instant::now())
|
||||
}
|
||||
|
||||
fn nudge_at(&mut self, now: Instant) -> bool {
|
||||
if self.nudged.is_some_and(|at| now.saturating_duration_since(at) < NUDGE_EVERY) {
|
||||
return false;
|
||||
}
|
||||
self.nudged = Some(now);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Messages written while the gateway is away, at most this many, go out
|
||||
/// when it is back.
|
||||
const MAX_UNSENT: usize = 64;
|
||||
|
||||
/// What a new connection restores: the chats open at the gateway, and
|
||||
/// messages written while it was away.
|
||||
#[derive(Default)]
|
||||
struct Chats {
|
||||
open: Vec<ChatTarget>,
|
||||
unsent: Vec<(ChatTarget, String)>,
|
||||
}
|
||||
|
||||
impl Chats {
|
||||
/// Note a chat command; it goes out when connected.
|
||||
fn note(&mut self, cmd: GatewayCmd) {
|
||||
match cmd {
|
||||
GatewayCmd::OpenChat(target) => {
|
||||
if !self.open.contains(&target) {
|
||||
self.open.push(target);
|
||||
}
|
||||
}
|
||||
GatewayCmd::CloseChat(target) => self.open.retain(|open| *open != target),
|
||||
GatewayCmd::SendChat(target, text) => {
|
||||
if self.unsent.len() < MAX_UNSENT {
|
||||
self.unsent.push((target, text));
|
||||
}
|
||||
}
|
||||
GatewayCmd::RetryNow | GatewayCmd::Stop => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Carry out a chat command on a connected gateway.
|
||||
fn apply(&mut self, client: &GatewayClient, cmd: GatewayCmd) -> Result<(), ClientError> {
|
||||
match cmd {
|
||||
GatewayCmd::OpenChat(target) => {
|
||||
if !self.open.contains(&target) {
|
||||
self.open.push(target.clone());
|
||||
}
|
||||
client.send(ClientMsg::OpenChat { target })
|
||||
}
|
||||
GatewayCmd::CloseChat(target) => {
|
||||
self.open.retain(|open| *open != target);
|
||||
client.send(ClientMsg::CloseChat { target })
|
||||
}
|
||||
GatewayCmd::SendChat(target, text) => client.send(ClientMsg::SendChat { target, text }),
|
||||
GatewayCmd::RetryNow | GatewayCmd::Stop => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the chats again on a new connection and send what waited.
|
||||
fn restore(&mut self, client: &GatewayClient) -> Result<(), ClientError> {
|
||||
for target in &self.open {
|
||||
client.send(ClientMsg::OpenChat { target: target.clone() })?;
|
||||
}
|
||||
for (target, text) in std::mem::take(&mut self.unsent) {
|
||||
client.send(ClientMsg::SendChat { target, text })?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Wait `delay` before the next attempt, noting the commands that come
|
||||
/// meanwhile, or until told to try now; false when the session stops
|
||||
/// observing.
|
||||
async fn wait(
|
||||
&mut self,
|
||||
delay: Duration,
|
||||
commands: &mut mpsc::UnboundedReceiver<GatewayCmd>,
|
||||
) -> bool {
|
||||
let sleep = tokio::time::sleep(delay);
|
||||
tokio::pin!(sleep);
|
||||
loop {
|
||||
tokio::select! {
|
||||
() = &mut sleep => return true,
|
||||
cmd = commands.recv() => match cmd {
|
||||
None | Some(GatewayCmd::Stop) => return false,
|
||||
Some(GatewayCmd::RetryNow) => {
|
||||
debug!("gateway: trying again now");
|
||||
return true;
|
||||
}
|
||||
Some(cmd) => self.note(cmd),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Features whose pushes for open chats need [`ClientMsg::Enable`].
|
||||
const CHAT_EXTENSIONS: [&str; 4] = [
|
||||
voelin_gateway_proto::feature::HISTORY,
|
||||
@@ -100,38 +399,155 @@ const CHAT_EXTENSIONS: [&str; 4] = [
|
||||
voelin_gateway_proto::feature::TOPICS,
|
||||
];
|
||||
|
||||
async fn run_inner(
|
||||
url: &str,
|
||||
/// One connection: log in, then relay until it ends.
|
||||
async fn attempt(
|
||||
at: &Try<'_>,
|
||||
identity: &tsclientlib::Identity,
|
||||
commands: &mut mpsc::UnboundedReceiver<GatewayCmd>,
|
||||
events: &mpsc::UnboundedSender<GatewayEvent>,
|
||||
) -> anyhow::Result<()> {
|
||||
let (client, mut pushes) = match connect(url, identity).await {
|
||||
Ok(connected) => connected,
|
||||
Err(ClientError::Gateway { code, message }) => {
|
||||
let _ = events
|
||||
.send(GatewayEvent::Push(Box::new(Push::Error { code, message: message.clone() })));
|
||||
anyhow::bail!("gateway refused login: {message}");
|
||||
chats: &mut Chats,
|
||||
told: &mut Told,
|
||||
) -> Ended {
|
||||
let url = at.url;
|
||||
let lost = |reason: String| Ended::Lost { reason, logged_in: false };
|
||||
let progress = Progress::default();
|
||||
let started = Instant::now();
|
||||
let result =
|
||||
tokio::time::timeout(CONNECT_TIMEOUT, connect_watched(url, identity, &progress)).await;
|
||||
let elapsed_ms = started.elapsed().as_millis() as u64;
|
||||
let (stage, peer) = (progress.stage(), progress.peer_addr());
|
||||
let (client, mut pushes) = match result {
|
||||
Ok(Ok(connected)) => connected,
|
||||
Ok(Err(ClientError::Gateway { code, message })) if refused(code) => {
|
||||
warn!(%url, ?code, %message, "gateway refused the login");
|
||||
return Ended::Refused(format!("gateway refused login: {code:?}: {message}"));
|
||||
}
|
||||
// Observing starts before voice: on a server we never joined, the
|
||||
// first login cannot work. Voice connecting makes it try again.
|
||||
Ok(Err(ClientError::Gateway { code: ErrorCode::UnknownIdentity, message })) => {
|
||||
if told.news(url, "unknown identity") {
|
||||
info!(%url, elapsed_ms, "the server does not know this identity yet (voice connects it); trying again");
|
||||
} else {
|
||||
debug!(%url, elapsed_ms, "the server does not know this identity yet");
|
||||
}
|
||||
return lost(format!("UnknownIdentity: {message}"));
|
||||
}
|
||||
Ok(Err(ClientError::Gateway { code, message })) => {
|
||||
if told.news(url, &format!("{code:?}")) {
|
||||
warn!(%url, ?code, %message, elapsed_ms, next = ?at.next, "gateway did not log us in; trying again");
|
||||
} else {
|
||||
debug!(%url, ?code, %message, elapsed_ms, "gateway still does not log us in");
|
||||
}
|
||||
return lost(format!("{code:?}: {message}"));
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
let reason = e.to_string();
|
||||
if told.news(url, &reason) {
|
||||
warn!(%url, %stage, ?peer, steps = %progress, elapsed_ms, error = %reason, next = ?at.next, "gateway unreachable");
|
||||
} else {
|
||||
debug!(%url, %stage, steps = %progress, elapsed_ms, error = %reason, "gateway still unreachable");
|
||||
}
|
||||
return lost(reason);
|
||||
}
|
||||
Err(_) => {
|
||||
let reason = format!("no answer within {} s ({stage})", CONNECT_TIMEOUT.as_secs());
|
||||
if told.news(url, &reason) {
|
||||
warn!(%url, %stage, ?peer, steps = %progress, elapsed_ms, next = ?at.next, "gateway unreachable: {reason}");
|
||||
} else {
|
||||
debug!(%url, %stage, steps = %progress, elapsed_ms, "gateway still unreachable: {reason}");
|
||||
}
|
||||
return lost(reason);
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
info!(server_name = %client.info().server_name, capabilities = ?client.capabilities(), "gateway connected");
|
||||
*told = Told::default();
|
||||
info!(
|
||||
%url,
|
||||
attempt = at.number,
|
||||
connect_ms = elapsed_ms,
|
||||
since_start_ms = at.since.elapsed().as_millis() as u64,
|
||||
server = %client.info().server_name,
|
||||
?peer,
|
||||
steps = %progress,
|
||||
capabilities = ?client.capabilities(),
|
||||
"gateway connected"
|
||||
);
|
||||
let connected = Instant::now();
|
||||
let reason = match relay(url, &client, &mut pushes, commands, events, chats, connected).await {
|
||||
Ok(Ended::Lost { reason, .. }) => reason,
|
||||
Ok(ended) => {
|
||||
debug!(%url, connected_for_s = connected.elapsed().as_secs(), "gateway: left");
|
||||
return ended;
|
||||
}
|
||||
Err(e) => e.to_string(),
|
||||
};
|
||||
warn!(%url, connected_for_s = connected.elapsed().as_secs(), error = %reason, "gateway connection lost");
|
||||
Ended::Lost { reason, logged_in: true }
|
||||
}
|
||||
|
||||
/// A connection is checked this often while nothing else asks the gateway
|
||||
/// anything ([`ClientMsg::Ping`])…
|
||||
const PING_EVERY: Duration = Duration::from_secs(30);
|
||||
/// …and taken as lost without an answer within this long (the gateway
|
||||
/// answers in turn, after requests that can take a while).
|
||||
const PING_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Whether the gateway still answers: a ping, answered in time.
|
||||
async fn alive(client: &GatewayClient) -> Result<(), String> {
|
||||
match tokio::time::timeout(PING_TIMEOUT, client.request(ClientMsg::Ping)).await {
|
||||
// Any answer will do, also an error from an older gateway.
|
||||
Ok(Ok(_) | Err(ClientError::Gateway { .. })) => Ok(()),
|
||||
Ok(Err(e)) => Err(e.to_string()),
|
||||
Err(_) => Err(format!("no answer to a ping within {} s", PING_TIMEOUT.as_secs())),
|
||||
}
|
||||
}
|
||||
|
||||
async fn relay(
|
||||
url: &str,
|
||||
client: &GatewayClient,
|
||||
pushes: &mut mpsc::UnboundedReceiver<Push>,
|
||||
commands: &mut mpsc::UnboundedReceiver<GatewayCmd>,
|
||||
events: &mpsc::UnboundedSender<GatewayEvent>,
|
||||
chats: &mut Chats,
|
||||
connected: Instant,
|
||||
) -> Result<Ended, ClientError> {
|
||||
let lost = |reason: String| Ended::Lost { reason, logged_in: true };
|
||||
// Messages with their gateway ids, pins, reactions and topics of open
|
||||
// chats (older gateways answer `unknown_type` as a push; ignored).
|
||||
if CHAT_EXTENSIONS.iter().any(|f| client.has(f)) {
|
||||
client.send(ClientMsg::Enable { features: Vec::new() })?;
|
||||
}
|
||||
let _ = events.send(GatewayEvent::Connected(client.clone()));
|
||||
let _ = events.send(GatewayEvent::Connected(client.clone(), url.to_owned()));
|
||||
client.subscribe_presence()?;
|
||||
chats.restore(client)?;
|
||||
let mut presence = Presence::default();
|
||||
let mut synced = false;
|
||||
// A connection that died without closing (a network change, sleep, a
|
||||
// NAT that forgot it) shows only when the gateway stops answering.
|
||||
let start = tokio::time::Instant::now() + PING_EVERY;
|
||||
let mut keepalive = tokio::time::interval_at(start, PING_EVERY);
|
||||
keepalive.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
let ping = Fuse::terminated();
|
||||
tokio::pin!(ping);
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
push = pushes.recv() => match push {
|
||||
None | Some(Push::Disconnected(None)) => return Ok(()),
|
||||
Some(Push::Disconnected(Some(reason))) => anyhow::bail!(reason),
|
||||
None | Some(Push::Disconnected(None)) => {
|
||||
return Ok(lost("the gateway closed the connection".into()));
|
||||
}
|
||||
Some(Push::Disconnected(Some(reason))) => return Ok(lost(reason)),
|
||||
Some(Push::PresenceSnapshot(snapshot)) => {
|
||||
presence = Presence::from_snapshot(snapshot);
|
||||
if !synced {
|
||||
synced = true;
|
||||
info!(
|
||||
%url,
|
||||
channels = presence.channels.len(),
|
||||
clients = presence.clients.len(),
|
||||
since_connect_ms = connected.elapsed().as_millis() as u64,
|
||||
"gateway presence"
|
||||
);
|
||||
}
|
||||
let _ = events.send(GatewayEvent::Presence(Box::new(presence.clone())));
|
||||
}
|
||||
Some(Push::PresenceDelta(delta)) => {
|
||||
@@ -140,25 +556,24 @@ async fn run_inner(
|
||||
}
|
||||
// Answers to requests sent without waiting.
|
||||
Some(Push::Other(_) | Push::Error { code: ErrorCode::UnknownType, .. }) => {}
|
||||
// The gateway forgot the login (restarted): log in again.
|
||||
Some(Push::Error { code: ErrorCode::NotAuthenticated, message }) => {
|
||||
let _ = events.send(GatewayEvent::Push(Box::new(Push::Error {
|
||||
code: ErrorCode::NotAuthenticated,
|
||||
message: message.clone(),
|
||||
})));
|
||||
anyhow::bail!("gateway session lost: {message}");
|
||||
return Ok(lost(format!("gateway session lost: {message}")));
|
||||
}
|
||||
Some(push) => {
|
||||
let _ = events.send(GatewayEvent::Push(Box::new(push)));
|
||||
}
|
||||
},
|
||||
cmd = commands.recv() => match cmd {
|
||||
None | Some(GatewayCmd::Stop) => return Ok(()),
|
||||
Some(GatewayCmd::OpenChat(target)) => client.send(ClientMsg::OpenChat { target })?,
|
||||
Some(GatewayCmd::CloseChat(target)) => client.send(ClientMsg::CloseChat { target })?,
|
||||
Some(GatewayCmd::SendChat(target, text)) => {
|
||||
client.send(ClientMsg::SendChat { target, text })?;
|
||||
}
|
||||
None | Some(GatewayCmd::Stop) => return Ok(Ended::Stopped),
|
||||
Some(cmd) => chats.apply(client, cmd)?,
|
||||
},
|
||||
_ = keepalive.tick(), if ping.is_terminated() => ping.set(alive(client).fuse()),
|
||||
answer = &mut ping => {
|
||||
if let Err(reason) = answer {
|
||||
return Ok(lost(reason));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -388,6 +803,8 @@ pub struct Pin {
|
||||
pub enum GatewayUpdate {
|
||||
/// Logged in.
|
||||
Connected {
|
||||
/// Where: the first of the published URLs that logged in.
|
||||
url: String,
|
||||
gateway_id: String,
|
||||
server_uid: String,
|
||||
server_name: String,
|
||||
@@ -733,3 +1150,194 @@ pub(crate) struct ReactionPush {
|
||||
pub added: bool,
|
||||
pub count: u32,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use voelin_gateway_proto::{Envelope, ServerMsg};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn millis(d: Duration) -> u64 {
|
||||
(d.as_secs_f64() * 1000.0).round() as u64
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retries_come_soon_then_every_30_s_spread() {
|
||||
let seconds: Vec<u64> = (0..=8).map(|n| retry_delay(n, 0.0).as_secs()).collect();
|
||||
assert_eq!(seconds, [1, 1, 2, 5, 10, 20, 30, 30, 30]);
|
||||
// Give or take 30 %.
|
||||
assert_eq!(millis(retry_delay(1, -1.0)), 700);
|
||||
assert_eq!(millis(retry_delay(1, 1.0)), 1300);
|
||||
assert_eq!(millis(retry_delay(6, 1.0)), 39_000);
|
||||
assert_eq!(millis(retry_delay(3, 7.0)), millis(retry_delay(3, 1.0)));
|
||||
let samples: Vec<f64> = (0..1000).map(|_| jitter()).collect();
|
||||
assert!(samples.iter().all(|j| (-1.0..1.0).contains(j)), "{samples:?}");
|
||||
assert!(samples.iter().any(|j| *j < -0.5) && samples.iter().any(|j| *j > 0.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_observation_is_nudged_at_most_every_5_s() {
|
||||
let identity = tsclientlib::Identity::create();
|
||||
let urls = vec!["ws://gw.example.test:7788/v1".to_owned()];
|
||||
let mut observed = Observed::new(&urls, &identity);
|
||||
assert!(observed.same(&urls, &identity));
|
||||
assert!(!observed.same(&["wss://gw.example.test/v1".to_owned()], &identity));
|
||||
assert!(!observed.same(&urls, &tsclientlib::Identity::create()));
|
||||
// Its security level raised: logged in with the new counter.
|
||||
let raised = tsclientlib::Identity::new(identity.key().clone(), identity.counter() + 1);
|
||||
assert!(!observed.same(&urls, &raised));
|
||||
let now = Instant::now();
|
||||
assert!(observed.nudge_at(now));
|
||||
assert!(!observed.nudge_at(now + Duration::from_secs(4)));
|
||||
assert!(observed.nudge_at(now + NUDGE_EVERY));
|
||||
assert!(!observed.nudge_at(now + NUDGE_EVERY + Duration::from_secs(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_some_login_errors_are_final() {
|
||||
use ErrorCode as E;
|
||||
for code in [E::AuthFailed, E::LevelTooLow, E::Banned, E::Forbidden] {
|
||||
assert!(refused(code), "{code:?}");
|
||||
}
|
||||
for code in [
|
||||
E::Unavailable,
|
||||
E::Internal,
|
||||
E::RateLimited,
|
||||
E::UnknownIdentity,
|
||||
E::NotAuthenticated,
|
||||
E::BadRequest,
|
||||
E::Unknown,
|
||||
] {
|
||||
assert!(!refused(code), "{code:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn retry_now_ends_the_wait() {
|
||||
let (tx, mut rx) = mpsc::unbounded_channel();
|
||||
let mut chats = Chats::default();
|
||||
let start = tokio::time::Instant::now();
|
||||
// What comes meanwhile is noted; RetryNow ends the wait at once.
|
||||
tx.send(GatewayCmd::OpenChat(ChatTarget::Channel(1))).unwrap();
|
||||
tx.send(GatewayCmd::RetryNow).unwrap();
|
||||
assert!(chats.wait(Duration::from_secs(30), &mut rx).await);
|
||||
assert_eq!(start.elapsed(), Duration::ZERO);
|
||||
assert_eq!(chats.open, [ChatTarget::Channel(1)]);
|
||||
// Told 3 s into a wait of 30.
|
||||
let told = tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_secs(3)).await;
|
||||
tx.send(GatewayCmd::RetryNow).unwrap();
|
||||
tx
|
||||
});
|
||||
assert!(chats.wait(Duration::from_secs(30), &mut rx).await);
|
||||
assert_eq!(millis(start.elapsed()), 3000);
|
||||
let tx = told.await.unwrap();
|
||||
// Not told: the whole wait.
|
||||
assert!(chats.wait(Duration::from_secs(30), &mut rx).await);
|
||||
assert_eq!(millis(start.elapsed()), 33_000);
|
||||
tx.send(GatewayCmd::Stop).unwrap();
|
||||
assert!(!chats.wait(Duration::from_secs(30), &mut rx).await);
|
||||
}
|
||||
|
||||
/// A logged-in client of a gateway on an in-memory connection that
|
||||
/// answers pings when `pings`; counts the pings.
|
||||
async fn gateway(
|
||||
pings: bool,
|
||||
) -> (GatewayClient, mpsc::UnboundedReceiver<Push>, Arc<AtomicUsize>) {
|
||||
let (near, far) = tokio::io::duplex(64 * 1024);
|
||||
let count = Arc::new(AtomicUsize::new(0));
|
||||
let counted = count.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut ws = tokio_tungstenite::accept_async(far).await.unwrap();
|
||||
let hello = ServerMsg::Hello {
|
||||
gateway_id: "gw".into(),
|
||||
server_uid: "server".into(),
|
||||
server_name: "Server".into(),
|
||||
nonce: "n".into(),
|
||||
capabilities: Vec::new(),
|
||||
};
|
||||
let text = serde_json::to_string(&Envelope::new(hello)).unwrap();
|
||||
ws.send(Message::Text(text.into())).await.unwrap();
|
||||
while let Some(Ok(frame)) = ws.next().await {
|
||||
let Message::Text(text) = frame else { continue };
|
||||
let env: Envelope<ClientMsg> = serde_json::from_str(text.as_str()).unwrap();
|
||||
let reply = match env.msg {
|
||||
ClientMsg::Resume { .. } => ServerMsg::AuthOk {
|
||||
uid: "me".into(),
|
||||
token: "t".into(),
|
||||
token_expires: 0,
|
||||
capabilities: Vec::new(),
|
||||
},
|
||||
ClientMsg::Ping => {
|
||||
counted.fetch_add(1, Ordering::SeqCst);
|
||||
if !pings {
|
||||
continue;
|
||||
}
|
||||
ServerMsg::Pong
|
||||
}
|
||||
_ => ServerMsg::Ok,
|
||||
};
|
||||
let text = serde_json::to_string(&Envelope::with_id(env.id.unwrap_or(0), reply));
|
||||
if ws.send(Message::Text(text.unwrap().into())).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let (ws, _) = tokio_tungstenite::client_async("ws://gw.test/v1", near).await.unwrap();
|
||||
let (client, pushes) = GatewayClient::start(ws, Login::Token("t".into())).await.unwrap();
|
||||
(client, pushes, count)
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_gateway_that_stops_answering_is_left() {
|
||||
let (client, mut pushes, pings) = gateway(false).await;
|
||||
let (_tx, mut commands) = mpsc::unbounded_channel();
|
||||
let (events, _events) = mpsc::unbounded_channel();
|
||||
let start = tokio::time::Instant::now();
|
||||
let mut chats = Chats::default();
|
||||
let ended = relay(
|
||||
"ws://gw.test/v1",
|
||||
&client,
|
||||
&mut pushes,
|
||||
&mut commands,
|
||||
&events,
|
||||
&mut chats,
|
||||
Instant::now(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let Ended::Lost { reason, logged_in: true } = ended else { panic!("not lost") };
|
||||
assert!(reason.contains("ping"), "{reason}");
|
||||
assert_eq!(millis(start.elapsed()), millis(PING_EVERY + PING_TIMEOUT));
|
||||
assert_eq!(pings.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_gateway_that_answers_pings_is_kept() {
|
||||
let (client, mut pushes, pings) = gateway(true).await;
|
||||
let (_tx, mut commands) = mpsc::unbounded_channel();
|
||||
let (events, _events) = mpsc::unbounded_channel();
|
||||
let mut chats = Chats::default();
|
||||
let relayed = tokio::time::timeout(
|
||||
// The 20th ping at 600 s, answered.
|
||||
Duration::from_secs(615),
|
||||
relay(
|
||||
"ws://gw.test/v1",
|
||||
&client,
|
||||
&mut pushes,
|
||||
&mut commands,
|
||||
&events,
|
||||
&mut chats,
|
||||
Instant::now(),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert!(relayed.is_err(), "the connection was left");
|
||||
assert_eq!(pings.load(Ordering::SeqCst), 20);
|
||||
}
|
||||
}
|
||||
+152
-29
@@ -3,7 +3,8 @@
|
||||
//! The UI talks to an [`Engine`] with [`Command`]s and receives [`Event`]s.
|
||||
//! Each server the user works with is a session with up to three sources:
|
||||
//!
|
||||
//! - **voice**: a normal client connection (visible, can talk)
|
||||
//! - **voice**: a normal client connection (visible, can talk), made by a
|
||||
//! [`link::ServerLink`] ([`TsLink`] for TeamSpeak servers; see [`link`])
|
||||
//! - **gateway**: a `tsgw` gateway (invisible presence, relayed chat)
|
||||
//! - **query**: the user's own ServerQuery credentials (same, without a gateway)
|
||||
//!
|
||||
@@ -39,9 +40,9 @@
|
||||
//! [`Event::Poke`]), private messages to any client (a
|
||||
//! [`ChatTarget::Private`] chat, stored under the peer's unique id), the
|
||||
//! channels' file browsers, avatars and icons ([`files`], cached in
|
||||
//! [`cache`]) and offline messages ([`offline`]). The host banner and
|
||||
//! channel banners are pictures on the web, fetched into the same cache
|
||||
//! ([`Event::PictureReady`]). Contacts (friends, blocked people, per-person
|
||||
//! [`cache`]) and offline messages ([`offline`]). The host banner, channel
|
||||
//! banners and the clients' badges are pictures on the web, fetched into the
|
||||
//! same cache ([`Event::PictureReady`]). Contacts (friends, blocked people, per-person
|
||||
//! volume) are engine-wide ([`contacts`]).
|
||||
|
||||
mod audio;
|
||||
@@ -53,6 +54,7 @@ pub mod files;
|
||||
pub mod gateway;
|
||||
pub mod history;
|
||||
pub mod identity;
|
||||
pub mod link;
|
||||
#[cfg(feature = "media")]
|
||||
pub mod media;
|
||||
pub mod offline;
|
||||
@@ -61,8 +63,10 @@ mod route;
|
||||
mod session;
|
||||
pub mod settings;
|
||||
pub mod stream;
|
||||
mod stream_types;
|
||||
#[cfg(feature = "media")]
|
||||
pub mod studio;
|
||||
mod ts_link;
|
||||
pub mod versions;
|
||||
mod voice;
|
||||
mod web;
|
||||
@@ -76,7 +80,6 @@ pub use voelin_audio::settings::TransmitMode;
|
||||
pub use voelin_audio::{AudioSettings, ProcessingSettings, VadSettings};
|
||||
use voelin_model::{
|
||||
Capabilities, ChannelId, ChatMessage, ChatTarget, FileRef, GroupInfo, Presence, ServerDetails,
|
||||
ServerFlavor,
|
||||
};
|
||||
|
||||
use crate::audio::{AudioEvent, AudioHandle, AudioIn};
|
||||
@@ -88,22 +91,36 @@ pub use files::{Bytes, DownloadTo, FileEntry, RequestId, TransferId, TransferSta
|
||||
pub use gateway::{GatewayRequest, GatewayUpdate};
|
||||
use history::SharedHistory;
|
||||
pub use history::{History, HistoryMessage, HistorySource};
|
||||
pub use link::ConnectOptions;
|
||||
pub use link::ConnectOptions as VoiceOptions;
|
||||
pub use link::ServerLink;
|
||||
pub use offline::{OfflineMessage, OfflineMessageInfo};
|
||||
pub use route::{ChatRoute, Dedup, route_chat};
|
||||
use settings::{SettingChange, Settings, SharedSettings};
|
||||
use stream::{EncodedFrame, LayerId, LayerSpec, StreamInfo, StreamSetup, ViewerInfo};
|
||||
pub use stream::{StreamFrame, StreamSink, StreamState, WatchState};
|
||||
use voelin_stream::{
|
||||
EncodedFrame, LayerId, LayerSpec, SrtpProfile, StreamInfo, StreamSetup, ViewerInfo,
|
||||
};
|
||||
pub use voice::VoiceOptions;
|
||||
pub use ts_link::TsLink;
|
||||
/// Banners are downloaded and shown by the same rule.
|
||||
pub use web::is_svg;
|
||||
/// Pictures from the web go through the desktop's proxy (set at startup).
|
||||
pub use web::set_proxy_resolver;
|
||||
|
||||
pub type SessionId = u64;
|
||||
|
||||
/// The longest poke message servers take, in characters; a longer one is
|
||||
/// cut ([`Command::Poke`]).
|
||||
pub const POKE_MESSAGE_MAX: usize = 100;
|
||||
|
||||
/// What the UI asks for.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Command {
|
||||
/// Main account proof for every current and future voice connection.
|
||||
SetMytsIdentity(Option<Arc<tsproto::myts::Identity>>),
|
||||
/// What voice servers are shown of the main account (its avatar and
|
||||
/// badges with their certificates, its User Tag; TeamSpeak 6): sent to
|
||||
/// every connection that presents the account's myTS ID, once connected
|
||||
/// and when it changes; cleared on a sign-out.
|
||||
SetMytsData(Option<Arc<tsclientlib::MytsData>>),
|
||||
ConnectVoice {
|
||||
session: SessionId,
|
||||
options: Box<VoiceOptions>,
|
||||
@@ -111,10 +128,14 @@ pub enum Command {
|
||||
DisconnectVoice {
|
||||
session: SessionId,
|
||||
},
|
||||
/// Invisible presence and relay chat through a `tsgw` gateway.
|
||||
/// Invisible presence and relay chat through a `tsgw` gateway: the first
|
||||
/// of `urls` (best first, [`discover::gateways`]) that logs in, tried in
|
||||
/// turn again whenever it is lost. Sent again with the same `urls` and
|
||||
/// identity while it runs, it is not started over; while still
|
||||
/// connecting, it tries again at once (at most every 5 s).
|
||||
ObserveGateway {
|
||||
session: SessionId,
|
||||
url: String,
|
||||
urls: Vec<String>,
|
||||
identity: Box<tsclientlib::Identity>,
|
||||
},
|
||||
/// Invisible presence and relay chat with own ServerQuery credentials.
|
||||
@@ -153,6 +174,7 @@ pub enum Command {
|
||||
session: SessionId,
|
||||
request: GatewayRequest,
|
||||
},
|
||||
/// Refusals come as [`Event::JoinFailed`].
|
||||
MoveToChannel {
|
||||
session: SessionId,
|
||||
channel: ChannelId,
|
||||
@@ -230,11 +252,13 @@ pub enum Command {
|
||||
session: SessionId,
|
||||
layers: Vec<LayerSpec>,
|
||||
},
|
||||
/// SRTP protection profiles for stream connections, in order of
|
||||
/// preference (a user setting; empty: the default,
|
||||
/// `SrtpProfile::DEFAULT_ORDER`). Applies to connections made from now
|
||||
/// on, in all sessions and those started later.
|
||||
SetSrtpProfiles(Vec<SrtpProfile>),
|
||||
/// SRTP protection profiles for stream connections by name (RFC 5764 and
|
||||
/// RFC 7714: `AEAD_AES_128_GCM`, `AES128_CM_SHA1_80`, ...; names the stream
|
||||
/// transport does not know are left out), in order of preference (the
|
||||
/// `stream.srtp_profiles` setting). Empty: the transport's default order.
|
||||
/// Applies to connections made from now on, in all sessions and those
|
||||
/// started later.
|
||||
SetSrtpProfiles(Vec<String>),
|
||||
/// Watch a stream from [`Event::StreamsChanged`]. Frames arrive through
|
||||
/// [`Engine::subscribe_frames`].
|
||||
WatchStream {
|
||||
@@ -273,7 +297,8 @@ pub enum Command {
|
||||
volume: f32,
|
||||
},
|
||||
/// Poke a client (voice): the server shows it a notification with
|
||||
/// `message`. Failures come as [`Event::Error`].
|
||||
/// `message`, cut to [`POKE_MESSAGE_MAX`] characters. Failures come as
|
||||
/// [`Event::Error`].
|
||||
Poke {
|
||||
session: SessionId,
|
||||
client: u16,
|
||||
@@ -365,6 +390,14 @@ pub enum Command {
|
||||
session: SessionId,
|
||||
client_uid: String,
|
||||
},
|
||||
/// Get a picture on the web that a chat message shows (`[img]`) into
|
||||
/// the cache ([`Event::PictureReady`]) while `cache.fetch_images` is on;
|
||||
/// one larger than `max_bytes` is not reported.
|
||||
FetchPicture {
|
||||
session: SessionId,
|
||||
url: String,
|
||||
max_bytes: u64,
|
||||
},
|
||||
/// Our offline messages ([`Event::OfflineMessages`]); see [`offline`].
|
||||
ListOfflineMessages {
|
||||
session: SessionId,
|
||||
@@ -469,6 +502,41 @@ pub struct SessionState {
|
||||
pub server_uid: Option<String>,
|
||||
}
|
||||
|
||||
/// Why the server did not let us into a channel ([`Event::JoinFailed`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum JoinFailure {
|
||||
/// The channel's password is missing or wrong.
|
||||
Password,
|
||||
/// The channel, or the channel with its subchannels, is full.
|
||||
Full,
|
||||
/// Anything else, as a sentence for the user.
|
||||
Other(String),
|
||||
}
|
||||
|
||||
/// The software on the other end of a session, as its link names it. It is
|
||||
/// for people to read; nothing branches on it (what the server can do is
|
||||
/// [`Capabilities`]).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct BackendInfo {
|
||||
/// What it is called ("TeamSpeak 6"); empty when it was not recognised.
|
||||
pub product: String,
|
||||
/// Its version as the product shows it ("6.0.0-beta13.1"); what the
|
||||
/// server said, as it is, when `product` is empty.
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
impl BackendInfo {
|
||||
/// For a sentence: the product and the version, whichever there are
|
||||
/// ("TeamSpeak 6 6.0.0-beta13.1", "TeamSpeak 3", "custom 9").
|
||||
pub fn label(&self) -> String {
|
||||
match (self.product.is_empty(), self.version.is_empty()) {
|
||||
(false, false) => format!("{} {}", self.product, self.version),
|
||||
(false, true) => self.product.clone(),
|
||||
(true, _) => self.version.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the engine reports.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Event {
|
||||
@@ -476,10 +544,12 @@ pub enum Event {
|
||||
session: SessionId,
|
||||
state: SessionState,
|
||||
},
|
||||
/// The server answered: its name, the software it runs and what that
|
||||
/// software can do (the UI hides what it cannot).
|
||||
ServerInfo {
|
||||
session: SessionId,
|
||||
name: String,
|
||||
flavor: ServerFlavor,
|
||||
backend: BackendInfo,
|
||||
capabilities: Capabilities,
|
||||
},
|
||||
/// Full presence of the session (the UI rebuilds its view from it).
|
||||
@@ -534,6 +604,12 @@ pub enum Event {
|
||||
session: SessionId,
|
||||
message: String,
|
||||
},
|
||||
/// The server refused [`Command::MoveToChannel`] into `channel`.
|
||||
JoinFailed {
|
||||
session: SessionId,
|
||||
channel: ChannelId,
|
||||
reason: JoinFailure,
|
||||
},
|
||||
/// The streams in our channel (TeamSpeak 6), full list.
|
||||
StreamsChanged {
|
||||
session: SessionId,
|
||||
@@ -640,9 +716,10 @@ pub enum Event {
|
||||
request: RequestId,
|
||||
result: Result<(), String>,
|
||||
},
|
||||
/// A client's avatar is in the cache: `path`, its MD5 `hash`
|
||||
/// ([`voelin_model::ClientInfo::avatar`]). Comes when the client appears
|
||||
/// with an avatar and when it changes.
|
||||
/// A client's avatar is in the cache: `path`, and `hash`: the MD5 of a
|
||||
/// server avatar ([`voelin_model::ClientInfo::avatar`]), or the address
|
||||
/// of a myTeamSpeak avatar ([`voelin_model::ClientInfo::myts_avatar`]).
|
||||
/// Comes when the client appears with an avatar and when it changes.
|
||||
AvatarReady {
|
||||
session: SessionId,
|
||||
client_uid: String,
|
||||
@@ -656,9 +733,11 @@ pub enum Event {
|
||||
path: PathBuf,
|
||||
},
|
||||
/// A picture on the web is in the cache: the host banner
|
||||
/// ([`ServerDetails::banner_gfx_url`]) or a channel's
|
||||
/// ([`voelin_model::ChannelInfo::banner_gfx_url`]) at `url` (setting
|
||||
/// `cache.fetch_images`). Comes again when the host banner was reloaded
|
||||
/// ([`ServerDetails::banner_gfx_url`]), a channel's
|
||||
/// ([`voelin_model::ChannelInfo::banner_gfx_url`]), a badge's
|
||||
/// ([`voelin_model::badges::icon_url`]) or one a chat message shows
|
||||
/// ([`Command::FetchPicture`]) at `url` (setting `cache.fetch_images`).
|
||||
/// Comes again when the host banner was reloaded
|
||||
/// (`banner_gfx_interval_s`, at least a minute): the file at `path`
|
||||
/// changed.
|
||||
PictureReady {
|
||||
@@ -713,8 +792,19 @@ impl Engine {
|
||||
}
|
||||
|
||||
/// Start the engine on the current tokio runtime with `settings` and
|
||||
/// chat `history`.
|
||||
/// chat `history`, connecting voice with [`TsLink`].
|
||||
pub fn start_with(settings: Settings, history: History) -> Self {
|
||||
Self::start_with_link(settings, history, Arc::new(TsLink))
|
||||
}
|
||||
|
||||
/// Start the engine on the current tokio runtime with `settings` and
|
||||
/// chat `history`, connecting voice with `link` (every session's voice
|
||||
/// source is one of its connections, see [`link`]).
|
||||
pub fn start_with_link(
|
||||
settings: Settings,
|
||||
history: History,
|
||||
link: Arc<dyn ServerLink>,
|
||||
) -> Self {
|
||||
let (commands, rx) = mpsc::unbounded_channel();
|
||||
let (events, _) = broadcast::channel(4096);
|
||||
// About a minute of one watched stream.
|
||||
@@ -726,7 +816,7 @@ impl Engine {
|
||||
history,
|
||||
cache: SharedCache::new(Cache::new(Cache::default_dir())),
|
||||
};
|
||||
tokio::spawn(run(rx, events.clone(), frames.clone(), shared.clone()));
|
||||
tokio::spawn(run(rx, events.clone(), frames.clone(), shared.clone(), link));
|
||||
Self { commands, events, frames, runtime: tokio::runtime::Handle::current(), shared }
|
||||
}
|
||||
|
||||
@@ -810,18 +900,20 @@ async fn run(
|
||||
events: broadcast::Sender<Event>,
|
||||
frames: broadcast::Sender<StreamFrame>,
|
||||
engine: Shared,
|
||||
link: Arc<dyn ServerLink>,
|
||||
) {
|
||||
let Shared { settings: shared, history, cache, contacts } = engine.clone();
|
||||
// Before any command: a contact set meanwhile would be lost.
|
||||
contacts.load().await;
|
||||
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
|
||||
let (myts_identity, _) = watch::channel(None);
|
||||
let (myts_data, _) = watch::channel(None);
|
||||
let mut current = shared.current();
|
||||
// Pruning: at start, then hourly (and when the setting changes).
|
||||
let mut prune = tokio::time::interval(std::time::Duration::from_secs(3600));
|
||||
let mut changes = current.subscribe();
|
||||
let mut settings = AudioSettings::default();
|
||||
let mut srtp_profiles: Option<Vec<SrtpProfile>> = None;
|
||||
let mut srtp_profiles: Option<Vec<String>> = None;
|
||||
let mut mic_test: Option<AudioHandle> = None;
|
||||
loop {
|
||||
let input = tokio::select! {
|
||||
@@ -873,6 +965,16 @@ async fn run(
|
||||
});
|
||||
continue;
|
||||
}
|
||||
Command::SetMytsData(data) => {
|
||||
myts_data.send_if_modified(|current| {
|
||||
if *current == data {
|
||||
return false;
|
||||
}
|
||||
*current = data;
|
||||
true
|
||||
});
|
||||
continue;
|
||||
}
|
||||
Command::SetAudioSettings(new) => {
|
||||
settings = (*new).clone();
|
||||
for s in sessions.values() {
|
||||
@@ -948,7 +1050,9 @@ async fn run(
|
||||
frames.clone(),
|
||||
settings.clone(),
|
||||
engine.clone(),
|
||||
link.clone(),
|
||||
myts_identity.subscribe(),
|
||||
myts_data.subscribe(),
|
||||
);
|
||||
if let Some(profiles) = &srtp_profiles {
|
||||
s.send(Command::SetSrtpProfiles(profiles.clone()));
|
||||
@@ -1020,6 +1124,7 @@ fn command_session(command: &Command) -> SessionId {
|
||||
| Command::CreateDirectory { session, .. }
|
||||
| Command::SetAvatar { session, .. }
|
||||
| Command::FetchAvatar { session, .. }
|
||||
| Command::FetchPicture { session, .. }
|
||||
| Command::ListOfflineMessages { session, .. }
|
||||
| Command::GetOfflineMessage { session, .. }
|
||||
| Command::SendOfflineMessage { session, .. }
|
||||
@@ -1027,6 +1132,7 @@ fn command_session(command: &Command) -> SessionId {
|
||||
| Command::SetOfflineMessageRead { session, .. }
|
||||
| Command::CloseSession { session } => *session,
|
||||
Command::SetMytsIdentity(_)
|
||||
| Command::SetMytsData(_)
|
||||
| Command::SetAudioSettings(_)
|
||||
| Command::SetSrtpProfiles(_)
|
||||
| Command::TestMicrophone { .. }
|
||||
@@ -1044,10 +1150,27 @@ fn command_session(command: &Command) -> SessionId {
|
||||
|
||||
/// The app has one rustls crypto provider. With two (aws-lc-rs and ring), a
|
||||
/// TLS client built without an explicit provider panics: `wss://` gateways
|
||||
/// did. This test's build has the app's TLS dependencies (reqwest here,
|
||||
/// tonic through the voelin-myts dev-dependency).
|
||||
/// did. This test's build has the app's TLS dependencies (reqwest).
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn one_rustls_crypto_provider() {
|
||||
let _ = rustls::ClientConfig::builder();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::BackendInfo;
|
||||
|
||||
#[test]
|
||||
fn a_backend_reads_as_its_product_and_version() {
|
||||
let backend = |product: &str, version: &str| BackendInfo {
|
||||
product: product.into(),
|
||||
version: version.into(),
|
||||
};
|
||||
assert_eq!(backend("TeamSpeak 6", "6.0.0-beta13.1").label(), "TeamSpeak 6 6.0.0-beta13.1");
|
||||
assert_eq!(backend("TeamSpeak 3", "").label(), "TeamSpeak 3");
|
||||
// Not recognised: the version string alone, or nothing.
|
||||
assert_eq!(backend("", "custom 9").label(), "custom 9");
|
||||
assert_eq!(BackendInfo::default().label(), "");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
//! The seam between a session and the server it talks to as a client.
|
||||
//!
|
||||
//! A session merges up to three sources (voice, gateway, query). The *voice*
|
||||
//! source is the connection that is visible on the server, can talk and
|
||||
//! carries chat, files, pokes, offline messages and streams. Everything the
|
||||
//! session needs from it goes through [`ServerLink`]: the session hands the
|
||||
//! link the connection's options and a [`LinkCtx`], and talks to it with two
|
||||
//! channels, [`LinkCmd`]s in and [`LinkEvent`]s out. Nothing else of the
|
||||
//! backend shows: the session merges, deduplicates, stores and routes what a
|
||||
//! link reports, whichever server software is behind it.
|
||||
//!
|
||||
//! # Contract for a link
|
||||
//!
|
||||
//! - [`ServerLink::spawn`] returns at once; the connection runs on its own
|
||||
//! task and reports through `events`. Connecting is not an event: the
|
||||
//! session shows `Connecting` from the moment it spawned the link, until
|
||||
//! [`LinkEvent::Connected`] (or [`LinkEvent::Disconnected`] if it failed).
|
||||
//! - The first thing a connected link reports is [`LinkEvent::Connected`]
|
||||
//! (name, backend, what it can do, our client id, the server's unique id),
|
||||
//! then [`LinkEvent::Presence`] whenever anything in the server's tree or
|
||||
//! client list changed (a full snapshot each time) and
|
||||
//! [`LinkEvent::OwnChannel`] when we moved.
|
||||
//! - [`LinkEvent::Disconnected`], with the reason if it was not asked for,
|
||||
//! reports that the connection ended, whichever way it did; a link sends it
|
||||
//! once, and nothing from the connection itself follows it. A link that
|
||||
//! gets [`LinkCmd::Disconnect`] (or whose command channel closes) leaves.
|
||||
//! It is not promised to be the last event of the link: the stream task of
|
||||
//! a connection with streams is a task of its own, which winds down after
|
||||
//! the connection, so [`LinkEvent::OwnStream`] (`Ended`) and
|
||||
//! [`LinkEvent::StreamAudioEnded`] from it, and the bus events of its
|
||||
//! streams, may follow `Disconnected` (`TsLink` ends the stream task as the
|
||||
//! connection's loop ends, which usually, not always, puts them before it).
|
||||
//! The session does not depend on the order: it ends our own stream and
|
||||
//! the audio of watched streams itself when it hears `Disconnected`, and
|
||||
//! ignores what a link says after that, like the events of a replaced one.
|
||||
//! - Streams (screen sharing) are the link's business from the capabilities
|
||||
//! on: when [`Capabilities::streams`] is set in `Connected`, it runs the
|
||||
//! stream task, takes [`LinkCmd::Stream`] and reports through the event
|
||||
//! bus ([`LinkCtx::emit`]) like the other answers that need not pass the
|
||||
//! session first (file lists, transfers, offline messages, stream state).
|
||||
//! What the session must place itself comes as events: our own stream's
|
||||
//! life ([`LinkEvent::OwnStream`], for the gateway directory) and the audio
|
||||
//! of watched streams ([`LinkEvent::StreamAudio`], for the audio thread,
|
||||
//! and [`LinkEvent::StreamAudioEnded`] when a stream's audio is over).
|
||||
//! When the session replaces a connection it gives the old link
|
||||
//! `StreamCmd::Shutdown` before [`LinkCmd::Disconnect`] (the streams hear
|
||||
//! of their end before the link stops reading commands).
|
||||
//! - What the session must see first (chat, pokes, who is talking, audio)
|
||||
//! comes as [`LinkEvent`]s; the answers to requests the UI made (a file
|
||||
//! list, a request's `Done`) go straight to the event bus with
|
||||
//! [`LinkCtx::emit`].
|
||||
//! - Events of a link the session replaced are ignored (each link has a
|
||||
//! generation), so a link need not stop emitting at once.
|
||||
//!
|
||||
//! # Implementations
|
||||
//!
|
||||
//! [`TsLink`](crate::TsLink) (`ts_link.rs`, with `voice.rs`) is the
|
||||
//! TeamSpeak 3 and 6 connection of `tsclientlib`; it is the only one for now,
|
||||
//! and [`Engine::start_with_link`](crate::Engine::start_with_link) takes
|
||||
//! another (the tests drive the session with an in-memory one,
|
||||
//! `tests/link_fake.rs`). The decoupling plan moves `TsLink` out of this
|
||||
//! crate into the TeamSpeak gateway (VoelinGateWay, `voelin-gateway-ts`), and
|
||||
//! the Voelin protocol's QUIC transport becomes the other implementation,
|
||||
//! both behind the backend-neutral `voelin_proto::link::Session` of
|
||||
//! VoelinProtocol; `ServerLink` is this crate's side of that seam until then.
|
||||
//!
|
||||
//! # What is still TeamSpeak's
|
||||
//!
|
||||
//! The seam is not backend-neutral yet. What still has TeamSpeak types or
|
||||
//! TeamSpeak's shape, and changes when `TsLink` leaves:
|
||||
//!
|
||||
//! - Types of the TeamSpeak crates: [`ConnectOptions::identity`] and
|
||||
//! [`ConnectOptions::client_version`] (`tsclientlib`), and the account
|
||||
//! proof in [`LinkCtx`] (`myts_identity` of `tsproto`, `myts_data` of
|
||||
//! `tsclientlib`).
|
||||
//! - Client ids are TeamSpeak's `u16`: `own_client` of
|
||||
//! [`LinkEvent::Connected`], `from` of [`LinkEvent::Poke`], `client` of
|
||||
//! [`LinkEvent::Talking`] and of [`LinkCmd::Poke`], the `author_id` of a
|
||||
//! [`ChatMessage`], and the viewer and streamer ids of the stream API.
|
||||
//! - [`LinkEvent::Presence`] snapshots have TeamSpeak's shape: `u16` client
|
||||
//! ids, `u64` channel and group ids, server and channel groups, talk
|
||||
//! power, icons, badges and the myTeamSpeak avatar.
|
||||
//! - The stream vocabulary is that of `voelin-stream`, the TeamSpeak 6 stream
|
||||
//! protocol: `PeerConfig` in [`ConnectOptions::stream_peer`], `MediaFrame`
|
||||
//! in the frames of watched streams ([`LinkCtx`]), `VideoFormat` in
|
||||
//! `StreamCmd::VideoFrame`, and `VideoCodec` and `FrameSource` of the same
|
||||
//! API (re-exported from [`crate::stream`]).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::{broadcast, mpsc, watch};
|
||||
use voelin_audio::{EncodedVoice, VoicePacket};
|
||||
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence};
|
||||
use voelin_stream::PeerConfig;
|
||||
|
||||
use crate::files::{Report, RequestId, Sink, TransferId};
|
||||
use crate::settings::SharedSettings;
|
||||
use crate::stream::{OwnStreamEvent, StreamCmd, StreamFrame};
|
||||
use crate::{BackendInfo, Event, SessionId};
|
||||
|
||||
/// Starts the voice connection of a session.
|
||||
///
|
||||
/// One link serves every session of an engine; [`spawn`](Self::spawn) starts
|
||||
/// one connection.
|
||||
pub trait ServerLink: Send + Sync + 'static {
|
||||
/// Connect to the server `options` names and run the connection on its
|
||||
/// own task: take commands from `cmds`, report through `events`, and end
|
||||
/// the connection with [`LinkEvent::Disconnected`]. Does not block.
|
||||
fn spawn(
|
||||
&self,
|
||||
options: ConnectOptions,
|
||||
ctx: LinkCtx,
|
||||
cmds: mpsc::UnboundedReceiver<LinkCmd>,
|
||||
events: mpsc::UnboundedSender<LinkEvent>,
|
||||
);
|
||||
}
|
||||
|
||||
/// What a connection needs to know: the server, who to be, where to join.
|
||||
/// ([`VoiceOptions`](crate::VoiceOptions) is the name the app uses for it.)
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ConnectOptions {
|
||||
pub address: String,
|
||||
pub nickname: String,
|
||||
/// The identity to connect with (TeamSpeak's, for now).
|
||||
pub identity: Option<tsclientlib::Identity>,
|
||||
/// Signed compatibility version; `None` selects the native platform's tuple.
|
||||
pub client_version: Option<tsclientlib::Version>,
|
||||
pub server_password: Option<String>,
|
||||
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
|
||||
pub channel: Option<String>,
|
||||
/// The password of `channel`.
|
||||
pub channel_password: Option<String>,
|
||||
/// A privilege key to use when connecting.
|
||||
pub token: Option<String>,
|
||||
/// Open the audio devices (capture and playback).
|
||||
pub audio: bool,
|
||||
/// Network settings for stream peer connections (TeamSpeak 6).
|
||||
pub stream_peer: PeerConfig,
|
||||
}
|
||||
|
||||
impl ConnectOptions {
|
||||
pub fn new(address: impl Into<String>, nickname: impl Into<String>) -> Self {
|
||||
Self {
|
||||
address: address.into(),
|
||||
nickname: nickname.into(),
|
||||
identity: None,
|
||||
client_version: None,
|
||||
server_password: None,
|
||||
channel: None,
|
||||
channel_password: None,
|
||||
token: None,
|
||||
audio: false,
|
||||
stream_peer: PeerConfig::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the engine gives a link besides the options: where the connection
|
||||
/// answers the requests the session need not see, and what it shares with
|
||||
/// the session's other parts.
|
||||
#[derive(Clone)]
|
||||
pub struct LinkCtx {
|
||||
pub(crate) session: SessionId,
|
||||
pub(crate) events: broadcast::Sender<Event>,
|
||||
/// The frames of watched streams (kept off the event bus).
|
||||
pub(crate) frames: broadcast::Sender<StreamFrame>,
|
||||
pub(crate) settings: SharedSettings,
|
||||
/// The main account's proof, for every connection ([`crate::Command::SetMytsIdentity`]).
|
||||
pub(crate) myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
/// What the server is shown of the account ([`crate::Command::SetMytsData`]).
|
||||
pub(crate) myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
}
|
||||
|
||||
impl LinkCtx {
|
||||
/// The session this connection belongs to.
|
||||
pub fn session(&self) -> SessionId {
|
||||
self.session
|
||||
}
|
||||
|
||||
/// Tell the engine's event bus something (a request's answer, a
|
||||
/// transfer's progress).
|
||||
pub fn emit(&self, event: Event) {
|
||||
let _ = self.events.send(event);
|
||||
}
|
||||
|
||||
pub(crate) fn done(&self, request: RequestId, result: Result<(), String>) {
|
||||
self.emit(Event::RequestDone { session: self.session, request, result });
|
||||
}
|
||||
}
|
||||
|
||||
/// A file on the server: channel, its password, path.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Remote {
|
||||
pub channel: ChannelId,
|
||||
pub password: Option<String>,
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// What the session asks of a connection.
|
||||
pub enum LinkCmd {
|
||||
SendChat(ChatTarget, String),
|
||||
Move(ChannelId, Option<String>),
|
||||
SetInputMuted(bool),
|
||||
SetOutputMuted(bool),
|
||||
/// An encoded voice frame from the audio thread.
|
||||
Audio(EncodedVoice),
|
||||
/// A stream command; the link answers on the event bus. Only sent while
|
||||
/// the connection's capabilities include streams.
|
||||
Stream(StreamCmd),
|
||||
Poke {
|
||||
client: u16,
|
||||
message: String,
|
||||
},
|
||||
ListFiles {
|
||||
request: RequestId,
|
||||
dir: Remote,
|
||||
},
|
||||
/// Download `file`; `transfer` if the user can cancel it.
|
||||
Download {
|
||||
transfer: Option<TransferId>,
|
||||
file: Remote,
|
||||
sink: Sink,
|
||||
report: Report,
|
||||
},
|
||||
Upload {
|
||||
transfer: Option<TransferId>,
|
||||
file: Remote,
|
||||
from: PathBuf,
|
||||
overwrite: bool,
|
||||
resume: bool,
|
||||
report: Report,
|
||||
},
|
||||
CancelTransfer(TransferId),
|
||||
DeleteFiles {
|
||||
/// `None`: best effort, nobody waits for the answer.
|
||||
request: Option<RequestId>,
|
||||
channel: ChannelId,
|
||||
password: Option<String>,
|
||||
paths: Vec<String>,
|
||||
},
|
||||
RenameFile {
|
||||
request: RequestId,
|
||||
from: Remote,
|
||||
to: Remote,
|
||||
},
|
||||
CreateDirectory {
|
||||
request: RequestId,
|
||||
dir: Remote,
|
||||
},
|
||||
/// Announce our avatar's hash (empty: no avatar).
|
||||
SetAvatarHash {
|
||||
request: Option<RequestId>,
|
||||
hash: String,
|
||||
},
|
||||
OfflineList {
|
||||
request: RequestId,
|
||||
},
|
||||
OfflineGet {
|
||||
request: RequestId,
|
||||
id: u32,
|
||||
},
|
||||
OfflineAdd {
|
||||
request: RequestId,
|
||||
to_uid: String,
|
||||
subject: String,
|
||||
text: String,
|
||||
},
|
||||
OfflineDelete {
|
||||
request: RequestId,
|
||||
id: u32,
|
||||
},
|
||||
OfflineFlag {
|
||||
request: RequestId,
|
||||
id: u32,
|
||||
read: bool,
|
||||
},
|
||||
Disconnect,
|
||||
}
|
||||
|
||||
/// What a connection tells the session.
|
||||
pub enum LinkEvent {
|
||||
Connected {
|
||||
name: String,
|
||||
/// The server software, and what it can do (the connection knows
|
||||
/// both from the server's version).
|
||||
backend: BackendInfo,
|
||||
capabilities: Capabilities,
|
||||
own_client: u16,
|
||||
/// The server's unique id.
|
||||
server_uid: String,
|
||||
/// Our unique id as the server knows it.
|
||||
own_uid: Option<String>,
|
||||
},
|
||||
/// The server's channels and clients as they are now.
|
||||
Presence(Box<Presence>),
|
||||
OwnChannel(ChannelId),
|
||||
Chat(ChatMessage),
|
||||
Poke {
|
||||
from: u16,
|
||||
from_uid: Option<String>,
|
||||
from_name: String,
|
||||
message: String,
|
||||
},
|
||||
/// Incoming voice for the audio thread.
|
||||
Audio(VoicePacket),
|
||||
/// Who is talking (on, and off again when it stopped).
|
||||
Talking {
|
||||
client: u16,
|
||||
talking: bool,
|
||||
},
|
||||
/// Our own stream's life, for the gateway directory.
|
||||
OwnStream(OwnStreamEvent),
|
||||
/// An Opus frame (48 kHz) of a watched stream, for the audio thread
|
||||
/// ([`ConnectOptions::audio`]); `time` is its RTP time on the 48 kHz
|
||||
/// clock.
|
||||
StreamAudio {
|
||||
stream: String,
|
||||
time: u64,
|
||||
data: Arc<[u8]>,
|
||||
},
|
||||
/// A watched stream ended: its audio leaves the mixer.
|
||||
StreamAudioEnded(String),
|
||||
/// A command failed (the connection stays).
|
||||
Error(String),
|
||||
/// The connection ended; the reason if it was not asked for. Sent once;
|
||||
/// the stream task's closing reports may still follow (see the module
|
||||
/// documentation).
|
||||
Disconnected(Option<String>),
|
||||
}
|
||||
@@ -56,16 +56,16 @@ use voelin_media::mix::{
|
||||
};
|
||||
pub use voelin_media::mix::{Level, SourceState};
|
||||
use voelin_media::scale::Pyramid;
|
||||
use voelin_media::stream::EncodedFrame;
|
||||
use voelin_media::studio::Studio;
|
||||
use voelin_media::studio::output::{Packet, Track};
|
||||
use voelin_media::{
|
||||
Codec, Codecs, ContentHint, EncodedChunk, EncoderConfig, FrameRef, GpuFrame, H264Profile,
|
||||
VideoEncoder, VideoFrame,
|
||||
LayerId, LayerSet, LayerSpec, VideoEncoder, VideoFrame,
|
||||
};
|
||||
pub use voelin_media::{DecoderBackend, DecoderPreference, EncoderBackend, EncoderPreference};
|
||||
use voelin_stream::{
|
||||
EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind,
|
||||
MediaTime, PeerConfig, VideoCodec, VideoFormat,
|
||||
FrameSource, Frequency, MediaFrame, MediaKind, MediaTime, PeerConfig, VideoCodec, VideoFormat,
|
||||
};
|
||||
|
||||
use crate::settings::{AudioSourceKindSetting, AudioSourceSetting};
|
||||
@@ -127,13 +127,7 @@ fn spawn(name: &str, f: impl FnOnce() + Send + 'static) -> Result<JoinHandle<()>
|
||||
|
||||
/// The `voelin_media` codec of a negotiated video codec.
|
||||
pub fn media_codec(codec: VideoCodec) -> Codec {
|
||||
match codec {
|
||||
VideoCodec::Vp8 => Codec::Vp8,
|
||||
VideoCodec::Vp9 => Codec::Vp9,
|
||||
VideoCodec::H264 => Codec::H264,
|
||||
VideoCodec::Av1 => Codec::Av1,
|
||||
VideoCodec::H265 => Codec::H265,
|
||||
}
|
||||
crate::stream::media_codec(codec)
|
||||
}
|
||||
|
||||
/// The H.264 profile an encoder of `format` makes (Constrained High for
|
||||
|
||||
+930
-201
File diff suppressed because it is too large.
Load diff
@@ -50,8 +50,8 @@ use serde_json::{Value, json};
|
||||
use tokio::sync::{broadcast, watch};
|
||||
use tracing::{debug, warn};
|
||||
use voelin_audio::AudioSettings;
|
||||
use voelin_media::{LayerId, LayerSpec};
|
||||
use voelin_store::Store;
|
||||
use voelin_stream::{LayerId, LayerSpec};
|
||||
|
||||
/// A value of any key, typed (`Arc<T>` of the key's `T`).
|
||||
type Stored = Arc<dyn Any + Send + Sync>;
|
||||
@@ -1121,15 +1121,16 @@ pub static CHAT_RETENTION_DAYS: Key<u32> = Key::new(
|
||||
pub static CACHE_MAX_MB: Key<u64> = Key::new(
|
||||
"cache.max_mb",
|
||||
Kind::UInt { min: 0 },
|
||||
"Size of the avatar and icon cache in MiB (0: no limit).",
|
||||
|| 256,
|
||||
"Size of the picture cache (avatars, icons, banners) in MiB (0: no limit).",
|
||||
|| 1024,
|
||||
);
|
||||
|
||||
/// Download the avatars, icons and banners of servers we are on.
|
||||
/// Download the avatars, icons, banners and badges of servers we are on,
|
||||
/// and the pictures their chats show (`[img]`).
|
||||
pub static CACHE_FETCH_IMAGES: Key<bool> = Key::new(
|
||||
"cache.fetch_images",
|
||||
Kind::Bool,
|
||||
"Download avatars, icons and banners of the servers we are on.",
|
||||
"Download avatars, icons, banners and badges of the servers we are on, and pictures in chat.",
|
||||
|| true,
|
||||
);
|
||||
|
||||
|
||||
+500
-155
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,155 @@
|
||||
//! The stream types of the engine's API, owned by the core: what the UI is
|
||||
//! told about streams ([`StreamInfo`], [`ViewerInfo`], why a stream
|
||||
//! [ended](EndReason)) and what it asks for ([`StreamSetup`]).
|
||||
//!
|
||||
//! They carry plain fields only: client ids are `u16`, an SRTP profile is its
|
||||
//! name, a video codec is `voelin_media`'s. What a server link speaks (the
|
||||
//! TeamSpeak 6 stream crate today) is converted to and from them at the
|
||||
//! boundary in [`crate::stream`], so the UI does not depend on the link's
|
||||
//! types. The frame and simulcast layer types (`EncodedFrame`, `LayerSpec`,
|
||||
//! `LayerId`) are `voelin-media`'s.
|
||||
|
||||
use voelin_media::{Codec, LayerId};
|
||||
|
||||
/// What a stream shows.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum StreamKind {
|
||||
Camera,
|
||||
Screen,
|
||||
Window,
|
||||
/// A kind this client does not know, by its number on the server.
|
||||
Other(u8),
|
||||
}
|
||||
|
||||
impl StreamKind {
|
||||
/// From the number servers use: 2 camera, 3 screen, 4 window.
|
||||
pub fn from_u8(v: u8) -> Self {
|
||||
match v {
|
||||
2 => Self::Camera,
|
||||
3 => Self::Screen,
|
||||
4 => Self::Window,
|
||||
v => Self::Other(v),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`from_u8`](Self::from_u8) back.
|
||||
pub fn to_u8(self) -> u8 {
|
||||
match self {
|
||||
Self::Camera => 2,
|
||||
Self::Screen => 3,
|
||||
Self::Window => 4,
|
||||
Self::Other(v) => v,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What we announce when we start a stream ([`crate::Command::StartStream`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StreamSetup {
|
||||
pub name: String,
|
||||
pub kind: StreamKind,
|
||||
/// The stream's video bitrate in kbit/s (the single layer's without
|
||||
/// simulcast). TeamSpeak 6 servers keep it in 16 bits, so it is
|
||||
/// announced as at most 65535; the stream sends its real rate whatever
|
||||
/// the announcement says.
|
||||
pub bitrate: u32,
|
||||
/// `accessibility`: the official client sends 1.
|
||||
pub accessibility: u8,
|
||||
/// `mode`: 1 (none) is what clients send today; 2 is P2P, 3 SFU.
|
||||
pub mode: u8,
|
||||
/// 0 = unlimited.
|
||||
pub viewer_limit: u32,
|
||||
pub audio: bool,
|
||||
}
|
||||
|
||||
impl Default for StreamSetup {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
name: String::new(),
|
||||
kind: StreamKind::Screen,
|
||||
bitrate: 4608,
|
||||
accessibility: 1,
|
||||
mode: 1,
|
||||
viewer_limit: 0,
|
||||
audio: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A stream on the server ([`crate::Event::StreamsChanged`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StreamInfo {
|
||||
pub id: String,
|
||||
/// The client id of the streamer.
|
||||
pub streamer: u16,
|
||||
pub name: String,
|
||||
pub kind: StreamKind,
|
||||
pub bitrate: u32,
|
||||
pub viewer_limit: u32,
|
||||
pub audio: bool,
|
||||
/// How many watch it; `None` where nothing told (e.g. a gateway's
|
||||
/// directory entry).
|
||||
pub viewers: Option<u32>,
|
||||
}
|
||||
|
||||
/// A viewer of our stream, as we see it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ViewerState {
|
||||
/// Asked to watch, waiting for our decision.
|
||||
Requested,
|
||||
/// Offer sent; waiting for the answer and the connection.
|
||||
Connecting,
|
||||
Connected,
|
||||
}
|
||||
|
||||
/// A viewer of our stream ([`crate::Event::StreamViewers`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ViewerInfo {
|
||||
/// The client id of the viewer.
|
||||
pub client: u16,
|
||||
pub state: ViewerState,
|
||||
/// The message of the join request.
|
||||
pub message: String,
|
||||
/// The simulcast layer the viewer receives (it moves at a keyframe of the
|
||||
/// new layer); `None` before we offered, and with RID simulcast (all
|
||||
/// layers).
|
||||
pub layer: Option<LayerId>,
|
||||
/// The latest bandwidth estimate of the connection (bit/s).
|
||||
pub estimate: Option<u64>,
|
||||
/// The SRTP profile of the connection by its name (as in RFC 5764 and
|
||||
/// WebRTC statistics, e.g. `AEAD_AES_128_GCM`), once the key exchange is
|
||||
/// done.
|
||||
pub srtp_profile: Option<String>,
|
||||
/// The video codec the viewer's answer chose (it gets video in that
|
||||
/// codec).
|
||||
pub codec: Option<Codec>,
|
||||
}
|
||||
|
||||
/// Why a viewer left a stream.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LeaveReason {
|
||||
None,
|
||||
Left,
|
||||
Denied,
|
||||
Failed,
|
||||
Kicked,
|
||||
Banned,
|
||||
/// A reason this client does not know, by its number on the server.
|
||||
Other(u8),
|
||||
}
|
||||
|
||||
/// Why a stream ended for us ([`crate::StreamState::Ended`],
|
||||
/// [`crate::WatchState::Ended`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum EndReason {
|
||||
/// We stopped streaming or watching.
|
||||
Local,
|
||||
/// The streamer denied our join request.
|
||||
Denied,
|
||||
/// The stream was stopped (or its streamer disconnected).
|
||||
Stopped,
|
||||
/// The streamer or the server ended our viewing session.
|
||||
Removed(Option<LeaveReason>),
|
||||
/// A command failed or no connection could be established.
|
||||
Failed(String),
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
//! [`TsLink`]: the TeamSpeak implementation of [`ServerLink`].
|
||||
//!
|
||||
//! It connects as a normal TeamSpeak 3 or 6 client with `tsclientlib` and
|
||||
//! runs the connection ([`crate::voice`]) with everything that rides on it:
|
||||
//! chat, voice, files, pokes, offline messages and, on TeamSpeak 6, the
|
||||
//! stream task. Which product the server is (and what it can do) is decided
|
||||
//! there, from the version it sends, and reported in
|
||||
//! [`LinkEvent::Connected`](crate::link::LinkEvent::Connected).
|
||||
//!
|
||||
//! Everything it uses (`voice.rs`, `book.rs`, `stream.rs`, `versions.rs`,
|
||||
//! `identity.rs`) is TeamSpeak's and leaves this crate together with it:
|
||||
//! the plan moves `TsLink` into the TeamSpeak gateway, `voelin-gateway-ts`
|
||||
//! of VoelinGateWay.
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, ServerLink};
|
||||
use crate::voice;
|
||||
|
||||
/// Connects to TeamSpeak 3 and 6 servers. The engine's default link.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct TsLink;
|
||||
|
||||
impl ServerLink for TsLink {
|
||||
fn spawn(
|
||||
&self,
|
||||
options: ConnectOptions,
|
||||
ctx: LinkCtx,
|
||||
cmds: mpsc::UnboundedReceiver<LinkCmd>,
|
||||
events: mpsc::UnboundedSender<LinkEvent>,
|
||||
) {
|
||||
tokio::spawn(voice::run(options, ctx, cmds, events));
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,8 @@ const VERSIONS_CSV: &str = include_str!("../../proto/tsproto-structs/declaration
|
||||
|
||||
/// The signed generic version of every platform, tsclientlib's default.
|
||||
const GENERIC_VERSION: &str = "3.?.? [Build: 5680278000]";
|
||||
/// The client generation claimed where a signed build of it exists.
|
||||
const CLIENT_GENERATION: &str = "6.";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct KnownVersion {
|
||||
@@ -52,12 +54,17 @@ pub fn known_versions() -> Vec<KnownVersion> {
|
||||
|
||||
/// Resolve a `--client-version` argument.
|
||||
///
|
||||
/// Accepts `default` (the core native-platform default), an index into [`known_versions`],
|
||||
/// or `<platform>@<version>` with the exact strings from `voelinctl versions`.
|
||||
/// Accepts `default` (the core native-platform default), `generic` (the
|
||||
/// generic `3.?.?` version of the native platform, as before 6.x builds were
|
||||
/// claimed), an index into [`known_versions`], or `<platform>@<version>` with
|
||||
/// the exact strings from `voelinctl versions`.
|
||||
pub fn resolve(spec: &str) -> Result<Option<Version>> {
|
||||
if spec == "default" {
|
||||
return Ok(None);
|
||||
}
|
||||
if spec == "generic" {
|
||||
return generic_version(std::env::consts::OS).map(Some);
|
||||
}
|
||||
let versions = known_versions();
|
||||
if let Ok(i) = spec.parse::<usize>() {
|
||||
let Some(v) = versions.get(i) else {
|
||||
@@ -74,10 +81,13 @@ pub fn resolve(spec: &str) -> Result<Option<Version>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The signed compatibility tuple for the native operating system.
|
||||
/// The signed compatibility tuple for the native operating system: the
|
||||
/// newest TeamSpeak 6 client build signed for it, so servers and other
|
||||
/// clients see a 6.x client (its build is recent enough for any server's
|
||||
/// minimum client version); where none is signed for the platform, the
|
||||
/// generic version, whose build passes every minimum.
|
||||
///
|
||||
/// The generic version retains the library's minimum-version compatibility.
|
||||
/// Its version, platform and signature must stay together: the signature does
|
||||
/// Version, platform and signature must stay together: the signature does
|
||||
/// not authorize renaming the client or changing its platform.
|
||||
///
|
||||
/// Unsupported operating systems return an error rather than claiming another
|
||||
@@ -87,6 +97,31 @@ pub fn native_version() -> Result<Version> {
|
||||
}
|
||||
|
||||
fn compatibility_version(os: &str) -> Result<Version> {
|
||||
// TeamSpeak 5 and 6 call macOS "macOS", TeamSpeak 3 "OS X".
|
||||
let platforms: &[&str] = match os {
|
||||
"linux" => &["Linux"],
|
||||
"windows" => &["Windows"],
|
||||
"macos" => &["macOS", "OS X"],
|
||||
"android" => &["Android"],
|
||||
"ios" => &["iOS"],
|
||||
_ => bail!("no signed compatibility version for operating system {os:?}"),
|
||||
};
|
||||
let versions = known_versions();
|
||||
let newest = versions
|
||||
.iter()
|
||||
.filter(|v| platforms.contains(&v.platform.as_str()))
|
||||
.filter(|v| v.version.starts_with(CLIENT_GENERATION))
|
||||
.filter_map(|v| Some((build(&v.version)?, v)))
|
||||
.max_by_key(|(build, _)| *build)
|
||||
.map(|(_, v)| v);
|
||||
match newest {
|
||||
Some(version) => version.to_version(),
|
||||
None => generic_version(os),
|
||||
}
|
||||
}
|
||||
|
||||
/// The generic version of the operating system's platform.
|
||||
fn generic_version(os: &str) -> Result<Version> {
|
||||
let platform = match os {
|
||||
"linux" => "Linux",
|
||||
"windows" => "Windows",
|
||||
@@ -95,15 +130,18 @@ fn compatibility_version(os: &str) -> Result<Version> {
|
||||
"ios" => "iOS",
|
||||
_ => bail!("no signed compatibility version for operating system {os:?}"),
|
||||
};
|
||||
// The library's generic version: its build passes servers' minimum client
|
||||
// version, which a real (older) build such as 3.6.0 may not.
|
||||
known_versions()
|
||||
.into_iter()
|
||||
.find(|version| version.platform == platform && version.version == GENERIC_VERSION)
|
||||
.find(|v| v.platform == platform && v.version == GENERIC_VERSION)
|
||||
.with_context(|| format!("missing signed compatibility version for {platform}"))?
|
||||
.to_version()
|
||||
}
|
||||
|
||||
/// The build number of a version string (`6.0.0 [Build: 1737468425]`).
|
||||
fn build(version: &str) -> Option<u64> {
|
||||
version.split_once("[Build: ")?.1.strip_suffix(']')?.parse().ok()
|
||||
}
|
||||
|
||||
/// Truthful product identity, separate from the signed compatibility tuple.
|
||||
pub fn client_metadata() -> String {
|
||||
serde_json::json!({
|
||||
@@ -121,16 +159,19 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn native_platform_preserves_complete_signed_tuple() {
|
||||
for (os, platform) in [
|
||||
("linux", "Linux"),
|
||||
("windows", "Windows"),
|
||||
("macos", "OS X"),
|
||||
("android", "Android"),
|
||||
("ios", "iOS"),
|
||||
for (os, platform, version) in [
|
||||
// The newest TeamSpeak 6 build signed for the platform.
|
||||
("linux", "Linux", "6.0.0-beta4.1 [Build: 1779880475]"),
|
||||
("windows", "Windows", "6.0.0-beta2 [Build: 1737468425]"),
|
||||
// None signed: the generic version.
|
||||
("macos", "OS X", GENERIC_VERSION),
|
||||
("android", "Android", GENERIC_VERSION),
|
||||
("ios", "iOS", GENERIC_VERSION),
|
||||
] {
|
||||
let expected = version;
|
||||
let version = compatibility_version(os).unwrap();
|
||||
assert_eq!(version.get_platform(), platform);
|
||||
assert_eq!(version.get_version_string(), "3.?.? [Build: 5680278000]");
|
||||
assert_eq!(version.get_version_string(), expected);
|
||||
assert_eq!(version.get_signature().len(), 64);
|
||||
let known = known_versions()
|
||||
.into_iter()
|
||||
@@ -156,6 +197,14 @@ mod tests {
|
||||
assert_eq!(metadata["platform"], std::env::consts::OS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_build_numbers() {
|
||||
assert_eq!(build("6.0.0-beta2 [Build: 1737468425]"), Some(1_737_468_425));
|
||||
assert_eq!(build(GENERIC_VERSION), Some(5_680_278_000));
|
||||
assert_eq!(build("3.0.0 [Build: x]"), None);
|
||||
assert_eq!(build("6.0.0"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_all_rows() {
|
||||
let versions = known_versions();
|
||||
@@ -169,6 +218,10 @@ mod tests {
|
||||
#[test]
|
||||
fn resolves_specs() {
|
||||
assert!(resolve("default").unwrap().is_none());
|
||||
if let Ok(generic) = generic_version(std::env::consts::OS) {
|
||||
assert_eq!(resolve("generic").unwrap(), Some(generic.clone()));
|
||||
assert_eq!(generic.get_version_string(), GENERIC_VERSION);
|
||||
}
|
||||
let by_index = resolve("0").unwrap().unwrap();
|
||||
let first = &known_versions()[0];
|
||||
let by_name = resolve(&format!("{}@{}", first.platform, first.version)).unwrap().unwrap();
|
||||
|
||||
+868
-268
File diff suppressed because it is too large.
Load diff
+1400
-93
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,7 @@
|
||||
//! Chat history and gateway features through the engine, against a fake
|
||||
//! gateway (a WebSocket server speaking the tsgw protocol from memory).
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet, VecDeque};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -43,6 +43,10 @@ struct State {
|
||||
requests: Vec<String>,
|
||||
/// Close connections at once (the gateway is down).
|
||||
refuse: bool,
|
||||
/// Answers to the next logins, in turn, instead of logging in.
|
||||
login_errors: VecDeque<ErrorCode>,
|
||||
/// Logins asked for.
|
||||
logins: usize,
|
||||
}
|
||||
|
||||
impl State {
|
||||
@@ -127,7 +131,12 @@ struct FakeGateway {
|
||||
|
||||
impl FakeGateway {
|
||||
async fn start() -> Self {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
Self::start_on(0).await
|
||||
}
|
||||
|
||||
/// A gateway at `port` of the loopback address (0: any free port).
|
||||
async fn start_on(port: u16) -> Self {
|
||||
let listener = TcpListener::bind(("127.0.0.1", port)).await.unwrap();
|
||||
let url = format!("ws://{}/v1", listener.local_addr().unwrap());
|
||||
let state: Arc<Mutex<State>> = Arc::default();
|
||||
let st = state.clone();
|
||||
@@ -146,6 +155,10 @@ impl FakeGateway {
|
||||
fn requests(&self) -> Vec<String> {
|
||||
self.state.lock().unwrap().requests.clone()
|
||||
}
|
||||
|
||||
fn logins(&self) -> usize {
|
||||
self.state.lock().unwrap().logins
|
||||
}
|
||||
}
|
||||
|
||||
fn caps() -> Vec<String> {
|
||||
@@ -231,6 +244,10 @@ fn answer(
|
||||
) -> ServerMsg {
|
||||
match msg {
|
||||
ClientMsg::Auth { .. } => {
|
||||
st.logins += 1;
|
||||
if let Some(code) = st.login_errors.pop_front() {
|
||||
return ServerMsg::Error { code, message: "not now".into() };
|
||||
}
|
||||
*logged_in = true;
|
||||
st.sessions.push((push.clone(), open.clone()));
|
||||
ServerMsg::AuthOk {
|
||||
@@ -363,7 +380,8 @@ fn answer(
|
||||
st.topics.push(topic.clone());
|
||||
ServerMsg::Topic { topic }
|
||||
}
|
||||
ClientMsg::SubscribeEvents | ClientMsg::Ping => ServerMsg::Ok,
|
||||
ClientMsg::Ping => ServerMsg::Pong,
|
||||
ClientMsg::SubscribeEvents => ServerMsg::Ok,
|
||||
_ => ServerMsg::Error { code: ErrorCode::UnknownType, message: "not in the fake".into() },
|
||||
}
|
||||
}
|
||||
@@ -429,7 +447,7 @@ fn observe(engine: &Engine, session: u64, gw: &FakeGateway) {
|
||||
let identity = tsclientlib::Identity::create();
|
||||
engine.send(Command::ObserveGateway {
|
||||
session,
|
||||
url: gw.url.clone(),
|
||||
urls: vec![gw.url.clone()],
|
||||
identity: Box::new(identity),
|
||||
});
|
||||
}
|
||||
@@ -545,7 +563,9 @@ async fn live_messages_and_gateway_requests() {
|
||||
};
|
||||
assert_eq!((server_uid.as_str(), uid.as_str()), ("fake-server", ME));
|
||||
assert!(capabilities.iter().any(|c| c == feature::PINS));
|
||||
// In sync (the chat is empty).
|
||||
// In sync (the chat is empty): the latest page, then what changed since
|
||||
// (else our message may come back with the sync instead of live).
|
||||
batch(&mut rx, HistorySource::Gateway).await;
|
||||
batch(&mut rx, HistorySource::Gateway).await;
|
||||
|
||||
// Our message: stored at once, then merged with the gateway's copy.
|
||||
@@ -707,3 +727,232 @@ async fn store_history_off_keeps_the_database_empty() {
|
||||
drop((engine, history));
|
||||
let _ = std::fs::remove_dir_all(path.parent().unwrap());
|
||||
}
|
||||
|
||||
/// A gateway that is away is tried again by itself and quietly: no error for
|
||||
/// the user, "connecting" meanwhile, then observing once it is there, with
|
||||
/// the open chats opened again.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_unreachable_gateway_is_tried_again_quietly() {
|
||||
// Nothing listens there yet: the connection is refused.
|
||||
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
|
||||
let path = temp_db("retry");
|
||||
let engine = Engine::start_with(Settings::in_memory(), History::open(&path).unwrap());
|
||||
let mut rx = engine.subscribe();
|
||||
engine.send(Command::OpenChat { session: 3, target: LOBBY });
|
||||
engine.send(Command::ObserveGateway {
|
||||
session: 3,
|
||||
urls: vec![format!("ws://127.0.0.1:{port}/v1")],
|
||||
identity: Box::new(tsclientlib::Identity::create()),
|
||||
});
|
||||
// The first attempts fail (the next ones about 1 s, then 2 s later):
|
||||
// still connecting, and the user is told nothing.
|
||||
let mut connecting = false;
|
||||
let quiet = timeout(Duration::from_millis(1500), async {
|
||||
loop {
|
||||
match rx.recv().await {
|
||||
Ok(Event::Error { message, .. }) => panic!("the user was told: {message}"),
|
||||
Ok(Event::State { session: 3, state }) => {
|
||||
// (Off before observing starts.)
|
||||
assert!(!connecting || state.observe != ObserveState::Off, "gave up");
|
||||
connecting |= state.observe == ObserveState::Connecting;
|
||||
}
|
||||
Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
|
||||
Err(e) => panic!("{e}"),
|
||||
}
|
||||
}
|
||||
});
|
||||
assert!(quiet.await.is_err(), "the event stream ended");
|
||||
assert!(connecting, "never started observing");
|
||||
// The gateway comes up: observing, and the open chat is opened again.
|
||||
let gw = FakeGateway::start_on(port).await;
|
||||
wait(&mut rx, "observing", |e| match e {
|
||||
Event::Error { message, .. } => panic!("the user was told: {message}"),
|
||||
Event::State { session: 3, state } if state.observe == ObserveState::Observing => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
timeout(Duration::from_secs(5), async {
|
||||
while !gw.requests().contains(&"open_chat".to_owned()) {
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|_| panic!("the chat was not opened again: {:?}", gw.requests()));
|
||||
drop(engine);
|
||||
let _ = std::fs::remove_dir_all(path.parent().unwrap());
|
||||
}
|
||||
|
||||
/// A reverse proxy without a rule for the gateway's host, as Zoraxy's
|
||||
/// default site answers: 404 to everything.
|
||||
async fn not_found_proxy() -> String {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("ws://{}/v1", listener.local_addr().unwrap());
|
||||
tokio::spawn(async move {
|
||||
while let Ok((mut tcp, _)) = listener.accept().await {
|
||||
tokio::spawn(async move {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let mut request = [0; 4096];
|
||||
let _ = tcp.read(&mut request).await;
|
||||
let _ = tcp
|
||||
.write_all(
|
||||
b"HTTP/1.1 404 Not Found\r\nContent-Type: text/plain; charset=utf-8\r\n\
|
||||
Content-Length: 19\r\n\r\n404 page not found\n",
|
||||
)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
});
|
||||
url
|
||||
}
|
||||
|
||||
/// Every published gateway is tried in turn, without waiting: a TLS proxy
|
||||
/// that answers 404 and a port nothing listens on are passed over, and the
|
||||
/// plain gateway published after them is used, quietly.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_next_published_gateway_is_used_when_one_fails() {
|
||||
let proxy = not_found_proxy().await;
|
||||
let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
|
||||
let gw = FakeGateway::start().await;
|
||||
let path = temp_db("fallback");
|
||||
let engine = Engine::start_with(Settings::in_memory(), History::open(&path).unwrap());
|
||||
let mut rx = engine.subscribe();
|
||||
engine.send(Command::ObserveGateway {
|
||||
session: 4,
|
||||
urls: vec![proxy, format!("ws://127.0.0.1:{closed}/v1"), gw.url.clone()],
|
||||
identity: Box::new(tsclientlib::Identity::create()),
|
||||
});
|
||||
// Within one round: sooner than the shortest wait after a failed round
|
||||
// (1 s, less 30 %).
|
||||
let url = timeout(Duration::from_millis(650), async {
|
||||
loop {
|
||||
match rx.recv().await {
|
||||
Ok(Event::Error { message, .. }) => panic!("the user was told: {message}"),
|
||||
Ok(Event::Gateway { session: 4, update: GatewayUpdate::Connected { url, .. } }) => {
|
||||
return url;
|
||||
}
|
||||
Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
|
||||
Err(e) => panic!("{e}"),
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("the plain gateway was not used within a round");
|
||||
assert_eq!(url, gw.url);
|
||||
wait(&mut rx, "observing", |e| match e {
|
||||
Event::Error { message, .. } => panic!("the user was told: {message}"),
|
||||
Event::State { session: 4, state } if state.observe == ObserveState::Observing => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
drop(engine);
|
||||
let _ = std::fs::remove_dir_all(path.parent().unwrap());
|
||||
}
|
||||
|
||||
/// Events until `until` matches one, within `within`: never an error for
|
||||
/// the user, never observing `session` off once it started.
|
||||
async fn quietly_until(
|
||||
rx: &mut Receiver<Event>,
|
||||
session: u64,
|
||||
within: Duration,
|
||||
what: &str,
|
||||
mut until: impl FnMut(&Event) -> bool,
|
||||
) {
|
||||
let mut started = false;
|
||||
timeout(within, async {
|
||||
loop {
|
||||
let e = match rx.recv().await {
|
||||
Ok(e) => e,
|
||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
|
||||
Err(e) => panic!("{e}"),
|
||||
};
|
||||
if let Event::Error { message, .. } = &e {
|
||||
panic!("the user was told: {message}");
|
||||
}
|
||||
if let Event::State { session: s, state } = &e
|
||||
&& *s == session
|
||||
{
|
||||
// (Off before observing starts.)
|
||||
assert!(!started || state.observe != ObserveState::Off, "gave up");
|
||||
started |= state.observe != ObserveState::Off;
|
||||
}
|
||||
if until(&e) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|_| panic!("timed out waiting for {what}"));
|
||||
}
|
||||
|
||||
fn observing(session: u64) -> impl FnMut(&Event) -> bool {
|
||||
move |e| {
|
||||
matches!(e, Event::State { session: s, state }
|
||||
if *s == session && state.observe == ObserveState::Observing)
|
||||
}
|
||||
}
|
||||
|
||||
/// A gateway that cannot log us in yet (its TeamSpeak server is away; the
|
||||
/// server does not know the identity before voice connected once) is tried
|
||||
/// again, quietly, and observed through once it can.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_login_the_gateway_cannot_do_yet_is_tried_again() {
|
||||
for (session, code) in [(5, ErrorCode::Unavailable), (6, ErrorCode::UnknownIdentity)] {
|
||||
let gw = FakeGateway::start().await;
|
||||
gw.state.lock().unwrap().login_errors.push_back(code);
|
||||
let engine = Engine::start();
|
||||
let mut rx = engine.subscribe();
|
||||
engine.send(Command::ObserveGateway {
|
||||
session,
|
||||
urls: vec![gw.url.clone()],
|
||||
identity: Box::new(tsclientlib::Identity::create()),
|
||||
});
|
||||
// After the first wait: about 1 s.
|
||||
quietly_until(&mut rx, session, Duration::from_secs(3), "observing", observing(session))
|
||||
.await;
|
||||
assert_eq!(gw.logins(), 2, "{code:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A login the gateway refuses (banned, not allowed, a bad signature or
|
||||
/// security level) is not tried again.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_refused_login_ends_observing() {
|
||||
let gw = FakeGateway::start().await;
|
||||
gw.state.lock().unwrap().login_errors.push_back(ErrorCode::Banned);
|
||||
let engine = Engine::start();
|
||||
let mut rx = engine.subscribe();
|
||||
observe(&engine, 8, &gw);
|
||||
wait(&mut rx, "observing off", |e| match e {
|
||||
Event::Error { message, .. } => panic!("the user was told: {message}"),
|
||||
Event::State { session: 8, state } if state.observe == ObserveState::Off => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
tokio::time::sleep(Duration::from_millis(1500)).await;
|
||||
assert_eq!(gw.logins(), 1);
|
||||
}
|
||||
|
||||
/// Selecting the server again while its gateway is still connecting does
|
||||
/// not start it over, and ends the wait for the next attempt.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn asking_again_while_connecting_tries_at_once() {
|
||||
let gw = FakeGateway::start().await;
|
||||
gw.state.lock().unwrap().login_errors.extend([ErrorCode::UnknownIdentity; 3]);
|
||||
let engine = Engine::start();
|
||||
let mut rx = engine.subscribe();
|
||||
let identity = tsclientlib::Identity::create();
|
||||
let ask = || Command::ObserveGateway {
|
||||
session: 9,
|
||||
urls: vec![gw.url.clone()],
|
||||
identity: Box::new(identity.clone()),
|
||||
};
|
||||
engine.send(ask());
|
||||
// Three logins fail (waits of about 1 and 2 s); the next wait is about 5 s.
|
||||
quietly_until(&mut rx, 9, Duration::from_secs(6), "three logins", |_| gw.logins() >= 3).await;
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_eq!(gw.logins(), 3);
|
||||
engine.send(ask());
|
||||
// Sooner than the shortest such wait (3.5 s), without starting over.
|
||||
quietly_until(&mut rx, 9, Duration::from_secs(2), "observing", observing(9)).await;
|
||||
assert_eq!(gw.logins(), 4);
|
||||
}
|
||||
@@ -0,0 +1,570 @@
|
||||
//! The session through an in-memory [`ServerLink`]: a `FakeLink` hands each
|
||||
//! connection the test asks for to the test, which plays the server by
|
||||
//! sending scripted [`LinkEvent`]s and reads the [`LinkCmd`]s the session
|
||||
//! gives. Presence, chat, the dedup of a message that comes twice, history
|
||||
//! and the end of a connection are the session's own behaviour; nothing here
|
||||
//! needs a TeamSpeak server or a TeamSpeak type.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
use voelin_core::history::MessageSource;
|
||||
use voelin_core::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, ServerLink};
|
||||
use voelin_core::settings::Settings;
|
||||
use voelin_core::stream::{StreamCmd, StreamSetup};
|
||||
use voelin_core::{
|
||||
BackendInfo, Command, Engine, Event, History, HistoryMessage, HistorySource, SessionId,
|
||||
SessionState, Source, VoiceOptions, VoiceState,
|
||||
};
|
||||
use voelin_model::{
|
||||
Capabilities, ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence,
|
||||
};
|
||||
|
||||
/// A connection the session asked the link for.
|
||||
struct Conn {
|
||||
options: ConnectOptions,
|
||||
session: SessionId,
|
||||
cmds: mpsc::UnboundedReceiver<LinkCmd>,
|
||||
events: mpsc::UnboundedSender<LinkEvent>,
|
||||
}
|
||||
|
||||
impl Conn {
|
||||
/// Play `script`, the server's side, in order.
|
||||
fn play(&self, script: impl IntoIterator<Item = LinkEvent>) {
|
||||
for event in script {
|
||||
self.events.send(event).expect("the session listens");
|
||||
}
|
||||
}
|
||||
|
||||
/// The next command the session gave.
|
||||
async fn cmd(&mut self) -> LinkCmd {
|
||||
tokio::time::timeout(Duration::from_secs(10), self.cmds.recv())
|
||||
.await
|
||||
.expect("a command in time")
|
||||
.expect("the session keeps the connection")
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands every connection to the test.
|
||||
struct FakeLink {
|
||||
conns: mpsc::UnboundedSender<Conn>,
|
||||
}
|
||||
|
||||
impl FakeLink {
|
||||
fn new() -> (Self, mpsc::UnboundedReceiver<Conn>) {
|
||||
let (conns, rx) = mpsc::unbounded_channel();
|
||||
(Self { conns }, rx)
|
||||
}
|
||||
}
|
||||
|
||||
impl ServerLink for FakeLink {
|
||||
fn spawn(
|
||||
&self,
|
||||
options: ConnectOptions,
|
||||
ctx: LinkCtx,
|
||||
cmds: mpsc::UnboundedReceiver<LinkCmd>,
|
||||
events: mpsc::UnboundedSender<LinkEvent>,
|
||||
) {
|
||||
let conn = Conn { options, session: ctx.session(), cmds, events };
|
||||
let _ = self.conns.send(conn);
|
||||
}
|
||||
}
|
||||
|
||||
const SESSION: SessionId = 1;
|
||||
const SERVER_UID: &str = "fake-server=";
|
||||
const ME: u16 = 7;
|
||||
const ME_UID: &str = "me=";
|
||||
const LOBBY: ChannelId = 1;
|
||||
const GAMES: ChannelId = 2;
|
||||
|
||||
struct Harness {
|
||||
engine: Engine,
|
||||
events: broadcast::Receiver<Event>,
|
||||
conns: mpsc::UnboundedReceiver<Conn>,
|
||||
}
|
||||
|
||||
impl Harness {
|
||||
fn start() -> Self {
|
||||
let (link, conns) = FakeLink::new();
|
||||
let engine =
|
||||
Engine::start_with_link(Settings::in_memory(), History::in_memory(), Arc::new(link));
|
||||
let events = engine.subscribe();
|
||||
Self { engine, events, conns }
|
||||
}
|
||||
|
||||
/// Ask for a voice connection and take it from the link.
|
||||
async fn connect(&mut self) -> Conn {
|
||||
let options = VoiceOptions::new("fake.test:9987", "tester");
|
||||
self.engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) });
|
||||
tokio::time::timeout(Duration::from_secs(10), self.conns.recv())
|
||||
.await
|
||||
.expect("the session spawns the link")
|
||||
.expect("the link lives")
|
||||
}
|
||||
|
||||
/// The next event `f` picks, skipping the others.
|
||||
async fn next<T>(&mut self, mut f: impl FnMut(Event) -> Option<T>) -> T {
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
if let Some(t) = f(self.events.recv().await.expect("engine events")) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("event in time")
|
||||
}
|
||||
|
||||
/// The next state of the session that `ok` accepts.
|
||||
async fn state(&mut self, mut ok: impl FnMut(&SessionState) -> bool) -> SessionState {
|
||||
self.next(|e| match e {
|
||||
Event::State { state, .. } if ok(&state) => Some(state),
|
||||
_ => None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The next live chat message.
|
||||
async fn chat(&mut self) -> ChatMessage {
|
||||
self.next(|e| match e {
|
||||
Event::Chat { message, .. } => Some(message),
|
||||
_ => None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The messages stored for `target`, oldest first.
|
||||
async fn stored(&self, target: ChatTarget) -> Vec<HistoryMessage> {
|
||||
self.engine
|
||||
.history()
|
||||
.page(SERVER_UID, &target, Default::default(), false)
|
||||
.await
|
||||
.expect("the history")
|
||||
}
|
||||
}
|
||||
|
||||
fn now_ms() -> i64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as i64
|
||||
}
|
||||
|
||||
fn capabilities(streams: bool) -> Capabilities {
|
||||
Capabilities { streams, file_transfer: true, ..Default::default() }
|
||||
}
|
||||
|
||||
fn backend() -> BackendInfo {
|
||||
BackendInfo { product: "Fake".into(), version: "1.2".into() }
|
||||
}
|
||||
|
||||
fn connected(streams: bool) -> LinkEvent {
|
||||
LinkEvent::Connected {
|
||||
name: "Fake Server".into(),
|
||||
backend: backend(),
|
||||
capabilities: capabilities(streams),
|
||||
own_client: ME,
|
||||
server_uid: SERVER_UID.into(),
|
||||
own_uid: Some(ME_UID.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn client(id: u16, nickname: &str, channel: ChannelId) -> ClientInfo {
|
||||
ClientInfo {
|
||||
id,
|
||||
uid: Some(format!("{nickname}=")),
|
||||
nickname: nickname.into(),
|
||||
channel,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Two channels, three clients; we are in the second channel.
|
||||
fn presence() -> Presence {
|
||||
let channel = |id, name: &str| ChannelInfo { id, name: name.into(), ..Default::default() };
|
||||
let mut presence = Presence { server_name: "Fake Server".into(), ..Default::default() };
|
||||
presence.channels.insert(LOBBY, channel(LOBBY, "Lobby"));
|
||||
presence.channels.insert(GAMES, channel(GAMES, "Games"));
|
||||
for c in [client(ME, "tester", GAMES), client(8, "alice", GAMES), client(9, "bob", LOBBY)] {
|
||||
presence.clients.insert(c.id, c);
|
||||
}
|
||||
presence
|
||||
}
|
||||
|
||||
fn message(author: &str, text: &str, ts_ms: i64) -> ChatMessage {
|
||||
ChatMessage {
|
||||
target: ChatTarget::Channel(GAMES),
|
||||
author_name: author.into(),
|
||||
author_uid: Some(format!("{author}=")),
|
||||
author_id: None,
|
||||
text: text.into(),
|
||||
ts_ms,
|
||||
via_relay: false,
|
||||
blocked: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Connecting, the server's presence, moving, talking, a failing command
|
||||
/// and the end of the connection, as the session reports them.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn presence_follows_the_link_until_it_disconnects() {
|
||||
let mut h = Harness::start();
|
||||
let conn = h.connect().await;
|
||||
// What the link was given.
|
||||
assert_eq!(
|
||||
(conn.options.address.as_str(), conn.options.nickname.as_str()),
|
||||
("fake.test:9987", "tester")
|
||||
);
|
||||
assert_eq!(conn.session, SESSION);
|
||||
h.state(|s| s.voice == VoiceState::Connecting).await;
|
||||
|
||||
conn.play([
|
||||
connected(false),
|
||||
LinkEvent::Presence(Box::new(presence())),
|
||||
LinkEvent::OwnChannel(GAMES),
|
||||
]);
|
||||
// In the order the session tells them: the server, its presence, our channel.
|
||||
let (name, info, caps) = h
|
||||
.next(|e| match e {
|
||||
Event::ServerInfo { name, backend, capabilities, .. } => {
|
||||
Some((name, backend, capabilities))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!((name.as_str(), info.label().as_str()), ("Fake Server", "Fake 1.2"));
|
||||
assert_eq!(caps, capabilities(false));
|
||||
let shown = h
|
||||
.next(|e| match e {
|
||||
Event::Presence { presence, .. } if !presence.clients.is_empty() => Some(presence),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(*shown, presence());
|
||||
let state = h.state(|s| s.own_channel == Some(GAMES)).await;
|
||||
assert_eq!(state.voice, VoiceState::Connected);
|
||||
assert_eq!(state.own_client, Some(ME));
|
||||
assert_eq!(state.server_uid.as_deref(), Some(SERVER_UID));
|
||||
assert_eq!(state.presence_source, Some(Source::Voice));
|
||||
|
||||
conn.play([
|
||||
LinkEvent::Talking { client: 8, talking: true },
|
||||
LinkEvent::Poke {
|
||||
from: 8,
|
||||
from_uid: Some("alice=".into()),
|
||||
from_name: "alice".into(),
|
||||
message: "wake up".into(),
|
||||
},
|
||||
LinkEvent::Error("move refused".into()),
|
||||
]);
|
||||
h.next(|e| matches!(e, Event::Talking { client: 8, talking: true, .. }).then_some(())).await;
|
||||
let poke = h
|
||||
.next(|e| match e {
|
||||
Event::Poke { from_name, message, blocked, .. } => Some((from_name, message, blocked)),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(poke, ("alice".into(), "wake up".into(), false));
|
||||
let error = h
|
||||
.next(|e| match e {
|
||||
Event::Error { message, .. } => Some(message),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(error, "move refused");
|
||||
|
||||
// The link ends the connection: the session forgets what it showed.
|
||||
conn.play([LinkEvent::Disconnected(Some("server shut down".into()))]);
|
||||
let state = h.state(|s| s.voice == VoiceState::Disconnected).await;
|
||||
assert_eq!((state.own_channel, state.own_client), (None, None));
|
||||
let error = h
|
||||
.next(|e| match e {
|
||||
Event::Error { message, .. } => Some(message),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(error, "voice: server shut down");
|
||||
let state = h.state(|s| s.presence_source.is_none()).await;
|
||||
assert_eq!(state.voice, VoiceState::Disconnected);
|
||||
let shown = h
|
||||
.next(|e| match e {
|
||||
Event::Presence { presence, .. } => Some(presence),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert!(shown.clients.is_empty() && shown.channels.is_empty());
|
||||
}
|
||||
|
||||
/// What the user asks for reaches the link; streams only where the link's
|
||||
/// capabilities say it has them.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn commands_reach_the_link() {
|
||||
let mut h = Harness::start();
|
||||
let mut conn = h.connect().await;
|
||||
conn.play([
|
||||
connected(false),
|
||||
LinkEvent::Presence(Box::new(presence())),
|
||||
LinkEvent::OwnChannel(GAMES),
|
||||
]);
|
||||
h.state(|s| s.own_channel == Some(GAMES)).await;
|
||||
|
||||
let engine = h.engine.clone();
|
||||
engine.send(Command::SendChat {
|
||||
session: SESSION,
|
||||
target: ChatTarget::Channel(GAMES),
|
||||
text: "hello".into(),
|
||||
});
|
||||
let LinkCmd::SendChat(target, text) = conn.cmd().await else { panic!("a chat message") };
|
||||
assert_eq!((target, text.as_str()), (ChatTarget::Channel(GAMES), "hello"));
|
||||
engine.send(Command::MoveToChannel {
|
||||
session: SESSION,
|
||||
channel: LOBBY,
|
||||
password: Some("pw".into()),
|
||||
});
|
||||
let LinkCmd::Move(channel, password) = conn.cmd().await else { panic!("a move") };
|
||||
assert_eq!((channel, password.as_deref()), (LOBBY, Some("pw")));
|
||||
engine.send(Command::SetInputMuted { session: SESSION, muted: true });
|
||||
assert!(matches!(conn.cmd().await, LinkCmd::SetInputMuted(true)));
|
||||
assert!(h.state(|s| s.input_muted).await.input_muted);
|
||||
engine.send(Command::Poke { session: SESSION, client: 8, message: "hi".into() });
|
||||
assert!(matches!(conn.cmd().await, LinkCmd::Poke { client: 8, .. }));
|
||||
engine.send(Command::ListFiles {
|
||||
session: SESSION,
|
||||
request: 5,
|
||||
channel: GAMES,
|
||||
password: None,
|
||||
path: "/docs/".into(),
|
||||
});
|
||||
let LinkCmd::ListFiles { request, dir } = conn.cmd().await else { panic!("a file list") };
|
||||
assert_eq!((request, dir.channel, dir.path.as_str()), (5, GAMES, "/docs/"));
|
||||
|
||||
// No streams in the capabilities: the session refuses them itself.
|
||||
let setup = || StreamSetup { name: "screen".into(), ..Default::default() };
|
||||
engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true });
|
||||
let error = h
|
||||
.next(|e| match e {
|
||||
Event::Error { message, .. } => Some(message),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert!(error.contains("streams"), "{error}");
|
||||
assert!(conn.cmds.try_recv().is_err(), "nothing reached the link");
|
||||
|
||||
// A link with streams: stream commands go to it, and end with the connection.
|
||||
let mut with_streams = {
|
||||
let link_engine = h.engine.clone();
|
||||
link_engine.send(Command::ConnectVoice {
|
||||
session: SESSION,
|
||||
options: Box::new(VoiceOptions::new("fake.test:9987", "tester")),
|
||||
});
|
||||
h.conns.recv().await.expect("the second connection")
|
||||
};
|
||||
// The replaced connection is told to go.
|
||||
assert!(matches!(conn.cmd().await, LinkCmd::Disconnect));
|
||||
with_streams.play([connected(true)]);
|
||||
h.next(|e| match e {
|
||||
Event::ServerInfo { capabilities, .. } if capabilities.streams => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
// A connection with streams is given the (empty) stream directory first.
|
||||
let LinkCmd::Stream(StreamCmd::Directory(directory)) = with_streams.cmd().await else {
|
||||
panic!("the stream directory")
|
||||
};
|
||||
assert!(directory.is_empty());
|
||||
engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true });
|
||||
let LinkCmd::Stream(StreamCmd::Start { setup, auto_accept }) = with_streams.cmd().await else {
|
||||
panic!("a stream start")
|
||||
};
|
||||
assert_eq!((setup.name.as_str(), auto_accept), ("screen", true));
|
||||
engine.send(Command::StopStream { session: SESSION });
|
||||
assert!(matches!(with_streams.cmd().await, LinkCmd::Stream(StreamCmd::Stop)));
|
||||
engine.send(Command::DisconnectVoice { session: SESSION });
|
||||
assert!(matches!(with_streams.cmd().await, LinkCmd::Disconnect));
|
||||
}
|
||||
|
||||
/// A reconnect ends the streams of the connection it replaces through that
|
||||
/// connection, before the connection itself: the old link is given
|
||||
/// `StreamCmd::Shutdown` and only then `Disconnect`. A link that ends its
|
||||
/// connection on `Disconnect` (the TeamSpeak one stops reading commands
|
||||
/// there) relies on this order for the streams to hear of their end.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_reconnect_shuts_the_streams_down_before_the_old_connection() {
|
||||
let mut h = Harness::start();
|
||||
let mut old = h.connect().await;
|
||||
old.play([
|
||||
connected(true),
|
||||
LinkEvent::Presence(Box::new(presence())),
|
||||
LinkEvent::OwnChannel(GAMES),
|
||||
]);
|
||||
h.state(|s| s.own_channel == Some(GAMES)).await;
|
||||
let LinkCmd::Stream(StreamCmd::Directory(directory)) = old.cmd().await else {
|
||||
panic!("the stream directory")
|
||||
};
|
||||
assert!(directory.is_empty());
|
||||
|
||||
// Connecting again replaces the connection.
|
||||
let _new = h.connect().await;
|
||||
let LinkCmd::Stream(StreamCmd::Shutdown(reason)) = old.cmd().await else {
|
||||
panic!("the streams end first")
|
||||
};
|
||||
assert_eq!(reason, "voice reconnecting");
|
||||
assert!(matches!(old.cmd().await, LinkCmd::Disconnect));
|
||||
}
|
||||
|
||||
/// A message we send is stored at once; the server's copy of it merges
|
||||
/// into the same row, and is shown (once).
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_sent_message_and_its_echo_are_one_message() {
|
||||
let mut h = Harness::start();
|
||||
let mut conn = h.connect().await;
|
||||
conn.play([
|
||||
connected(false),
|
||||
LinkEvent::Presence(Box::new(presence())),
|
||||
LinkEvent::OwnChannel(GAMES),
|
||||
]);
|
||||
h.state(|s| s.own_channel == Some(GAMES)).await;
|
||||
|
||||
h.engine.send(Command::SendChat {
|
||||
session: SESSION,
|
||||
target: ChatTarget::Channel(GAMES),
|
||||
text: "hello".into(),
|
||||
});
|
||||
assert!(matches!(conn.cmd().await, LinkCmd::SendChat(..)));
|
||||
// The server sends it back to everyone in the channel, to us too.
|
||||
let mut echo = message("tester", "hello", now_ms());
|
||||
echo.author_uid = Some(ME_UID.into());
|
||||
echo.author_id = Some(ME);
|
||||
conn.play([LinkEvent::Chat(echo.clone())]);
|
||||
let shown = h.chat().await;
|
||||
assert_eq!((shown.author_name.as_str(), shown.text.as_str()), ("tester", "hello"));
|
||||
|
||||
// A marker: what comes next is the next message, not a second "hello".
|
||||
conn.play([LinkEvent::Chat(message("alice", "marker", now_ms()))]);
|
||||
assert_eq!(h.chat().await.text, "marker");
|
||||
let rows = h.stored(ChatTarget::Channel(GAMES)).await;
|
||||
let texts: Vec<_> = rows.iter().map(|m| m.message.text.as_str()).collect();
|
||||
assert_eq!(texts, ["hello", "marker"]);
|
||||
assert_eq!(rows[0].source, MessageSource::Local);
|
||||
}
|
||||
|
||||
/// A message that comes twice (the server's and a relay's copy, with the
|
||||
/// relay's `[nick] ` prefix) is shown once.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_message_that_comes_twice_is_shown_once() {
|
||||
let mut h = Harness::start();
|
||||
let conn = h.connect().await;
|
||||
h.engine.send(Command::OpenChat { session: SESSION, target: ChatTarget::Channel(GAMES) });
|
||||
conn.play([
|
||||
connected(false),
|
||||
LinkEvent::Presence(Box::new(presence())),
|
||||
LinkEvent::OwnChannel(GAMES),
|
||||
]);
|
||||
h.state(|s| s.own_channel == Some(GAMES)).await;
|
||||
|
||||
let t = now_ms();
|
||||
let mut relayed = message("alice", "[alice] gg everyone", t + 300);
|
||||
relayed.via_relay = true;
|
||||
conn.play([
|
||||
LinkEvent::Chat(message("alice", "gg everyone", t)),
|
||||
LinkEvent::Chat(relayed),
|
||||
// The same words much later are another message.
|
||||
LinkEvent::Chat(message("alice", "gg everyone", t + 10_000)),
|
||||
LinkEvent::Chat(message("bob", "gg everyone", t + 10_100)),
|
||||
]);
|
||||
let shown: Vec<_> = {
|
||||
let mut shown = Vec::new();
|
||||
while shown.len() < 3 {
|
||||
shown.push(h.chat().await);
|
||||
}
|
||||
shown
|
||||
};
|
||||
let who: Vec<_> = shown.iter().map(|m| (m.author_name.as_str(), m.ts_ms)).collect();
|
||||
assert_eq!(who, [("alice", t), ("alice", t + 10_000), ("bob", t + 10_100)]);
|
||||
}
|
||||
|
||||
/// Stored messages come back when a chat opens, also after the connection
|
||||
/// is gone; the server's id keys them.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn history_is_kept_across_the_connection() {
|
||||
let mut h = Harness::start();
|
||||
let conn = h.connect().await;
|
||||
conn.play([
|
||||
connected(false),
|
||||
LinkEvent::Presence(Box::new(presence())),
|
||||
LinkEvent::OwnChannel(GAMES),
|
||||
]);
|
||||
h.state(|s| s.own_channel == Some(GAMES)).await;
|
||||
let t = now_ms();
|
||||
conn.play([
|
||||
LinkEvent::Chat(message("alice", "first", t)),
|
||||
LinkEvent::Chat(message("bob", "second", t + 1_000)),
|
||||
// A private message to us is stored under its peer, not the channel.
|
||||
LinkEvent::Chat(ChatMessage {
|
||||
target: ChatTarget::Private("alice=".into()),
|
||||
..message("alice", "psst", t + 2_000)
|
||||
}),
|
||||
]);
|
||||
for _ in 0..3 {
|
||||
h.chat().await;
|
||||
}
|
||||
conn.play([LinkEvent::Disconnected(None)]);
|
||||
h.state(|s| s.voice == VoiceState::Disconnected).await;
|
||||
|
||||
h.engine.send(Command::OpenChat { session: SESSION, target: ChatTarget::Channel(GAMES) });
|
||||
// The stored page (the live batches of the messages came before).
|
||||
let messages = h
|
||||
.next(|e| match e {
|
||||
Event::ChatHistory { messages, source: HistorySource::Local, .. } => Some(messages),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
let texts: Vec<_> = messages.iter().map(|m| m.message.text.as_str()).collect();
|
||||
assert_eq!(texts, ["first", "second"]);
|
||||
let private = h.stored(ChatTarget::Private("alice=".into())).await;
|
||||
assert_eq!(private.len(), 1);
|
||||
assert_eq!(private[0].message.text, "psst");
|
||||
}
|
||||
|
||||
/// Events of a connection the session replaced do not reach it.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_replaced_connection_is_ignored() {
|
||||
let mut h = Harness::start();
|
||||
let mut old = h.connect().await;
|
||||
old.play([
|
||||
connected(false),
|
||||
LinkEvent::Presence(Box::new(presence())),
|
||||
LinkEvent::OwnChannel(GAMES),
|
||||
]);
|
||||
h.state(|s| s.own_channel == Some(GAMES)).await;
|
||||
|
||||
let new = h.connect().await;
|
||||
assert!(matches!(old.cmd().await, LinkCmd::Disconnect));
|
||||
// The old connection winds down, and says more than it should.
|
||||
let mut stale = presence();
|
||||
stale.clients.insert(10, client(10, "ghost", LOBBY));
|
||||
old.play([
|
||||
LinkEvent::Presence(Box::new(stale)),
|
||||
LinkEvent::Chat(message("ghost", "boo", now_ms())),
|
||||
LinkEvent::Disconnected(None),
|
||||
]);
|
||||
let mut fresh = presence();
|
||||
fresh.clients.remove(&9);
|
||||
new.play([
|
||||
connected(false),
|
||||
LinkEvent::Presence(Box::new(fresh.clone())),
|
||||
LinkEvent::OwnChannel(LOBBY),
|
||||
]);
|
||||
// Only the new connection's presence is shown (nobody else has 2 clients).
|
||||
let shown = h
|
||||
.next(|e| match e {
|
||||
Event::Presence { presence, .. } if presence.clients.len() == fresh.clients.len() => {
|
||||
Some(presence)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(*shown, fresh);
|
||||
let state = h.state(|s| s.own_channel == Some(LOBBY)).await;
|
||||
assert_eq!(state.voice, VoiceState::Connected, "the old disconnect did not count");
|
||||
new.play([LinkEvent::Chat(message("alice", "hello", now_ms()))]);
|
||||
assert_eq!(h.chat().await.text, "hello", "the old connection's chat never showed");
|
||||
}
|
||||
@@ -123,6 +123,131 @@ async fn ts3_engine() {
|
||||
.await;
|
||||
}
|
||||
|
||||
/// A channel password and a privilege key work when connecting; a refused
|
||||
/// move says why. One connection, as the servers refuse quick reconnects.
|
||||
async fn channel_joins(voice_addr: &str, query: voelin_query::Connect) {
|
||||
use voelin_core::JoinFailure;
|
||||
use voelin_query::{Command as Query, QueryClient};
|
||||
let (admin, _) = QueryClient::connect(&query).await.unwrap();
|
||||
let tag = std::process::id() % 10_000;
|
||||
let create = |name: &str| {
|
||||
Query::new("channelcreate")
|
||||
.arg("channel_name", format!("{name}-{tag}"))
|
||||
.arg("channel_flag_semi_permanent", 1)
|
||||
};
|
||||
let locked = admin.send(&create("locked").arg("channel_password", "secret")).await.unwrap()[0]
|
||||
.parse::<u64>("cid")
|
||||
.unwrap();
|
||||
let full =
|
||||
create("full").arg("channel_maxclients", 0).arg("channel_flag_maxclients_unlimited", 0);
|
||||
let full = admin.send(&full).await.unwrap()[0].parse::<u64>("cid").unwrap();
|
||||
// A key for the Normal group, which has to keep to passwords and limits.
|
||||
let groups = admin.send(&Query::new("servergrouplist")).await.unwrap();
|
||||
let normal = groups
|
||||
.iter()
|
||||
.find(|g| g.get("name") == Some("Normal") && g.get("type") == Some("1"))
|
||||
.and_then(|g| g.parse::<u64>("sgid"))
|
||||
.expect("a Normal server group");
|
||||
let key = Query::new("privilegekeyadd")
|
||||
.arg("tokentype", 0)
|
||||
.arg("tokenid1", normal)
|
||||
.arg("tokenid2", 0);
|
||||
let token = admin.send(&key).await.unwrap()[0].get("token").unwrap().to_owned();
|
||||
let channels = admin.send(&Query::new("channellist").flag("-flags")).await.unwrap();
|
||||
let lobby = channels
|
||||
.iter()
|
||||
.find(|c| c.flag("channel_flag_default") == Some(true))
|
||||
.and_then(|c| c.parse::<u64>("cid"))
|
||||
.expect("a default channel");
|
||||
|
||||
let engine = Engine::start();
|
||||
let check = {
|
||||
let (engine, voice_addr, token) = (engine.clone(), voice_addr.to_owned(), token.clone());
|
||||
tokio::spawn(async move {
|
||||
let mut events = engine.subscribe();
|
||||
let mut options = VoiceOptions::new(&voice_addr, format!("joins-{tag}"));
|
||||
options.channel = Some(format!("locked-{tag}"));
|
||||
options.channel_password = Some("secret".into());
|
||||
options.token = Some(token);
|
||||
engine.send(Command::ConnectVoice { session: 1, options: Box::new(options) });
|
||||
let (mut own, mut presence) = (None, None);
|
||||
wait_for(&mut events, "connected into the channel, in the key's group", |e| {
|
||||
match e {
|
||||
Event::State { session: 1, state } => own = state.own_client,
|
||||
Event::Presence { session: 1, presence: p } => presence = Some(p.clone()),
|
||||
_ => {}
|
||||
}
|
||||
let client = own.and_then(|id| presence.as_ref()?.clients.get(&id).cloned());
|
||||
client.is_some_and(|c| c.channel == locked && c.server_groups.contains(&normal))
|
||||
})
|
||||
.await;
|
||||
let moved = async |events: &mut Receiver<Event>, channel: u64| {
|
||||
wait_for(
|
||||
events,
|
||||
"a move",
|
||||
|e| matches!(e, Event::State { session: 1, state } if state.own_channel == Some(channel)),
|
||||
)
|
||||
.await;
|
||||
};
|
||||
let refused =
|
||||
async |events: &mut Receiver<Event>, channel: u64, reason: JoinFailure| {
|
||||
let failed = wait_for(events, "a refused move", |e| {
|
||||
matches!(e, Event::JoinFailed { session: 1, .. })
|
||||
})
|
||||
.await;
|
||||
let Event::JoinFailed { channel: c, reason: r, .. } = failed else {
|
||||
unreachable!()
|
||||
};
|
||||
assert_eq!((c, r), (channel, reason));
|
||||
};
|
||||
let move_to = |channel, password: Option<&str>| Command::MoveToChannel {
|
||||
session: 1,
|
||||
channel,
|
||||
password: password.map(Into::into),
|
||||
};
|
||||
engine.send(move_to(lobby, None));
|
||||
moved(&mut events, lobby).await;
|
||||
engine.send(move_to(locked, None));
|
||||
refused(&mut events, locked, JoinFailure::Password).await;
|
||||
engine.send(move_to(locked, Some("wrong")));
|
||||
refused(&mut events, locked, JoinFailure::Password).await;
|
||||
engine.send(move_to(locked, Some("secret")));
|
||||
moved(&mut events, locked).await;
|
||||
// Moving where we are says nothing: the next refusal is the full channel's.
|
||||
engine.send(move_to(locked, Some("secret")));
|
||||
engine.send(move_to(full, None));
|
||||
refused(&mut events, full, JoinFailure::Full).await;
|
||||
})
|
||||
};
|
||||
let result = check.await;
|
||||
engine.send(Command::CloseSession { session: 1 });
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
// Clean up everything before reporting a failure; the key is gone once used.
|
||||
let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await;
|
||||
for cid in [locked, full] {
|
||||
admin.send(&Query::new("channeldelete").arg("cid", cid).arg("force", 1)).await.unwrap();
|
||||
}
|
||||
if let Err(error) = result {
|
||||
std::panic::resume_unwind(error.into_panic());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_channel_joins() {
|
||||
if !live() {
|
||||
return;
|
||||
}
|
||||
channel_joins("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022")).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_channel_joins() {
|
||||
if !live() {
|
||||
return;
|
||||
}
|
||||
channel_joins("127.0.0.1:9987", query(voelin_query::Transport::Raw, "127.0.0.1:10011")).await;
|
||||
}
|
||||
|
||||
/// A 1×1 PNG.
|
||||
const PNG: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
|
||||
|
||||
|
||||
@@ -1,149 +0,0 @@
|
||||
//! Opt-in account + isolated server interoperability check. No keys are saved.
|
||||
//! Requires VOELIN_MYTS_LIVE=1, EMAIL/PASSWORD/DEVICE_ID and optional OTP under
|
||||
//! the VOELIN_MYTS_ prefix; TEST_TS3/TEST_TS6 and QUERY_TS3/QUERY_TS6 give
|
||||
//! loopback voice/query addresses. QUERY_PASSWORD authenticates local query.
|
||||
#![cfg(not(target_os = "android"))]
|
||||
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::{Context, Result, bail, ensure};
|
||||
use tokio::{sync::broadcast, time::timeout};
|
||||
use voelin_core::{Command, Engine, Event, VoiceOptions, VoiceState};
|
||||
use voelin_myts::{Client, ServerIdentity};
|
||||
use voelin_query::{Command as QueryCommand, QueryClient, Row};
|
||||
|
||||
fn env(name: &str) -> Result<String> {
|
||||
std::env::var(format!("VOELIN_MYTS_{name}")).with_context(|| format!("missing {name}"))
|
||||
}
|
||||
|
||||
async fn connected(events: &mut broadcast::Receiver<Event>, session_id: u64) -> Result<u16> {
|
||||
timeout(Duration::from_secs(35), async {
|
||||
loop {
|
||||
match events.recv().await? {
|
||||
Event::State { session, state }
|
||||
if session == session_id && state.voice == VoiceState::Connected =>
|
||||
{
|
||||
if let Some(id) = state.own_client {
|
||||
return Ok(id);
|
||||
}
|
||||
}
|
||||
Event::Error { message, .. } => bail!("engine: {message}"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
async fn info(query: &QueryClient, client: u16) -> Result<Row> {
|
||||
query
|
||||
.send(&QueryCommand::new("clientinfo").arg("clid", client))
|
||||
.await?
|
||||
.into_iter()
|
||||
.next()
|
||||
.context("clientinfo missing")
|
||||
}
|
||||
|
||||
async fn wait_id(query: &QueryClient, client: u16, expected: &str) -> Result<()> {
|
||||
timeout(Duration::from_secs(12), async {
|
||||
loop {
|
||||
let row = info(query, client).await?;
|
||||
if row.get("client_myteamspeak_id") == Some(expected) {
|
||||
return Ok(());
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.context("server did not report the expected myTS association")?
|
||||
}
|
||||
|
||||
async fn server(identity: Arc<ServerIdentity>, kind: &str) -> Result<()> {
|
||||
let address = env(&format!("TEST_{kind}"))?;
|
||||
let query_address = env(&format!("QUERY_{kind}"))?;
|
||||
// This test is deliberately limited to caller-owned loopback test servers.
|
||||
ensure!(address.starts_with("127.0.0.1:"), "voice endpoint must be loopback");
|
||||
ensure!(query_address.starts_with("127.0.0.1:"), "query endpoint must be loopback");
|
||||
let (query, _) = QueryClient::connect(&voelin_query::Connect {
|
||||
transport: if kind == "TS3" {
|
||||
voelin_query::Transport::Raw
|
||||
} else {
|
||||
voelin_query::Transport::Ssh
|
||||
},
|
||||
addr: query_address,
|
||||
user: "serveradmin".into(),
|
||||
secret: Some(env("QUERY_PASSWORD")?),
|
||||
server_id: Some(1),
|
||||
server_port: None,
|
||||
line: voelin_query::LineOptions { rate_limit: None, ..Default::default() },
|
||||
})
|
||||
.await?;
|
||||
let engine = Engine::start();
|
||||
let mut events = engine.subscribe();
|
||||
let result = async {
|
||||
engine.send(Command::SetMytsIdentity(Some(identity.clone())));
|
||||
for session in 1..=2 {
|
||||
engine.send(Command::ConnectVoice {
|
||||
session,
|
||||
options: Box::new(VoiceOptions::new(&address, format!("myts-proof-{session}"))),
|
||||
});
|
||||
let client = connected(&mut events, session).await?;
|
||||
let row = info(&query, client).await?;
|
||||
let version = voelin_core::versions::native_version()?;
|
||||
ensure!(row.get("client_platform") == Some(version.get_platform()), "wrong platform");
|
||||
ensure!(
|
||||
row.get("client_version") == Some(version.get_version_string()),
|
||||
"wrong version"
|
||||
);
|
||||
let metadata: serde_json::Value =
|
||||
serde_json::from_str(row.get("client_meta_data").context("missing metadata")?)?;
|
||||
ensure!(metadata["name"] == "Voelin", "wrong client metadata");
|
||||
ensure!(metadata["platform"] == std::env::consts::OS, "wrong metadata platform");
|
||||
eprintln!("{kind}: native platform/Voelin metadata passed");
|
||||
wait_id(&query, client, &identity.id()).await?;
|
||||
eprintln!("{kind}: signed clientinit myTS ID passed");
|
||||
// Two fresh connections prove the signature is bound to each handshake.
|
||||
engine.send(Command::SetMytsIdentity(None));
|
||||
wait_id(&query, client, "").await?;
|
||||
engine.send(Command::SetMytsIdentity(Some(identity.clone())));
|
||||
wait_id(&query, client, &identity.id()).await?;
|
||||
eprintln!("{kind}: live clear and reattach passed");
|
||||
engine.send(Command::CloseSession { session });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
engine.send(Command::SetMytsIdentity(None));
|
||||
for session in 1..=2 {
|
||||
engine.send(Command::CloseSession { session });
|
||||
}
|
||||
query.quit().await;
|
||||
result
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires owner-authorized account and isolated loopback servers"]
|
||||
async fn authenticated_account_and_server_lifecycle() -> Result<()> {
|
||||
ensure!(env("LIVE")? == "1", "explicit live opt-in required");
|
||||
let client = Client::new()?;
|
||||
let login = client
|
||||
.login(&env("EMAIL")?, &env("PASSWORD")?, env("OTP").ok().as_deref(), &env("DEVICE_ID")?)
|
||||
.await?;
|
||||
// Capture every result before deleting the newly created remote session.
|
||||
let result = async {
|
||||
client.validate_session(&login.token).await?;
|
||||
let identity = Arc::new(login.identity.context("server identity unlock failed")?);
|
||||
let mut failures = Vec::new();
|
||||
for kind in ["TS3", "TS6"] {
|
||||
if let Err(error) = server(identity.clone(), kind).await {
|
||||
failures.push(format!("{kind}: {error:#}"));
|
||||
}
|
||||
}
|
||||
ensure!(failures.is_empty(), "{}", failures.join("; "));
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
let logout = client.logout(&login.token).await;
|
||||
logout.context("remote test session revocation failed")?;
|
||||
result
|
||||
}
|
||||
@@ -167,7 +167,7 @@ async fn ts6_stream_between_sessions() {
|
||||
Event::StreamViewers { session: 1, viewers }
|
||||
if viewers
|
||||
.iter()
|
||||
.any(|v| v.client.0 == viewer && v.state == ViewerState::Connected) =>
|
||||
.any(|v| v.client == viewer && v.state == ViewerState::Connected) =>
|
||||
{
|
||||
Some(())
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ serde_json = "1"
|
||||
sha1 = { package = "sha-1", version = "0.10" }
|
||||
sha2 = "0.10"
|
||||
thiserror = "2"
|
||||
tokio = { version = "1", features = ["macros", "rt", "sync"], optional = true }
|
||||
tokio = { version = "1", features = ["macros", "net", "rt", "sync"], optional = true }
|
||||
# TLS (`wss://`, as gateways run behind a proxy) with the system's
|
||||
# certificates; rustls and its crates are in the tree already (reqwest).
|
||||
tokio-tungstenite = { version = "0.30", optional = true, features = ["rustls-tls-native-roots"] }
|
||||
|
||||
@@ -20,10 +20,14 @@
|
||||
//! ```
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use futures_util::{Sink, SinkExt, Stream, StreamExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio_tungstenite::tungstenite::{self, Message};
|
||||
use tsproto_types::crypto::EccKeyPrivP256;
|
||||
@@ -196,15 +200,163 @@ pub struct GatewayClient {
|
||||
pub async fn connect(
|
||||
url: &str,
|
||||
login: Login,
|
||||
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
|
||||
connect_watched(url, login, &Progress::default()).await
|
||||
}
|
||||
|
||||
/// [`connect`], telling `progress` each step as it is reached, so a
|
||||
/// timeout around it can say which step hung, and how long each took.
|
||||
pub async fn connect_watched(
|
||||
url: &str,
|
||||
login: Login,
|
||||
progress: &Progress,
|
||||
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
|
||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||
use tokio_tungstenite::tungstenite::error::UrlError;
|
||||
let mut request = url.into_client_request()?;
|
||||
request.headers_mut().insert(
|
||||
"Sec-WebSocket-Protocol",
|
||||
tungstenite::http::HeaderValue::from_static(crate::SUBPROTOCOL),
|
||||
);
|
||||
let (ws, _) = tokio_tungstenite::connect_async(request).await?;
|
||||
GatewayClient::start(ws, login).await
|
||||
// As tokio-tungstenite's connect_async, a step at a time.
|
||||
let uri = request.uri();
|
||||
let host = uri.host().ok_or(tungstenite::Error::Url(UrlError::NoHostName))?;
|
||||
let host = host.strip_prefix('[').and_then(|h| h.strip_suffix(']')).unwrap_or(host);
|
||||
let port = uri
|
||||
.port_u16()
|
||||
.or_else(|| match uri.scheme_str() {
|
||||
Some("wss") => Some(443),
|
||||
Some("ws") => Some(80),
|
||||
_ => None,
|
||||
})
|
||||
.ok_or(tungstenite::Error::Url(UrlError::UnsupportedUrlScheme))?;
|
||||
let tcp = open(host, port, progress).await?;
|
||||
progress.enter(Stage::WebSocket);
|
||||
let (ws, _) = tokio_tungstenite::client_async_tls_with_config(request, tcp, None, None).await?;
|
||||
GatewayClient::login(ws, login, progress).await
|
||||
}
|
||||
|
||||
/// The TCP connection to `host`: each of its addresses in turn.
|
||||
async fn open(host: &str, port: u16, progress: &Progress) -> Result<TcpStream, ClientError> {
|
||||
let io = |e| ClientError::WebSocket(tungstenite::Error::Io(e));
|
||||
progress.enter(Stage::Dns);
|
||||
let addrs: Vec<SocketAddr> = tokio::net::lookup_host((host, port)).await.map_err(io)?.collect();
|
||||
progress.enter(Stage::Tcp);
|
||||
let mut error = None;
|
||||
for addr in addrs {
|
||||
progress.peer(addr);
|
||||
match TcpStream::connect(addr).await {
|
||||
Ok(tcp) => {
|
||||
// Small frames, each answered: no waiting to fill packets.
|
||||
let _ = tcp.set_nodelay(true);
|
||||
return Ok(tcp);
|
||||
}
|
||||
Err(e) => error = Some(e),
|
||||
}
|
||||
}
|
||||
Err(io(error.unwrap_or_else(|| {
|
||||
std::io::Error::new(std::io::ErrorKind::NotFound, format!("no address for {host}"))
|
||||
})))
|
||||
}
|
||||
|
||||
/// A step of logging in to a gateway ([`connect_watched`]).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Stage {
|
||||
/// Looking up the host's addresses.
|
||||
#[default]
|
||||
Dns,
|
||||
/// The TCP connection.
|
||||
Tcp,
|
||||
/// TLS (`wss://`) and the WebSocket upgrade.
|
||||
WebSocket,
|
||||
/// Waiting for the gateway's `hello`.
|
||||
Hello,
|
||||
/// Waiting for the answer to the login.
|
||||
Auth,
|
||||
/// Logged in.
|
||||
Done,
|
||||
}
|
||||
|
||||
impl Stage {
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Stage::Dns => "dns",
|
||||
Stage::Tcp => "tcp",
|
||||
Stage::WebSocket => "websocket",
|
||||
Stage::Hello => "hello",
|
||||
Stage::Auth => "auth",
|
||||
Stage::Done => "done",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Stage {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(self.name())
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a login ([`connect_watched`]) got and how long each step took;
|
||||
/// clones share it. Shown as e.g. `dns 2 ms, tcp 31 ms, websocket 64 ms,
|
||||
/// hello 1 ms, auth 134 ms`, a step still under way as `hello for 19900 ms`.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Progress(Arc<Mutex<Steps>>);
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct Steps {
|
||||
/// The step under way, since when.
|
||||
stage: Stage,
|
||||
since: Option<Instant>,
|
||||
/// The steps done, with how long they took.
|
||||
done: Vec<(Stage, Duration)>,
|
||||
/// The address connected to (or being tried).
|
||||
peer: Option<SocketAddr>,
|
||||
}
|
||||
|
||||
impl Progress {
|
||||
/// The step under way (the one that hung, after a timeout), or
|
||||
/// [`Stage::Done`].
|
||||
pub fn stage(&self) -> Stage {
|
||||
self.0.lock().unwrap().stage
|
||||
}
|
||||
|
||||
/// The gateway's address, once the TCP connection is being made.
|
||||
pub fn peer_addr(&self) -> Option<SocketAddr> {
|
||||
self.0.lock().unwrap().peer
|
||||
}
|
||||
|
||||
fn enter(&self, stage: Stage) {
|
||||
let mut steps = self.0.lock().unwrap();
|
||||
let now = Instant::now();
|
||||
if let Some(since) = steps.since {
|
||||
let step = steps.stage;
|
||||
steps.done.push((step, now - since));
|
||||
}
|
||||
steps.stage = stage;
|
||||
steps.since = (stage != Stage::Done).then_some(now);
|
||||
}
|
||||
|
||||
fn peer(&self, addr: SocketAddr) {
|
||||
self.0.lock().unwrap().peer = Some(addr);
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Progress {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let steps = self.0.lock().unwrap();
|
||||
let mut parts: Vec<String> = steps
|
||||
.done
|
||||
.iter()
|
||||
.map(|(stage, took)| format!("{stage} {} ms", took.as_millis()))
|
||||
.collect();
|
||||
if let Some(since) = steps.since {
|
||||
parts.push(format!("{} for {} ms", steps.stage, since.elapsed().as_millis()));
|
||||
}
|
||||
if parts.is_empty() {
|
||||
return f.write_str("not started");
|
||||
}
|
||||
f.write_str(&parts.join(", "))
|
||||
}
|
||||
}
|
||||
|
||||
fn now_secs() -> i64 {
|
||||
@@ -241,7 +393,7 @@ impl GatewayClient {
|
||||
/// Log in over an open WebSocket (subprotocol [`crate::SUBPROTOCOL`]) and
|
||||
/// start the connection task.
|
||||
pub async fn start<S>(
|
||||
mut ws: S,
|
||||
ws: S,
|
||||
login: Login,
|
||||
) -> Result<(Self, mpsc::UnboundedReceiver<Push>), ClientError>
|
||||
where
|
||||
@@ -251,12 +403,29 @@ impl GatewayClient {
|
||||
+ Send
|
||||
+ 'static,
|
||||
{
|
||||
Self::login(ws, login, &Progress::default()).await
|
||||
}
|
||||
|
||||
async fn login<S>(
|
||||
mut ws: S,
|
||||
login: Login,
|
||||
progress: &Progress,
|
||||
) -> Result<(Self, mpsc::UnboundedReceiver<Push>), ClientError>
|
||||
where
|
||||
S: Stream<Item = Result<Message, tungstenite::Error>>
|
||||
+ Sink<Message, Error = tungstenite::Error>
|
||||
+ Unpin
|
||||
+ Send
|
||||
+ 'static,
|
||||
{
|
||||
progress.enter(Stage::Hello);
|
||||
let (gateway_id, server_uid, server_name, nonce) = match recv(&mut ws).await?.msg {
|
||||
ServerMsg::Hello { gateway_id, server_uid, server_name, nonce, .. } => {
|
||||
(gateway_id, server_uid, server_name, nonce)
|
||||
}
|
||||
other => return Err(ClientError::unexpected(other)),
|
||||
};
|
||||
progress.enter(Stage::Auth);
|
||||
let msg = match login {
|
||||
Login::Identity { key, key_offset } => {
|
||||
let ts = now_secs();
|
||||
@@ -280,6 +449,7 @@ impl GatewayClient {
|
||||
}
|
||||
other => return Err(ClientError::unexpected(other)),
|
||||
};
|
||||
progress.enter(Stage::Done);
|
||||
let info = Arc::new(SessionInfo {
|
||||
gateway_id,
|
||||
server_uid,
|
||||
@@ -732,3 +902,104 @@ async fn run<S>(
|
||||
};
|
||||
let _ = pushes.send(Push::Disconnected(reason));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tokio::net::TcpListener;
|
||||
use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Wait (without a clock: tokio's `time` is not enabled here) until the
|
||||
/// login in progress reaches `stage`.
|
||||
async fn reaches(progress: &Progress, stage: Stage) {
|
||||
for _ in 0..100_000 {
|
||||
if progress.stage() == stage {
|
||||
return;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
panic!("at {} instead of {stage}", progress.stage());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_closed_port_fails_at_the_tcp_step() {
|
||||
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
|
||||
let progress = Progress::default();
|
||||
assert_eq!(progress.to_string(), "not started");
|
||||
let login = Login::Token("t".into());
|
||||
let result = connect_watched(&format!("ws://127.0.0.1:{port}/v1"), login, &progress).await;
|
||||
assert!(matches!(result, Err(ClientError::WebSocket(_))));
|
||||
assert_eq!(progress.stage(), Stage::Tcp);
|
||||
assert_eq!(progress.peer_addr(), Some(([127, 0, 0, 1], port).into()));
|
||||
assert!(progress.to_string().starts_with("dns "), "{progress}");
|
||||
}
|
||||
|
||||
/// A gateway that takes each step only when told: the login waits at
|
||||
/// each, and tells which.
|
||||
#[tokio::test]
|
||||
async fn each_step_is_told_until_logged_in() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("ws://{}/v1", listener.local_addr().unwrap());
|
||||
let (go, mut steps) = mpsc::unbounded_channel::<()>();
|
||||
let server = tokio::spawn(async move {
|
||||
let (tcp, _) = listener.accept().await.unwrap();
|
||||
steps.recv().await;
|
||||
#[allow(clippy::result_large_err)] // tungstenite's callback type
|
||||
let callback = |_: &Request, mut response: Response| {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("Sec-WebSocket-Protocol", crate::SUBPROTOCOL.parse().unwrap());
|
||||
Ok(response)
|
||||
};
|
||||
let mut ws = tokio_tungstenite::accept_hdr_async(tcp, callback).await.unwrap();
|
||||
steps.recv().await;
|
||||
let hello = ServerMsg::Hello {
|
||||
gateway_id: "gw".into(),
|
||||
server_uid: "server".into(),
|
||||
server_name: "Server".into(),
|
||||
nonce: "n".into(),
|
||||
capabilities: Vec::new(),
|
||||
};
|
||||
let text = serde_json::to_string(&Envelope::new(hello)).unwrap();
|
||||
ws.send(Message::Text(text.into())).await.unwrap();
|
||||
let Some(Ok(Message::Text(auth))) = ws.next().await else { panic!("no login") };
|
||||
let auth: Envelope<ClientMsg> = serde_json::from_str(auth.as_str()).unwrap();
|
||||
assert!(matches!(auth.msg, ClientMsg::Resume { .. }));
|
||||
steps.recv().await;
|
||||
let ok = ServerMsg::AuthOk {
|
||||
uid: "me".into(),
|
||||
token: "t".into(),
|
||||
token_expires: 0,
|
||||
capabilities: Vec::new(),
|
||||
};
|
||||
let text = serde_json::to_string(&Envelope::with_id(auth.id.unwrap(), ok)).unwrap();
|
||||
ws.send(Message::Text(text.into())).await.unwrap();
|
||||
// Open until the client is done.
|
||||
while let Some(Ok(_)) = ws.next().await {}
|
||||
});
|
||||
let progress = Progress::default();
|
||||
let login = {
|
||||
let progress = progress.clone();
|
||||
tokio::spawn(async move {
|
||||
connect_watched(&url, Login::Token("t".into()), &progress).await.map(|(c, _)| c)
|
||||
})
|
||||
};
|
||||
reaches(&progress, Stage::WebSocket).await;
|
||||
go.send(()).unwrap();
|
||||
reaches(&progress, Stage::Hello).await;
|
||||
go.send(()).unwrap();
|
||||
reaches(&progress, Stage::Auth).await;
|
||||
assert!(progress.to_string().contains(", auth for "), "{progress}");
|
||||
go.send(()).unwrap();
|
||||
let client = login.await.unwrap().expect("logged in");
|
||||
assert_eq!(client.uid(), "me");
|
||||
assert_eq!(progress.stage(), Stage::Done);
|
||||
let shown = progress.to_string();
|
||||
let names: Vec<&str> =
|
||||
shown.split(", ").map(|step| step.split(' ').next().unwrap()).collect();
|
||||
assert_eq!(names, ["dns", "tcp", "websocket", "hello", "auth"], "{shown}");
|
||||
drop(client);
|
||||
server.await.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,35 @@
|
||||
# Build: docker build -f crates/voelin-gateway/Dockerfile -t tsgw .
|
||||
# Run: docker run -v ./tsgw.toml:/etc/tsgw/tsgw.toml -p 7788:7788 tsgw
|
||||
# syntax=docker/dockerfile:1
|
||||
# Build: docker build --ssh default -f crates/voelin-gateway/Dockerfile -t tsgw .
|
||||
# (--ssh default hands the build your ssh-agent, which must hold a key that
|
||||
# can read the private VoelinProtocol repository: docs/building.md,
|
||||
# "Depending on VoelinProtocol". The gateway itself does not use it, but
|
||||
# Cargo resolves the whole workspace, which includes voelin-identity.)
|
||||
# Run: docker run -d --name tsgw --init --restart unless-stopped \
|
||||
# -v ./tsgw.toml:/etc/tsgw/tsgw.toml:ro -v tsgw-data:/var/lib/tsgw \
|
||||
# -e TSGW_QUERY_PASSWORD=… -p 7788:7788 tsgw
|
||||
# Logs: docker logs -f tsgw (more: -e TSGW_LOG_LEVEL=debug; also to a file in
|
||||
# the volume: -e TSGW_LOG_FILE=logs/tsgw.log). See docs/gateway-admin.md.
|
||||
FROM rust:1.94-bookworm AS build
|
||||
ENV CARGO_BUILD_JOBS=1 CARGO_INCREMENTAL=0
|
||||
WORKDIR /src
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends cmake libasound2-dev && rm -rf /var/lib/apt/lists/*
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends cmake git libasound2-dev openssh-client && rm -rf /var/lib/apt/lists/*
|
||||
# voelin-identity comes from the private VoelinProtocol repository, fetched
|
||||
# over SSH by Cargo through the system git, with the agent that
|
||||
# `docker build --ssh default` forwards (scripts/docker-build.sh passes it):
|
||||
# the key stays in the agent and never reaches a layer. The host key is the
|
||||
# reviewed line from .gitea/known_hosts. Cargo resolves the whole workspace, so
|
||||
# every cargo command needs this, although this crate does not use
|
||||
# voelin-identity.
|
||||
COPY .gitea/known_hosts /etc/ssh/ssh_known_hosts
|
||||
ENV CARGO_NET_GIT_FETCH_WITH_CLI=true
|
||||
COPY . .
|
||||
RUN cargo build --release --locked -p voelin-gateway && cp target/release/tsgw /tsgw
|
||||
RUN --mount=type=ssh,required=true \
|
||||
cargo build --release --locked -p voelin-gateway && cp target/release/tsgw /tsgw && mkdir /data
|
||||
|
||||
FROM gcr.io/distroless/cc-debian12:nonroot
|
||||
COPY --from=build /tsgw /usr/local/bin/tsgw
|
||||
# The database (and a log file, if set) live here; owned by the image's user
|
||||
# (nonroot, 65532), so a new volume mounted here is writable too.
|
||||
COPY --from=build --chown=65532:65532 /data /var/lib/tsgw
|
||||
ENV TSGW_CONFIG=/etc/tsgw/tsgw.toml
|
||||
WORKDIR /var/lib/tsgw
|
||||
EXPOSE 7788
|
||||
|
||||
@@ -130,6 +130,18 @@ pub static KEYS: &[KeyDef] = &[
|
||||
"null",
|
||||
"URL clients use, e.g. wss://gw.example.org/v1",
|
||||
),
|
||||
boot(
|
||||
"log.level",
|
||||
Kind::OptStr,
|
||||
"null",
|
||||
"What to log, e.g. \"debug\" or \"info,voelin_query=trace\"; default: RUST_LOG, else \"info\"",
|
||||
),
|
||||
boot(
|
||||
"log.file",
|
||||
Kind::OptStr,
|
||||
"null",
|
||||
"Also write the log to this file (appended; at 20 MB it moves to <name>.1.log, 5 files kept)",
|
||||
),
|
||||
boot(
|
||||
"history.path",
|
||||
Kind::Str,
|
||||
@@ -160,7 +172,7 @@ pub static KEYS: &[KeyDef] = &[
|
||||
"relay.format",
|
||||
Kind::Str,
|
||||
"\"[{nick}] {text}\"",
|
||||
"How posts appear in TeamSpeak; {nick} and {text} are replaced",
|
||||
"How posts appear when the relay cannot take the user's nickname; {nick} and {text} are replaced",
|
||||
),
|
||||
key(
|
||||
"relay.idle_teardown_secs",
|
||||
@@ -493,6 +505,10 @@ impl Layers {
|
||||
bind: self.get::<String>("listen.bind")?.parse().context("listen.bind")?,
|
||||
public_url: self.get("listen.public_url")?,
|
||||
db_path: self.get("history.path")?,
|
||||
log_level: self.get::<Option<String>>("log.level")?.filter(|l| !l.trim().is_empty()),
|
||||
log_file: self
|
||||
.get::<Option<PathBuf>>("log.file")?
|
||||
.filter(|p| !p.as_os_str().is_empty()),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -514,6 +530,10 @@ pub struct Bootstrap {
|
||||
pub bind: SocketAddr,
|
||||
pub public_url: Option<String>,
|
||||
pub db_path: PathBuf,
|
||||
/// Log filter (`log.level`); `None`: `RUST_LOG`, else the default.
|
||||
pub log_level: Option<String>,
|
||||
/// Log file (`log.file`), on top of standard output.
|
||||
pub log_file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Bootstrap {
|
||||
@@ -524,6 +544,8 @@ impl Bootstrap {
|
||||
.unwrap_or_else(|| format!("tsgw@{}", self.addr))
|
||||
}
|
||||
|
||||
/// How to open query connections. Connections opened with clones of
|
||||
/// the result share one flood count, as the server counts them.
|
||||
pub fn query_connect(&self) -> voelin_query::Connect {
|
||||
voelin_query::Connect {
|
||||
transport: self.transport,
|
||||
@@ -751,4 +773,21 @@ mod tests {
|
||||
assert!(cli_values(&["nope=1".into()]).is_err());
|
||||
assert!(cli_values(&["history.retention_days=-1".into()]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn log_settings_are_bootstrap_keys() {
|
||||
let file = file_values(
|
||||
"[query]\ntransport = \"ssh\"\naddr = \"127.0.0.1:10022\"\n\
|
||||
[log]\nfile = \"logs/tsgw.log\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let env = env_values(|name| (name == "TSGW_LOG_LEVEL").then(|| "debug".into())).unwrap();
|
||||
let boot = Layers { file, env, ..Default::default() }.bootstrap().unwrap();
|
||||
assert_eq!(boot.log_level.as_deref(), Some("debug"));
|
||||
assert_eq!(boot.log_file, Some(PathBuf::from("logs/tsgw.log")));
|
||||
assert!(key_def("log.level").unwrap().bootstrap);
|
||||
let none = file_values("[query]\ntransport = \"raw\"\naddr = \"h:1\"\n").unwrap();
|
||||
let boot = Layers { file: none, ..Default::default() }.bootstrap().unwrap();
|
||||
assert_eq!((boot.log_level, boot.log_file), (None, None));
|
||||
}
|
||||
}
|
||||
@@ -367,6 +367,7 @@ impl Db {
|
||||
}
|
||||
|
||||
/// Whether `uid` reacted with `emoji`.
|
||||
#[cfg(test)]
|
||||
pub fn has_reaction(&self, message_id: i64, emoji: &str, uid: &str) -> rusqlite::Result<bool> {
|
||||
self.lock()
|
||||
.conn
|
||||
|
||||
@@ -253,6 +253,7 @@ impl Db {
|
||||
self.0.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn schema_version(&self) -> rusqlite::Result<i64> {
|
||||
self.lock().conn.pragma_query_value(None, "user_version", |r| r.get(0))
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
//! feed are in `features.rs`, the stream directory in `streams.rs`, the
|
||||
//! background tasks in `tasks.rs`.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
use std::time::Instant;
|
||||
|
||||
@@ -19,12 +19,13 @@ use voelin_gateway_proto::{
|
||||
Action, ActivityEntry, ErrorCode, EventInfo, HistoryEntry, PinInfo, StreamEntry, TopicInfo,
|
||||
UniqueIds, UserRef, feature, identity_level, verify_auth,
|
||||
};
|
||||
use voelin_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor, relay_text};
|
||||
use voelin_observer::{Observer, ObserverConfig, RelayConfig, RelayPool};
|
||||
use voelin_query::{Command, Connect, QueryClient};
|
||||
use voelin_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor};
|
||||
use voelin_observer::{Observer, ObserverConfig, RelayConfig, RelayPool, post_as};
|
||||
use voelin_query::{Command, Connect};
|
||||
|
||||
use crate::config::{Bootstrap, Layers, Runtime};
|
||||
use crate::config::{Layers, Runtime};
|
||||
use crate::db::{Db, TokenInfo};
|
||||
use crate::lookup::Lookup;
|
||||
use crate::perms::{
|
||||
ChannelAccess, GroupResolver, PermIds, PermResolver, UserGroups, channel_access, effective,
|
||||
granted, rule_allows,
|
||||
@@ -192,7 +193,6 @@ impl Feature {
|
||||
}
|
||||
|
||||
pub struct Hub {
|
||||
pub boot: Bootstrap,
|
||||
pub settings: Settings,
|
||||
pub gateway_id: String,
|
||||
pub server_uid: String,
|
||||
@@ -205,83 +205,78 @@ pub struct Hub {
|
||||
relays: RwLock<RelayPool>,
|
||||
/// Serializes rebuilding the relay pool.
|
||||
relay_rebuild: tokio::sync::Mutex<()>,
|
||||
lookup: QueryClient,
|
||||
pub(crate) lookup: Arc<Lookup>,
|
||||
/// One server-chat post at a time: each borrows the poster's nickname.
|
||||
lookup_posting: tokio::sync::Mutex<()>,
|
||||
perms: PermResolver,
|
||||
groups: GroupResolver,
|
||||
pub db: Db,
|
||||
events: broadcast::Sender<Arc<HubEvent>>,
|
||||
/// Readers per relayed channel, and when the last one left.
|
||||
readers: Mutex<HashMap<ChannelId, (usize, Instant)>>,
|
||||
/// Our own query clients, whose messages are echoes.
|
||||
own_clients: Mutex<HashSet<u16>>,
|
||||
/// Message ids while history is off.
|
||||
next_message_id: Mutex<i64>,
|
||||
pub(crate) directory: Mutex<Directory>,
|
||||
}
|
||||
|
||||
impl Hub {
|
||||
/// Connect to the server, open the database and start the background tasks.
|
||||
/// Connect to the server, open the database and start the background
|
||||
/// tasks. Waits for the TeamSpeak server as long as it takes.
|
||||
pub async fn start(layers: Layers) -> Result<Arc<Self>> {
|
||||
let started = Instant::now();
|
||||
let boot = layers.bootstrap()?;
|
||||
let db = Db::open(&boot.db_path)
|
||||
.with_context(|| format!("failed to open {}", boot.db_path.display()))?;
|
||||
let settings = Settings::new(layers, &db)?;
|
||||
let rt = settings.current();
|
||||
|
||||
// Clones share the count of commands for the flood protection.
|
||||
let connect = boot.query_connect();
|
||||
let (lookup, _) =
|
||||
QueryClient::connect(&connect).await.context("query login for lookups failed")?;
|
||||
let info = lookup.send(&Command::new("serverinfo")).await?;
|
||||
let info = info.first().context("empty serverinfo")?;
|
||||
let version = info.get("virtualserver_version").unwrap_or_default();
|
||||
let is_ts6 = matches!(ServerFlavor::from_version_string(version), ServerFlavor::Ts6(_));
|
||||
let server_uid =
|
||||
info.get("virtualserver_unique_identifier").unwrap_or_default().to_string();
|
||||
let server_name = info.get("virtualserver_name").unwrap_or_default().to_string();
|
||||
let needed_level = info.parse("virtualserver_needed_identity_security_level").unwrap_or(8);
|
||||
let channels = lookup.send(&Command::new("channellist").flag("flags")).await?;
|
||||
let default_channel = channels
|
||||
.iter()
|
||||
.find(|r| r.flag("channel_flag_default") == Some(true))
|
||||
.and_then(|r| r.parse("cid"))
|
||||
.unwrap_or(1);
|
||||
let perms = PermResolver::new(PermIds::load(&lookup).await?);
|
||||
let own_id = lookup.own_client_id().await?;
|
||||
set_lookup_nickname(&lookup, &rt.relay.nickname).await;
|
||||
let lookup = Lookup::open(connect.clone(), lookup_nickname(&rt.relay.nickname)).await;
|
||||
lookup.log_address(boot.allowlisted).await;
|
||||
let server = ServerFacts::load_until_it_works(&lookup, &connect).await;
|
||||
let perms = PermResolver::new(server.perm_ids);
|
||||
|
||||
let observer = Observer::spawn(ObserverConfig::new(connect.clone()));
|
||||
let relays = new_relay_pool(&connect, &rt.relay.nickname);
|
||||
let directory = Directory::load(&db);
|
||||
|
||||
info!(%server_name, %server_uid, version, is_ts6, "gateway connected to server");
|
||||
info!(
|
||||
server_name = %server.name,
|
||||
server_uid = %server.uid,
|
||||
version = %server.version,
|
||||
is_ts6 = server.is_ts6,
|
||||
default_channel = server.default_channel,
|
||||
needed_level = server.needed_level,
|
||||
elapsed_ms = started.elapsed().as_millis() as u64,
|
||||
"gateway connected to server"
|
||||
);
|
||||
let hub = Arc::new(Self {
|
||||
gateway_id: boot.gateway_id(),
|
||||
boot,
|
||||
settings,
|
||||
server_uid,
|
||||
server_name,
|
||||
is_ts6,
|
||||
needed_level,
|
||||
default_channel,
|
||||
server_uid: server.uid,
|
||||
server_name: server.name,
|
||||
is_ts6: server.is_ts6,
|
||||
needed_level: server.needed_level,
|
||||
default_channel: server.default_channel,
|
||||
observer,
|
||||
connect,
|
||||
relays: RwLock::new(relays),
|
||||
relay_rebuild: Default::default(),
|
||||
lookup,
|
||||
lookup_posting: Default::default(),
|
||||
perms,
|
||||
groups: GroupResolver::default(),
|
||||
db,
|
||||
events: broadcast::channel(4096).0,
|
||||
readers: Default::default(),
|
||||
own_clients: Mutex::new([own_id].into()),
|
||||
next_message_id: Mutex::new(0),
|
||||
directory: Mutex::new(directory),
|
||||
});
|
||||
crate::tasks::spawn_all(&hub);
|
||||
// Apps may log in meanwhile.
|
||||
for &cid in &rt.relay.pinned_channels {
|
||||
if let Err(error) = hub.relays().open(cid).await {
|
||||
warn!(cid, %error, "could not open pinned relay");
|
||||
}
|
||||
hub.open_relay_soon(cid);
|
||||
}
|
||||
Ok(hub)
|
||||
}
|
||||
@@ -303,7 +298,7 @@ impl Hub {
|
||||
}
|
||||
|
||||
pub(crate) fn is_own_client(&self, id: u16) -> bool {
|
||||
self.own_clients.lock().unwrap().contains(&id)
|
||||
self.lookup.is_own(id)
|
||||
}
|
||||
|
||||
/// Features for the `hello` message.
|
||||
@@ -347,26 +342,37 @@ impl Hub {
|
||||
let pool = new_relay_pool(&self.connect, nickname);
|
||||
tokio::spawn(crate::tasks::pump_relays(self.clone(), pool.subscribe()));
|
||||
let old = std::mem::replace(&mut *self.relays.write().unwrap(), pool);
|
||||
let channels = old.channels().await;
|
||||
old.close_all().await;
|
||||
// Also the relays being opened now, which open no more in the old pool.
|
||||
let channels = old.close_all().await;
|
||||
drop(old);
|
||||
set_lookup_nickname(&self.lookup, nickname).await;
|
||||
self.lookup.set_nickname(&lookup_nickname(nickname)).await;
|
||||
let pool = self.relays();
|
||||
for cid in channels {
|
||||
if let Err(error) = pool.open(cid).await {
|
||||
warn!(cid, %error, "could not reopen relay");
|
||||
// A failure is logged by the pool.
|
||||
if pool.open(cid).await.is_err() && self.relay_wanted(cid) {
|
||||
let hub = self.clone();
|
||||
tokio::spawn(async move { hub.reopen_relay(cid).await });
|
||||
}
|
||||
}
|
||||
info!(nickname, "relays renamed");
|
||||
}
|
||||
|
||||
/// Pinned channels changed: open new ones, let removed ones idle out.
|
||||
pub(crate) async fn apply_pinned_channels(&self, old: &[u64], new: &[u64]) {
|
||||
let pool = self.relays();
|
||||
for cid in new.iter().filter(|c| !old.contains(c)) {
|
||||
if let Err(error) = pool.open(*cid).await {
|
||||
warn!(cid, %error, "could not open pinned relay");
|
||||
/// Open a channel's relay in the background, and while that fails, again
|
||||
/// for as long as it is wanted ([`Hub::reopen_relay`]).
|
||||
fn open_relay_soon(self: &Arc<Self>, cid: ChannelId) {
|
||||
let hub = self.clone();
|
||||
tokio::spawn(async move {
|
||||
// A failure is logged by the pool.
|
||||
if hub.relays().open(cid).await.is_err() {
|
||||
hub.reopen_relay(cid).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Pinned channels changed: open new ones, let removed ones idle out.
|
||||
pub(crate) fn apply_pinned_channels(self: &Arc<Self>, old: &[u64], new: &[u64]) {
|
||||
for cid in new.iter().filter(|c| !old.contains(c)) {
|
||||
self.open_relay_soon(*cid);
|
||||
}
|
||||
for cid in old.iter().filter(|c| !new.contains(c)) {
|
||||
// The idle teardown closes it once nobody reads it.
|
||||
@@ -374,6 +380,27 @@ impl Hub {
|
||||
}
|
||||
}
|
||||
|
||||
/// Someone reads the channel, or it is pinned.
|
||||
pub(crate) fn relay_wanted(&self, cid: ChannelId) -> bool {
|
||||
self.runtime().relay.pinned_channels.contains(&cid)
|
||||
|| self.readers.lock().unwrap().get(&cid).is_some_and(|(n, _)| *n > 0)
|
||||
}
|
||||
|
||||
/// Open a relay the server dropped again, waiting longer after each
|
||||
/// failure, for as long as it is wanted.
|
||||
pub(crate) async fn reopen_relay(&self, cid: ChannelId) {
|
||||
let mut attempt = 0;
|
||||
while self.relay_wanted(cid) {
|
||||
attempt += 1;
|
||||
tokio::time::sleep(self.connect.retry_delay(attempt)).await;
|
||||
// A failure is logged by the pool.
|
||||
if self.relays().open(cid).await.is_ok() {
|
||||
info!(channel = cid, attempt, "relay reopened");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Channels whose relay nobody needs any more.
|
||||
pub(crate) fn idle_relays(&self, rt: &Runtime) -> Vec<ChannelId> {
|
||||
let idle = std::time::Duration::from_secs(rt.relay.idle_teardown_secs);
|
||||
@@ -708,7 +735,15 @@ impl Hub {
|
||||
));
|
||||
}
|
||||
}
|
||||
self.relays().open(cid).await?;
|
||||
loop {
|
||||
let pool = self.relays();
|
||||
match pool.open(cid).await {
|
||||
// Replaced on the way (a new nickname): open in the new pool.
|
||||
Err(_) if pool.is_closed() => continue,
|
||||
result => result?,
|
||||
}
|
||||
break;
|
||||
}
|
||||
self.readers.lock().unwrap().entry(cid).or_insert((0, Instant::now())).0 += 1;
|
||||
Ok(())
|
||||
}
|
||||
@@ -751,16 +786,20 @@ impl Hub {
|
||||
}
|
||||
None => text.to_string(),
|
||||
};
|
||||
let full = relay_text(&rt.relay.format, &user.nickname, &relayed);
|
||||
// Posts go out under the user's nickname; `relay.format` only when the
|
||||
// session cannot take it.
|
||||
match target {
|
||||
ChatTarget::Server => {
|
||||
for part in voelin_model::split_message(&full, 1024) {
|
||||
self.lookup
|
||||
.send(
|
||||
&Command::new("sendtextmessage").arg("targetmode", 3).arg("msg", part),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
let _posting = self.lookup_posting.lock().await;
|
||||
post_as(
|
||||
&self.lookup.client().await,
|
||||
&lookup_nickname(&rt.relay.nickname),
|
||||
&user.nickname,
|
||||
&relayed,
|
||||
&rt.relay.format,
|
||||
|part| Command::new("sendtextmessage").arg("targetmode", 3).arg("msg", part),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
ChatTarget::Channel(cid) => {
|
||||
if !self.readers.lock().unwrap().contains_key(cid) {
|
||||
@@ -768,8 +807,7 @@ impl Hub {
|
||||
self.add_reader(*cid).await?;
|
||||
self.remove_reader(*cid);
|
||||
}
|
||||
// The pool's format is `{text}`: `full` is already formatted.
|
||||
self.relays().send(*cid, &user.nickname, &full).await?;
|
||||
self.relays().post(*cid, &user.nickname, &relayed, &rt.relay.format).await?;
|
||||
}
|
||||
ChatTarget::Private(_) => unreachable!("checked by require_post"),
|
||||
}
|
||||
@@ -797,15 +835,69 @@ impl Hub {
|
||||
fn new_relay_pool(connect: &Connect, nickname: &str) -> RelayPool {
|
||||
let mut config = RelayConfig::new(connect.clone());
|
||||
config.nickname = nickname.to_string();
|
||||
// Posts are formatted by the hub, with the current settings.
|
||||
config.format = "{text}".into();
|
||||
RelayPool::new(config)
|
||||
}
|
||||
|
||||
async fn set_lookup_nickname(lookup: &QueryClient, nickname: &str) {
|
||||
let _ = lookup
|
||||
.send(&Command::new("clientupdate").arg("client_nickname", format!("{nickname} Gateway")))
|
||||
.await;
|
||||
/// The lookup session's own name, given `relay.nickname`.
|
||||
fn lookup_nickname(nickname: &str) -> String {
|
||||
format!("{nickname} Gateway")
|
||||
}
|
||||
|
||||
/// What the gateway reads from the server once, at start.
|
||||
struct ServerFacts {
|
||||
version: String,
|
||||
is_ts6: bool,
|
||||
uid: String,
|
||||
name: String,
|
||||
needed_level: u8,
|
||||
default_channel: ChannelId,
|
||||
perm_ids: PermIds,
|
||||
}
|
||||
|
||||
impl ServerFacts {
|
||||
async fn load_until_it_works(lookup: &Lookup, connect: &Connect) -> Self {
|
||||
let mut attempt = 0;
|
||||
loop {
|
||||
attempt += 1;
|
||||
match Self::load(lookup).await {
|
||||
Ok(facts) => return facts,
|
||||
Err(error) => {
|
||||
let retry_in = connect.retry_delay(attempt);
|
||||
warn!(
|
||||
error = format!("{error:#}"),
|
||||
attempt,
|
||||
retry_in_s = retry_in.as_secs_f32(),
|
||||
"could not read the server's settings; trying again"
|
||||
);
|
||||
tokio::time::sleep(retry_in).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn load(lookup: &Lookup) -> Result<Self> {
|
||||
// Failures are logged by the caller.
|
||||
let info = lookup.send_quiet(&Command::new("serverinfo")).await.context("serverinfo")?;
|
||||
let info = info.first().context("empty serverinfo")?;
|
||||
let version = info.get("virtualserver_version").unwrap_or_default().to_string();
|
||||
let channels = lookup
|
||||
.send_quiet(&Command::new("channellist").flag("flags"))
|
||||
.await
|
||||
.context("channellist")?;
|
||||
Ok(Self {
|
||||
is_ts6: matches!(ServerFlavor::from_version_string(&version), ServerFlavor::Ts6(_)),
|
||||
version,
|
||||
uid: info.get("virtualserver_unique_identifier").unwrap_or_default().to_string(),
|
||||
name: info.get("virtualserver_name").unwrap_or_default().to_string(),
|
||||
needed_level: info.parse("virtualserver_needed_identity_security_level").unwrap_or(8),
|
||||
default_channel: channels
|
||||
.iter()
|
||||
.find(|r| r.flag("channel_flag_default") == Some(true))
|
||||
.and_then(|r| r.parse("cid"))
|
||||
.unwrap_or(1),
|
||||
perm_ids: PermIds::load(lookup).await.context("looking up permission ids")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Split `text` by a topic format like `[#{topic}] {text}` into title and
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
//! Where the log goes: standard output (journald, `docker logs`) and, with
|
||||
//! `log.file`, a file as well.
|
||||
//!
|
||||
//! What is logged comes from `log.level` (`TSGW_LOG_LEVEL`), else
|
||||
//! `RUST_LOG`, else [`DEFAULT_FILTER`]. The libraries that log every packet
|
||||
//! stay at warnings unless the filter names them, so `debug` stays readable.
|
||||
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{self, IsTerminal, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use tracing::warn;
|
||||
use tracing_subscriber::prelude::*;
|
||||
use tracing_subscriber::{EnvFilter, fmt};
|
||||
|
||||
use crate::config::Bootstrap;
|
||||
|
||||
/// What is logged when nothing says otherwise.
|
||||
pub const DEFAULT_FILTER: &str = "info,russh=warn,hyper=warn,h2=warn,tower=warn,tungstenite=warn";
|
||||
|
||||
/// Libraries kept at warnings unless a filter names them.
|
||||
const NOISY: &[&str] = &["russh", "hyper", "h2", "tower", "tungstenite", "tokio_tungstenite"];
|
||||
|
||||
/// One log file's limit before it moves aside.
|
||||
const MAX_BYTES: u64 = 20 << 20;
|
||||
/// Files kept: the one written and the ones moved aside.
|
||||
const KEEP: usize = 5;
|
||||
|
||||
/// Start logging. Problems with the filter or the file are logged, not
|
||||
/// fatal. Returns the log file in use.
|
||||
pub fn init(boot: &Bootstrap) -> Option<PathBuf> {
|
||||
let rust_log = std::env::var("RUST_LOG").ok();
|
||||
let (directives, from) = match (&boot.log_level, &rust_log) {
|
||||
(Some(level), _) => (level.as_str(), "log.level"),
|
||||
(None, Some(rust_log)) if !rust_log.trim().is_empty() => (rust_log.as_str(), "RUST_LOG"),
|
||||
_ => (DEFAULT_FILTER, "default"),
|
||||
};
|
||||
let (filter, bad_filter) = match EnvFilter::try_new(quiet_noisy(directives)) {
|
||||
Ok(filter) => (filter, None),
|
||||
Err(error) => (EnvFilter::new(DEFAULT_FILTER), Some(error)),
|
||||
};
|
||||
let ansi = io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none();
|
||||
let console = fmt::layer().with_ansi(ansi);
|
||||
let file = boot.log_file.as_deref().map(|path| (path, LogFile::open(path, KEEP, MAX_BYTES)));
|
||||
let to_file = match &file {
|
||||
Some((_, Ok(log))) => {
|
||||
let log = log.clone();
|
||||
Some(fmt::layer().with_ansi(false).with_writer(move || log.clone()))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
tracing_subscriber::registry().with(filter).with(console).with(to_file).init();
|
||||
if let Some(error) = bad_filter {
|
||||
warn!(filter = directives, from, %error, "not a log filter; using the default");
|
||||
}
|
||||
match file {
|
||||
Some((path, Ok(_))) => Some(path.to_path_buf()),
|
||||
Some((path, Err(error))) => {
|
||||
warn!(
|
||||
file = %path.display(),
|
||||
%error,
|
||||
"cannot write the log file; logging to standard output only"
|
||||
);
|
||||
None
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `directives` with the libraries in [`NOISY`] it does not name at
|
||||
/// warnings.
|
||||
fn quiet_noisy(directives: &str) -> String {
|
||||
let named = |lib: &str| {
|
||||
directives.split(',').any(|d| {
|
||||
let target = d.trim().split(['=', '[']).next().unwrap_or_default();
|
||||
target == lib || target.starts_with(&format!("{lib}::"))
|
||||
})
|
||||
};
|
||||
let mut filter = directives.trim().trim_end_matches(',').to_string();
|
||||
for lib in NOISY.iter().filter(|lib| !named(lib)) {
|
||||
filter.push_str(&format!(",{lib}=warn"));
|
||||
}
|
||||
filter
|
||||
}
|
||||
|
||||
/// A log file written by appending, also across restarts. When it would
|
||||
/// grow past its limit it moves to `<name>.1.<ext>` (the older ones one
|
||||
/// further along, the oldest dropped) and a new one starts. Clones write to
|
||||
/// the same file.
|
||||
#[derive(Clone)]
|
||||
pub struct LogFile(Arc<Mutex<Inner>>);
|
||||
|
||||
struct Inner {
|
||||
path: PathBuf,
|
||||
file: File,
|
||||
written: u64,
|
||||
keep: usize,
|
||||
max: u64,
|
||||
}
|
||||
|
||||
impl LogFile {
|
||||
pub fn open(path: &Path, keep: usize, max: u64) -> io::Result<Self> {
|
||||
if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let file = append(path)?;
|
||||
let written = file.metadata()?.len();
|
||||
let inner = Inner { path: path.to_path_buf(), file, written, keep: keep.max(1), max };
|
||||
Ok(Self(Arc::new(Mutex::new(inner))))
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for LogFile {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
let mut inner = self.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if inner.written > 0 && inner.written + buf.len() as u64 > inner.max {
|
||||
rotate(&inner.path, inner.keep);
|
||||
// If no new file can be made, the moved one goes on: moving the
|
||||
// files along on every line would soon drop them all.
|
||||
if let Ok(file) = append(&inner.path) {
|
||||
inner.file = file;
|
||||
}
|
||||
inner.written = 0;
|
||||
}
|
||||
let n = inner.file.write(buf)?;
|
||||
inner.written += n as u64;
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner).file.flush()
|
||||
}
|
||||
}
|
||||
|
||||
fn append(path: &Path) -> io::Result<File> {
|
||||
OpenOptions::new().create(true).append(true).open(path)
|
||||
}
|
||||
|
||||
/// `tsgw.log` as the `n`th one moved aside: `tsgw.1.log`.
|
||||
fn moved_aside(path: &Path, n: usize) -> PathBuf {
|
||||
let stem = path.file_stem().unwrap_or_default().to_string_lossy();
|
||||
let name = match path.extension() {
|
||||
Some(ext) => format!("{stem}.{n}.{}", ext.to_string_lossy()),
|
||||
None => format!("{stem}.{n}"),
|
||||
};
|
||||
path.with_file_name(name)
|
||||
}
|
||||
|
||||
/// Move the files one along; the oldest goes.
|
||||
fn rotate(path: &Path, keep: usize) {
|
||||
if keep <= 1 {
|
||||
let _ = std::fs::remove_file(path);
|
||||
return;
|
||||
}
|
||||
let _ = std::fs::remove_file(moved_aside(path, keep - 1));
|
||||
for n in (1..keep - 1).rev() {
|
||||
let _ = std::fs::rename(moved_aside(path, n), moved_aside(path, n + 1));
|
||||
}
|
||||
let _ = std::fs::rename(path, moved_aside(path, 1));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn noisy_libraries_stay_quiet_unless_named() {
|
||||
assert_eq!(
|
||||
quiet_noisy("debug"),
|
||||
"debug,russh=warn,hyper=warn,h2=warn,tower=warn,tungstenite=warn,tokio_tungstenite=warn"
|
||||
);
|
||||
let named = quiet_noisy("info,voelin_query=trace,russh=debug,hyper::proto=info,");
|
||||
assert!(named.starts_with("info,voelin_query=trace,russh=debug,hyper::proto=info,h2=warn"));
|
||||
assert!(!named.contains("russh=warn") && !named.contains("hyper=warn"));
|
||||
assert!(EnvFilter::try_new(quiet_noisy(DEFAULT_FILTER)).is_ok());
|
||||
assert_eq!(quiet_noisy(DEFAULT_FILTER).matches("russh").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_is_appended_to_and_moved_aside_when_full() {
|
||||
let dir = std::env::temp_dir().join(format!("tsgw-log-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let path = dir.join("logs").join("tsgw.log");
|
||||
let read = |p: PathBuf| std::fs::read_to_string(p).ok();
|
||||
LogFile::open(&path, 3, 12).unwrap().write_all(b"start 1\n").unwrap();
|
||||
// A restart goes on in the same file.
|
||||
let log = LogFile::open(&path, 3, 12).unwrap();
|
||||
log.clone().write_all(b"two\n").unwrap();
|
||||
assert_eq!(read(path.clone()).as_deref(), Some("start 1\ntwo\n"));
|
||||
// Full: moved aside, and the oldest goes.
|
||||
log.clone().write_all(b"three\n").unwrap();
|
||||
log.clone().write_all(b"four 4\n").unwrap();
|
||||
log.clone().write_all(b"five 5\n").unwrap();
|
||||
assert_eq!(read(path.clone()).as_deref(), Some("five 5\n"));
|
||||
assert_eq!(read(dir.join("logs/tsgw.1.log")).as_deref(), Some("four 4\n"));
|
||||
assert_eq!(read(dir.join("logs/tsgw.2.log")).as_deref(), Some("three\n"));
|
||||
assert_eq!(read(dir.join("logs/tsgw.3.log")), None, "three files in all");
|
||||
assert_eq!(moved_aside(Path::new("/var/log/tsgw"), 2), Path::new("/var/log/tsgw.2"));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
//! The lookup query connection: logins, permission checks and server chat
|
||||
//! posts go through it. When the TeamSpeak server drops it (a restart, a
|
||||
//! network problem) it is opened again, and commands sent meanwhile wait
|
||||
//! for it a little.
|
||||
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tokio::sync::watch;
|
||||
use tracing::{debug, error, info, warn};
|
||||
use voelin_query::{Command, Connect, QueryClient, Row, Transport, attempt_worth_a_warning};
|
||||
|
||||
/// How long a command waits for a lost connection to come back.
|
||||
const RECONNECT_WAIT: Duration = Duration::from_secs(5);
|
||||
|
||||
pub struct Lookup {
|
||||
connect: Connect,
|
||||
client: watch::Sender<QueryClient>,
|
||||
/// The session's nickname, set again on every new connection.
|
||||
nickname: Mutex<String>,
|
||||
/// The connection's client id while it is up: server chat from it is the
|
||||
/// gateway's own. Not kept across reconnects: after a server restart the
|
||||
/// old id may be a user's.
|
||||
own_id: Mutex<Option<u16>>,
|
||||
}
|
||||
|
||||
impl Lookup {
|
||||
/// Log in, trying until it works, and keep the connection open from
|
||||
/// then on.
|
||||
pub async fn open(mut connect: Connect, nickname: String) -> Arc<Self> {
|
||||
connect.line.label = "lookup".into();
|
||||
let (client, own_id) = open_until_it_works(&connect, &nickname).await;
|
||||
let lookup = Arc::new(Self {
|
||||
connect,
|
||||
client: watch::channel(client).0,
|
||||
nickname: Mutex::new(nickname),
|
||||
own_id: Mutex::new(Some(own_id)),
|
||||
});
|
||||
tokio::spawn(keep_open(Arc::downgrade(&lookup)));
|
||||
lookup
|
||||
}
|
||||
|
||||
/// The connection is up.
|
||||
pub fn is_up(&self) -> bool {
|
||||
!self.client.borrow().is_closed()
|
||||
}
|
||||
|
||||
/// The connection's client id, while it is up.
|
||||
pub fn own_id(&self) -> Option<u16> {
|
||||
*self.own_id.lock().unwrap()
|
||||
}
|
||||
|
||||
/// The id is the connection's own.
|
||||
pub fn is_own(&self, id: u16) -> bool {
|
||||
self.own_id() == Some(id)
|
||||
}
|
||||
|
||||
/// Send a command; when the connection is lost on the way, once more
|
||||
/// on the new one. A failure is logged with the command's name.
|
||||
pub async fn send(&self, cmd: &Command) -> voelin_query::Result<Vec<Row>> {
|
||||
let result = self.send_quiet(cmd).await;
|
||||
if let Err(error) = &result {
|
||||
warn!(command = %cmd.name, %error, "ServerQuery command failed");
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// [`Lookup::send`] for callers that log a failure themselves.
|
||||
pub async fn send_quiet(&self, cmd: &Command) -> voelin_query::Result<Vec<Row>> {
|
||||
let mut current = self.client.subscribe();
|
||||
let client = current.borrow_and_update().clone();
|
||||
match client.send(cmd).await {
|
||||
Err(error) if lost(&error, &client) => {
|
||||
match tokio::time::timeout(RECONNECT_WAIT, current.changed()).await {
|
||||
Ok(Ok(())) => {
|
||||
let client = current.borrow_and_update().clone();
|
||||
client.send(cmd).await
|
||||
}
|
||||
_ => Err(error),
|
||||
}
|
||||
}
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
|
||||
/// The connection, after waiting a little for it if it is lost.
|
||||
pub async fn client(&self) -> QueryClient {
|
||||
let mut current = self.client.subscribe();
|
||||
let client = current.borrow_and_update().clone();
|
||||
if !client.is_closed() {
|
||||
return client;
|
||||
}
|
||||
match tokio::time::timeout(RECONNECT_WAIT, current.changed()).await {
|
||||
Ok(Ok(())) => current.borrow_and_update().clone(),
|
||||
_ => client,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rename the session, now and after reconnects.
|
||||
pub async fn set_nickname(&self, nickname: &str) {
|
||||
*self.nickname.lock().unwrap() = nickname.to_string();
|
||||
set_nickname(&self.client().await, nickname).await;
|
||||
}
|
||||
|
||||
/// Log the address the server sees the gateway's queries come from: it
|
||||
/// counts the commands of each address for its flood protection, unless
|
||||
/// the address is in its `query_ip_allowlist.txt`.
|
||||
pub async fn log_address(&self, allowlisted: bool) {
|
||||
let Some(own) = self.own_id() else { return };
|
||||
let Ok(rows) = self.send(&Command::new("clientlist").flag("ip")).await else { return };
|
||||
let address = rows
|
||||
.iter()
|
||||
.find(|r| r.parse::<u16>("clid") == Some(own))
|
||||
.and_then(|r| r.get("connection_client_ip"));
|
||||
let Some(address) = address.filter(|a| !a.is_empty()) else {
|
||||
debug!("the server did not say where the gateway's queries come from");
|
||||
return;
|
||||
};
|
||||
let loopback = address.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback());
|
||||
match (allowlisted, loopback) {
|
||||
(true, _) => info!(
|
||||
address,
|
||||
"the TeamSpeak server sees the gateway's queries coming from this address"
|
||||
),
|
||||
(false, true) => info!(
|
||||
address,
|
||||
hint = "the server's query_ip_allowlist.txt has this address by default; if it still \
|
||||
does, set query.allowlisted = true so the gateway stops slowing itself down",
|
||||
"the TeamSpeak server sees the gateway's queries coming from this address"
|
||||
),
|
||||
(false, false) => info!(
|
||||
address,
|
||||
hint = "add this address to the server's query_ip_allowlist.txt (read again within \
|
||||
seconds) and set query.allowlisted = true; until then the server's flood \
|
||||
protection limits the gateway",
|
||||
"the TeamSpeak server sees the gateway's queries coming from this address"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The error means the connection is gone, not that the command failed.
|
||||
fn lost(error: &voelin_query::Error, client: &QueryClient) -> bool {
|
||||
use voelin_query::Error;
|
||||
matches!(error, Error::Closed | Error::Io(_) | Error::Ssh(_)) || client.is_closed()
|
||||
}
|
||||
|
||||
/// Wait for the connection to close, open it again, repeat.
|
||||
async fn keep_open(lookup: Weak<Lookup>) {
|
||||
loop {
|
||||
let Some(client) = lookup.upgrade().map(|l| l.client.borrow().clone()) else { return };
|
||||
client.closed().await;
|
||||
let Some(lookup) = lookup.upgrade() else { return };
|
||||
let lost_at = Instant::now();
|
||||
*lookup.own_id.lock().unwrap() = None;
|
||||
warn!(addr = %lookup.connect.addr, "lookup query connection lost; reconnecting");
|
||||
let nickname = lookup.nickname.lock().unwrap().clone();
|
||||
let (client, own_id) = open_until_it_works(&lookup.connect, &nickname).await;
|
||||
*lookup.own_id.lock().unwrap() = Some(own_id);
|
||||
lookup.client.send_replace(client);
|
||||
info!(down_ms = lost_at.elapsed().as_millis() as u64, "lookup query connection restored");
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a connection, waiting longer after each failure.
|
||||
async fn open_until_it_works(connect: &Connect, nickname: &str) -> (QueryClient, u16) {
|
||||
let started = Instant::now();
|
||||
let transport = match connect.transport {
|
||||
Transport::Ssh => "ssh",
|
||||
Transport::Raw => "raw",
|
||||
Transport::Http => "http",
|
||||
};
|
||||
let mut attempt = 0;
|
||||
loop {
|
||||
attempt += 1;
|
||||
match open_once(connect, nickname).await {
|
||||
Ok(opened) => {
|
||||
let elapsed_ms = started.elapsed().as_millis() as u64;
|
||||
info!(addr = %connect.addr, transport, attempt, elapsed_ms, "query login ok");
|
||||
return opened;
|
||||
}
|
||||
Err(e) => {
|
||||
let retry_in = connect.retry_delay(attempt);
|
||||
let retry_in_s = retry_in.as_secs_f32();
|
||||
let refused = matches!(&e, voelin_query::Error::SshAuth)
|
||||
|| matches!(&e, voelin_query::Error::Query(q) if q.id == ERR_INVALID_LOGIN);
|
||||
if refused {
|
||||
error!(
|
||||
addr = %connect.addr,
|
||||
user = %connect.user,
|
||||
attempt,
|
||||
retry_in_s,
|
||||
"the TeamSpeak server refused the query login; check query.user and the password"
|
||||
);
|
||||
} else if attempt_worth_a_warning(attempt) {
|
||||
warn!(
|
||||
addr = %connect.addr,
|
||||
error = %e,
|
||||
attempt,
|
||||
retry_in_s,
|
||||
"query login failed; trying again"
|
||||
);
|
||||
} else {
|
||||
debug!(
|
||||
addr = %connect.addr,
|
||||
error = %e,
|
||||
attempt,
|
||||
retry_in_s,
|
||||
"query login failed; trying again"
|
||||
);
|
||||
}
|
||||
tokio::time::sleep(retry_in).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `login` with a wrong name or password.
|
||||
const ERR_INVALID_LOGIN: u32 = 520;
|
||||
|
||||
async fn open_once(connect: &Connect, nickname: &str) -> voelin_query::Result<(QueryClient, u16)> {
|
||||
let (client, _) = QueryClient::connect(connect).await?;
|
||||
let own_id = client.own_client_id().await?;
|
||||
set_nickname(&client, nickname).await;
|
||||
Ok((client, own_id))
|
||||
}
|
||||
|
||||
/// The name is cosmetic: failing keeps the server-assigned one.
|
||||
async fn set_nickname(client: &QueryClient, nickname: &str) {
|
||||
let _ = client.send(&Command::new("clientupdate").arg("client_nickname", nickname)).await;
|
||||
}
|
||||
@@ -9,6 +9,8 @@ mod config;
|
||||
mod db;
|
||||
mod features;
|
||||
mod hub;
|
||||
mod logging;
|
||||
mod lookup;
|
||||
mod perms;
|
||||
mod session;
|
||||
mod settings;
|
||||
@@ -17,20 +19,27 @@ mod tasks;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::future::IntoFuture;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::Result;
|
||||
use axum::extract::{State, WebSocketUpgrade};
|
||||
use axum::http::{HeaderMap, header};
|
||||
use axum::response::IntoResponse;
|
||||
use anyhow::{Context, Result};
|
||||
use axum::extract::{ConnectInfo, State, WebSocketUpgrade};
|
||||
use axum::http::{HeaderMap, StatusCode, header};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::get;
|
||||
use axum::{Json, Router};
|
||||
use axum::{Extension, Json, Router};
|
||||
use clap::Parser;
|
||||
use tracing::info;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use tokio::sync::watch;
|
||||
use tracing::{debug, info, warn};
|
||||
use voelin_query::Transport;
|
||||
|
||||
use crate::config::Bootstrap;
|
||||
use crate::hub::Hub;
|
||||
use crate::session::Peer;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(version, about)]
|
||||
@@ -44,54 +53,207 @@ struct Args {
|
||||
set: Vec<String>,
|
||||
}
|
||||
|
||||
/// How long a WebSocket connection made while the gateway starts waits for
|
||||
/// the TeamSpeak server before it is refused.
|
||||
const START_WAIT: Duration = Duration::from_secs(10);
|
||||
/// How long open connections get to close at shutdown.
|
||||
const CLOSE_WAIT: Duration = Duration::from_secs(2);
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")),
|
||||
)
|
||||
.init();
|
||||
let args = Args::parse();
|
||||
let layers = config::Layers::load(&args.config, &args.set)?;
|
||||
let bind = layers.bootstrap()?.bind;
|
||||
let hub = Hub::start(layers).await?;
|
||||
tokio::spawn(reload_on_hangup(hub.clone()));
|
||||
let listener = tokio::net::TcpListener::bind(bind).await?;
|
||||
info!(%bind, "listening");
|
||||
axum::serve(listener, router(hub)).with_graceful_shutdown(shutdown()).await?;
|
||||
let boot = layers.bootstrap()?;
|
||||
let log_file = logging::init(&boot);
|
||||
info!(
|
||||
version = env!("CARGO_PKG_VERSION"),
|
||||
config = %args.config.display(),
|
||||
bind = %boot.bind,
|
||||
public_url = boot.public_url.as_deref(),
|
||||
gateway_id = %boot.gateway_id(),
|
||||
voice_port = boot.voice_port,
|
||||
query_transport = transport_name(boot.transport),
|
||||
query_addr = %boot.addr,
|
||||
query_user = %boot.user,
|
||||
query_password = if boot.password.is_some() { "set" } else { "none" },
|
||||
allowlisted = boot.allowlisted,
|
||||
db = %boot.db_path.display(),
|
||||
log_file = log_file.as_ref().map(|p| p.display().to_string()),
|
||||
"tsgw starting"
|
||||
);
|
||||
// Listen at once: apps that come while the TeamSpeak server is not
|
||||
// reachable yet wait for it a little instead of being turned away.
|
||||
let listener = tokio::net::TcpListener::bind(boot.bind)
|
||||
.await
|
||||
.with_context(|| format!("cannot listen on {}", boot.bind))?;
|
||||
info!(
|
||||
bind = %boot.bind,
|
||||
public_url = boot.public_url.as_deref(),
|
||||
well_known = boot.public_url.as_deref().unwrap_or("ws://<host the app asked for>/v1"),
|
||||
"listening"
|
||||
);
|
||||
let app = App::new(boot);
|
||||
let service = router(app.clone()).into_make_service_with_connect_info::<SocketAddr>();
|
||||
let server = axum::serve(listener, service).with_graceful_shutdown(shutdown(app.clone()));
|
||||
let mut server = std::pin::pin!(server.into_future());
|
||||
tokio::select! {
|
||||
// Stopped before the TeamSpeak server answered.
|
||||
served = &mut server => return served.context("serving failed"),
|
||||
hub = Hub::start(layers) => {
|
||||
let hub = hub?;
|
||||
app.hub.send_replace(Some(hub.clone()));
|
||||
tokio::spawn(reload_on_hangup(hub));
|
||||
}
|
||||
}
|
||||
server.await.context("serving failed")?;
|
||||
app.closed_within(CLOSE_WAIT).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn router(hub: Arc<Hub>) -> Router {
|
||||
fn transport_name(transport: Transport) -> &'static str {
|
||||
match transport {
|
||||
Transport::Ssh => "ssh",
|
||||
Transport::Raw => "raw",
|
||||
Transport::Http => "http",
|
||||
}
|
||||
}
|
||||
|
||||
/// What the HTTP handlers share.
|
||||
pub struct App {
|
||||
boot: Bootstrap,
|
||||
/// The hub, once the gateway is logged in to the TeamSpeak server.
|
||||
hub: watch::Sender<Option<Arc<Hub>>>,
|
||||
/// Turns true at shutdown, which closes the WebSocket connections.
|
||||
stop: watch::Sender<bool>,
|
||||
/// WebSocket connections open now, and since the start.
|
||||
open: AtomicUsize,
|
||||
connections: AtomicU64,
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn new(boot: Bootstrap) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
boot,
|
||||
hub: watch::channel(None).0,
|
||||
stop: watch::channel(false).0,
|
||||
open: AtomicUsize::new(0),
|
||||
connections: AtomicU64::new(0),
|
||||
})
|
||||
}
|
||||
|
||||
/// An app for a hub that has started.
|
||||
#[cfg(test)]
|
||||
fn started(boot: Bootstrap, hub: Arc<Hub>) -> Arc<Self> {
|
||||
let app = Self::new(boot);
|
||||
app.hub.send_replace(Some(hub));
|
||||
app
|
||||
}
|
||||
|
||||
fn hub(&self) -> Option<Arc<Hub>> {
|
||||
self.hub.borrow().clone()
|
||||
}
|
||||
|
||||
/// The hub, waiting up to `wait` for it to start.
|
||||
async fn hub_within(&self, wait: Duration) -> Option<Arc<Hub>> {
|
||||
let mut hub = self.hub.subscribe();
|
||||
let started = tokio::time::timeout(wait, hub.wait_for(Option::is_some)).await;
|
||||
started.ok()?.ok()?.clone()
|
||||
}
|
||||
|
||||
/// Wait for the WebSocket connections to close, at most `wait`.
|
||||
async fn closed_within(&self, wait: Duration) {
|
||||
let deadline = Instant::now() + wait;
|
||||
while self.open.load(Ordering::Relaxed) > 0 && Instant::now() < deadline {
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn router(app: Arc<App>) -> Router {
|
||||
Router::new()
|
||||
.route("/v1", get(ws))
|
||||
.route("/health", get(|| async { "ok" }))
|
||||
.route("/health", get(health))
|
||||
.route("/.well-known/tsgw", get(well_known))
|
||||
.with_state(hub)
|
||||
.with_state(app)
|
||||
}
|
||||
|
||||
/// `ok` while the gateway is logged in to the TeamSpeak server and watching
|
||||
/// it; otherwise 503 and what is missing.
|
||||
async fn health(State(app): State<Arc<App>>) -> (StatusCode, String) {
|
||||
let Some(hub) = app.hub() else {
|
||||
let starting = "starting: not logged in to the TeamSpeak server yet";
|
||||
return (StatusCode::SERVICE_UNAVAILABLE, starting.into());
|
||||
};
|
||||
let (query, observer) = (hub.lookup.is_up(), hub.observer.is_connected());
|
||||
if query && observer {
|
||||
return (StatusCode::OK, "ok".into());
|
||||
}
|
||||
let state = |up| if up { "up" } else { "down" };
|
||||
let text = format!("query: {}, observer: {}", state(query), state(observer));
|
||||
(StatusCode::SERVICE_UNAVAILABLE, text)
|
||||
}
|
||||
|
||||
/// Where apps reach this gateway, for those that find it by asking the
|
||||
/// server's host on the default port (docs/gateway-admin.md): the
|
||||
/// configured public URL, else this listener as the request reached it.
|
||||
async fn well_known(State(hub): State<Arc<Hub>>, headers: HeaderMap) -> Json<serde_json::Value> {
|
||||
let url = hub.boot.public_url.clone().unwrap_or_else(|| {
|
||||
let host = headers.get(header::HOST).and_then(|h| h.to_str().ok()).unwrap_or("localhost");
|
||||
format!("ws://{host}/v1")
|
||||
});
|
||||
async fn well_known(State(app): State<Arc<App>>, headers: HeaderMap) -> Json<serde_json::Value> {
|
||||
let host = headers.get(header::HOST).and_then(|h| h.to_str().ok());
|
||||
let url = app
|
||||
.boot
|
||||
.public_url
|
||||
.clone()
|
||||
.unwrap_or_else(|| format!("ws://{}/v1", host.unwrap_or("localhost")));
|
||||
debug!(host, answer = %url, "asked where the gateway is");
|
||||
Json(serde_json::json!({ "url": url }))
|
||||
}
|
||||
|
||||
async fn ws(State(hub): State<Arc<Hub>>, upgrade: WebSocketUpgrade) -> impl IntoResponse {
|
||||
async fn ws(
|
||||
State(app): State<Arc<App>>,
|
||||
connect_info: Option<Extension<ConnectInfo<SocketAddr>>>,
|
||||
headers: HeaderMap,
|
||||
upgrade: WebSocketUpgrade,
|
||||
) -> Response {
|
||||
let text = |name: header::HeaderName| {
|
||||
headers.get(name).and_then(|v| v.to_str().ok()).map(str::to_owned)
|
||||
};
|
||||
let peer = Peer {
|
||||
id: app.connections.fetch_add(1, Ordering::Relaxed) + 1,
|
||||
addr: connect_info.map(|Extension(ConnectInfo(addr))| addr),
|
||||
forwarded_for: text(header::HeaderName::from_static("x-forwarded-for")),
|
||||
user_agent: text(header::USER_AGENT),
|
||||
};
|
||||
let mut stop = app.stop.subscribe();
|
||||
// Not held up by the wait at shutdown, which waits for open requests.
|
||||
let hub = tokio::select! {
|
||||
hub = app.hub_within(START_WAIT) => hub,
|
||||
_ = stop.wait_for(|stopping| *stopping) => None,
|
||||
};
|
||||
if *stop.borrow_and_update() {
|
||||
debug!(id = peer.id, peer = %peer.address(), "websocket refused: shutting down");
|
||||
return (StatusCode::SERVICE_UNAVAILABLE, "the gateway is stopping").into_response();
|
||||
}
|
||||
let Some(hub) = hub else {
|
||||
warn!(
|
||||
id = peer.id,
|
||||
peer = %peer.address(),
|
||||
"websocket refused: not logged in to the TeamSpeak server yet"
|
||||
);
|
||||
return (StatusCode::SERVICE_UNAVAILABLE, "the gateway is starting").into_response();
|
||||
};
|
||||
upgrade
|
||||
.protocols([voelin_gateway_proto::SUBPROTOCOL])
|
||||
.on_upgrade(move |socket| session::run(hub, socket))
|
||||
.on_upgrade(move |socket| async move {
|
||||
app.open.fetch_add(1, Ordering::Relaxed);
|
||||
session::run(hub, socket, peer, stop).await;
|
||||
app.open.fetch_sub(1, Ordering::Relaxed);
|
||||
})
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// `SIGHUP` reads the configuration file again.
|
||||
#[cfg(unix)]
|
||||
async fn reload_on_hangup(hub: Arc<Hub>) {
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
use tracing::warn;
|
||||
let Ok(mut hangup) = signal(SignalKind::hangup()) else { return };
|
||||
while hangup.recv().await.is_some() {
|
||||
if let Err(error) = hub.settings.reload() {
|
||||
@@ -103,7 +265,31 @@ async fn reload_on_hangup(hub: Arc<Hub>) {
|
||||
#[cfg(not(unix))]
|
||||
async fn reload_on_hangup(_hub: Arc<Hub>) {}
|
||||
|
||||
async fn shutdown() {
|
||||
async fn shutdown(app: Arc<App>) {
|
||||
terminated().await;
|
||||
info!(connections = app.open.load(Ordering::Relaxed), "shutting down");
|
||||
app.stop.send_replace(true);
|
||||
}
|
||||
|
||||
/// Ctrl-C, or `SIGTERM` (`systemctl stop`, `docker stop`: as the
|
||||
/// container's first process tsgw gets no default handling of it).
|
||||
#[cfg(unix)]
|
||||
async fn terminated() {
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
match signal(SignalKind::terminate()) {
|
||||
Ok(mut term) => {
|
||||
tokio::select! {
|
||||
_ = tokio::signal::ctrl_c() => {}
|
||||
_ = term.recv() => {}
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
async fn terminated() {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
info!("shutting down");
|
||||
}
|
||||
@@ -10,7 +10,9 @@ use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use voelin_gateway_proto::PermRule;
|
||||
use voelin_query::{Command, QueryClient, Row};
|
||||
use voelin_query::{Command, Row};
|
||||
|
||||
use crate::lookup::Lookup;
|
||||
|
||||
const CACHE_TTL: Duration = Duration::from_secs(60);
|
||||
|
||||
@@ -87,7 +89,8 @@ pub struct PermIds {
|
||||
}
|
||||
|
||||
impl PermIds {
|
||||
pub async fn load(client: &QueryClient) -> voelin_query::Result<Self> {
|
||||
/// Look the ids up. Failures are logged here or by the caller.
|
||||
pub async fn load(client: &Lookup) -> voelin_query::Result<Self> {
|
||||
let names = [
|
||||
"i_channel_join_power",
|
||||
"i_channel_needed_join_power",
|
||||
@@ -98,7 +101,8 @@ impl PermIds {
|
||||
];
|
||||
let mut ids = [0u32; 6];
|
||||
for (i, name) in names.iter().enumerate() {
|
||||
let rows = client.send(&Command::new("permidgetbyname").arg("permsid", name)).await?;
|
||||
let rows =
|
||||
client.send_quiet(&Command::new("permidgetbyname").arg("permsid", name)).await?;
|
||||
ids[i] = rows.first().and_then(|r| r.parse("permid")).ok_or_else(|| {
|
||||
voelin_query::Error::Protocol(format!("unknown permission {name}"))
|
||||
})?;
|
||||
@@ -108,8 +112,16 @@ impl PermIds {
|
||||
let mut optional = [0u32; 2];
|
||||
for (i, name) in ["b_channel_modify_name", "b_virtualserver_modify_name"].iter().enumerate()
|
||||
{
|
||||
match client.send(&Command::new("permidgetbyname").arg("permsid", name)).await {
|
||||
match client.send_quiet(&Command::new("permidgetbyname").arg("permsid", name)).await {
|
||||
Ok(rows) => optional[i] = rows.first().and_then(|r| r.parse("permid")).unwrap_or(0),
|
||||
// More commands now would get the gateway banned.
|
||||
Err(voelin_query::Error::Query(e)) if e.is_flood() => {
|
||||
tracing::warn!(
|
||||
name,
|
||||
"the server's flood protection refused looking up a permission; its default grants nobody"
|
||||
);
|
||||
break;
|
||||
}
|
||||
Err(error) => tracing::warn!(%error, name, "unknown permission"),
|
||||
}
|
||||
}
|
||||
@@ -160,7 +172,7 @@ pub struct GroupResolver {
|
||||
impl GroupResolver {
|
||||
pub async fn server_groups(
|
||||
&self,
|
||||
client: &QueryClient,
|
||||
client: &Lookup,
|
||||
cldbid: u64,
|
||||
) -> voelin_query::Result<Vec<u64>> {
|
||||
if let Some((at, groups)) = self.server.lock().unwrap().get(&cldbid)
|
||||
@@ -177,7 +189,7 @@ impl GroupResolver {
|
||||
|
||||
pub async fn channel_groups(
|
||||
&self,
|
||||
client: &QueryClient,
|
||||
client: &Lookup,
|
||||
cldbid: u64,
|
||||
cid: u64,
|
||||
) -> voelin_query::Result<Vec<u64>> {
|
||||
@@ -231,7 +243,7 @@ impl PermResolver {
|
||||
|
||||
pub async fn entries(
|
||||
&self,
|
||||
client: &QueryClient,
|
||||
client: &Lookup,
|
||||
cldbid: u64,
|
||||
cid: u64,
|
||||
) -> voelin_query::Result<Vec<Entry>> {
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
//! One WebSocket client.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use axum::extract::ws::{Message, WebSocket};
|
||||
use axum::extract::ws::{CloseFrame, Message, WebSocket, close_code};
|
||||
use base64::prelude::*;
|
||||
use rand::RngExt;
|
||||
use serde::Deserialize;
|
||||
use tokio::sync::broadcast::error::RecvError;
|
||||
use tracing::{debug, info};
|
||||
use tokio::sync::watch;
|
||||
use tracing::{Instrument, Level, debug, info, info_span, warn};
|
||||
use voelin_gateway_proto::{ClientMsg, Envelope, ErrorCode, EventInfo, ServerMsg, feature};
|
||||
use voelin_model::{ChatTarget, Presence};
|
||||
use voelin_observer::ObserverEvent;
|
||||
@@ -53,13 +55,50 @@ struct Session {
|
||||
actions: RateLimit,
|
||||
}
|
||||
|
||||
/// Enough of an envelope to answer one that did not parse.
|
||||
/// Enough of an envelope to answer one that did not parse, and to name it
|
||||
/// in the log.
|
||||
#[derive(Deserialize)]
|
||||
struct RawEnvelope {
|
||||
id: Option<u64>,
|
||||
/// Any JSON value: a `type` that is no string must not cost the `id`.
|
||||
#[serde(rename = "type")]
|
||||
kind: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
pub async fn run(hub: Arc<Hub>, mut socket: WebSocket) {
|
||||
/// Requests that take longer are logged.
|
||||
const SLOW: Duration = Duration::from_secs(1);
|
||||
|
||||
/// Where a connection comes from, for the log.
|
||||
#[derive(Debug)]
|
||||
pub struct Peer {
|
||||
/// Counts connections since the start.
|
||||
pub id: u64,
|
||||
/// The address the connection came from (a proxy's, behind one).
|
||||
pub addr: Option<SocketAddr>,
|
||||
pub forwarded_for: Option<String>,
|
||||
pub user_agent: Option<String>,
|
||||
}
|
||||
|
||||
impl Peer {
|
||||
/// [`Peer::addr`] for the log.
|
||||
pub fn address(&self) -> String {
|
||||
self.addr.map_or_else(|| "unknown".to_string(), |a| a.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve one connection until it closes or `stop` turns true.
|
||||
pub async fn run(hub: Arc<Hub>, socket: WebSocket, peer: Peer, stop: watch::Receiver<bool>) {
|
||||
let span = info_span!("ws", id = peer.id, peer = %peer.address());
|
||||
serve(hub, socket, peer, stop).instrument(span).await;
|
||||
}
|
||||
|
||||
async fn serve(hub: Arc<Hub>, mut socket: WebSocket, peer: Peer, mut stop: watch::Receiver<bool>) {
|
||||
let connected = Instant::now();
|
||||
info!(
|
||||
forwarded_for = peer.forwarded_for.as_deref(),
|
||||
user_agent = peer.user_agent.as_deref(),
|
||||
"websocket connected"
|
||||
);
|
||||
let nonce_bytes: [u8; 24] = rand::rng().random();
|
||||
let mut session = Session {
|
||||
nonce: BASE64_URL_SAFE_NO_PAD.encode(nonce_bytes),
|
||||
@@ -83,22 +122,29 @@ pub async fn run(hub: Arc<Hub>, mut socket: WebSocket) {
|
||||
capabilities: hub.capabilities(),
|
||||
};
|
||||
if send(&mut socket, None, hello).await.is_err() {
|
||||
info!(reason = "could not send", "websocket closed");
|
||||
return;
|
||||
}
|
||||
let mut observer = hub.observer.subscribe();
|
||||
let mut events = hub.subscribe();
|
||||
|
||||
'outer: loop {
|
||||
let reason = 'outer: loop {
|
||||
tokio::select! {
|
||||
msg = socket.recv() => {
|
||||
let Some(Ok(msg)) = msg else { break };
|
||||
let text = match msg {
|
||||
Message::Text(t) => t,
|
||||
Message::Close(_) => break,
|
||||
_ => continue,
|
||||
Some(Ok(Message::Text(t))) => t,
|
||||
Some(Ok(Message::Close(_))) => break "closed by the app".to_string(),
|
||||
Some(Ok(_)) => continue,
|
||||
Some(Err(e)) => break format!("connection failed: {e}"),
|
||||
None => break "connection ended".to_string(),
|
||||
};
|
||||
let replies = match serde_json::from_str::<Envelope<ClientMsg>>(text.as_str()) {
|
||||
Ok(env) => session.handle(env.msg).await.into_iter().map(|m| (env.id, m)).collect(),
|
||||
Ok(env) => {
|
||||
let started = Instant::now();
|
||||
let replies = session.handle(env.msg).await;
|
||||
log_request(text.as_str(), started.elapsed(), &replies);
|
||||
replies.into_iter().map(|m| (env.id, m)).collect()
|
||||
}
|
||||
Err(e) => {
|
||||
let id = serde_json::from_str::<RawEnvelope>(text.as_str()).ok().and_then(|r| r.id);
|
||||
let code = if e.to_string().starts_with("unknown variant") {
|
||||
@@ -111,18 +157,18 @@ pub async fn run(hub: Arc<Hub>, mut socket: WebSocket) {
|
||||
};
|
||||
for (id, reply) in replies {
|
||||
if send(&mut socket, id, reply).await.is_err() {
|
||||
break 'outer;
|
||||
break 'outer "could not send".to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
event = observer.recv(), if session.presence.is_some() => {
|
||||
let resync = matches!(event, Err(RecvError::Lagged(_)) | Ok(ObserverEvent::Snapshot(_)));
|
||||
if let Err(RecvError::Closed) = event {
|
||||
break;
|
||||
break "the gateway stopped".to_string();
|
||||
}
|
||||
for msg in session.presence_update(resync) {
|
||||
if send(&mut socket, None, msg).await.is_err() {
|
||||
break 'outer;
|
||||
break 'outer "could not send".to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,19 +176,59 @@ pub async fn run(hub: Arc<Hub>, mut socket: WebSocket) {
|
||||
let event = match event {
|
||||
Ok(event) => event,
|
||||
Err(RecvError::Lagged(_)) => continue,
|
||||
Err(RecvError::Closed) => break,
|
||||
Err(RecvError::Closed) => break "the gateway stopped".to_string(),
|
||||
};
|
||||
for msg in session.push(&event).await {
|
||||
if send(&mut socket, None, msg).await.is_err() {
|
||||
break 'outer;
|
||||
break 'outer "could not send".to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
// Turns true once, at shutdown.
|
||||
_ = stop.changed() => {
|
||||
// Apps connect again at once instead of finding out later.
|
||||
let frame = CloseFrame { code: close_code::AWAY, reason: "the gateway is restarting".into() };
|
||||
let _ = socket.send(Message::Close(Some(frame))).await;
|
||||
break "the gateway is shutting down".to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
info!(
|
||||
uid = session.user.as_ref().map(|u| u.uid.as_str()),
|
||||
connected_s = connected.elapsed().as_secs(),
|
||||
%reason,
|
||||
open_chats = session.open_chats.len(),
|
||||
"websocket closed"
|
||||
);
|
||||
session.close();
|
||||
}
|
||||
|
||||
/// Log a request that failed on the gateway's side or took long, and every
|
||||
/// request at debug level.
|
||||
fn log_request(text: &str, elapsed: Duration, replies: &[ServerMsg]) {
|
||||
let failure = replies.iter().find_map(|m| match m {
|
||||
ServerMsg::Error {
|
||||
code: code @ (ErrorCode::Unavailable | ErrorCode::Internal),
|
||||
message,
|
||||
} => Some((code, message.as_str())),
|
||||
_ => None,
|
||||
});
|
||||
let slow = elapsed >= SLOW;
|
||||
if !slow && failure.is_none() && !tracing::enabled!(Level::DEBUG) {
|
||||
return;
|
||||
}
|
||||
let kind = serde_json::from_str::<RawEnvelope>(text).ok().and_then(|r| r.kind);
|
||||
let request = kind.as_ref().and_then(serde_json::Value::as_str).unwrap_or("unknown");
|
||||
let elapsed_ms = elapsed.as_millis() as u64;
|
||||
match failure {
|
||||
// Logged as a refused login.
|
||||
Some(_) if matches!(request, "auth" | "resume") => {}
|
||||
Some((code, error)) => warn!(request, ?code, error, elapsed_ms, "request failed"),
|
||||
None if slow => warn!(request, elapsed_ms, "slow request"),
|
||||
None => debug!(request, elapsed_ms, "request"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn send(socket: &mut WebSocket, id: Option<u64>, msg: ServerMsg) -> Result<(), axum::Error> {
|
||||
let env = Envelope { v: voelin_gateway_proto::VERSION, id, msg };
|
||||
let text = serde_json::to_string(&env).expect("messages serialize");
|
||||
@@ -175,9 +261,21 @@ fn is_action(msg: &ClientMsg) -> bool {
|
||||
|
||||
impl Session {
|
||||
async fn handle(&mut self, msg: ClientMsg) -> Vec<ServerMsg> {
|
||||
let login = match &msg {
|
||||
ClientMsg::Auth { .. } => Some("signature"),
|
||||
ClientMsg::Resume { .. } => Some("token"),
|
||||
_ => None,
|
||||
};
|
||||
let started = Instant::now();
|
||||
match self.handle_inner(msg).await {
|
||||
Ok(msgs) => msgs,
|
||||
Err(Denied(code, message)) => vec![error(code, &message)],
|
||||
Err(Denied(code, message)) => {
|
||||
if let Some(via) = login {
|
||||
let elapsed_ms = started.elapsed().as_millis() as u64;
|
||||
warn!(?code, %message, via, elapsed_ms, "login refused");
|
||||
}
|
||||
vec![error(code, &message)]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,14 +301,15 @@ impl Session {
|
||||
match msg {
|
||||
ClientMsg::Ping => Ok(vec![ServerMsg::Pong]),
|
||||
ClientMsg::Auth { omega, key_offset, ts, signature, .. } => {
|
||||
let started = Instant::now();
|
||||
let (user, token, token_expires) =
|
||||
hub.authenticate(&omega, key_offset, ts, &signature, &self.nonce).await?;
|
||||
info!(uid = %user.uid, nickname = %user.nickname, "user logged in");
|
||||
self.logged_in(user, token, token_expires).await
|
||||
self.logged_in(user, token, token_expires, "signature", started).await
|
||||
}
|
||||
ClientMsg::Resume { token, .. } => {
|
||||
let started = Instant::now();
|
||||
let (user, token, token_expires) = hub.resume(&token).await?;
|
||||
self.logged_in(user, token, token_expires).await
|
||||
self.logged_in(user, token, token_expires, "token", started).await
|
||||
}
|
||||
ClientMsg::SubscribePresence => {
|
||||
self.user()?;
|
||||
@@ -437,9 +536,13 @@ impl Session {
|
||||
user: User,
|
||||
token: String,
|
||||
token_expires: i64,
|
||||
via: &str,
|
||||
started: Instant,
|
||||
) -> Result<Vec<ServerMsg>, Denied> {
|
||||
let capabilities = self.hub.user_capabilities(&user).await;
|
||||
let uid = user.uid.clone();
|
||||
let elapsed_ms = started.elapsed().as_millis() as u64;
|
||||
info!(uid = %user.uid, nickname = %user.nickname, via, elapsed_ms, "user logged in");
|
||||
self.user = Some(user);
|
||||
Ok(vec![ServerMsg::AuthOk { uid, token, token_expires, capabilities }])
|
||||
}
|
||||
@@ -571,3 +674,16 @@ impl Session {
|
||||
self.hub.session_streams_closed(&self.own_streams);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_bad_request_keeps_its_id() {
|
||||
let raw = |text: &str| serde_json::from_str::<RawEnvelope>(text).unwrap();
|
||||
assert_eq!(raw(r#"{"id":7,"type":5}"#).id, Some(7));
|
||||
assert_eq!(raw(r#"{"id":8,"type":"ping","extra":[]}"#).id, Some(8));
|
||||
assert_eq!(raw(r#"{"type":"ping"}"#).id, None);
|
||||
}
|
||||
}
|
||||
@@ -81,8 +81,12 @@ pub async fn pump_relays(hub: Arc<Hub>, mut events: broadcast::Receiver<RelayEve
|
||||
hub.publish_incoming(msg);
|
||||
}
|
||||
}
|
||||
Ok(RelayEvent::Closed { channel, reason }) => {
|
||||
warn!(channel, %reason, "relay closed");
|
||||
// Logged by the pool.
|
||||
Ok(RelayEvent::Closed { channel, .. }) => {
|
||||
if hub.relay_wanted(channel) {
|
||||
let hub = hub.clone();
|
||||
tokio::spawn(async move { hub.reopen_relay(channel).await });
|
||||
}
|
||||
}
|
||||
Err(RecvError::Lagged(_)) => {}
|
||||
Err(RecvError::Closed) => return,
|
||||
@@ -196,7 +200,7 @@ async fn apply_settings(hub: Arc<Hub>) {
|
||||
hub.rebuild_relays(&new.relay.nickname).await;
|
||||
}
|
||||
if new.relay.pinned_channels != old.relay.pinned_channels {
|
||||
hub.apply_pinned_channels(&old.relay.pinned_channels, &new.relay.pinned_channels).await;
|
||||
hub.apply_pinned_channels(&old.relay.pinned_channels, &new.relay.pinned_channels);
|
||||
}
|
||||
let features_changed = Feature::ALL.iter().any(|f| f.enabled(&old) != f.enabled(&new));
|
||||
if features_changed || new.perm.admin != old.perm.admin {
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
use voelin_query::{Command, escape};
|
||||
|
||||
/// Permission ids the fake server uses.
|
||||
@@ -49,19 +49,29 @@ pub struct State {
|
||||
pub server_groups: HashMap<u64, Vec<u64>>,
|
||||
/// (target mode, channel of the posting connection, text)
|
||||
pub posted: Vec<(u8, u64, String)>,
|
||||
/// The nickname of the posting connection, for each of `posted`.
|
||||
pub posters: Vec<String>,
|
||||
/// Nicknames set with clientupdate.
|
||||
pub nicknames: Vec<String>,
|
||||
/// The current nickname of each query connection.
|
||||
names: HashMap<u16, String>,
|
||||
/// Connections that registered for server events (the observer).
|
||||
observers: Vec<mpsc::UnboundedSender<String>>,
|
||||
/// Relay connections by channel.
|
||||
relays: Vec<(u64, mpsc::UnboundedSender<String>)>,
|
||||
next_clid: u16,
|
||||
/// Permission lookups (`permsid`) to refuse for flooding, and how often.
|
||||
refusals: HashMap<String, usize>,
|
||||
/// The commands received, in order (`login` left out).
|
||||
commands: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct FakeServer {
|
||||
pub addr: SocketAddr,
|
||||
pub state: Arc<Mutex<State>>,
|
||||
/// Ends every open connection, like a server restart.
|
||||
kick: broadcast::Sender<()>,
|
||||
}
|
||||
|
||||
impl FakeServer {
|
||||
@@ -69,7 +79,7 @@ impl FakeServer {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let state = Arc::new(Mutex::new(State { next_clid: 100, ..Default::default() }));
|
||||
let server = Self { addr, state };
|
||||
let server = Self { addr, state, kick: broadcast::channel(1).0 };
|
||||
let s = server.clone();
|
||||
tokio::spawn(async move {
|
||||
while let Ok((stream, _)) = listener.accept().await {
|
||||
@@ -116,14 +126,50 @@ impl FakeServer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer looking up permission `permsid` with the flood protection's
|
||||
/// refusal, the next `times` times.
|
||||
pub fn refuse(&self, permsid: &str, times: usize) {
|
||||
self.state.lock().unwrap().refusals.insert(permsid.to_string(), times);
|
||||
}
|
||||
|
||||
/// The commands received so far, in order (`login` left out).
|
||||
pub fn commands(&self) -> Vec<String> {
|
||||
self.state.lock().unwrap().commands.clone()
|
||||
}
|
||||
|
||||
/// An observer connection is registered for server events.
|
||||
pub fn observed(&self) -> bool {
|
||||
!self.state.lock().unwrap().observers.is_empty()
|
||||
}
|
||||
|
||||
/// Channels with a relay listening.
|
||||
pub fn relayed_channels(&self) -> Vec<u64> {
|
||||
self.state.lock().unwrap().relays.iter().map(|(c, _)| *c).collect()
|
||||
}
|
||||
|
||||
/// Drop every query connection, as a restarting server does.
|
||||
pub fn drop_connections(&self) {
|
||||
let mut s = self.state.lock().unwrap();
|
||||
s.observers.clear();
|
||||
s.relays.clear();
|
||||
let _ = self.kick.send(());
|
||||
}
|
||||
|
||||
pub fn posted(&self) -> Vec<(u8, u64, String)> {
|
||||
self.state.lock().unwrap().posted.clone()
|
||||
}
|
||||
|
||||
/// What was posted as `(nickname of the poster, text)`.
|
||||
pub fn posted_by(&self) -> Vec<(String, String)> {
|
||||
let s = self.state.lock().unwrap();
|
||||
s.posters.iter().cloned().zip(s.posted.iter().map(|p| p.2.clone())).collect()
|
||||
}
|
||||
|
||||
async fn connection(self, stream: tokio::net::TcpStream) {
|
||||
let (r, mut w) = stream.into_split();
|
||||
let mut lines = BufReader::new(r).lines();
|
||||
let (tx, mut rx) = mpsc::unbounded_channel::<String>();
|
||||
let mut kicked = self.kick.subscribe();
|
||||
let clid = {
|
||||
let mut s = self.state.lock().unwrap();
|
||||
s.next_clid += 1;
|
||||
@@ -138,6 +184,9 @@ impl FakeServer {
|
||||
line = lines.next_line() => {
|
||||
let Ok(Some(line)) = line else { return };
|
||||
let Some(cmd) = Command::parse(&line) else { continue };
|
||||
if cmd.name != "login" {
|
||||
self.state.lock().unwrap().commands.push(line.clone());
|
||||
}
|
||||
let reply = self.answer(&cmd, clid, &mut channel, &tx);
|
||||
if w.write_all(reply.as_bytes()).await.is_err() {
|
||||
return;
|
||||
@@ -148,6 +197,7 @@ impl FakeServer {
|
||||
return;
|
||||
}
|
||||
}
|
||||
_ = kicked.recv() => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -184,6 +234,12 @@ impl FakeServer {
|
||||
]),
|
||||
"permidgetbyname" => {
|
||||
let name = arg("permsid").unwrap_or_default();
|
||||
if let Some(left @ 1..) = s.refusals.get_mut(&name) {
|
||||
*left -= 1;
|
||||
return "error id=524 msg=client\\sis\\sflooding \
|
||||
extra_msg=please\\swait\\s1\\sseconds\n\r"
|
||||
.into();
|
||||
}
|
||||
match PERMS.iter().find(|(n, _)| *n == name) {
|
||||
Some((_, id)) => data(vec![format!("permsid={name} permid={id}")]),
|
||||
None => "error id=2 msg=invalid\\spermission\n\r".into(),
|
||||
@@ -192,6 +248,12 @@ impl FakeServer {
|
||||
"whoami" => data(vec![format!("client_id={clid} client_channel_id={channel}")]),
|
||||
"clientupdate" => {
|
||||
if let Some(nick) = arg("client_nickname") {
|
||||
let in_use = s.online.iter().any(|c| c.nickname == nick)
|
||||
|| s.names.iter().any(|(id, n)| *id != clid && *n == nick);
|
||||
if in_use {
|
||||
return "error id=513 msg=nickname\\sis\\salready\\sin\\suse\n\r".into();
|
||||
}
|
||||
s.names.insert(clid, nick.clone());
|
||||
s.nicknames.push(nick);
|
||||
}
|
||||
ok
|
||||
@@ -262,6 +324,8 @@ impl FakeServer {
|
||||
"sendtextmessage" => {
|
||||
let mode = num("targetmode") as u8;
|
||||
s.posted.push((mode, *channel, arg("msg").unwrap_or_default()));
|
||||
let poster = s.names.get(&clid).cloned().unwrap_or_default();
|
||||
s.posters.push(poster);
|
||||
ok
|
||||
}
|
||||
_ => ok,
|
||||
|
||||
@@ -26,6 +26,7 @@ const LOBBY: ChatTarget = ChatTarget::Channel(1);
|
||||
|
||||
struct Fixture {
|
||||
fake: FakeServer,
|
||||
boot: crate::config::Bootstrap,
|
||||
hub: Arc<Hub>,
|
||||
url: String,
|
||||
dir: std::path::PathBuf,
|
||||
@@ -80,6 +81,7 @@ impl Fixture {
|
||||
});
|
||||
}
|
||||
let layers = Layers { file: file_values(&toml).unwrap(), ..Default::default() };
|
||||
let boot = layers.bootstrap().unwrap();
|
||||
let hub = Hub::start(layers).await.unwrap();
|
||||
// Wait for the observer's first snapshot.
|
||||
for _ in 0..100 {
|
||||
@@ -90,9 +92,10 @@ impl Fixture {
|
||||
}
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("ws://{}/v1", listener.local_addr().unwrap());
|
||||
let app = crate::router(hub.clone());
|
||||
let app = crate::router(crate::App::started(boot.clone(), hub.clone()))
|
||||
.into_make_service_with_connect_info::<std::net::SocketAddr>();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await });
|
||||
Self { fake, hub, url, dir, people }
|
||||
Self { fake, boot, hub, url, dir, people }
|
||||
}
|
||||
|
||||
fn people(&self) -> (&Person, &Person, &Person) {
|
||||
@@ -173,7 +176,11 @@ async fn chat_pins_reactions_topics() {
|
||||
unreachable!()
|
||||
};
|
||||
assert_eq!((id, message.text.as_str()), (hello.id, "hello"));
|
||||
assert!(fx.fake.posted().contains(&(2, 1, "[Bob] hello".into())));
|
||||
// Under Bob's name: "Bob1", as Bob is online with voice as "Bob". The
|
||||
// relay takes its own name back after the post.
|
||||
assert!(fx.fake.posted().contains(&(2, 1, "hello".into())));
|
||||
assert!(fx.fake.posted_by().contains(&("Bob1".into(), "hello".into())));
|
||||
assert_eq!(fx.fake.state.lock().unwrap().nicknames.last().unwrap(), "Chat Relay 1");
|
||||
|
||||
// Pins: moderators only by default; Alice is an admin.
|
||||
assert_eq!(code(b.pin(hello.id).await), ErrorCode::Forbidden);
|
||||
@@ -213,7 +220,7 @@ async fn chat_pins_reactions_topics() {
|
||||
assert_eq!(t.id, topic.id);
|
||||
let in_topic = b.post(LOBBY, "saturday?".into(), Some(topic.id)).await.unwrap();
|
||||
assert_eq!(in_topic.topic_id, Some(topic.id));
|
||||
assert!(fx.fake.posted().contains(&(2, 1, "[Bob] [#Plans] saturday?".into())));
|
||||
assert!(fx.fake.posted_by().contains(&("Bob1".into(), "[#Plans] saturday?".into())));
|
||||
expect(
|
||||
&mut c_rx,
|
||||
"prefixed chat event",
|
||||
@@ -456,7 +463,7 @@ async fn admin_settings_apply_live() {
|
||||
|
||||
// Feature switches reach connected clients at once.
|
||||
let first = b.post(LOBBY, "one".into(), None).await.unwrap();
|
||||
assert!(fx.fake.posted().contains(&(2, 1, "<Bob> one".into())));
|
||||
assert!(fx.fake.posted_by().contains(&("Bob1".into(), "one".into())));
|
||||
let entry = a.config_set("features.pins".into(), json!(false)).await.unwrap();
|
||||
assert_eq!(entry.source, voelin_gateway_proto::ConfigSource::Db);
|
||||
expect(
|
||||
@@ -506,10 +513,22 @@ async fn admin_settings_apply_live() {
|
||||
// 0: no limit.
|
||||
a.config_set("limits.posts_per_window".into(), json!(0)).await.unwrap();
|
||||
|
||||
// Relay settings apply without a restart.
|
||||
// Relay settings apply without a restart. The format is for posts the
|
||||
// relay cannot make under Bob's name: every variant of it is taken.
|
||||
for (clid, nick) in [(21, "Bob1"), (22, "Bob2"), (23, "Bob3")] {
|
||||
fx.fake.add_online(Online {
|
||||
clid,
|
||||
cid: 2,
|
||||
uid: format!("other-{nick}"),
|
||||
nickname: nick.into(),
|
||||
server_groups: Vec::new(),
|
||||
streaming: false,
|
||||
});
|
||||
}
|
||||
a.config_set("relay.format".into(), json!("{nick}: {text}")).await.unwrap();
|
||||
b.post(LOBBY, "two".into(), None).await.unwrap();
|
||||
assert!(fx.fake.posted().contains(&(2, 1, "Bob: two".into())));
|
||||
assert!(fx.fake.posted_by().contains(&("Chat Relay 1".into(), "Bob: two".into())));
|
||||
a.config_set("relay.nickname".into(), json!("Bridge")).await.unwrap();
|
||||
for _ in 0..100 {
|
||||
if fx.fake.state.lock().unwrap().nicknames.iter().any(|n| n == "Bridge 1") {
|
||||
@@ -567,3 +586,100 @@ async fn tells_apps_where_it_is() {
|
||||
let fx = Fixture::start("well-known-public", public).await;
|
||||
assert_eq!(well_known(&fx).await, "wss://gw.example.test/v1");
|
||||
}
|
||||
|
||||
/// The TeamSpeak server drops the gateway's query connections (a restart):
|
||||
/// logins go on working, through a new lookup connection.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn logins_work_after_the_server_dropped_the_gateway() {
|
||||
let fx = Fixture::start("reconnect", "").await;
|
||||
let (alice, bob, _) = fx.people();
|
||||
let (b, mut b_rx) = bob.connect(&fx).await;
|
||||
b.open_chat(LOBBY).await.unwrap();
|
||||
b.open_chat(ChatTarget::Server).await.unwrap();
|
||||
assert!(fx.hub.lookup.is_up());
|
||||
let old_id = fx.hub.lookup.own_id().unwrap();
|
||||
fx.fake.drop_connections();
|
||||
// At once: the login waits for the new connection.
|
||||
let (a, _a_rx) = alice.connect(&fx).await;
|
||||
assert!(a.has(feature::ADMIN));
|
||||
assert!(fx.hub.lookup.is_up());
|
||||
a.post(ChatTarget::Server, "back again".into(), None).await.unwrap();
|
||||
assert!(fx.fake.posted().contains(&(3, 1, "back again".into())));
|
||||
|
||||
// Bob still reads the lobby: its relay comes back.
|
||||
for _ in 0..100 {
|
||||
if fx.fake.relayed_channels().contains(&1) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
fx.fake.say_in_channel(1, "Dave", "dave", "after the restart");
|
||||
expect(
|
||||
&mut b_rx,
|
||||
"relayed after the restart",
|
||||
|p| matches!(p, Push::Chat { message, .. } if message.text == "after the restart"),
|
||||
)
|
||||
.await;
|
||||
|
||||
// A restarted server hands out client ids from 1 again: a user may get
|
||||
// the one the gateway had. Their server chat is not the gateway's own.
|
||||
assert_ne!(fx.hub.lookup.own_id(), Some(old_id));
|
||||
for _ in 0..100 {
|
||||
if fx.fake.observed() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
fx.fake.notify_observers(&format!(
|
||||
"notifytextmessage targetmode=3 msg=hi\\sall invokerid={old_id} invokername=Erin \
|
||||
invokeruid=erin"
|
||||
));
|
||||
expect(
|
||||
&mut b_rx,
|
||||
"server chat from the gateway's old id",
|
||||
|p| matches!(p, Push::Chat { message, .. } if message.text == "hi all"),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// The server's flood protection refuses looking up an optional permission,
|
||||
/// also when asked again after the wait: the gateway asks for no more, which
|
||||
/// would get it banned for 10 minutes.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn optional_permissions_stop_at_the_flood_protection() {
|
||||
let fake = FakeServer::start().await;
|
||||
fake.refuse("b_channel_modify_name", 2);
|
||||
let connect = voelin_query::Connect {
|
||||
transport: voelin_query::Transport::Raw,
|
||||
addr: fake.addr.to_string(),
|
||||
user: "serveradmin".into(),
|
||||
secret: None,
|
||||
server_port: None,
|
||||
server_id: None,
|
||||
// Taken to be on the allowlist.
|
||||
line: voelin_query::LineOptions { rate_limit: None, ..Default::default() },
|
||||
};
|
||||
let lookup = crate::lookup::Lookup::open(connect, "Gateway".into()).await;
|
||||
let ids = crate::perms::PermIds::load(&lookup).await.unwrap();
|
||||
assert_eq!(ids.subscribe_power, fake::SUBSCRIBE_POWER);
|
||||
assert_eq!((ids.channel_modify_name, ids.server_modify_name), (0, 0));
|
||||
let asked = fake.commands();
|
||||
let count =
|
||||
|name: &str| asked.iter().filter(|c| c.ends_with(&format!("permsid={name}"))).count();
|
||||
assert_eq!(count("b_channel_modify_name"), 2, "{asked:?}");
|
||||
assert_eq!(count("b_virtualserver_modify_name"), 0, "{asked:?}");
|
||||
}
|
||||
|
||||
/// `/health` says what is missing until the gateway is logged in.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn health_tells_whether_the_gateway_is_up() {
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
let fx = Fixture::start("health", "").await;
|
||||
let app = crate::App::started(fx.boot.clone(), fx.hub.clone());
|
||||
assert_eq!(crate::health(State(app)).await, (StatusCode::OK, "ok".to_string()));
|
||||
let starting = crate::App::new(fx.boot.clone());
|
||||
let (status, text) = crate::health(State(starting)).await;
|
||||
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
|
||||
assert!(text.starts_with("starting"), "{text}");
|
||||
}
|
||||
@@ -33,6 +33,14 @@ allowlisted = false
|
||||
bind = "0.0.0.0:7788"
|
||||
# public_url = "wss://gw.example.org/v1"
|
||||
|
||||
# BOOTSTRAP. The log goes to standard output (journalctl -u tsgw, docker logs).
|
||||
# Uncomment to change it; tsgw versions before these keys refuse the section.
|
||||
# [log]
|
||||
# What to log (TSGW_LOG_LEVEL); default: RUST_LOG, else info.
|
||||
# level = "info,voelin_query=trace"
|
||||
# Also write it to this file: appended, moved aside at 20 MB, 5 files kept.
|
||||
# file = "logs/tsgw.log"
|
||||
|
||||
[auth]
|
||||
# Only these server groups may use the gateway (empty: everyone known to the server).
|
||||
require_server_groups = []
|
||||
@@ -42,6 +50,8 @@ token_ttl_hours = 720
|
||||
|
||||
[relay]
|
||||
nickname = "Chat Relay"
|
||||
# Posts go out under the user's nickname; this form only when the relay
|
||||
# cannot take it.
|
||||
format = "[{nick}] {text}"
|
||||
idle_teardown_secs = 120
|
||||
# Each relay is one query connection; stay below the server's per-IP limit.
|
||||
|
||||
@@ -9,7 +9,8 @@ repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[features]
|
||||
default = ["vpx", "openh264", "openh264-download", "ffmpeg", "x11", "pipewire", "wlroots", "segment"]
|
||||
# Every codec backend: desktop builds have all encoders and decoders.
|
||||
default = ["vpx", "openh264", "openh264-download", "ffmpeg", "av1", "x11", "pipewire", "wlroots", "segment"]
|
||||
# VP8 and VP9 through the system libvpx (pkg-config `vpx`).
|
||||
vpx = ["dep:libvpx-native-sys"]
|
||||
# H.264 through Cisco's prebuilt OpenH264 library, loaded at runtime. The
|
||||
@@ -21,7 +22,9 @@ openh264-download = ["openh264", "dep:reqwest", "dep:bzip2", "dep:sha2"]
|
||||
# VA-API, NVENC, Quick Sync, AMF, Media Foundation, VideoToolbox, x264,
|
||||
# SVT-AV1, ... whatever the installed FFmpeg has (see docs/media.md).
|
||||
ffmpeg = ["dep:libloading", "dep:rustix"]
|
||||
# AV1 decoding through the system libdav1d (pkg-config `dav1d` >= 1.3).
|
||||
# AV1 decoding through libdav1d (pkg-config `dav1d` >= 1.3; on Windows
|
||||
# vcpkg's or our MinGW build, see .github/actions/system-deps and
|
||||
# docker/windows.Dockerfile).
|
||||
av1 = ["dep:dav1d"]
|
||||
# X11 screen capture (Linux).
|
||||
x11 = ["dep:x11rb", "dep:memmap2", "dep:rustix"]
|
||||
@@ -37,11 +40,9 @@ wlroots = ["dep:wayland-client", "dep:wayland-protocols", "dep:wayland-protocols
|
||||
# model (PP-HumanSeg, ONNX, bundled in `models/`) run on the CPU by tract.
|
||||
# Without it the background is cut around a centred oval.
|
||||
segment = ["dep:tract-onnx"]
|
||||
# Conversion between `Codec` and `str0m::format::Codec`.
|
||||
str0m = ["dep:str0m"]
|
||||
# The studio's WHIP output: a WebRTC session (str0m) set up over HTTP. Needs
|
||||
# str0m's crypto provider, the same one voelin-stream uses.
|
||||
whip = ["str0m", "str0m/aws-lc-rs", "dep:reqwest"]
|
||||
whip = ["str0m/aws-lc-rs", "dep:reqwest"]
|
||||
|
||||
[dependencies]
|
||||
bzip2 = { version = "0.6.1", optional = true }
|
||||
@@ -58,7 +59,9 @@ serde = { version = "1", features = ["derive"] }
|
||||
ab_glyph = "0.2.32"
|
||||
image = { version = "0.25.10", default-features = false, features = ["jpeg", "png"] }
|
||||
sha2 = { version = "0.10.9", optional = true }
|
||||
str0m = { version = "0.23.1", default-features = false, optional = true }
|
||||
# Its media types (`MediaKind`, `MediaTime`) are in `stream::EncodedFrame`, and
|
||||
# `Codec` converts to and from its codec type.
|
||||
str0m = { version = "0.23.1", default-features = false }
|
||||
thiserror = "2.0.21"
|
||||
tract-onnx = { version = "0.23.8", optional = true }
|
||||
tokio = { version = "1", features = ["sync"] }
|
||||
@@ -94,8 +97,10 @@ criterion = "0.8"
|
||||
opus2 = "0.4"
|
||||
serde_json = "1"
|
||||
# The H.264 `profile-level-id` the signalling offers, to check it against the
|
||||
# SPS the encoders really emit (`tests/ffmpeg.rs`). No cycle: voelin-stream
|
||||
# does not depend on this crate.
|
||||
# SPS the encoders really emit (`tests/ffmpeg.rs`). A cycle through a
|
||||
# dev-dependency, which cargo allows: voelin-stream depends on this crate for
|
||||
# the frame and layer types, so this crate's unit tests see itself twice, and
|
||||
# only primitives and voelin-stream's own types cross between the copies.
|
||||
voelin-stream = { path = "../voelin-stream" }
|
||||
# Logs of integration tests (`RUST_LOG`).
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
|
||||
@@ -21,9 +21,7 @@ impl Dav1dDecoder {
|
||||
pub fn new() -> Result<Self> {
|
||||
let mut settings = Settings::new();
|
||||
settings.set_max_frame_delay(1);
|
||||
settings.set_n_threads(
|
||||
std::thread::available_parallelism().map_or(1, |n| n.get().min(4) as u32),
|
||||
);
|
||||
settings.set_n_threads(crate::codec::dav1d_threads() as u32);
|
||||
let decoder = dav1d::Decoder::with_settings(&settings).map_err(|e| {
|
||||
Error::CodecUnavailable { codec: Codec::Av1, reason: format!("dav1d: {e}") }
|
||||
})?;
|
||||
|
||||
@@ -25,6 +25,15 @@ use std::sync::Arc;
|
||||
use crate::frame::VideoFrame;
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// dav1d's threads with a frame delay of one (ours and FFmpeg's `libdav1d`):
|
||||
/// a quarter of the cores, 1 to 4. They wait on each other where cores are
|
||||
/// few (on 4 cores, 1080p: 211 fps on one thread, 155-166 on 3 or 4) and
|
||||
/// help where there are many (32 cores, 1440p: 412 fps on 8).
|
||||
#[cfg_attr(not(any(feature = "av1", feature = "ffmpeg")), allow(dead_code))]
|
||||
pub(crate) fn dav1d_threads() -> usize {
|
||||
std::thread::available_parallelism().map_or(1, |n| (n.get() / 4).clamp(1, 4))
|
||||
}
|
||||
|
||||
#[cfg(feature = "av1")]
|
||||
pub mod av1;
|
||||
#[cfg(feature = "openh264")]
|
||||
@@ -86,7 +95,6 @@ impl FromStr for Codec {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "str0m")]
|
||||
impl From<Codec> for str0m::format::Codec {
|
||||
fn from(c: Codec) -> Self {
|
||||
match c {
|
||||
@@ -99,7 +107,6 @@ impl From<Codec> for str0m::format::Codec {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "str0m")]
|
||||
impl TryFrom<str0m::format::Codec> for Codec {
|
||||
type Error = Error;
|
||||
|
||||
@@ -217,7 +224,9 @@ pub struct EncodedChunk<'a> {
|
||||
pub pts_90khz: u64,
|
||||
}
|
||||
|
||||
/// One encoded frame, ready for `voelin_stream::Peer::write`.
|
||||
/// One frame as an encoder makes it. A stream takes it as a
|
||||
/// [`stream::EncodedFrame`](crate::stream::EncodedFrame), which adds the kind
|
||||
/// of media, the RTP time and the layer.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct EncodedFrame {
|
||||
pub data: Vec<u8>,
|
||||
@@ -1030,7 +1039,6 @@ mod tests {
|
||||
assert_eq!(Codec::Av1.to_string(), "AV1");
|
||||
}
|
||||
|
||||
#[cfg(feature = "str0m")]
|
||||
#[test]
|
||||
fn str0m_mapping() {
|
||||
for c in Codec::ALL {
|
||||
@@ -1051,7 +1059,17 @@ mod tests {
|
||||
assert!(codecs.new_decoder(Codec::H265).is_err());
|
||||
#[cfg(feature = "vpx")]
|
||||
{
|
||||
assert_eq!(codecs.decoders()[..2], [Codec::Vp9, Codec::Vp8]);
|
||||
// AV1 (dav1d, feature `av1`) comes first where it is built in.
|
||||
let vpx: Vec<_> = codecs
|
||||
.decoders()
|
||||
.into_iter()
|
||||
.filter(|c| matches!(c, Codec::Vp8 | Codec::Vp9))
|
||||
.collect();
|
||||
assert_eq!(vpx, [Codec::Vp9, Codec::Vp8]);
|
||||
assert_eq!(
|
||||
codecs.decoders()[0],
|
||||
if cfg!(feature = "av1") { Codec::Av1 } else { Codec::Vp9 }
|
||||
);
|
||||
assert_eq!(codecs.encoder_codecs()[0], Codec::Vp8);
|
||||
assert_eq!(codecs.pick_encoder(&[Codec::H264, Codec::Vp9]), Some(Codec::Vp9));
|
||||
assert_eq!(codecs.pick_encoder(&[Codec::Vp8, Codec::Vp9]), Some(Codec::Vp8));
|
||||
|
||||
@@ -302,7 +302,11 @@ impl VpxDecoder {
|
||||
pub fn new(codec: Codec) -> Result<Self> {
|
||||
let vp9 = is_vp9(codec)?;
|
||||
check(codec, false)?;
|
||||
let threads = std::thread::available_parallelism().map_or(1, |n| n.get().min(4) as u32);
|
||||
// libvpx's decoder threads spin waiting for each other: on 4 threads
|
||||
// with another core busy, our 4- and 8-partition 1440p streams
|
||||
// decoded at 23 and 11 fps, on 2 at 143 and 129.
|
||||
let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
|
||||
let threads = (cores / 2).clamp(1, 2) as u32;
|
||||
let decoder =
|
||||
raw::Decoder::new(vp9, threads).map_err(|message| Error::Decoder { codec, message })?;
|
||||
Ok(Self { codec, decoder })
|
||||
|
||||
@@ -16,7 +16,8 @@
|
||||
//! Every decoder is set up for live video: slice threads only (frame
|
||||
//! threads hold one frame per thread before the first picture comes out),
|
||||
//! dav1d with a frame delay of one, so each frame's picture comes out of
|
||||
//! the call that decoded it.
|
||||
//! the call that decoded it. VP8 decodes on one thread: its slice threads
|
||||
//! split frames by token partitions and wait on each other ([`decoder_threads`]).
|
||||
//!
|
||||
//! [`probe`] runs every decoder once per process (in parallel) on a short
|
||||
//! clip of its codec: three frames of a test picture encoded by this crate's
|
||||
@@ -196,9 +197,18 @@ fn hw_device(ffmpeg: &Ffmpeg, kind: &'static str) -> std::result::Result<Ptr, St
|
||||
}
|
||||
|
||||
/// Threads of a software decoder: slice (or dav1d's tile and row) threads,
|
||||
/// which add no delay.
|
||||
fn decoder_threads() -> usize {
|
||||
std::thread::available_parallelism().map_or(1, |n| n.get().min(8))
|
||||
/// which add no delay. Except for VP8, whose slice threads work on the
|
||||
/// frame's token partitions and wait on each other: a stream of 4 or 8
|
||||
/// partitions (ours, from a sender with 6 cores or more) decoded 40-80 %
|
||||
/// slower on 4 threads than on one, too slow for 1440p at 60 fps. dav1d
|
||||
/// ([`crate::codec::dav1d_threads`]) gets a quarter of the cores.
|
||||
fn decoder_threads(codec: Codec, decoder: &str) -> usize {
|
||||
let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
|
||||
match (codec, decoder) {
|
||||
(Codec::Vp8, _) => 1,
|
||||
(_, "libdav1d") => crate::codec::dav1d_threads(),
|
||||
_ => cores.min(8),
|
||||
}
|
||||
}
|
||||
|
||||
/// A decoder of one [`DecoderSpec`]; see the [module docs](self).
|
||||
@@ -258,7 +268,8 @@ impl FfmpegDecoder {
|
||||
// private options object (NULL if the decoder has none).
|
||||
let private = unsafe { (api.av_opt_child_next)(this.ctx, std::ptr::null_mut()) };
|
||||
// A hardware decoder's work is on the GPU.
|
||||
let threads = if spec.is_hardware() { 1 } else { decoder_threads() };
|
||||
let threads =
|
||||
if spec.is_hardware() { 1 } else { decoder_threads(spec.codec, spec.decoder) };
|
||||
this.set(this.ctx, "threads", &threads.to_string());
|
||||
this.set(this.ctx, "thread_type", "slice");
|
||||
if spec.decoder == "libdav1d"
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
//! Simulcast layers: several encodings of one stream, each with its own size,
|
||||
//! frame rate and bitrate.
|
||||
//!
|
||||
//! The streamer encodes every layer of its [`LayerSpec`] list and tags each
|
||||
//! [`EncodedFrame`](crate::stream::EncodedFrame) with its [`LayerId`]. Each
|
||||
//! viewer connection gets the layer that fits its bandwidth estimate; peers
|
||||
//! that negotiate RID simulcast (`a=simulcast`) get all of them. There is no
|
||||
//! limit on the number of layers.
|
||||
//!
|
||||
//! The types are the media side's vocabulary; the stream transports (the
|
||||
//! `voelin-stream` crate, and whatever else carries a stream) and the client
|
||||
//! engine use them as they are.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// A simulcast layer. Layer 0 is the one a stream without simulcast has.
|
||||
pub type LayerId = u16;
|
||||
|
||||
/// One encoding of the stream. Compared bit for bit (`scale` by its bits),
|
||||
/// so it is `Eq`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct LayerSpec {
|
||||
pub id: LayerId,
|
||||
/// Output size relative to the source (1.0: the source's size). Ignored
|
||||
/// when [`size`](Self::size) is set.
|
||||
pub scale: f32,
|
||||
/// Exact output size in pixels, instead of `scale`.
|
||||
pub size: Option<(u32, u32)>,
|
||||
/// Frame rate cap; `None`: the source's frame rate.
|
||||
pub max_fps: Option<u32>,
|
||||
/// Bitrate the encoder starts with, in bit/s. Bandwidth estimates move it
|
||||
/// down (and back up to this value, or [`max_bitrate`](Self::max_bitrate)).
|
||||
pub bitrate: u64,
|
||||
/// Highest bitrate bandwidth estimates may raise the layer to; `None`: no
|
||||
/// maximum.
|
||||
pub max_bitrate: Option<u64>,
|
||||
/// Estimate (bit/s) a viewer needs to receive this layer; below it the
|
||||
/// viewer moves to the next smaller layer.
|
||||
pub min_bitrate: u64,
|
||||
/// RTP stream id for peers that negotiate RID simulcast.
|
||||
pub rid: Option<String>,
|
||||
}
|
||||
|
||||
impl PartialEq for LayerSpec {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.id == other.id
|
||||
&& self.scale.to_bits() == other.scale.to_bits()
|
||||
&& self.size == other.size
|
||||
&& self.max_fps == other.max_fps
|
||||
&& self.bitrate == other.bitrate
|
||||
&& self.max_bitrate == other.max_bitrate
|
||||
&& self.min_bitrate == other.min_bitrate
|
||||
&& self.rid == other.rid
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for LayerSpec {}
|
||||
|
||||
impl LayerSpec {
|
||||
/// A stream without simulcast: layer 0 at the source's size and rate.
|
||||
pub fn single(bitrate: u64) -> Self {
|
||||
Self {
|
||||
id: 0,
|
||||
scale: 1.0,
|
||||
size: None,
|
||||
max_fps: None,
|
||||
bitrate,
|
||||
max_bitrate: None,
|
||||
min_bitrate: 0,
|
||||
rid: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Output size for a source of `width` x `height`: [`size`](Self::size),
|
||||
/// or the scaled source size rounded down to even numbers (I420), at least
|
||||
/// 2x2.
|
||||
pub fn output_size(&self, width: u32, height: u32) -> (u32, u32) {
|
||||
let (w, h) = self.size.unwrap_or_else(|| {
|
||||
let scale = if self.scale.is_finite() && self.scale > 0.0 { self.scale } else { 1.0 };
|
||||
((width as f32 * scale) as u32, (height as f32 * scale) as u32)
|
||||
});
|
||||
((w & !1).max(2), (h & !1).max(2))
|
||||
}
|
||||
}
|
||||
|
||||
/// A set of layers, e.g. those waiting for a keyframe. Grows as needed.
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
pub struct LayerSet {
|
||||
words: Vec<u64>,
|
||||
}
|
||||
|
||||
impl LayerSet {
|
||||
pub const fn new() -> Self {
|
||||
Self { words: Vec::new() }
|
||||
}
|
||||
|
||||
/// Adds `layer`; `true` if it was not in the set.
|
||||
pub fn insert(&mut self, layer: LayerId) -> bool {
|
||||
let (word, bit) = Self::position(layer);
|
||||
if self.words.len() <= word {
|
||||
self.words.resize(word + 1, 0);
|
||||
}
|
||||
let new = self.words[word] & bit == 0;
|
||||
self.words[word] |= bit;
|
||||
new
|
||||
}
|
||||
|
||||
/// Removes `layer`; `true` if it was in the set.
|
||||
pub fn remove(&mut self, layer: LayerId) -> bool {
|
||||
let (word, bit) = Self::position(layer);
|
||||
match self.words.get_mut(word) {
|
||||
Some(w) if *w & bit != 0 => {
|
||||
*w &= !bit;
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn contains(&self, layer: LayerId) -> bool {
|
||||
let (word, bit) = Self::position(layer);
|
||||
self.words.get(word).is_some_and(|w| w & bit != 0)
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.words.iter().all(|w| *w == 0)
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.words.iter().map(|w| w.count_ones() as usize).sum()
|
||||
}
|
||||
|
||||
/// Empties the set, keeping its memory.
|
||||
pub fn clear(&mut self) {
|
||||
self.words.fill(0);
|
||||
}
|
||||
|
||||
/// Adds every layer of `other`.
|
||||
pub fn union_with(&mut self, other: &LayerSet) {
|
||||
if self.words.len() < other.words.len() {
|
||||
self.words.resize(other.words.len(), 0);
|
||||
}
|
||||
for (w, o) in self.words.iter_mut().zip(&other.words) {
|
||||
*w |= o;
|
||||
}
|
||||
}
|
||||
|
||||
/// The layers in ascending order.
|
||||
pub fn iter(&self) -> impl Iterator<Item = LayerId> + '_ {
|
||||
self.words.iter().enumerate().flat_map(|(i, &word)| {
|
||||
(0..64).filter(move |b| word & (1 << b) != 0).map(move |b| (i * 64 + b) as LayerId)
|
||||
})
|
||||
}
|
||||
|
||||
fn position(layer: LayerId) -> (usize, u64) {
|
||||
(usize::from(layer) / 64, 1 << (layer % 64))
|
||||
}
|
||||
}
|
||||
|
||||
impl FromIterator<LayerId> for LayerSet {
|
||||
fn from_iter<I: IntoIterator<Item = LayerId>>(iter: I) -> Self {
|
||||
let mut set = Self::new();
|
||||
for layer in iter {
|
||||
set.insert(layer);
|
||||
}
|
||||
set
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for LayerSet {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_set().entries(self.iter()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn layer_set() {
|
||||
let mut set = LayerSet::new();
|
||||
assert!(set.is_empty());
|
||||
assert!(set.insert(3));
|
||||
assert!(!set.insert(3));
|
||||
assert!(set.insert(200));
|
||||
assert!(set.insert(LayerId::MAX));
|
||||
assert_eq!(set.iter().collect::<Vec<_>>(), [3, 200, LayerId::MAX]);
|
||||
assert_eq!(set.len(), 3);
|
||||
assert!(set.contains(200) && !set.contains(4));
|
||||
assert!(set.remove(200) && !set.remove(200));
|
||||
let other: LayerSet = [1, 3].into_iter().collect();
|
||||
set.union_with(&other);
|
||||
assert_eq!(format!("{set:?}"), format!("{{1, 3, {}}}", LayerId::MAX));
|
||||
set.clear();
|
||||
assert!(set.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_size() {
|
||||
let mut layer = LayerSpec::single(1_000_000);
|
||||
assert_eq!(layer.output_size(1921, 1081), (1920, 1080));
|
||||
layer.scale = 0.5;
|
||||
assert_eq!(layer.output_size(2560, 1440), (1280, 720));
|
||||
layer.scale = 0.0001;
|
||||
assert_eq!(layer.output_size(640, 360), (2, 2));
|
||||
layer.size = Some((853, 480));
|
||||
assert_eq!(layer.output_size(1920, 1080), (852, 480));
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,10 @@
|
||||
//! (interleaved `f32`, 48 kHz)
|
||||
//! - [`convert`]: YUV ↔ RGB conversion (BT.601 limited range, the WebRTC
|
||||
//! default), e.g. RGBA for rendering and I420 for encoding
|
||||
//! - [`layer`] and [`stream`]: the simulcast layers of a stream
|
||||
//! ([`LayerSpec`]) and its frames on the way to the viewers
|
||||
//! ([`stream::EncodedFrame`], the encoder's frame plus kind, RTP time and
|
||||
//! layer)
|
||||
//! - [`codec`]: [`VideoEncoder`] / [`VideoDecoder`] traits, codec preference
|
||||
//! and the backends: libvpx (VP8/VP9, feature `vpx`), Cisco's OpenH264
|
||||
//! loaded at runtime (H.264, feature `openh264`), dav1d (AV1 decoding,
|
||||
@@ -24,8 +28,8 @@
|
||||
//! scaling and the [`scale::Pyramid`] of simulcast sizes), and
|
||||
//! [`convert::Converter`] (borrowed capture buffers straight to I420)
|
||||
//!
|
||||
//! Encoded frames go to `voelin_stream::Peer::write` with an RTP time of
|
||||
//! [`EncodedFrame::pts_90khz`] (90 kHz clock); received `MediaFrame`s go to
|
||||
//! Encoded frames go to a stream as [`stream::EncodedFrame`]s with an RTP time
|
||||
//! of [`EncodedFrame::pts_90khz`] (90 kHz clock); received `MediaFrame`s go to
|
||||
//! [`VideoDecoder::decode`].
|
||||
|
||||
pub mod capture;
|
||||
@@ -35,10 +39,12 @@ pub mod convert;
|
||||
pub mod ffmpeg;
|
||||
pub mod frame;
|
||||
pub mod handoff;
|
||||
pub mod layer;
|
||||
pub mod mix;
|
||||
pub mod pool;
|
||||
pub mod queue;
|
||||
pub mod scale;
|
||||
pub mod stream;
|
||||
pub mod studio;
|
||||
pub mod workers;
|
||||
|
||||
@@ -51,6 +57,7 @@ pub use codec::{
|
||||
pub use frame::{
|
||||
AudioBuffer, FrameData, FrameRef, GpuFrame, PixelFormat, PixelsRef, Plane, PlaneRef, VideoFrame,
|
||||
};
|
||||
pub use layer::{LayerId, LayerSet, LayerSpec};
|
||||
pub use queue::{FrameReceiver, FrameSender, frame_channel};
|
||||
|
||||
/// Errors of this crate.
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
//! The frames of a stream on their way to its viewers.
|
||||
//!
|
||||
//! An [`EncodedFrame`] is what the streamer's encoders and the Opus encoder
|
||||
//! hand to a stream: the encoder's output ([`codec::EncodedFrame`]) plus what
|
||||
//! the transport needs, which media it is, its RTP time and its simulcast
|
||||
//! layer. The engine's stream sink, the stream sessions (`voelin-stream`) and
|
||||
//! the tools that feed a stream by hand all pass it on unchanged.
|
||||
//!
|
||||
//! [`codec::EncodedFrame`]: crate::codec::EncodedFrame
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use str0m::media::{MediaKind, MediaTime};
|
||||
|
||||
use crate::layer::LayerId;
|
||||
|
||||
/// One encoded video or audio frame of a stream, ready to be sent.
|
||||
///
|
||||
/// Not the encoder's [`codec::EncodedFrame`](crate::codec::EncodedFrame),
|
||||
/// which has neither a kind nor a layer and counts time on the 90 kHz clock
|
||||
/// only.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct EncodedFrame {
|
||||
pub kind: MediaKind,
|
||||
/// RTP time: 90 kHz for video, 48 kHz for Opus.
|
||||
pub time: MediaTime,
|
||||
pub data: Arc<[u8]>,
|
||||
/// The simulcast layer of a video frame (0 without simulcast, and for
|
||||
/// audio).
|
||||
pub layer: LayerId,
|
||||
/// A video keyframe: viewers can start decoding (or switch to this layer)
|
||||
/// here.
|
||||
pub keyframe: bool,
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
uid,name,description,filename,codes
|
||||
4b27be5a-b92a-4b30-8b2d-14b59653f427,20th Anniversary,Celebrating 20 Years of TeamSpeak,20_years,
|
||||
f81ad44d-e931-47d1-a3ef-5fd160217cf8,4Netplayers,4Netplayers customer,4netplayers,
|
||||
b78a0f3e-8758-4572-b102-42a79b4a0342,????,Reads between the line,hat,
|
||||
2bf80270-8efe-46dc-a472-3280a0479145,Alpha Tester,Helped to test our software. THANK YOU!,Alpha,
|
||||
05114019-6b46-4b13-b5a1-e5179ef69fb5,April Fools!,"Roses are red, gaming is fun, you are carrying too much to be able to run :(",rpg,
|
||||
1a518885-520c-4f54-9f49-8b1acb674771,Braindance,I’m chippin’ in,Braindance,P4TEKZ80PZ
|
||||
cbf5aafd-2554-4053-80bb-0cf82ec0a430,Bright Idea,TeamSpeak took my idea on board,FeatureBadge_Lightbulb,
|
||||
d6062d9c-42a3-49c9-91dd-8c43a5a46805,Bug Catcher,I found a bug!,BugBadge_Splat,
|
||||
dfc70674-0fd0-431e-b3a1-edc32d7b09b2,Challenge Accepted,"Unlocked at SCILL Play — Challenges, tournaments and more!",scill,
|
||||
afed63f4-82f1-4479-ab02-0ef053f55723,Communities Early Adopter,Thank you for your Support!,communities_early_adopter,
|
||||
54be472d-3163-4076-9059-7f46128d937e,Communities Purchase,Purchased a TeamSpeak Community,communities_purchase,
|
||||
f85f7e21-753a-4566-b26a-4e3e9155d2ef,Cyberpunk,We have a city to burn,Cyberpunk,
|
||||
c028298c-84ff-4e22-be4e-b8c17552b4bb,Digi,Digi joined your channel #DIGWIN,digi,
|
||||
56df5ce2-6c5a-4a24-90e2-29e497e26170,Drone Champions League,I follow the Drone Champions League,DCL_Badge,DRONECHAMP
|
||||
935e5a2a-954a-44ca-aa7a-55c79285b601,E3 2018 - Winner,Discovered at E3 2018,E3-2018,
|
||||
61723e54-3da2-4f19-a33f-fcdc8ef5eaa0,Father's Day 2022,Not all heroes wear capes,fathersday2022,
|
||||
b9c7d6ad-5b99-40fb-988c-1d02ab6cc130,Found Tim Speak,Found Tim Speak at Gamescom 2018,met_tim,XJN4WJZEJN
|
||||
809bdd5a-2601-4152-82ff-a21d23d8fd46,G2 Esports,Aged 20 years being a G2 fan,G2_Esports,
|
||||
62444179-0d99-42ba-a45c-c6b1557d079a,Gamescom 2014,Registered at Gamescom 2014,gamescom_2014,
|
||||
50bbdbc8-0f2a-46eb-9808-602225b49627,Gamescom 2016,Registered during Gamescom 2016,gamescom_2016,
|
||||
534c9582-ab02-4267-aec6-2d94361daa2a,Gamescom 2017,Visited TeamSpeak at Gamescom 2017,gamescom_2017,DK9JGRJH1Q
|
||||
4eef1ecf-a0ea-423d-bfd0-496543a00305,Gamescom 2018,Visited TeamSpeak at Gamescom 2018,gamescom_2018,8CXB49KPJ4
|
||||
b82a45a5-b235-4926-be77-de102222e5eb,Gamescom 2019,Visited TeamSpeak at Gamescom 2019,Gamescom19,PNKCB76VZ8
|
||||
34dbfa8f-bd27-494c-aa08-a312fc0bb240,Gamescom Hero 2017,Gaming Hero at Gamescom 2017,hero_2017,
|
||||
24512806-f886-4440-b579-9e26e4219ef6,Gamescom Hero 2018,Gamescom Exclusive Gaming Hero 2018,gamescom_2018_played,BJCFQBU53C
|
||||
d49fd07e-99fb-41de-8d7b-c98064713171,GommeHD.net,Your #1 Minecraft Network for over 10 years,GMHD,
|
||||
c565972a-3912-457b-826f-84820c1ba6ca,Halloween 2021,Happy Halloween 2021,halloween21,
|
||||
133595e7-950f-4ef2-b113-f91a68b5770d,Halloween 2021 Special,Earned by participating in our Halloween 2021 special stream,halloween21_special,
|
||||
fb154277-5fe7-428a-85a4-43c0bdcdda3d,Halloween 2022,Spooky_Scary_Skeletons.mp4,halloween22,
|
||||
e6679ce2-d458-493c-8ffb-5660e47ac99f,Happy Hanami,Enjoy the view,hanami2023,
|
||||
de7bd960-eb02-47e1-9ce2-a44f6e255d8f,Happy Holidays 2019,Happy holidays from everyone at TeamSpeak!,Happy_Holidays,
|
||||
d4ea0251-ba46-4c1a-83b7-59db3f89e52c,Happy New Year 2021,Survived the great toilet paper crisis of 2020,firework_2020,
|
||||
1519e001-06a0-458c-9195-a8a6d0ec87fc,Happy New Year 2023,"Aw man, here we go again",2023_NewYear,
|
||||
834d4cc1-cd80-48d6-96c4-23d131d78649,Happy Summer 2023,heat death of the universe,happy_summer_2023,
|
||||
c68bcc52-7aeb-4868-b4d2-e7b20716f9ba,Heatwave 2022,I'm melting... help,summer_icecream,
|
||||
94242c4e-6742-4540-8b66-ce951ed57159,Helping Hand,\ pushed some buttons *beep* *bop* ~ thanks!,homebase,
|
||||
288a56c6-4da3-48de-9c9f-bd9eede5d832,Immortal Roleplay,This is your life.,Immortal_Roleplay,
|
||||
69bfffc8-e9c0-4f70-8a37-47cb8c73fb1d,International Peace Day,"United we stand, divided we fall",peaceday2022,
|
||||
9ea23c77-8755-4d82-b30c-92f4aac109ef,International Women's Day 2021,"To all the mums, sisters, aunties, nieces and beyond, Happy Women's Day!",wft,
|
||||
7d9fa2b1-b6fa-47ad-9838-c239a4ddd116,MIFCOM,MIFCOM | Entered Performance,mifcom,
|
||||
ed85bdff-2a2b-4bea-a1a5-4d06fcc0d776,Merry Christmas 2019,It’s the most wonderful ‘Tim’ of the Year,Christmas,
|
||||
c6480fe2-ee25-4ee8-9853-243652c8ec54,Merry Christmas 2020,"Let it snow, let it snow, let it snow!",Christmas2020,
|
||||
0581aa0f-8c2d-4681-bb9f-8492fec49977,Merry Christmas 2021,Look what Santa's left under the server tree!,christmas2021,
|
||||
d4875b30-9908-43cb-a1eb-1a958e226078,Merry Christmas 2022,There's snow place like home,christmas2022,
|
||||
87ccf9ea-67c9-45e5-adbc-77e210e6128a,Met Tim,Met Tim Speak IRL,tim_irl,
|
||||
0d98391c-ecdf-4f26-931a-49bfd669cda7,Mind Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_MindEgg,
|
||||
2fdda3c6-20e0-48f1-9c12-f39239a2ed02,Mother's Day 2022,Thanks for bearing with us,rose,
|
||||
c3f823eb-5d5c-40f9-9dbd-3437d59a539d,Official TeamSpeak Gamer,New myTeamSpeak member,TS-2018,
|
||||
8dfa37ac-b40d-4466-b393-ff2184a9adf3,Overwatch League,I follow the Overwatch League,OWL_Badge,
|
||||
4ce435d1-6ac5-4530-b81d-6d14ddaaa1ac,PGL Antwerp 2022,Watched the PGL CS:GO Major,PGLant,
|
||||
fa3ece28-64df-431f-b1b3-90844bfdd2d9,Paris Games Week 2014,Registered at Paris Games Week 2014,paris_gamesweek_2014,
|
||||
d95f9901-c42d-4bac-8849-7164fd9e2310,Paris Games Week 2016,Registered during Paris Games Week 2016,paris_gamesweek_2016,
|
||||
0005232e-538e-4cb2-93b6-d7d83e873829,PietSmiet,Werde Snob auf PietSmiet.de ;),PietSmiet,
|
||||
be932556-dfa9-4dc6-afd0-98de0ab25777,PolTeamgeist,WooOOHoohOOHooo,PolTeamgeist,
|
||||
5f6d49e4-35c8-4809-8c81-6e71f7f749e9,Power Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_PowerEgg,
|
||||
ceee2445-4fbf-4f06-9421-286f0f4e875a,Pride,Never be afraid to show your colors.,pride,
|
||||
1aa375e8-7207-45bf-8b80-556bafafc834,Reality Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_RealityEgg,
|
||||
f22c22f1-8e2d-4d99-8de9-f352dc26ac5b,Rocket Beans TV,Rocket Beans TV Community,rbtv,RWGE2NURJZ
|
||||
2c9698c1-1fec-4baa-a28f-4845f045f42f,Soul Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_SoulEgg,
|
||||
641a4d85-2351-482c-97a1-02fc3b6abbb5,Space Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_SpaceEgg,
|
||||
63261116-4359-4842-873e-56820afbe068,SpartaTheOriginal,Olaf Toast @ twitch.tv/SpartaTheOriginal,Toast,
|
||||
ef567ec5-f46e-4520-be07-6021023cf6bd,Sponsorship License,Sponsored by TeamSpeak,Sponsorship,
|
||||
7a627d47-5496-4d68-83b5-2c4eafff9b30,"Stay Home, Stay Safe","Playing Apart, Staying Connected",StaySafeStayHome,
|
||||
7262a528-c7df-4369-bc2c-d34bf5853d7b,TS Chat Alpha Tester,"Helped us test our new mobile app, thanks!",slim_golden,
|
||||
6eee759e-b1e9-4937-b023-07fc778532a2,TS Gameday Participant,At least i tried...,silvered,
|
||||
e1447b99-53b0-448a-98b7-ee7bad8bd268,TS Gameday Winner,As shiny as the golden frying pan,goldenjoystick,
|
||||
1cb07348-34a4-4741-b50f-c41e584370f7,TeamSpeak Addon Author,Creator of TeamSpeak Addons,addon_author,
|
||||
450f81c1-ab41-4211-a338-222fa94ed157,TeamSpeak Addon Developer (Bronze),Creator of at least 1 TeamSpeak Addon,addon_author_bronze,
|
||||
94ec66de-5940-4e38-b002-970df0cf6c94,TeamSpeak Addon Developer (Gold),Creator of at least 5 TeamSpeak Addons,addon_author_gold,
|
||||
c9e97536-5a2d-4c8e-a135-af404587a472,TeamSpeak Addon Developer (Silver),Creator of at least 3 TeamSpeak Addons,addon_author_silver,
|
||||
9cd152a7-bf65-4ece-aeba-62d27678f79a,TeamSpeak Competition Winner Badge,TeamSpeak Competition Winner,CompWinnerBadge,
|
||||
64221fd1-706c-4bb2-ba55-996c39effa79,TeamSpeak Jedi,myTeamSpeak early adopter,TS-OG,
|
||||
6b187e83-873b-46b0-b2c2-a31af15e76a4,TeamSpeak Merch Badge,TeamSpeak Merch Owner - 1st Edition,cap_red,
|
||||
22b9ec39-7694-453e-864c-dfc7b1b0d7c7,TeamSpeak Merch Badge 2.0,TeamSpeak Merch Owner - 2nd Edition,topper,
|
||||
205916f3-a953-4754-8905-bc15069b1f91,TeamSpeak Merch Badge 3.0,TeamSpeak Merch Owner — 3rd Edition,Merch3,
|
||||
8d843dfa-c51a-407f-87b3-94cfc8f03e96,TeamSpeak Staff,Official Staff Member,teamspeak_staff,
|
||||
c2368518-3728-4260-bcd1-8b85e9f8984c,Test,"Testing, Testing.",Testing,
|
||||
4086a249-a503-4f31-9e83-8a0a8e3089bd,Tim-o'-Lantern,Mwuhaahaahaahaahaa,Tim-O-Lantern,JQGCTAQWHT
|
||||
089c7295-3aa2-48b0-b2f1-2dd1bec12caf,Time Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_TimeEgg,
|
||||
904e232c-f369-44db-87f7-5142e15620cc,Time Machine,Worked like a machine to update addons in super-quick time.,time_machine,
|
||||
4c61af66-22ef-4897-b0bb-25fcef2acf60,Undead Nightmare,I'm the last of my kind,undead_nightmare,
|
||||
b0a36aea-3e46-4e83-a455-6e92ae1b9d94,Undead Nightmare,I'm the last of my kind,undead_nightmare,
|
||||
0cd924ed-c5ea-459e-b60a-4f1bc0b65f07,"Up, Up and Away!",Find me on Mount Chiliad,"up,_up_and_away!",
|
||||
4b0fd4f5-d456-4294-973d-853a1db5c7d8,Valentim's Day 2019,Valentim's Day 2019,Valentines_Badge,
|
||||
92801833-e721-4b7e-84d4-6c02dbb332b9,Valentim's Day 2020,Valentim's Day 2020,Valentim2020,
|
||||
958f904b-8260-48a4-a961-f786cbd39411,Valentine's Day 2023,Love you like my Tamagotchi,ValentinesDay23,
|
||||
a676c708-da67-4784-ba7f-3fb7e8d2e865,Valentines Day 2021,"Roses are red, TS is blue, Servers are Sweet and so are you.",valentine21,
|
||||
c54a9f92-07f7-4214-90f3-eafeea8005da,World Backup Day,Don't be an April Fool. Back up your data!,backupday_2023,
|
||||
448a6d13-4e08-46a1-aafa-b4ff6d6c2d06,World Bonsai Day,"harmony, balance, patience",bonsai_day,
|
||||
0f976a27-ddf5-447c-b79c-0644a8e8a297,Year of the Dragon 2024,"Arise, Shenron!",year_of_the_dragon_2024,
|
||||
8c22fe26-30ac-4231-8b31-67d8a75c808a,Year of the Ox 2021,Only listen to the fortune cookie; disregard all other fortune telling units.,ox21,
|
||||
970c70e6-00a1-41c1-ac5c-81c89a06c7a6,Year of the Rabbit 2023,Do a barrel roll!,chineseNY2023,
|
||||
92356386-0451-4a97-87d9-10ff4f43260c,Year of the Tiger 2022,Rocky sends his regards,tiger,
|
||||
|
@@ -0,0 +1,144 @@
|
||||
//! myTeamSpeak badges: what the GUIDs a client shows (`client_badges`)
|
||||
//! stand for, and where TeamSpeak keeps their pictures.
|
||||
//!
|
||||
//! The table is `data/badges.csv`: tsclientlib's list (2023, also in
|
||||
//! `proto/tsproto-structs/declarations`) and the newer badges of
|
||||
//! TeamSpeak's own list (`https://badges-content.teamspeak.com/list`, a
|
||||
//! protobuf) as of October 2026. Badges added since are unknown here.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
/// How many badges a client shows at most (TeamSpeak lets one pick three).
|
||||
pub const SHOWN: usize = 3;
|
||||
|
||||
/// TeamSpeak's server for the badges' pictures.
|
||||
const CONTENT: &str = "https://badges-content.teamspeak.com";
|
||||
|
||||
/// One badge of the table.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct BadgeInfo {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
/// Its picture's name on TeamSpeak's server, without `.svg`.
|
||||
pub filename: String,
|
||||
}
|
||||
|
||||
/// The table by GUID (lower case), read once.
|
||||
static BADGES: LazyLock<HashMap<String, BadgeInfo>> = LazyLock::new(|| {
|
||||
// Columns: uid, name, description, filename, codes.
|
||||
records(include_str!("../data/badges.csv"))
|
||||
.into_iter()
|
||||
.skip(1)
|
||||
.filter_map(|mut fields| {
|
||||
fields.truncate(4);
|
||||
let [uid, name, description, filename] = <[String; 4]>::try_from(fields).ok()?;
|
||||
Some((uid.to_ascii_lowercase(), BadgeInfo { name, description, filename }))
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
|
||||
/// What a badge GUID stands for; none for one the table does not know.
|
||||
pub fn info(guid: &str) -> Option<&'static BadgeInfo> {
|
||||
BADGES.get(&guid.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
/// The address of a badge's picture (an SVG); none for an unknown badge.
|
||||
pub fn icon_url(guid: &str) -> Option<String> {
|
||||
let info = info(guid)?;
|
||||
Some(format!("{CONTENT}/{}/{}.svg", guid.to_ascii_lowercase(), info.filename))
|
||||
}
|
||||
|
||||
/// The records of a CSV text (RFC 4180): fields split at commas; a quoted
|
||||
/// field may hold commas and line breaks, and `""` for a quote.
|
||||
fn records(text: &str) -> Vec<Vec<String>> {
|
||||
let mut records = Vec::new();
|
||||
let mut record = Vec::new();
|
||||
let mut field = String::new();
|
||||
let mut quoted = false;
|
||||
let mut chars = text.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
'"' if quoted => {
|
||||
if chars.next_if_eq(&'"').is_some() {
|
||||
field.push('"');
|
||||
} else {
|
||||
quoted = false;
|
||||
}
|
||||
}
|
||||
'"' if field.is_empty() => quoted = true,
|
||||
',' if !quoted => record.push(std::mem::take(&mut field)),
|
||||
'\r' if !quoted => {}
|
||||
'\n' if !quoted => {
|
||||
record.push(std::mem::take(&mut field));
|
||||
records.push(std::mem::take(&mut record));
|
||||
}
|
||||
c => field.push(c),
|
||||
}
|
||||
}
|
||||
if !field.is_empty() || !record.is_empty() {
|
||||
record.push(field);
|
||||
records.push(record);
|
||||
}
|
||||
records
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn known_badges() {
|
||||
let info = info("4b27be5a-b92a-4b30-8b2d-14b59653f427").unwrap();
|
||||
assert_eq!(info.name, "20th Anniversary");
|
||||
assert_eq!(info.description, "Celebrating 20 Years of TeamSpeak");
|
||||
assert_eq!(info.filename, "20_years");
|
||||
// Upper case on the wire finds it too.
|
||||
assert_eq!(super::info("4B27BE5A-B92A-4B30-8B2D-14B59653F427"), Some(info));
|
||||
assert_eq!(
|
||||
icon_url("4b27be5a-b92a-4b30-8b2d-14b59653f427").as_deref(),
|
||||
Some(
|
||||
"https://badges-content.teamspeak.com/4b27be5a-b92a-4b30-8b2d-14b59653f427/20_years.svg"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quoted_fields_keep_their_commas() {
|
||||
let fools = info("05114019-6b46-4b13-b5a1-e5179ef69fb5").unwrap();
|
||||
assert_eq!(fools.name, "April Fools!");
|
||||
assert_eq!(
|
||||
fools.description,
|
||||
"Roses are red, gaming is fun, you are carrying too much to be able to run :("
|
||||
);
|
||||
assert_eq!(fools.filename, "rpg");
|
||||
let stay = info("7a627d47-5496-4d68-83b5-2c4eafff9b30").unwrap();
|
||||
assert_eq!(stay.name, "Stay Home, Stay Safe");
|
||||
assert_eq!(stay.description, "Playing Apart, Staying Connected");
|
||||
let up = info("0cd924ed-c5ea-459e-b60a-4f1bc0b65f07").unwrap();
|
||||
assert_eq!(up.filename, "up,_up_and_away!");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_badges() {
|
||||
assert_eq!(info("00000000-0000-0000-0000-000000000000"), None);
|
||||
assert_eq!(info(""), None);
|
||||
assert_eq!(icon_url("00000000-0000-0000-0000-000000000000"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_row_is_read() {
|
||||
let rows = include_str!("../data/badges.csv").lines().count() - 1;
|
||||
assert_eq!(BADGES.len(), rows);
|
||||
assert!(BADGES.values().all(|b| !b.name.is_empty() && !b.filename.is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_records() {
|
||||
assert_eq!(
|
||||
records("a,\"b, \"\"c\"\"\",\r\n\"multi\nline\",d"),
|
||||
[vec!["a", "b, \"c\"", ""], vec!["multi\nline", "d"]]
|
||||
);
|
||||
assert!(records("").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::percent;
|
||||
use crate::presence::{ChannelId, ClientId};
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
@@ -93,7 +94,7 @@ impl FileRef {
|
||||
let mut channel = None;
|
||||
for pair in query.split('&') {
|
||||
let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
|
||||
let value = percent_decode(value);
|
||||
let value = percent::decode(value);
|
||||
match key.to_ascii_lowercase().as_str() {
|
||||
"serveruid" => file.server_uid = Some(value).filter(|v| !v.is_empty()),
|
||||
"channel" | "cid" => channel = value.parse().ok(),
|
||||
@@ -106,7 +107,7 @@ impl FileRef {
|
||||
}
|
||||
}
|
||||
if file.name.is_empty() {
|
||||
file.name = percent_decode(host.trim_end_matches('/'));
|
||||
file.name = percent::decode(host.trim_end_matches('/'));
|
||||
}
|
||||
file.channel = channel?;
|
||||
(!file.name.is_empty()).then_some(file)
|
||||
@@ -114,15 +115,15 @@ impl FileRef {
|
||||
|
||||
/// The link as TeamSpeak clients post it: `[URL=ts3file://…]name[/URL]`.
|
||||
pub fn to_bbcode(&self) -> String {
|
||||
let mut url = format!("ts3file://{}?", percent_encode(&self.name));
|
||||
let mut url = format!("ts3file://{}?", percent::encode(&self.name));
|
||||
if let Some(uid) = &self.server_uid {
|
||||
url.push_str(&format!("serverUID={}&", percent_encode(uid)));
|
||||
url.push_str(&format!("serverUID={}&", percent::encode(uid)));
|
||||
}
|
||||
url.push_str(&format!(
|
||||
"channel={}&path={}&filename={}&isDir={}",
|
||||
self.channel,
|
||||
percent_encode(&self.path),
|
||||
percent_encode(&self.name),
|
||||
percent::encode(&self.path),
|
||||
percent::encode(&self.name),
|
||||
u8::from(self.is_dir)
|
||||
));
|
||||
if let Some(size) = self.size {
|
||||
@@ -157,39 +158,6 @@ pub fn parse_file_links(text: &str) -> Vec<FileRef> {
|
||||
found
|
||||
}
|
||||
|
||||
/// `%XX` escapes to bytes (a `+` stays: file names keep theirs).
|
||||
fn percent_decode(s: &str) -> String {
|
||||
let bytes = s.as_bytes();
|
||||
let hex = |b: u8| (b as char).to_digit(16);
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'%'
|
||||
&& let (Some(h), Some(l)) =
|
||||
(bytes.get(i + 1).and_then(|b| hex(*b)), bytes.get(i + 2).and_then(|b| hex(*b)))
|
||||
{
|
||||
out.push((h * 16 + l) as u8);
|
||||
i += 3;
|
||||
continue;
|
||||
}
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
fn percent_encode(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for b in s.bytes() {
|
||||
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
|
||||
out.push(b as char);
|
||||
} else {
|
||||
out.push_str(&format!("%{b:02X}"));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Format of messages a relay posts on behalf of a user.
|
||||
pub fn relay_text(format: &str, nick: &str, text: &str) -> String {
|
||||
format.replace("{nick}", nick).replace("{text}", text)
|
||||
|
||||
@@ -3,17 +3,21 @@
|
||||
//! Nothing in here does IO; the types describe what a server offers and what
|
||||
//! the user sees.
|
||||
|
||||
pub mod badges;
|
||||
mod chat;
|
||||
mod link;
|
||||
mod percent;
|
||||
mod presence;
|
||||
mod server;
|
||||
mod tree;
|
||||
|
||||
pub use chat::{ChatMessage, ChatTarget, FileRef, parse_file_links, relay_text, split_message};
|
||||
pub use link::{Link, ServerLink, channel_path_id, join_channel_path, split_channel_path};
|
||||
pub use presence::{
|
||||
ChannelId, ChannelInfo, ClientId, ClientInfo, GroupId, GroupInfo, GroupNamingMode, GroupType,
|
||||
Presence, PresenceDelta, PresenceSnapshot, parse_badges,
|
||||
Presence, PresenceDelta, PresenceSnapshot, myts_avatar_url, parse_badges, shown_badges,
|
||||
};
|
||||
pub use server::{
|
||||
BannerMode, Capabilities, HostMessageMode, ServerDetails, ServerFlavor, ServerVersion,
|
||||
};
|
||||
pub use tree::{TreeRow, order_siblings, tree_rows};
|
||||
pub use tree::{Spacer, TreeRow, channel_title, order_siblings, parse_spacer, tree_rows};
|
||||
@@ -0,0 +1,420 @@
|
||||
//! Server links: `ts3server://` (TeamSpeak 3 and 5), `teamspeak://`
|
||||
//! (TeamSpeak 6) and TeamSpeak's short links on `tmspk.gg`, whose page sends
|
||||
//! the browser on to a `teamspeak://` link.
|
||||
|
||||
use crate::percent;
|
||||
use crate::presence::ChannelId;
|
||||
|
||||
/// What a link opens ([`Link::parse`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Link {
|
||||
/// A server, and maybe a channel on it.
|
||||
Server(ServerLink),
|
||||
/// A TeamSpeak 6 invite code (`tmspk.gg/<code>`,
|
||||
/// `teamspeak://invite=<code>`): only a TeamSpeak service knows the
|
||||
/// server it stands for.
|
||||
Invite(String),
|
||||
}
|
||||
|
||||
/// A server link: the server, and what to join it with (none of it empty).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ServerLink {
|
||||
/// A host name, an IP address (IPv6 without brackets) or a server
|
||||
/// nickname.
|
||||
pub host: String,
|
||||
pub port: Option<u16>,
|
||||
pub nickname: Option<String>,
|
||||
/// The server's password.
|
||||
pub password: Option<String>,
|
||||
/// The channel to join: its names from the top, separated by `/` (a `/`
|
||||
/// in a name as `\/`, [`split_channel_path`]), or `/<id>` (`cid=`).
|
||||
pub channel: Option<String>,
|
||||
pub channel_password: Option<String>,
|
||||
/// A privilege key: it puts its user in a server or channel group.
|
||||
pub token: Option<String>,
|
||||
}
|
||||
|
||||
const SCHEMES: [&str; 2] = ["ts3server://", "teamspeak://"];
|
||||
const WEB: [&str; 2] = ["https://", "http://"];
|
||||
const SHORT_HOSTS: [&str; 2] = ["tmspk.gg", "www.tmspk.gg"];
|
||||
|
||||
impl Link {
|
||||
/// Read a link: `ts3server://<host>?<query>` with the keys `port`,
|
||||
/// `nickname`, `password`, `channel` (`A/B`), `cid`, `channelpassword`
|
||||
/// and `token` (`teamspeak://` alike; the scheme and the keys in any
|
||||
/// case, other keys ignored, a `+` kept as it is),
|
||||
/// `https://tmspk.gg/s/<host>?<query>` (also `/s=<host>`), and the
|
||||
/// invite codes `tmspk.gg/<code>` and `teamspeak://invite=<code>`. None
|
||||
/// for anything else.
|
||||
pub fn parse(text: &str) -> Option<Link> {
|
||||
let text = text.trim();
|
||||
// The same length in bytes: an index of one is one of the other.
|
||||
let lower = text.to_ascii_lowercase();
|
||||
match SCHEMES.iter().find(|s| lower.starts_with(**s)) {
|
||||
Some(scheme) => parse_server(&text[scheme.len()..]),
|
||||
None => parse_short(text, &lower),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ServerLink {
|
||||
/// A link to the server at `address` (`host`, `host:port`, `[v6]`,
|
||||
/// `[v6]:port` or a bare IPv6 address), joining nothing.
|
||||
pub fn new(address: &str) -> Self {
|
||||
let (host, port) = split_address(address.trim());
|
||||
ServerLink { host: host.to_owned(), port, ..Default::default() }
|
||||
}
|
||||
|
||||
/// The server's address as a bookmark keeps it: `host`, `host:port` or
|
||||
/// `[v6]:port`.
|
||||
pub fn address(&self) -> String {
|
||||
match self.port {
|
||||
Some(port) if self.host.contains(':') => format!("[{}]:{port}", self.host),
|
||||
Some(port) => format!("{}:{port}", self.host),
|
||||
None => self.host.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The link as TeamSpeak clients open it: `ts3server://<host>?port=…`,
|
||||
/// then what is set of nickname, password, channel (or `cid` for
|
||||
/// `/<id>`), channel password and privilege key.
|
||||
pub fn to_url(&self) -> String {
|
||||
let mut url = match self.port {
|
||||
Some(_) if self.host.contains(':') => format!("ts3server://[{}]", self.host),
|
||||
_ => format!("ts3server://{}", self.host),
|
||||
};
|
||||
let pair = |key: &str, value: &Option<String>| {
|
||||
let value = value.as_deref().filter(|v| !v.is_empty())?;
|
||||
Some(format!("{key}={}", percent::encode(value)))
|
||||
};
|
||||
let channel = self.channel.as_deref().filter(|c| !c.is_empty()).map(|path| {
|
||||
match channel_path_id(path) {
|
||||
Some(id) => format!("cid={id}"),
|
||||
// A `/` between names, `%2F` in one.
|
||||
None => {
|
||||
let names: Vec<String> =
|
||||
split_channel_path(path).iter().map(|n| percent::encode(n)).collect();
|
||||
format!("channel={}", names.join("/"))
|
||||
}
|
||||
}
|
||||
});
|
||||
let query: Vec<String> = [
|
||||
self.port.map(|port| format!("port={port}")),
|
||||
pair("nickname", &self.nickname),
|
||||
pair("password", &self.password),
|
||||
channel,
|
||||
pair("channelpassword", &self.channel_password),
|
||||
pair("token", &self.token),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect();
|
||||
if !query.is_empty() {
|
||||
url.push('?');
|
||||
url.push_str(&query.join("&"));
|
||||
}
|
||||
url
|
||||
}
|
||||
}
|
||||
|
||||
/// A channel path's names from the top: `Gaming/Raid Night` →
|
||||
/// `["Gaming", "Raid Night"]`, `AC\/DC` → `["AC/DC"]`.
|
||||
pub fn split_channel_path(path: &str) -> Vec<String> {
|
||||
let mut names = Vec::new();
|
||||
let mut name = String::new();
|
||||
let mut chars = path.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
'\\' if chars.peek() == Some(&'/') => {
|
||||
name.push('/');
|
||||
chars.next();
|
||||
}
|
||||
'/' => names.push(std::mem::take(&mut name)),
|
||||
c => name.push(c),
|
||||
}
|
||||
}
|
||||
names.push(name);
|
||||
names
|
||||
}
|
||||
|
||||
/// A channel path from its names from the top, a `/` in a name as `\/`:
|
||||
/// the reverse of [`split_channel_path`].
|
||||
pub fn join_channel_path(names: &[impl AsRef<str>]) -> String {
|
||||
names.iter().map(|n| n.as_ref().replace('/', "\\/")).collect::<Vec<_>>().join("/")
|
||||
}
|
||||
|
||||
/// The channel id of a path `/<id>` (what `cid=` gives).
|
||||
pub fn channel_path_id(path: &str) -> Option<ChannelId> {
|
||||
let id = path.strip_prefix('/')?;
|
||||
if id.is_empty() || !id.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
id.parse().ok()
|
||||
}
|
||||
|
||||
/// After `ts3server://` or `teamspeak://`: `<host>[:port][/]?<query>`, or
|
||||
/// `invite=<code>`.
|
||||
fn parse_server(rest: &str) -> Option<Link> {
|
||||
let (head, query) = rest.split_once('?').unwrap_or((rest, ""));
|
||||
let authority = head.split('/').next().unwrap_or_default();
|
||||
if let Some(key) = authority.get(..7).filter(|k| k.eq_ignore_ascii_case("invite=")) {
|
||||
let code = percent::decode(&authority[key.len()..]);
|
||||
return (!code.is_empty()).then_some(Link::Invite(code));
|
||||
}
|
||||
let authority = percent::decode(authority);
|
||||
let (host, port) = split_address(&authority);
|
||||
if host.is_empty() || host.chars().any(|c| c.is_whitespace() || c.is_control()) {
|
||||
return None;
|
||||
}
|
||||
let mut link = ServerLink { host: host.to_owned(), port, ..Default::default() };
|
||||
let mut cid = None;
|
||||
for pair in query.split('&') {
|
||||
let (key, raw) = pair.split_once('=').unwrap_or((pair, ""));
|
||||
let value = Some(percent::decode(raw)).filter(|v| !v.is_empty());
|
||||
match key.to_ascii_lowercase().as_str() {
|
||||
// One that is no port is ignored.
|
||||
"port" => link.port = value.as_deref().and_then(parse_port).or(link.port),
|
||||
"nickname" => link.nickname = value,
|
||||
"password" => link.password = value,
|
||||
// A `/` between names, `%2F` in one.
|
||||
"channel" => {
|
||||
let names: Vec<String> = raw.split('/').map(percent::decode).collect();
|
||||
link.channel = Some(join_channel_path(&names)).filter(|_| names.concat() != "");
|
||||
}
|
||||
"cid" => cid = value.and_then(|v| v.parse::<ChannelId>().ok()).filter(|c| *c != 0),
|
||||
"channelpassword" => link.channel_password = value,
|
||||
"token" => link.token = value,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// The id names one channel for sure.
|
||||
if let Some(cid) = cid {
|
||||
link.channel = Some(format!("/{cid}"));
|
||||
}
|
||||
Some(Link::Server(link))
|
||||
}
|
||||
|
||||
/// `tmspk.gg/s/<host>?…` (or `/s=`), with or without `https://`, goes where
|
||||
/// its page sends the browser: `teamspeak://<host>?…`; any other path is an
|
||||
/// invite code.
|
||||
fn parse_short(text: &str, lower: &str) -> Option<Link> {
|
||||
let start = WEB.iter().find(|s| lower.starts_with(**s)).map_or(0, |s| s.len());
|
||||
let (host, path) = text[start..].split_once('/')?;
|
||||
if !SHORT_HOSTS.contains(&host.to_ascii_lowercase().as_str()) {
|
||||
return None;
|
||||
}
|
||||
if path.get(..2).is_some_and(|s| s.eq_ignore_ascii_case("s/") || s.eq_ignore_ascii_case("s=")) {
|
||||
return parse_server(&path[2..]);
|
||||
}
|
||||
let code = path.split(['?', '#', '/']).next().unwrap_or_default();
|
||||
let valid = |b: u8| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_');
|
||||
(!code.is_empty() && code.bytes().all(valid)).then(|| Link::Invite(code.to_owned()))
|
||||
}
|
||||
|
||||
/// `host`, `host:port`, `[v6]`, `[v6]:port` or a bare IPv6 address: the
|
||||
/// host (an IPv6 address without its brackets) and the port, if one is
|
||||
/// given that is one.
|
||||
fn split_address(address: &str) -> (&str, Option<u16>) {
|
||||
if let Some((host, after)) = address.strip_prefix('[').and_then(|a| a.split_once(']')) {
|
||||
return (host, after.strip_prefix(':').and_then(parse_port));
|
||||
}
|
||||
match address.rsplit_once(':') {
|
||||
// A port follows the only colon; more colons: an IPv6 address.
|
||||
Some((host, port))
|
||||
if !host.contains(':')
|
||||
&& !port.is_empty()
|
||||
&& port.bytes().all(|b| b.is_ascii_digit()) =>
|
||||
{
|
||||
(host, parse_port(port))
|
||||
}
|
||||
_ => (address, None),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_port(text: &str) -> Option<u16> {
|
||||
text.parse().ok().filter(|p| *p != 0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn server(text: &str) -> ServerLink {
|
||||
match Link::parse(text) {
|
||||
Some(Link::Server(link)) => link,
|
||||
other => panic!("{text}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn host(host: &str, port: Option<u16>) -> ServerLink {
|
||||
ServerLink { host: host.into(), port, ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_parameter() {
|
||||
let link = server(
|
||||
"ts3server://ts.example.org?port=9988&nickname=Nova%20X&password=s3cr%3Ft&channel=Gaming/Raid%20Night&channelpassword=raid+1&token=AbC%2Bd&addbookmark=Mine",
|
||||
);
|
||||
assert_eq!(
|
||||
link,
|
||||
ServerLink {
|
||||
host: "ts.example.org".into(),
|
||||
port: Some(9988),
|
||||
nickname: Some("Nova X".into()),
|
||||
password: Some("s3cr?t".into()),
|
||||
channel: Some("Gaming/Raid Night".into()),
|
||||
// A `+` stays.
|
||||
channel_password: Some("raid+1".into()),
|
||||
token: Some("AbC+d".into()),
|
||||
}
|
||||
);
|
||||
assert_eq!(link.address(), "ts.example.org:9988");
|
||||
assert_eq!(
|
||||
link.to_url(),
|
||||
"ts3server://ts.example.org?port=9988&nickname=Nova%20X&password=s3cr%3Ft&channel=Gaming/Raid%20Night&channelpassword=raid%2B1&token=AbC%2Bd"
|
||||
);
|
||||
assert_eq!(Link::parse(&link.to_url()), Some(Link::Server(link)));
|
||||
// A channel id names the channel, also next to a path.
|
||||
assert_eq!(server("ts3server://h?cid=12").channel.as_deref(), Some("/12"));
|
||||
assert_eq!(server("ts3server://h?channel=Lobby&cid=12").channel.as_deref(), Some("/12"));
|
||||
assert_eq!(server("ts3server://h?cid=x&channel=Lobby").channel.as_deref(), Some("Lobby"));
|
||||
assert_eq!(server("ts3server://h?cid=12").to_url(), "ts3server://h?cid=12");
|
||||
// Empty values are none.
|
||||
assert_eq!(server("ts3server://h?nickname=&channel=&password"), host("h", None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teamspeak_scheme_is_the_same() {
|
||||
let query = "ts.example.org?port=9987&channel=Lobby&nickname=Nova";
|
||||
assert_eq!(
|
||||
Link::parse(&format!("teamspeak://{query}")),
|
||||
Link::parse(&format!("ts3server://{query}"))
|
||||
);
|
||||
// Any case, of the scheme and the keys; the host as written.
|
||||
let link = server("TeamSpeak://TS.Example.org/?PORT=9988&Channel=Lobby&CID=");
|
||||
assert_eq!(
|
||||
link,
|
||||
ServerLink { channel: Some("Lobby".into()), ..host("TS.Example.org", Some(9988)) }
|
||||
);
|
||||
assert_eq!(server("TS3SERVER://h:9988"), host("h", Some(9988)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_links() {
|
||||
for text in [
|
||||
"https://tmspk.gg/s/ts.example.org?port=9988&channel=Lobby",
|
||||
"https://tmspk.gg/s=ts.example.org?port=9988&channel=Lobby",
|
||||
"HTTPS://www.TMSPK.gg/S/ts.example.org?port=9988&channel=Lobby",
|
||||
"tmspk.gg/s/ts.example.org/?port=9988&channel=Lobby",
|
||||
"http://tmspk.gg/s/ts.example.org:9988?channel=Lobby",
|
||||
] {
|
||||
assert_eq!(
|
||||
server(text),
|
||||
ServerLink { channel: Some("Lobby".into()), ..host("ts.example.org", Some(9988)) },
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
let invite = |code: &str| Some(Link::Invite(code.into()));
|
||||
assert_eq!(Link::parse("https://tmspk.gg/AbC12x"), invite("AbC12x"));
|
||||
assert_eq!(Link::parse("tmspk.gg/AbC12x/?ref=1"), invite("AbC12x"));
|
||||
assert_eq!(Link::parse("teamspeak://invite=AbC12x"), invite("AbC12x"));
|
||||
assert_eq!(Link::parse("TEAMSPEAK://Invite=AbC12x/"), invite("AbC12x"));
|
||||
for text in ["https://tmspk.gg/", "https://tmspk.gg", "tmspk.gg/a.b", "teamspeak://invite="]
|
||||
{
|
||||
assert_eq!(Link::parse(text), None, "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ipv6() {
|
||||
let v6 = host("2001:db8::1", Some(9987));
|
||||
assert_eq!(server("ts3server://[2001:db8::1]?port=9987"), v6);
|
||||
assert_eq!(server("ts3server://[2001:db8::1]:9987"), v6);
|
||||
assert_eq!(v6.address(), "[2001:db8::1]:9987");
|
||||
assert_eq!(v6.to_url(), "ts3server://[2001:db8::1]?port=9987");
|
||||
// Without a port, with or without brackets.
|
||||
let bare = host("2001:db8::1", None);
|
||||
assert_eq!(server("ts3server://2001:db8::1"), bare);
|
||||
assert_eq!(server("ts3server://[2001:db8::1]"), bare);
|
||||
assert_eq!(bare.address(), "2001:db8::1");
|
||||
assert_eq!(ServerLink::new(" [2001:db8::1]:9988 "), host("2001:db8::1", Some(9988)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escapes() {
|
||||
let link = server("ts3server://h?channel=%C3%84rger/Caf%C3%A9&nickname=J%C3%BCrgen");
|
||||
assert_eq!(link.channel.as_deref(), Some("Ärger/Café"));
|
||||
assert_eq!(link.nickname.as_deref(), Some("Jürgen"));
|
||||
// `%2F` is a `/` in a name.
|
||||
let link = server("ts3server://h?channel=AC%2FDC/Live");
|
||||
assert_eq!(link.channel.as_deref(), Some("AC\\/DC/Live"));
|
||||
assert_eq!(split_channel_path("AC\\/DC/Live"), ["AC/DC", "Live"]);
|
||||
assert_eq!(join_channel_path(&["AC/DC", "Live"]), "AC\\/DC/Live");
|
||||
assert_eq!(link.to_url(), "ts3server://h?channel=AC%2FDC/Live");
|
||||
assert_eq!(split_channel_path("Lobby"), ["Lobby"]);
|
||||
assert_eq!(channel_path_id("/12"), Some(12));
|
||||
assert_eq!(channel_path_id("12"), None);
|
||||
assert_eq!(channel_path_id("/1a"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_ports_are_ignored() {
|
||||
for text in [
|
||||
"ts3server://h?port=abc",
|
||||
"ts3server://h?port=70000",
|
||||
"ts3server://h?port=0",
|
||||
"ts3server://h?port=",
|
||||
"ts3server://h:70000",
|
||||
] {
|
||||
assert_eq!(server(text), host("h", None), "{text}");
|
||||
}
|
||||
// One in the address stays.
|
||||
assert_eq!(server("ts3server://h:9988?port=x"), host("h", Some(9988)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_links_are_none() {
|
||||
for text in [
|
||||
"",
|
||||
"http://example.com",
|
||||
"https://example.com/s/ts.example.org",
|
||||
"ts3file://a.png?serverUID=x&channel=1",
|
||||
"ts3server://",
|
||||
"ts3server://?port=9987",
|
||||
"ts3server://a b",
|
||||
"ts.example.org",
|
||||
"mailto:a@example.org",
|
||||
] {
|
||||
assert_eq!(Link::parse(text), None, "{text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip() {
|
||||
// The invite links of voelin-ui (`vm::servers::invite_link`).
|
||||
for (address, names, url) in [
|
||||
(
|
||||
"ts.example.com:9988",
|
||||
&["Gaming", "Raid Night"][..],
|
||||
"ts3server://ts.example.com?port=9988&channel=Gaming/Raid%20Night",
|
||||
),
|
||||
(" ts.example.com ", &[], "ts3server://ts.example.com"),
|
||||
(
|
||||
"[2001:db8::1]:9987",
|
||||
&["Chill & Co"],
|
||||
"ts3server://[2001:db8::1]?port=9987&channel=Chill%20%26%20Co",
|
||||
),
|
||||
("2001:db8::1", &[], "ts3server://2001:db8::1"),
|
||||
("h:x", &["Ä/b"], "ts3server://h:x?channel=%C3%84%2Fb"),
|
||||
] {
|
||||
let mut link = ServerLink::new(address);
|
||||
link.channel = (!names.is_empty()).then(|| join_channel_path(names));
|
||||
assert_eq!(link.to_url(), url);
|
||||
assert_eq!(Link::parse(url), Some(Link::Server(link.clone())), "{url}");
|
||||
assert_eq!(link.address(), address.trim());
|
||||
if let Some(path) = &link.channel {
|
||||
assert_eq!(split_channel_path(path), names);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
//! Percent escapes in links: file links ([`crate::FileRef`]) and server
|
||||
//! links ([`crate::Link`]).
|
||||
|
||||
/// `%XX` escapes to bytes, read as UTF-8 (a `+` stays: file names and
|
||||
/// passwords keep theirs).
|
||||
pub(crate) fn decode(s: &str) -> String {
|
||||
let bytes = s.as_bytes();
|
||||
let hex = |b: u8| (b as char).to_digit(16);
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'%'
|
||||
&& let (Some(h), Some(l)) =
|
||||
(bytes.get(i + 1).and_then(|b| hex(*b)), bytes.get(i + 2).and_then(|b| hex(*b)))
|
||||
{
|
||||
out.push((h * 16 + l) as u8);
|
||||
i += 3;
|
||||
continue;
|
||||
}
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
/// Every byte but letters, digits and `-._~` as `%XX`.
|
||||
pub(crate) fn encode(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for b in s.bytes() {
|
||||
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
|
||||
out.push(b as char);
|
||||
} else {
|
||||
out.push_str(&format!("%{b:02X}"));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn escapes() {
|
||||
assert_eq!(decode("Raid%20Night"), "Raid Night");
|
||||
assert_eq!(decode("%C3%84b"), "Äb");
|
||||
assert_eq!(decode("a+b"), "a+b");
|
||||
// A broken escape stays as it is.
|
||||
assert_eq!(decode("100%"), "100%");
|
||||
assert_eq!(decode("%zz"), "%zz");
|
||||
assert_eq!(encode("Chill & Co/Ä"), "Chill%20%26%20Co%2F%C3%84");
|
||||
assert_eq!(decode(&encode("a b+c%")), "a b+c%");
|
||||
}
|
||||
}
|
||||
@@ -98,6 +98,11 @@ pub struct ClientInfo {
|
||||
/// no avatar. A new hash means a new avatar.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub avatar: Option<String>,
|
||||
/// The myTeamSpeak avatar's picture (TeamSpeak 6, an HTTPS link from
|
||||
/// `client_myteamspeak_avatar`, [`myts_avatar_url`]): shown where the
|
||||
/// server has no avatar for the client.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub myts_avatar: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub description: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "is_zero_i32")]
|
||||
@@ -107,7 +112,7 @@ pub struct ClientInfo {
|
||||
pub talker: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub channel_group: Option<GroupId>,
|
||||
/// Badge GUIDs (`client_badges`), in display order.
|
||||
/// Badge GUIDs, in display order ([`shown_badges`]).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub badges: Vec<String>,
|
||||
/// Icon id (`client_icon_id`); 0: none.
|
||||
@@ -136,6 +141,48 @@ pub fn parse_badges(value: &str) -> Vec<String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The badges a client shows: those a TeamSpeak 6 server verified
|
||||
/// (`client_signed_badges`, ids joined by `,`) first, then those of its
|
||||
/// `client_badges` ([`parse_badges`]), each once.
|
||||
pub fn shown_badges(badges: &str, signed: &str) -> Vec<String> {
|
||||
let signed = signed.split(',').map(str::trim).filter(|g| !g.is_empty()).map(str::to_owned);
|
||||
let mut shown: Vec<String> = Vec::new();
|
||||
for guid in signed.chain(parse_badges(badges)) {
|
||||
if !shown.iter().any(|g| g.eq_ignore_ascii_case(&guid)) {
|
||||
shown.push(guid);
|
||||
}
|
||||
}
|
||||
shown
|
||||
}
|
||||
|
||||
/// The picture to show of a `client_myteamspeak_avatar` value (TeamSpeak
|
||||
/// 6): `<state>,<url>;<state>,<url>…`, states as myTeamSpeak's
|
||||
/// `AvatarState` (1 do not disturb, 2 online, 3 away, 4 offline). As the
|
||||
/// official client reads it: an entry that is not `<number>,<url>` (an
|
||||
/// empty one too, from a trailing `;`) makes the whole value no avatar;
|
||||
/// the "online" picture is shown whatever the client's state (an unknown
|
||||
/// state counts as online), else away, do not disturb, offline, the first
|
||||
/// of a kind. Only an HTTPS link of at most 4 KiB.
|
||||
pub fn myts_avatar_url(value: &str) -> Option<String> {
|
||||
let mut best: Option<(u8, &str)> = None;
|
||||
for entry in value.split(';') {
|
||||
let mut parts = entry.split(',');
|
||||
let state: u32 = parts.next()?.trim().parse().ok()?;
|
||||
let url = parts.next()?.trim();
|
||||
let rank = match state {
|
||||
3 => 1,
|
||||
1 => 2,
|
||||
4 => 3,
|
||||
_ => 0,
|
||||
};
|
||||
if best.is_none_or(|(r, _)| rank < r) {
|
||||
best = Some((rank, url));
|
||||
}
|
||||
}
|
||||
let url = best?.1;
|
||||
(url.starts_with("https://") && url.len() <= 4096).then(|| url.to_owned())
|
||||
}
|
||||
|
||||
/// How a group's name is shown next to its members.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
@@ -348,6 +395,38 @@ mod tests {
|
||||
assert!(new.diff(&new).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn myts_avatars_as_the_official_client_reads_them() {
|
||||
let on = "https://a.example.test/on.png";
|
||||
assert_eq!(myts_avatar_url(&format!("3,https://a/away;2,{on}")).as_deref(), Some(on));
|
||||
// Away before do not disturb before offline; the first of a kind.
|
||||
assert_eq!(
|
||||
myts_avatar_url("4,https://a/off;1,https://a/dnd;3,https://a/away;3,https://a/b")
|
||||
.as_deref(),
|
||||
Some("https://a/away")
|
||||
);
|
||||
assert_eq!(
|
||||
myts_avatar_url("1,https://a/dnd;4,https://a/off").as_deref(),
|
||||
Some("https://a/dnd")
|
||||
);
|
||||
// An unknown state counts as online.
|
||||
assert_eq!(
|
||||
myts_avatar_url("3,https://a/away;9,https://a/x").as_deref(),
|
||||
Some("https://a/x")
|
||||
);
|
||||
// One bad entry spoils the value.
|
||||
for bad in ["", "2", "x,https://a/on", "2,https://a/on;", "2,https://a/on;;3,https://a/b"] {
|
||||
assert_eq!(myts_avatar_url(bad), None, "{bad:?}");
|
||||
}
|
||||
// Only HTTPS, and not endless.
|
||||
assert_eq!(myts_avatar_url("2,http://a/on"), None);
|
||||
assert_eq!(myts_avatar_url(&format!("2,https://a/{}", "x".repeat(4096))), None);
|
||||
// Older JSON without the field still loads.
|
||||
let client: ClientInfo =
|
||||
serde_json::from_str(r#"{"id":1,"nickname":"a","channel":1}"#).unwrap();
|
||||
assert_eq!(client.myts_avatar, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn badges_and_groups() {
|
||||
assert_eq!(
|
||||
@@ -358,6 +437,19 @@ mod tests {
|
||||
);
|
||||
assert!(parse_badges("").is_empty());
|
||||
assert!(parse_badges("Overwolf=1").is_empty());
|
||||
// TeamSpeak 6's verified badges first, each once.
|
||||
assert_eq!(
|
||||
shown_badges(
|
||||
"Overwolf=0:badges=c9e97536-5a2d-4c8e-a135-af404587a472,450f81c1-ab41-4211-a338-222fa94ed157",
|
||||
"450F81C1-AB41-4211-A338-222FA94ED157,1cb07348-34a4-4741-b50f-c41e584370f7"
|
||||
),
|
||||
[
|
||||
"450F81C1-AB41-4211-A338-222FA94ED157",
|
||||
"1cb07348-34a4-4741-b50f-c41e584370f7",
|
||||
"c9e97536-5a2d-4c8e-a135-af404587a472"
|
||||
]
|
||||
);
|
||||
assert!(shown_badges("", "").is_empty());
|
||||
let group = |id, sort_id| GroupInfo { id, sort_id, ..Default::default() };
|
||||
let groups = BTreeMap::from([(1, group(1, 20)), (2, group(2, 10)), (3, group(3, 10))]);
|
||||
let order: Vec<_> = Presence::sorted_groups(&groups).iter().map(|g| g.id).collect();
|
||||
|
||||
@@ -184,6 +184,11 @@ pub struct ServerDetails {
|
||||
pub version: String,
|
||||
#[serde(default)]
|
||||
pub max_clients: u16,
|
||||
/// How much everyone else is dimmed while a priority speaker talks
|
||||
/// (dB, e.g. -18; `virtualserver_priority_speaker_dimm_modificator`,
|
||||
/// rounded).
|
||||
#[serde(default)]
|
||||
pub priority_speaker_dimm_db: i32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub default_server_group: Option<u64>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Flatten presence into display rows in TeamSpeak's channel order.
|
||||
//! Flatten presence into display rows in TeamSpeak's channel order, and
|
||||
//! read the names of spacer channels.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -64,6 +65,51 @@ fn add_level<'a>(
|
||||
}
|
||||
}
|
||||
|
||||
/// How a TeamSpeak spacer channel draws its text.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Spacer {
|
||||
Left,
|
||||
Center,
|
||||
Right,
|
||||
/// The text repeated across the row: a line such as `---`.
|
||||
Fill,
|
||||
}
|
||||
|
||||
impl Spacer {
|
||||
/// Whether a spacer with this text only separates the rows around it
|
||||
/// (a line, or no text): nothing to search for or pick.
|
||||
pub fn separates(self, text: &str) -> bool {
|
||||
self == Spacer::Fill || text.trim().is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// A spacer name split into its kind and its text: `[cspacer]Games` is a
|
||||
/// centred "Games", `[*spacer1]-=` repeats "-=", plain `[spacer3]` is an
|
||||
/// empty row. The part between `spacer` and `]` only keeps the names
|
||||
/// unique, so anything goes there. Anything else is not a spacer.
|
||||
pub fn parse_spacer(name: &str) -> Option<(Spacer, &str)> {
|
||||
let (inside, text) = name.strip_prefix('[')?.split_once(']')?;
|
||||
let (kind, _suffix) = inside.split_once("spacer")?;
|
||||
let kind = match kind {
|
||||
"" | "l" => Spacer::Left,
|
||||
"c" => Spacer::Center,
|
||||
"r" => Spacer::Right,
|
||||
"*" => Spacer::Fill,
|
||||
_ => return None,
|
||||
};
|
||||
Some((kind, text))
|
||||
}
|
||||
|
||||
/// A channel's name as shown, and its spacer kind. Only top-level channels
|
||||
/// are spacers, as in TeamSpeak: a sub-channel keeps its name as it is.
|
||||
/// Names sent to the server (joining by name, invite links) stay raw.
|
||||
pub fn channel_title(channel: &ChannelInfo) -> (&str, Option<Spacer>) {
|
||||
match parse_spacer(&channel.name).filter(|_| channel.parent == 0) {
|
||||
Some((kind, text)) => (text, Some(kind)),
|
||||
None => (&channel.name, None),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -113,4 +159,34 @@ mod tests {
|
||||
["0#Lobby", "1-Alice", "1-zed", "0#Games"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spacer_names() {
|
||||
use Spacer::*;
|
||||
for (name, spacer) in [
|
||||
("[spacer0]", Some((Left, ""))),
|
||||
("[spacer3]Hi", Some((Left, "Hi"))),
|
||||
("[lspacer]Hi", Some((Left, "Hi"))),
|
||||
("[rspacer9]Hi", Some((Right, "Hi"))),
|
||||
("[cspacer]Hi", Some((Center, "Hi"))),
|
||||
("[cspacerx]Hi", Some((Center, "Hi"))),
|
||||
("[cspacer12]Гамесы [1]", Some((Center, "Гамесы [1]"))),
|
||||
("[*spacer1]-=", Some((Fill, "-="))),
|
||||
("[*spacer]", Some((Fill, ""))),
|
||||
("[cspacer2Games", None),
|
||||
("Games", None),
|
||||
("[Spacer]x", None),
|
||||
("[xspacer]x", None),
|
||||
("[spacr]x", None),
|
||||
("x[spacer]", None),
|
||||
] {
|
||||
assert_eq!(parse_spacer(name), spacer, "{name}");
|
||||
}
|
||||
assert!(Fill.separates("-=") && Left.separates("") && Center.separates(" "));
|
||||
assert!(!Left.separates("Hi"));
|
||||
// Only top-level channels are spacers: a sub-channel keeps its name.
|
||||
assert_eq!(channel_title(&ch(1, 0, 0, "[rspacer]Staff")), ("Staff", Some(Right)));
|
||||
assert_eq!(channel_title(&ch(2, 1, 0, "[rspacer]Staff")), ("[rspacer]Staff", None));
|
||||
assert_eq!(channel_title(&ch(3, 0, 0, "Lobby")), ("Lobby", None));
|
||||
}
|
||||
}
|
||||
@@ -89,6 +89,7 @@ pub fn client_from_row(row: &Row) -> Option<ClientInfo> {
|
||||
// What the row carries (`notifycliententerview` all of it,
|
||||
// `clientlist -voice -groups -icon` some).
|
||||
avatar: row.get("client_flag_avatar").filter(|a| !a.is_empty()).map(str::to_string),
|
||||
myts_avatar: row.get("client_myteamspeak_avatar").and_then(voelin_model::myts_avatar_url),
|
||||
description: row.get("client_description").filter(|d| !d.is_empty()).map(str::to_string),
|
||||
talk_power: row.parse("client_talk_power").unwrap_or(0),
|
||||
talker: row.flag("client_is_talker").unwrap_or(false),
|
||||
|
||||
@@ -14,4 +14,4 @@ mod relay;
|
||||
|
||||
pub use convert::{channel_from_row, client_from_row, delta_from_notification, is_text_message};
|
||||
pub use observer::{Observer, ObserverConfig, ObserverEvent};
|
||||
pub use relay::{RelayConfig, RelayEvent, RelayPool};
|
||||
pub use relay::{RelayConfig, RelayEvent, RelayPool, post_as};
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Keep a server's presence up to date from one query session.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -7,7 +8,7 @@ use tokio::sync::{broadcast, watch};
|
||||
use tokio::time::{Instant, sleep, sleep_until};
|
||||
use tracing::{debug, info, warn};
|
||||
use voelin_model::{ChatMessage, Presence, PresenceDelta, PresenceSnapshot};
|
||||
use voelin_query::{Command, Connect, Notification, QueryClient};
|
||||
use voelin_query::{Command, Connect, Notification, QueryClient, attempt_worth_a_warning};
|
||||
|
||||
use crate::convert::{
|
||||
channel_from_row, client_from_row, delta_from_notification, is_text_message, update_channel,
|
||||
@@ -15,24 +16,18 @@ use crate::convert::{
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ObserverConfig {
|
||||
/// Reconnects wait [`Connect::retry_delay`].
|
||||
pub connect: Connect,
|
||||
/// Full resync interval. Query sessions receive no `notifyclientupdated`,
|
||||
/// so mute/away changes are only noticed by re-reading the client list.
|
||||
pub poll_interval: Duration,
|
||||
/// Also deliver server chat (`event=textserver`).
|
||||
pub server_chat: bool,
|
||||
/// Wait between reconnect attempts.
|
||||
pub reconnect_delay: Duration,
|
||||
}
|
||||
|
||||
impl ObserverConfig {
|
||||
pub fn new(connect: Connect) -> Self {
|
||||
Self {
|
||||
connect,
|
||||
poll_interval: Duration::from_secs(10),
|
||||
server_chat: true,
|
||||
reconnect_delay: Duration::from_secs(5),
|
||||
}
|
||||
Self { connect, poll_interval: Duration::from_secs(10), server_chat: true }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +45,7 @@ pub enum ObserverEvent {
|
||||
pub struct Observer {
|
||||
presence: Arc<RwLock<Presence>>,
|
||||
events: broadcast::Sender<ObserverEvent>,
|
||||
connected: Arc<AtomicBool>,
|
||||
_stop: watch::Sender<()>,
|
||||
}
|
||||
|
||||
@@ -58,8 +54,19 @@ impl Observer {
|
||||
let presence = Arc::new(RwLock::new(Presence::default()));
|
||||
let (events, _) = broadcast::channel(1024);
|
||||
let (stop, stopped) = watch::channel(());
|
||||
tokio::spawn(run(config, presence.clone(), events.clone(), stopped));
|
||||
Self { presence, events, _stop: stop }
|
||||
let connected = Arc::new(AtomicBool::new(false));
|
||||
let state = State {
|
||||
presence: presence.clone(),
|
||||
events: events.clone(),
|
||||
connected: connected.clone(),
|
||||
};
|
||||
tokio::spawn(run(config, state, stopped));
|
||||
Self { presence, events, connected, _stop: stop }
|
||||
}
|
||||
|
||||
/// Connected and in sync with the server.
|
||||
pub fn is_connected(&self) -> bool {
|
||||
self.connected.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Receive events. Call [`Observer::snapshot`] after subscribing to get
|
||||
@@ -77,25 +84,48 @@ impl Observer {
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(
|
||||
config: ObserverConfig,
|
||||
/// What the observer task shares with its handle.
|
||||
struct State {
|
||||
presence: Arc<RwLock<Presence>>,
|
||||
events: broadcast::Sender<ObserverEvent>,
|
||||
mut stopped: watch::Receiver<()>,
|
||||
) {
|
||||
connected: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
async fn run(config: ObserverConfig, state: State, mut stopped: watch::Receiver<()>) {
|
||||
let mut connect = config.connect.clone();
|
||||
connect.line.label = "observer".into();
|
||||
// Attempts since the last connection that worked.
|
||||
let mut attempt = 0u32;
|
||||
loop {
|
||||
attempt += 1;
|
||||
let started = Instant::now();
|
||||
let result = tokio::select! {
|
||||
r = session(&config, &presence, &events) => r,
|
||||
r = session(&config, &connect, &state, attempt, started) => r,
|
||||
_ = stopped.changed() => return,
|
||||
};
|
||||
let reason = match result {
|
||||
Ok(()) => "connection closed".to_string(),
|
||||
Err(e) => e.to_string(),
|
||||
};
|
||||
warn!(%reason, addr = %config.connect.addr, "observer disconnected");
|
||||
let _ = events.send(ObserverEvent::Disconnected(reason));
|
||||
let lost = state.connected.swap(false, Ordering::Relaxed);
|
||||
if lost {
|
||||
attempt = 0;
|
||||
}
|
||||
// Longer after each failure, or as long as the server asked.
|
||||
let retry_in = connect.retry_delay(attempt.max(1));
|
||||
let retry_in_s = retry_in.as_secs_f32();
|
||||
let elapsed_ms = started.elapsed().as_millis() as u64;
|
||||
if lost {
|
||||
let connected_for_s = started.elapsed().as_secs();
|
||||
warn!(%reason, addr = %connect.addr, connected_for_s, retry_in_s, "observer disconnected");
|
||||
} else if attempt_worth_a_warning(attempt) {
|
||||
warn!(%reason, addr = %connect.addr, attempt, elapsed_ms, retry_in_s, "observer could not connect");
|
||||
} else {
|
||||
debug!(%reason, addr = %connect.addr, attempt, elapsed_ms, retry_in_s, "observer could not connect");
|
||||
}
|
||||
let _ = state.events.send(ObserverEvent::Disconnected(reason));
|
||||
tokio::select! {
|
||||
_ = sleep(config.reconnect_delay) => {}
|
||||
_ = sleep(retry_in) => {}
|
||||
_ = stopped.changed() => return,
|
||||
}
|
||||
}
|
||||
@@ -145,10 +175,13 @@ fn now_ms() -> i64 {
|
||||
|
||||
async fn session(
|
||||
config: &ObserverConfig,
|
||||
presence: &RwLock<Presence>,
|
||||
events: &broadcast::Sender<ObserverEvent>,
|
||||
connect: &Connect,
|
||||
state: &State,
|
||||
attempt: u32,
|
||||
started: Instant,
|
||||
) -> voelin_query::Result<()> {
|
||||
let (client, mut notifications) = QueryClient::connect(&config.connect).await?;
|
||||
let (presence, events) = (&*state.presence, &state.events);
|
||||
let (client, mut notifications) = QueryClient::connect(connect).await?;
|
||||
if notifications.is_some() {
|
||||
for event in ["server", "channel"] {
|
||||
let mut cmd = Command::new("servernotifyregister").arg("event", event);
|
||||
@@ -161,16 +194,19 @@ async fn session(
|
||||
client.send(&Command::new("servernotifyregister").arg("event", "textserver")).await?;
|
||||
}
|
||||
}
|
||||
let state = load(&client).await?;
|
||||
let loaded = load(&client).await?;
|
||||
info!(
|
||||
server = %state.server_name,
|
||||
channels = state.channels.len(),
|
||||
clients = state.clients.len(),
|
||||
server = %loaded.server_name,
|
||||
channels = loaded.channels.len(),
|
||||
clients = loaded.clients.len(),
|
||||
events = notifications.is_some(),
|
||||
attempt,
|
||||
elapsed_ms = started.elapsed().as_millis() as u64,
|
||||
"observer connected"
|
||||
);
|
||||
*presence.write().unwrap() = state.clone();
|
||||
let _ = events.send(ObserverEvent::Snapshot(state.snapshot()));
|
||||
*presence.write().unwrap() = loaded.clone();
|
||||
state.connected.store(true, Ordering::Relaxed);
|
||||
let _ = events.send(ObserverEvent::Snapshot(loaded.snapshot()));
|
||||
|
||||
let mut next_poll = Instant::now() + config.poll_interval;
|
||||
loop {
|
||||
@@ -191,7 +227,8 @@ async fn session(
|
||||
Some(n) => handle_notification(&n, presence, events),
|
||||
None => {
|
||||
// Resync and publish only what changed.
|
||||
let fresh = load(&client).await?;
|
||||
let listed = load(&client).await?;
|
||||
let fresh = keep_unlisted(&presence.read().unwrap(), listed);
|
||||
let deltas = presence.read().unwrap().diff(&fresh);
|
||||
if !deltas.is_empty() {
|
||||
debug!(changes = deltas.len(), "observer resync");
|
||||
@@ -206,6 +243,24 @@ async fn session(
|
||||
}
|
||||
}
|
||||
|
||||
/// What `clientlist` does not tell (the avatars, which come with
|
||||
/// `notifycliententerview` and `notifyclientupdated`), kept from what was
|
||||
/// known of the same client: a resync must not take them away.
|
||||
fn keep_unlisted(old: &Presence, mut fresh: Presence) -> Presence {
|
||||
for (id, client) in &mut fresh.clients {
|
||||
let Some(known) = old.clients.get(id).filter(|known| known.uid == client.uid) else {
|
||||
continue;
|
||||
};
|
||||
if client.avatar.is_none() {
|
||||
client.avatar.clone_from(&known.avatar);
|
||||
}
|
||||
if client.myts_avatar.is_none() {
|
||||
client.myts_avatar.clone_from(&known.myts_avatar);
|
||||
}
|
||||
}
|
||||
fresh
|
||||
}
|
||||
|
||||
fn handle_notification(
|
||||
n: &Notification,
|
||||
presence: &RwLock<Presence>,
|
||||
@@ -240,3 +295,36 @@ fn handle_notification(
|
||||
let _ = events.send(ObserverEvent::Delta(d));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod resync_tests {
|
||||
use super::*;
|
||||
use voelin_model::ClientInfo;
|
||||
|
||||
#[test]
|
||||
fn a_resync_keeps_the_avatars_the_list_does_not_tell() {
|
||||
let client = |uid: &str, myts: Option<&str>| ClientInfo {
|
||||
id: 5,
|
||||
uid: Some(uid.into()),
|
||||
nickname: "a".into(),
|
||||
avatar: myts.map(|_| "0123456789abcdef0123456789abcdef".into()),
|
||||
myts_avatar: myts.map(Into::into),
|
||||
..Default::default()
|
||||
};
|
||||
let mut old = Presence::default();
|
||||
old.clients.insert(5, client("u=", Some("https://a.example.test/on.png")));
|
||||
let mut listed = Presence::default();
|
||||
listed.clients.insert(5, client("u=", None));
|
||||
let fresh = keep_unlisted(&old, listed.clone());
|
||||
assert_eq!(fresh.clients[&5], old.clients[&5]);
|
||||
assert!(old.diff(&fresh).is_empty());
|
||||
// Another client in the same slot starts without them.
|
||||
let mut other = Presence::default();
|
||||
other.clients.insert(5, client("v=", None));
|
||||
let fresh = keep_unlisted(&old, other);
|
||||
assert_eq!(
|
||||
(fresh.clients[&5].avatar.clone(), fresh.clients[&5].myts_avatar.clone()),
|
||||
(None, None)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,12 @@
|
||||
//! TeamSpeak only delivers channel chat to clients in that channel, and a
|
||||
//! client can only post to its own channel. A relay session is an invisible
|
||||
//! query client moved into the channel; it forwards what is said there and
|
||||
//! posts messages on behalf of users as `[Nick] text`.
|
||||
//! posts messages on behalf of users under their own nickname ([`post_as`]).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
use tokio::sync::{Mutex, broadcast, mpsc};
|
||||
use tokio::task::JoinHandle;
|
||||
@@ -23,13 +25,17 @@ const ERR_ALREADY_MEMBER: u32 = 770;
|
||||
|
||||
/// TeamSpeak's limit for one text message.
|
||||
const MAX_MESSAGE_BYTES: usize = 1024;
|
||||
/// TeamSpeak's limits for a nickname, in characters.
|
||||
const MIN_NICKNAME_CHARS: usize = 3;
|
||||
const MAX_NICKNAME_CHARS: usize = 30;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RelayConfig {
|
||||
pub connect: Connect,
|
||||
/// Base nickname; the channel id is appended because nicknames are unique.
|
||||
pub nickname: String,
|
||||
/// How posts appear, with `{nick}` and `{text}` placeholders.
|
||||
/// How posts appear when the relay cannot take the author's nickname
|
||||
/// ([`post_as`]), with `{nick}` and `{text}` placeholders.
|
||||
pub format: String,
|
||||
}
|
||||
|
||||
@@ -49,6 +55,11 @@ pub enum RelayEvent {
|
||||
|
||||
struct Session {
|
||||
client: QueryClient,
|
||||
opened: Instant,
|
||||
/// The relay's own nickname, taken back after each post.
|
||||
nickname: String,
|
||||
/// One post at a time: each borrows the author's nickname.
|
||||
posting: Arc<Mutex<()>>,
|
||||
task: JoinHandle<()>,
|
||||
}
|
||||
|
||||
@@ -63,13 +74,29 @@ impl Drop for Session {
|
||||
pub struct RelayPool {
|
||||
config: Arc<RelayConfig>,
|
||||
sessions: Arc<Mutex<HashMap<ChannelId, Session>>>,
|
||||
/// Held while a channel's relay opens or closes, so opening one channel
|
||||
/// (a login and a few commands) holds up nobody in other channels.
|
||||
gates: Arc<std::sync::Mutex<HashMap<ChannelId, Arc<Mutex<()>>>>>,
|
||||
/// Set by [`RelayPool::close_all`]: the pool opens no more relays.
|
||||
closed: Arc<AtomicBool>,
|
||||
events: broadcast::Sender<RelayEvent>,
|
||||
}
|
||||
|
||||
impl RelayPool {
|
||||
pub fn new(config: RelayConfig) -> Self {
|
||||
let (events, _) = broadcast::channel(1024);
|
||||
Self { config: Arc::new(config), sessions: Default::default(), events }
|
||||
Self {
|
||||
config: Arc::new(config),
|
||||
sessions: Default::default(),
|
||||
gates: Default::default(),
|
||||
closed: Default::default(),
|
||||
events,
|
||||
}
|
||||
}
|
||||
|
||||
fn gate(&self, channel: ChannelId) -> Arc<Mutex<()>> {
|
||||
let mut gates = self.gates.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
gates.entry(channel).or_default().clone()
|
||||
}
|
||||
|
||||
pub fn subscribe(&self) -> broadcast::Receiver<RelayEvent> {
|
||||
@@ -81,18 +108,43 @@ impl RelayPool {
|
||||
self.sessions.lock().await.keys().copied().collect()
|
||||
}
|
||||
|
||||
/// [`RelayPool::close_all`] was called: opening fails with
|
||||
/// [`voelin_query::Error::Closed`].
|
||||
pub fn is_closed(&self) -> bool {
|
||||
self.closed.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Start relaying a channel (no-op if already open).
|
||||
pub async fn open(&self, channel: ChannelId) -> voelin_query::Result<()> {
|
||||
let mut sessions = self.sessions.lock().await;
|
||||
let gate = self.gate(channel);
|
||||
let _opening = gate.lock().await;
|
||||
if self.is_closed() {
|
||||
return Err(voelin_query::Error::Closed);
|
||||
}
|
||||
let sessions = self.sessions.lock().await;
|
||||
if sessions.get(&channel).is_some_and(|s| !s.task.is_finished()) {
|
||||
return Ok(());
|
||||
}
|
||||
let (client, notifications) = QueryClient::connect(&self.config.connect).await?;
|
||||
drop(sessions);
|
||||
let started = Instant::now();
|
||||
let session = self.connect(channel).await.inspect_err(|error| {
|
||||
let elapsed_ms = started.elapsed().as_millis() as u64;
|
||||
warn!(channel, elapsed_ms, %error, "relay could not be opened");
|
||||
})?;
|
||||
self.sessions.lock().await.insert(channel, session);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn connect(&self, channel: ChannelId) -> voelin_query::Result<Session> {
|
||||
let started = Instant::now();
|
||||
let mut connect = self.config.connect.clone();
|
||||
connect.line.label = format!("relay {channel}");
|
||||
let (client, notifications) = QueryClient::connect(&connect).await?;
|
||||
let Some(notifications) = notifications else {
|
||||
return Err(voelin_query::Error::Unsupported("relays need a transport with events"));
|
||||
};
|
||||
let own_id = client.own_client_id().await?;
|
||||
set_nickname(&client, &format!("{} {channel}", self.config.nickname)).await;
|
||||
let nickname = set_nickname(&client, &format!("{} {channel}", self.config.nickname)).await;
|
||||
match client.send(&Command::new("clientmove").arg("clid", own_id).arg("cid", channel)).await
|
||||
{
|
||||
// Query clients start in the default channel.
|
||||
@@ -102,72 +154,160 @@ impl RelayPool {
|
||||
}
|
||||
}
|
||||
client.send(&Command::new("servernotifyregister").arg("event", "textchannel")).await?;
|
||||
info!(channel, own_id, "relay opened");
|
||||
let elapsed_ms = started.elapsed().as_millis() as u64;
|
||||
info!(channel, own_id, elapsed_ms, "relay opened");
|
||||
let task = tokio::spawn(forward(channel, own_id, notifications, self.events.clone()));
|
||||
sessions.insert(channel, Session { client, task });
|
||||
Ok(())
|
||||
Ok(Session { client, opened: Instant::now(), nickname, posting: Default::default(), task })
|
||||
}
|
||||
|
||||
/// Stop relaying a channel.
|
||||
pub async fn close(&self, channel: ChannelId) {
|
||||
let session = self.sessions.lock().await.remove(&channel);
|
||||
if let Some(session) = session {
|
||||
session.client.quit().await;
|
||||
info!(channel, "relay closed");
|
||||
}
|
||||
self.close_one(channel).await;
|
||||
}
|
||||
|
||||
/// Stop all relays.
|
||||
pub async fn close_all(&self) {
|
||||
let sessions: Vec<_> = self.sessions.lock().await.drain().collect();
|
||||
for (channel, session) in sessions {
|
||||
session.client.quit().await;
|
||||
info!(channel, "relay closed");
|
||||
}
|
||||
/// Stop relaying a channel; whether it was relayed.
|
||||
async fn close_one(&self, channel: ChannelId) -> bool {
|
||||
// After an open in progress, which would otherwise come back with it.
|
||||
let gate = self.gate(channel);
|
||||
let _closing = gate.lock().await;
|
||||
let Some(session) = self.sessions.lock().await.remove(&channel) else { return false };
|
||||
// Not a lost connection: no `Closed` event for it.
|
||||
session.task.abort();
|
||||
session.client.quit().await;
|
||||
info!(channel, open_for_s = session.opened.elapsed().as_secs(), "relay closed");
|
||||
true
|
||||
}
|
||||
|
||||
/// Post `text` in `channel` on behalf of `nick`, opening a relay if needed.
|
||||
/// Stop all relays, after any opens in progress, and open no more.
|
||||
/// Returns the channels that were relayed.
|
||||
pub async fn close_all(&self) -> Vec<ChannelId> {
|
||||
self.closed.store(true, Ordering::Relaxed);
|
||||
// Every channel that has a relay or is opening one has a gate.
|
||||
let channels: Vec<ChannelId> = {
|
||||
let gates = self.gates.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
gates.keys().copied().collect()
|
||||
};
|
||||
let mut closed = Vec::new();
|
||||
for channel in channels {
|
||||
if self.close_one(channel).await {
|
||||
closed.push(channel);
|
||||
}
|
||||
}
|
||||
closed
|
||||
}
|
||||
|
||||
/// Post `text` in `channel` as `nick` wrote it ([`post_as`]), opening a
|
||||
/// relay if needed.
|
||||
pub async fn send(
|
||||
&self,
|
||||
channel: ChannelId,
|
||||
nick: &str,
|
||||
text: &str,
|
||||
) -> voelin_query::Result<()> {
|
||||
self.post(channel, nick, text, &self.config.format).await
|
||||
}
|
||||
|
||||
/// [`RelayPool::send`] with another fallback `format` than the pool's.
|
||||
pub async fn post(
|
||||
&self,
|
||||
channel: ChannelId,
|
||||
nick: &str,
|
||||
text: &str,
|
||||
format: &str,
|
||||
) -> voelin_query::Result<()> {
|
||||
self.open(channel).await?;
|
||||
let client = match self.sessions.lock().await.get(&channel) {
|
||||
Some(s) => s.client.clone(),
|
||||
let (client, nickname, posting) = match self.sessions.lock().await.get(&channel) {
|
||||
Some(s) => (s.client.clone(), s.nickname.clone(), s.posting.clone()),
|
||||
None => return Err(voelin_query::Error::Closed),
|
||||
};
|
||||
let full = relay_text(&self.config.format, nick, text);
|
||||
for part in split_message(&full, MAX_MESSAGE_BYTES) {
|
||||
client
|
||||
.send(
|
||||
&Command::new("sendtextmessage")
|
||||
.arg("targetmode", 2)
|
||||
.arg("target", channel)
|
||||
.arg("msg", part),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
let _posting = posting.lock().await;
|
||||
post_as(&client, &nickname, nick, text, format, |part| {
|
||||
Command::new("sendtextmessage")
|
||||
.arg("targetmode", 2)
|
||||
.arg("target", channel)
|
||||
.arg("msg", part)
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
/// Post `text` through the query session `client` as if `nick` wrote it: the
|
||||
/// session takes the nickname for the post (or `nick1`, `nick2`, … while
|
||||
/// someone has it, as TeamSpeak names a second client of the same name) and
|
||||
/// goes back to `own_nickname` afterwards, so it never keeps someone's name.
|
||||
/// When it cannot take any (too short, refused), the post goes out under the
|
||||
/// session's own name as `format` (`{nick}`, `{text}`). `command` makes the
|
||||
/// `sendtextmessage` for one part of the text.
|
||||
///
|
||||
/// Callers serialize posts through one session: each borrows a nickname.
|
||||
pub async fn post_as(
|
||||
client: &QueryClient,
|
||||
own_nickname: &str,
|
||||
nick: &str,
|
||||
text: &str,
|
||||
format: &str,
|
||||
command: impl Fn(String) -> Command,
|
||||
) -> voelin_query::Result<()> {
|
||||
let taken = take_nickname(client, nick).await;
|
||||
let full = if taken { text.to_owned() } else { relay_text(format, nick, text) };
|
||||
let mut result = Ok(());
|
||||
for part in split_message(&full, MAX_MESSAGE_BYTES) {
|
||||
result = client.send(&command(part)).await.map(drop);
|
||||
if result.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if taken && !own_nickname.is_empty() {
|
||||
set_nickname(client, own_nickname).await;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Name the session `nick` or a numbered variant; whether it did.
|
||||
async fn take_nickname(client: &QueryClient, nick: &str) -> bool {
|
||||
for nickname in author_nicknames(nick) {
|
||||
match client.send(&Command::new("clientupdate").arg("client_nickname", &nickname)).await {
|
||||
Ok(_) => return true,
|
||||
Err(voelin_query::Error::Query(e)) if e.id == ERR_NICKNAME_IN_USE => continue,
|
||||
Err(e) => {
|
||||
debug!(%e, "could not take the author's nickname");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The names a post by `nick` may go out under, in order: the nickname
|
||||
/// itself, then `nick1` to `nick3`, each within TeamSpeak's length limits.
|
||||
fn author_nicknames(nick: &str) -> Vec<String> {
|
||||
let nick = nick.trim();
|
||||
if nick.chars().count() < MIN_NICKNAME_CHARS {
|
||||
return Vec::new();
|
||||
}
|
||||
let fit = |suffix: &str| {
|
||||
let head: String = nick.chars().take(MAX_NICKNAME_CHARS - suffix.len()).collect();
|
||||
format!("{}{suffix}", head.trim_end())
|
||||
};
|
||||
std::iter::once(fit("")).chain((1..=3).map(|n| fit(&n.to_string()))).collect()
|
||||
}
|
||||
|
||||
/// Nicknames are unique per server; try a few numbered variants. The name is
|
||||
/// cosmetic, so failing keeps the server-assigned one.
|
||||
async fn set_nickname(client: &QueryClient, base: &str) {
|
||||
/// cosmetic, so failing keeps the server-assigned one. The name it got.
|
||||
async fn set_nickname(client: &QueryClient, base: &str) -> String {
|
||||
for attempt in 1..=5 {
|
||||
let nickname = if attempt == 1 { base.to_string() } else { format!("{base} ({attempt})") };
|
||||
match client.send(&Command::new("clientupdate").arg("client_nickname", &nickname)).await {
|
||||
Ok(_) => return,
|
||||
Ok(_) => return nickname,
|
||||
Err(voelin_query::Error::Query(e)) if e.id == ERR_NICKNAME_IN_USE => continue,
|
||||
Err(e) => {
|
||||
warn!(%e, %nickname, "could not set relay nickname");
|
||||
return;
|
||||
return base.to_owned();
|
||||
}
|
||||
}
|
||||
}
|
||||
warn!(base, "all relay nicknames in use");
|
||||
base.to_owned()
|
||||
}
|
||||
|
||||
async fn forward(
|
||||
@@ -176,6 +316,7 @@ async fn forward(
|
||||
mut notifications: mpsc::UnboundedReceiver<Notification>,
|
||||
events: broadcast::Sender<RelayEvent>,
|
||||
) {
|
||||
let opened = Instant::now();
|
||||
while let Some(n) = notifications.recv().await {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
@@ -191,5 +332,45 @@ async fn forward(
|
||||
debug!(channel, author = %msg.author_name, "relayed message");
|
||||
let _ = events.send(RelayEvent::Message(msg));
|
||||
}
|
||||
// Closing a relay stops this task before it quits, so this is a loss.
|
||||
warn!(channel, open_for_s = opened.elapsed().as_secs(), "relay connection lost");
|
||||
let _ = events.send(RelayEvent::Closed { channel, reason: "connection closed".into() });
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_closed_pool_opens_no_relays() {
|
||||
let connect = Connect {
|
||||
transport: voelin_query::Transport::Raw,
|
||||
addr: "127.0.0.1:9".into(),
|
||||
user: "serveradmin".into(),
|
||||
secret: None,
|
||||
server_port: None,
|
||||
server_id: None,
|
||||
line: Default::default(),
|
||||
};
|
||||
let pool = RelayPool::new(RelayConfig::new(connect));
|
||||
assert!(!pool.is_closed());
|
||||
assert!(pool.close_all().await.is_empty());
|
||||
assert!(pool.is_closed());
|
||||
// Without trying to connect.
|
||||
assert!(matches!(pool.open(1).await, Err(voelin_query::Error::Closed)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn posts_go_out_under_the_authors_name_then_numbered_variants() {
|
||||
assert_eq!(author_nicknames(" Alice "), ["Alice", "Alice1", "Alice2", "Alice3"]);
|
||||
// Too short for TeamSpeak: the relay's own name and the format.
|
||||
assert!(author_nicknames("Al").is_empty());
|
||||
let long = "x".repeat(40);
|
||||
let names = author_nicknames(&long);
|
||||
assert_eq!(names[0], "x".repeat(30));
|
||||
assert_eq!(names[1], format!("{}1", "x".repeat(29)));
|
||||
assert!(names.iter().all(|n| n.chars().count() <= MAX_NICKNAME_CHARS));
|
||||
// Characters, not bytes.
|
||||
assert_eq!(author_nicknames(&"é".repeat(31))[0].chars().count(), 30);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 260 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user