Compare commits
106
Commits
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,3 +1,4 @@
|
||||
/target/
|
||||
/dev/.state/
|
||||
/dist/
|
||||
/.cargo/
|
||||
+28
-20
@@ -8,10 +8,6 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
|
||||
### Added
|
||||
|
||||
- myTeamSpeak profile: Settings → My Account shows the account's avatar,
|
||||
description, registration date, previous sign-in, badges and signed-in
|
||||
devices from the account service; the avatar is also the sidebar's
|
||||
profile picture where a server has none for us.
|
||||
- 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.
|
||||
@@ -28,8 +24,7 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
- 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, the ones you chose in Settings → My Account
|
||||
included.
|
||||
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/…`)
|
||||
@@ -47,16 +42,6 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
- 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.
|
||||
- Voice connections show servers the account's avatar, the badges chosen
|
||||
in Settings → My Account (up to three) and its User Tag, as the official
|
||||
client does, so other TeamSpeak 6 users see them; again after a
|
||||
reconnect or an account change, and cleared on sign-out. A saved session
|
||||
is enough: the avatar, its certificate, the signed badges and the User
|
||||
Tag's token come from myTeamSpeak's services, and Voelin checks each
|
||||
signature as the server does before sending it. The log says what the
|
||||
server published.
|
||||
- Settings → My Account shows the account's User Tag and lets you choose the
|
||||
badges servers show.
|
||||
- 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.
|
||||
@@ -84,8 +69,21 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
|
||||
### Changed
|
||||
|
||||
- New login page; it no longer opens when a session is saved (only when one
|
||||
has expired), and "Continue without an account" is remembered.
|
||||
- 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.
|
||||
@@ -186,10 +184,20 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
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
|
||||
|
||||
- The account's avatar is downloaded from its own link; it was asked for
|
||||
as an upload link and refused with HTTP 403.
|
||||
- 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.
|
||||
|
||||
@@ -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
+85
-244
@@ -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"
|
||||
@@ -4879,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"
|
||||
@@ -5863,7 +5857,6 @@ checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629"
|
||||
dependencies = [
|
||||
"digest 0.11.3",
|
||||
"hmac 0.13.0",
|
||||
"sha2 0.11.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6342,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"
|
||||
@@ -6376,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"
|
||||
@@ -6460,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"
|
||||
@@ -7259,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",
|
||||
@@ -7382,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"
|
||||
@@ -8856,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"
|
||||
@@ -8934,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",
|
||||
@@ -9660,7 +9462,6 @@ dependencies = [
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"tsclientlib",
|
||||
"voelin-core",
|
||||
"voelin-media",
|
||||
"voelin-model",
|
||||
@@ -9685,8 +9486,6 @@ dependencies = [
|
||||
"sonora-simd",
|
||||
"thiserror 2.0.21",
|
||||
"tracing",
|
||||
"tsclientlib",
|
||||
"tsproto-packets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9719,11 +9518,12 @@ dependencies = [
|
||||
"tsproto-types",
|
||||
"voelin-audio",
|
||||
"voelin-gateway-proto",
|
||||
"voelin-identity",
|
||||
"voelin-media",
|
||||
"voelin-model",
|
||||
"voelin-myts",
|
||||
"voelin-observer",
|
||||
"voelin-platform",
|
||||
"voelin-proto",
|
||||
"voelin-query",
|
||||
"voelin-store",
|
||||
"voelin-stream",
|
||||
@@ -9775,6 +9575,23 @@ dependencies = [
|
||||
"voelin-model",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "voelin-identity"
|
||||
version = "0.2.0"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c8e0e5a17c1ff5dfaefa087f49b395d2918af650#c8e0e5a17c1ff5dfaefa087f49b395d2918af650"
|
||||
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"
|
||||
@@ -9820,29 +9637,11 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "voelin-model"
|
||||
version = "0.1.0"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c8e0e5a17c1ff5dfaefa087f49b395d2918af650#c8e0e5a17c1ff5dfaefa087f49b395d2918af650"
|
||||
dependencies = [
|
||||
"prost",
|
||||
"serde",
|
||||
"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",
|
||||
"curve25519-dalek 4.1.3",
|
||||
"pbkdf2",
|
||||
"reqwest",
|
||||
"schema-api",
|
||||
"sha2 0.10.9",
|
||||
"subtle",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tsproto",
|
||||
"zeroize",
|
||||
"voelin-proto",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9874,6 +9673,17 @@ dependencies = [
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "voelin-proto"
|
||||
version = "0.2.0"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c8e0e5a17c1ff5dfaefa087f49b395d2918af650#c8e0e5a17c1ff5dfaefa087f49b395d2918af650"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"prost",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "voelin-query"
|
||||
version = "0.1.0"
|
||||
@@ -9897,7 +9707,9 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tracing",
|
||||
"tsclientlib",
|
||||
"voelin-identity",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9917,6 +9729,7 @@ dependencies = [
|
||||
"tracing-subscriber",
|
||||
"tsclientlib",
|
||||
"tsproto-packets",
|
||||
"voelin-media",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9927,7 +9740,6 @@ dependencies = [
|
||||
"chrono",
|
||||
"dirs",
|
||||
"image",
|
||||
"miniz_oxide 0.8.9",
|
||||
"png",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -9942,10 +9754,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]]
|
||||
@@ -11085,6 +10915,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"
|
||||
@@ -11201,9 +11042,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",
|
||||
|
||||
+16
-5
@@ -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",
|
||||
@@ -16,14 +16,13 @@ members = [
|
||||
"crates/voelin-gateway",
|
||||
"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 = [
|
||||
@@ -37,14 +36,13 @@ default-members = [
|
||||
"crates/voelin-core",
|
||||
"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 +53,19 @@ 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:
|
||||
# the three crates below are at one revision (main c8e0e5a: the account-bound
|
||||
# KeyStore of Phase 2 task 28, the account types of the session seam).
|
||||
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" }
|
||||
# The backend-neutral session seam (`voelin_proto::link`) and the v1 messages.
|
||||
voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" }
|
||||
# The UI-facing domain model and the client's replica of v1 entities.
|
||||
voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" }
|
||||
|
||||
[workspace.lints.rust]
|
||||
# deny, not forbid: generated code (Slint) needs a local allow.
|
||||
unsafe_code = "deny"
|
||||
|
||||
@@ -28,7 +28,7 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
|
||||
- `crates/proto/`: vendored tsclientlib, modernised (TS6 fields and stream
|
||||
messages, faster off-thread Init1 puzzle, `curve25519-dalek` 4, fuzzing fixes;
|
||||
see [UPSTREAM.md](crates/proto/UPSTREAM.md))
|
||||
- `crates/voelin-model`: server flavor detection (TS3 / TS6) and capabilities
|
||||
- `voelin-model` (from VoelinProtocol, a git dependency): domain model, server flavor detection (TS3 / TS6) and capabilities
|
||||
- `crates/voelin-audio`: Opus voice encoding, framing, resampling, WAV, jitter buffer/mixer, cpal devices
|
||||
- `crates/voelin-store`: SQLite store for identities, bookmarks, settings and chat history; keyring secrets
|
||||
- `crates/voelin-query`: ServerQuery client over raw TCP, SSH and HTTP WebQuery (events, rate limiting, keepalive)
|
||||
@@ -45,6 +45,9 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
|
||||
(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
|
||||
|
||||
+9
-69
@@ -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
|
||||
@@ -182,8 +175,8 @@ the crate's authors are listed as its copyright holders.
|
||||
|
||||
| License | Crates |
|
||||
|---|---|
|
||||
| MIT License | 661 |
|
||||
| Apache License 2.0 | 32 |
|
||||
| MIT License | 660 |
|
||||
| Apache License 2.0 | 31 |
|
||||
| Unicode License v3 | 26 |
|
||||
| BSD 3-Clause "New" or "Revised" License | 22 |
|
||||
| LicenseRef-Slint-Royalty-free-2.0 | 12 |
|
||||
@@ -1026,7 +1019,7 @@ Used by: cpal 0.18.2, imgref 1.12.3, self_cell 1.3.0, unicode-linebreak 0.1.5
|
||||
|
||||
````
|
||||
|
||||
Used by: gethostname 1.1.0, prost-derive 0.14.4, prost-types 0.14.4, prost 0.14.4
|
||||
Used by: gethostname 1.1.0, prost-derive 0.14.4, prost 0.14.4
|
||||
|
||||
````text
|
||||
Apache License
|
||||
@@ -4157,7 +4150,7 @@ DEALINGS IN THE SOFTWARE.
|
||||
|
||||
````
|
||||
|
||||
Used by: hyper-rustls 0.27.10, rustls-native-certs 0.8.4, rustls 0.23.45
|
||||
Used by: hyper-rustls 0.27.10, rustls-native-certs 0.8.4, rustls 0.23.46
|
||||
|
||||
````text
|
||||
Copyright (c) 2016 Joseph Birr-Pixton <jpixton@gmail.com>
|
||||
@@ -7001,7 +6994,7 @@ DEALINGS IN THE SOFTWARE.
|
||||
|
||||
````
|
||||
|
||||
Used by: cpufeatures 0.2.17
|
||||
Used by: cpufeatures 0.2.17, der_derive 0.8.0
|
||||
|
||||
````text
|
||||
Copyright (c) 2020-2025 The RustCrypto Project Developers
|
||||
@@ -7253,7 +7246,7 @@ DEALINGS IN THE SOFTWARE.
|
||||
|
||||
````
|
||||
|
||||
Used by: pem-rfc7468 1.0.0, pkcs1 0.8.0-rc.4
|
||||
Used by: pem-rfc7468 1.0.0, pkcs1 0.8.0-rc.4, x509-cert 0.3.0
|
||||
|
||||
````text
|
||||
Copyright (c) 2021-2025 The RustCrypto Project Developers
|
||||
@@ -7906,31 +7899,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
````
|
||||
|
||||
Used by: tonic 0.14.6
|
||||
|
||||
````text
|
||||
Copyright (c) 2025 Lucio Franco
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
````
|
||||
|
||||
Used by: secret-service 5.2.0
|
||||
|
||||
````text
|
||||
@@ -9846,7 +9814,6 @@ Standard text, used by:
|
||||
- str0m-proto 0.7.0: Martin Algesten <martin@algesten.se> (https://github.com/algesten/str0m)
|
||||
- taffy 0.10.1: Alice Cecile <alice.i.cecile@gmail.com>, Johnathan Kelley <jkelleyrtp@gmail.com>, Nico Burns <nico@nicoburns.com> (https://github.com/DioxusLabs/taffy)
|
||||
- tauri-winrt-notification 0.7.3: allenbenz, Tauri Programme within The Commons Conservancy (https://github.com/tauri-apps/winrt-notification)
|
||||
- tonic-prost 0.14.6: Lucio Franco <luciofranco14@gmail.com> (https://github.com/hyperium/tonic)
|
||||
- tract-extra 0.23.8: Mathieu Poumeyrol <kali@zoy.org> (https://github.com/sonos/tract)
|
||||
- tract-transformers 0.23.8: Mathieu Poumeyrol <kali@zoy.org>, Louis Chouraki <louis.chouraki@sonos.com> (https://github.com/sonos/tract)
|
||||
- windows-collections 0.2.0 (https://github.com/microsoft/windows-rs)
|
||||
@@ -10812,34 +10779,6 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
````
|
||||
|
||||
Used by: hyper-timeout 0.5.2
|
||||
|
||||
````text
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016 The weldr Project Developers
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
|
||||
````
|
||||
|
||||
Used by: same-file 1.0.6, winapi-util 0.1.11
|
||||
@@ -11857,7 +11796,7 @@ authorization of the copyright holder.
|
||||
|
||||
````
|
||||
|
||||
Used by: fixed_decimal 0.7.2, icu_collections 2.3.0, icu_decimal 2.3.0, icu_decimal_data 2.3.0, icu_locale_core 2.3.0, icu_locale_fallback 2.3.0, icu_locale_fallback_data 2.3.0, icu_normalizer 2.3.0, icu_normalizer_data 2.3.0, icu_properties 2.3.0, icu_properties_data 2.3.0, icu_provider 2.3.1, icu_segmenter 2.3.0, icu_segmenter_data 2.3.0, litemap 0.8.3, potential_utf 0.1.6, tinystr 0.8.4, writeable 0.6.4, yoke-derive 0.8.3, yoke 0.8.3, zerofrom-derive 0.1.8, zerofrom 0.1.8, zerotrie 0.2.5, zerovec-derive 0.11.6, zerovec 0.11.8
|
||||
Used by: fixed_decimal 0.7.2, icu_collections 2.3.0, icu_decimal 2.3.0, icu_decimal_data 2.3.0, icu_locale_core 2.3.0, icu_locale_fallback 2.3.0, icu_locale_fallback_data 2.3.0, icu_normalizer 2.3.0, icu_normalizer_data 2.3.0, icu_properties 2.3.0, icu_properties_data 2.3.0, icu_provider 2.3.1, icu_segmenter 2.3.0, icu_segmenter_data 2.3.0, litemap 0.8.3, potential_utf 0.1.6, tinystr 0.8.4, writeable 0.6.4, yoke-derive 0.8.4, yoke 0.8.3, zerofrom-derive 0.1.8, zerofrom 0.1.8, zerotrie 0.2.5, zerovec-derive 0.11.6, zerovec 0.11.8
|
||||
|
||||
````text
|
||||
UNICODE LICENSE V3
|
||||
@@ -12052,7 +11991,8 @@ bzip2/libbzip2 version 1.1.0 of 6 September 2010
|
||||
|
||||
<!-- 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).
|
||||
|
||||
+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
|
||||
|
||||
@@ -19,7 +19,7 @@ tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "sync", "
|
||||
tracing = "0.1.44"
|
||||
voelin-core = { path = "../voelin-core" }
|
||||
# Channels and people for the voice notification.
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
voelin-model = { workspace = true }
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
anyhow = "1.0.104"
|
||||
@@ -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
|
||||
@@ -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::*;
|
||||
|
||||
@@ -244,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));
|
||||
@@ -316,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,9 +1,9 @@
|
||||
//! Incoming voice: per-client jitter buffer, decoder and mixer, with a
|
||||
//! volume and mute per client, and everyone else dimmed while a priority
|
||||
//! 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);
|
||||
@@ -21,13 +21,11 @@
|
||||
|
||||
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;
|
||||
@@ -35,14 +33,14 @@ const MAX_DIMM_DB: f32 = -60.0;
|
||||
/// 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.
|
||||
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<ClientId>,
|
||||
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).
|
||||
@@ -70,21 +68,17 @@ 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, and dimmed while a
|
||||
/// priority speaker talks. Returns the clients that stopped talking.
|
||||
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<ClientId> {
|
||||
/// 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.
|
||||
@@ -141,9 +135,9 @@ impl Mixer {
|
||||
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);
|
||||
@@ -153,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 {
|
||||
@@ -169,30 +163,30 @@ impl Mixer {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_muted(&self, id: ClientId) -> bool {
|
||||
pub fn is_muted(&self, id: TalkerId) -> bool {
|
||||
self.muted.contains(&id)
|
||||
}
|
||||
|
||||
/// 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 clients change.
|
||||
pub fn set_priority(&mut self, clients: impl IntoIterator<Item = ClientId>, dimm_db: f32) {
|
||||
self.priority = clients.into_iter().collect();
|
||||
/// 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 client (e.g. it left the server; client
|
||||
/// ids are reused).
|
||||
pub fn forget(&mut self, id: ClientId) {
|
||||
/// 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()
|
||||
}
|
||||
|
||||
@@ -202,7 +196,7 @@ impl Mixer {
|
||||
}
|
||||
|
||||
/// The underlying jitter buffer.
|
||||
pub fn handler(&self) -> &AudioHandler<ClientId> {
|
||||
pub fn handler(&self) -> &AudioHandler {
|
||||
&self.handler
|
||||
}
|
||||
}
|
||||
@@ -221,23 +215,26 @@ impl std::fmt::Debug for Mixer {
|
||||
|
||||
#[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);
|
||||
@@ -251,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));
|
||||
@@ -274,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));
|
||||
@@ -289,7 +286,7 @@ mod tests {
|
||||
/// in and out, but not itself, and not while we muted it.
|
||||
#[test]
|
||||
fn priority_speaker_dims_others() {
|
||||
let (a, p) = (ClientId(3), ClientId(5));
|
||||
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);
|
||||
@@ -308,14 +305,12 @@ mod tests {
|
||||
let mut out = Vec::new();
|
||||
for _ in 0..frames {
|
||||
let fa = frame(&tone_a, id_a);
|
||||
mixer
|
||||
.handle_packet(a, packet(3, id_a, enc_a.encode_to_bytes(&fa).unwrap()))
|
||||
.unwrap();
|
||||
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(p, packet(5, id_p, data)).unwrap();
|
||||
mixer.handle_packet(packet(5, id_p, data)).unwrap();
|
||||
id_p += 1;
|
||||
}
|
||||
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
|
||||
@@ -359,7 +354,7 @@ mod tests {
|
||||
/// frame: the other talker's level (per period of its tone) never jumps.
|
||||
#[test]
|
||||
fn priority_dimming_ramps_per_sample() {
|
||||
let (a, p) = (ClientId(3), ClientId(5));
|
||||
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);
|
||||
@@ -371,10 +366,10 @@ mod tests {
|
||||
// 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(a, packet(3, id, enc_a.encode_to_bytes(frame).unwrap())).unwrap();
|
||||
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(p, packet(5, j as u16, data)).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);
|
||||
@@ -400,17 +395,17 @@ mod tests {
|
||||
fn priority_dimm_bounds() {
|
||||
let mut mixer = Mixer::new();
|
||||
assert_eq!(mixer.dimm, 1.0);
|
||||
mixer.set_priority([ClientId(1)], -18.0);
|
||||
mixer.set_priority([TalkerId(1)], -18.0);
|
||||
assert!((mixer.dimm - 0.1259).abs() < 1e-3);
|
||||
mixer.set_priority([ClientId(1)], 6.0);
|
||||
mixer.set_priority([TalkerId(1)], 6.0);
|
||||
assert_eq!(mixer.dimm, 1.0);
|
||||
mixer.set_priority([ClientId(1)], f32::NEG_INFINITY);
|
||||
mixer.set_priority([TalkerId(1)], f32::NEG_INFINITY);
|
||||
assert!((mixer.dimm - 0.001).abs() < 1e-6);
|
||||
mixer.set_priority([ClientId(1)], f32::NAN);
|
||||
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(ClientId(1));
|
||||
assert!(mixer.priority.contains(&ClientId(1)));
|
||||
mixer.forget(TalkerId(1));
|
||||
assert!(mixer.priority.contains(&TalkerId(1)));
|
||||
mixer.set_priority([], -18.0);
|
||||
assert!(mixer.priority.is_empty());
|
||||
}
|
||||
@@ -418,7 +413,7 @@ mod tests {
|
||||
#[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,8 +14,9 @@ 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"]
|
||||
# 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).
|
||||
@@ -24,6 +25,8 @@ media-desktop = ["media", "voelin-media/default"]
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
base64 = "0.22"
|
||||
# The RTP packets of the session seam (`voelin_proto::link::MediaPacket`).
|
||||
bytes = "1"
|
||||
dirs = "6"
|
||||
futures = "0.3"
|
||||
# Finding a server's gateway in DNS (the voice resolver's version).
|
||||
@@ -49,11 +52,17 @@ 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-model = { path = "../voelin-model" }
|
||||
# `IdentityBlob`, the identity of the API (a TeamSpeak identity as the key store
|
||||
# keeps it, or a Voelin key).
|
||||
voelin-identity = { workspace = true }
|
||||
voelin-media = { path = "../voelin-media", default-features = false }
|
||||
voelin-model = { workspace = true }
|
||||
voelin-observer = { path = "../voelin-observer" }
|
||||
# Paths only (the cache directory).
|
||||
voelin-platform = { path = "../voelin-platform", default-features = false }
|
||||
# The backend-neutral session seam the engine consumes (`voelin_proto::link`)
|
||||
# and the v1 messages it speaks.
|
||||
voelin-proto = { workspace = true }
|
||||
voelin-query = { path = "../voelin-query" }
|
||||
voelin-store = { path = "../voelin-store" }
|
||||
voelin-stream = { path = "../voelin-stream" }
|
||||
@@ -64,14 +73,15 @@ 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"
|
||||
# An HTTP/2 connection in a test (already in the tree through h2).
|
||||
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"] }
|
||||
# The fakes of the session seam (`FakeHost`, `FakeSession`, the conformance
|
||||
# suite).
|
||||
voelin-proto = { workspace = true, features = ["test-util"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -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,19 +35,19 @@ 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<ClientId>,
|
||||
clients: Vec<TalkerId>,
|
||||
dimm_db: f32,
|
||||
},
|
||||
/// An Opus frame (48 kHz) of a watched stream; `time` is its RTP time
|
||||
@@ -111,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 {
|
||||
@@ -126,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)>,
|
||||
}
|
||||
@@ -190,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");
|
||||
}
|
||||
}
|
||||
@@ -241,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;
|
||||
};
|
||||
@@ -263,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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,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);
|
||||
@@ -308,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);
|
||||
@@ -369,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,
|
||||
) {
|
||||
@@ -445,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};
|
||||
|
||||
@@ -509,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() {
|
||||
@@ -575,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]
|
||||
@@ -667,14 +664,14 @@ 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
|
||||
@@ -682,7 +679,7 @@ mod tests {
|
||||
#[test]
|
||||
fn priority_speaker() {
|
||||
let mut p = pipeline(TransmitMode::PushToTalk);
|
||||
p.handle(AudioIn::PrioritySpeakers { clients: vec![ClientId(2)], dimm_db: -12.0 });
|
||||
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();
|
||||
|
||||
@@ -4,21 +4,21 @@
|
||||
//! id (the CRC32 of the image, as TeamSpeak assigns them), so a lookup is a
|
||||
//! map access, and the same image seen on several servers or under
|
||||
//! several clients is one file. Pictures from the web (banners,
|
||||
//! [`crate::web`]) are named by the MD5 hash of their address. Keys are
|
||||
//! `web`) are named by the MD5 hash of their address. Keys are
|
||||
//! relative paths (`avatars/<md5>`, `icons/<id>`, `pictures/<md5>`).
|
||||
//!
|
||||
//! The cache is bounded by `cache.max_mb` (read on every insert; 0: no
|
||||
//! limit): the least recently used files go first. Use times survive
|
||||
//! restarts as the files' modification times.
|
||||
//!
|
||||
//! Downloads are deduplicated: [`Cache::fetch`] tells the first asker to
|
||||
//! 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).
|
||||
//! 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`]).
|
||||
//! again, it is downloaded only if it changed (`Cache::validators`,
|
||||
//! `Arrived::Unchanged`).
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::fmt;
|
||||
@@ -184,6 +184,17 @@ pub(crate) const MAX_PICTURE_BYTES: u64 = 128 << 20;
|
||||
/// does not hold a download slot.
|
||||
pub(crate) const MIN_PICTURE_RATE: u64 = 8 << 10;
|
||||
|
||||
/// How long a picture of `size` bytes may take to arrive: a minute, plus
|
||||
/// its size at [`MIN_PICTURE_RATE`], so large banners arrive on slow
|
||||
/// links while a stalled transfer still ends.
|
||||
pub(crate) fn image_download_time(size: u64) -> std::time::Duration {
|
||||
std::time::Duration::from_secs(60 + size / MIN_PICTURE_RATE)
|
||||
}
|
||||
|
||||
/// How long the server may take to start an image transfer (a busy server
|
||||
/// answers the requests of a large channel tree in turn).
|
||||
pub(crate) const IMAGE_NEGOTIATION: std::time::Duration = std::time::Duration::from_secs(30);
|
||||
|
||||
/// The cache key of a picture on the web: only `http` and `https`
|
||||
/// addresses (blanks around one are not part of it).
|
||||
pub(crate) fn picture_key(url: &str) -> Option<String> {
|
||||
@@ -489,6 +500,15 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn large_pictures_get_time_to_arrive() {
|
||||
let secs = std::time::Duration::from_secs;
|
||||
assert_eq!(image_download_time(0), secs(60));
|
||||
assert_eq!(image_download_time(100 << 10), secs(72));
|
||||
// The largest picture, at the slowest rate allowed.
|
||||
assert_eq!(image_download_time(MAX_PICTURE_BYTES), secs(60 + 16384));
|
||||
}
|
||||
|
||||
fn temp_dir(tag: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"voelin-cache-{tag}-{}-{:?}",
|
||||
|
||||
@@ -453,10 +453,15 @@ mod tests {
|
||||
lookups
|
||||
}
|
||||
|
||||
/// `lookups` asking the real `/.well-known/tsgw` at `port`.
|
||||
/// `lookups` asking the real `/.well-known/tsgw` at `port`. A name is
|
||||
/// connected to through the system's resolver, except `localhost`: the
|
||||
/// servers of the tests listen on 127.0.0.1, and some machines resolve
|
||||
/// `localhost` to `::1` only. (The test cares that the gateway is asked at
|
||||
/// the name `localhost`, not what the resolver makes of it.)
|
||||
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()
|
||||
let host = if name == "localhost" { "127.0.0.1".to_owned() } else { name };
|
||||
async move { timeout(PROBE_TIMEOUT, well_known(&host, port)).await.ok()?.ok() }.boxed()
|
||||
});
|
||||
lookups
|
||||
}
|
||||
|
||||
@@ -32,13 +32,13 @@
|
||||
//! never downloaded). [`crate::Command::SetAvatar`] uploads our own.
|
||||
|
||||
use std::fmt;
|
||||
use std::future::Future;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde::Serialize;
|
||||
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeekExt, AsyncWrite, AsyncWriteExt};
|
||||
|
||||
/// Picked by the caller; the answer carries it back.
|
||||
pub type RequestId = u64;
|
||||
@@ -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,
|
||||
@@ -168,9 +168,10 @@ impl Progress<'_> {
|
||||
const CHUNK: usize = 64 * 1024;
|
||||
|
||||
/// Receive a file: `size` bytes in total, `offset` of them already in the
|
||||
/// sink. Reports `Started`, `Progress` and the final state.
|
||||
pub(crate) async fn download(
|
||||
mut stream: TcpStream,
|
||||
/// sink; `stream` carries the rest. Reports `Started`, `Progress` and the
|
||||
/// final state.
|
||||
pub(crate) async fn download<R: AsyncRead + Unpin>(
|
||||
mut stream: R,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
sink: Sink,
|
||||
@@ -185,8 +186,8 @@ pub(crate) async fn download(
|
||||
});
|
||||
}
|
||||
|
||||
async fn receive(
|
||||
stream: &mut TcpStream,
|
||||
async fn receive<R: AsyncRead + Unpin>(
|
||||
stream: &mut R,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
sink: &Sink,
|
||||
@@ -253,26 +254,34 @@ async fn receive(
|
||||
}
|
||||
}
|
||||
|
||||
/// Send `file` from `offset` (`size` bytes in total). Reports `Started`,
|
||||
/// `Progress` and the final state.
|
||||
pub(crate) async fn upload(
|
||||
mut stream: TcpStream,
|
||||
/// Send `file` from `offset` (`size` bytes in total) into `writer`, then end
|
||||
/// it and wait for `stored`, which resolves once the server has the file.
|
||||
/// Reports `Started`, `Progress` and the final state.
|
||||
pub(crate) async fn upload_to<W, F>(
|
||||
mut writer: W,
|
||||
stored: F,
|
||||
file: PathBuf,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
progress_every: Duration,
|
||||
report: Report,
|
||||
) {
|
||||
) where
|
||||
W: AsyncWrite + Unpin,
|
||||
F: Future<Output = Result<(), String>>,
|
||||
{
|
||||
report(TransferState::Started { size, offset });
|
||||
let result = send(&mut stream, &file, size, offset, progress_every, &report).await;
|
||||
let result = match send(&mut writer, &file, size, offset, progress_every, &report).await {
|
||||
Ok(()) => stored.await,
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
report(match result {
|
||||
Ok(()) => TransferState::Done { size, path: Some(file), data: None },
|
||||
Err(e) => TransferState::Failed(e),
|
||||
});
|
||||
}
|
||||
|
||||
async fn send(
|
||||
stream: &mut TcpStream,
|
||||
async fn send<W: AsyncWrite + Unpin>(
|
||||
stream: &mut W,
|
||||
path: &Path,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
@@ -300,8 +309,6 @@ async fn send(
|
||||
}
|
||||
stream.flush().await.map_err(|e| e.to_string())?;
|
||||
stream.shutdown().await.map_err(|e| e.to_string())?;
|
||||
// The server closes the connection once it has everything.
|
||||
let _ = tokio::time::timeout(Duration::from_secs(30), stream.read(&mut buf[..1])).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -421,7 +428,7 @@ fn percent_decode(text: &str) -> Option<String> {
|
||||
mod tests {
|
||||
use std::sync::Mutex;
|
||||
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -562,7 +569,8 @@ mod tests {
|
||||
});
|
||||
let (report, states) = recorder();
|
||||
let stream = TcpStream::connect(addr).await.unwrap();
|
||||
upload(stream, file.clone(), 10, 4, Duration::ZERO, report).await;
|
||||
let (_, write) = tokio::io::split(stream);
|
||||
upload_to(write, async { Ok(()) }, file.clone(), 10, 4, Duration::ZERO, report).await;
|
||||
assert_eq!(server.await.unwrap(), b"456789");
|
||||
assert!(matches!(states.lock().unwrap().last(), Some(TransferState::Done { .. })));
|
||||
assert_eq!(md5_file(&file).unwrap(), "781e5e245d69b566979b86e28d23f2c7");
|
||||
|
||||
@@ -61,6 +61,7 @@ use voelin_gateway_proto::{
|
||||
HistoryEntry, HistoryQuery, PermRule, PermRuleInfo, PinInfo, RsvpStatus, StreamEntry,
|
||||
StreamSpec, TopicInfo, UserRef,
|
||||
};
|
||||
use voelin_identity::IdentityBlob;
|
||||
use voelin_model::{ChannelId, ChatTarget, Presence};
|
||||
use voelin_store::WriteOutcome;
|
||||
|
||||
@@ -91,13 +92,23 @@ pub(crate) enum GatewayEvent {
|
||||
Disconnected(Option<String>),
|
||||
}
|
||||
|
||||
/// The TeamSpeak identity of a blob, or why a gateway cannot be logged in to
|
||||
/// with it.
|
||||
fn login_identity(blob: &IdentityBlob) -> Result<tsclientlib::Identity, String> {
|
||||
crate::ts::identity::from_blob(blob).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Connect to a gateway (`ws://…/v1` or `wss://…/v1`) and log in with a
|
||||
/// TeamSpeak identity.
|
||||
/// TeamSpeak identity (a blob of kind `teamspeak`, see
|
||||
/// [`crate::ts::identity::to_blob`]; one that is none is refused as
|
||||
/// [`ErrorCode::AuthFailed`], the way the gateway would).
|
||||
pub async fn connect(
|
||||
url: &str,
|
||||
identity: &tsclientlib::Identity,
|
||||
identity: &IdentityBlob,
|
||||
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
|
||||
connect_watched(url, identity, &Progress::default()).await
|
||||
let identity = login_identity(identity)
|
||||
.map_err(|message| ClientError::Gateway { code: ErrorCode::AuthFailed, message })?;
|
||||
connect_watched(url, &identity, &Progress::default()).await
|
||||
}
|
||||
|
||||
/// [`connect`], telling `progress` each step (for the log).
|
||||
@@ -114,10 +125,19 @@ async fn connect_watched(
|
||||
/// logs in.
|
||||
pub(crate) async fn run(
|
||||
mut urls: Vec<String>,
|
||||
identity: tsclientlib::Identity,
|
||||
identity: IdentityBlob,
|
||||
mut commands: mpsc::UnboundedReceiver<GatewayCmd>,
|
||||
events: mpsc::UnboundedSender<GatewayEvent>,
|
||||
) {
|
||||
// An identity that cannot be read will not be tomorrow: like a refused login.
|
||||
let identity = match login_identity(&identity) {
|
||||
Ok(identity) => identity,
|
||||
Err(reason) => {
|
||||
debug!(%reason, "gateway: the identity cannot be read");
|
||||
let _ = events.send(GatewayEvent::Disconnected(Some(reason)));
|
||||
return;
|
||||
}
|
||||
};
|
||||
// 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)
|
||||
@@ -274,20 +294,24 @@ pub(crate) struct Observed {
|
||||
}
|
||||
|
||||
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,
|
||||
pub(crate) fn new(urls: &[String], identity: &IdentityBlob) -> Self {
|
||||
let (key, counter) = Self::of(identity);
|
||||
Self { urls: urls.to_vec(), key, counter, nudged: None }
|
||||
}
|
||||
|
||||
/// The public key and the counter of an identity: an identity that cannot be
|
||||
/// read has neither (and so is the same as any other that cannot).
|
||||
fn of(identity: &IdentityBlob) -> (String, u64) {
|
||||
match login_identity(identity) {
|
||||
Ok(identity) => (identity.key().to_pub().to_ts(), identity.counter()),
|
||||
Err(_) => (String::new(), 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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()
|
||||
pub(crate) fn same(&self, urls: &[String], identity: &IdentityBlob) -> bool {
|
||||
let (key, counter) = Self::of(identity);
|
||||
self.urls == urls && self.counter == counter && self.key == key
|
||||
}
|
||||
|
||||
/// Whether to try again now ([`GatewayCmd::RetryNow`]): not twice
|
||||
@@ -1182,15 +1206,16 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn the_same_observation_is_nudged_at_most_every_5_s() {
|
||||
let blob = crate::ts::identity::to_blob;
|
||||
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()));
|
||||
let mut observed = Observed::new(&urls, &blob(&identity));
|
||||
assert!(observed.same(&urls, &blob(&identity)));
|
||||
assert!(!observed.same(&["wss://gw.example.test/v1".to_owned()], &blob(&identity)));
|
||||
assert!(!observed.same(&urls, &blob(&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));
|
||||
assert!(!observed.same(&urls, &blob(&raised)));
|
||||
let now = Instant::now();
|
||||
assert!(observed.nudge_at(now));
|
||||
assert!(!observed.nudge_at(now + Duration::from_secs(4)));
|
||||
|
||||
@@ -3,7 +3,10 @@
|
||||
//! 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): a
|
||||
//! `voelin_proto::link::Session` that the connector of the server's address
|
||||
//! makes ([`Backends`], and [`ts::TsConnector`] for TeamSpeak servers; see
|
||||
//! [`link`])
|
||||
//! - **gateway**: a `tsgw` gateway (invisible presence, relayed chat)
|
||||
//! - **query**: the user's own ServerQuery credentials (same, without a gateway)
|
||||
//!
|
||||
@@ -16,9 +19,9 @@
|
||||
//! [`Engine::subscribe_frames`] for the frames of watched streams. The audio
|
||||
//! of watched streams plays through the session's speakers by itself
|
||||
//! ([`Command::SetStreamVolume`]); capture, encoding and decoding of video
|
||||
//! are in [`media`] (feature `media`), and the Stream Studio (scenes of
|
||||
//! are in `media` (feature `media`), and the Stream Studio (scenes of
|
||||
//! sources composited into one stream, recording, a replay buffer, WHIP) in
|
||||
//! [`studio`].
|
||||
//! `studio`.
|
||||
//!
|
||||
//! Settings are a [`settings::Settings`] service: typed keys, runtime
|
||||
//! values stored in the client database ahead of command line, config file
|
||||
@@ -45,14 +48,13 @@
|
||||
//! volume) are engine-wide ([`contacts`]).
|
||||
|
||||
mod audio;
|
||||
mod book;
|
||||
pub mod cache;
|
||||
pub mod contacts;
|
||||
pub mod discover;
|
||||
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,22 +63,21 @@ mod route;
|
||||
mod session;
|
||||
pub mod settings;
|
||||
pub mod stream;
|
||||
mod stream_types;
|
||||
#[cfg(feature = "media")]
|
||||
pub mod studio;
|
||||
pub mod versions;
|
||||
mod voice;
|
||||
pub mod ts;
|
||||
mod web;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::{broadcast, mpsc, watch};
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
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,14 +89,14 @@ 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::{Backends, VoiceOptions};
|
||||
pub use offline::{OfflineMessage, OfflineMessageInfo};
|
||||
pub use query::{QueryLogin, QueryTransport};
|
||||
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 voelin_identity::IdentityBlob;
|
||||
/// 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).
|
||||
@@ -110,13 +111,6 @@ 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>,
|
||||
@@ -132,12 +126,15 @@ pub enum Command {
|
||||
ObserveGateway {
|
||||
session: SessionId,
|
||||
urls: Vec<String>,
|
||||
identity: Box<tsclientlib::Identity>,
|
||||
/// The TeamSpeak identity to log in with ([`ts::identity::to_blob`]).
|
||||
/// One that is none, or cannot be read, ends the observation with
|
||||
/// its reason.
|
||||
identity: Box<IdentityBlob>,
|
||||
},
|
||||
/// Invisible presence and relay chat with own ServerQuery credentials.
|
||||
ObserveQuery {
|
||||
session: SessionId,
|
||||
connect: Box<voelin_query::Connect>,
|
||||
connect: Box<QueryLogin>,
|
||||
},
|
||||
StopObserving {
|
||||
session: SessionId,
|
||||
@@ -248,11 +245,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 {
|
||||
@@ -270,7 +269,7 @@ pub enum Command {
|
||||
},
|
||||
/// The video of a watched stream arrives, but none of it decodes: watch
|
||||
/// it in another codec the streamer offered, if there is one (a new
|
||||
/// connection without this one). [`media::Viewer`] sends it.
|
||||
/// connection without this one). `media::Viewer` sends it.
|
||||
StreamUndecodable {
|
||||
session: SessionId,
|
||||
stream_id: String,
|
||||
@@ -507,6 +506,30 @@ pub enum JoinFailure {
|
||||
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 {
|
||||
@@ -514,10 +537,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).
|
||||
@@ -760,8 +785,18 @@ impl Engine {
|
||||
}
|
||||
|
||||
/// Start the engine on the current tokio runtime with `settings` and
|
||||
/// chat `history`.
|
||||
/// chat `history`, connecting voice with the engine's own connectors
|
||||
/// ([`Backends::default`]: TeamSpeak 3 and 6).
|
||||
pub fn start_with(settings: Settings, history: History) -> Self {
|
||||
Self::start_with_backends(settings, history, Backends::default())
|
||||
}
|
||||
|
||||
/// Start the engine on the current tokio runtime with `settings` and
|
||||
/// chat `history`, connecting voice with the connectors in `backends`:
|
||||
/// the one for the scheme of a session's address makes its
|
||||
/// `voelin_proto::link::Session`.
|
||||
pub fn start_with_backends(settings: Settings, history: History, backends: Backends) -> Self {
|
||||
let link = Arc::new(link::SessionLink::new(backends));
|
||||
let (commands, rx) = mpsc::unbounded_channel();
|
||||
let (events, _) = broadcast::channel(4096);
|
||||
// About a minute of one watched stream.
|
||||
@@ -773,7 +808,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 }
|
||||
}
|
||||
|
||||
@@ -857,19 +892,18 @@ async fn run(
|
||||
events: broadcast::Sender<Event>,
|
||||
frames: broadcast::Sender<StreamFrame>,
|
||||
engine: Shared,
|
||||
link: Arc<link::SessionLink>,
|
||||
) {
|
||||
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! {
|
||||
@@ -908,29 +942,6 @@ async fn run(
|
||||
},
|
||||
};
|
||||
let id = match command {
|
||||
Command::SetMytsIdentity(identity) => {
|
||||
// Still no account is no change: every notification restarts
|
||||
// handshakes and sends `updatemytsid` on every connection. Any
|
||||
// account is (each connection's proof is signed anew).
|
||||
myts_identity.send_if_modified(|current| {
|
||||
if current.is_none() && identity.is_none() {
|
||||
return false;
|
||||
}
|
||||
*current = identity;
|
||||
true
|
||||
});
|
||||
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() {
|
||||
@@ -1006,8 +1017,7 @@ async fn run(
|
||||
frames.clone(),
|
||||
settings.clone(),
|
||||
engine.clone(),
|
||||
myts_identity.subscribe(),
|
||||
myts_data.subscribe(),
|
||||
link.clone(),
|
||||
);
|
||||
if let Some(profiles) = &srtp_profiles {
|
||||
s.send(Command::SetSrtpProfiles(profiles.clone()));
|
||||
@@ -1086,9 +1096,7 @@ fn command_session(command: &Command) -> SessionId {
|
||||
| Command::DeleteOfflineMessage { session, .. }
|
||||
| Command::SetOfflineMessageRead { session, .. }
|
||||
| Command::CloseSession { session } => *session,
|
||||
Command::SetMytsIdentity(_)
|
||||
| Command::SetMytsData(_)
|
||||
| Command::SetAudioSettings(_)
|
||||
Command::SetAudioSettings(_)
|
||||
| Command::SetSrtpProfiles(_)
|
||||
| Command::TestMicrophone { .. }
|
||||
| Command::SetSetting { .. }
|
||||
@@ -1105,10 +1113,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,265 @@
|
||||
//! The registry of the engine's connectors, by address scheme.
|
||||
//!
|
||||
//! A session's voice source is a `voelin_proto::link::Session`
|
||||
//! (`docs/session-seam.md` section 4.1). Which backend makes it is the
|
||||
//! scheme of the address: [`Backends`] holds the plain connectors of
|
||||
//! `voelin_proto::link::Connectors` (the Voelin protocol's QUIC connector
|
||||
//! later, `FakeConnector` in tests) and the in-process connectors, which
|
||||
//! also hand the engine what a `Session` has no room for yet (the TeamSpeak 6
|
||||
//! stream task, [`StreamPort`]).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use voelin_proto::link::{
|
||||
AccountAgent, BoxFuture, ConnectParams, Connected, Connector, Connectors, HostIdentity,
|
||||
HostTrust, SessionError,
|
||||
};
|
||||
use voelin_stream::PeerConfig;
|
||||
|
||||
use super::LinkCtx;
|
||||
use crate::stream::{OwnStreamEvent, StreamCmd};
|
||||
use crate::ts::TsConnector;
|
||||
|
||||
/// The scheme of the TeamSpeak servers a bookmark names without one.
|
||||
pub(crate) const TEAMSPEAK_SCHEME: &str = "ts3server";
|
||||
|
||||
/// What comes back from the stream task of a connection that has one.
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum StreamEvent {
|
||||
/// Our own stream's life, for the gateway directory.
|
||||
OwnStream(OwnStreamEvent),
|
||||
/// An Opus frame of a watched stream, for the audio thread.
|
||||
Audio { stream: String, time: u64, data: Arc<[u8]> },
|
||||
/// A watched stream ended.
|
||||
AudioEnded(String),
|
||||
}
|
||||
|
||||
/// The in-process channel of TeamSpeak 6 streams past the `Session` trait
|
||||
/// (`docs/session-seam.md` section 6.4): TeamSpeak 6 streams are peer to peer
|
||||
/// and not v1 entities yet, so the commands go to the connection's stream
|
||||
/// task and its events come back here.
|
||||
pub(crate) struct StreamPort {
|
||||
send: Box<dyn Fn(StreamCmd) + Send + Sync>,
|
||||
/// What the stream task reports.
|
||||
pub(crate) events: mpsc::UnboundedReceiver<StreamEvent>,
|
||||
}
|
||||
|
||||
impl StreamPort {
|
||||
/// A port whose commands go to `send`.
|
||||
pub(crate) fn new(
|
||||
send: impl Fn(StreamCmd) + Send + Sync + 'static,
|
||||
events: mpsc::UnboundedReceiver<StreamEvent>,
|
||||
) -> Self {
|
||||
Self { send: Box::new(send), events }
|
||||
}
|
||||
|
||||
/// Give the stream task a command.
|
||||
pub(crate) fn send(&self, cmd: StreamCmd) {
|
||||
(self.send)(cmd);
|
||||
}
|
||||
}
|
||||
|
||||
/// What an in-process backend needs besides the connect parameters.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct LocalCtx {
|
||||
/// The session's side of the engine: its id, event bus, frames and
|
||||
/// settings.
|
||||
pub(crate) link: LinkCtx,
|
||||
/// Open the audio devices (the stream task plays what streams carry).
|
||||
pub(crate) audio: bool,
|
||||
/// Network settings for stream peer connections.
|
||||
pub(crate) stream_peer: PeerConfig,
|
||||
}
|
||||
|
||||
impl LocalCtx {
|
||||
pub(crate) fn new(link: LinkCtx, audio: bool, stream_peer: PeerConfig) -> Self {
|
||||
Self { link, audio, stream_peer }
|
||||
}
|
||||
|
||||
/// A context for a connection made outside an engine (a test or a tool
|
||||
/// that calls a connector itself): a session of its own that nobody
|
||||
/// listens to.
|
||||
pub(crate) fn standalone() -> Self {
|
||||
let (events, _) = tokio::sync::broadcast::channel(16);
|
||||
let (frames, _) = tokio::sync::broadcast::channel(16);
|
||||
let link = LinkCtx {
|
||||
session: 0,
|
||||
events,
|
||||
frames,
|
||||
settings: crate::settings::SharedSettings::new(crate::settings::Settings::in_memory()),
|
||||
};
|
||||
Self { link, audio: false, stream_peer: PeerConfig::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// A connection an in-process connector made.
|
||||
pub(crate) struct LocalConnected {
|
||||
pub(crate) connected: Connected,
|
||||
/// The stream task's port, for a backend that runs one.
|
||||
pub(crate) streams: Option<StreamPort>,
|
||||
}
|
||||
|
||||
/// A connector that runs in this process and can use the engine's context
|
||||
/// ([`LocalCtx`]); its sessions may come with a [`StreamPort`].
|
||||
pub(crate) trait LocalConnector: Connector {
|
||||
/// Whether this connector serves addresses of `scheme`. By default, the
|
||||
/// schemes it names.
|
||||
fn accepts(&self, scheme: &str) -> bool {
|
||||
self.schemes().contains(&scheme)
|
||||
}
|
||||
|
||||
/// Connect with the engine's context.
|
||||
fn connect_local(
|
||||
&self,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> BoxFuture<Result<LocalConnected, SessionError>>;
|
||||
}
|
||||
|
||||
/// The connectors of an engine, found by the scheme of an address.
|
||||
///
|
||||
/// A scheme served by an in-process connector goes to it, one served by a
|
||||
/// plain connector ([`Backends::register`]) to that. An address without a
|
||||
/// scheme is a TeamSpeak bookmark and is taken for a `ts3server` one.
|
||||
#[derive(Clone)]
|
||||
pub struct Backends {
|
||||
connectors: Connectors,
|
||||
locals: Vec<Arc<dyn LocalConnector>>,
|
||||
account: Option<Arc<dyn AccountAgent>>,
|
||||
/// The connections' trust in hosts that are neither valid nor pinned.
|
||||
trust: Option<Arc<dyn HostTrust>>,
|
||||
}
|
||||
|
||||
impl Default for Backends {
|
||||
/// The engine's connectors: TeamSpeak 3 and 6 (`ts3server://` and
|
||||
/// `teamspeak://`, and an address without a scheme).
|
||||
fn default() -> Self {
|
||||
let mut backends = Self::empty();
|
||||
backends.register_teamspeak(TsConnector::new());
|
||||
backends
|
||||
}
|
||||
}
|
||||
|
||||
impl Backends {
|
||||
/// No connector at all. ([`Backends::default`] has the TeamSpeak one.)
|
||||
pub fn empty() -> Self {
|
||||
Self { connectors: Connectors::default(), locals: Vec::new(), account: None, trust: None }
|
||||
}
|
||||
|
||||
/// Register a connector for the schemes it names.
|
||||
pub fn register(&mut self, connector: Arc<dyn Connector>) {
|
||||
self.connectors.register(connector);
|
||||
}
|
||||
|
||||
pub(crate) fn register_local(&mut self, connector: Arc<dyn LocalConnector>) {
|
||||
self.locals.push(connector);
|
||||
}
|
||||
|
||||
/// Register the TeamSpeak connector for the schemes it names
|
||||
/// (`ts3server`, `teamspeak`, and addresses without a scheme).
|
||||
/// [`Backends::default`] registers one of its own; register yours to keep a
|
||||
/// clone of it, whose [`TsConnector::set_myts_identity`] and
|
||||
/// [`TsConnector::set_myts_data`] set the main myTeamSpeak account for every
|
||||
/// connection it makes.
|
||||
pub fn register_teamspeak(&mut self, connector: TsConnector) {
|
||||
self.register_local(Arc::new(connector));
|
||||
}
|
||||
|
||||
/// The device's Voelin account, which every connect hands the connector as
|
||||
/// `ConnectParams::account`. No connector reads it yet: the TeamSpeak
|
||||
/// connector takes the myTeamSpeak account it presents from its own setters
|
||||
/// ([`TsConnector::set_myts_identity`], [`TsConnector::set_myts_data`]), and a
|
||||
/// Voelin host's connector (the QUIC one, for its certificate) does not exist
|
||||
/// yet. Follow-up H4 of `docs/session-seam.md` (11.2) moves the myTeamSpeak
|
||||
/// proof from those setters to this hook. None is the default.
|
||||
pub fn set_account(&mut self, agent: Option<Arc<dyn AccountAgent>>) {
|
||||
self.account = agent;
|
||||
}
|
||||
|
||||
/// The account agent, if one was set ([`Backends::set_account`]).
|
||||
pub fn account(&self) -> Option<Arc<dyn AccountAgent>> {
|
||||
self.account.clone()
|
||||
}
|
||||
|
||||
/// Decide about hosts that are neither valid nor pinned. The default
|
||||
/// refuses them: there is no trust dialog yet, and TeamSpeak has no host
|
||||
/// key.
|
||||
pub fn set_trust(&mut self, trust: Option<Arc<dyn HostTrust>>) {
|
||||
self.trust = trust;
|
||||
}
|
||||
|
||||
pub(crate) fn trust(&self) -> Arc<dyn HostTrust> {
|
||||
self.trust.clone().unwrap_or_else(|| Arc::new(RefuseUnknownHosts))
|
||||
}
|
||||
|
||||
/// The scheme of an address, lowercase; a TeamSpeak bookmark's when there
|
||||
/// is none.
|
||||
pub(crate) fn scheme(address: &str) -> String {
|
||||
match address.split_once("://") {
|
||||
Some((scheme, _)) => scheme.to_ascii_lowercase(),
|
||||
None => TEAMSPEAK_SCHEME.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a session to `params.address` with the connector of its scheme.
|
||||
pub(crate) fn connect(
|
||||
&self,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> BoxFuture<Result<LocalConnected, SessionError>> {
|
||||
let scheme = Self::scheme(¶ms.address);
|
||||
if let Some(local) = self.locals.iter().find(|c| c.accepts(&scheme)) {
|
||||
return local.connect_local(params, ctx);
|
||||
}
|
||||
// Not `Connectors::connect`, which names the whole address when none serves it:
|
||||
// the text is shown, and a TeamSpeak link carries a channel password.
|
||||
let Some(connector) = self.connectors.for_address(¶ms.address) else {
|
||||
let shown = without_query(¶ms.address).to_owned();
|
||||
return Box::pin(async move {
|
||||
Err(SessionError::Protocol(format!("no connector for {shown}")))
|
||||
});
|
||||
};
|
||||
let connect = connector.connect(params);
|
||||
Box::pin(async move {
|
||||
let connected = connect.await?;
|
||||
Ok(LocalConnected { connected, streams: None })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// An address as it may be shown or logged: without its query and fragment,
|
||||
/// where a link keeps a channel password or a host pin.
|
||||
pub(crate) fn without_query(address: &str) -> &str {
|
||||
address.split(['?', '#']).next().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Refuses every host that asks to be trusted.
|
||||
struct RefuseUnknownHosts;
|
||||
|
||||
impl HostTrust for RefuseUnknownHosts {
|
||||
fn confirm(&self, _host: HostIdentity) -> BoxFuture<bool> {
|
||||
Box::pin(async { false })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_bookmark_without_a_scheme_is_a_teamspeak_server() {
|
||||
assert_eq!(Backends::scheme("ts.example.com:9987"), "ts3server");
|
||||
assert_eq!(Backends::scheme("[::1]:9987"), "ts3server");
|
||||
assert_eq!(Backends::scheme("TS3Server://ts.example.com"), "ts3server");
|
||||
assert_eq!(Backends::scheme("teamspeak://x"), "teamspeak");
|
||||
assert_eq!(Backends::scheme("voelin://host/i/code"), "voelin");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_address_is_shown_without_its_secrets() {
|
||||
assert_eq!(without_query("ts3server://h?port=1&channelpassword=hunter2"), "ts3server://h");
|
||||
assert_eq!(without_query("voelin://h/i/code#h=abcd"), "voelin://h/i/code");
|
||||
assert_eq!(without_query("host:9987"), "host:9987");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
//! What a session hands the connector of an address: the `ConnectParams` of
|
||||
//! a [`VoiceOptions`] (`docs/session-seam.md` section 4.2).
|
||||
//!
|
||||
//! The options are the engine's own, and a connector reads them back: the
|
||||
//! address is the link of the bookmark (a `ts3server://` link for a
|
||||
//! bookmark that names a TeamSpeak server by `host[:port]`), the nickname,
|
||||
//! the server password and the privilege key are in the hello, the identity
|
||||
//! is the credential. What v1 has no field for yet (the channel to join and
|
||||
//! its password, the client version a TeamSpeak server is shown) rides in
|
||||
//! the address, as parameters of the link.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use bytes::Bytes;
|
||||
use voelin_identity::{IdentityBlob, KIND_TEAMSPEAK};
|
||||
use voelin_model::Link;
|
||||
use voelin_proto::link::{ConnectParams, Credential, IssuerTrust, MediaSink, SessionError};
|
||||
use voelin_proto::v1;
|
||||
|
||||
use super::{Backends, VoiceOptions, without_query};
|
||||
|
||||
/// The link parameter that carries the client version to impersonate: the
|
||||
/// user's spec (`VoiceOptions::client_version`), in unpadded URL-safe base64.
|
||||
/// The connector for TeamSpeak resolves it; other connectors never read it.
|
||||
pub(crate) const VERSION_PARAM: &str = "client_version";
|
||||
|
||||
/// The connect parameters of a connection, from the options the session was
|
||||
/// asked to connect with.
|
||||
///
|
||||
/// The address is the link of the bookmark (the channel and its password
|
||||
/// ride in it, and so does the client version to claim, until v1 has fields
|
||||
/// for them), the server password is `Hello.password` and the privilege key
|
||||
/// `Hello.invite_code`. The identity goes as the credential of its kind; no
|
||||
/// account is used yet.
|
||||
///
|
||||
/// An address a link cannot carry is refused here ([`bookmark`]), and so is
|
||||
/// an identity that is of no kind a connector can use.
|
||||
pub(crate) fn connect_params(
|
||||
options: &VoiceOptions,
|
||||
media: Arc<dyn MediaSink>,
|
||||
backends: &Backends,
|
||||
) -> Result<ConnectParams, SessionError> {
|
||||
let hello = v1::Hello {
|
||||
version: 1,
|
||||
client: Some(v1::ClientInfo {
|
||||
name: "Voelin".into(),
|
||||
version: voelin_platform::crash::app_version().to_owned(),
|
||||
platform: std::env::consts::OS.into(),
|
||||
kind: v1::ClientKind::User as i32,
|
||||
}),
|
||||
nickname: options.nickname.clone(),
|
||||
password: options.server_password.clone().unwrap_or_default(),
|
||||
invite_code: options.token.clone().unwrap_or_default(),
|
||||
..Default::default()
|
||||
};
|
||||
Ok(ConnectParams {
|
||||
address: address_link(options)?,
|
||||
credential: credential(options.identity.as_ref())?,
|
||||
linked: Vec::new(),
|
||||
account: backends.account(),
|
||||
issuer_trust: IssuerTrust::Unknown,
|
||||
hello,
|
||||
host_pin: None,
|
||||
trust: backends.trust(),
|
||||
media,
|
||||
push_capacity: 1024,
|
||||
timeout: Duration::from_secs(35),
|
||||
})
|
||||
}
|
||||
|
||||
/// The credential of an identity (`docs/session-seam.md` section 7). A
|
||||
/// TeamSpeak identity goes as the JSON the key store keeps, and none at all as
|
||||
/// an empty one, for which the TeamSpeak connector makes an identity up (the
|
||||
/// protocol's convention for "generate one", follow-up P11); a Voelin key
|
||||
/// signs. A TeamSpeak identity that holds no JSON is refused: sent as it is,
|
||||
/// it would be that same empty blob and be taken for the request to make one
|
||||
/// up, which only the absence of an identity may be.
|
||||
fn credential(identity: Option<&IdentityBlob>) -> Result<Credential, SessionError> {
|
||||
let Some(blob) = identity else {
|
||||
return Ok(Credential::Foreign { kind: KIND_TEAMSPEAK, blob: Bytes::new() });
|
||||
};
|
||||
if blob.is_teamspeak() {
|
||||
if blob.json.trim().is_empty() {
|
||||
return Err(SessionError::Protocol(
|
||||
"the TeamSpeak identity cannot be read: it is empty".into(),
|
||||
));
|
||||
}
|
||||
let json = Bytes::copy_from_slice(blob.json.as_bytes());
|
||||
Ok(Credential::Foreign { kind: KIND_TEAMSPEAK, blob: json })
|
||||
} else if blob.is_voelin() {
|
||||
let key = blob.voelin_key().map_err(|e| {
|
||||
SessionError::Protocol(format!("the Voelin identity cannot be read: {e}"))
|
||||
})?;
|
||||
Ok(Credential::Voelin(Arc::new(key)))
|
||||
} else {
|
||||
Err(SessionError::Protocol(format!(
|
||||
"an identity of kind {:?} cannot be used to connect",
|
||||
blob.kind
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The `ts3server://` link of the options' address, with the channel to join
|
||||
/// and the client version to claim.
|
||||
fn address_link(options: &VoiceOptions) -> Result<String, SessionError> {
|
||||
let mut link = match Link::parse(&options.address) {
|
||||
Some(Link::Server(link)) => link,
|
||||
// Not a TeamSpeak link, or none: a bookmark's `host[:port]`.
|
||||
_ if !options.address.contains("://") => bookmark(&options.address)?,
|
||||
// Some other scheme: as given, for the connector of that scheme.
|
||||
_ => return Ok(options.address.clone()),
|
||||
};
|
||||
link.channel = options.channel.clone().filter(|c| !c.is_empty()).or(link.channel);
|
||||
link.channel_password =
|
||||
options.channel_password.clone().filter(|p| !p.is_empty()).or(link.channel_password);
|
||||
let mut url = link.to_url();
|
||||
if let Some(spec) = &options.client_version {
|
||||
url.push(if url.contains('?') { '&' } else { '?' });
|
||||
url.push_str(VERSION_PARAM);
|
||||
url.push('=');
|
||||
url.push_str(&URL_SAFE_NO_PAD.encode(spec));
|
||||
}
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
/// The link to a bookmark's `host[:port]`.
|
||||
///
|
||||
/// A link cannot say everything an address can: it drops a port that is no
|
||||
/// port (`ServerLink::new` takes `host:99999` for the host `host` and joins
|
||||
/// the default port), and it ends the host at a `?`, `#` or `/` and decodes a
|
||||
/// `%` (so that a `?` in the host would hide the channel behind the next
|
||||
/// one). The TeamSpeak library refuses such an address when it resolves it;
|
||||
/// so does this, in words, instead of connecting to something else.
|
||||
fn bookmark(address: &str) -> Result<voelin_model::ServerLink, SessionError> {
|
||||
let address = address.trim();
|
||||
// Without the query: a link keeps secrets in it.
|
||||
let shown = without_query(address);
|
||||
let not_an_address = || SessionError::Protocol(format!("not a server address: {shown}"));
|
||||
if address.is_empty()
|
||||
|| address
|
||||
.chars()
|
||||
.any(|c| matches!(c, '?' | '#' | '/' | '%') || c.is_whitespace() || c.is_control())
|
||||
{
|
||||
return Err(not_an_address());
|
||||
}
|
||||
// The text after the port's colon: `[v6]:port`, or `host:port` with the one
|
||||
// colon (more colons are an IPv6 address without a port).
|
||||
let port = if let Some(rest) = address.strip_prefix('[') {
|
||||
let (_, after) = rest.split_once(']').ok_or_else(not_an_address)?;
|
||||
(!after.is_empty()).then(|| after.strip_prefix(':').unwrap_or(after))
|
||||
} else {
|
||||
address.rsplit_once(':').filter(|(host, _)| !host.contains(':')).map(|(_, port)| port)
|
||||
};
|
||||
if let Some(port) = port
|
||||
&& !port.parse::<u16>().is_ok_and(|port| port != 0)
|
||||
{
|
||||
return Err(SessionError::Protocol(format!(
|
||||
"the port in {shown} is not a number from 1 to 65535"
|
||||
)));
|
||||
}
|
||||
Ok(voelin_model::ServerLink::new(address))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use voelin_identity::IdentityKey;
|
||||
|
||||
fn params(options: &VoiceOptions) -> Result<ConnectParams, SessionError> {
|
||||
let (media, _rx) = voelin_proto::test_util::media_channel();
|
||||
connect_params(options, media, &Backends::empty())
|
||||
}
|
||||
|
||||
/// The identity of the options is the credential of its kind: a TeamSpeak
|
||||
/// identity as the JSON the key store keeps, none as the empty blob a
|
||||
/// connector makes an identity up for, a Voelin key as its signer.
|
||||
#[test]
|
||||
fn an_identity_is_the_credential_of_its_kind() {
|
||||
let mut options = VoiceOptions::new("ts.example.com", "nick");
|
||||
let none = params(&options).unwrap();
|
||||
assert!(matches!(
|
||||
&none.credential,
|
||||
Credential::Foreign { kind: "teamspeak", blob } if blob.is_empty()
|
||||
));
|
||||
|
||||
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, r#"{"key":"k"}"#));
|
||||
let sent = params(&options).unwrap();
|
||||
assert!(matches!(
|
||||
&sent.credential,
|
||||
Credential::Foreign { kind: "teamspeak", blob } if &blob[..] == br#"{"key":"k"}"#
|
||||
));
|
||||
|
||||
let key = IdentityKey::generate().unwrap();
|
||||
options.identity = Some(IdentityBlob::voelin(&key).unwrap());
|
||||
let Credential::Voelin(signer) = params(&options).unwrap().credential else {
|
||||
panic!("a Voelin credential")
|
||||
};
|
||||
assert_eq!(signer.public_key(), key.public_key());
|
||||
assert_eq!(signer.sign(b"hello"), key.sign(b"hello"));
|
||||
|
||||
// A Voelin blob whose key cannot be read, and a kind that connects to
|
||||
// nothing: refused in words, without the JSON.
|
||||
options.identity = Some(IdentityBlob::new("voelin", "x", 0, "hunter2"));
|
||||
let Err(SessionError::Protocol(text)) = params(&options) else { panic!("a refusal") };
|
||||
assert!(
|
||||
text.starts_with("the Voelin identity cannot be read") && !text.contains("hunter2")
|
||||
);
|
||||
options.identity = Some(IdentityBlob::new("account", "x", 0, "hunter2"));
|
||||
let Err(SessionError::Protocol(text)) = params(&options) else { panic!("a refusal") };
|
||||
assert_eq!(text, "an identity of kind \"account\" cannot be used to connect");
|
||||
}
|
||||
|
||||
/// A TeamSpeak identity with no JSON is no identity. The empty blob is
|
||||
/// what asks the TeamSpeak connector to make one up (`identity: None`), so
|
||||
/// it is refused here instead of being sent as that request.
|
||||
#[test]
|
||||
fn a_teamspeak_identity_without_json_is_refused() {
|
||||
let mut options = VoiceOptions::new("ts.example.com", "nick");
|
||||
for json in ["", " \n\t"] {
|
||||
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, json));
|
||||
let Err(SessionError::Protocol(text)) = params(&options) else {
|
||||
panic!("a refusal for {json:?}")
|
||||
};
|
||||
assert_eq!(text, "the TeamSpeak identity cannot be read: it is empty");
|
||||
}
|
||||
// No identity at all is the request to make one up, as before.
|
||||
options.identity = None;
|
||||
assert!(matches!(
|
||||
params(&options).unwrap().credential,
|
||||
Credential::Foreign { kind: "teamspeak", blob } if blob.is_empty()
|
||||
));
|
||||
}
|
||||
|
||||
/// The client version spec rides the link as it was typed, whatever it
|
||||
/// holds, and only for an address that is a TeamSpeak bookmark or link.
|
||||
#[test]
|
||||
fn the_client_version_spec_rides_the_link_unchanged() {
|
||||
let spec = |address: &str, spec: &str| {
|
||||
let mut options = VoiceOptions::new(address, "nick");
|
||||
options.client_version = Some(spec.into());
|
||||
params(&options).unwrap().address
|
||||
};
|
||||
let address = spec("ts.example.com:9988", "windows@3.6.2 [Build: 1]&x=#");
|
||||
let (_, query) = address.split_once('?').unwrap();
|
||||
let text = query
|
||||
.split('&')
|
||||
.find_map(|pair| pair.strip_prefix("client_version="))
|
||||
.expect("the parameter");
|
||||
let decoded = URL_SAFE_NO_PAD.decode(text).unwrap();
|
||||
assert_eq!(decoded, b"windows@3.6.2 [Build: 1]&x=#");
|
||||
// Another scheme is left as it is: its connector has no use for a TeamSpeak
|
||||
// client's version.
|
||||
assert_eq!(spec("voelin://host/i/code", "generic"), "voelin://host/i/code");
|
||||
// No spec, no parameter.
|
||||
let options = VoiceOptions::new("ts.example.com", "nick");
|
||||
assert!(!params(&options).unwrap().address.contains(VERSION_PARAM));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
//! 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. These are the tests that need the inner link itself:
|
||||
//!
|
||||
//! - the stream commands, which travel on the in-process port of the link
|
||||
//! and which a `voelin_proto::link::Session` has no part in until the
|
||||
//! stream task moves (`docs/session-seam.md` sections 6.4 and 9.2);
|
||||
//! - the order in which a reconnect shuts the streams and the old connection
|
||||
//! down, which is the order of the one queue `LinkSession` keeps;
|
||||
//! - a link that keeps talking after the engine replaced its connection,
|
||||
//! which a closed `FakeSession` cannot do on purpose.
|
||||
//!
|
||||
//! (They were integration tests while the inner link was public; it is the
|
||||
//! TeamSpeak module's now, and so are these.)
|
||||
//!
|
||||
//! Presence, chat, the dedup of a message that comes twice, history, transfers
|
||||
//! and the rest of what the engine does with a session are tested on the
|
||||
//! protocol repository's fake host in `tests/session_fake.rs`. 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 super::{Backends, LinkCmd, LinkCtx, LinkEvent};
|
||||
use crate::settings::Settings;
|
||||
use crate::stream::{StreamCmd, StreamSetup};
|
||||
use crate::ts::ts_session::LinkConnector;
|
||||
use crate::ts::{ConnectOptions, ServerLink};
|
||||
use crate::{
|
||||
BackendInfo, Command, Engine, Event, History, SessionId, SessionState, VoiceOptions, VoiceState,
|
||||
};
|
||||
use voelin_model::{
|
||||
Capabilities, ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence,
|
||||
ServerDetails,
|
||||
};
|
||||
|
||||
/// A connection the session asked the link for.
|
||||
struct Conn {
|
||||
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 _ = self.conns.send(Conn { cmds, events });
|
||||
}
|
||||
}
|
||||
|
||||
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 mut backends = Backends::empty();
|
||||
backends.register_local(Arc::new(LinkConnector::any(Arc::new(link))));
|
||||
let engine =
|
||||
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends);
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
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()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A client as a TeamSpeak link reports one: with its database id, and not
|
||||
/// talking (who talks comes from the media, which the session derives).
|
||||
fn client(id: u16, nickname: &str, channel: ChannelId) -> ClientInfo {
|
||||
ClientInfo {
|
||||
id,
|
||||
uid: Some(format!("{nickname}=")),
|
||||
nickname: nickname.into(),
|
||||
channel,
|
||||
talking: Some(false),
|
||||
database_id: Some(1_000 + u64::from(id)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Two channels, three clients; we are in the second channel. The shape is
|
||||
/// what a TeamSpeak link reports: sibling channels form an order chain, the
|
||||
/// server is named and has its unique id.
|
||||
fn presence() -> Presence {
|
||||
let channel =
|
||||
|id, name: &str, order| ChannelInfo { id, name: name.into(), order, ..Default::default() };
|
||||
let mut presence = Presence { server_name: "Fake Server".into(), ..Default::default() };
|
||||
presence.server = ServerDetails {
|
||||
name: "Fake Server".into(),
|
||||
uid: Some(SERVER_UID.into()),
|
||||
version: backend().version,
|
||||
..Default::default()
|
||||
};
|
||||
presence.channels.insert(LOBBY, channel(LOBBY, "Lobby", 0));
|
||||
presence.channels.insert(GAMES, channel(GAMES, "Games", LOBBY));
|
||||
let me = ClientInfo { uid: Some(ME_UID.into()), ..client(ME, "tester", GAMES) };
|
||||
for c in [me, 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,
|
||||
}
|
||||
}
|
||||
|
||||
/// Stream commands reach a link that has streams in its capabilities, and
|
||||
/// end with the connection; a link without them is spared. (The rest of what
|
||||
/// the user asks for is checked on the fake host in `session_fake.rs`.)
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn stream_commands_reach_a_link_with_streams() {
|
||||
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;
|
||||
|
||||
// No streams in the capabilities: the session refuses them itself.
|
||||
let engine = h.engine.clone();
|
||||
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));
|
||||
}
|
||||
|
||||
/// 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);
|
||||
// A link that says we are in the lobby shows us in the lobby.
|
||||
fresh.clients.get_mut(&ME).expect("we are on the server").channel = LOBBY;
|
||||
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");
|
||||
// Channel chat reaches the channel we are in (the lobby, now).
|
||||
new.play([LinkEvent::Chat(ChatMessage {
|
||||
target: ChatTarget::Channel(LOBBY),
|
||||
..message("alice", "hello", now_ms())
|
||||
})]);
|
||||
assert_eq!(h.chat().await.text, "hello", "the old connection's chat never showed");
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
//! The engine's side of the seam against the protocol repository's fake host
|
||||
//! (`docs/session-seam.md` sections 9.2 and 16): the voice path through a
|
||||
//! `SessionLink` that talks to a `FakeSession`, and the link conformance
|
||||
//! suite run against the session the engine's registry hands over.
|
||||
//!
|
||||
//! The tests that need only the engine's public API are in
|
||||
//! `tests/session_fake.rs`; these need what is private to the crate: the
|
||||
//! `LinkCmd`/`LinkEvent` vocabulary between `session.rs` and `SessionLink`,
|
||||
//! the registry's `connect` and the context of a connector called outside an
|
||||
//! engine.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use voelin_audio::{EncodedVoice, VoiceCodec, VoicePacket};
|
||||
use voelin_proto::link::{FlowId, MediaClass, MediaPacket, voice_sub};
|
||||
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, PT_OPUS};
|
||||
use voelin_proto::media::{RtpHeader, RtpView};
|
||||
use voelin_proto::test_util::conformance::{self, Fixture, Verdict};
|
||||
use voelin_proto::test_util::{
|
||||
FAKE_HOST_UID, FakeConnector, FakeHandle, connect_params, eventually,
|
||||
};
|
||||
use voelin_proto::v1::{self, entity::Kind};
|
||||
|
||||
use super::*;
|
||||
|
||||
const WAIT: Duration = Duration::from_secs(10);
|
||||
/// An Opus frame of 20 ms, mono (TOC `0xf8`), and the same as stereo (`0xfc`).
|
||||
const MONO: [u8; 3] = [0xf8, 0xff, 0xfe];
|
||||
const STEREO: [u8; 3] = [0xfc, 0xff, 0xfe];
|
||||
const ALICE: u32 = 50;
|
||||
const ALICE_SLOT: u32 = 90;
|
||||
const BOB: u32 = 51;
|
||||
const BOB_SLOT: u32 = 91;
|
||||
|
||||
fn put(connector: &FakeConnector, kind: Kind) {
|
||||
connector.host().put(v1::Entity { kind: Some(kind) }).expect("the fake host stores it");
|
||||
}
|
||||
|
||||
/// A host with one server, a lobby, and alice and bob talking in it.
|
||||
fn host() -> FakeConnector {
|
||||
let connector = FakeConnector::new();
|
||||
put(
|
||||
&connector,
|
||||
Kind::Server(v1::Server {
|
||||
id: 1,
|
||||
name: "Fake Host".into(),
|
||||
uid: "fake-host".into(),
|
||||
default_channel_id: 10,
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
put(
|
||||
&connector,
|
||||
Kind::Channel(v1::Channel {
|
||||
id: 10,
|
||||
server_id: 1,
|
||||
kind: v1::ChannelKind::Voice as i32,
|
||||
name: "Lobby".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
for (user, participant, slot, name) in
|
||||
[(2, ALICE, ALICE_SLOT, "alice"), (3, BOB, BOB_SLOT, "bob")]
|
||||
{
|
||||
put(
|
||||
&connector,
|
||||
Kind::User(v1::User {
|
||||
id: user,
|
||||
uid: vec![user as u8; 32].into(),
|
||||
uid_kind: v1::IdKind::Voelin as i32,
|
||||
name: name.into(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
put(
|
||||
&connector,
|
||||
Kind::Voice(v1::VoiceState {
|
||||
server_id: 1,
|
||||
participant_id: participant,
|
||||
user_id: user,
|
||||
channel_id: 10,
|
||||
slot,
|
||||
nick: name.into(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
}
|
||||
connector
|
||||
}
|
||||
|
||||
/// A `SessionLink` over a fake host, driven the way `session.rs` drives it.
|
||||
struct HostRig {
|
||||
handle: FakeHandle,
|
||||
cmds: mpsc::UnboundedSender<LinkCmd>,
|
||||
events: mpsc::UnboundedReceiver<LinkEvent>,
|
||||
/// Our participant and voice slot, as the host gave them.
|
||||
own_client: u16,
|
||||
own_slot: u32,
|
||||
/// The clients the link told started talking, in order.
|
||||
talking: Vec<u16>,
|
||||
}
|
||||
|
||||
/// The next event `f` picks from `events`, skipping the others.
|
||||
async fn event_of<T>(
|
||||
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
|
||||
mut f: impl FnMut(LinkEvent) -> Option<T>,
|
||||
) -> T {
|
||||
tokio::time::timeout(WAIT, async {
|
||||
loop {
|
||||
if let Some(t) = f(events.recv().await.expect("the link lives")) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("an event in time")
|
||||
}
|
||||
|
||||
impl HostRig {
|
||||
async fn connect() -> Self {
|
||||
let connector = host();
|
||||
let mut backends = Backends::empty();
|
||||
backends.register(Arc::new(connector.clone()));
|
||||
let link = SessionLink::new(backends);
|
||||
let (cmds, cmd_rx) = mpsc::unbounded_channel();
|
||||
let (event_tx, mut events) = mpsc::unbounded_channel();
|
||||
let ctx = LocalCtx::standalone().link;
|
||||
link.spawn(VoiceOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx);
|
||||
let own_client = event_of(&mut events, |e| match e {
|
||||
LinkEvent::Connected { own_client, .. } => Some(own_client),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
event_of(&mut events, |e| matches!(e, LinkEvent::OwnChannel(10)).then_some(())).await;
|
||||
let own_slot = connector
|
||||
.host()
|
||||
.entities(&v1::Scope { kind: v1::ScopeKind::Live as i32, id: 1 })
|
||||
.into_iter()
|
||||
.find_map(|e| match e.kind? {
|
||||
Kind::Voice(v) if v.participant_id == u32::from(own_client) => Some(v.slot),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the host seated us in voice");
|
||||
let handle = connector.last_session().expect("the connector made a session");
|
||||
Self { handle, cmds, events, own_client, own_slot, talking: Vec::new() }
|
||||
}
|
||||
|
||||
/// The next voice packet the audio thread would get; who started to talk on
|
||||
/// the way is kept in `talking`.
|
||||
async fn audio(&mut self) -> VoicePacket {
|
||||
let talking = &mut self.talking;
|
||||
event_of(&mut self.events, |e| match e {
|
||||
LinkEvent::Talking { client, talking: true } => {
|
||||
talking.push(client);
|
||||
None
|
||||
}
|
||||
LinkEvent::Audio(packet) => Some(packet),
|
||||
_ => None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
fn give(&self, cmd: LinkCmd) {
|
||||
self.cmds.send(cmd).expect("the link listens");
|
||||
}
|
||||
}
|
||||
|
||||
/// A voice packet of `slot` on sub-flow `sub`, as a host delivers it.
|
||||
fn voice_packet(slot: u32, sub: u8, sequence: u16, payload: &[u8]) -> MediaPacket {
|
||||
let flow = FlowId::new(slot, sub);
|
||||
let mut out = bytes::BytesMut::new();
|
||||
RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960)
|
||||
.write(flow, &mut out)
|
||||
.expect("a header");
|
||||
out.extend_from_slice(payload);
|
||||
MediaPacket { flow, rtp: out.freeze() }
|
||||
}
|
||||
|
||||
fn voice(payload: &[u8]) -> EncodedVoice {
|
||||
EncodedVoice { codec: VoiceCodec::Voice, payload: payload.to_vec() }
|
||||
}
|
||||
|
||||
/// Our voice leaves as RTP on the slot the host gave us: the sequence counts
|
||||
/// every packet, the timestamp advances by the duration of the previous one,
|
||||
/// the marker is on the first packet of a spurt, the end of a spurt is an
|
||||
/// empty payload sent once, and the SSRC is the flow (protocol section 6).
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn our_voice_is_rtp_on_the_slot_the_host_gave_us() {
|
||||
let rig = HostRig::connect().await;
|
||||
// The fake host loops accepted media back; this test looks at what left.
|
||||
rig.handle.set_loopback(false);
|
||||
for n in 1..=3 {
|
||||
rig.give(LinkCmd::Audio(voice(&[0xf8, 0xff, 0xfe, n])));
|
||||
}
|
||||
rig.give(LinkCmd::Audio(voice(&[])));
|
||||
rig.give(LinkCmd::Audio(voice(&[0xf8, 0xff, 0xfe, 9])));
|
||||
let handle = rig.handle.clone();
|
||||
eventually(WAIT, "the five packets", || handle.sent_media().len() == 5).await;
|
||||
|
||||
let flow = FlowId::new(rig.own_slot, voice_sub::CHANNEL);
|
||||
let sent = rig.handle.sent_media();
|
||||
let seen: Vec<_> = sent
|
||||
.iter()
|
||||
.map(|(class, packet)| {
|
||||
let view = RtpView::parse(&packet.rtp).expect("RTP");
|
||||
assert_eq!(*class, MediaClass::Voice);
|
||||
assert_eq!(packet.flow, flow);
|
||||
assert_eq!((view.payload_type(), view.ssrc()), (PT_OPUS, flow.0));
|
||||
(view.sequence(), view.marker(), view.timestamp(), view.payload().to_vec())
|
||||
})
|
||||
.collect();
|
||||
let ticks = OPUS_20_MS_TICKS;
|
||||
assert_eq!(
|
||||
seen,
|
||||
[
|
||||
(0, true, 0, vec![0xf8, 0xff, 0xfe, 1]),
|
||||
(1, false, ticks, vec![0xf8, 0xff, 0xfe, 2]),
|
||||
(2, false, 2 * ticks, vec![0xf8, 0xff, 0xfe, 3]),
|
||||
// The end of the spurt: no payload, no marker, once.
|
||||
(3, false, 3 * ticks, vec![]),
|
||||
// The next spurt marks its first packet again.
|
||||
(4, true, 3 * ticks, vec![0xf8, 0xff, 0xfe, 9]),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// The RTP of other slots becomes the packets of the audio thread: the talker
|
||||
/// is the participant of the slot, a whisper sub-flow is a whisper, a stereo
|
||||
/// Opus frame is music, an empty payload ends the spurt; what is no voice of a
|
||||
/// slot the host told about is dropped.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_voice_of_other_slots_reaches_the_audio_thread() {
|
||||
let mut rig = HostRig::connect().await;
|
||||
let handle = rig.handle.clone();
|
||||
|
||||
// A slot nobody has, a probe and feedback: nothing. Then alice, mono.
|
||||
handle.inject_media(voice_packet(777, voice_sub::CHANNEL, 1, &MONO));
|
||||
handle.inject_media(MediaPacket { flow: FlowId::PROBE, rtp: bytes::Bytes::from_static(&[1]) });
|
||||
handle.inject_media(MediaPacket {
|
||||
flow: FlowId::FEEDBACK,
|
||||
rtp: bytes::Bytes::from_static(&[1, 2]),
|
||||
});
|
||||
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 5, &MONO));
|
||||
let packet = rig.audio().await;
|
||||
assert_eq!(
|
||||
(packet.talker.0, packet.seq, packet.codec, packet.whisper, packet.payload.as_slice()),
|
||||
(ALICE as u16, 5, VoiceCodec::Voice, false, MONO.as_slice())
|
||||
);
|
||||
|
||||
// Bob whispers (sub-flow 1) in stereo: music, a whisper.
|
||||
handle.inject_media(voice_packet(BOB_SLOT, 1, 6, &STEREO));
|
||||
let packet = rig.audio().await;
|
||||
assert_eq!(
|
||||
(packet.talker.0, packet.seq, packet.codec, packet.whisper),
|
||||
(BOB as u16, 6, VoiceCodec::Music, true)
|
||||
);
|
||||
|
||||
// Alice stops: an empty payload.
|
||||
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 7, &[]));
|
||||
let packet = rig.audio().await;
|
||||
assert_eq!((packet.talker.0, packet.seq, packet.payload.len()), (ALICE as u16, 7, 0));
|
||||
|
||||
// Who talks comes from the same packets: alice started, then bob, once each
|
||||
// (the slot nobody has started nobody).
|
||||
assert_eq!(rig.talking, [ALICE as u16, BOB as u16]);
|
||||
}
|
||||
|
||||
/// A host whose session loops our own voice back (the fake one does, so that
|
||||
/// the conformance suite can see media move) does not make the engine play us
|
||||
/// our own voice or show us as talking: the engine never plays itself.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn our_own_voice_coming_back_is_not_played_back() {
|
||||
let mut rig = HostRig::connect().await;
|
||||
// The fake host loops accepted media back into the sink (the default).
|
||||
rig.give(LinkCmd::Audio(voice(&MONO)));
|
||||
let handle = rig.handle.clone();
|
||||
eventually(WAIT, "the packet to leave", || handle.sent_media().len() == 1).await;
|
||||
// A packet of alice behind it: when this one is out, ours has been through.
|
||||
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 1, &MONO));
|
||||
let own = rig.own_client;
|
||||
let mut heard = Vec::new();
|
||||
while heard.last().is_none_or(|talker| *talker != ALICE as u16) {
|
||||
heard.push(rig.audio().await.talker.0);
|
||||
}
|
||||
assert!(!heard.contains(&own), "the engine played our own voice back: {heard:?}");
|
||||
}
|
||||
|
||||
/// The link conformance suite of the protocol repository against the session
|
||||
/// the engine's registry hands over: the registry adds nothing to a plain
|
||||
/// connector's session (`Backends::connect` returns it untouched), so the 17
|
||||
/// cases pass as they do in the protocol repository, none skipped.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_conformance_suite_passes_on_a_session_of_the_registry() {
|
||||
async fn through_the_registry() -> Fixture {
|
||||
let connector = FakeConnector::new();
|
||||
let mut backends = Backends::empty();
|
||||
backends.register(Arc::new(connector.clone()));
|
||||
let (params, media) = connect_params("fake://conformance");
|
||||
let local = backends
|
||||
.connect(params, LocalCtx::standalone())
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("the registry connects: {e}"));
|
||||
assert_eq!(local.connected.host_uid, FAKE_HOST_UID, "the connector's own answer");
|
||||
assert!(local.streams.is_none(), "a plain connector has no stream port");
|
||||
let backend = connector.last_session().expect("the connector made a session");
|
||||
// The session is the connector's own, so a request id means the same to both.
|
||||
Fixture {
|
||||
shared_request_ids: true,
|
||||
..Fixture::new(local.connected.session, local.connected.pushes, media, backend)
|
||||
}
|
||||
}
|
||||
let report = conformance::run(&through_the_registry).await;
|
||||
assert_eq!(report.cases.len(), conformance::CASES.len());
|
||||
assert_eq!(report.cases.len(), 17, "the suite of c8e0e5a has 17 cases");
|
||||
assert!(
|
||||
report.cases.iter().all(|(_, verdict)| *verdict == Verdict::Passed),
|
||||
"{:?}",
|
||||
report.cases
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
//! Voice across the seam, engine side (`docs/session-seam.md` section 6.1):
|
||||
//! our encoded frames as RTP on our voice slot, the RTP of other slots as
|
||||
//! the audio thread's packets, and who is talking from the media.
|
||||
//!
|
||||
//! `voelin-audio`'s [`EncodedVoice`] and [`VoicePacket`] stay what the audio
|
||||
//! thread speaks; this is the framing in the v1 media codec
|
||||
//! (`voelin_proto::media`, protocol section 6).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::BytesMut;
|
||||
use voelin_audio::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket};
|
||||
use voelin_proto::link::{FlowId, MediaPacket, voice_sub};
|
||||
use voelin_proto::media::opus::{self, Toc};
|
||||
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, PT_OPUS};
|
||||
use voelin_proto::media::{RtpHeader, RtpView};
|
||||
|
||||
/// A talker is silent after this long without a packet.
|
||||
pub(crate) const TALK_SILENCE: Duration = Duration::from_millis(400);
|
||||
|
||||
/// Our voice as RTP: the sequence number counts every packet from 0, the
|
||||
/// timestamp starts at 0 and advances by the duration of the previous
|
||||
/// packet, the marker is set on the first packet of a spurt, and the end of a
|
||||
/// spurt is a packet with an empty payload, sent once.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Uplink {
|
||||
sequence: u16,
|
||||
timestamp: u32,
|
||||
/// The ticks the last voice packet spans.
|
||||
ticks: u32,
|
||||
in_spurt: bool,
|
||||
}
|
||||
|
||||
impl Uplink {
|
||||
/// `voice` as the RTP packet of our voice slot.
|
||||
pub(crate) fn frame(&mut self, slot: u32, voice: &EncodedVoice) -> Option<MediaPacket> {
|
||||
let flow = FlowId::new(slot, voice_sub::CHANNEL);
|
||||
// The previous packet's duration has passed.
|
||||
self.timestamp = self.timestamp.wrapping_add(self.ticks);
|
||||
let end = voice.is_end();
|
||||
let mut header = RtpHeader::new(PT_OPUS, self.sequence, self.timestamp);
|
||||
header.marker = !end && !self.in_spurt;
|
||||
self.ticks =
|
||||
if end { 0 } else { opus::packet_ticks(&voice.payload).unwrap_or(OPUS_20_MS_TICKS) };
|
||||
self.in_spurt = !end;
|
||||
self.sequence = self.sequence.wrapping_add(1);
|
||||
let mut out = BytesMut::with_capacity(header.encoded_len() + voice.payload.len());
|
||||
header.write(flow, &mut out).ok()?;
|
||||
out.extend_from_slice(&voice.payload);
|
||||
Some(MediaPacket { flow, rtp: out.freeze() })
|
||||
}
|
||||
}
|
||||
|
||||
/// A voice packet of some slot, taken from its RTP.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Incoming {
|
||||
pub(crate) slot: u32,
|
||||
/// Sent on a whisper sub-flow (1 to 6).
|
||||
pub(crate) whisper: bool,
|
||||
pub(crate) sequence: u16,
|
||||
pub(crate) codec: VoiceCodec,
|
||||
/// Empty: the spurt ends.
|
||||
pub(crate) payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Incoming {
|
||||
/// Parse a media packet. `None` for what is not the voice of a slot:
|
||||
/// feedback, probes, a flow that is no media, a packet that is no RTP.
|
||||
pub(crate) fn parse(packet: &MediaPacket) -> Option<Incoming> {
|
||||
if !packet.flow.is_media() {
|
||||
return None;
|
||||
}
|
||||
let view = RtpView::parse(&packet.rtp).ok()?;
|
||||
let payload = view.payload();
|
||||
// Stereo Opus is music; the jitter buffer decodes both the same way.
|
||||
let codec = match Toc::parse(payload) {
|
||||
Ok(toc) if toc.stereo() => VoiceCodec::Music,
|
||||
_ => VoiceCodec::Voice,
|
||||
};
|
||||
Some(Incoming {
|
||||
slot: packet.flow.slot(),
|
||||
whisper: (voice_sub::FIRST_TALK_TARGET..=voice_sub::LAST_TALK_TARGET)
|
||||
.contains(&packet.flow.sub()),
|
||||
sequence: view.sequence(),
|
||||
codec,
|
||||
payload: payload.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The packet for the audio thread, from `talker`.
|
||||
pub(crate) fn voice(self, talker: u16) -> VoicePacket {
|
||||
VoicePacket {
|
||||
talker: TalkerId(talker),
|
||||
seq: self.sequence,
|
||||
codec: self.codec,
|
||||
whisper: self.whisper,
|
||||
payload: self.payload,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Who is talking: derived from the media (protocol section 6.4). A talker
|
||||
/// starts with its first packet and stops after [`TALK_SILENCE`] without one.
|
||||
///
|
||||
/// A host can also say that someone talks whose voice it does not carry as
|
||||
/// media (a `Speaking` signal; TeamSpeak's Speex and CELT talkers are such):
|
||||
/// that is a hint, which holds until the host says it is over.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct TalkTracker {
|
||||
last: HashMap<u16, Instant>,
|
||||
hinted: HashSet<u16>,
|
||||
}
|
||||
|
||||
impl TalkTracker {
|
||||
/// A packet of `client` arrived; whether this starts its talking.
|
||||
pub(crate) fn heard(&mut self, client: u16, now: Instant) -> bool {
|
||||
let was = self.is_talking(client);
|
||||
self.last.insert(client, now);
|
||||
!was
|
||||
}
|
||||
|
||||
/// The host says `client` talks or has stopped; whether this changes
|
||||
/// whether it is talking.
|
||||
pub(crate) fn hint(&mut self, client: u16, talking: bool) -> bool {
|
||||
let was = self.is_talking(client);
|
||||
if talking {
|
||||
self.hinted.insert(client);
|
||||
} else {
|
||||
self.hinted.remove(&client);
|
||||
}
|
||||
was != self.is_talking(client)
|
||||
}
|
||||
|
||||
/// Forget the hints about clients `present` does not hold any more: a
|
||||
/// client that left cannot say it stopped.
|
||||
pub(crate) fn retain_hints(&mut self, present: impl Fn(u16) -> bool) {
|
||||
self.hinted.retain(|client| present(*client));
|
||||
}
|
||||
|
||||
/// The talkers that have been silent long enough, no longer talking.
|
||||
pub(crate) fn expire(&mut self, now: Instant) -> Vec<u16> {
|
||||
let mut silent: Vec<u16> = self
|
||||
.last
|
||||
.iter()
|
||||
.filter(|(_, last)| now.saturating_duration_since(**last) >= TALK_SILENCE)
|
||||
.map(|(client, _)| *client)
|
||||
.collect();
|
||||
silent.sort_unstable();
|
||||
for client in &silent {
|
||||
self.last.remove(client);
|
||||
}
|
||||
silent.retain(|client| !self.hinted.contains(client));
|
||||
silent
|
||||
}
|
||||
|
||||
pub(crate) fn is_talking(&self, client: u16) -> bool {
|
||||
self.last.contains_key(&client) || self.hinted.contains(&client)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// 20 ms of CELT, mono, one frame.
|
||||
const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02];
|
||||
|
||||
fn voice(payload: &[u8]) -> EncodedVoice {
|
||||
EncodedVoice { codec: VoiceCodec::Voice, payload: payload.to_vec() }
|
||||
}
|
||||
|
||||
fn view(packet: &MediaPacket) -> RtpView<'_> {
|
||||
RtpView::parse(&packet.rtp).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn our_voice_is_sequenced_stamped_and_marked() {
|
||||
let mut up = Uplink::default();
|
||||
let first = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
let second = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
assert_eq!((first.flow.slot(), first.flow.sub()), (8, 0));
|
||||
let (a, b) = (view(&first), view(&second));
|
||||
assert_eq!((a.sequence(), a.timestamp(), a.marker()), (0, 0, true));
|
||||
assert_eq!((b.sequence(), b.timestamp(), b.marker()), (1, OPUS_20_MS_TICKS, false));
|
||||
assert_eq!((a.ssrc(), a.payload_type()), (first.flow.0, PT_OPUS));
|
||||
assert_eq!(a.payload(), OPUS_20_MS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_is_one_empty_packet_and_the_next_spurt_has_a_marker() {
|
||||
let mut up = Uplink::default();
|
||||
up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
let end = up.frame(8, &voice(&[])).unwrap();
|
||||
assert!(view(&end).payload().is_empty() && !view(&end).marker());
|
||||
assert_eq!(view(&end).sequence(), 1);
|
||||
let next = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
assert!(view(&next).marker());
|
||||
assert_eq!(view(&next).sequence(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sequence_wraps() {
|
||||
let mut up = Uplink { sequence: u16::MAX, ..Default::default() };
|
||||
up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
let wrapped = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
assert_eq!(view(&wrapped).sequence(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn received_voice_is_split_into_slot_sub_flow_sequence_and_codec() {
|
||||
let flow = FlowId::new(9, 0);
|
||||
let mut header = RtpHeader::new(PT_OPUS, 513, 0);
|
||||
header.marker = true;
|
||||
let mut rtp = BytesMut::new();
|
||||
header.write(flow, &mut rtp).unwrap();
|
||||
rtp.extend_from_slice(&OPUS_20_MS);
|
||||
let packet = MediaPacket { flow, rtp: rtp.freeze() };
|
||||
let got = Incoming::parse(&packet).unwrap();
|
||||
assert_eq!(
|
||||
got,
|
||||
Incoming {
|
||||
slot: 9,
|
||||
whisper: false,
|
||||
sequence: 513,
|
||||
codec: VoiceCodec::Voice,
|
||||
payload: OPUS_20_MS.to_vec()
|
||||
}
|
||||
);
|
||||
let voice = got.voice(8);
|
||||
assert_eq!((voice.talker, voice.seq, voice.whisper), (TalkerId(8), 513, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whispers_stereo_ends_and_what_is_no_voice() {
|
||||
let packet = |flow: FlowId, payload: &[u8]| {
|
||||
let mut rtp = BytesMut::new();
|
||||
RtpHeader::new(PT_OPUS, 1, 0).write(flow, &mut rtp).unwrap();
|
||||
rtp.extend_from_slice(payload);
|
||||
MediaPacket { flow, rtp: rtp.freeze() }
|
||||
};
|
||||
assert!(Incoming::parse(&packet(FlowId::new(9, 3), &OPUS_20_MS)).unwrap().whisper);
|
||||
assert!(!Incoming::parse(&packet(FlowId::new(9, 7), &OPUS_20_MS)).unwrap().whisper);
|
||||
let stereo = [OPUS_20_MS[0] | 0x04, 1, 2];
|
||||
assert_eq!(
|
||||
Incoming::parse(&packet(FlowId::new(9, 0), &stereo)).unwrap().codec,
|
||||
VoiceCodec::Music
|
||||
);
|
||||
let end = Incoming::parse(&packet(FlowId::new(9, 0), &[])).unwrap();
|
||||
assert!(end.payload.is_empty() && end.voice(8).is_end());
|
||||
// Feedback and probes are no voice.
|
||||
assert!(
|
||||
Incoming::parse(&MediaPacket { flow: FlowId::FEEDBACK, rtp: Default::default() })
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
Incoming::parse(&MediaPacket { flow: FlowId::PROBE, rtp: Default::default() })
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
Incoming::parse(&MediaPacket { flow: FlowId::new(9, 0), rtp: vec![1, 2].into() })
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_talker_starts_with_a_packet_and_stops_400_ms_after_its_last() {
|
||||
let mut talk = TalkTracker::default();
|
||||
let t0 = Instant::now();
|
||||
assert!(talk.heard(8, t0));
|
||||
assert!(!talk.heard(8, t0 + Duration::from_millis(100)), "already talking");
|
||||
assert!(talk.heard(9, t0 + Duration::from_millis(150)));
|
||||
assert!(talk.is_talking(8));
|
||||
// 399 ms after 8's last packet: still talking.
|
||||
assert!(talk.expire(t0 + Duration::from_millis(499)).is_empty());
|
||||
assert_eq!(talk.expire(t0 + Duration::from_millis(500)), [8]);
|
||||
assert!(!talk.is_talking(8) && talk.is_talking(9));
|
||||
assert_eq!(talk.expire(t0 + Duration::from_millis(551)), [9]);
|
||||
// A packet after the silence starts it again.
|
||||
assert!(talk.heard(8, t0 + Duration::from_secs(2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_that_says_someone_talks_is_believed_until_it_says_otherwise() {
|
||||
let mut talk = TalkTracker::default();
|
||||
let t0 = Instant::now();
|
||||
// A talker whose voice is no media: on, and no silence ends it.
|
||||
assert!(talk.hint(8, true));
|
||||
assert!(!talk.hint(8, true), "already talking");
|
||||
assert!(talk.is_talking(8));
|
||||
assert!(talk.expire(t0 + Duration::from_secs(60)).is_empty());
|
||||
assert!(talk.hint(8, false));
|
||||
assert!(!talk.is_talking(8));
|
||||
// A talker with media that the host also names: the media ends it, when
|
||||
// the host has said it is over (in either order).
|
||||
assert!(talk.heard(9, t0));
|
||||
assert!(!talk.hint(9, true), "heard already");
|
||||
assert!(talk.expire(t0 + Duration::from_millis(500)).is_empty(), "the host still says so");
|
||||
assert!(talk.is_talking(9));
|
||||
assert!(talk.hint(9, false));
|
||||
assert!(!talk.is_talking(9));
|
||||
assert!(talk.heard(10, t0));
|
||||
assert!(!talk.hint(10, false), "the media goes on");
|
||||
assert_eq!(talk.expire(t0 + Duration::from_millis(500)), [10]);
|
||||
// A hint about somebody who is gone is forgotten.
|
||||
assert!(talk.hint(11, true));
|
||||
talk.retain_hints(|client| client != 11);
|
||||
assert!(!talk.is_talking(11));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
//! The engine's seam to the server its voice source talks to.
|
||||
//!
|
||||
//! 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. The engine holds
|
||||
//! it as a `voelin_proto::link::Session`, the backend-neutral interface of the
|
||||
//! protocol repository, and knows nothing else of the server software behind
|
||||
//! it: which backend makes the `Session` is the scheme of the address, and
|
||||
//! [`Backends`] is the registry of connectors by scheme
|
||||
//! ([`Backends::default`] has the TeamSpeak one,
|
||||
//! [`crate::ts::TsConnector`]; a Voelin host's QUIC connector will be
|
||||
//! another). [`VoiceOptions`] says what to connect to and as whom.
|
||||
//!
|
||||
//! Inside the crate `session.rs` merges and routes, and an adapter below it
|
||||
//! turns what it asks into `Session` calls and what the `Session` pushes into
|
||||
//! what it hears (`link/session_link.rs`, with `project.rs` and `media.rs`);
|
||||
//! `docs/session-seam.md` describes the mapping row by row.
|
||||
|
||||
mod backends;
|
||||
mod connect;
|
||||
#[cfg(test)]
|
||||
mod fake_link_tests;
|
||||
#[cfg(test)]
|
||||
mod fake_tests;
|
||||
pub(crate) mod media;
|
||||
pub(crate) mod project;
|
||||
mod session_link;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub use backends::Backends;
|
||||
pub(crate) use backends::{
|
||||
LocalConnected, LocalConnector, LocalCtx, StreamEvent, StreamPort, without_query,
|
||||
};
|
||||
pub(crate) use connect::{VERSION_PARAM, connect_params};
|
||||
pub(crate) use session_link::SessionLink;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tokio::sync::{broadcast, oneshot};
|
||||
use voelin_audio::{EncodedVoice, VoicePacket};
|
||||
use voelin_identity::IdentityBlob;
|
||||
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};
|
||||
|
||||
/// What a voice connection needs to know: the server, who to be, where to
|
||||
/// join ([`Command::ConnectVoice`](crate::Command::ConnectVoice)).
|
||||
///
|
||||
/// Nothing in it belongs to one kind of server: what a connector needs of it
|
||||
/// that is its own (a TeamSpeak identity, the client version to claim) is in
|
||||
/// the `identity` blob and the `client_version` spec, which the connector of
|
||||
/// the address reads.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct VoiceOptions {
|
||||
/// The server: `host[:port]` of a TeamSpeak bookmark, or an address with a
|
||||
/// scheme (`ts3server://`, `teamspeak://`, a Voelin host's `voelin://`)
|
||||
/// that picks the connector ([`Backends`]).
|
||||
pub address: String,
|
||||
/// The name shown on the server: `Hello.nickname` to a Voelin host, the
|
||||
/// client name on a TeamSpeak server (which may refuse or change it). When
|
||||
/// it is empty, the `nickname` parameter of an `address` that is a
|
||||
/// TeamSpeak link applies.
|
||||
pub nickname: String,
|
||||
/// The identity to connect with: a TeamSpeak identity
|
||||
/// ([`crate::ts::identity::to_blob`]) for a TeamSpeak server, a Voelin key
|
||||
/// for a Voelin host. None lets the connector make one up (a TeamSpeak
|
||||
/// connection generates an identity, which a server then knows as a new
|
||||
/// client).
|
||||
pub identity: Option<IdentityBlob>,
|
||||
/// The client version a TeamSpeak server is shown, as a spec for
|
||||
/// [`crate::ts::versions::resolve`] (`default`, `generic`, an index, or
|
||||
/// `<platform>@<version>`); `None` is the native platform's. A spec that is
|
||||
/// none ends the connect with the reason. Other backends ignore it.
|
||||
pub client_version: Option<String>,
|
||||
/// The password of the server (`Hello.password`), for one that has a
|
||||
/// password. When it is `None` or empty, the `password` parameter of an
|
||||
/// `address` that is a TeamSpeak link applies. Not the password of
|
||||
/// `channel` (that is `channel_password`).
|
||||
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 VoiceOptions {
|
||||
/// Options for `address` and `nickname`; everything else is left to the
|
||||
/// connector.
|
||||
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(crate) 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,
|
||||
}
|
||||
|
||||
impl LinkCtx {
|
||||
/// The session this connection belongs to.
|
||||
pub(crate) fn session(&self) -> SessionId {
|
||||
self.session
|
||||
}
|
||||
|
||||
/// Tell the engine's event bus something (a request's answer, a
|
||||
/// transfer's progress).
|
||||
pub(crate) 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(crate) struct Remote {
|
||||
pub channel: ChannelId,
|
||||
pub password: Option<String>,
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// A boxed stream of bytes to read: the body of a file the server sends.
|
||||
pub(crate) type BoxRead = Pin<Box<dyn AsyncRead + Send>>;
|
||||
|
||||
/// A connection that can be read and written: a file transfer connection.
|
||||
pub(crate) trait Duplex: AsyncRead + AsyncWrite + Send {}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite + Send> Duplex for T {}
|
||||
|
||||
/// A boxed [`Duplex`].
|
||||
pub(crate) type BoxDuplex = Pin<Box<dyn Duplex>>;
|
||||
|
||||
/// What the session asks of a connection.
|
||||
pub(crate) 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),
|
||||
/// Open a file of the server for reading, from `offset`: the transfer
|
||||
/// connection itself, and the file's size in all, once the server has
|
||||
/// agreed (the text of the failure otherwise). The engine copies the
|
||||
/// bytes, reports the progress and cancels by dropping the connection, so
|
||||
/// this does not use [`LinkCmd::Download`]'s sink and report.
|
||||
OpenRead {
|
||||
file: Remote,
|
||||
offset: u64,
|
||||
reply: oneshot::Sender<Result<(u64, BoxRead), String>>,
|
||||
},
|
||||
/// Open a file of the server for writing: the transfer connection and the
|
||||
/// position the server wants the bytes from (the size it already has, if
|
||||
/// `resume`). The engine writes the bytes and ends the connection.
|
||||
OpenWrite {
|
||||
file: Remote,
|
||||
/// The file's size in all.
|
||||
size: u64,
|
||||
overwrite: bool,
|
||||
resume: bool,
|
||||
reply: oneshot::Sender<Result<(u64, BoxDuplex), String>>,
|
||||
},
|
||||
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(crate) 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,
|
||||
/// Our client id when the link connected. TeamSpeak's own reconnect gives
|
||||
/// a new one, which is not announced; the engine follows it in the
|
||||
/// snapshots by our unique id.
|
||||
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>),
|
||||
/// The channel we are in, after every [`LinkEvent::Presence`]. The engine
|
||||
/// derives it itself, from our own voice state in the snapshots of the
|
||||
/// `Session` it talks to, and so follows us when TeamSpeak's reconnect makes
|
||||
/// us another client. What an in-process link such as `TsLink` says here only
|
||||
/// tells the TeamSpeak `Session` made of it that a move has arrived.
|
||||
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). The engine derives
|
||||
/// it from the media of its `Session` (protocol section 6.4). What an
|
||||
/// in-process link such as `TsLink` says here reaches the engine as a
|
||||
/// speaking hint next to the media: that is what shows the talkers whose
|
||||
/// packets the link does not forward as Opus (Speex, CELT).
|
||||
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
|
||||
/// ([`VoiceOptions::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>),
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
//! The engine's view of a session's replica, in the client's older model
|
||||
//! (`docs/session-seam.md` section 5.3).
|
||||
//!
|
||||
//! The UI and `session.rs` still speak `Presence`, `ChannelInfo`,
|
||||
//! `ClientInfo`, `ServerDetails` and `ChatMessage`. [`presence`] and
|
||||
//! [`chat_message`] project the replica into them with
|
||||
//! `voelin_model::replica::convert`, and fix up where that says less than the
|
||||
//! older model does (F1 to F10 of the design). The fix-ups apply the
|
||||
//! TeamSpeak gateway's id rules of protocol section 11.1, so the UI keeps the
|
||||
//! ids it has; they go when the UI reads the replica.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use voelin_model::replica::{Replica, convert};
|
||||
use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails};
|
||||
use voelin_proto::link::Features;
|
||||
use voelin_proto::v1::{self, ChannelKind, MessageFlag, RoleScope};
|
||||
|
||||
use super::media::TalkTracker;
|
||||
use crate::ts::ts_session::entities::user_uid;
|
||||
use crate::ts::ts_session::ids::{self, FOREIGN_SYSTEM};
|
||||
|
||||
/// What the projection needs to know besides the replica.
|
||||
pub(crate) struct View<'a> {
|
||||
pub(crate) replica: &'a Replica,
|
||||
/// The server of the session.
|
||||
pub(crate) server: u64,
|
||||
/// The backend is TeamSpeak (`Welcome.host.backend.product`): its id rules
|
||||
/// (channel groups) are undone.
|
||||
pub(crate) teamspeak: bool,
|
||||
/// The version the host said (`Welcome.host.backend.version`).
|
||||
pub(crate) version: &'a str,
|
||||
pub(crate) features: &'a Features,
|
||||
/// Whether the connection has streams (a port, not just the feature).
|
||||
pub(crate) streams: bool,
|
||||
pub(crate) talking: &'a TalkTracker,
|
||||
}
|
||||
|
||||
/// What a `Foreign` of TeamSpeak holds under `key`.
|
||||
fn foreign_value(
|
||||
foreign: Option<&v1::Foreign>,
|
||||
kind: &str,
|
||||
key: &str,
|
||||
) -> Option<serde_json::Value> {
|
||||
let foreign = foreign.filter(|f| f.system == FOREIGN_SYSTEM && f.kind == kind)?;
|
||||
serde_json::from_slice::<serde_json::Value>(&foreign.json).ok()?.get(key).cloned()
|
||||
}
|
||||
|
||||
/// The server's unique id as the client keys its history and aliases by it:
|
||||
/// the host's without the `ts:` of protocol section 11.2 (F3).
|
||||
pub(crate) fn server_key(uid: &str) -> String {
|
||||
uid.strip_prefix("ts:").unwrap_or(uid).to_owned()
|
||||
}
|
||||
|
||||
/// The client's older model of the server (what `LinkEvent::Presence` holds).
|
||||
pub(crate) fn presence(view: &View<'_>) -> Presence {
|
||||
let replica = view.replica;
|
||||
let server = view.server;
|
||||
// F1: only what the older model calls channels.
|
||||
let channels: Vec<&v1::Channel> = replica
|
||||
.channels(server)
|
||||
.filter(|channel| {
|
||||
!matches!(
|
||||
ChannelKind::try_from(channel.kind),
|
||||
Ok(ChannelKind::ServerChat
|
||||
| ChannelKind::Dm
|
||||
| ChannelKind::GroupDm
|
||||
| ChannelKind::Thread)
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let by_id: BTreeMap<u64, &v1::Channel> = channels.iter().map(|c| (c.id, *c)).collect();
|
||||
let channel_infos = convert::channel_infos(&channels)
|
||||
.into_iter()
|
||||
.map(|mut info| {
|
||||
// F7: a limit of 0 is a limit, not "unlimited".
|
||||
let zero = by_id
|
||||
.get(&info.id)
|
||||
.and_then(|c| foreign_value(c.foreign.as_ref(), "channel", "max_clients"));
|
||||
if zero.and_then(|v| v.as_i64()) == Some(0) {
|
||||
info.max_clients = Some(0);
|
||||
}
|
||||
(info.id, info)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let clients = replica
|
||||
.voice_states(server)
|
||||
.filter_map(|voice| {
|
||||
let user = replica.user(voice.user_id);
|
||||
let member = replica.member(server, voice.user_id);
|
||||
let mut client =
|
||||
convert::client_info(voice, user, member, replica.presence_of(voice.user_id))?;
|
||||
// F10: a unique id that is no base64 rides in `Foreign`.
|
||||
client.uid = user.and_then(user_uid);
|
||||
// F2: the client's channel group is TeamSpeak's own number.
|
||||
if view.teamspeak {
|
||||
client.channel_group = client.channel_group.map(ids::channel_group);
|
||||
}
|
||||
// F6: the client's icon.
|
||||
client.icon = foreign_value(member.and_then(|m| m.foreign.as_ref()), "client", "icon")
|
||||
.and_then(|v| v.as_u64())
|
||||
.and_then(|v| u32::try_from(v).ok())
|
||||
.unwrap_or(0);
|
||||
// F8: who is talking comes from the media.
|
||||
client.talking = view.features.has("voice").then(|| view.talking.is_talking(client.id));
|
||||
// F9: the stream flag only where there are streams.
|
||||
if !view.streams {
|
||||
client.streaming = None;
|
||||
}
|
||||
Some((client.id, client))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut server_groups: BTreeMap<u64, GroupInfo> = BTreeMap::new();
|
||||
let mut channel_groups: BTreeMap<u64, GroupInfo> = BTreeMap::new();
|
||||
for role in replica.roles(server) {
|
||||
let mut info = convert::group_info(role);
|
||||
if role.scope == RoleScope::Channel as i32 {
|
||||
if view.teamspeak {
|
||||
info.id = ids::channel_group(info.id);
|
||||
}
|
||||
channel_groups.insert(info.id, info);
|
||||
} else {
|
||||
server_groups.insert(info.id, info);
|
||||
}
|
||||
}
|
||||
|
||||
let details = replica.server(server).map(|stub| server_details(view, stub)).unwrap_or_default();
|
||||
Presence {
|
||||
server_name: details.name.clone(),
|
||||
channels: channel_infos,
|
||||
clients,
|
||||
server: details,
|
||||
server_groups,
|
||||
channel_groups,
|
||||
}
|
||||
}
|
||||
|
||||
/// `convert::server_details` with F2 to F5.
|
||||
fn server_details(view: &View<'_>, server: &v1::Server) -> ServerDetails {
|
||||
let mut details = convert::server_details(server);
|
||||
// F3: the unique id as the client keys it.
|
||||
details.uid = details.uid.as_deref().map(server_key);
|
||||
let foreign = server.foreign.as_ref();
|
||||
// F4: the version the server sent, else the one the host reports.
|
||||
details.version = foreign_value(foreign, "server", "version")
|
||||
.and_then(|v| v.as_str().map(str::to_owned))
|
||||
.filter(|v| !v.is_empty())
|
||||
.unwrap_or_else(|| view.version.to_owned());
|
||||
// F5: the server's platform.
|
||||
details.platform = foreign_value(foreign, "server", "platform")
|
||||
.and_then(|v| v.as_str().map(str::to_owned))
|
||||
.unwrap_or_default();
|
||||
// F2: the default channel group is TeamSpeak's own number.
|
||||
if view.teamspeak {
|
||||
details.default_channel_group = details.default_channel_group.map(ids::channel_group);
|
||||
}
|
||||
details
|
||||
}
|
||||
|
||||
/// Where the older model files the messages of a channel (the replica's
|
||||
/// `chat_target`, with the unique id of F10).
|
||||
fn chat_target(replica: &Replica, channel: u64) -> ChatTarget {
|
||||
let Some(info) = replica.channel(channel) else { return ChatTarget::Channel(channel) };
|
||||
match ChannelKind::try_from(info.kind) {
|
||||
Ok(ChannelKind::ServerChat) => ChatTarget::Server,
|
||||
Ok(ChannelKind::Dm | ChannelKind::GroupDm) => {
|
||||
let own = replica.own_user();
|
||||
info.recipients
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|id| *id != own)
|
||||
.and_then(|id| replica.user(id))
|
||||
.and_then(user_uid)
|
||||
.map_or(ChatTarget::Channel(channel), ChatTarget::Private)
|
||||
}
|
||||
_ => ChatTarget::Channel(channel),
|
||||
}
|
||||
}
|
||||
|
||||
/// A message of the replica as the older model has it.
|
||||
pub(crate) fn chat_message(replica: &Replica, channel: u64, id: u64) -> Option<ChatMessage> {
|
||||
let message = replica.message(channel, id)?;
|
||||
let author = replica.user(message.author_id);
|
||||
let name = Some(message.author_name.as_str())
|
||||
.filter(|name| !name.is_empty())
|
||||
.or_else(|| author.map(|u| u.name.as_str()).filter(|name| !name.is_empty()))
|
||||
.unwrap_or_default();
|
||||
Some(ChatMessage {
|
||||
target: chat_target(replica, channel),
|
||||
author_name: name.to_owned(),
|
||||
author_uid: author.and_then(user_uid),
|
||||
author_id: (message.author_participant != 0)
|
||||
.then(|| u16::try_from(message.author_participant).ok())
|
||||
.flatten(),
|
||||
text: message.text.clone(),
|
||||
ts_ms: message.ts_ms,
|
||||
via_relay: message.flags & MessageFlag::Relayed as u32 != 0,
|
||||
blocked: false,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_ts_prefix_of_a_server_uid_goes() {
|
||||
assert_eq!(server_key("ts:abc="), "abc=");
|
||||
assert_eq!(server_key("abc="), "abc=");
|
||||
assert_eq!(server_key(""), "");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
@@ -2686,7 +2680,7 @@ pub struct DecodeStats {
|
||||
pub bytes: u64,
|
||||
/// Pictures decoded per second and video received in bit/s, over the
|
||||
/// time since the previous [`VideoPipeline::stats`] (at least
|
||||
/// [`RATE_WINDOW`]; the watch screen asks once a second).
|
||||
/// `RATE_WINDOW`; the watch screen asks once a second).
|
||||
pub fps: u32,
|
||||
pub bitrate: u64,
|
||||
}
|
||||
|
||||
@@ -1,11 +1,94 @@
|
||||
//! The query source: own ServerQuery credentials, in-process observer and relays.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
use voelin_model::{ChatMessage, ChatTarget, Presence};
|
||||
use voelin_observer::{
|
||||
Observer, ObserverConfig, ObserverEvent, RelayConfig, RelayEvent, RelayPool,
|
||||
};
|
||||
|
||||
/// How a ServerQuery connection talks to the server.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum QueryTransport {
|
||||
/// The raw text protocol (TeamSpeak 3; port 10011).
|
||||
Raw,
|
||||
/// SSH.
|
||||
Ssh,
|
||||
/// The HTTP query (TeamSpeak 6; a WebQuery API key is the secret).
|
||||
Http,
|
||||
}
|
||||
|
||||
/// The user's own ServerQuery credentials for a server
|
||||
/// ([`Command::ObserveQuery`](crate::Command::ObserveQuery)): what the
|
||||
/// engine logs in with to observe a server invisibly and to relay its
|
||||
/// channels' chat. The connection's own tuning (flood protection, timeouts)
|
||||
/// is the engine's.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct QueryLogin {
|
||||
/// The protocol of the query interface at `address`.
|
||||
pub transport: QueryTransport,
|
||||
/// `host:port` of the query interface.
|
||||
pub address: String,
|
||||
/// The login name (raw and SSH; ignored for HTTP).
|
||||
pub user: String,
|
||||
/// The password (raw and SSH) or API key (HTTP, optional for guest access).
|
||||
pub secret: Option<String>,
|
||||
/// Select the virtual server by its voice port...
|
||||
pub server_port: Option<u16>,
|
||||
/// ...or by id (the first server when neither is given).
|
||||
pub server_id: Option<u32>,
|
||||
/// This machine's address is on the server's query allowlist, which the
|
||||
/// server's flood protection skips: the engine then sends its commands
|
||||
/// without the limit it keeps for a server that has not said so (a command
|
||||
/// the server refuses as a flood slows the connection down all the same).
|
||||
/// The application usually cannot know, and says `false`; the development
|
||||
/// servers of the tests allowlist their clients.
|
||||
pub allowlisted: bool,
|
||||
}
|
||||
|
||||
impl fmt::Debug for QueryLogin {
|
||||
// The secret is kept out of logs.
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("QueryLogin")
|
||||
.field("transport", &self.transport)
|
||||
.field("address", &self.address)
|
||||
.field("user", &self.user)
|
||||
.field("secret", &self.secret.as_ref().map(|_| "[secret]"))
|
||||
.field("server_port", &self.server_port)
|
||||
.field("server_id", &self.server_id)
|
||||
.field("allowlisted", &self.allowlisted)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl QueryLogin {
|
||||
/// The connection the observer and the relays open.
|
||||
fn connect(&self) -> voelin_query::Connect {
|
||||
voelin_query::Connect {
|
||||
transport: match self.transport {
|
||||
QueryTransport::Raw => voelin_query::Transport::Raw,
|
||||
QueryTransport::Ssh => voelin_query::Transport::Ssh,
|
||||
QueryTransport::Http => voelin_query::Transport::Http,
|
||||
},
|
||||
addr: self.address.clone(),
|
||||
user: self.user.clone(),
|
||||
secret: self.secret.clone(),
|
||||
server_port: self.server_port,
|
||||
server_id: self.server_id,
|
||||
line: voelin_query::LineOptions {
|
||||
// Off the client-side limit only where the server skips it.
|
||||
rate_limit: if self.allowlisted {
|
||||
None
|
||||
} else {
|
||||
voelin_query::LineOptions::default().rate_limit
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum QueryCmd {
|
||||
OpenChat(ChatTarget),
|
||||
CloseChat(ChatTarget),
|
||||
@@ -21,10 +104,11 @@ pub(crate) enum QueryEvent {
|
||||
}
|
||||
|
||||
pub(crate) async fn run(
|
||||
connect: voelin_query::Connect,
|
||||
login: QueryLogin,
|
||||
mut commands: mpsc::UnboundedReceiver<QueryCmd>,
|
||||
events: mpsc::UnboundedSender<QueryEvent>,
|
||||
) {
|
||||
let connect = login.connect();
|
||||
let observer = Observer::spawn(ObserverConfig::new(connect.clone()));
|
||||
let relays = RelayPool::new(RelayConfig::new(connect));
|
||||
let mut observed = observer.subscribe();
|
||||
@@ -88,3 +172,59 @@ pub(crate) async fn run(
|
||||
relays.close_all().await;
|
||||
let _ = events.send(QueryEvent::Disconnected);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_login_is_the_connection_the_query_crate_opens() {
|
||||
let login = QueryLogin {
|
||||
transport: QueryTransport::Ssh,
|
||||
address: "ts.example.com:10022".into(),
|
||||
user: "serveradmin".into(),
|
||||
secret: Some("hunter2".into()),
|
||||
server_port: Some(9987),
|
||||
server_id: Some(3),
|
||||
allowlisted: false,
|
||||
};
|
||||
let connect = login.connect();
|
||||
assert_eq!(connect.transport, voelin_query::Transport::Ssh);
|
||||
assert_eq!(
|
||||
(connect.addr.as_str(), connect.user.as_str(), connect.secret.as_deref()),
|
||||
("ts.example.com:10022", "serveradmin", Some("hunter2"))
|
||||
);
|
||||
assert_eq!((connect.server_port, connect.server_id), (Some(9987), Some(3)));
|
||||
for (ours, theirs) in [
|
||||
(QueryTransport::Raw, voelin_query::Transport::Raw),
|
||||
(QueryTransport::Http, voelin_query::Transport::Http),
|
||||
] {
|
||||
let connect = QueryLogin { transport: ours, ..login.clone() }.connect();
|
||||
assert_eq!(connect.transport, theirs);
|
||||
}
|
||||
// The line options are the query crate's defaults, as the UI always
|
||||
// gave them, unless the server allowlists the client.
|
||||
let line = voelin_query::LineOptions::default();
|
||||
assert!(line.rate_limit.is_some());
|
||||
assert_eq!(connect.line.rate_limit, line.rate_limit);
|
||||
assert_eq!(connect.line.timeout, line.timeout);
|
||||
let allowlisted = QueryLogin { allowlisted: true, ..login.clone() }.connect();
|
||||
assert_eq!(allowlisted.line.rate_limit, None);
|
||||
assert_eq!(allowlisted.line.timeout, line.timeout);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_secret_stays_out_of_the_debug_text() {
|
||||
let login = QueryLogin {
|
||||
transport: QueryTransport::Raw,
|
||||
address: "h:1".into(),
|
||||
user: "u".into(),
|
||||
secret: Some("hunter2".into()),
|
||||
server_port: None,
|
||||
server_id: None,
|
||||
allowlisted: false,
|
||||
};
|
||||
let text = format!("{login:?}");
|
||||
assert!(!text.contains("hunter2") && text.contains("[secret]"), "{text}");
|
||||
}
|
||||
}
|
||||
+146
-185
@@ -16,11 +16,9 @@ use tokio::time::Instant;
|
||||
|
||||
use tokio::sync::{broadcast, mpsc, watch};
|
||||
use tracing::{debug, info, warn};
|
||||
use tsclientlib::ClientId;
|
||||
use voelin_audio::AudioSettings;
|
||||
use voelin_audio::{AudioSettings, EncodedVoice, TalkerId};
|
||||
use voelin_gateway_proto::{ErrorCode, HistoryEntry, StreamEntry, StreamSpec, feature};
|
||||
use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails, badges};
|
||||
use voelin_stream::ClientState;
|
||||
|
||||
use crate::audio::{self, AudioEvent, AudioHandle, AudioIn};
|
||||
use crate::cache::{self, Fetch, FetchError, RetryHint, SharedCache, Waiter};
|
||||
@@ -31,6 +29,7 @@ use crate::gateway::{
|
||||
Push, ReactionPush,
|
||||
};
|
||||
use crate::history::{self, ChatCtx, HistoryMessage, MessageSource, SharedHistory};
|
||||
use crate::link::{LinkCmd, LinkCtx, LinkEvent, Remote, SessionLink};
|
||||
use crate::query::{self, QueryCmd, QueryEvent};
|
||||
use crate::route::{ChatRoute, Dedup, route_chat};
|
||||
use crate::settings::{
|
||||
@@ -38,10 +37,9 @@ use crate::settings::{
|
||||
PRIVACY_PRIVATE_MESSAGES, SharedSettings,
|
||||
};
|
||||
use crate::stream::{
|
||||
LayerSpec, OwnStreamEvent, PeerConfig, SrtpProfile, StreamFrame, StreamHandle, StreamInfo,
|
||||
StreamInput, StreamKind, kind_name, parse_kind,
|
||||
LayerSpec, OwnStreamEvent, StreamCmd, StreamFrame, StreamInfo, StreamKind, kind_name,
|
||||
parse_kind, parse_srtp_profiles,
|
||||
};
|
||||
use crate::voice::{self, Remote, VoiceCmd, VoiceEvent, VoiceLink};
|
||||
use crate::web;
|
||||
use crate::{Command, Event, ObserveState, SessionId, SessionState, Shared, Source, VoiceState};
|
||||
|
||||
@@ -86,14 +84,10 @@ impl SessionHandle {
|
||||
frames: broadcast::Sender<StreamFrame>,
|
||||
audio_settings: AudioSettings,
|
||||
shared: Shared,
|
||||
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
link: Arc<SessionLink>,
|
||||
) -> Self {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
tokio::spawn(
|
||||
Session::new(id, events, frames, audio_settings, shared, myts_identity, myts_data)
|
||||
.run(rx),
|
||||
);
|
||||
tokio::spawn(Session::new(id, events, frames, audio_settings, shared, link).run(rx));
|
||||
Self { tx }
|
||||
}
|
||||
|
||||
@@ -105,13 +99,11 @@ impl SessionHandle {
|
||||
/// Events from sources, tagged with the generation of the source so events
|
||||
/// of a replaced source are ignored.
|
||||
enum SourceEvent {
|
||||
Voice(u64, VoiceEvent),
|
||||
Voice(u64, LinkEvent),
|
||||
Gateway(u64, GatewayEvent),
|
||||
Query(u64, QueryEvent),
|
||||
AudioOut(u64, tsproto_packets::packets::OutPacket),
|
||||
AudioOut(u64, EncodedVoice),
|
||||
Audio(u64, AudioEvent),
|
||||
/// Our own stream (from the stream task of that voice connection).
|
||||
OwnStream(u64, OwnStreamEvent),
|
||||
/// The gateway's stream directory after subscribing.
|
||||
Directory(u64, Result<Vec<StreamEntry>, ClientError>),
|
||||
/// The server's unique id the database remembers for an address.
|
||||
@@ -290,13 +282,13 @@ struct OwnStream {
|
||||
}
|
||||
|
||||
struct Session {
|
||||
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
/// Starts the voice connections.
|
||||
link: Arc<SessionLink>,
|
||||
id: SessionId,
|
||||
events: broadcast::Sender<Event>,
|
||||
state: SessionState,
|
||||
generation: u64,
|
||||
voice: Option<(u64, mpsc::UnboundedSender<VoiceCmd>)>,
|
||||
voice: Option<(u64, mpsc::UnboundedSender<LinkCmd>)>,
|
||||
voice_address: String,
|
||||
voice_presence: Option<Presence>,
|
||||
nickname: String,
|
||||
@@ -318,18 +310,15 @@ struct Session {
|
||||
/// Other names of this server (`voice:<address>`, `gateway:<url>`),
|
||||
/// remembered with its unique id once a source tells it.
|
||||
aliases: Vec<String>,
|
||||
/// Streams of the voice connection (TeamSpeak 6 only).
|
||||
streams: Option<StreamHandle>,
|
||||
stream_peer: PeerConfig,
|
||||
/// The voice connection carries streams (its capabilities say so; the
|
||||
/// connection runs their task, `LinkCmd::Stream` reaches it).
|
||||
streams: bool,
|
||||
/// Simulcast layers of our stream, for the stream task.
|
||||
stream_layers: Vec<LayerSpec>,
|
||||
/// The SRTP profile setting (`Command::SetSrtpProfiles`), over the voice
|
||||
/// options' `stream_peer`.
|
||||
srtp_profiles: Option<Vec<SrtpProfile>>,
|
||||
srtp_profiles: Option<Vec<String>>,
|
||||
frames: broadcast::Sender<StreamFrame>,
|
||||
/// Channel and `client_is_streaming` of the voice presence, as last told
|
||||
/// to the streams.
|
||||
streaming_clients: BTreeMap<u16, ClientState>,
|
||||
/// The gateway's stream directory, by id.
|
||||
directory: BTreeMap<String, StreamEntry>,
|
||||
own_stream: Option<OwnStream>,
|
||||
@@ -386,15 +375,13 @@ impl Session {
|
||||
frames: broadcast::Sender<StreamFrame>,
|
||||
audio_settings: AudioSettings,
|
||||
shared: Shared,
|
||||
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
link: Arc<SessionLink>,
|
||||
) -> Self {
|
||||
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
|
||||
let Shared { settings, history, cache, contacts } = shared;
|
||||
let contacts_rx = Some(contacts.watch());
|
||||
Self {
|
||||
myts_identity,
|
||||
myts_data,
|
||||
link,
|
||||
cache,
|
||||
contacts,
|
||||
contacts_rx,
|
||||
@@ -434,12 +421,10 @@ impl Session {
|
||||
history,
|
||||
own_uid: None,
|
||||
aliases: Vec::new(),
|
||||
streams: None,
|
||||
stream_peer: PeerConfig::default(),
|
||||
streams: false,
|
||||
stream_layers: Vec::new(),
|
||||
srtp_profiles: None,
|
||||
frames,
|
||||
streaming_clients: BTreeMap::new(),
|
||||
directory: BTreeMap::new(),
|
||||
own_stream: None,
|
||||
open_chats: HashSet::new(),
|
||||
@@ -509,17 +494,19 @@ impl Session {
|
||||
fn command(&mut self, cmd: Command) {
|
||||
match cmd {
|
||||
Command::ConnectVoice { options, .. } => {
|
||||
if let Some((_, tx)) = self.voice.take() {
|
||||
let _ = tx.send(VoiceCmd::Disconnect);
|
||||
}
|
||||
// The streams end first: their shutdown goes through the
|
||||
// connection that is replaced.
|
||||
self.stop_streams("voice reconnecting");
|
||||
if let Some((_, tx)) = self.voice.take() {
|
||||
let _ = tx.send(LinkCmd::Disconnect);
|
||||
}
|
||||
let mut options = *options;
|
||||
let generation = self.next_generation();
|
||||
self.voice_address = options.address.clone();
|
||||
self.details = None;
|
||||
self.nickname = options.nickname.clone();
|
||||
self.stream_peer = options.stream_peer.clone();
|
||||
if let Some(profiles) = &self.srtp_profiles {
|
||||
self.stream_peer.srtp_profiles = profiles.clone();
|
||||
options.stream_peer.srtp_profiles = parse_srtp_profiles(profiles);
|
||||
}
|
||||
self.known_server(format!("voice:{}", options.address));
|
||||
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
|
||||
@@ -532,14 +519,13 @@ impl Session {
|
||||
self.forward(out_rx, move |p| SourceEvent::AudioOut(generation, p));
|
||||
self.forward(audio_rx, move |e| SourceEvent::Audio(generation, e));
|
||||
}
|
||||
let link = VoiceLink {
|
||||
myts_identity: self.myts_identity.clone(),
|
||||
myts_data: self.myts_data.clone(),
|
||||
let ctx = LinkCtx {
|
||||
session: self.id,
|
||||
events: self.events.clone(),
|
||||
frames: self.frames.clone(),
|
||||
settings: self.settings.clone(),
|
||||
};
|
||||
tokio::spawn(voice::run(*options, link, cmd_rx, ev_tx));
|
||||
self.link.spawn(options, ctx, cmd_rx, ev_tx);
|
||||
self.forward(ev_rx, move |e| SourceEvent::Voice(generation, e));
|
||||
self.forget_images();
|
||||
self.voice = Some((generation, cmd_tx));
|
||||
@@ -548,7 +534,7 @@ impl Session {
|
||||
}
|
||||
Command::DisconnectVoice { .. } => {
|
||||
if let Some((_, tx)) = &self.voice {
|
||||
let _ = tx.send(VoiceCmd::Disconnect);
|
||||
let _ = tx.send(LinkCmd::Disconnect);
|
||||
}
|
||||
}
|
||||
Command::ObserveGateway { urls, identity, .. } => {
|
||||
@@ -590,7 +576,10 @@ impl Session {
|
||||
// source, the history is kept under the query address.
|
||||
if self.state.server_uid.is_none() {
|
||||
let port = connect.server_port.map(|p| format!("/{p}")).unwrap_or_default();
|
||||
self.learn_server_uid(format!("query:{}{port}", connect.addr), Source::Query);
|
||||
self.learn_server_uid(
|
||||
format!("query:{}{port}", connect.address),
|
||||
Source::Query,
|
||||
);
|
||||
self.open_histories();
|
||||
}
|
||||
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
|
||||
@@ -626,7 +615,7 @@ impl Session {
|
||||
self.store_own(&target, &text, &route);
|
||||
}
|
||||
match route {
|
||||
ChatRoute::Voice => self.voice_cmd(VoiceCmd::SendChat(target, text)),
|
||||
ChatRoute::Voice => self.voice_cmd(LinkCmd::SendChat(target, text)),
|
||||
ChatRoute::Gateway => {
|
||||
if let Some((_, tx)) = &self.gateway {
|
||||
let _ = tx.send(GatewayCmd::SendChat(target, text));
|
||||
@@ -657,11 +646,11 @@ impl Session {
|
||||
},
|
||||
Command::Gateway { request, .. } => self.gateway_request(request),
|
||||
Command::MoveToChannel { channel, password, .. } => {
|
||||
self.voice_cmd(VoiceCmd::Move(channel, password));
|
||||
self.voice_cmd(LinkCmd::Move(channel, password));
|
||||
}
|
||||
Command::SetInputMuted { muted, .. } => {
|
||||
self.state.input_muted = muted;
|
||||
self.voice_cmd(VoiceCmd::SetInputMuted(muted));
|
||||
self.voice_cmd(LinkCmd::SetInputMuted(muted));
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::InputMuted(muted));
|
||||
}
|
||||
@@ -669,7 +658,7 @@ impl Session {
|
||||
}
|
||||
Command::SetOutputMuted { muted, .. } => {
|
||||
self.state.output_muted = muted;
|
||||
self.voice_cmd(VoiceCmd::SetOutputMuted(muted));
|
||||
self.voice_cmd(LinkCmd::SetOutputMuted(muted));
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::OutputMuted(muted));
|
||||
}
|
||||
@@ -692,12 +681,12 @@ impl Session {
|
||||
// again after connecting.
|
||||
Command::SetClientVolume { client, volume, .. } => {
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::ClientVolume { client: ClientId(client), volume });
|
||||
a.send(AudioIn::ClientVolume { client: TalkerId(client), volume });
|
||||
}
|
||||
}
|
||||
Command::SetClientMuted { client, muted, .. } => {
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::ClientMuted { client: ClientId(client), muted });
|
||||
a.send(AudioIn::ClientMuted { client: TalkerId(client), muted });
|
||||
}
|
||||
}
|
||||
Command::SetStreamVolume { stream_id, volume, .. } => {
|
||||
@@ -706,50 +695,43 @@ impl Session {
|
||||
}
|
||||
}
|
||||
Command::StartStream { setup, auto_accept, .. } => {
|
||||
self.stream_input(StreamInput::Start { setup, auto_accept });
|
||||
self.stream_input(StreamCmd::Start { setup, auto_accept });
|
||||
}
|
||||
Command::StopStream { .. } => self.stream_input(StreamInput::Stop),
|
||||
Command::StopStream { .. } => self.stream_input(StreamCmd::Stop),
|
||||
Command::AcceptViewer { viewer, accept, .. } => {
|
||||
self.stream_input(StreamInput::Respond { viewer, accept });
|
||||
self.stream_input(StreamCmd::Respond { viewer, accept });
|
||||
}
|
||||
Command::KickViewer { viewer, .. } => self.stream_input(StreamInput::Kick { viewer }),
|
||||
Command::KickViewer { viewer, .. } => self.stream_input(StreamCmd::Kick { viewer }),
|
||||
Command::SendStreamFrame { frame, .. } => {
|
||||
// Frames without a stream are dropped silently.
|
||||
if let Some(s) = &self.streams {
|
||||
s.send(StreamInput::Frame(frame));
|
||||
}
|
||||
self.stream_cmd(StreamCmd::Frame(frame));
|
||||
}
|
||||
Command::WatchStream { stream_id, .. } => {
|
||||
self.stream_input(StreamInput::Watch { stream_id });
|
||||
self.stream_input(StreamCmd::Watch { stream_id });
|
||||
}
|
||||
Command::LeaveStream { stream_id, .. } => {
|
||||
self.stream_input(StreamInput::Leave { stream_id });
|
||||
self.stream_input(StreamCmd::Leave { stream_id });
|
||||
}
|
||||
Command::RequestStreamKeyframe { stream_id, .. } => {
|
||||
self.stream_input(StreamInput::RequestKeyframe { stream_id });
|
||||
self.stream_input(StreamCmd::RequestKeyframe { stream_id });
|
||||
}
|
||||
Command::StreamUndecodable { stream_id, .. } => {
|
||||
self.stream_input(StreamInput::Undecodable { stream_id });
|
||||
self.stream_input(StreamCmd::Undecodable { stream_id });
|
||||
}
|
||||
Command::SetWatchLayer { stream_id, layer, .. } => {
|
||||
self.stream_input(StreamInput::WatchLayer { stream_id, layer });
|
||||
self.stream_input(StreamCmd::WatchLayer { stream_id, layer });
|
||||
}
|
||||
// Kept for streams started later, also without a connection.
|
||||
Command::SetStreamLayers { layers, .. } => {
|
||||
self.stream_layers = layers.clone();
|
||||
if let Some(s) = &self.streams {
|
||||
s.send(StreamInput::Layers(layers));
|
||||
}
|
||||
self.stream_cmd(StreamCmd::Layers(layers));
|
||||
}
|
||||
Command::SetSrtpProfiles(profiles) => {
|
||||
self.stream_peer.srtp_profiles = profiles.clone();
|
||||
self.srtp_profiles = Some(profiles.clone());
|
||||
if let Some(s) = &self.streams {
|
||||
s.send(StreamInput::SrtpProfiles(profiles));
|
||||
}
|
||||
self.stream_cmd(StreamCmd::SrtpProfiles(profiles));
|
||||
}
|
||||
Command::Poke { client, message, .. } => {
|
||||
self.voice_cmd(VoiceCmd::Poke { client, message });
|
||||
self.voice_cmd(LinkCmd::Poke { client, message });
|
||||
}
|
||||
Command::ListFiles { request, channel, password, path, .. } => {
|
||||
if self.voice.is_none() {
|
||||
@@ -759,7 +741,7 @@ impl Session {
|
||||
return;
|
||||
}
|
||||
let dir = Remote { channel, password, path };
|
||||
self.voice_cmd(VoiceCmd::ListFiles { request, dir });
|
||||
self.voice_cmd(LinkCmd::ListFiles { request, dir });
|
||||
}
|
||||
Command::DownloadFile { transfer, channel, password, path, to, .. } => {
|
||||
self.download(transfer, Remote { channel, password, path }, &to);
|
||||
@@ -797,34 +779,27 @@ impl Session {
|
||||
let report = self.transfer_report(transfer);
|
||||
let file = Remote { channel, password, path };
|
||||
let transfer = Some(transfer);
|
||||
self.voice_cmd(VoiceCmd::Upload {
|
||||
transfer,
|
||||
file,
|
||||
from,
|
||||
overwrite,
|
||||
resume,
|
||||
report,
|
||||
});
|
||||
self.voice_cmd(LinkCmd::Upload { transfer, file, from, overwrite, resume, report });
|
||||
}
|
||||
Command::CancelTransfer { transfer, .. } => {
|
||||
self.voice_cmd(VoiceCmd::CancelTransfer(transfer));
|
||||
self.voice_cmd(LinkCmd::CancelTransfer(transfer));
|
||||
}
|
||||
Command::DeleteFiles { request, channel, password, paths, .. } => {
|
||||
let request = Some(request);
|
||||
self.voice_request(
|
||||
request,
|
||||
VoiceCmd::DeleteFiles { request, channel, password, paths },
|
||||
LinkCmd::DeleteFiles { request, channel, password, paths },
|
||||
);
|
||||
}
|
||||
Command::RenameFile { request, channel, password, from, to, to_channel, .. } => {
|
||||
let (to_channel, to_password) = to_channel.unwrap_or((channel, password.clone()));
|
||||
let from = Remote { channel, password, path: from };
|
||||
let to = Remote { channel: to_channel, password: to_password, path: to };
|
||||
self.voice_request(Some(request), VoiceCmd::RenameFile { request, from, to });
|
||||
self.voice_request(Some(request), LinkCmd::RenameFile { request, from, to });
|
||||
}
|
||||
Command::CreateDirectory { request, channel, password, path, .. } => {
|
||||
let dir = Remote { channel, password, path };
|
||||
self.voice_request(Some(request), VoiceCmd::CreateDirectory { request, dir });
|
||||
self.voice_request(Some(request), LinkCmd::CreateDirectory { request, dir });
|
||||
}
|
||||
Command::SetAvatar { request, image, .. } => self.set_avatar(request, image),
|
||||
Command::FetchAvatar { client_uid, .. } => {
|
||||
@@ -856,7 +831,7 @@ impl Session {
|
||||
self.emit(Event::OfflineMessages { session: self.id, request, result });
|
||||
return;
|
||||
}
|
||||
self.voice_cmd(VoiceCmd::OfflineList { request });
|
||||
self.voice_cmd(LinkCmd::OfflineList { request });
|
||||
}
|
||||
Command::GetOfflineMessage { request, id, .. } => {
|
||||
if self.voice.is_none() {
|
||||
@@ -864,22 +839,20 @@ impl Session {
|
||||
self.emit(Event::OfflineMessage { session: self.id, request, result });
|
||||
return;
|
||||
}
|
||||
self.voice_cmd(VoiceCmd::OfflineGet { request, id });
|
||||
self.voice_cmd(LinkCmd::OfflineGet { request, id });
|
||||
}
|
||||
Command::SendOfflineMessage { request, to_uid, subject, text, .. } => {
|
||||
let cmd = VoiceCmd::OfflineAdd { request, to_uid, subject, text };
|
||||
let cmd = LinkCmd::OfflineAdd { request, to_uid, subject, text };
|
||||
self.voice_request(Some(request), cmd);
|
||||
}
|
||||
Command::DeleteOfflineMessage { request, id, .. } => {
|
||||
self.voice_request(Some(request), VoiceCmd::OfflineDelete { request, id });
|
||||
self.voice_request(Some(request), LinkCmd::OfflineDelete { request, id });
|
||||
}
|
||||
Command::SetOfflineMessageRead { request, id, read, .. } => {
|
||||
self.voice_request(Some(request), VoiceCmd::OfflineFlag { request, id, read });
|
||||
self.voice_request(Some(request), LinkCmd::OfflineFlag { request, id, read });
|
||||
}
|
||||
// Engine-wide.
|
||||
Command::SetMytsIdentity(_)
|
||||
| Command::SetMytsData(_)
|
||||
| Command::CloseSession { .. }
|
||||
Command::CloseSession { .. }
|
||||
| Command::TestMicrophone { .. }
|
||||
| Command::SetSetting { .. }
|
||||
| Command::ResetSetting { .. }
|
||||
@@ -894,7 +867,7 @@ impl Session {
|
||||
// Files, avatars, icons
|
||||
|
||||
/// A request to the voice connection; without one it fails at once.
|
||||
fn voice_request(&self, request: Option<RequestId>, cmd: VoiceCmd) {
|
||||
fn voice_request(&self, request: Option<RequestId>, cmd: LinkCmd) {
|
||||
match (&self.voice, request) {
|
||||
(Some(_), _) => self.voice_cmd(cmd),
|
||||
(None, Some(request)) => self.emit(Event::RequestDone {
|
||||
@@ -925,7 +898,7 @@ impl Session {
|
||||
}
|
||||
let report = self.transfer_report(transfer);
|
||||
let sink = Sink::from_target(to);
|
||||
self.voice_cmd(VoiceCmd::Download { transfer: Some(transfer), file, sink, report });
|
||||
self.voice_cmd(LinkCmd::Download { transfer: Some(transfer), file, sink, report });
|
||||
}
|
||||
|
||||
/// Upload our avatar and announce its hash, or remove it.
|
||||
@@ -938,7 +911,7 @@ impl Session {
|
||||
let Some(image) = image else {
|
||||
// The file too (best effort), then no hash.
|
||||
if let Some(path) = self.own_uid.as_deref().and_then(files::avatar_path) {
|
||||
let cmd = VoiceCmd::DeleteFiles {
|
||||
let cmd = LinkCmd::DeleteFiles {
|
||||
request: None,
|
||||
channel: 0,
|
||||
password: None,
|
||||
@@ -947,7 +920,7 @@ impl Session {
|
||||
self.voice_cmd(cmd);
|
||||
}
|
||||
let hash = String::new();
|
||||
self.voice_cmd(VoiceCmd::SetAvatarHash { request: Some(request), hash });
|
||||
self.voice_cmd(LinkCmd::SetAvatarHash { request: Some(request), hash });
|
||||
return;
|
||||
};
|
||||
let (sources, cache, settings) =
|
||||
@@ -983,7 +956,7 @@ impl Session {
|
||||
let _ = sources.send(SourceEvent::AvatarUploaded(generation, request, result));
|
||||
});
|
||||
let file = Remote { channel: 0, password: None, path: "/avatar".into() };
|
||||
let upload = VoiceCmd::Upload {
|
||||
let upload = LinkCmd::Upload {
|
||||
transfer: None,
|
||||
file,
|
||||
from: image,
|
||||
@@ -1403,7 +1376,7 @@ impl Session {
|
||||
let sink = Sink::File { part: temp.clone(), dest: temp, append: false };
|
||||
let file = Remote { channel, password: None, path };
|
||||
let failed = report.clone();
|
||||
if voice.send(VoiceCmd::Download { transfer: None, file, sink, report }).is_err() {
|
||||
if voice.send(LinkCmd::Download { transfer: None, file, sink, report }).is_err() {
|
||||
failed(TransferState::Failed(NO_VOICE.into()));
|
||||
}
|
||||
}
|
||||
@@ -1436,24 +1409,22 @@ impl Session {
|
||||
if let Some(a) = &self.audio {
|
||||
for (client, (volume, muted)) in &wanted {
|
||||
if self.contact_audio.get(client) != Some(&(*volume, *muted)) {
|
||||
a.send(AudioIn::ClientVolume { client: ClientId(*client), volume: *volume });
|
||||
a.send(AudioIn::ClientMuted { client: ClientId(*client), muted: *muted });
|
||||
a.send(AudioIn::ClientVolume { client: TalkerId(*client), volume: *volume });
|
||||
a.send(AudioIn::ClientMuted { client: TalkerId(*client), muted: *muted });
|
||||
}
|
||||
}
|
||||
// No contact setting any more: back to normal.
|
||||
for client in self.contact_audio.keys().filter(|c| !wanted.contains_key(c)) {
|
||||
if p.clients.contains_key(client) {
|
||||
a.send(AudioIn::ClientVolume { client: ClientId(*client), volume: 1.0 });
|
||||
a.send(AudioIn::ClientMuted { client: ClientId(*client), muted: false });
|
||||
a.send(AudioIn::ClientVolume { client: TalkerId(*client), volume: 1.0 });
|
||||
a.send(AudioIn::ClientMuted { client: TalkerId(*client), muted: false });
|
||||
}
|
||||
}
|
||||
self.contact_audio = wanted;
|
||||
}
|
||||
if friends != self.stream_friends {
|
||||
self.stream_friends = friends.clone();
|
||||
if let Some(s) = &self.streams {
|
||||
s.send(StreamInput::Friends(friends));
|
||||
}
|
||||
self.stream_cmd(StreamCmd::Friends(friends));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1464,7 +1435,7 @@ impl Session {
|
||||
let clients = p.clients.values().filter(|c| c.priority_speaker).map(|c| c.id).collect();
|
||||
let wanted = (clients, p.server.priority_speaker_dimm_db);
|
||||
if wanted != self.priority_audio {
|
||||
let clients = wanted.0.iter().map(|c| ClientId(*c)).collect();
|
||||
let clients = wanted.0.iter().map(|c| TalkerId(*c)).collect();
|
||||
a.send(AudioIn::PrioritySpeakers { clients, dimm_db: wanted.1 as f32 });
|
||||
self.priority_audio = wanted;
|
||||
}
|
||||
@@ -1502,26 +1473,36 @@ impl Session {
|
||||
allows(self.settings.current().get(key), uid.map(|u| self.contacts.relation(u)))
|
||||
}
|
||||
|
||||
fn stream_input(&self, input: StreamInput) {
|
||||
match &self.streams {
|
||||
Some(s) => s.send(input),
|
||||
None if self.state.voice == VoiceState::Connected => {
|
||||
self.error("streams need a TeamSpeak 6 server");
|
||||
}
|
||||
None => self.error("not connected with voice"),
|
||||
/// A stream command of the user: an error where the connection has no
|
||||
/// streams.
|
||||
fn stream_input(&self, cmd: StreamCmd) {
|
||||
if self.streams {
|
||||
self.stream_cmd(cmd);
|
||||
} else if self.state.voice == VoiceState::Connected {
|
||||
self.error("streams need a TeamSpeak 6 server");
|
||||
} else {
|
||||
self.error("not connected with voice");
|
||||
}
|
||||
}
|
||||
|
||||
/// A command for the streams of the voice connection; dropped where it
|
||||
/// has none.
|
||||
fn stream_cmd(&self, cmd: StreamCmd) {
|
||||
if let (true, Some((_, tx))) = (self.streams, &self.voice) {
|
||||
let _ = tx.send(LinkCmd::Stream(cmd));
|
||||
}
|
||||
}
|
||||
|
||||
fn stop_streams(&mut self, reason: &str) {
|
||||
if let Some(s) = self.streams.take() {
|
||||
s.send(StreamInput::Shutdown(reason.into()));
|
||||
if self.streams {
|
||||
self.stream_cmd(StreamCmd::Shutdown(reason.into()));
|
||||
self.streams = false;
|
||||
}
|
||||
self.streaming_clients.clear();
|
||||
// The stream task's report comes from a replaced source.
|
||||
self.own_stream_ended();
|
||||
}
|
||||
|
||||
fn voice_cmd(&self, cmd: VoiceCmd) {
|
||||
fn voice_cmd(&self, cmd: LinkCmd) {
|
||||
match &self.voice {
|
||||
Some((_, tx)) => {
|
||||
let _ = tx.send(cmd);
|
||||
@@ -1710,14 +1691,16 @@ impl Session {
|
||||
|
||||
/// The registered streams of the directory, for the stream task.
|
||||
fn feed_directory(&self) {
|
||||
let Some(streams) = &self.streams else { return };
|
||||
if !self.streams {
|
||||
return;
|
||||
}
|
||||
let entries = self
|
||||
.directory
|
||||
.values()
|
||||
.filter_map(|e| {
|
||||
Some(StreamInfo {
|
||||
id: e.stream_id.clone()?,
|
||||
streamer: ClientId(e.client_id?),
|
||||
streamer: e.client_id?,
|
||||
name: e.title.clone(),
|
||||
kind: parse_kind(&e.kind),
|
||||
// Not in the directory; the stream's offer tells.
|
||||
@@ -1729,7 +1712,7 @@ impl Session {
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
streams.send(StreamInput::Directory(entries));
|
||||
self.stream_cmd(StreamCmd::Directory(entries));
|
||||
}
|
||||
|
||||
fn register_own_stream(&mut self) {
|
||||
@@ -1834,7 +1817,7 @@ impl Session {
|
||||
}
|
||||
self.stop_streams("session closed");
|
||||
if let Some((_, tx)) = self.voice.take() {
|
||||
let _ = tx.send(VoiceCmd::Disconnect);
|
||||
let _ = tx.send(LinkCmd::Disconnect);
|
||||
}
|
||||
self.audio = None;
|
||||
self.stop_observing();
|
||||
@@ -1858,7 +1841,7 @@ impl Session {
|
||||
SourceEvent::Query(g, e) if self.is_current(Source::Query, g) => self.query_event(e),
|
||||
SourceEvent::AudioOut(g, packet) if self.is_current(Source::Voice, g) => {
|
||||
if let Some((_, tx)) = &self.voice {
|
||||
let _ = tx.send(VoiceCmd::Audio(packet));
|
||||
let _ = tx.send(LinkCmd::Audio(packet));
|
||||
}
|
||||
}
|
||||
SourceEvent::Audio(g, event) if self.is_current(Source::Voice, g) => match event {
|
||||
@@ -1867,9 +1850,6 @@ impl Session {
|
||||
self.emit(Event::InputLevel { session: Some(self.id), level_db: db, sending })
|
||||
}
|
||||
},
|
||||
SourceEvent::OwnStream(g, e) if self.is_current(Source::Voice, g) => {
|
||||
self.own_stream_event(e)
|
||||
}
|
||||
SourceEvent::Directory(g, result) if self.is_current(Source::Gateway, g) => {
|
||||
match result {
|
||||
Ok(streams) => {
|
||||
@@ -1895,7 +1875,7 @@ impl Session {
|
||||
}
|
||||
SourceEvent::AvatarUploaded(g, request, result) => match result {
|
||||
Ok(hash) if self.is_current(Source::Voice, g) => {
|
||||
self.voice_cmd(VoiceCmd::SetAvatarHash { request: Some(request), hash });
|
||||
self.voice_cmd(LinkCmd::SetAvatarHash { request: Some(request), hash });
|
||||
}
|
||||
Ok(_) => self.emit(Event::RequestDone {
|
||||
session: self.id,
|
||||
@@ -1923,9 +1903,16 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
fn voice_event(&mut self, e: VoiceEvent) {
|
||||
fn voice_event(&mut self, e: LinkEvent) {
|
||||
match e {
|
||||
VoiceEvent::Connected { name, flavor, own_client, server_uid, own_uid } => {
|
||||
LinkEvent::Connected {
|
||||
name,
|
||||
backend,
|
||||
capabilities,
|
||||
own_client,
|
||||
server_uid,
|
||||
own_uid,
|
||||
} => {
|
||||
self.state.voice = VoiceState::Connected;
|
||||
self.state.own_client = Some(own_client);
|
||||
if own_uid.is_some() {
|
||||
@@ -1940,50 +1927,26 @@ impl Session {
|
||||
{
|
||||
let _ = tx.send(GatewayCmd::RetryNow);
|
||||
}
|
||||
let capabilities = flavor.capabilities();
|
||||
if capabilities.streams
|
||||
&& let Some((generation, voice)) = &self.voice
|
||||
{
|
||||
let generation = *generation;
|
||||
let (own_tx, own_rx) = mpsc::unbounded_channel();
|
||||
self.forward(own_rx, move |e| SourceEvent::OwnStream(generation, e));
|
||||
let streams = StreamHandle::spawn(
|
||||
self.id,
|
||||
own_client,
|
||||
self.stream_peer.clone(),
|
||||
voice.clone(),
|
||||
self.events.clone(),
|
||||
self.frames.clone(),
|
||||
self.audio.clone(),
|
||||
self.settings.clone(),
|
||||
own_tx,
|
||||
);
|
||||
if capabilities.streams {
|
||||
self.streams = true;
|
||||
if !self.stream_layers.is_empty() {
|
||||
streams.send(StreamInput::Layers(self.stream_layers.clone()));
|
||||
self.stream_cmd(StreamCmd::Layers(self.stream_layers.clone()));
|
||||
}
|
||||
// The setting may have changed since the connection was asked for.
|
||||
if let Some(profiles) = self.srtp_profiles.clone() {
|
||||
self.stream_cmd(StreamCmd::SrtpProfiles(profiles));
|
||||
}
|
||||
self.streams = Some(streams);
|
||||
self.feed_directory();
|
||||
}
|
||||
self.emit(Event::ServerInfo { session: self.id, name, flavor, capabilities });
|
||||
self.emit(Event::ServerInfo { session: self.id, name, backend, capabilities });
|
||||
self.reopen_relayed_chats();
|
||||
self.open_histories();
|
||||
}
|
||||
VoiceEvent::Presence(p) => {
|
||||
LinkEvent::Presence(p) => {
|
||||
// Client ids are reused: forget the volumes of those who left.
|
||||
if let (Some(a), Some(old)) = (&self.audio, &self.voice_presence) {
|
||||
for id in old.clients.keys().filter(|id| !p.clients.contains_key(id)) {
|
||||
a.send(AudioIn::ClientLeft(ClientId(*id)));
|
||||
}
|
||||
}
|
||||
if let Some(s) = &self.streams {
|
||||
let clients: BTreeMap<_, _> = p
|
||||
.clients
|
||||
.values()
|
||||
.map(|c| (c.id, ClientState { channel: c.channel, streaming: c.streaming }))
|
||||
.collect();
|
||||
if clients != self.streaming_clients {
|
||||
self.streaming_clients = clients.clone();
|
||||
s.send(StreamInput::Clients(clients));
|
||||
a.send(AudioIn::ClientLeft(TalkerId(*id)));
|
||||
}
|
||||
}
|
||||
self.report_details(&p);
|
||||
@@ -1993,7 +1956,7 @@ impl Session {
|
||||
self.voice_presence = Some(*p);
|
||||
self.publish_presence();
|
||||
}
|
||||
VoiceEvent::Poke { from, from_uid, from_name, message } => {
|
||||
LinkEvent::Poke { from, from_uid, from_name, message } => {
|
||||
let blocked = self.contacts.is_blocked(from_uid.as_deref());
|
||||
if blocked && self.block_mode() == BlockMode::Hide {
|
||||
debug!(?from_uid, "poke of a blocked contact hidden");
|
||||
@@ -2006,35 +1969,37 @@ impl Session {
|
||||
let session = self.id;
|
||||
self.emit(Event::Poke { session, from, from_uid, from_name, message, blocked });
|
||||
}
|
||||
VoiceEvent::Error(message) => self.error(message),
|
||||
VoiceEvent::Stream(n) => {
|
||||
if let Some(s) = &self.streams {
|
||||
s.send(StreamInput::Notification(n));
|
||||
LinkEvent::Error(message) => self.error(message),
|
||||
LinkEvent::OwnStream(e) => self.own_stream_event(e),
|
||||
LinkEvent::StreamAudio { stream, time, data } => {
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::StreamAudio { stream, time, data });
|
||||
}
|
||||
}
|
||||
VoiceEvent::StreamRequestFailed(request, error) => {
|
||||
if let Some(s) = &self.streams {
|
||||
s.send(StreamInput::RequestFailed(request, error));
|
||||
LinkEvent::StreamAudioEnded(stream) => {
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::StreamEnded(stream));
|
||||
}
|
||||
}
|
||||
VoiceEvent::OwnChannel(cid) => {
|
||||
LinkEvent::OwnChannel(cid) => {
|
||||
if self.state.own_channel != Some(cid) {
|
||||
self.state.own_channel = Some(cid);
|
||||
self.emit_state();
|
||||
}
|
||||
}
|
||||
VoiceEvent::Chat(msg) => self.chat(msg, MessageSource::Voice, None),
|
||||
VoiceEvent::Audio(packet) => {
|
||||
LinkEvent::Chat(msg) => self.chat(msg, MessageSource::Voice, None),
|
||||
LinkEvent::Audio(packet) => {
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::Packet(packet));
|
||||
}
|
||||
}
|
||||
VoiceEvent::Talking { client, talking } => {
|
||||
LinkEvent::Talking { client, talking } => {
|
||||
self.emit(Event::Talking { session: self.id, client, talking });
|
||||
}
|
||||
VoiceEvent::Disconnected(reason) => {
|
||||
self.stop_streams("voice disconnected");
|
||||
LinkEvent::Disconnected(reason) => {
|
||||
// The connection ended its streams itself.
|
||||
self.voice = None;
|
||||
self.stop_streams("voice disconnected");
|
||||
self.voice_presence = None;
|
||||
self.audio = None;
|
||||
self.forget_images();
|
||||
@@ -2288,18 +2253,13 @@ mod banner_tests {
|
||||
cache: SharedCache::new(Cache::new(dir)),
|
||||
contacts: Contacts::new(events.clone(), history),
|
||||
};
|
||||
// No myTeamSpeak account; its source stays open, as the engine's does
|
||||
// (a closed one ends voice connections).
|
||||
let myts_identity = Box::leak(Box::new(watch::Sender::new(None))).subscribe();
|
||||
let myts_data = Box::leak(Box::new(watch::Sender::new(None))).subscribe();
|
||||
let session = Session::new(
|
||||
1,
|
||||
events,
|
||||
frames,
|
||||
AudioSettings::default(),
|
||||
shared,
|
||||
myts_identity,
|
||||
myts_data,
|
||||
Arc::new(SessionLink::new(crate::Backends::empty())),
|
||||
);
|
||||
(session, receiver)
|
||||
}
|
||||
@@ -2386,7 +2346,7 @@ mod banner_tests {
|
||||
Err("temporarily unavailable".into()),
|
||||
);
|
||||
session.retry_images(session.image_retries[&request].due.unwrap());
|
||||
let VoiceCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
|
||||
let LinkCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
|
||||
commands.try_recv().unwrap()
|
||||
else {
|
||||
panic!("expected an image download");
|
||||
@@ -2433,7 +2393,7 @@ mod banner_tests {
|
||||
session.state.server_uid = Some("server-a".into());
|
||||
session.fetch_pictures(&presence);
|
||||
assert!(session.pictures.contains(url));
|
||||
let VoiceCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
|
||||
let LinkCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
|
||||
commands.try_recv().unwrap()
|
||||
else {
|
||||
panic!("expected a file download");
|
||||
@@ -2975,9 +2935,10 @@ mod banner_tests {
|
||||
let (mut session, _events) = session("gateway-wake");
|
||||
let (tx, mut rx) = mpsc::unbounded_channel();
|
||||
session.gateway = Some((session.next_generation(), tx));
|
||||
let connected = || VoiceEvent::Connected {
|
||||
let connected = || LinkEvent::Connected {
|
||||
name: "test".into(),
|
||||
flavor: voelin_model::ServerFlavor::Unknown(String::new()),
|
||||
backend: crate::BackendInfo::default(),
|
||||
capabilities: voelin_model::Capabilities::default(),
|
||||
own_client: 1,
|
||||
server_uid: "server=".into(),
|
||||
own_uid: None,
|
||||
|
||||
@@ -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>;
|
||||
@@ -1135,7 +1135,7 @@ pub static CACHE_FETCH_IMAGES: Key<bool> = Key::new(
|
||||
);
|
||||
|
||||
/// Import identities from the official TeamSpeak clients when the app
|
||||
/// starts ([`crate::identity::import_new`]; their files are only read).
|
||||
/// starts ([`crate::ts::identity::import_new`]; their files are only read).
|
||||
pub static IDENTITY_IMPORT: Key<bool> = Key::new(
|
||||
"identity.import_from_teamspeak",
|
||||
Kind::Bool,
|
||||
|
||||
+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),
|
||||
}
|
||||
@@ -331,4 +331,301 @@ mod tests {
|
||||
let p = presence_from_book(&book, None, |_| false);
|
||||
assert_eq!(avatar(&p, 6).as_deref(), Some("https://a.example/off.png"));
|
||||
}
|
||||
|
||||
// ---- across the session seam ---------------------------------------------
|
||||
|
||||
/// A presence made into the entities the TeamSpeak session writes
|
||||
/// (`ts_session::entities`), pushed the way a host syncs them, and
|
||||
/// projected back by the engine (`link::project`): what the UI is shown
|
||||
/// of what a TeamSpeak link reported (`docs/session-seam.md` section 5.1).
|
||||
fn through_the_seam(presence: &Presence, ts6: bool, own: Option<u16>) -> Presence {
|
||||
use voelin_model::replica::{Replica, SCHEMA_GENERATION, ScopeId};
|
||||
use voelin_proto::link::Features;
|
||||
use voelin_proto::v1::{self, push::Body};
|
||||
|
||||
use crate::link::media::TalkTracker;
|
||||
use crate::link::project::{View, presence as project};
|
||||
use crate::ts::ts_session::entities::build;
|
||||
|
||||
let built = build(presence, ts6, own);
|
||||
let mut replica = Replica::new(SCHEMA_GENERATION);
|
||||
for (scope, layer) in [(ScopeId::Server(1), &built.server), (ScopeId::Live(1), &built.live)]
|
||||
{
|
||||
replica.subscribe(scope);
|
||||
let pushes = [
|
||||
Body::SyncBegin(v1::SyncBegin {
|
||||
scope: Some(scope.to_proto()),
|
||||
mode: v1::SyncMode::Full as i32,
|
||||
epoch: 1,
|
||||
}),
|
||||
Body::Change(v1::Change {
|
||||
scope: Some(scope.to_proto()),
|
||||
rev: 1,
|
||||
put: layer.values().cloned().collect(),
|
||||
del: Vec::new(),
|
||||
}),
|
||||
Body::SyncEnd(v1::SyncEnd {
|
||||
scope: Some(scope.to_proto()),
|
||||
cursor: Some(v1::Cursor { epoch: 1, rev: 1 }),
|
||||
gap: false,
|
||||
}),
|
||||
];
|
||||
for body in pushes {
|
||||
replica.apply_push(&v1::Push { body: Some(body) });
|
||||
}
|
||||
}
|
||||
let features = Features::new(["voice"]);
|
||||
let talking = TalkTracker::default();
|
||||
project(&View {
|
||||
replica: &replica,
|
||||
server: 1,
|
||||
teamspeak: true,
|
||||
version: "",
|
||||
features: &features,
|
||||
streams: ts6,
|
||||
talking: &talking,
|
||||
})
|
||||
}
|
||||
|
||||
/// A TeamSpeak 6 server and some clients with what the book holds of them.
|
||||
fn ts6_presence() -> Presence {
|
||||
let mut book = ts6_book();
|
||||
let list = format!(
|
||||
"channellist {}|{}|{}",
|
||||
channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"),
|
||||
channel(
|
||||
12,
|
||||
1,
|
||||
"Raid",
|
||||
r"channel_banner_gfx_url=http:\/\/127.0.0.1:1\/d.png channel_banner_mode=2"
|
||||
),
|
||||
channel(20, 12, "Last", "channel_banner_gfx_url channel_banner_mode=0"),
|
||||
);
|
||||
book.handle_command(&message(&list)).unwrap();
|
||||
let enter = |clid: u16, channel: u64, groups: &str, away: &str, avatar: &str| {
|
||||
format!(
|
||||
"notifycliententerview reasonid=0 ctid={channel} clid={clid} \
|
||||
client_database_id={} client_nickname=c{clid} client_type=0 cfid=0 \
|
||||
client_unique_identifier=u{clid}= client_flag_avatar=abcdef \
|
||||
client_description=about\\sme client_icon_id=777 client_input_muted=1 \
|
||||
client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 \
|
||||
client_output_hardware=1 client_meta_data client_is_recording=1 \
|
||||
client_channel_group_id=8 client_channel_group_inherited_channel_id=1 \
|
||||
client_servergroups={groups} client_away={} client_away_message={away} \
|
||||
client_talk_power=75 client_talk_request=0 client_talk_request_msg \
|
||||
client_is_talker=1 client_is_priority_speaker=1 client_unread_messages=0 \
|
||||
client_nickname_phonetic client_needed_serverquery_view_power=75 \
|
||||
client_is_channel_commander=1 client_country=RU client_badges \
|
||||
client_myteamspeak_id=m{clid} client_integrations{avatar}",
|
||||
100 + u64::from(clid),
|
||||
u8::from(!away.is_empty()),
|
||||
)
|
||||
};
|
||||
for text in [
|
||||
enter(5, 1, "8", "", r" client_myteamspeak_avatar=2,https:\/\/a.example\/on.png"),
|
||||
enter(6, 12, "8,9", "gone\\sfishing", ""),
|
||||
enter(7, 12, "", "", " client_myteamspeak_avatar"),
|
||||
] {
|
||||
book.handle_command(&message(&text)).unwrap();
|
||||
}
|
||||
presence_from_book(&book, Some("ibhejBRSRRI7v+fSsUzpQ33JGK6rf5xKOLelpWUr0sE="), |_| false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_book_is_what_the_ui_is_shown_across_the_seam() {
|
||||
let p = ts6_presence();
|
||||
assert_eq!(p.clients.len(), 3, "the fixture has clients");
|
||||
assert!(p.clients.values().any(|c| c.away.is_some()), "one is away");
|
||||
// A TeamSpeak 6 client the book has no streaming flag of (it was not
|
||||
// sent) is not streaming: v1 has no "unknown" for it.
|
||||
let mut expected = p.clone();
|
||||
for client in expected.clients.values_mut() {
|
||||
client.streaming = Some(client.streaming.unwrap_or(false));
|
||||
}
|
||||
assert_eq!(through_the_seam(&p, true, Some(5)), expected);
|
||||
// The same server as a TeamSpeak 3 one has no streams to tell of.
|
||||
let mut ts3 = p.clone();
|
||||
for client in ts3.clients.values_mut() {
|
||||
client.streaming = None;
|
||||
}
|
||||
assert_eq!(through_the_seam(&ts3, false, Some(5)), ts3);
|
||||
}
|
||||
|
||||
/// A deterministic stream of numbers for the generated presences.
|
||||
struct Numbers(u64);
|
||||
|
||||
impl Numbers {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n
|
||||
}
|
||||
|
||||
fn flag(&mut self) -> bool {
|
||||
self.below(2) == 0
|
||||
}
|
||||
|
||||
fn text(&mut self, prefix: &str) -> String {
|
||||
format!("{prefix}{}", self.below(1000))
|
||||
}
|
||||
}
|
||||
|
||||
/// A presence of the shape a TeamSpeak link reports: sibling channels in an
|
||||
/// order chain, every client with a database id, unique ids that are base64
|
||||
/// (TeamSpeak 3 and 6) or login names, groups of both kinds.
|
||||
fn generated(seed: u64, ts6: bool) -> Presence {
|
||||
use base64::Engine as _;
|
||||
use voelin_model::{
|
||||
BannerMode, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType,
|
||||
HostMessageMode,
|
||||
};
|
||||
let mut n = Numbers(seed | 1);
|
||||
let mut p = Presence::default();
|
||||
let name = n.text("Server ");
|
||||
p.server_name = name.clone();
|
||||
p.server = voelin_model::ServerDetails {
|
||||
name,
|
||||
uid: Some(n.text("uid")),
|
||||
welcome_message: n.text("welcome "),
|
||||
host_message: n.text("host "),
|
||||
host_message_mode: [
|
||||
HostMessageMode::None,
|
||||
HostMessageMode::Log,
|
||||
HostMessageMode::Modal,
|
||||
][n.below(3) as usize],
|
||||
banner_url: if n.flag() { n.text("https://b/") } else { String::new() },
|
||||
banner_gfx_url: if n.flag() { n.text("https://g/") } else { String::new() },
|
||||
banner_gfx_interval_s: n.below(100),
|
||||
banner_mode: [BannerMode::NoAdjust, BannerMode::IgnoreAspect, BannerMode::KeepAspect]
|
||||
[n.below(3) as usize],
|
||||
host_button_tooltip: if n.flag() { n.text("tip ") } else { String::new() },
|
||||
host_button_url: String::new(),
|
||||
host_button_gfx_url: String::new(),
|
||||
icon: n.below(5) as u32 * 1000,
|
||||
platform: "Linux".into(),
|
||||
version: n.text("6.0."),
|
||||
max_clients: n.below(500) as u16,
|
||||
priority_speaker_dimm_db: -(n.below(30) as i32),
|
||||
default_server_group: Some(1 + n.below(9)),
|
||||
default_channel_group: Some(1 + n.below(9)),
|
||||
};
|
||||
// Groups.
|
||||
for id in 1..=(2 + n.below(4)) {
|
||||
let group = |id: u64, n: &mut Numbers| GroupInfo {
|
||||
id,
|
||||
name: n.text("group "),
|
||||
icon: n.below(3) as u32 * 100,
|
||||
sort_id: n.below(1000) as i32 - 500,
|
||||
naming_mode: [
|
||||
GroupNamingMode::None,
|
||||
GroupNamingMode::Before,
|
||||
GroupNamingMode::After,
|
||||
][n.below(3) as usize],
|
||||
group_type: [GroupType::Regular, GroupType::Template, GroupType::Query]
|
||||
[n.below(3) as usize],
|
||||
};
|
||||
p.server_groups.insert(id, group(id, &mut n));
|
||||
p.channel_groups.insert(id, group(id, &mut n));
|
||||
}
|
||||
// Channels: a tree whose siblings follow each other.
|
||||
let mut parents = vec![0u64];
|
||||
for id in 1..=(3 + n.below(8)) {
|
||||
let parent = parents[n.below(parents.len() as u64) as usize];
|
||||
let order = p
|
||||
.channels
|
||||
.values()
|
||||
.filter(|c| c.parent == parent)
|
||||
.map(|c| c.id)
|
||||
.next_back()
|
||||
.unwrap_or(0);
|
||||
parents.push(id);
|
||||
p.channels.insert(
|
||||
id,
|
||||
ChannelInfo {
|
||||
id,
|
||||
parent,
|
||||
order,
|
||||
name: n.text("channel "),
|
||||
topic: n.flag().then(|| n.text("topic ")),
|
||||
has_password: n.flag(),
|
||||
max_clients: match n.below(3) {
|
||||
0 => None,
|
||||
1 => Some(0),
|
||||
_ => Some(1 + n.below(50) as i32),
|
||||
},
|
||||
needed_subscribe_power: n.below(3) as i32 * 10,
|
||||
needed_talk_power: n.below(3) as i32 * 25,
|
||||
is_default: id == 1,
|
||||
icon: n.below(3) as u32 * 500,
|
||||
banner_gfx_url: n.flag().then(|| n.text("https://c/")),
|
||||
banner_mode: [
|
||||
BannerMode::NoAdjust,
|
||||
BannerMode::IgnoreAspect,
|
||||
BannerMode::KeepAspect,
|
||||
][n.below(3) as usize],
|
||||
},
|
||||
);
|
||||
}
|
||||
// Clients.
|
||||
let channels: Vec<u64> = p.channels.keys().copied().collect();
|
||||
for id in 1..=(1 + n.below(12)) {
|
||||
let id = id as u16;
|
||||
let uid = match n.below(4) {
|
||||
0 => None,
|
||||
1 => Some(n.text("login")),
|
||||
_ => {
|
||||
let bytes: Vec<u8> =
|
||||
(0..if ts6 { 32 } else { 20 }).map(|_| n.below(256) as u8).collect();
|
||||
Some(base64::engine::general_purpose::STANDARD.encode(bytes))
|
||||
}
|
||||
};
|
||||
let channel = channels[n.below(channels.len() as u64) as usize];
|
||||
p.clients.insert(
|
||||
id,
|
||||
ClientInfo {
|
||||
id,
|
||||
uid,
|
||||
nickname: n.text("nick "),
|
||||
channel,
|
||||
is_query: n.below(5) == 0,
|
||||
away: n.flag().then(|| if n.flag() { n.text("away ") } else { String::new() }),
|
||||
input_muted: n.flag(),
|
||||
output_muted: n.flag(),
|
||||
talking: Some(false),
|
||||
streaming: ts6.then(|| n.flag()),
|
||||
server_groups: (0..n.below(3)).map(|_| 1 + n.below(9)).collect(),
|
||||
country: n.flag().then(|| "DE".into()),
|
||||
avatar: n.flag().then(|| n.text("hash")),
|
||||
myts_avatar: n.flag().then(|| n.text("https://a/")),
|
||||
description: n.flag().then(|| n.text("about ")),
|
||||
talk_power: n.below(100) as i32,
|
||||
talker: n.flag(),
|
||||
channel_group: n.flag().then(|| 1 + n.below(9)),
|
||||
badges: (0..n.below(3)).map(|_| n.text("badge")).collect(),
|
||||
icon: n.below(3) as u32 * 111,
|
||||
recording: n.flag(),
|
||||
priority_speaker: n.flag(),
|
||||
channel_commander: n.flag(),
|
||||
database_id: Some(1_000 + u64::from(id)),
|
||||
},
|
||||
);
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_presences_survive_the_seam() {
|
||||
for seed in 1..=200u64 {
|
||||
for ts6 in [false, true] {
|
||||
let p = generated(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15), ts6);
|
||||
let own = p.clients.keys().next().copied();
|
||||
assert_eq!(through_the_seam(&p, ts6, own), p, "seed {seed}, ts6 {ts6}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ use std::{fs, str};
|
||||
use rusqlite::{Connection, OpenFlags, OptionalExtension};
|
||||
use tsclientlib::Identity;
|
||||
use voelin_gateway_proto::UniqueIds;
|
||||
use voelin_identity::IdentityBlob;
|
||||
use voelin_store::{IdentityOrigin, Store};
|
||||
|
||||
/// Name given to an identity whose source kept none.
|
||||
@@ -55,6 +56,9 @@ pub enum IdentityError {
|
||||
NoIdentity { path: String },
|
||||
#[error("client database: {0}")]
|
||||
Store(String),
|
||||
/// An [`IdentityBlob`] that is no TeamSpeak identity ([`from_blob`]).
|
||||
#[error("{0}")]
|
||||
Blob(String),
|
||||
}
|
||||
|
||||
impl IdentityError {
|
||||
@@ -230,6 +234,76 @@ pub fn import_new(store: &Store, paths: &[PathBuf]) -> Result<LaunchImport, Iden
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// A TeamSpeak identity as the API takes it
|
||||
/// ([`VoiceOptions::identity`](crate::VoiceOptions::identity),
|
||||
/// [`Command::ObserveGateway`](crate::Command::ObserveGateway)) and the key
|
||||
/// store keeps it: kind `teamspeak`, the unique id TeamSpeak 3 servers know it
|
||||
/// by (also how [`voelin_store`] keys it), its security level, and the JSON
|
||||
/// the store writes.
|
||||
pub fn to_blob(identity: &Identity) -> IdentityBlob {
|
||||
// An identity is a key and two counters: writing it cannot fail. (A blob with
|
||||
// no JSON is refused when it is used, in words.)
|
||||
let json = serde_json::to_string(identity).unwrap_or_default();
|
||||
IdentityBlob::teamspeak(identity.key().to_pub().get_uid(), identity.level(), json)
|
||||
}
|
||||
|
||||
/// The TeamSpeak identity of a blob (the reverse of [`to_blob`]).
|
||||
pub fn from_blob(blob: &IdentityBlob) -> Result<Identity, IdentityError> {
|
||||
if !blob.is_teamspeak() {
|
||||
return Err(IdentityError::Blob(format!(
|
||||
"the identity is of kind {:?}, not a TeamSpeak one",
|
||||
blob.kind
|
||||
)));
|
||||
}
|
||||
from_json(&blob.json)
|
||||
}
|
||||
|
||||
/// The TeamSpeak identity in `json`, the text [`to_blob`] writes and the key
|
||||
/// store keeps; every reader of that text refuses it through here.
|
||||
///
|
||||
/// What does not read is refused in words that say how it is wrong
|
||||
/// (malformed, cut short, not an identity, unreadable) and where (line and
|
||||
/// column), and never what it holds: the text holds a private key, and the
|
||||
/// message of the JSON reader quotes a value it refuses (`tsproto` reports a
|
||||
/// key that does not import as an invalid value, the key string and all), so
|
||||
/// that message is never shown, not in an error, an event or a log.
|
||||
pub(crate) fn from_json(json: &str) -> Result<Identity, IdentityError> {
|
||||
serde_json::from_str(json).map_err(|e| {
|
||||
let what = match e.classify() {
|
||||
serde_json::error::Category::Syntax => "malformed",
|
||||
serde_json::error::Category::Eof => "cut short",
|
||||
serde_json::error::Category::Data => "not an identity",
|
||||
serde_json::error::Category::Io => "unreadable",
|
||||
};
|
||||
IdentityError::Blob(format!(
|
||||
"the TeamSpeak identity cannot be read: {what} at line {}, column {}",
|
||||
e.line(),
|
||||
e.column()
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// The JSON of a fresh identity whose key lost its last two characters (a key
|
||||
/// that does not import), and that cut key.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn json_with_a_cut_key() -> (String, String) {
|
||||
let mut json = serde_json::to_value(Identity::create()).unwrap();
|
||||
let key = json["key"].as_str().unwrap().to_owned();
|
||||
let cut = key[..key.len() - 2].to_owned();
|
||||
json["key"] = cut.clone().into();
|
||||
(json.to_string(), cut)
|
||||
}
|
||||
|
||||
/// Fail if `text` holds any 8 characters in a row of `secret`.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn assert_holds_no_piece_of(text: &str, secret: &str) {
|
||||
assert!(secret.len() >= 8 && secret.is_ascii());
|
||||
for piece in secret.as_bytes().windows(8) {
|
||||
let piece = std::str::from_utf8(piece).unwrap();
|
||||
assert!(!text.contains(piece), "{text:?} holds {piece:?} of the key");
|
||||
}
|
||||
}
|
||||
|
||||
/// The TeamSpeak 3 `.ini` export of an identity, which the official client
|
||||
/// and every other tool reads.
|
||||
pub fn export(nickname: &str, identity: &Identity) -> String {
|
||||
@@ -548,18 +622,69 @@ mod tests {
|
||||
Identity::create()
|
||||
}
|
||||
|
||||
/// The blob of an identity is how the key store keeps it, and reads back as
|
||||
/// the same identity; what is no TeamSpeak identity is refused without
|
||||
/// quoting its JSON.
|
||||
#[test]
|
||||
fn an_identity_goes_through_its_blob() {
|
||||
let identity = synthetic();
|
||||
let blob = to_blob(&identity);
|
||||
assert!(blob.is_teamspeak());
|
||||
assert_eq!(blob.uid, identity.key().to_pub().get_uid());
|
||||
assert_eq!(blob.level, identity.level());
|
||||
assert_eq!(blob.json, serde_json::to_string(&identity).unwrap());
|
||||
let back = from_blob(&blob).unwrap();
|
||||
assert_eq!(serde_json::to_value(&back).unwrap(), serde_json::to_value(&identity).unwrap());
|
||||
|
||||
// Another kind.
|
||||
let other = IdentityBlob::new("voelin", "x", 0, blob.json.clone());
|
||||
let error = from_blob(&other).unwrap_err().to_string();
|
||||
assert!(error.contains("\"voelin\""), "{error}");
|
||||
// Not an identity: the text says where, and nothing of what it holds.
|
||||
for json in ["", "{", r#"{"key":"hunter2-key","counter":"hunter2"}"#, "[1]"] {
|
||||
let error = from_blob(&IdentityBlob::teamspeak("x", 0, json)).unwrap_err().to_string();
|
||||
assert!(error.starts_with("the TeamSpeak identity cannot be read"), "{error}");
|
||||
assert!(!error.contains("hunter2"), "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The JSON reader's own message quotes a key that does not import, so the
|
||||
/// refusal is worded by `from_json` and holds none of the key.
|
||||
#[test]
|
||||
fn a_key_that_does_not_import_is_refused_without_quoting_it() {
|
||||
let (json, cut) = json_with_a_cut_key();
|
||||
let raw = serde_json::from_str::<Identity>(&json).unwrap_err().to_string();
|
||||
assert!(raw.contains(&cut), "the reader's own message quotes the key: {raw}");
|
||||
for error in [
|
||||
from_json(&json).unwrap_err().to_string(),
|
||||
from_blob(&IdentityBlob::teamspeak("x", 8, json.clone())).unwrap_err().to_string(),
|
||||
] {
|
||||
assert!(
|
||||
error.starts_with(
|
||||
"the TeamSpeak identity cannot be read: not an identity at line 1, column "
|
||||
),
|
||||
"{error}"
|
||||
);
|
||||
assert_holds_no_piece_of(&error, &cut);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn improve_level_keeps_the_key() {
|
||||
let identity = synthetic();
|
||||
// A fresh identity stops at the first counter whose level is 8 or more,
|
||||
// and about one in 32 has 13 or more already, which `improve_level`
|
||||
// returns as it is: ask for more than this one has, whatever it has.
|
||||
let target = identity.level() + 3;
|
||||
let levels = std::sync::Mutex::new(Vec::new());
|
||||
let better = improve_level(&identity, 13, &AtomicBool::new(false), |l| {
|
||||
let better = improve_level(&identity, target, &AtomicBool::new(false), |l| {
|
||||
levels.lock().unwrap().push(l);
|
||||
})
|
||||
.unwrap();
|
||||
assert!(better.level() >= 13);
|
||||
assert!(better.level() >= target);
|
||||
assert_eq!(better.key().to_pub().get_uid(), identity.key().to_pub().get_uid());
|
||||
assert!(better.counter() > identity.counter());
|
||||
assert!(levels.into_inner().unwrap().iter().any(|l| *l >= 13));
|
||||
assert!(levels.into_inner().unwrap().iter().any(|l| *l >= target));
|
||||
// Cancelled: nothing.
|
||||
assert!(improve_level(&identity, 60, &AtomicBool::new(true), |_| {}).is_none());
|
||||
// Already there: the same identity.
|
||||
@@ -0,0 +1,30 @@
|
||||
//! The TeamSpeak implementation of the session seam.
|
||||
//!
|
||||
//! Everything of the engine that is TeamSpeak's lives here, so that it can
|
||||
//! leave this crate for the TeamSpeak gateway (`voelin-gateway-ts` of
|
||||
//! VoelinGateWay) as one piece (`docs/session-seam.md`, H9):
|
||||
//!
|
||||
//! - `ts_link.rs` and `voice.rs` are the connection of `tsclientlib`
|
||||
//! (chat, voice, files, pokes, offline messages, the stream task's
|
||||
//! requests) with `book.rs`, its presence from the library's book;
|
||||
//! - `ts_session/` makes a `voelin_proto::link::Session` of such a connection
|
||||
//! ([`TsConnector`] is the `Connector` the engine registers for
|
||||
//! `ts3server://` and `teamspeak://`);
|
||||
//! - [`versions`] and [`identity`] are what a TeamSpeak client has to know
|
||||
//! about itself: the signed compatibility versions it can claim, and the
|
||||
//! identities (reading, importing from the official clients, the security
|
||||
//! level).
|
||||
//!
|
||||
//! The TeamSpeak crates' types (`tsclientlib::Identity`, `Version`, ...) are
|
||||
//! named in the public items of this module and nowhere else of the crate's
|
||||
//! API.
|
||||
|
||||
mod book;
|
||||
pub mod identity;
|
||||
mod ts_link;
|
||||
pub(crate) mod ts_session;
|
||||
pub mod versions;
|
||||
mod voice;
|
||||
|
||||
pub(crate) use ts_link::{ConnectOptions, ServerLink, TsLink};
|
||||
pub use ts_session::TsConnector;
|
||||
@@ -0,0 +1,256 @@
|
||||
//! The inner link of the TeamSpeak side: [`ServerLink`], the trait that
|
||||
//! [`TsLink`] implements, and the [`ConnectOptions`] it connects with.
|
||||
//!
|
||||
//! The engine does not know this vocabulary: it talks to a
|
||||
//! `voelin_proto::link::Session`. The `ts_session` module makes a `Session`
|
||||
//! of a [`ServerLink`] (`LinkSession`), and the engine's tests give it a link
|
||||
//! of their own, an in-memory one. [`TsLink`] connects as a normal TeamSpeak 3
|
||||
//! or 6 client with `tsclientlib` and
|
||||
//! runs the connection ([`super::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 std::sync::Arc;
|
||||
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use voelin_stream::PeerConfig;
|
||||
|
||||
use super::voice;
|
||||
use crate::link::{LinkCmd, LinkCtx, LinkEvent};
|
||||
|
||||
/// Starts the connection of a link: the contract of `crate::link` for the
|
||||
/// vocabulary ([`LinkCmd`] in, [`LinkEvent`] out) holds for what a link does
|
||||
/// with them, and the module documentation of `link/session_link.rs` states
|
||||
/// it.
|
||||
///
|
||||
/// One link serves every session of an engine; [`spawn`](Self::spawn) starts
|
||||
/// one connection.
|
||||
pub(crate) 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 TeamSpeak connection needs to know: the server, who to be, where
|
||||
/// to join. The reverse of what the engine's `ConnectParams` carry
|
||||
/// (`ts_session::inner_options`).
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ConnectOptions {
|
||||
pub address: String,
|
||||
pub nickname: String,
|
||||
/// The identity to connect with; none generates one.
|
||||
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.
|
||||
pub stream_peer: PeerConfig,
|
||||
}
|
||||
|
||||
impl ConnectOptions {
|
||||
/// Options for `address` and `nickname`, the rest as a test leaves it.
|
||||
#[cfg(test)]
|
||||
pub(crate) 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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The main myTeamSpeak account of an application, as its connections show
|
||||
/// it to the servers: the proof of the myTS ID, and what servers are shown
|
||||
/// of it (its avatar and badges with their certificates, its User Tag).
|
||||
///
|
||||
/// The senders live here, one pair for every connection of a [`TsLink`]; each
|
||||
/// connection watches the pair through [`Watches`], presents the account it
|
||||
/// finds when it connects, and follows the changes.
|
||||
pub(crate) struct Account {
|
||||
identity: watch::Sender<Option<Arc<tsproto::myts::Identity>>>,
|
||||
data: watch::Sender<Option<Arc<tsclientlib::MytsData>>>,
|
||||
}
|
||||
|
||||
impl Default for Account {
|
||||
/// No account is signed in.
|
||||
fn default() -> Self {
|
||||
Self { identity: watch::Sender::new(None), data: watch::Sender::new(None) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Account {
|
||||
/// The account proof for every current and future connection. Still no
|
||||
/// account is no change: every notification restarts the handshakes and
|
||||
/// sends `updatemytsid` on every connection. Any account is (each
|
||||
/// connection's proof is signed anew).
|
||||
pub(crate) fn set_identity(&self, identity: Option<Arc<tsproto::myts::Identity>>) {
|
||||
self.identity.send_if_modified(|current| {
|
||||
if current.is_none() && identity.is_none() {
|
||||
return false;
|
||||
}
|
||||
*current = identity;
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
/// What the servers are shown of the account: sent to every connection
|
||||
/// that presents the account's myTS ID, once connected and when it
|
||||
/// changes; cleared on a sign-out. The same data is no change.
|
||||
pub(crate) fn set_data(&self, data: Option<Arc<tsclientlib::MytsData>>) {
|
||||
self.data.send_if_modified(|current| {
|
||||
if *current == data {
|
||||
return false;
|
||||
}
|
||||
*current = data;
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
/// What one connection watches. It keeps the senders alive for as long as
|
||||
/// it runs: a connection ends with "account source closed" when its
|
||||
/// watches have lost them, so the account outlives the connector that
|
||||
/// made the connection.
|
||||
pub(crate) fn watches(self: &Arc<Self>) -> Watches {
|
||||
Watches {
|
||||
identity: self.identity.subscribe(),
|
||||
data: self.data.subscribe(),
|
||||
_keep: Some(self.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The account a connection presents and follows ([`Account::watches`]).
|
||||
pub(crate) struct Watches {
|
||||
pub(super) identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
pub(super) data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
_keep: Option<Arc<Account>>,
|
||||
}
|
||||
|
||||
impl Watches {
|
||||
/// Watches of senders that someone else keeps (a test's).
|
||||
#[cfg(test)]
|
||||
pub(super) fn of(
|
||||
identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
) -> Self {
|
||||
Self { identity, data, _keep: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// Connects to TeamSpeak 3 and 6 servers. The link of [`TsConnector`](super::TsConnector).
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct TsLink {
|
||||
account: Arc<Account>,
|
||||
}
|
||||
|
||||
impl TsLink {
|
||||
/// A link that presents no account until it is given one.
|
||||
pub(crate) fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// The account the link's connections present.
|
||||
pub(crate) fn account(&self) -> &Arc<Account> {
|
||||
&self.account
|
||||
}
|
||||
}
|
||||
|
||||
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, self.account.watches(), cmds, events));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A myTS ID's proof (the standard Ed25519 base point as the public key).
|
||||
fn identity() -> Arc<tsproto::myts::Identity> {
|
||||
let mut private = [0; 32];
|
||||
private[0] = 1;
|
||||
let mut public = [0x66; 32];
|
||||
public[0] = 0x58;
|
||||
Arc::new(
|
||||
tsproto::myts::Identity::new(vec![1; 33], 42, public, private, vec![2; 65]).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
/// An account sets what it holds only when it changes: every notification
|
||||
/// of a watch restarts the handshake of a connection.
|
||||
#[test]
|
||||
fn a_watch_hears_of_a_change_and_not_of_the_same_account_again() {
|
||||
let account = Arc::new(Account::default());
|
||||
let mut watches = account.watches();
|
||||
// No account, still none: nothing.
|
||||
account.set_identity(None);
|
||||
account.set_data(None);
|
||||
assert!(!watches.identity.has_changed().unwrap());
|
||||
assert!(!watches.data.has_changed().unwrap());
|
||||
|
||||
let proof = identity();
|
||||
account.set_identity(Some(proof.clone()));
|
||||
assert!(watches.identity.borrow_and_update().is_some());
|
||||
// An account again is a change (each connection signs its proof anew), the
|
||||
// same data is none.
|
||||
account.set_identity(Some(proof));
|
||||
assert!(watches.identity.has_changed().unwrap());
|
||||
watches.identity.borrow_and_update();
|
||||
let data = Arc::new(tsclientlib::MytsData::default());
|
||||
account.set_data(Some(data.clone()));
|
||||
assert!(watches.data.has_changed().unwrap());
|
||||
watches.data.borrow_and_update();
|
||||
account.set_data(Some(Arc::new(tsclientlib::MytsData::default())));
|
||||
assert!(!watches.data.has_changed().unwrap(), "equal data is no change");
|
||||
// A sign-out is a change.
|
||||
account.set_identity(None);
|
||||
assert!(watches.identity.has_changed().unwrap());
|
||||
assert!(watches.identity.borrow_and_update().is_none());
|
||||
}
|
||||
|
||||
/// A connection outlives the connector that made it (a session handed out
|
||||
/// by a connector that was dropped): its watches keep their senders.
|
||||
#[test]
|
||||
fn a_connection_keeps_the_account_open_when_its_link_is_gone() {
|
||||
let link = TsLink::new();
|
||||
let watches = link.account().watches();
|
||||
drop(link);
|
||||
assert!(watches.identity.has_changed().is_ok(), "the identity watch lost its sender");
|
||||
assert!(watches.data.has_changed().is_ok(), "the data watch lost its sender");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,537 @@
|
||||
//! The TeamSpeak connection's presence as v1 entities (protocol section
|
||||
//! 11.1, "Ids and entities"): the client's older model on one side, the
|
||||
//! protocol's `Server`, `Channel`, `Role`, `User`, `Member`, `Presence` and
|
||||
//! `VoiceState` on the other.
|
||||
//!
|
||||
//! [`build`] is the translation the TeamSpeak `Session` makes of every
|
||||
//! snapshot its link reports; the engine's projection (`link/project.rs`)
|
||||
//! is its reverse, and `docs/session-seam.md` section 5.1 states the rule
|
||||
//! both keep: projecting what was built gives back the snapshot (up to the
|
||||
//! normalisations of section 5.4). What v1 has no field for rides in
|
||||
//! [`Foreign`](v1::Foreign) under [`FOREIGN_SYSTEM`].
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
|
||||
use serde_json::json;
|
||||
use voelin_model::replica::Key;
|
||||
use voelin_model::{
|
||||
BannerMode, ChannelId, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType,
|
||||
HostMessageMode, Presence, ServerDetails,
|
||||
};
|
||||
use voelin_proto::v1::{self, Entity, entity::Kind};
|
||||
|
||||
use super::ids::{self, FOREIGN_SYSTEM, SERVER_CHAT, SERVER_ID};
|
||||
|
||||
/// Entities by key, as a scope holds them.
|
||||
pub(crate) type Layer = BTreeMap<Key, Entity>;
|
||||
|
||||
/// The entities one snapshot stands for, by scope.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Built {
|
||||
/// SERVER (1): the server, its channels and its roles.
|
||||
pub server: Layer,
|
||||
/// LIVE (1): who is online and where.
|
||||
pub live: Layer,
|
||||
/// The own user, for HOME, when the snapshot holds our client.
|
||||
pub own_user: Option<v1::User>,
|
||||
/// Clients by unique id: their user id and participant id.
|
||||
pub by_uid: HashMap<String, (u64, u32)>,
|
||||
}
|
||||
|
||||
/// The `Foreign` of something v1 has no field for.
|
||||
pub(crate) fn foreign(kind: &str, json: &serde_json::Value) -> v1::Foreign {
|
||||
v1::Foreign {
|
||||
system: FOREIGN_SYSTEM.into(),
|
||||
kind: kind.into(),
|
||||
json: serde_json::to_vec(json).unwrap_or_default().into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn entity(kind: Kind) -> Entity {
|
||||
Entity { kind: Some(kind) }
|
||||
}
|
||||
|
||||
/// A picture known by its id (an icon CRC).
|
||||
fn icon(id: u32) -> Option<v1::Image> {
|
||||
(id != 0).then(|| v1::Image { hash: id.to_string(), ..Default::default() })
|
||||
}
|
||||
|
||||
fn banner_mode(mode: BannerMode) -> v1::BannerMode {
|
||||
match mode {
|
||||
BannerMode::NoAdjust => v1::BannerMode::NoAdjust,
|
||||
BannerMode::IgnoreAspect => v1::BannerMode::IgnoreAspect,
|
||||
BannerMode::KeepAspect => v1::BannerMode::KeepAspect,
|
||||
}
|
||||
}
|
||||
|
||||
fn host_message_mode(mode: HostMessageMode) -> v1::HostMessageMode {
|
||||
match mode {
|
||||
HostMessageMode::None => v1::HostMessageMode::None,
|
||||
HostMessageMode::Log => v1::HostMessageMode::Log,
|
||||
HostMessageMode::Modal => v1::HostMessageMode::Modal,
|
||||
HostMessageMode::ModalQuit => v1::HostMessageMode::ModalQuit,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `Server` entity of a connection.
|
||||
pub(crate) fn server(details: &ServerDetails, name: &str, default_channel: u64) -> v1::Server {
|
||||
let gfx =
|
||||
|url: &str| (!url.is_empty()).then(|| v1::Image { url: url.into(), ..Default::default() });
|
||||
let banner = (!details.banner_url.is_empty()
|
||||
|| !details.banner_gfx_url.is_empty()
|
||||
|| details.banner_gfx_interval_s != 0
|
||||
|| details.banner_mode != BannerMode::NoAdjust)
|
||||
.then(|| v1::Banner {
|
||||
image: gfx(&details.banner_gfx_url),
|
||||
link: details.banner_url.clone(),
|
||||
reload_s: u32::try_from(details.banner_gfx_interval_s).unwrap_or(u32::MAX),
|
||||
mode: banner_mode(details.banner_mode) as i32,
|
||||
});
|
||||
let host_button = (!details.host_button_tooltip.is_empty()
|
||||
|| !details.host_button_url.is_empty()
|
||||
|| !details.host_button_gfx_url.is_empty())
|
||||
.then(|| v1::HostButton {
|
||||
tooltip: details.host_button_tooltip.clone(),
|
||||
url: details.host_button_url.clone(),
|
||||
icon: gfx(&details.host_button_gfx_url),
|
||||
});
|
||||
v1::Server {
|
||||
id: SERVER_ID,
|
||||
name: name.to_owned(),
|
||||
icon: icon(details.icon),
|
||||
banner,
|
||||
host_button,
|
||||
welcome: details.welcome_message.clone(),
|
||||
host_message: details.host_message.clone(),
|
||||
host_message_mode: host_message_mode(details.host_message_mode) as i32,
|
||||
default_channel_id: default_channel,
|
||||
default_role_id: details.default_server_group.unwrap_or(0),
|
||||
default_channel_role_id: details.default_channel_group.map_or(0, ids::channel_role),
|
||||
priority_dim_db: details.priority_speaker_dimm_db,
|
||||
max_members: u32::from(details.max_clients),
|
||||
uid: details.uid.as_deref().map(|uid| format!("ts:{uid}")).unwrap_or_default(),
|
||||
foreign: Some(foreign(
|
||||
"server",
|
||||
&json!({ "platform": details.platform, "version": details.version }),
|
||||
)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The server group or channel group `info` as a role.
|
||||
fn role(info: &GroupInfo, channel: bool) -> v1::Role {
|
||||
v1::Role {
|
||||
id: if channel { ids::channel_role(info.id) } else { info.id },
|
||||
server_id: SERVER_ID,
|
||||
name: info.name.clone(),
|
||||
icon: icon(info.icon),
|
||||
position: info.sort_id.saturating_neg(),
|
||||
scope: if channel { v1::RoleScope::Channel } else { v1::RoleScope::Server } as i32,
|
||||
name_mode: match info.naming_mode {
|
||||
GroupNamingMode::None => v1::NameMode::None,
|
||||
GroupNamingMode::Before => v1::NameMode::Before,
|
||||
GroupNamingMode::After => v1::NameMode::After,
|
||||
} as i32,
|
||||
kind: match info.group_type {
|
||||
GroupType::Template => v1::RoleKind::Template,
|
||||
GroupType::Regular => v1::RoleKind::Regular,
|
||||
GroupType::Query => v1::RoleKind::Query,
|
||||
} as i32,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The sibling chain of each parent as positions: `order` names the sibling
|
||||
/// above, so the chain is followed from 0; siblings that no chain reaches
|
||||
/// (a snapshot with broken orders) follow by id.
|
||||
fn positions(channels: &BTreeMap<ChannelId, ChannelInfo>) -> HashMap<ChannelId, i64> {
|
||||
let mut by_parent: BTreeMap<ChannelId, Vec<&ChannelInfo>> = BTreeMap::new();
|
||||
for channel in channels.values() {
|
||||
by_parent.entry(channel.parent).or_default().push(channel);
|
||||
}
|
||||
let mut positions = HashMap::new();
|
||||
for siblings in by_parent.values() {
|
||||
let mut placed: HashSet<ChannelId> = HashSet::new();
|
||||
let mut next = 0;
|
||||
let mut above = 0;
|
||||
// The sibling whose `order` is the one placed last (lowest id first, so
|
||||
// that two claiming the same place do not depend on map order).
|
||||
while let Some(channel) = siblings
|
||||
.iter()
|
||||
.filter(|c| c.order == above && !placed.contains(&c.id))
|
||||
.min_by_key(|c| c.id)
|
||||
{
|
||||
positions.insert(channel.id, next * 1024);
|
||||
placed.insert(channel.id);
|
||||
above = channel.id;
|
||||
next += 1;
|
||||
}
|
||||
for channel in siblings.iter().filter(|c| !placed.contains(&c.id)) {
|
||||
positions.insert(channel.id, next * 1024);
|
||||
next += 1;
|
||||
}
|
||||
}
|
||||
positions
|
||||
}
|
||||
|
||||
fn channel(info: &ChannelInfo, position: i64) -> v1::Channel {
|
||||
let mut needed = HashMap::new();
|
||||
if info.needed_talk_power != 0 {
|
||||
needed.insert(v1::Power::Talk as u32, info.needed_talk_power);
|
||||
}
|
||||
if info.needed_subscribe_power != 0 {
|
||||
needed.insert(v1::Power::Subscribe as u32, info.needed_subscribe_power);
|
||||
}
|
||||
let banner =
|
||||
(info.banner_gfx_url.is_some() || info.banner_mode != BannerMode::NoAdjust).then(|| {
|
||||
v1::Banner {
|
||||
image: info
|
||||
.banner_gfx_url
|
||||
.as_ref()
|
||||
.map(|url| v1::Image { url: url.clone(), ..Default::default() }),
|
||||
mode: banner_mode(info.banner_mode) as i32,
|
||||
..Default::default()
|
||||
}
|
||||
});
|
||||
v1::Channel {
|
||||
id: info.id,
|
||||
server_id: SERVER_ID,
|
||||
parent_id: info.parent,
|
||||
kind: v1::ChannelKind::Voice as i32,
|
||||
name: info.name.clone(),
|
||||
topic: info.topic.clone().unwrap_or_default(),
|
||||
position,
|
||||
has_password: info.has_password,
|
||||
// A limit of 0 cannot be said with `max_members` (0 is unlimited).
|
||||
max_members: info.max_clients.map_or(0, |n| u32::try_from(n).unwrap_or(0)),
|
||||
needed,
|
||||
icon: icon(info.icon),
|
||||
banner,
|
||||
is_default: info.is_default,
|
||||
foreign: (info.max_clients == Some(0))
|
||||
.then(|| foreign("channel", &json!({ "max_clients": 0 }))),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The user a client is. `Foreign` carries a unique id that is no base64.
|
||||
fn user(client: &ClientInfo, id: u64, ts6: bool) -> v1::User {
|
||||
let uid = client.uid.as_deref().filter(|u| !u.is_empty());
|
||||
let bytes = uid.and_then(ids::uid_bytes);
|
||||
let avatar = (client.avatar.is_some() || client.myts_avatar.is_some()).then(|| v1::Image {
|
||||
hash: client.avatar.clone().unwrap_or_default(),
|
||||
url: client.myts_avatar.clone().unwrap_or_default(),
|
||||
..Default::default()
|
||||
});
|
||||
v1::User {
|
||||
id,
|
||||
uid: bytes.clone().unwrap_or_default().into(),
|
||||
uid_kind: if ts6 { v1::IdKind::Ts6 } else { v1::IdKind::Ts3 } as i32,
|
||||
name: client.nickname.clone(),
|
||||
avatar,
|
||||
badges: client.badges.clone(),
|
||||
country: client.country.clone().unwrap_or_default(),
|
||||
foreign: uid.filter(|_| bytes.is_none()).map(|uid| foreign("user", &json!({ "uid": uid }))),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A user who is on no snapshot (the sender of a message or a poke): its
|
||||
/// unique id and name only. `None` for a unique id with no content.
|
||||
pub(crate) fn bare_user(uid: &str, name: &str, ts6: bool) -> v1::User {
|
||||
user(
|
||||
&ClientInfo { uid: Some(uid.to_owned()), nickname: name.to_owned(), ..Default::default() },
|
||||
ids::synthetic_user(uid),
|
||||
ts6,
|
||||
)
|
||||
}
|
||||
|
||||
/// A user who is on no snapshot and has no unique id (the sender of a poke
|
||||
/// or a message that the link names by its client id only): `id` and name.
|
||||
pub(crate) fn client_user(id: u64, name: &str, ts6: bool) -> v1::User {
|
||||
user(&ClientInfo { nickname: name.to_owned(), ..Default::default() }, id, ts6)
|
||||
}
|
||||
|
||||
/// Everything the snapshot `presence` says, as entities of the scopes of
|
||||
/// server 1. `ts6`: the server is TeamSpeak 6 (the kind of its unique ids).
|
||||
pub(crate) fn build(presence: &Presence, ts6: bool, own_client: Option<u16>) -> Built {
|
||||
let mut built = Built::default();
|
||||
let name =
|
||||
if presence.server.name.is_empty() { &presence.server_name } else { &presence.server.name };
|
||||
let default_channel =
|
||||
presence.channels.values().find(|c| c.is_default).map_or(0, |channel| channel.id);
|
||||
let put = |layer: &mut Layer, kind: Kind| {
|
||||
let entity = entity(kind);
|
||||
if let Some(key) = Key::of(&entity) {
|
||||
layer.insert(key, entity);
|
||||
}
|
||||
};
|
||||
put(&mut built.server, Kind::Server(server(&presence.server, name, default_channel)));
|
||||
put(
|
||||
&mut built.server,
|
||||
Kind::Channel(v1::Channel {
|
||||
id: SERVER_CHAT,
|
||||
server_id: SERVER_ID,
|
||||
kind: v1::ChannelKind::ServerChat as i32,
|
||||
name: "Server chat".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
let positions = positions(&presence.channels);
|
||||
for info in presence.channels.values() {
|
||||
let position = positions.get(&info.id).copied().unwrap_or_default();
|
||||
put(&mut built.server, Kind::Channel(channel(info, position)));
|
||||
}
|
||||
for info in presence.server_groups.values() {
|
||||
put(&mut built.server, Kind::Role(role(info, false)));
|
||||
}
|
||||
for info in presence.channel_groups.values() {
|
||||
put(&mut built.server, Kind::Role(role(info, true)));
|
||||
}
|
||||
// The own client first, then by client id.
|
||||
let mut clients: Vec<&ClientInfo> = presence.clients.values().collect();
|
||||
clients.sort_by_key(|client| (Some(client.id) != own_client, client.id));
|
||||
let mut used: HashSet<u64> = HashSet::new();
|
||||
for client in clients {
|
||||
// The same identity twice on a server has one database id: the own
|
||||
// client keeps it (it must stay the user we are, also while a ghost of
|
||||
// our old connection lingers), else the lower client id; the other is a
|
||||
// user of its own.
|
||||
let uid = client.uid.as_deref().filter(|u| !u.is_empty());
|
||||
let mut id = client.database_id.unwrap_or_else(|| {
|
||||
ids::synthetic_user(&uid.map_or_else(|| format!("client:{}", client.id), str::to_owned))
|
||||
});
|
||||
if !used.insert(id) {
|
||||
id = ids::synthetic_user(&format!("client:{}", client.id));
|
||||
used.insert(id);
|
||||
}
|
||||
let participant = u32::from(client.id);
|
||||
if let Some(uid) = uid {
|
||||
built.by_uid.entry(uid.to_owned()).or_insert((id, participant));
|
||||
}
|
||||
let user = user(client, id, ts6);
|
||||
if Some(client.id) == own_client {
|
||||
built.own_user = Some(user.clone());
|
||||
}
|
||||
put(&mut built.live, Kind::User(user));
|
||||
put(
|
||||
&mut built.live,
|
||||
Kind::Member(v1::Member {
|
||||
server_id: SERVER_ID,
|
||||
user_id: id,
|
||||
roles: client.server_groups.clone(),
|
||||
channel_roles: client
|
||||
.channel_group
|
||||
.map(|group| (client.channel, ids::channel_role(group)))
|
||||
.into_iter()
|
||||
.collect(),
|
||||
description: client.description.clone().unwrap_or_default(),
|
||||
foreign: (client.icon != 0)
|
||||
.then(|| foreign("client", &json!({ "icon": client.icon }))),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
put(
|
||||
&mut built.live,
|
||||
Kind::Presence(v1::Presence {
|
||||
user_id: id,
|
||||
status: if client.away.is_some() { v1::Status::Idle } else { v1::Status::Online }
|
||||
as i32,
|
||||
text: client.away.clone().unwrap_or_default(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
put(
|
||||
&mut built.live,
|
||||
Kind::Voice(v1::VoiceState {
|
||||
server_id: SERVER_ID,
|
||||
participant_id: participant,
|
||||
user_id: id,
|
||||
channel_id: client.channel,
|
||||
slot: slot(client.id),
|
||||
nick: client.nickname.clone(),
|
||||
kind: if client.is_query {
|
||||
v1::ParticipantKind::Query
|
||||
} else {
|
||||
v1::ParticipantKind::User
|
||||
} as i32,
|
||||
self_mute: client.input_muted,
|
||||
self_deaf: client.output_muted,
|
||||
priority_speaker: client.priority_speaker,
|
||||
channel_commander: client.channel_commander,
|
||||
talker: client.talker,
|
||||
talk_power: client.talk_power,
|
||||
recording: client.recording,
|
||||
streaming: client.streaming.unwrap_or(false),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
}
|
||||
built
|
||||
}
|
||||
|
||||
/// The unique id of a user as the client's older model writes it: base64 for
|
||||
/// a TeamSpeak id, or the text kept in `Foreign` when it was no base64 (a
|
||||
/// ServerQuery client's login name). `None` for a user without one.
|
||||
pub(crate) fn user_uid(user: &v1::User) -> Option<String> {
|
||||
let kept = user
|
||||
.foreign
|
||||
.as_ref()
|
||||
.filter(|f| f.system == FOREIGN_SYSTEM && f.kind == "user")
|
||||
.and_then(|f| serde_json::from_slice::<serde_json::Value>(&f.json).ok())
|
||||
.and_then(|json| json.get("uid")?.as_str().map(str::to_owned));
|
||||
kept.or_else(|| voelin_model::replica::convert::uid_text(user))
|
||||
}
|
||||
|
||||
/// The media slot of a client: its id plus one (slot 0 is not a media source).
|
||||
pub(crate) fn slot(client: u16) -> u32 {
|
||||
u32::from(client) + 1
|
||||
}
|
||||
|
||||
/// The key of an entity, as a `Change` deletes it: the key fields only.
|
||||
pub(crate) fn key_only(entity: &Entity) -> Entity {
|
||||
let kind = match entity.kind.as_ref() {
|
||||
Some(Kind::Server(s)) => Kind::Server(v1::Server { id: s.id, ..Default::default() }),
|
||||
Some(Kind::Channel(c)) => Kind::Channel(v1::Channel { id: c.id, ..Default::default() }),
|
||||
Some(Kind::Role(r)) => {
|
||||
Kind::Role(v1::Role { server_id: r.server_id, id: r.id, ..Default::default() })
|
||||
}
|
||||
Some(Kind::Member(m)) => Kind::Member(v1::Member {
|
||||
server_id: m.server_id,
|
||||
user_id: m.user_id,
|
||||
..Default::default()
|
||||
}),
|
||||
Some(Kind::User(u)) => Kind::User(v1::User { id: u.id, ..Default::default() }),
|
||||
Some(Kind::Presence(p)) => {
|
||||
Kind::Presence(v1::Presence { user_id: p.user_id, ..Default::default() })
|
||||
}
|
||||
Some(Kind::Voice(v)) => Kind::Voice(v1::VoiceState {
|
||||
server_id: v.server_id,
|
||||
participant_id: v.participant_id,
|
||||
..Default::default()
|
||||
}),
|
||||
Some(Kind::Message(m)) => {
|
||||
Kind::Message(v1::Message { channel_id: m.channel_id, id: m.id, ..Default::default() })
|
||||
}
|
||||
Some(Kind::Mail(m)) => Kind::Mail(v1::Mail { id: m.id, ..Default::default() }),
|
||||
_ => return entity.clone(),
|
||||
};
|
||||
Entity { kind: Some(kind) }
|
||||
}
|
||||
|
||||
/// What changed from `old` to `new`: the entities to put (new or different)
|
||||
/// and the keys to delete.
|
||||
pub(crate) fn diff(old: &Layer, new: &Layer) -> (Vec<Entity>, Vec<Entity>) {
|
||||
let put = new.iter().filter(|(key, entity)| old.get(*key) != Some(*entity));
|
||||
let del = old.iter().filter(|(key, _)| !new.contains_key(*key));
|
||||
(put.map(|(_, e)| e.clone()).collect(), del.map(|(_, e)| key_only(e)).collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn channel_info(id: u64, parent: u64, order: u64) -> ChannelInfo {
|
||||
ChannelInfo { id, parent, order, name: format!("c{id}"), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_order_chain_becomes_positions() {
|
||||
// 3 first, then 1, then 2 under the same parent; 5 alone under 3.
|
||||
let channels: BTreeMap<_, _> = [
|
||||
channel_info(1, 0, 3),
|
||||
channel_info(2, 0, 1),
|
||||
channel_info(3, 0, 0),
|
||||
channel_info(5, 3, 0),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|c| (c.id, c))
|
||||
.collect();
|
||||
let positions = positions(&channels);
|
||||
assert!(positions[&3] < positions[&1] && positions[&1] < positions[&2]);
|
||||
assert_eq!(positions[&5], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn siblings_a_chain_does_not_reach_follow_by_id() {
|
||||
// Both claim the first place, and 4 follows nobody.
|
||||
let channels: BTreeMap<_, _> =
|
||||
[channel_info(1, 0, 0), channel_info(2, 0, 0), channel_info(4, 0, 77)]
|
||||
.into_iter()
|
||||
.map(|c| (c.id, c))
|
||||
.collect();
|
||||
let positions = positions(&channels);
|
||||
assert_eq!((positions[&1], positions[&2], positions[&4]), (0, 1024, 2048));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_identity_twice_keeps_both_clients() {
|
||||
let client = |id, db| ClientInfo {
|
||||
id,
|
||||
uid: Some("uXDkxSZbv0IoA0z/toW3guGpUbI=".into()),
|
||||
nickname: format!("n{id}"),
|
||||
database_id: Some(db),
|
||||
..Default::default()
|
||||
};
|
||||
let mut presence = Presence::default();
|
||||
for c in [client(3, 77), client(4, 77)] {
|
||||
presence.clients.insert(c.id, c);
|
||||
}
|
||||
let built = build(&presence, false, None);
|
||||
let voices = built.live.keys().filter(|k| matches!(k, Key::Voice { .. })).count();
|
||||
let users = built.live.keys().filter(|k| matches!(k, Key::User { .. })).count();
|
||||
assert_eq!((voices, users), (2, 2));
|
||||
}
|
||||
|
||||
/// The own client is the user whose database id the identity has, also when a
|
||||
/// ghost of the old connection (the lower client id) lingers.
|
||||
#[test]
|
||||
fn the_own_client_keeps_the_database_id_of_an_identity_that_is_there_twice() {
|
||||
let client = |id| ClientInfo {
|
||||
id,
|
||||
uid: Some("uXDkxSZbv0IoA0z/toW3guGpUbI=".into()),
|
||||
nickname: format!("n{id}"),
|
||||
database_id: Some(77),
|
||||
..Default::default()
|
||||
};
|
||||
let mut presence = Presence::default();
|
||||
for c in [client(3), client(4)] {
|
||||
presence.clients.insert(c.id, c);
|
||||
}
|
||||
let user_of = |built: &Built, client: u32| {
|
||||
let key = Key::Voice { server_id: SERVER_ID, participant_id: client };
|
||||
let Some(Entity { kind: Some(Kind::Voice(voice)) }) = built.live.get(&key) else {
|
||||
panic!("no voice state")
|
||||
};
|
||||
voice.user_id
|
||||
};
|
||||
// Nobody is us: the lower client id keeps it.
|
||||
let built = build(&presence, false, None);
|
||||
assert_eq!(user_of(&built, 3), 77);
|
||||
assert_ne!(user_of(&built, 4), 77);
|
||||
// The later client is us: it keeps it, and the ghost has the made-up id.
|
||||
let built = build(&presence, false, Some(4));
|
||||
assert_eq!(user_of(&built, 4), 77);
|
||||
assert_ne!(user_of(&built, 3), 77);
|
||||
assert_eq!(built.own_user.map(|u| u.id), Some(77));
|
||||
assert_eq!(built.by_uid["uXDkxSZbv0IoA0z/toW3guGpUbI="], (77, 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_deletes_by_key_and_puts_what_differs() {
|
||||
let mut presence = Presence::default();
|
||||
presence.channels.insert(1, channel_info(1, 0, 0));
|
||||
let before = build(&presence, false, None);
|
||||
presence.channels.insert(2, channel_info(2, 0, 1));
|
||||
presence.channels.get_mut(&1).unwrap().name = "renamed".into();
|
||||
let after = build(&presence, false, None);
|
||||
let (put, del) = diff(&before.server, &after.server);
|
||||
assert_eq!(put.len(), 2, "the renamed channel and the new one");
|
||||
assert!(del.is_empty());
|
||||
let (put, del) = diff(&after.server, &before.server);
|
||||
assert_eq!(put.len(), 1, "channel 1 is back to its old name");
|
||||
assert_eq!(del.len(), 1);
|
||||
let Some(Kind::Channel(gone)) = &del[0].kind else { panic!("a channel") };
|
||||
assert_eq!((gone.id, gone.name.as_str()), (2, ""));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//! Ids and unique ids as the TeamSpeak gateway writes them (protocol
|
||||
//! section 11.1, "Ids"): TeamSpeak's numbers as they are, and a few
|
||||
//! synthetic ones with bit 63 set.
|
||||
//!
|
||||
//! Both sides of the seam use these rules: the TeamSpeak `Session`
|
||||
//! ([`super::LinkSession`]) writes entities with them, and the engine's
|
||||
//! projection (`link/project.rs`) undoes the few that the client's older
|
||||
//! model has no room for.
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
|
||||
/// The only server of a TeamSpeak connection (its virtual server).
|
||||
pub(crate) const SERVER_ID: u64 = 1;
|
||||
|
||||
/// Marks the ids the gateway makes up: the server chat, direct-message
|
||||
/// channels and users it knows by their unique id only.
|
||||
pub(crate) const SYNTHETIC: u64 = 1 << 63;
|
||||
|
||||
/// The channel of the server chat, in the SERVER scope.
|
||||
pub(crate) const SERVER_CHAT: u64 = SYNTHETIC;
|
||||
|
||||
/// Set on the id of a channel group, so that a role id does not mean a server
|
||||
/// group and a channel group at once.
|
||||
pub(crate) const CHANNEL_ROLE: u64 = 1 << 62;
|
||||
|
||||
/// The `Foreign.system` of what the protocol has no field for.
|
||||
pub(crate) const FOREIGN_SYSTEM: &str = "teamspeak";
|
||||
|
||||
/// The role id of a channel group.
|
||||
pub(crate) fn channel_role(group: u64) -> u64 {
|
||||
group | CHANNEL_ROLE
|
||||
}
|
||||
|
||||
/// The channel group a role id stands for (the reverse of [`channel_role`]).
|
||||
pub(crate) fn channel_group(role: u64) -> u64 {
|
||||
role & !CHANNEL_ROLE
|
||||
}
|
||||
|
||||
/// FNV-1a, 64 bits.
|
||||
fn fnv1a(bytes: &[u8]) -> u64 {
|
||||
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for byte in bytes {
|
||||
hash ^= u64::from(*byte);
|
||||
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
hash
|
||||
}
|
||||
|
||||
/// A synthetic id for something known by a name only: bit 63 set and the
|
||||
/// hash of `name` in the low 63 bits (1 if they come out 0, so it is never
|
||||
/// [`SERVER_CHAT`]).
|
||||
fn synthetic(name: &str) -> u64 {
|
||||
let low = fnv1a(name.as_bytes()) & !SYNTHETIC;
|
||||
SYNTHETIC | low.max(1)
|
||||
}
|
||||
|
||||
/// The direct-message channel with the client of this unique id.
|
||||
pub(crate) fn dm_channel(uid: &str) -> u64 {
|
||||
synthetic(uid)
|
||||
}
|
||||
|
||||
/// The user id of a client that has no database id (or that the snapshot
|
||||
/// does not hold): by unique id, else by whatever names it.
|
||||
pub(crate) fn synthetic_user(uid: &str) -> u64 {
|
||||
synthetic(uid)
|
||||
}
|
||||
|
||||
/// The bytes of a unique id, when it is canonical base64 (what TeamSpeak
|
||||
/// writes): decoding and encoding again gives the same text. A ServerQuery
|
||||
/// client's login name, or anything else, is not, and goes into
|
||||
/// [`Foreign`](voelin_proto::v1::Foreign) instead.
|
||||
pub(crate) fn uid_bytes(uid: &str) -> Option<Vec<u8>> {
|
||||
let bytes = STANDARD.decode(uid).ok()?;
|
||||
(STANDARD.encode(&bytes) == uid && !bytes.is_empty()).then_some(bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn channel_groups_keep_their_number_below_the_flag() {
|
||||
assert_eq!(channel_role(8), 8 | (1 << 62));
|
||||
assert_eq!(channel_group(channel_role(8)), 8);
|
||||
assert_eq!(channel_group(channel_role(0)), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthetic_ids_have_bit_63_and_are_never_the_server_chat() {
|
||||
for name in ["", "alice=", "client:7", "a-very-long-name-that-hashes-to-something"] {
|
||||
let id = dm_channel(name);
|
||||
assert_ne!(id & SYNTHETIC, 0, "{name}");
|
||||
assert_ne!(id, SERVER_CHAT, "{name}");
|
||||
}
|
||||
assert_eq!(dm_channel("alice="), dm_channel("alice="));
|
||||
assert_ne!(dm_channel("alice="), dm_channel("bob="));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_canonical_base64_is_a_unique_id() {
|
||||
// A TeamSpeak 3 unique id (SHA-1) and a TeamSpeak 6 one (SHA-256).
|
||||
assert_eq!(uid_bytes("uXDkxSZbv0IoA0z/toW3guGpUbI=").map(|b| b.len()), Some(20));
|
||||
assert_eq!(
|
||||
uid_bytes("xEZDkyeGdZ4bOSBCKqzTw8jVz2jsZCrJDRl9F8WWd3M=").map(|b| b.len()),
|
||||
Some(32)
|
||||
);
|
||||
// A ServerQuery login name, a fixture's name, the empty string.
|
||||
for not in ["serveradmin", "alice=", "me=", "", "Af4"] {
|
||||
assert_eq!(uid_bytes(not), None, "{not:?}");
|
||||
}
|
||||
// Non-canonical trailing bits decode but do not round trip.
|
||||
assert_eq!(uid_bytes("Af5="), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,862 @@
|
||||
//! The TeamSpeak `Session` against the development servers
|
||||
//! (`dev/docker-compose.yml`; `docs/session-seam.md` sections 9.3 and 16).
|
||||
//! Runs only with `VOELIN_LIVE=1`:
|
||||
//!
|
||||
//! ```text
|
||||
//! VOELIN_LIVE=1 cargo test -p voelin-core --lib ts_session::live_tests -- --test-threads=1
|
||||
//! ```
|
||||
//!
|
||||
//! Two kinds of test, each on TeamSpeak 3 and on TeamSpeak 6:
|
||||
//!
|
||||
//! - the link conformance suite of the protocol repository, the cases that
|
||||
//! apply to a TeamSpeak session, with the verdict of every case asserted
|
||||
//! and the reason of every case that cannot pass or cannot run in
|
||||
//! [`EXPECTED`];
|
||||
//! - what the suite cannot reach, as a session of its own does it: a message
|
||||
//! in the own channel answered, then pushed to the other session and back to
|
||||
//! ours, the refusals of a move, a poke between two sessions, voice RTP from
|
||||
//! one session's slot to the other's media sink, and a channel file written
|
||||
//! and read back from an offset.
|
||||
//!
|
||||
//! The sessions are made by [`TsConnector`] through the plain `Connector`
|
||||
//! interface, as a client of the seam outside an engine would make them.
|
||||
//!
|
||||
//! The servers ban an address that connects as often as these tests do
|
||||
//! (`ConnectFailedBanned` after three or four connections) unless their
|
||||
//! anti-flood limits are raised first. `scripts/it-smoke.sh` raises them when it
|
||||
//! prepares its admin identity; this module raises them itself, once per server
|
||||
//! and run, through the ServerQuery admin login that `refused_moves` uses
|
||||
//! ([`raise_flood_limits`]), so that the command above works on a freshly
|
||||
//! started stack. It needs that login (the development servers of
|
||||
//! `dev/docker-compose.yml` have it) and does not lower the limits again.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::sync::mpsc;
|
||||
use voelin_proto::link::{Connector, FlowId, MediaClass, MediaPacket, voice_sub};
|
||||
use voelin_proto::media::payload::PT_OPUS;
|
||||
use voelin_proto::media::{RtpHeader, RtpView};
|
||||
use voelin_proto::test_util::conformance::{self, Fixture, Verdict};
|
||||
use voelin_proto::test_util::{FakeConnector, MediaReceiver, media_channel};
|
||||
use voelin_proto::v1::request::Op;
|
||||
use voelin_proto::v1::{self, entity::Kind};
|
||||
|
||||
use super::*;
|
||||
use crate::link::{Backends, VoiceOptions, connect_params};
|
||||
|
||||
fn live() -> bool {
|
||||
std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1")
|
||||
}
|
||||
|
||||
/// How long a test waits for the server.
|
||||
const WAIT: Duration = Duration::from_secs(20);
|
||||
|
||||
async fn within<T>(what: &str, future: impl Future<Output = T>) -> T {
|
||||
match tokio::time::timeout(WAIT, future).await {
|
||||
Ok(value) => value,
|
||||
Err(_) => panic!("timed out after {WAIT:?} waiting for {what}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A development server: where to connect, and how to ask it as the admin.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Dev {
|
||||
name: &'static str,
|
||||
voice: &'static str,
|
||||
ssh: bool,
|
||||
query: &'static str,
|
||||
}
|
||||
|
||||
const TS3: Dev = Dev { name: "ts3", voice: "127.0.0.1:9987", ssh: false, query: "127.0.0.1:10011" };
|
||||
const TS6: Dev = Dev { name: "ts6", voice: "127.0.0.1:9988", ssh: true, query: "127.0.0.1:10022" };
|
||||
|
||||
impl Dev {
|
||||
fn query(&self) -> voelin_query::Connect {
|
||||
voelin_query::Connect {
|
||||
transport: if self.ssh {
|
||||
voelin_query::Transport::Ssh
|
||||
} else {
|
||||
voelin_query::Transport::Raw
|
||||
},
|
||||
addr: self.query.into(),
|
||||
user: "serveradmin".into(),
|
||||
secret: Some("voelin-dev-admin".into()),
|
||||
server_port: Some(9987),
|
||||
server_id: None,
|
||||
line: voelin_query::LineOptions { rate_limit: None, ..Default::default() },
|
||||
}
|
||||
}
|
||||
|
||||
/// A nickname no other client of this run has.
|
||||
fn nick(&self, role: &str) -> String {
|
||||
static COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
let n = COUNT.fetch_add(1, Ordering::Relaxed);
|
||||
format!("{role}-{}-{n}", std::process::id() % 10_000)
|
||||
}
|
||||
}
|
||||
|
||||
/// Raise the anti-flood limits of a development server, once per run, and
|
||||
/// lift the bans an earlier run left behind. The tests connect many times in
|
||||
/// a few seconds from one address, which a server with its default limits
|
||||
/// bans (`ConnectFailedBanned`); `scripts/it-smoke.sh` sets the same two
|
||||
/// values in `admin_args`. Done through the ServerQuery login of the admin,
|
||||
/// which the tests that create channels and keys use as well.
|
||||
async fn raise_flood_limits(dev: &Dev) {
|
||||
use tokio::sync::OnceCell;
|
||||
use voelin_query::{Command as Query, QueryClient};
|
||||
static TS3_READY: OnceCell<()> = OnceCell::const_new();
|
||||
static TS6_READY: OnceCell<()> = OnceCell::const_new();
|
||||
let ready = if dev.ssh { &TS6_READY } else { &TS3_READY };
|
||||
ready
|
||||
.get_or_init(|| async {
|
||||
let (admin, _) = within("the query login", QueryClient::connect(&dev.query()))
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("the query login of {}: {e}", dev.name));
|
||||
for key in [
|
||||
"virtualserver_antiflood_points_needed_ip_block",
|
||||
"virtualserver_antiflood_points_needed_command_block",
|
||||
] {
|
||||
let edit = Query::new("serveredit").arg(key, 100_000);
|
||||
within("the anti-flood limits", admin.send(&edit))
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("{} refused {key}: {e}", dev.name));
|
||||
}
|
||||
// A ban of an earlier run outlives the change of the limit.
|
||||
within("the ban list", admin.send(&Query::new("bandelall")))
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("{} did not lift its bans: {e}", dev.name));
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// A TeamSpeak session as a client of the seam sees it: made by the
|
||||
/// connector, with its push channel and media sink.
|
||||
async fn session(
|
||||
dev: &Dev,
|
||||
options: &VoiceOptions,
|
||||
) -> (Arc<dyn Session>, mpsc::Receiver<v1::Push>, MediaReceiver) {
|
||||
raise_flood_limits(dev).await;
|
||||
let (sink, media) = media_channel();
|
||||
let params = connect_params(options, sink, &Backends::empty()).expect("connect parameters");
|
||||
let connected =
|
||||
within(&format!("a connection to {}", dev.name), TsConnector::new().connect(params))
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("{} did not connect: {e}", dev.name));
|
||||
(connected.session, connected.pushes, media)
|
||||
}
|
||||
|
||||
/// A client of the TeamSpeak session that has done what an engine does after
|
||||
/// it connects (`docs/session-seam.md` 4.2, without the replica): the server
|
||||
/// listed, HOME, SERVER and LIVE subscribed and synced, a seat in voice.
|
||||
struct Client {
|
||||
session: Arc<dyn Session>,
|
||||
pushes: mpsc::Receiver<v1::Push>,
|
||||
media: MediaReceiver,
|
||||
server: u64,
|
||||
default_channel: u64,
|
||||
/// Our seat in voice (participant, slot, channel).
|
||||
seat: v1::VoiceState,
|
||||
/// The voice states of the server, as the pushes told them.
|
||||
voices: BTreeMap<u32, v1::VoiceState>,
|
||||
}
|
||||
|
||||
fn scope(kind: v1::ScopeKind, id: u64) -> v1::Scope {
|
||||
v1::Scope { kind: kind as i32, id }
|
||||
}
|
||||
|
||||
impl Client {
|
||||
async fn connect(dev: &Dev, nick: &str) -> Self {
|
||||
Self::connect_with(dev, VoiceOptions::new(dev.voice, nick)).await
|
||||
}
|
||||
|
||||
async fn connect_with(dev: &Dev, options: VoiceOptions) -> Self {
|
||||
let (session, pushes, media) = session(dev, &options).await;
|
||||
let mut client = Self {
|
||||
session,
|
||||
pushes,
|
||||
media,
|
||||
server: 0,
|
||||
default_channel: 0,
|
||||
seat: v1::VoiceState::default(),
|
||||
voices: BTreeMap::new(),
|
||||
};
|
||||
let list = Op::List(v1::List { kind: v1::EntityKind::Server as i32, ..Default::default() });
|
||||
let Answer::Entities(servers) = client.ask(list).await.expect("the server list") else {
|
||||
panic!("the server list is not entities")
|
||||
};
|
||||
let server = servers
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|e| match &e.kind {
|
||||
Some(Kind::Server(server)) => Some(server.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the host lists its server");
|
||||
client.server = server.id;
|
||||
client.default_channel = server.default_channel_id;
|
||||
for scope in [
|
||||
scope(v1::ScopeKind::Home, 0),
|
||||
scope(v1::ScopeKind::Server, server.id),
|
||||
scope(v1::ScopeKind::Live, server.id),
|
||||
] {
|
||||
client.subscribe(scope).await;
|
||||
}
|
||||
client.seat = client.join(client.default_channel, "").await.expect("a seat in voice");
|
||||
client.settle().await;
|
||||
client
|
||||
}
|
||||
|
||||
/// A request, answered within [`WAIT`].
|
||||
async fn ask(&self, op: Op) -> Result<Answer, SessionError> {
|
||||
within("an answer", self.session.request(op)).await
|
||||
}
|
||||
|
||||
/// Subscribe `scope` and take its sync off the push channel.
|
||||
async fn subscribe(&mut self, scope: v1::Scope) {
|
||||
let op = Op::Subscribe(v1::Subscribe { scope: Some(scope), ..Default::default() });
|
||||
self.ask(op).await.expect("a subscription");
|
||||
self.until("the end of the sync", |push| match &push.body {
|
||||
Some(v1::push::Body::SyncEnd(end)) if end.scope == Some(scope) => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// `JoinVoice`: our seat, or why not.
|
||||
async fn join(&self, channel: u64, password: &str) -> Result<v1::VoiceState, SessionError> {
|
||||
let join = v1::JoinVoice {
|
||||
server_id: self.server,
|
||||
channel_id: channel,
|
||||
password: password.into(),
|
||||
..Default::default()
|
||||
};
|
||||
match self.ask(Op::JoinVoice(join)).await? {
|
||||
Answer::Entities(entities) => entities
|
||||
.items
|
||||
.into_iter()
|
||||
.find_map(|e| match e.kind {
|
||||
Some(Kind::Voice(voice)) => Some(voice),
|
||||
_ => None,
|
||||
})
|
||||
.ok_or_else(|| SessionError::Protocol("no voice state in the answer".into())),
|
||||
other => Err(SessionError::Protocol(format!("unexpected answer {other:?}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep track of what a push says about the server and its voice states.
|
||||
fn absorb(&mut self, push: &v1::Push) {
|
||||
let Some(v1::push::Body::Change(change)) = &push.body else { return };
|
||||
for entity in &change.put {
|
||||
match &entity.kind {
|
||||
Some(Kind::Voice(voice)) => {
|
||||
self.voices.insert(voice.participant_id, voice.clone());
|
||||
}
|
||||
Some(Kind::Server(server)) if server.default_channel_id != 0 => {
|
||||
self.default_channel = server.default_channel_id;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for entity in &change.del {
|
||||
if let Some(Kind::Voice(voice)) = &entity.kind {
|
||||
self.voices.remove(&voice.participant_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The next push `f` picks, skipping (and keeping track of) the others.
|
||||
async fn until<T>(&mut self, what: &str, mut f: impl FnMut(&v1::Push) -> Option<T>) -> T {
|
||||
within(what, async {
|
||||
loop {
|
||||
let push = self.pushes.recv().await.expect("the session lives");
|
||||
self.absorb(&push);
|
||||
if let Some(t) = f(&push) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Wait until the host shows our seat in LIVE: the first snapshot of the
|
||||
/// TeamSpeak link may come after the session was handed out, so the syncs
|
||||
/// can be empty and the voice states follow as changes. The seat then
|
||||
/// names the channel we are in.
|
||||
async fn settle(&mut self) {
|
||||
let participant = self.seat.participant_id;
|
||||
within("our voice state to appear", async {
|
||||
while !self.voices.contains_key(&participant) {
|
||||
let push = self.pushes.recv().await.expect("the session lives");
|
||||
self.absorb(&push);
|
||||
}
|
||||
})
|
||||
.await;
|
||||
self.seat = self.voices[&participant].clone();
|
||||
}
|
||||
|
||||
/// The next message `Change` of the CHAT scope of `channel` with `text`.
|
||||
async fn message(&mut self, channel: u64, text: &str) -> v1::Message {
|
||||
let chat = Some(scope(v1::ScopeKind::Chat, channel));
|
||||
self.until(&format!("the message {text:?}"), |push| match &push.body {
|
||||
Some(v1::push::Body::Change(change)) if change.scope == chat => {
|
||||
change.put.iter().find_map(|e| match &e.kind {
|
||||
Some(Kind::Message(message)) if message.text == text => Some(message.clone()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn close(self) {
|
||||
self.session.close(v1::CloseCode::Normal, "");
|
||||
within("the session to close", self.session.closed()).await;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the conformance suite ----------------------------------------------------
|
||||
|
||||
/// What a case is expected to do against a TeamSpeak session, and why.
|
||||
enum Expect {
|
||||
/// Every assertion of the case holds.
|
||||
Passes,
|
||||
/// The session lacks the feature the case needs (`Verdict::Skipped`).
|
||||
Skipped(&'static str),
|
||||
/// The case does not apply: it cannot run, or cannot pass, for this reason
|
||||
/// (`cases_that_do_not_apply_fail` runs them and watches them fail).
|
||||
NotRun(&'static str),
|
||||
}
|
||||
use Expect::{NotRun, Passes, Skipped};
|
||||
|
||||
/// Every case of the suite of the protocol repository at `c8e0e5a`, in its
|
||||
/// order, with what a TeamSpeak session does with it. A case the suite gains
|
||||
/// fails `the_suite_is_known` until it is listed here.
|
||||
///
|
||||
/// The suite is written for a backend that is a `FakeHost`. A case that needs
|
||||
/// the backend gets the `FakeHandle` of an unrelated fake host, so the cases
|
||||
/// that hold, kill or read it, or push into it, cannot run against a session of
|
||||
/// a TeamSpeak server; the others write to places a TeamSpeak server does not
|
||||
/// have (the suite's channels, a server with another id, `ScheduledEvent`,
|
||||
/// `Emoji`, attachments). Each reason is what the case did when it was run.
|
||||
const EXPECTED: [(&str, Expect); 17] = [
|
||||
("welcome_matches_features", Passes),
|
||||
(
|
||||
"subscribe_syncs_the_scope",
|
||||
NotRun("writes to channel 4001: rejected (NotFound) no such channel"),
|
||||
),
|
||||
(
|
||||
"subscribe_resumes_from_a_cursor",
|
||||
NotRun("writes to channel 4002: rejected (NotFound) no such channel"),
|
||||
),
|
||||
(
|
||||
"put_answers_entities_and_pushes_the_change_with_the_same_rev",
|
||||
NotRun("writes to channel 4003: rejected (NotFound) no such channel"),
|
||||
),
|
||||
(
|
||||
"delete_answers_an_ack_and_pushes_the_removal",
|
||||
NotRun(
|
||||
"writes to channel 4004 first (no such channel); and TeamSpeak cannot delete a message, \
|
||||
where the case needs only `chat`, not `chat.delete` (P8)",
|
||||
),
|
||||
),
|
||||
(
|
||||
"a_key_names_an_entity_without_its_server",
|
||||
NotRun(
|
||||
"rejected (NotFound) no such server; and it creates a ScheduledEvent and an Emoji, \
|
||||
which TeamSpeak lacks, though it needs no feature (P8)",
|
||||
),
|
||||
),
|
||||
("a_stale_rev_conflicts_and_a_patch_writes_only_its_paths", Skipped("chat.edit")),
|
||||
("requests_apply_in_the_order_they_were_issued", Skipped("chat.edit")),
|
||||
("list_pages_history", Skipped("chat.history")),
|
||||
(
|
||||
"cancel_before_apply_is_cancelled",
|
||||
NotRun("holds the unrelated fake host, so the request is answered while it \"holds\""),
|
||||
),
|
||||
("idempotency_keys_apply_a_put_once", Skipped("idempotency")),
|
||||
(
|
||||
"notifications_are_fire_and_forget",
|
||||
NotRun("reads the request log of the unrelated fake host: the notification never arrives"),
|
||||
),
|
||||
(
|
||||
"renew_account_follows_the_feature",
|
||||
NotRun("pushes a HostUpdate into the unrelated fake session's closed push channel"),
|
||||
),
|
||||
(
|
||||
"media_loops_back",
|
||||
NotRun(
|
||||
"a TeamSpeak server does not return a client's own voice: the packet never loops back",
|
||||
),
|
||||
),
|
||||
(
|
||||
"files_round_trip",
|
||||
NotRun(
|
||||
"writes an AttachmentSlot: rejected (Unsupported) attachments are not offered; \
|
||||
TeamSpeak has channel files, and the case needs `files`, not `chat.attachments` (P8)",
|
||||
),
|
||||
),
|
||||
("close_ends_the_session", Passes),
|
||||
(
|
||||
"the_backend_can_end_the_session",
|
||||
NotRun(
|
||||
"kills the unrelated fake session, so closed() of this one never resolves; and a \
|
||||
kick is Network(text), not Remote{KICKED}, until H1",
|
||||
),
|
||||
),
|
||||
];
|
||||
|
||||
/// A fixture on a TeamSpeak session. The suite wants a `FakeHandle` on the
|
||||
/// backend behind the session; a TeamSpeak server has none, so it gets the one
|
||||
/// of an unrelated fake host, which the cases that are run never touch.
|
||||
async fn fixture(dev: Dev) -> Fixture {
|
||||
let (session, pushes, media) =
|
||||
session(&dev, &VoiceOptions::new(dev.voice, dev.nick("conf"))).await;
|
||||
let unrelated = FakeConnector::new();
|
||||
let (params, _media) = voelin_proto::test_util::connect_params("fake://unrelated");
|
||||
unrelated.connect(params).await.expect("a fake session");
|
||||
let backend = unrelated.last_session().expect("a fake session");
|
||||
Fixture::new(session, pushes, media, backend)
|
||||
}
|
||||
|
||||
fn the_suite_is_known() {
|
||||
let known: Vec<_> = EXPECTED.iter().map(|(name, _)| *name).collect();
|
||||
let cases: Vec<_> = conformance::CASES.iter().map(|case| case.name).collect();
|
||||
assert_eq!(known, cases, "the suite changed: list the new cases in EXPECTED");
|
||||
}
|
||||
|
||||
/// The cases that apply run and pass, the ones that need a feature the session
|
||||
/// lacks are skipped, and the rest are not run (their reason is in
|
||||
/// [`EXPECTED`]).
|
||||
async fn conformance_subset(dev: Dev) {
|
||||
the_suite_is_known();
|
||||
let harness = move || fixture(dev);
|
||||
let (mut passed, mut skipped) = (0, 0);
|
||||
for (case, (name, expect)) in conformance::CASES.iter().zip(&EXPECTED) {
|
||||
match expect {
|
||||
Passes => {
|
||||
let verdict = conformance::run_case(&harness, case).await;
|
||||
assert_eq!(verdict, Verdict::Passed, "{name} on {}", dev.name);
|
||||
passed += 1;
|
||||
}
|
||||
Skipped(feature) => {
|
||||
let verdict = conformance::run_case(&harness, case).await;
|
||||
assert_eq!(verdict, Verdict::Skipped(feature), "{name} on {}", dev.name);
|
||||
skipped += 1;
|
||||
}
|
||||
NotRun(reason) => eprintln!("{} {name}: not run: {reason}", dev.name),
|
||||
}
|
||||
}
|
||||
assert_eq!((passed, skipped), (2, 4));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_conformance_subset() {
|
||||
if live() {
|
||||
conformance_subset(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_conformance_subset() {
|
||||
if live() {
|
||||
conformance_subset(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- what the suite cannot reach ----------------------------------------------
|
||||
|
||||
/// A message in the own channel is answered with the message as written, and
|
||||
/// pushed to the CHAT scope of every session in the channel: to the other one
|
||||
/// as a `Change`, and back to ours (the ids agree only with the native
|
||||
/// session of H1: the answer has a local id, the echo the one of the
|
||||
/// `Change`).
|
||||
async fn chat_in_the_own_channel(dev: Dev) {
|
||||
let mut a = Client::connect(&dev, &dev.nick("chat-a")).await;
|
||||
let mut b = Client::connect(&dev, &dev.nick("chat-b")).await;
|
||||
assert_eq!(a.seat.channel_id, b.seat.channel_id, "both sessions are in the default channel");
|
||||
let channel = a.seat.channel_id;
|
||||
a.subscribe(scope(v1::ScopeKind::Chat, channel)).await;
|
||||
b.subscribe(scope(v1::ScopeKind::Chat, channel)).await;
|
||||
|
||||
let text = format!("live-chat-{}", std::process::id());
|
||||
let message = v1::Message { channel_id: channel, text: text.clone(), ..Default::default() };
|
||||
let write = v1::Write {
|
||||
entity: Some(v1::Entity { kind: Some(Kind::Message(message)) }),
|
||||
paths: Vec::new(),
|
||||
};
|
||||
let put = Op::Put(v1::Put { writes: vec![write], ..Default::default() });
|
||||
let Answer::Entities(answer) = a.ask(put).await.expect("the message is accepted") else {
|
||||
panic!("a message is answered with entities")
|
||||
};
|
||||
let written = match &answer.items[..] {
|
||||
[v1::Entity { kind: Some(Kind::Message(message)) }] => message.clone(),
|
||||
other => panic!("one message expected, got {other:?}"),
|
||||
};
|
||||
assert_eq!((written.channel_id, written.text.as_str()), (channel, text.as_str()));
|
||||
|
||||
let heard = b.message(channel, &text).await;
|
||||
assert_ne!(heard.id, 0);
|
||||
assert_eq!(heard.channel_id, channel);
|
||||
// And ours, back from the server: the same words, once.
|
||||
let echo = a.message(channel, &text).await;
|
||||
assert_ne!(echo.id, 0);
|
||||
a.close().await;
|
||||
b.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_chat_in_the_own_channel() {
|
||||
if live() {
|
||||
chat_in_the_own_channel(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_chat_in_the_own_channel() {
|
||||
if live() {
|
||||
chat_in_the_own_channel(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A move into a channel with a password or without room is refused with the
|
||||
/// code the seam names: `PASSWORD` and `FULL`.
|
||||
async fn refused_moves(dev: Dev) {
|
||||
use voelin_query::{Command as Query, QueryClient};
|
||||
let (admin, _) = QueryClient::connect(&dev.query()).await.expect("the query login");
|
||||
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("seam-locked").arg("channel_password", "secret")).await.unwrap()[0]
|
||||
.parse::<u64>("cid")
|
||||
.unwrap();
|
||||
let full = create("seam-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 token = group_token(&admin, "Normal").await;
|
||||
|
||||
let check = {
|
||||
let token = token.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut options = VoiceOptions::new(dev.voice, dev.nick("moves"));
|
||||
options.token = Some(token);
|
||||
let client = Client::connect_with(&dev, options).await;
|
||||
let code = |result: Result<v1::VoiceState, SessionError>| match result {
|
||||
Err(SessionError::Rejected(error)) => error.code(),
|
||||
other => panic!("expected a refusal, got {other:?}"),
|
||||
};
|
||||
assert_eq!(code(client.join(locked, "").await), v1::ErrorCode::Password);
|
||||
assert_eq!(code(client.join(locked, "wrong").await), v1::ErrorCode::Password);
|
||||
let seat = client.join(locked, "secret").await.expect("the right password");
|
||||
assert_eq!(seat.channel_id, locked);
|
||||
assert_eq!(code(client.join(full, "").await), v1::ErrorCode::Full);
|
||||
client.close().await;
|
||||
})
|
||||
};
|
||||
let result = check.await;
|
||||
// Clean up 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 ts3_refused_moves() {
|
||||
if live() {
|
||||
refused_moves(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_refused_moves() {
|
||||
if live() {
|
||||
refused_moves(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A poke is a `Signal` to a participant: the other session gets it, with
|
||||
/// the participant and the words of the sender.
|
||||
async fn poke_between_sessions(dev: Dev) {
|
||||
let a = Client::connect(&dev, &dev.nick("poke-a")).await;
|
||||
let mut b = Client::connect(&dev, &dev.nick("poke-b")).await;
|
||||
let text = format!("live-poke-{}", std::process::id());
|
||||
let target = v1::SignalTarget {
|
||||
server_id: a.server,
|
||||
participant_id: b.seat.participant_id,
|
||||
..Default::default()
|
||||
};
|
||||
let signal = v1::Signal {
|
||||
to: Some(target),
|
||||
body: Some(v1::signal::Body::Poke(v1::Poke { message: text.clone() })),
|
||||
..Default::default()
|
||||
};
|
||||
a.ask(Op::Signal(signal)).await.expect("the poke is accepted");
|
||||
let from = b
|
||||
.until("the poke", |push| match &push.body {
|
||||
Some(v1::push::Body::Signal(signal)) => match &signal.body {
|
||||
Some(v1::signal::Body::Poke(poke)) if poke.message == text => {
|
||||
Some(signal.from_participant)
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(from, a.seat.participant_id);
|
||||
a.close().await;
|
||||
b.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_poke_between_sessions() {
|
||||
if live() {
|
||||
poke_between_sessions(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_poke_between_sessions() {
|
||||
if live() {
|
||||
poke_between_sessions(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// One frame of Opus (20 ms, mono, fullband).
|
||||
const OPUS: [u8; 3] = [0xf8, 0xff, 0xfe];
|
||||
|
||||
fn rtp(flow: FlowId, sequence: u16, marker: bool, payload: &[u8]) -> MediaPacket {
|
||||
let mut header = RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960);
|
||||
header.marker = marker;
|
||||
let mut out = bytes::BytesMut::new();
|
||||
header.write(flow, &mut out).expect("a header");
|
||||
out.extend_from_slice(payload);
|
||||
MediaPacket { flow, rtp: out.freeze() }
|
||||
}
|
||||
|
||||
/// Voice sent on our slot arrives on the sender's slot at the other session's
|
||||
/// media sink: the frames in order (the sequence is TeamSpeak's packet id, so
|
||||
/// it only has to count up), the marker on the first, and an empty payload at
|
||||
/// the end.
|
||||
async fn voice_between_sessions(dev: Dev) {
|
||||
let a = Client::connect(&dev, &dev.nick("voice-a")).await;
|
||||
let mut b = Client::connect(&dev, &dev.nick("voice-b")).await;
|
||||
assert_eq!(a.seat.channel_id, b.seat.channel_id);
|
||||
let flow = FlowId::new(a.seat.slot, voice_sub::CHANNEL);
|
||||
for n in 0..5u8 {
|
||||
let frame = [0xf8, 0xff, 0xfe, n];
|
||||
let packet = rtp(flow, u16::from(n), n == 0, &frame);
|
||||
a.session.send_media(MediaClass::Voice, packet).expect("our own slot");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
a.session.send_media(MediaClass::Voice, rtp(flow, 5, false, &[])).expect("the end");
|
||||
|
||||
let mut heard = Vec::new();
|
||||
while let Some(packet) = b.media.recv_within(Duration::from_secs(5)).await {
|
||||
let view = RtpView::parse(&packet.rtp).expect("RTP");
|
||||
heard.push((packet.flow, view.sequence(), view.marker(), view.payload().to_vec()));
|
||||
if view.payload().is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(heard.len() >= 2, "{heard:?}");
|
||||
assert!(heard.iter().all(|(heard_flow, ..)| *heard_flow == flow), "{heard:?}");
|
||||
let (_, _, first_marker, first_payload) = &heard[0];
|
||||
assert!(*first_marker, "the first packet of the spurt carries the marker: {heard:?}");
|
||||
assert_eq!(&first_payload[..3], &OPUS[..], "{heard:?}");
|
||||
let (end_flow, _, end_marker, end_payload) = heard.last().expect("an end");
|
||||
assert!(
|
||||
end_payload.is_empty() && !*end_marker,
|
||||
"the spurt ends with an empty payload: {heard:?}"
|
||||
);
|
||||
assert_eq!(*end_flow, flow);
|
||||
let sequences: Vec<_> = heard.iter().map(|(_, sequence, ..)| *sequence).collect();
|
||||
assert!(
|
||||
sequences.windows(2).all(|pair| pair[1] == pair[0].wrapping_add(1)),
|
||||
"the sequence counts up by one: {sequences:?}"
|
||||
);
|
||||
// Voice on a slot that is not ours is refused before it reaches the server.
|
||||
let other = FlowId::new(a.seat.slot + 1000, voice_sub::CHANNEL);
|
||||
assert!(a.session.send_media(MediaClass::Voice, rtp(other, 0, true, &OPUS)).is_err());
|
||||
a.close().await;
|
||||
b.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_voice_between_sessions() {
|
||||
if live() {
|
||||
voice_between_sessions(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_voice_between_sessions() {
|
||||
if live() {
|
||||
voice_between_sessions(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A channel file written with `write_file` and read back from an offset with
|
||||
/// `read_file`: the head names the file and its size, the body starts where
|
||||
/// the offset says.
|
||||
async fn channel_file_from_an_offset(dev: Dev) {
|
||||
use voelin_query::{Command as Query, QueryClient};
|
||||
// Guests may not upload: a key for the Server Admin group.
|
||||
let (admin, _) = QueryClient::connect(&dev.query()).await.expect("the query login");
|
||||
let token = group_token(&admin, "Server Admin").await;
|
||||
let check = tokio::spawn({
|
||||
let token = token.clone();
|
||||
async move { channel_file_with_a_key(dev, token).await }
|
||||
});
|
||||
let result = check.await;
|
||||
let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await;
|
||||
if let Err(error) = result {
|
||||
std::panic::resume_unwind(error.into_panic());
|
||||
}
|
||||
}
|
||||
|
||||
/// A one-time key for the server group `name` (a template group, type 1).
|
||||
async fn group_token(admin: &voelin_query::QueryClient, name: &str) -> String {
|
||||
use voelin_query::Command as Query;
|
||||
let groups = admin.send(&Query::new("servergrouplist")).await.unwrap();
|
||||
let group = groups
|
||||
.iter()
|
||||
.find(|g| g.get("name") == Some(name) && g.get("type") == Some("1"))
|
||||
.and_then(|g| g.parse::<u64>("sgid"))
|
||||
.unwrap_or_else(|| panic!("a {name} server group"));
|
||||
let key =
|
||||
Query::new("privilegekeyadd").arg("tokentype", 0).arg("tokenid1", group).arg("tokenid2", 0);
|
||||
admin.send(&key).await.unwrap()[0].get("token").unwrap().to_owned()
|
||||
}
|
||||
|
||||
async fn channel_file_with_a_key(dev: Dev, token: String) {
|
||||
let mut options = VoiceOptions::new(dev.voice, dev.nick("files"));
|
||||
options.token = Some(token);
|
||||
let a = Client::connect_with(&dev, options).await;
|
||||
let channel = a.seat.channel_id;
|
||||
let name = format!("seam-{}.bin", std::process::id());
|
||||
let path = format!("/{name}");
|
||||
let data: Vec<u8> = (0..3_000usize).map(|i| (i * 7 % 251) as u8).collect();
|
||||
let target = v1::FilePath { channel_id: channel, path: path.clone(), password: String::new() };
|
||||
|
||||
let write = v1::FileWrite {
|
||||
target: Some(v1::file_write::Target::Path(target.clone())),
|
||||
size: data.len() as u64,
|
||||
offset: 0,
|
||||
overwrite: true,
|
||||
sha256: Default::default(),
|
||||
};
|
||||
let mut upload =
|
||||
within("the upload to open", a.session.write_file(write)).await.expect("an upload");
|
||||
upload.body.write_all(&data).await.expect("the body");
|
||||
upload.body.shutdown().await.expect("the end of the body");
|
||||
let stored = within("the server to keep it", upload.done).await.expect("the file is stored");
|
||||
assert!(
|
||||
stored.items.iter().any(|e| matches!(&e.kind, Some(Kind::File(f)) if f.name == name)),
|
||||
"{stored:?}"
|
||||
);
|
||||
|
||||
let read = v1::FileRead {
|
||||
target: Some(v1::file_read::Target::Path(target.clone())),
|
||||
offset: 1_000,
|
||||
length: 0,
|
||||
};
|
||||
let mut download =
|
||||
within("the download to open", a.session.read_file(read)).await.expect("a download");
|
||||
let size = download.head.items.iter().find_map(|e| match &e.kind {
|
||||
Some(Kind::File(file)) => Some(file.size),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(size, Some(3_000), "{:?}", download.head);
|
||||
let mut body = Vec::new();
|
||||
within("the body", download.body.read_to_end(&mut body)).await.expect("the body");
|
||||
assert_eq!(body, data[1_000..], "the body starts at the offset");
|
||||
|
||||
// Clean up what we put on the server.
|
||||
let key = v1::FileEntry { channel_id: channel, path: "/".into(), name, ..Default::default() };
|
||||
let delete = Op::Delete(v1::Delete {
|
||||
keys: vec![v1::Entity { kind: Some(Kind::File(key)) }],
|
||||
..Default::default()
|
||||
});
|
||||
let _ = a.ask(delete).await;
|
||||
a.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_channel_file_from_an_offset() {
|
||||
if live() {
|
||||
channel_file_from_an_offset(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_channel_file_from_an_offset() {
|
||||
if live() {
|
||||
channel_file_from_an_offset(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the cases that do not apply ----------------------------------------------
|
||||
|
||||
/// The cases of [`EXPECTED`] that do not apply fail against a session of a
|
||||
/// TeamSpeak server, each with a panic of its own (its first line is printed):
|
||||
/// the reasons of the table are what they did when they were run. A case that
|
||||
/// passes one day (with the native session of H1) is to be moved to `Passes`.
|
||||
///
|
||||
/// Ignored by default: the cases that wait for a backend that is not there
|
||||
/// take their three seconds each.
|
||||
async fn cases_that_do_not_apply_fail(dev: Dev) {
|
||||
// A case the suite gained is not in `EXPECTED`, and the zip below would leave
|
||||
// it out without a word.
|
||||
the_suite_is_known();
|
||||
for (case, (name, expect)) in conformance::CASES.iter().zip(&EXPECTED) {
|
||||
let NotRun(reason) = expect else { continue };
|
||||
let harness = move || async move {
|
||||
let mut fixture = fixture(dev).await;
|
||||
fixture.step = Duration::from_secs(3);
|
||||
fixture
|
||||
};
|
||||
match tokio::spawn(async move { conformance::run_case(&harness, case).await }).await {
|
||||
Err(error) if error.is_panic() => {
|
||||
let payload = error.into_panic();
|
||||
let message = payload
|
||||
.downcast_ref::<String>()
|
||||
.cloned()
|
||||
.or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_owned()))
|
||||
.unwrap_or_default();
|
||||
let first = message.lines().next().unwrap_or_default();
|
||||
eprintln!("{} {name}: failed as expected ({reason}): {first}", dev.name);
|
||||
}
|
||||
other => panic!("{name} on {} was expected to fail, and: {other:?}", dev.name),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "runs the conformance cases that cannot pass and waits for their timeouts"]
|
||||
async fn ts3_cases_that_do_not_apply_fail() {
|
||||
if live() {
|
||||
cases_that_do_not_apply_fail(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "runs the conformance cases that cannot pass and waits for their timeouts"]
|
||||
async fn ts6_cases_that_do_not_apply_fail() {
|
||||
if live() {
|
||||
cases_that_do_not_apply_fail(TS6).await;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
//! Voice across the seam, TeamSpeak side (`docs/session-seam.md` section
|
||||
//! 6.2): TeamSpeak's Opus packets as RTP on the talker's slot, and RTP on our
|
||||
//! own slot as TeamSpeak's `EncodedVoice`. Nothing is transcoded
|
||||
//! (protocol section 1.2): the Opus payload is the same bytes both ways.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::BytesMut;
|
||||
use voelin_audio::{EncodedVoice, VoiceCodec, VoicePacket};
|
||||
use voelin_proto::link::{FlowId, MediaPacket, voice_sub};
|
||||
use voelin_proto::media::opus::{self, Toc};
|
||||
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, OPUS_CLOCK_RATE, PT_OPUS};
|
||||
use voelin_proto::media::{RtpHeader, RtpView};
|
||||
|
||||
use super::entities::slot;
|
||||
|
||||
/// Silence this long between two packets of a talker starts a new talk spurt
|
||||
/// (the marker bit is set on the first packet of it).
|
||||
const SPURT_GAP: Duration = Duration::from_millis(250);
|
||||
|
||||
/// What is kept of the last packet of a talker.
|
||||
struct Talker {
|
||||
timestamp: u32,
|
||||
sequence: u16,
|
||||
at: Instant,
|
||||
/// The 48 kHz ticks the last packet spans.
|
||||
ticks: u32,
|
||||
/// The last packet ended the spurt.
|
||||
ended: bool,
|
||||
}
|
||||
|
||||
/// Wraps what a TeamSpeak connection receives into RTP.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Downlink {
|
||||
talkers: HashMap<u16, Talker>,
|
||||
}
|
||||
|
||||
impl Downlink {
|
||||
/// `packet` as the RTP packet of its talker's slot. The sequence number is
|
||||
/// TeamSpeak's packet id (both 16 bits); the timestamp advances by each
|
||||
/// packet's duration (its Opus table-of-contents byte) on the packet id's
|
||||
/// counter, so it never goes back when the id wraps, and by wall-clock time
|
||||
/// across silences, so a silence is not compressed. The marker is set on
|
||||
/// the first packet after an end or a gap, and an end is an empty payload.
|
||||
pub(super) fn wrap(&mut self, packet: &VoicePacket, now: Instant) -> Option<MediaPacket> {
|
||||
let id = packet.talker.0;
|
||||
let sub = if packet.whisper { voice_sub::FIRST_TALK_TARGET } else { voice_sub::CHANNEL };
|
||||
let flow = FlowId::new(slot(id), sub);
|
||||
let end = packet.is_end();
|
||||
let (timestamp, marker) = match self.talkers.get(&id) {
|
||||
None => (0, !end),
|
||||
Some(last) => {
|
||||
let gap = now.saturating_duration_since(last.at);
|
||||
if last.ended || gap > SPURT_GAP {
|
||||
// A new spurt: the time that passed since the last packet.
|
||||
let wall = (gap.as_micros() * u128::from(OPUS_CLOCK_RATE) / 1_000_000) as u32;
|
||||
(last.timestamp.wrapping_add(last.ticks.max(wall)), !end)
|
||||
} else {
|
||||
let ahead = packet.seq.wrapping_sub(last.sequence);
|
||||
if ahead == 0 || ahead >= 0x8000 {
|
||||
// A duplicate or a late packet: where it belongs, and the
|
||||
// state keeps what the latest packet said.
|
||||
let back = u32::from(last.sequence.wrapping_sub(packet.seq));
|
||||
let at = last.timestamp.wrapping_sub(back * last.ticks);
|
||||
return self.finish(flow, packet, at, false);
|
||||
}
|
||||
(last.timestamp.wrapping_add(u32::from(ahead) * last.ticks), false)
|
||||
}
|
||||
}
|
||||
};
|
||||
let ticks =
|
||||
if end { 0 } else { opus::packet_ticks(&packet.payload).unwrap_or(OPUS_20_MS_TICKS) };
|
||||
self.talkers
|
||||
.insert(id, Talker { timestamp, sequence: packet.seq, at: now, ticks, ended: end });
|
||||
self.finish(flow, packet, timestamp, marker)
|
||||
}
|
||||
|
||||
fn finish(
|
||||
&self,
|
||||
flow: FlowId,
|
||||
packet: &VoicePacket,
|
||||
timestamp: u32,
|
||||
marker: bool,
|
||||
) -> Option<MediaPacket> {
|
||||
let mut header = RtpHeader::new(PT_OPUS, packet.seq, timestamp);
|
||||
header.marker = marker;
|
||||
// An end is an empty payload, also where the server sent one byte.
|
||||
let payload = if packet.is_end() { &[][..] } else { &packet.payload[..] };
|
||||
let mut out = BytesMut::with_capacity(header.encoded_len() + payload.len());
|
||||
header.write(flow, &mut out).ok()?;
|
||||
out.extend_from_slice(payload);
|
||||
Some(MediaPacket { flow, rtp: out.freeze() })
|
||||
}
|
||||
|
||||
/// Forget a talker (it left the server).
|
||||
pub(super) fn forget(&mut self, client: u16) {
|
||||
self.talkers.remove(&client);
|
||||
}
|
||||
}
|
||||
|
||||
/// The voice a media packet of our own slot carries, for TeamSpeak: its
|
||||
/// payload, and `Music` when the Opus packet is stereo. `None` for a packet
|
||||
/// that is no RTP.
|
||||
pub(super) fn uplink(packet: &MediaPacket) -> Option<EncodedVoice> {
|
||||
let view = RtpView::parse(&packet.rtp).ok()?;
|
||||
let payload = view.payload();
|
||||
let codec = match Toc::parse(payload) {
|
||||
Ok(toc) if toc.stereo() => VoiceCodec::Music,
|
||||
_ => VoiceCodec::Voice,
|
||||
};
|
||||
Some(EncodedVoice { codec, payload: payload.to_vec() })
|
||||
}
|
||||
|
||||
/// An RTP packet of voice, for tests of both sides.
|
||||
#[cfg(test)]
|
||||
pub(super) fn rtp_packet(
|
||||
flow: FlowId,
|
||||
sequence: u16,
|
||||
timestamp: u32,
|
||||
marker: bool,
|
||||
payload: &[u8],
|
||||
) -> bytes::Bytes {
|
||||
let mut header = RtpHeader::new(PT_OPUS, sequence, timestamp);
|
||||
header.marker = marker;
|
||||
let mut out = BytesMut::new();
|
||||
header.write(flow, &mut out).unwrap();
|
||||
out.extend_from_slice(payload);
|
||||
out.freeze()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use bytes::Bytes;
|
||||
use voelin_audio::TalkerId;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn voice(talker: u16, seq: u16, payload: &[u8], whisper: bool) -> VoicePacket {
|
||||
VoicePacket {
|
||||
talker: TalkerId(talker),
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper,
|
||||
payload: payload.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
/// An Opus packet of 20 ms in a CELT-only frame (config 16 is 2.5 ms; 19
|
||||
/// is 20 ms), mono, one frame.
|
||||
const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02];
|
||||
|
||||
fn view(packet: &MediaPacket) -> RtpView<'_> {
|
||||
RtpView::parse(&packet.rtp).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spurt_is_sequenced_by_the_packet_id_with_a_marker_on_its_first_packet() {
|
||||
let mut down = Downlink::default();
|
||||
let t0 = Instant::now();
|
||||
let first = down.wrap(&voice(7, 65_534, &OPUS_20_MS, false), t0).unwrap();
|
||||
let v = view(&first);
|
||||
assert!(v.marker());
|
||||
assert_eq!((v.ssrc(), first.flow), (FlowId::new(8, 0).0, FlowId::new(8, 0)));
|
||||
assert_eq!((v.sequence(), v.timestamp()), (65_534, 0));
|
||||
// The id wraps; the timestamp keeps counting.
|
||||
let t1 = t0 + Duration::from_millis(20);
|
||||
let second = down.wrap(&voice(7, 65_535, &OPUS_20_MS, false), t1).unwrap();
|
||||
let third =
|
||||
down.wrap(&voice(7, 0, &OPUS_20_MS, false), t1 + Duration::from_millis(20)).unwrap();
|
||||
assert!(!view(&second).marker() && !view(&third).marker());
|
||||
assert_eq!(view(&second).timestamp(), OPUS_20_MS_TICKS);
|
||||
assert_eq!((view(&third).sequence(), view(&third).timestamp()), (0, 2 * OPUS_20_MS_TICKS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_is_an_empty_payload_and_the_next_packet_has_a_marker() {
|
||||
let mut down = Downlink::default();
|
||||
let t0 = Instant::now();
|
||||
down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
|
||||
let end = down.wrap(&voice(7, 2, &[], false), t0 + Duration::from_millis(20)).unwrap();
|
||||
assert!(view(&end).payload().is_empty() && !view(&end).marker());
|
||||
// TeamSpeak's single byte after a talk is an end too.
|
||||
let mut down = Downlink::default();
|
||||
down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
|
||||
let end = down.wrap(&voice(7, 2, &[0], false), t0 + Duration::from_millis(20)).unwrap();
|
||||
assert!(view(&end).payload().is_empty());
|
||||
let next =
|
||||
down.wrap(&voice(7, 3, &OPUS_20_MS, false), t0 + Duration::from_millis(60)).unwrap();
|
||||
assert!(view(&next).marker());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_silence_is_not_compressed() {
|
||||
let mut down = Downlink::default();
|
||||
let t0 = Instant::now();
|
||||
let first = down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
|
||||
let again =
|
||||
down.wrap(&voice(7, 2, &OPUS_20_MS, false), t0 + Duration::from_secs(2)).unwrap();
|
||||
assert!(view(&again).marker(), "a gap starts a spurt");
|
||||
// Two seconds of wall-clock time are 96,000 ticks of the 48 kHz clock.
|
||||
assert_eq!(view(&again).timestamp() - view(&first).timestamp(), 96_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whispers_ride_sub_flow_1_and_talkers_have_slots_of_their_own() {
|
||||
let mut down = Downlink::default();
|
||||
let now = Instant::now();
|
||||
let whisper = down.wrap(&voice(300, 1, &OPUS_20_MS, true), now).unwrap();
|
||||
assert_eq!((whisper.flow.slot(), whisper.flow.sub()), (301, 1));
|
||||
let channel = down.wrap(&voice(300, 2, &OPUS_20_MS, false), now).unwrap();
|
||||
assert_eq!((channel.flow.slot(), channel.flow.sub()), (301, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_packet_that_is_not_in_order_keeps_the_state_of_the_latest() {
|
||||
let mut down = Downlink::default();
|
||||
let t0 = Instant::now();
|
||||
down.wrap(&voice(7, 10, &OPUS_20_MS, false), t0).unwrap();
|
||||
down.wrap(&voice(7, 11, &OPUS_20_MS, false), t0 + Duration::from_millis(20)).unwrap();
|
||||
let late =
|
||||
down.wrap(&voice(7, 10, &OPUS_20_MS, false), t0 + Duration::from_millis(25)).unwrap();
|
||||
assert_eq!(view(&late).timestamp(), 0, "where packet 10 belongs");
|
||||
let next =
|
||||
down.wrap(&voice(7, 12, &OPUS_20_MS, false), t0 + Duration::from_millis(40)).unwrap();
|
||||
assert_eq!(view(&next).timestamp(), 2 * OPUS_20_MS_TICKS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn our_voice_loses_its_header_and_stereo_is_music() {
|
||||
let flow = FlowId::new(8, 0);
|
||||
let mono = MediaPacket { flow, rtp: rtp_packet(flow, 0, 0, true, &OPUS_20_MS) };
|
||||
let voice = uplink(&mono).unwrap();
|
||||
assert_eq!((voice.codec, voice.payload.as_slice()), (VoiceCodec::Voice, &OPUS_20_MS[..]));
|
||||
// The same TOC with the stereo bit.
|
||||
let stereo_toc = [OPUS_20_MS[0] | 0x04, 1, 2];
|
||||
let stereo = MediaPacket { flow, rtp: rtp_packet(flow, 1, 960, false, &stereo_toc) };
|
||||
assert_eq!(uplink(&stereo).unwrap().codec, VoiceCodec::Music);
|
||||
// The end of a spurt: an empty payload.
|
||||
let end = MediaPacket { flow, rtp: rtp_packet(flow, 2, 1920, false, &[]) };
|
||||
assert!(uplink(&end).unwrap().is_end());
|
||||
// Not RTP.
|
||||
assert!(uplink(&MediaPacket { flow, rtp: Bytes::from_static(&[1, 2, 3]) }).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,887 @@
|
||||
//! A TeamSpeak connection as a `voelin_proto::link::Session`
|
||||
//! (`docs/session-seam.md`, "the TeamSpeak side").
|
||||
//!
|
||||
//! [`LinkSession`] is a `Session` over any [`ServerLink`]:
|
||||
//! it turns the link's `LinkCmd`s and `LinkEvent`s (the client's older,
|
||||
//! TeamSpeak-shaped vocabulary) into v1 entities, pushes and answers. With
|
||||
//! `TsLink` inside it is the in-process TeamSpeak `Session`; with a fake link
|
||||
//! inside it is what the link tests of the engine run through. [`TsConnector`]
|
||||
//! is the `Connector` that makes them for `ts3server://` and `teamspeak://`
|
||||
//! addresses.
|
||||
//!
|
||||
//! This module and the files it is made of are TeamSpeak's: they keep the
|
||||
//! TeamSpeak types (`tsclientlib`'s identity and client version) in
|
||||
//! [`inner_options`], the reverse of what the engine's `connect_params` wrote,
|
||||
//! and everything else is v1 and the client's own model. In the second half
|
||||
//! of the decoupling plan they move, with `TsLink`, to the TeamSpeak gateway
|
||||
//! (`voelin-gateway-ts` of VoelinGateWay).
|
||||
|
||||
mod driver;
|
||||
pub(crate) mod entities;
|
||||
pub(crate) mod ids;
|
||||
#[cfg(test)]
|
||||
mod live_tests;
|
||||
mod media;
|
||||
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::Duration;
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use bytes::Bytes;
|
||||
use tokio::io::{AsyncReadExt, AsyncWrite};
|
||||
use tokio::sync::{broadcast, mpsc, oneshot, watch};
|
||||
use voelin_model::{Link, ServerDetails};
|
||||
use voelin_proto::link::{
|
||||
BoxFuture, CloseReason, ConnectParams, Connected, Connector, Credential, Download, Features,
|
||||
LinkStats, MAX_RTP, MediaClass, MediaError, MediaPacket, Placement, Sent, Session,
|
||||
SessionError, Upload, placement, voice_sub,
|
||||
};
|
||||
use voelin_proto::v1::{self, response::Result as Answer};
|
||||
|
||||
use self::driver::{Cmd, Config, Driver, Parts, rejected};
|
||||
use super::{ConnectOptions, ServerLink, TsLink, identity, versions};
|
||||
use crate::BackendInfo;
|
||||
use crate::link::{
|
||||
BoxDuplex, LinkCmd, LinkCtx, LinkEvent, LocalConnected, LocalConnector, LocalCtx, StreamPort,
|
||||
VERSION_PARAM,
|
||||
};
|
||||
|
||||
/// The `Credential::Foreign` kind of a stored TeamSpeak identity.
|
||||
const IDENTITY_KIND: &str = voelin_identity::KIND_TEAMSPEAK;
|
||||
/// How long the link may take to report its first snapshot after it said it
|
||||
/// is connected; the snapshot gives the `Welcome` its own user.
|
||||
const FIRST_SNAPSHOT: Duration = Duration::from_millis(250);
|
||||
|
||||
static SESSIONS: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
fn now_ms() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis() as i64)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
// ---- what the engine hands a connector ------------------------------------
|
||||
|
||||
/// The options a TeamSpeak link is connected with: the reverse of
|
||||
/// `link::connect_params`. A client version spec that [`versions::resolve`]
|
||||
/// refuses fails the connect, in words.
|
||||
fn inner_options(params: &ConnectParams, ctx: &LocalCtx) -> Result<ConnectOptions, SessionError> {
|
||||
let link = match Link::parse(¶ms.address) {
|
||||
Some(Link::Server(link)) => link,
|
||||
_ => {
|
||||
// Without the query: a channel password rides in it.
|
||||
let shown = crate::link::without_query(¶ms.address);
|
||||
return Err(SessionError::Protocol(format!("not a TeamSpeak server address: {shown}")));
|
||||
}
|
||||
};
|
||||
let identity = match ¶ms.credential {
|
||||
Credential::Foreign { kind: IDENTITY_KIND, blob } if blob.is_empty() => None,
|
||||
Credential::Foreign { kind: IDENTITY_KIND, blob } => {
|
||||
// The refusal never quotes the JSON: it holds the private key, and the
|
||||
// JSON reader's own message would show a key that does not import.
|
||||
let json = std::str::from_utf8(blob).map_err(|_| {
|
||||
SessionError::Protocol(
|
||||
"the TeamSpeak identity cannot be read: it is not text".into(),
|
||||
)
|
||||
})?;
|
||||
Some(identity::from_json(json).map_err(|e| SessionError::Protocol(e.to_string()))?)
|
||||
}
|
||||
_ => {
|
||||
return Err(SessionError::Protocol(
|
||||
"a TeamSpeak server needs a TeamSpeak identity".into(),
|
||||
));
|
||||
}
|
||||
};
|
||||
let spec = params
|
||||
.address
|
||||
.split_once('?')
|
||||
.and_then(|(_, query)| {
|
||||
query.split('&').find_map(|pair| pair.strip_prefix(&format!("{VERSION_PARAM}=")))
|
||||
})
|
||||
.map(|text| {
|
||||
URL_SAFE_NO_PAD
|
||||
.decode(text)
|
||||
.ok()
|
||||
.and_then(|bytes| String::from_utf8(bytes).ok())
|
||||
.ok_or_else(|| SessionError::Protocol("the client version cannot be read".into()))
|
||||
})
|
||||
.transpose()?;
|
||||
let client_version = match spec {
|
||||
None => None,
|
||||
Some(spec) => versions::resolve(&spec).map_err(|e| {
|
||||
SessionError::Protocol(format!("invalid client compatibility version: {e}"))
|
||||
})?,
|
||||
};
|
||||
let nonempty = |text: &str| (!text.is_empty()).then(|| text.to_owned());
|
||||
Ok(ConnectOptions {
|
||||
address: link.address(),
|
||||
nickname: nonempty(¶ms.hello.nickname).or(link.nickname.clone()).unwrap_or_default(),
|
||||
identity,
|
||||
client_version,
|
||||
server_password: nonempty(¶ms.hello.password).or(link.password.clone()),
|
||||
channel: link.channel.clone(),
|
||||
channel_password: link.channel_password.clone(),
|
||||
token: nonempty(¶ms.hello.invite_code).or(link.token.clone()),
|
||||
audio: ctx.audio,
|
||||
stream_peer: ctx.stream_peer.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
// ---- backend and features ---------------------------------------------------
|
||||
|
||||
/// The server software as v1 names it (table 4.7): `teamspeak` with the
|
||||
/// flavor `ts3` or `ts6`; what is not a TeamSpeak product as it is.
|
||||
pub(crate) fn backend_to_v1(backend: &BackendInfo) -> v1::BackendInfo {
|
||||
let (product, flavor) = match backend.product.as_str() {
|
||||
"TeamSpeak 3" => ("teamspeak", "ts3"),
|
||||
"TeamSpeak 6" => ("teamspeak", "ts6"),
|
||||
// A TeamSpeak server the engine does not recognise: the version it
|
||||
// sent, no flavor.
|
||||
"" => ("teamspeak", ""),
|
||||
other => (other, ""),
|
||||
};
|
||||
v1::BackendInfo {
|
||||
product: product.into(),
|
||||
version: backend.version.clone(),
|
||||
flavor: flavor.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The features a TeamSpeak connection offers, from what its link can do
|
||||
/// (`docs/session-seam.md` section 4.7).
|
||||
pub(crate) fn features_of(capabilities: &voelin_model::Capabilities) -> Vec<&'static str> {
|
||||
let mut features =
|
||||
vec!["voice", "chat", "chat.bbcode", "dm", "sync.delta", "roles", "roles.channel"];
|
||||
if capabilities.file_transfer {
|
||||
features.extend(["files", "files.upload"]);
|
||||
}
|
||||
if capabilities.offline_messages {
|
||||
features.push("mailbox");
|
||||
}
|
||||
if capabilities.streams {
|
||||
features.extend(["streams", "streams.p2p", "streams.audio", "streams.approval"]);
|
||||
}
|
||||
features
|
||||
}
|
||||
|
||||
// ---- the session ------------------------------------------------------------
|
||||
|
||||
/// A `Session` over a [`ServerLink`]: the TeamSpeak side of the seam.
|
||||
pub(crate) struct LinkSession {
|
||||
welcome: v1::Welcome,
|
||||
features: Features,
|
||||
cmds: mpsc::UnboundedSender<Cmd>,
|
||||
closed: watch::Receiver<Option<CloseReason>>,
|
||||
/// The media slot of our client; the driver changes it when we are another
|
||||
/// client after TeamSpeak's own reconnect.
|
||||
own_slot: Arc<AtomicU32>,
|
||||
}
|
||||
|
||||
fn closed_reason(closed: &watch::Receiver<Option<CloseReason>>) -> CloseReason {
|
||||
closed.borrow().clone().unwrap_or_else(|| CloseReason::Network("the connection ended".into()))
|
||||
}
|
||||
|
||||
impl Session for LinkSession {
|
||||
fn welcome(&self) -> &v1::Welcome {
|
||||
&self.welcome
|
||||
}
|
||||
|
||||
fn features(&self) -> Features {
|
||||
self.features.clone()
|
||||
}
|
||||
|
||||
fn request(&self, op: v1::request::Op) -> BoxFuture<Result<Answer, SessionError>> {
|
||||
let closed = self.closed.clone();
|
||||
match placement(&op) {
|
||||
Placement::Invalid => {
|
||||
return Box::pin(async {
|
||||
Err(SessionError::Protocol("a Hello is part of connecting".into()))
|
||||
});
|
||||
}
|
||||
Placement::OwnStream
|
||||
if matches!(op, v1::request::Op::FileRead(_) | v1::request::Op::FileWrite(_)) =>
|
||||
{
|
||||
return Box::pin(async {
|
||||
Err(SessionError::Protocol("files go through read_file and write_file".into()))
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// Queued now, in the order of the calls, not when the future is polled.
|
||||
let (reply, answer) = oneshot::channel();
|
||||
if self.cmds.send(Cmd::Request { op, reply }).is_err() {
|
||||
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
|
||||
}
|
||||
Box::pin(async move {
|
||||
match answer.await {
|
||||
Ok(answer) => answer,
|
||||
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn notify(&self, op: v1::request::Op) -> Result<(), SessionError> {
|
||||
// Only an op of the control stream can go without an answer: a Hello is
|
||||
// part of connecting, and a List and the file transfers have streams
|
||||
// (and answers) of their own.
|
||||
match placement(&op) {
|
||||
Placement::Control => {}
|
||||
Placement::Invalid => {
|
||||
return Err(SessionError::Protocol("a Hello is part of connecting".into()));
|
||||
}
|
||||
Placement::OwnStream => {
|
||||
return Err(SessionError::Protocol(
|
||||
"a List and the file transfers have a stream and an answer of their own, \
|
||||
they cannot be sent without one"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
// The task may be on its way out and not have dropped its queue yet.
|
||||
if self.closed.borrow().is_some() {
|
||||
return Err(SessionError::Closed(closed_reason(&self.closed)));
|
||||
}
|
||||
self.cmds
|
||||
.send(Cmd::Notify(op))
|
||||
.map_err(|_| SessionError::Closed(closed_reason(&self.closed)))
|
||||
}
|
||||
|
||||
fn read_file(&self, request: v1::FileRead) -> BoxFuture<Result<Download, SessionError>> {
|
||||
let closed = self.closed.clone();
|
||||
let (reply, answer) = oneshot::channel();
|
||||
if self.cmds.send(Cmd::Read { request, reply }).is_err() {
|
||||
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
|
||||
}
|
||||
Box::pin(async move {
|
||||
match answer.await {
|
||||
Ok(answer) => answer,
|
||||
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn write_file(&self, request: v1::FileWrite) -> BoxFuture<Result<Upload, SessionError>> {
|
||||
let closed = self.closed.clone();
|
||||
let (reply, answer) = oneshot::channel();
|
||||
if self.cmds.send(Cmd::Write { request, reply }).is_err() {
|
||||
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
|
||||
}
|
||||
Box::pin(async move {
|
||||
match answer.await {
|
||||
Ok(answer) => answer,
|
||||
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn send_media(&self, class: MediaClass, packet: MediaPacket) -> Result<Sent, MediaError> {
|
||||
let flow = packet.flow;
|
||||
if self.closed.borrow().is_some() {
|
||||
return Err(MediaError::Closed);
|
||||
}
|
||||
if packet.rtp.len() > MAX_RTP {
|
||||
return Err(MediaError::TooLarge { len: packet.rtp.len(), max: MAX_RTP });
|
||||
}
|
||||
// Only our voice to the channel: TeamSpeak whispers and priority voice,
|
||||
// like video, are not offered here.
|
||||
if class != MediaClass::Voice
|
||||
|| flow.slot() != self.own_slot.load(Ordering::Relaxed)
|
||||
|| flow.sub() != voice_sub::CHANNEL
|
||||
{
|
||||
return Err(MediaError::NotOwned(flow));
|
||||
}
|
||||
let voice = media::uplink(&packet).ok_or(MediaError::NotOwned(flow))?;
|
||||
self.cmds.send(Cmd::Audio(voice)).map_err(|_| MediaError::Closed)?;
|
||||
Ok(Sent::Queued)
|
||||
}
|
||||
|
||||
fn stats(&self) -> LinkStats {
|
||||
LinkStats { max_rtp: MAX_RTP, ..Default::default() }
|
||||
}
|
||||
|
||||
fn close(&self, code: v1::CloseCode, reason: &str) {
|
||||
let _ = self.cmds.send(Cmd::Close { code, reason: reason.to_owned() });
|
||||
}
|
||||
|
||||
fn closed(&self) -> BoxFuture<CloseReason> {
|
||||
let mut closed = self.closed.clone();
|
||||
Box::pin(async move {
|
||||
let reason = closed.wait_for(Option::is_some).await.ok().and_then(|r| r.clone());
|
||||
reason.unwrap_or_else(|| closed_reason(&closed))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The write half of an upload: ending it tells the other half of the
|
||||
/// upload that the file is all there.
|
||||
struct UploadBody {
|
||||
inner: tokio::io::WriteHalf<BoxDuplex>,
|
||||
ended: Option<oneshot::Sender<()>>,
|
||||
}
|
||||
|
||||
impl AsyncWrite for UploadBody {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<std::io::Result<usize>> {
|
||||
Pin::new(&mut self.inner).poll_write(cx, buf)
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_flush(cx)
|
||||
}
|
||||
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
let done = Pin::new(&mut self.inner).poll_shutdown(cx);
|
||||
if matches!(done, Poll::Ready(Ok(())))
|
||||
&& let Some(ended) = self.ended.take()
|
||||
{
|
||||
let _ = ended.send(());
|
||||
}
|
||||
done
|
||||
}
|
||||
}
|
||||
|
||||
/// An upload over the transfer connection `stream`: the body writes to it,
|
||||
/// and `done` resolves once the body is shut down and the server has closed
|
||||
/// the connection (or 30 s passed), with the file as `stored`.
|
||||
fn upload(stream: BoxDuplex, stored: v1::FileEntry) -> Upload {
|
||||
let (mut read, write) = tokio::io::split(stream);
|
||||
let (ended, shut) = oneshot::channel();
|
||||
let done: BoxFuture<Result<v1::Entities, SessionError>> = Box::pin(async move {
|
||||
if shut.await.is_err() {
|
||||
return Err(rejected(v1::ErrorCode::Cancelled, "the upload was dropped"));
|
||||
}
|
||||
// The server closes the connection once it has everything.
|
||||
let _ = tokio::time::timeout(Duration::from_secs(30), read.read(&mut [0u8; 1])).await;
|
||||
Ok(v1::Entities {
|
||||
items: vec![v1::Entity { kind: Some(v1::entity::Kind::File(stored)) }],
|
||||
..Default::default()
|
||||
})
|
||||
});
|
||||
Upload { body: Box::pin(UploadBody { inner: write, ended: Some(ended) }), done }
|
||||
}
|
||||
|
||||
// ---- the connector ----------------------------------------------------------
|
||||
|
||||
/// The `Connector` of a [`ServerLink`]: its sessions are [`LinkSession`]s.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct LinkConnector {
|
||||
link: Arc<dyn ServerLink>,
|
||||
schemes: &'static [&'static str],
|
||||
/// Serves every scheme (the engine's tests give a link of their own).
|
||||
any: bool,
|
||||
}
|
||||
|
||||
impl LinkConnector {
|
||||
/// A connector for `schemes`.
|
||||
pub(crate) fn new(link: Arc<dyn ServerLink>, schemes: &'static [&'static str]) -> Self {
|
||||
Self { link, schemes, any: false }
|
||||
}
|
||||
|
||||
/// A connector for addresses of every scheme.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn any(link: Arc<dyn ServerLink>) -> Self {
|
||||
Self { link, schemes: &[], any: true }
|
||||
}
|
||||
}
|
||||
|
||||
impl Connector for LinkConnector {
|
||||
fn schemes(&self) -> &'static [&'static str] {
|
||||
self.schemes
|
||||
}
|
||||
|
||||
fn connect(&self, params: ConnectParams) -> BoxFuture<Result<Connected, SessionError>> {
|
||||
let connect = connect_link(self.link.clone(), params, LocalCtx::standalone());
|
||||
Box::pin(async move { Ok(connect.await?.connected) })
|
||||
}
|
||||
}
|
||||
|
||||
impl LocalConnector for LinkConnector {
|
||||
fn accepts(&self, scheme: &str) -> bool {
|
||||
self.any || self.schemes.contains(&scheme)
|
||||
}
|
||||
|
||||
fn connect_local(
|
||||
&self,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> BoxFuture<Result<LocalConnected, SessionError>> {
|
||||
Box::pin(connect_link(self.link.clone(), params, ctx))
|
||||
}
|
||||
}
|
||||
|
||||
/// Connects to TeamSpeak 3 and 6 servers (`ts3server://` and `teamspeak://`)
|
||||
/// with `tsclientlib`: a `LinkSession` over a `TsLink` for every connection.
|
||||
///
|
||||
/// Clones share one account: the main myTeamSpeak account that every
|
||||
/// connection of the connector presents ([`TsConnector::set_myts_identity`],
|
||||
/// [`TsConnector::set_myts_data`]), also those made before it was set.
|
||||
/// Register a connector in the engine's registry with
|
||||
/// [`Backends::register_teamspeak`](crate::Backends::register_teamspeak) and
|
||||
/// keep a clone to set the account.
|
||||
#[derive(Clone)]
|
||||
pub struct TsConnector {
|
||||
connector: LinkConnector,
|
||||
link: Arc<TsLink>,
|
||||
}
|
||||
|
||||
impl Default for TsConnector {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl TsConnector {
|
||||
/// A connector that presents no account until it is given one.
|
||||
pub fn new() -> Self {
|
||||
let link = Arc::new(TsLink::new());
|
||||
Self { connector: LinkConnector::new(link.clone(), &["ts3server", "teamspeak"]), link }
|
||||
}
|
||||
|
||||
/// The main account's proof for every current and future connection of
|
||||
/// this connector (and its clones): a myTS ID signed with the account's
|
||||
/// key. Connections that are up show the server the new proof, and those
|
||||
/// that connect later present it from the start; `None` is a sign-out.
|
||||
pub fn set_myts_identity(&self, identity: Option<Arc<tsproto::myts::Identity>>) {
|
||||
self.link.account().set_identity(identity);
|
||||
}
|
||||
|
||||
/// What servers are shown of the main account: its avatar and badges with
|
||||
/// their certificates, its User Tag (TeamSpeak 6). It is sent to every
|
||||
/// connection that presents the account's myTS ID, once connected and when
|
||||
/// it changes; cleared on a sign-out (`None`).
|
||||
pub fn set_myts_data(&self, data: Option<Arc<tsclientlib::MytsData>>) {
|
||||
self.link.account().set_data(data);
|
||||
}
|
||||
}
|
||||
|
||||
impl Connector for TsConnector {
|
||||
fn schemes(&self) -> &'static [&'static str] {
|
||||
self.connector.schemes()
|
||||
}
|
||||
|
||||
fn connect(&self, params: ConnectParams) -> BoxFuture<Result<Connected, SessionError>> {
|
||||
self.connector.connect(params)
|
||||
}
|
||||
}
|
||||
|
||||
impl LocalConnector for TsConnector {
|
||||
fn connect_local(
|
||||
&self,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> BoxFuture<Result<LocalConnected, SessionError>> {
|
||||
self.connector.connect_local(params, ctx)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the link told when it connected.
|
||||
struct Joined {
|
||||
name: String,
|
||||
backend: BackendInfo,
|
||||
capabilities: voelin_model::Capabilities,
|
||||
own_client: u16,
|
||||
server_uid: String,
|
||||
own_uid: Option<String>,
|
||||
}
|
||||
|
||||
fn ended_error(reason: Option<String>) -> SessionError {
|
||||
SessionError::Closed(match reason {
|
||||
Some(reason) => CloseReason::Network(reason),
|
||||
None => CloseReason::Remote { code: v1::CloseCode::Normal as u64, reason: String::new() },
|
||||
})
|
||||
}
|
||||
|
||||
/// Wait for the link to say it is connected (or that it failed).
|
||||
async fn wait_connected(
|
||||
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
|
||||
) -> Result<Joined, SessionError> {
|
||||
loop {
|
||||
match events.recv().await {
|
||||
Some(LinkEvent::Connected {
|
||||
name,
|
||||
backend,
|
||||
capabilities,
|
||||
own_client,
|
||||
server_uid,
|
||||
own_uid,
|
||||
}) => {
|
||||
return Ok(Joined { name, backend, capabilities, own_client, server_uid, own_uid });
|
||||
}
|
||||
Some(LinkEvent::Disconnected(reason)) => return Err(ended_error(reason)),
|
||||
Some(_) => {}
|
||||
None => return Err(ended_error(Some("the connection ended".into()))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a [`LinkSession`] over `link` to the address in `params`.
|
||||
async fn connect_link(
|
||||
link: Arc<dyn ServerLink>,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> Result<LocalConnected, SessionError> {
|
||||
let options = inner_options(¶ms, &ctx)?;
|
||||
let nickname = options.nickname.clone();
|
||||
let (inner_tx, inner_rx) = mpsc::unbounded_channel();
|
||||
let (events_tx, mut events) = mpsc::unbounded_channel();
|
||||
// The link answers requests on a bus of its own: this session reads the
|
||||
// answers, and passes on the rest to the engine's.
|
||||
let (bus_tx, bus) = broadcast::channel(4096);
|
||||
let inner_ctx = LinkCtx { events: bus_tx, ..ctx.link.clone() };
|
||||
link.spawn(options, inner_ctx, inner_rx, events_tx);
|
||||
|
||||
let joined = match tokio::time::timeout(params.timeout, wait_connected(&mut events)).await {
|
||||
Ok(joined) => joined?,
|
||||
Err(_) => {
|
||||
let _ = inner_tx.send(LinkCmd::Disconnect);
|
||||
return Err(SessionError::Timeout);
|
||||
}
|
||||
};
|
||||
// The link reports its first snapshot right after it says it is connected;
|
||||
// the session needs it to know the own user.
|
||||
let mut early: Vec<LinkEvent> = Vec::new();
|
||||
let _ = tokio::time::timeout(FIRST_SNAPSHOT, async {
|
||||
while let Some(event) = events.recv().await {
|
||||
let stop = matches!(event, LinkEvent::Presence(_) | LinkEvent::Disconnected(_));
|
||||
early.push(event);
|
||||
if stop {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
if let Some(LinkEvent::Disconnected(reason)) = early.last() {
|
||||
return Err(ended_error(reason.clone()));
|
||||
}
|
||||
let own_database_id = early.iter().find_map(|event| match event {
|
||||
LinkEvent::Presence(presence) => {
|
||||
presence.clients.get(&joined.own_client).and_then(|c| c.database_id)
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
|
||||
let ts6 = joined.backend.product == "TeamSpeak 6";
|
||||
let own_user =
|
||||
own_database_id.or_else(|| joined.own_uid.as_deref().map(ids::synthetic_user)).unwrap_or(0);
|
||||
let features = features_of(&joined.capabilities);
|
||||
let welcome = v1::Welcome {
|
||||
user_id: own_user,
|
||||
session_id: SESSIONS.fetch_add(1, Ordering::Relaxed),
|
||||
uid: joined.own_uid.as_deref().and_then(ids::uid_bytes).unwrap_or_default().into(),
|
||||
host: Some(v1::HostInfo {
|
||||
host_key: Bytes::new(),
|
||||
name: joined.name.clone(),
|
||||
product: joined.backend.product.clone(),
|
||||
version: joined.backend.version.clone(),
|
||||
backend: Some(backend_to_v1(&joined.backend)),
|
||||
icon: None,
|
||||
}),
|
||||
features: features.iter().map(|f| (*f).to_owned()).collect(),
|
||||
limits: Some(v1::Limits {
|
||||
max_message_chars: 1024,
|
||||
max_page: 100,
|
||||
// HOME, SERVER and LIVE, and the chats.
|
||||
max_subscriptions: driver::MAX_CHAT_SUBSCRIPTIONS + 3,
|
||||
max_chat_subscriptions: driver::MAX_CHAT_SUBSCRIPTIONS,
|
||||
max_live_subscriptions: 8,
|
||||
..Default::default()
|
||||
}),
|
||||
time_ms: now_ms(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let (cmds_tx, cmds_rx) = mpsc::unbounded_channel();
|
||||
let own_slot = Arc::new(AtomicU32::new(entities::slot(joined.own_client)));
|
||||
let (pushes_tx, pushes_rx) = mpsc::channel(params.push_capacity.max(16));
|
||||
let (closed_tx, closed_rx) = watch::channel(None);
|
||||
let (port, streams) = if joined.capabilities.streams {
|
||||
let (events_tx, events_rx) = mpsc::unbounded_channel();
|
||||
let cmds = cmds_tx.clone();
|
||||
let send = move |cmd| {
|
||||
let _ = cmds.send(Cmd::Stream(cmd));
|
||||
};
|
||||
(Some(events_tx), Some(StreamPort::new(send, events_rx)))
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
let details = ServerDetails { uid: Some(joined.server_uid.clone()), ..Default::default() };
|
||||
let driver = Driver::new(Parts {
|
||||
cfg: Config {
|
||||
ts6,
|
||||
own_client: joined.own_client,
|
||||
nickname,
|
||||
own_uid: joined.own_uid.clone(),
|
||||
files: joined.capabilities.file_transfer,
|
||||
mail: joined.capabilities.offline_messages,
|
||||
},
|
||||
inner: inner_tx,
|
||||
events,
|
||||
early,
|
||||
bus,
|
||||
engine_bus: ctx.link.events.clone(),
|
||||
pushes: pushes_tx,
|
||||
media: params.media.clone(),
|
||||
port,
|
||||
closed: closed_tx,
|
||||
own_slot: own_slot.clone(),
|
||||
server: entities::server(&details, &joined.name, 0),
|
||||
epoch: u64::try_from(now_ms()).unwrap_or(1).max(1),
|
||||
});
|
||||
let session = LinkSession {
|
||||
welcome,
|
||||
features: Features::new(features),
|
||||
cmds: cmds_tx,
|
||||
closed: closed_rx,
|
||||
own_slot,
|
||||
};
|
||||
tokio::spawn(driver.run(cmds_rx));
|
||||
Ok(LocalConnected {
|
||||
connected: Connected {
|
||||
session: Arc::new(session),
|
||||
pushes: pushes_rx,
|
||||
// A TeamSpeak server has no host key to pin.
|
||||
host_uid: [0; 32],
|
||||
},
|
||||
streams,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::link::{Backends, VoiceOptions, connect_params};
|
||||
use voelin_proto::link::IssuerTrust;
|
||||
|
||||
fn params(options: &VoiceOptions) -> ConnectParams {
|
||||
let (media, _rx) = voelin_proto::test_util::media_channel();
|
||||
connect_params(options, media, &Backends::empty()).unwrap()
|
||||
}
|
||||
|
||||
fn back(options: &VoiceOptions) -> ConnectOptions {
|
||||
inner_options(¶ms(options), &LocalCtx::standalone()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_options_of_a_bookmark_come_back_as_they_went() {
|
||||
let mut options = VoiceOptions::new("ts.example.com:9988", "nick");
|
||||
let same = back(&options);
|
||||
assert_eq!(
|
||||
(same.address.as_str(), same.nickname.as_str()),
|
||||
("ts.example.com:9988", "nick")
|
||||
);
|
||||
assert!(same.identity.is_none() && same.client_version.is_none());
|
||||
assert!(same.channel.is_none() && same.server_password.is_none() && same.token.is_none());
|
||||
|
||||
// Everything a connection can be told: the server password and the
|
||||
// privilege key go in the hello, the channel and its password in the
|
||||
// link, the identity as a credential.
|
||||
options.server_password = Some("s3cret pass&word".into());
|
||||
options.channel = Some("Games/Raid Night".into());
|
||||
options.channel_password = Some("p w+%".into());
|
||||
options.token = Some("tokenvalue".into());
|
||||
let identity = tsclientlib::Identity::create();
|
||||
options.identity = Some(crate::ts::identity::to_blob(&identity));
|
||||
// A spec the user can give; the connector resolves it.
|
||||
options.client_version = Some("generic".into());
|
||||
options.audio = false;
|
||||
let sent = params(&options);
|
||||
assert_eq!(sent.hello.password, "s3cret pass&word");
|
||||
assert_eq!(sent.hello.invite_code, "tokenvalue");
|
||||
assert_eq!(sent.hello.nickname, "nick");
|
||||
assert!(
|
||||
sent.address.starts_with("ts3server://ts.example.com?port=9988"),
|
||||
"{}",
|
||||
sent.address
|
||||
);
|
||||
assert!(!sent.address.contains("s3cret") && !sent.address.contains("tokenvalue"));
|
||||
let got = back(&options);
|
||||
assert_eq!(got.address, "ts.example.com:9988");
|
||||
assert_eq!(got.server_password, options.server_password);
|
||||
assert_eq!(got.channel.as_deref(), Some("Games/Raid Night"));
|
||||
assert_eq!(got.channel_password, options.channel_password);
|
||||
assert_eq!(got.token.as_deref(), Some("tokenvalue"));
|
||||
assert_eq!(got.client_version, versions::resolve("generic").unwrap());
|
||||
assert!(got.client_version.is_some());
|
||||
// The identity is the same key and counters.
|
||||
let b = got.identity.as_ref().unwrap();
|
||||
assert_eq!(serde_json::to_value(&identity).unwrap(), serde_json::to_value(b).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_channel_by_id_and_an_address_that_is_a_link_are_kept() {
|
||||
let mut options = VoiceOptions::new("[::1]:9987", "nick");
|
||||
options.channel = Some("/12".into());
|
||||
let got = back(&options);
|
||||
assert_eq!(got.address, "[::1]:9987");
|
||||
assert_eq!(got.channel.as_deref(), Some("/12"));
|
||||
|
||||
// A bookmark that is a link keeps its own parameters.
|
||||
let options = VoiceOptions::new("ts3server://ts.example.com?port=1&channel=Lobby", "nick");
|
||||
let got = back(&options);
|
||||
assert_eq!(
|
||||
(got.address.as_str(), got.channel.as_deref()),
|
||||
("ts.example.com:1", Some("Lobby"))
|
||||
);
|
||||
// Another scheme is left as it is for the connector of that scheme.
|
||||
let options = VoiceOptions::new("voelin://host/i/code", "nick");
|
||||
assert_eq!(params(&options).address, "voelin://host/i/code");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_no_teamspeak_identity_is_refused() {
|
||||
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
|
||||
sent.credential = Credential::Voelin(Arc::new(voelin_proto::test_util::FakeSigner));
|
||||
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
|
||||
assert!(matches!(error, SessionError::Protocol(_)));
|
||||
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
|
||||
sent.credential =
|
||||
Credential::Account { kind: "teamspeak", integration_id: Bytes::from_static(b"id") };
|
||||
assert!(inner_options(&sent, &LocalCtx::standalone()).is_err());
|
||||
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
|
||||
sent.credential =
|
||||
Credential::Foreign { kind: "teamspeak", blob: Bytes::from_static(b"not json") };
|
||||
assert!(inner_options(&sent, &LocalCtx::standalone()).is_err());
|
||||
// A host that wants trust is refused: TeamSpeak has no host key.
|
||||
let backends = Backends::empty();
|
||||
let confirm = backends.trust().confirm(voelin_proto::link::HostIdentity {
|
||||
address: "x".into(),
|
||||
uid: [0; 32],
|
||||
previous: None,
|
||||
});
|
||||
assert!(!futures::executor::block_on(confirm));
|
||||
}
|
||||
|
||||
/// An identity that cannot be read ends the connect with words that say
|
||||
/// where it is wrong and hold none of the key: the JSON reader's own
|
||||
/// message quotes a key that does not import, and this text reaches the
|
||||
/// event bus and the status line.
|
||||
#[test]
|
||||
fn an_identity_that_cannot_be_read_is_refused_without_the_key() {
|
||||
let (json, cut) = identity::json_with_a_cut_key();
|
||||
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
|
||||
sent.credential = Credential::Foreign { kind: "teamspeak", blob: Bytes::from(json) };
|
||||
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
|
||||
let SessionError::Protocol(text) = error else { panic!("a protocol error: {error:?}") };
|
||||
assert!(
|
||||
text.starts_with(
|
||||
"the TeamSpeak identity cannot be read: not an identity at line 1, column "
|
||||
),
|
||||
"{text}"
|
||||
);
|
||||
identity::assert_holds_no_piece_of(&text, &cut);
|
||||
|
||||
// Not even text.
|
||||
sent.credential =
|
||||
Credential::Foreign { kind: "teamspeak", blob: Bytes::from_static(&[b'{', 0xff]) };
|
||||
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
|
||||
let SessionError::Protocol(text) = error else { panic!("a protocol error: {error:?}") };
|
||||
assert_eq!(text, "the TeamSpeak identity cannot be read: it is not text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_params_carry_what_the_session_needs_and_no_account_yet() {
|
||||
let sent = params(&VoiceOptions::new("ts.example.com", "nick"));
|
||||
assert!(sent.account.is_none());
|
||||
assert_eq!(sent.issuer_trust, IssuerTrust::Unknown);
|
||||
assert!(sent.linked.is_empty() && sent.host_pin.is_none());
|
||||
assert_eq!((sent.push_capacity, sent.timeout), (1024, Duration::from_secs(35)));
|
||||
let client = sent.hello.client.unwrap();
|
||||
assert_eq!(client.name, "Voelin");
|
||||
assert_eq!(sent.hello.version, 1);
|
||||
}
|
||||
|
||||
/// Why `connect_params` refused an address, if it did.
|
||||
fn refused(address: &str) -> Option<String> {
|
||||
let (media, _rx) = voelin_proto::test_util::media_channel();
|
||||
match connect_params(&VoiceOptions::new(address, "nick"), media, &Backends::empty()) {
|
||||
Ok(_) => None,
|
||||
Err(SessionError::Protocol(text)) => Some(text),
|
||||
Err(other) => panic!("{address}: {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bookmark_the_link_would_change_is_refused() {
|
||||
// A port that is no port, in any shape: the link would drop it and the
|
||||
// connection would go to the default port.
|
||||
for address in [
|
||||
"ts.example.com:99999",
|
||||
"ts.example.com:65536",
|
||||
"ts.example.com:0",
|
||||
"ts.example.com:abc",
|
||||
"ts.example.com:",
|
||||
"[::1]:70000",
|
||||
"[::1]:",
|
||||
"[::1]x",
|
||||
] {
|
||||
let text = refused(address).unwrap_or_else(|| panic!("{address} was accepted"));
|
||||
assert!(text.contains("65535") && text.contains(address), "{text}");
|
||||
}
|
||||
// A host the link would cut or decode: a `?` hides the channel behind the
|
||||
// next one, a `/` or `#` ends the host, a `%` is decoded.
|
||||
for address in [
|
||||
"",
|
||||
" ",
|
||||
"ts.example.com?x",
|
||||
"ts.example.com#x",
|
||||
"ts.example.com/x",
|
||||
"a b",
|
||||
"h%41",
|
||||
"[::1",
|
||||
] {
|
||||
let text = refused(address).unwrap_or_else(|| panic!("{address:?} was accepted"));
|
||||
assert!(text.starts_with("not a server address"), "{text}");
|
||||
}
|
||||
// The text names no query: a link keeps secrets in it.
|
||||
let text = refused("ts.example.com?password=hunter2").unwrap();
|
||||
assert!(!text.contains("hunter2"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bookmarks_a_server_has_come_back_with_their_channel() {
|
||||
for (address, host) in [
|
||||
("ts.example.com", "ts.example.com"),
|
||||
("ts.example.com:9987", "ts.example.com:9987"),
|
||||
(" ts.example.com:1 ", "ts.example.com:1"),
|
||||
("127.0.0.1:65535", "127.0.0.1:65535"),
|
||||
("[::1]:9987", "[::1]:9987"),
|
||||
// The brackets of a v6 address without a port are the link's to drop;
|
||||
// the TeamSpeak library reads both forms.
|
||||
("[::1]", "::1"),
|
||||
("::1", "::1"),
|
||||
("2001:db8::1", "2001:db8::1"),
|
||||
] {
|
||||
let mut options = VoiceOptions::new(address, "nick");
|
||||
options.channel = Some("Games/Raid".into());
|
||||
let got = back(&options);
|
||||
assert_eq!((got.address.as_str(), got.channel.as_deref()), (host, Some("Games/Raid")));
|
||||
}
|
||||
}
|
||||
|
||||
/// The normalisations of the round trip, listed in `docs/session-seam.md`
|
||||
/// (13): an empty option is none, and an empty nickname stays empty.
|
||||
#[test]
|
||||
fn empty_options_come_back_as_none() {
|
||||
let mut options = VoiceOptions::new("ts.example.com", "");
|
||||
options.server_password = Some(String::new());
|
||||
options.channel = Some(String::new());
|
||||
options.channel_password = Some(String::new());
|
||||
options.token = Some(String::new());
|
||||
let got = back(&options);
|
||||
assert!(got.nickname.is_empty());
|
||||
assert!(
|
||||
got.server_password.is_none()
|
||||
&& got.channel.is_none()
|
||||
&& got.channel_password.is_none()
|
||||
&& got.token.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ use anyhow::{Context, Result, bail};
|
||||
use base64::prelude::*;
|
||||
use tsclientlib::Version;
|
||||
|
||||
const VERSIONS_CSV: &str = include_str!("../../proto/tsproto-structs/declarations/Versions.csv");
|
||||
const VERSIONS_CSV: &str = include_str!("../../../proto/tsproto-structs/declarations/Versions.csv");
|
||||
|
||||
/// The signed generic version of every platform, tsclientlib's default.
|
||||
const GENERIC_VERSION: &str = "3.?.? [Build: 5680278000]";
|
||||
File diff suppressed because it is too large.
Load diff
@@ -960,11 +960,27 @@ pub(crate) mod tests {
|
||||
|
||||
/// What `f` logs at info (and above) on this thread: each line its
|
||||
/// message, then its fields (` name=value`).
|
||||
///
|
||||
/// One recording subscriber is installed for the whole test process, the
|
||||
/// first time this is called, and each call records into a buffer of its
|
||||
/// own thread. A scoped one (`tracing::subscriber::with_default`) loses
|
||||
/// lines: while it is the only subscriber alive, a callsite that another
|
||||
/// test's thread meets first is registered against that thread's own
|
||||
/// default, which is none, and stays disabled for every thread, so the
|
||||
/// lines of the test that reads them are gone
|
||||
/// (`session::banner_tests::a_failing_banner_is_logged_once_with_its_address`
|
||||
/// failed with no lines at all, once in about thirty runs of the suite).
|
||||
pub(crate) fn info_lines<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) {
|
||||
use std::cell::RefCell;
|
||||
use std::sync::Once;
|
||||
use tracing::field::{Field, Visit};
|
||||
use tracing::span;
|
||||
|
||||
struct Lines(Arc<Mutex<Vec<String>>>);
|
||||
thread_local! {
|
||||
/// The lines of the `info_lines` running on this thread, if any.
|
||||
static LINES: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Line(String, String);
|
||||
impl Visit for Line {
|
||||
@@ -975,7 +991,8 @@ pub(crate) mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
impl tracing::Subscriber for Lines {
|
||||
struct Recorder;
|
||||
impl tracing::Subscriber for Recorder {
|
||||
fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool {
|
||||
*metadata.level() <= tracing::Level::INFO
|
||||
}
|
||||
@@ -985,19 +1002,57 @@ pub(crate) mod tests {
|
||||
fn record(&self, _: &span::Id, _: &span::Record<'_>) {}
|
||||
fn record_follows_from(&self, _: &span::Id, _: &span::Id) {}
|
||||
fn event(&self, event: &tracing::Event<'_>) {
|
||||
let mut line = Line::default();
|
||||
event.record(&mut line);
|
||||
self.0.lock().unwrap().push(line.0 + &line.1);
|
||||
LINES.with(|lines| {
|
||||
if let Some(lines) = lines.borrow_mut().as_mut() {
|
||||
let mut line = Line::default();
|
||||
event.record(&mut line);
|
||||
lines.push(line.0 + &line.1);
|
||||
}
|
||||
});
|
||||
}
|
||||
fn enter(&self, _: &span::Id) {}
|
||||
fn exit(&self, _: &span::Id) {}
|
||||
}
|
||||
let lines = Arc::new(Mutex::new(Vec::new()));
|
||||
let result = tracing::subscriber::with_default(Lines(lines.clone()), f);
|
||||
let lines = lines.lock().unwrap().clone();
|
||||
/// Ends the recording of this thread, also when `f` panics.
|
||||
struct Recording;
|
||||
impl Drop for Recording {
|
||||
fn drop(&mut self) {
|
||||
LINES.with(|lines| lines.borrow_mut().take());
|
||||
}
|
||||
}
|
||||
|
||||
static INSTALL: Once = Once::new();
|
||||
INSTALL.call_once(|| {
|
||||
tracing::subscriber::set_global_default(Recorder)
|
||||
.expect("no other global tracing subscriber in the tests");
|
||||
// Makes every callsite decide again with the subscriber in place, also
|
||||
// one that a thread was registering while it was being installed
|
||||
// (creating a `Dispatch` rebuilds the cached interest of all of them).
|
||||
drop(tracing::Dispatch::new(Recorder));
|
||||
});
|
||||
|
||||
LINES.with(|lines| *lines.borrow_mut() = Some(Vec::new()));
|
||||
let _recording = Recording;
|
||||
let result = f();
|
||||
let lines = LINES.with(|lines| lines.borrow_mut().take().unwrap_or_default());
|
||||
(result, lines)
|
||||
}
|
||||
|
||||
/// The lines of `info_lines` do not depend on which thread met a callsite
|
||||
/// first: this one is met on another thread, which records nothing, before
|
||||
/// the thread that reads the lines meets it.
|
||||
#[test]
|
||||
fn info_lines_see_a_callsite_another_thread_met_first() {
|
||||
fn log() {
|
||||
tracing::info!("met");
|
||||
}
|
||||
let ((), lines) = info_lines(|| {
|
||||
std::thread::spawn(log).join().unwrap();
|
||||
log();
|
||||
});
|
||||
assert_eq!(lines, ["met"]);
|
||||
}
|
||||
|
||||
fn temp_dir(tag: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("voelin-web-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
@@ -1375,9 +1430,15 @@ pub(crate) mod tests {
|
||||
};
|
||||
let mut port = [0u8; 2];
|
||||
client.read_exact(&mut port).await.unwrap();
|
||||
let target = format!("{host}:{}", u16::from_be_bytes(port));
|
||||
let port = u16::from_be_bytes(port);
|
||||
let target = format!("{host}:{port}");
|
||||
targets.send(target.clone()).unwrap();
|
||||
let mut server = TcpStream::connect(target).await.unwrap();
|
||||
// The proxy resolves the name it is given (SOCKS5h). `localhost` is
|
||||
// 127.0.0.1 to it, whatever this machine's resolver says: some answer
|
||||
// `::1` only, and the servers of the tests listen on 127.0.0.1.
|
||||
let dial =
|
||||
if host == "localhost" { format!("127.0.0.1:{port}") } else { target };
|
||||
let mut server = TcpStream::connect(dial).await.unwrap();
|
||||
client.write_all(&[5, 0, 0, 1, 0, 0, 0, 0, 0, 0]).await.unwrap();
|
||||
let _ = tokio::io::copy_bidirectional(&mut client, &mut server).await;
|
||||
});
|
||||
|
||||
@@ -16,6 +16,7 @@ use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
|
||||
use voelin_core::gateway::{GatewayRequest, GatewayUpdate};
|
||||
use voelin_core::history::MessageSource;
|
||||
use voelin_core::settings::Settings;
|
||||
use voelin_core::ts::identity::to_blob;
|
||||
use voelin_core::{Command, Engine, Event, History, HistoryMessage, HistorySource, ObserveState};
|
||||
use voelin_gateway_proto::{
|
||||
ClientMsg, Envelope, ErrorCode, HistoryEntry, HistoryPage, PinInfo, ReactionCount, ServerMsg,
|
||||
@@ -448,7 +449,7 @@ fn observe(engine: &Engine, session: u64, gw: &FakeGateway) {
|
||||
engine.send(Command::ObserveGateway {
|
||||
session,
|
||||
urls: vec![gw.url.clone()],
|
||||
identity: Box::new(identity),
|
||||
identity: Box::new(to_blob(&identity)),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -742,7 +743,7 @@ async fn an_unreachable_gateway_is_tried_again_quietly() {
|
||||
engine.send(Command::ObserveGateway {
|
||||
session: 3,
|
||||
urls: vec![format!("ws://127.0.0.1:{port}/v1")],
|
||||
identity: Box::new(tsclientlib::Identity::create()),
|
||||
identity: Box::new(to_blob(&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.
|
||||
@@ -819,7 +820,7 @@ async fn the_next_published_gateway_is_used_when_one_fails() {
|
||||
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()),
|
||||
identity: Box::new(to_blob(&tsclientlib::Identity::create())),
|
||||
});
|
||||
// Within one round: sooner than the shortest wait after a failed round
|
||||
// (1 s, less 30 %).
|
||||
@@ -904,7 +905,7 @@ async fn a_login_the_gateway_cannot_do_yet_is_tried_again() {
|
||||
engine.send(Command::ObserveGateway {
|
||||
session,
|
||||
urls: vec![gw.url.clone()],
|
||||
identity: Box::new(tsclientlib::Identity::create()),
|
||||
identity: Box::new(to_blob(&tsclientlib::Identity::create())),
|
||||
});
|
||||
// After the first wait: about 1 s.
|
||||
quietly_until(&mut rx, session, Duration::from_secs(3), "observing", observing(session))
|
||||
@@ -932,6 +933,45 @@ async fn a_refused_login_ends_observing() {
|
||||
assert_eq!(gw.logins(), 1);
|
||||
}
|
||||
|
||||
/// An identity that cannot be read will not be better tomorrow: like a refused
|
||||
/// login, observing ends, and the gateway is not even asked.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_identity_that_cannot_be_read_ends_observing_without_a_login() {
|
||||
let gw = FakeGateway::start().await;
|
||||
let engine = Engine::start();
|
||||
let mut rx = engine.subscribe();
|
||||
let not_an_identity = voelin_core::IdentityBlob::teamspeak("x", 0, "not an identity");
|
||||
engine.send(Command::ObserveGateway {
|
||||
session: 10,
|
||||
urls: vec![gw.url.clone()],
|
||||
identity: Box::new(not_an_identity),
|
||||
});
|
||||
wait(&mut rx, "connecting", |e| match e {
|
||||
Event::State { session: 10, state } if state.observe == ObserveState::Connecting => {
|
||||
Some(())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
wait(&mut rx, "observing off", |e| match e {
|
||||
Event::State { session: 10, state } if state.observe == ObserveState::Off => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
assert_eq!(gw.logins(), 0);
|
||||
// The public entry refuses it the same way.
|
||||
let error = voelin_core::gateway::connect(
|
||||
&gw.url,
|
||||
&voelin_core::IdentityBlob::new("voelin", "x", 0, "{}"),
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.expect("a refusal");
|
||||
assert_eq!(error.code(), Some(ErrorCode::AuthFailed), "{error}");
|
||||
assert_eq!(gw.logins(), 0);
|
||||
}
|
||||
|
||||
/// 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")]
|
||||
@@ -944,7 +984,7 @@ async fn asking_again_while_connecting_tries_at_once() {
|
||||
let ask = || Command::ObserveGateway {
|
||||
session: 9,
|
||||
urls: vec![gw.url.clone()],
|
||||
identity: Box::new(identity.clone()),
|
||||
identity: Box::new(to_blob(&identity)),
|
||||
};
|
||||
engine.send(ask());
|
||||
// Three logins fail (waits of about 1 and 2 s); the next wait is about 5 s.
|
||||
|
||||
@@ -5,7 +5,10 @@ use std::time::Duration;
|
||||
|
||||
use tokio::sync::broadcast::Receiver;
|
||||
use tokio::time::{Instant, timeout_at};
|
||||
use voelin_core::{Command, Engine, Event, ObserveState, Source, VoiceOptions, VoiceState};
|
||||
use voelin_core::{
|
||||
Command, Engine, Event, ObserveState, QueryLogin, QueryTransport, Source, VoiceOptions,
|
||||
VoiceState,
|
||||
};
|
||||
use voelin_model::ChatTarget;
|
||||
|
||||
fn live() -> bool {
|
||||
@@ -45,7 +48,7 @@ async fn engine_roundtrip(voice_addr: &str, query: voelin_query::Connect) {
|
||||
.await;
|
||||
|
||||
// Session 2: invisible, through own query credentials.
|
||||
engine.send(Command::ObserveQuery { session: 2, connect: Box::new(query) });
|
||||
engine.send(Command::ObserveQuery { session: 2, connect: Box::new(login(&query)) });
|
||||
let (mut observing, mut sees_voice_client) = (false, false);
|
||||
wait_for(&mut events, "query presence with the voice client", |e| {
|
||||
match e {
|
||||
@@ -93,6 +96,24 @@ async fn engine_roundtrip(voice_addr: &str, query: voelin_query::Connect) {
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
|
||||
/// The credentials of a query connection, as the engine takes them.
|
||||
fn login(connect: &voelin_query::Connect) -> QueryLogin {
|
||||
QueryLogin {
|
||||
transport: match connect.transport {
|
||||
voelin_query::Transport::Raw => QueryTransport::Raw,
|
||||
voelin_query::Transport::Ssh => QueryTransport::Ssh,
|
||||
voelin_query::Transport::Http => QueryTransport::Http,
|
||||
},
|
||||
address: connect.addr.clone(),
|
||||
user: connect.user.clone(),
|
||||
secret: connect.secret.clone(),
|
||||
server_port: connect.server_port,
|
||||
server_id: connect.server_id,
|
||||
// The development servers allowlist their clients.
|
||||
allowlisted: connect.line.rate_limit.is_none(),
|
||||
}
|
||||
}
|
||||
|
||||
fn query(transport: voelin_query::Transport, addr: &str) -> voelin_query::Connect {
|
||||
voelin_query::Connect {
|
||||
transport,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//! The engine on a `voelin_proto::link::Session` that no TeamSpeak code
|
||||
//! made: `Engine::start_with_backends` takes the connector registry, and the
|
||||
//! scheme of a session's address picks the connector. The fake host of the
|
||||
//! protocol repository stands for a Voelin host here (the fuller tests of the
|
||||
//! seam on the fake host come with the next slice of
|
||||
//! `docs/session-seam.md`).
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::sync::broadcast;
|
||||
use voelin_core::settings::Settings;
|
||||
use voelin_core::{
|
||||
Backends, Command, Engine, Event, History, SessionState, VoiceOptions, VoiceState,
|
||||
};
|
||||
use voelin_proto::test_util::FakeConnector;
|
||||
use voelin_proto::v1::{self, entity::Kind};
|
||||
|
||||
const SESSION: u64 = 1;
|
||||
|
||||
async fn next<T>(
|
||||
events: &mut broadcast::Receiver<Event>,
|
||||
mut f: impl FnMut(Event) -> Option<T>,
|
||||
) -> T {
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
if let Some(t) = f(events.recv().await.expect("engine events")) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("an event in time")
|
||||
}
|
||||
|
||||
fn host_with_two_channels(connector: &FakeConnector) {
|
||||
let host = connector.host();
|
||||
let put = |kind: Kind| host.put(v1::Entity { kind: Some(kind) }).unwrap();
|
||||
put(Kind::Server(v1::Server {
|
||||
id: 1,
|
||||
name: "Fake Host".into(),
|
||||
uid: "fake-host".into(),
|
||||
default_channel_id: 10,
|
||||
..Default::default()
|
||||
}));
|
||||
for (id, name, position) in [(10, "Lobby", 0), (11, "Games", 1024)] {
|
||||
put(Kind::Channel(v1::Channel {
|
||||
id,
|
||||
server_id: 1,
|
||||
kind: v1::ChannelKind::Voice as i32,
|
||||
name: name.into(),
|
||||
position,
|
||||
..Default::default()
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_session_of_a_registered_connector_is_the_engines_voice_source() {
|
||||
let connector = FakeConnector::new();
|
||||
host_with_two_channels(&connector);
|
||||
let mut backends = Backends::empty();
|
||||
backends.register(Arc::new(connector.clone()));
|
||||
let engine = Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends);
|
||||
let mut events = engine.subscribe();
|
||||
|
||||
engine.send(Command::ConnectVoice {
|
||||
session: SESSION,
|
||||
options: Box::new(VoiceOptions::new("fake://host", "tester")),
|
||||
});
|
||||
let (name, backend) = next(&mut events, |e| match e {
|
||||
Event::ServerInfo { name, backend, .. } => Some((name, backend)),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!((name.as_str(), backend.product.as_str()), ("Fake Host", "voelin-fake"));
|
||||
let presence = next(&mut events, |e| match e {
|
||||
Event::Presence { presence, .. } if !presence.channels.is_empty() => Some(presence),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
let channels: Vec<_> =
|
||||
presence.channels.values().map(|c| (c.id, c.name.as_str(), c.order)).collect();
|
||||
assert_eq!(channels, [(10, "Lobby", 0), (11, "Games", 10)]);
|
||||
// The host was asked once, with the nickname and the TeamSpeak-shaped
|
||||
// credential the engine makes of its options for now.
|
||||
let connects = connector.connects();
|
||||
assert_eq!(connects.len(), 1);
|
||||
assert_eq!(connects[0].address, "fake://host");
|
||||
assert_eq!(connects[0].hello.nickname, "tester");
|
||||
|
||||
// A move is a request to the host; the host's voice state is where we are.
|
||||
engine.send(Command::MoveToChannel { session: SESSION, channel: 11, password: None });
|
||||
let state: SessionState = next(&mut events, |e| match e {
|
||||
Event::State { state, .. } if state.own_channel == Some(11) => Some(state),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(state.voice, VoiceState::Connected);
|
||||
|
||||
engine.send(Command::DisconnectVoice { session: SESSION });
|
||||
next(&mut events, |e| match e {
|
||||
Event::State { state, .. } if state.voice == VoiceState::Disconnected => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_address_no_connector_serves_fails_with_the_registry_s_words() {
|
||||
let engine =
|
||||
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), Backends::empty());
|
||||
let mut events = engine.subscribe();
|
||||
engine.send(Command::ConnectVoice {
|
||||
session: SESSION,
|
||||
options: Box::new(VoiceOptions::new("voelin://host/i/code", "tester")),
|
||||
});
|
||||
let error = next(&mut events, |e| match e {
|
||||
Event::Error { message, .. } => Some(message),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(error, "voice: no connector for voelin://host/i/code");
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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(())
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! in the client database). The round trips against real servers are in
|
||||
//! `scripts/it-smoke.sh` (`voelinctl engine`).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::sync::broadcast;
|
||||
@@ -22,6 +23,29 @@ async fn next<T>(rx: &mut broadcast::Receiver<Event>, mut f: impl FnMut(Event) -
|
||||
.expect("event in time")
|
||||
}
|
||||
|
||||
/// Wait until nothing has the SQLite database at `path` open any more, as when
|
||||
/// the process that had it has ended: SQLite deletes the write-ahead log
|
||||
/// (`<path>-wal`) when the last connection closes.
|
||||
///
|
||||
/// A dropped `Engine` is not that yet. Its task ends later, the history writer
|
||||
/// is joined there, and closing the connection checkpoints the log under an
|
||||
/// exclusive lock, with fsyncs. A connection opened meanwhile waits for the
|
||||
/// lock only as long as the busy timeout (5 s) and then fails with
|
||||
/// `DatabaseBusy`, which a loaded disk makes happen (with every fsync taking
|
||||
/// 6 s it happens every time).
|
||||
async fn closed(path: &Path) {
|
||||
let mut wal = path.as_os_str().to_owned();
|
||||
wal.push("-wal");
|
||||
let wal = PathBuf::from(wal);
|
||||
tokio::time::timeout(Duration::from_secs(120), async {
|
||||
while wal.exists() {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("the engine's database connection closed");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn requests_without_voice_fail_with_their_ids() {
|
||||
let engine = Engine::start();
|
||||
@@ -165,6 +189,7 @@ async fn contacts_are_kept_in_the_database() {
|
||||
engine.history().flush();
|
||||
}
|
||||
// A new engine attaches the database later: the contacts come back.
|
||||
closed(&path).await;
|
||||
let engine = Engine::start();
|
||||
let mut rx = engine.subscribe();
|
||||
engine.send(Command::AttachHistory(History::open(&path).unwrap()));
|
||||
|
||||
@@ -24,7 +24,7 @@ tokio = { version = "1", features = ["macros", "net", "rt", "sync"], optional =
|
||||
# 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"] }
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
voelin-model = { workspace = true }
|
||||
tsproto-types = { path = "../proto/tsproto-types" }
|
||||
|
||||
[lints]
|
||||
|
||||
@@ -29,7 +29,7 @@ toml = "1.1.6"
|
||||
tracing = "0.1.44"
|
||||
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
|
||||
voelin-gateway-proto = { path = "../voelin-gateway-proto" }
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
voelin-model = { workspace = true }
|
||||
voelin-observer = { path = "../voelin-observer" }
|
||||
voelin-query = { path = "../voelin-query" }
|
||||
|
||||
|
||||
@@ -40,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 }
|
||||
@@ -61,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"] }
|
||||
@@ -97,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"] }
|
||||
|
||||
@@ -95,7 +95,6 @@ impl FromStr for Codec {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "str0m")]
|
||||
impl From<Codec> for str0m::format::Codec {
|
||||
fn from(c: Codec) -> Self {
|
||||
match c {
|
||||
@@ -108,7 +107,6 @@ impl From<Codec> for str0m::format::Codec {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "str0m")]
|
||||
impl TryFrom<str0m::format::Codec> for Codec {
|
||||
type Error = Error;
|
||||
|
||||
@@ -226,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>,
|
||||
@@ -1039,7 +1039,6 @@ mod tests {
|
||||
assert_eq!(Codec::Av1.to_string(), "AV1");
|
||||
}
|
||||
|
||||
#[cfg(feature = "str0m")]
|
||||
#[test]
|
||||
fn str0m_mapping() {
|
||||
for c in Codec::ALL {
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
[package]
|
||||
name = "voelin-model"
|
||||
version = "0.1.0"
|
||||
description = "UI-facing domain model shared by the client engine, gateway and UI (no IO)."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = "1"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,94 +0,0 @@
|
||||
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,
|
||||
|
@@ -1,144 +0,0 @@
|
||||
//! 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());
|
||||
}
|
||||
}
|
||||
@@ -1,283 +0,0 @@
|
||||
//! Chat messages, from any source.
|
||||
//!
|
||||
//! Messages can link files in a channel's file browser: TeamSpeak clients
|
||||
//! post them as `[URL=ts3file://…]name[/URL]`; [`ChatMessage::file_refs`]
|
||||
//! finds them as [`FileRef`]s (for file cards) and [`FileRef::to_bbcode`]
|
||||
//! writes one.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::percent;
|
||||
use crate::presence::{ChannelId, ClientId};
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", content = "id", rename_all = "snake_case")]
|
||||
pub enum ChatTarget {
|
||||
/// Everyone on the server.
|
||||
Server,
|
||||
Channel(ChannelId),
|
||||
/// Private chat, by the other side's unique id when known.
|
||||
Private(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ChatMessage {
|
||||
pub target: ChatTarget,
|
||||
pub author_name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub author_uid: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub author_id: Option<ClientId>,
|
||||
pub text: String,
|
||||
/// Unix time in milliseconds.
|
||||
pub ts_ms: i64,
|
||||
/// Carried by a gateway or query relay rather than our own connection.
|
||||
#[serde(default)]
|
||||
pub via_relay: bool,
|
||||
/// The author is blocked in our contacts (set by the engine when it
|
||||
/// reports the message; never sent over the wire).
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub blocked: bool,
|
||||
}
|
||||
|
||||
impl ChatMessage {
|
||||
/// The file links in the text, in order of appearance, each once.
|
||||
pub fn file_refs(&self) -> Vec<FileRef> {
|
||||
parse_file_links(&self.text)
|
||||
}
|
||||
}
|
||||
|
||||
/// A file in a channel's file browser, as a chat message links it.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct FileRef {
|
||||
/// The server's unique id (`serverUID`), when the link tells it: a link
|
||||
/// from another server cannot be downloaded here.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub server_uid: Option<String>,
|
||||
pub channel: ChannelId,
|
||||
/// The directory, `/` for the channel's root.
|
||||
pub path: String,
|
||||
pub name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub size: Option<u64>,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub is_dir: bool,
|
||||
/// Unix seconds of the last change, when the link tells it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub modified_s: Option<i64>,
|
||||
/// The link as it appeared.
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
/// URL schemes of file links (`ts3file`; later clients may use others of
|
||||
/// the same form).
|
||||
const FILE_SCHEMES: &[&str] = &["ts3file://", "tsfile://", "ts5file://", "ts6file://"];
|
||||
|
||||
impl FileRef {
|
||||
/// The file's path in the channel: [`Self::path`] joined with [`Self::name`].
|
||||
pub fn full_path(&self) -> String {
|
||||
let dir = self.path.trim_end_matches('/');
|
||||
format!("{dir}/{}", self.name)
|
||||
}
|
||||
|
||||
/// Parse one link (`ts3file://name?serverUID=…&channel=…&path=…&filename=…&isDir=…&size=…&fileDateTime=…`).
|
||||
pub fn parse(url: &str) -> Option<Self> {
|
||||
let lower = url.get(..12).unwrap_or(url).to_ascii_lowercase();
|
||||
let scheme = FILE_SCHEMES.iter().find(|s| lower.starts_with(**s))?;
|
||||
let rest = &url[scheme.len()..];
|
||||
let (host, query) = rest.split_once('?').unwrap_or((rest, ""));
|
||||
let mut file = FileRef { url: url.to_owned(), path: "/".into(), ..Default::default() };
|
||||
let mut channel = None;
|
||||
for pair in query.split('&') {
|
||||
let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
|
||||
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(),
|
||||
"path" => file.path = if value.is_empty() { "/".into() } else { value },
|
||||
"filename" | "name" => file.name = value,
|
||||
"isdir" => file.is_dir = matches!(value.as_str(), "1" | "true"),
|
||||
"size" => file.size = value.parse().ok(),
|
||||
"filedatetime" => file.modified_s = value.parse().ok(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if file.name.is_empty() {
|
||||
file.name = percent::decode(host.trim_end_matches('/'));
|
||||
}
|
||||
file.channel = channel?;
|
||||
(!file.name.is_empty()).then_some(file)
|
||||
}
|
||||
|
||||
/// 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));
|
||||
if let Some(uid) = &self.server_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),
|
||||
u8::from(self.is_dir)
|
||||
));
|
||||
if let Some(size) = self.size {
|
||||
url.push_str(&format!("&size={size}"));
|
||||
}
|
||||
if let Some(t) = self.modified_s {
|
||||
url.push_str(&format!("&fileDateTime={t}"));
|
||||
}
|
||||
format!("[URL={url}]{}[/URL]", self.name)
|
||||
}
|
||||
}
|
||||
|
||||
/// The file links in `text` (BBCode `[URL=…]`, `[URL]…[/URL]`, Markdown
|
||||
/// `[name](…)` or bare), in order, each once.
|
||||
pub fn parse_file_links(text: &str) -> Vec<FileRef> {
|
||||
let lower = text.to_ascii_lowercase();
|
||||
let mut found: Vec<FileRef> = Vec::new();
|
||||
let mut at = 0;
|
||||
while at < text.len() {
|
||||
let next = FILE_SCHEMES.iter().filter_map(|s| lower[at..].find(s).map(|i| at + i)).min();
|
||||
let Some(start) = next else { break };
|
||||
let end = text[start..]
|
||||
.find(|c: char| c.is_whitespace() || matches!(c, ']' | '[' | ')' | '"' | '<' | '>'))
|
||||
.map_or(text.len(), |i| start + i);
|
||||
if let Some(file) = FileRef::parse(&text[start..end])
|
||||
&& !found.iter().any(|f| f.url == file.url)
|
||||
{
|
||||
found.push(file);
|
||||
}
|
||||
at = end.max(start + 1);
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// Split text so each part fits TeamSpeak's message limit (1024 bytes of
|
||||
/// text), breaking at character boundaries.
|
||||
pub fn split_message(text: &str, max_bytes: usize) -> Vec<String> {
|
||||
let mut parts = Vec::new();
|
||||
let mut current = String::new();
|
||||
for c in text.chars() {
|
||||
if current.len() + c.len_utf8() > max_bytes {
|
||||
parts.push(std::mem::take(&mut current));
|
||||
}
|
||||
current.push(c);
|
||||
}
|
||||
if !current.is_empty() || parts.is_empty() {
|
||||
parts.push(current);
|
||||
}
|
||||
parts
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn relay_format() {
|
||||
assert_eq!(relay_text("[{nick}] {text}", "Alice", "hi"), "[Alice] hi");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splits_on_char_boundaries() {
|
||||
assert_eq!(split_message("abcdef", 4), vec!["abcd", "ef"]);
|
||||
assert_eq!(split_message("", 4), vec![""]);
|
||||
let parts = split_message("ääää", 3);
|
||||
assert!(parts.iter().all(|p| p.len() <= 3));
|
||||
assert_eq!(parts.concat(), "ääää");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_ts3_file_links() {
|
||||
let text = "look: [URL=ts3file://Report%20Q3.pdf?serverUID=l%2FHvD5zXg5r4%2F%2FC6Ht7J9Ts3Wmc%3D&channel=5&path=%2Fdocs&filename=Report%20Q3.pdf&isDir=0&size=12345&fileDateTime=1454598011]Report Q3.pdf[/URL] and [URL]ts3file://a.txt?channel=1&path=%2F&filename=a+b.txt[/URL]";
|
||||
let files = parse_file_links(text);
|
||||
assert_eq!(files.len(), 2);
|
||||
let f = &files[0];
|
||||
assert_eq!(f.server_uid.as_deref(), Some("l/HvD5zXg5r4//C6Ht7J9Ts3Wmc="));
|
||||
assert_eq!((f.channel, f.path.as_str(), f.name.as_str()), (5, "/docs", "Report Q3.pdf"));
|
||||
assert_eq!((f.size, f.modified_s, f.is_dir), (Some(12345), Some(1_454_598_011), false));
|
||||
assert_eq!(f.full_path(), "/docs/Report Q3.pdf");
|
||||
assert_eq!(files[1].name, "a+b.txt");
|
||||
assert_eq!(files[1].full_path(), "/a+b.txt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_links_in_other_forms() {
|
||||
// Markdown, bare, a repeated link, a link without a channel.
|
||||
let text = "[x](ts3file://x?channel=2&filename=x&isDir=true) ts3file://y?channel=3&path=/d/ \
|
||||
ts3file://y?channel=3&path=/d/ ts3file://z?filename=z";
|
||||
let files = parse_file_links(text);
|
||||
assert_eq!(files.len(), 2);
|
||||
assert!(files[0].is_dir);
|
||||
assert_eq!((files[1].name.as_str(), files[1].full_path().as_str()), ("y", "/d/y"));
|
||||
let msg = ChatMessage {
|
||||
target: ChatTarget::Channel(1),
|
||||
author_name: "a".into(),
|
||||
author_uid: None,
|
||||
author_id: None,
|
||||
text: text.into(),
|
||||
ts_ms: 0,
|
||||
via_relay: false,
|
||||
blocked: false,
|
||||
};
|
||||
assert_eq!(msg.file_refs(), files);
|
||||
assert!(parse_file_links("no links, ts3file:// alone").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_link_round_trip() {
|
||||
let file = FileRef {
|
||||
server_uid: Some("uid+/=".into()),
|
||||
channel: 7,
|
||||
path: "/a dir".into(),
|
||||
name: "ä b&c.png".into(),
|
||||
size: Some(10),
|
||||
is_dir: false,
|
||||
modified_s: Some(99),
|
||||
url: String::new(),
|
||||
};
|
||||
let text = file.to_bbcode();
|
||||
let parsed = parse_file_links(&text);
|
||||
assert_eq!(parsed.len(), 1);
|
||||
assert_eq!(FileRef { url: String::new(), ..parsed[0].clone() }, file);
|
||||
assert!(text.ends_with("]ä b&c.png[/URL]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocked_flag_stays_off_the_wire() {
|
||||
let msg = ChatMessage {
|
||||
target: ChatTarget::Server,
|
||||
author_name: "a".into(),
|
||||
author_uid: None,
|
||||
author_id: None,
|
||||
text: "t".into(),
|
||||
ts_ms: 1,
|
||||
via_relay: false,
|
||||
blocked: false,
|
||||
};
|
||||
let json = serde_json::to_string(&msg).unwrap();
|
||||
assert!(!json.contains("blocked"));
|
||||
let back: ChatMessage = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back, msg);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_json() {
|
||||
assert_eq!(
|
||||
serde_json::to_string(&ChatTarget::Channel(5)).unwrap(),
|
||||
r#"{"kind":"channel","id":5}"#
|
||||
);
|
||||
assert_eq!(serde_json::to_string(&ChatTarget::Server).unwrap(), r#"{"kind":"server"}"#);
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
//! Domain model shared by the client engine, the gateway and the UI.
|
||||
//!
|
||||
//! 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, myts_avatar_url, parse_badges, shown_badges,
|
||||
};
|
||||
pub use server::{
|
||||
BannerMode, Capabilities, HostMessageMode, ServerDetails, ServerFlavor, ServerVersion,
|
||||
};
|
||||
pub use tree::{Spacer, TreeRow, channel_title, order_siblings, parse_spacer, tree_rows};
|
||||
@@ -1,420 +0,0 @@
|
||||
//! 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
//! 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%");
|
||||
}
|
||||
}
|
||||
@@ -1,493 +0,0 @@
|
||||
//! Who is where: channels and the clients in them.
|
||||
//!
|
||||
//! The same model is fed from a voice connection, a query session or a
|
||||
//! gateway. Sources send a [`PresenceSnapshot`] followed by
|
||||
//! [`PresenceDelta`]s; sources that can only poll use [`Presence::diff`].
|
||||
//!
|
||||
//! A voice connection also knows the server's details (welcome message,
|
||||
//! host banner, …) and its server and channel groups ([`Presence::server`],
|
||||
//! [`Presence::server_groups`], [`Presence::channel_groups`]); snapshots and
|
||||
//! deltas do not carry them (other sources leave them empty).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::server::{BannerMode, ServerDetails};
|
||||
|
||||
pub type ChannelId = u64;
|
||||
pub type ClientId = u16;
|
||||
/// A server or channel group id.
|
||||
pub type GroupId = u64;
|
||||
|
||||
fn is_zero_i32(n: &i32) -> bool {
|
||||
*n == 0
|
||||
}
|
||||
|
||||
fn is_zero_u32(n: &u32) -> bool {
|
||||
*n == 0
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
|
||||
fn is_default<T: Default + PartialEq>(v: &T) -> bool {
|
||||
*v == T::default()
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ChannelInfo {
|
||||
pub id: ChannelId,
|
||||
/// `0` for top-level channels.
|
||||
pub parent: ChannelId,
|
||||
/// Id of the sibling directly above, `0` for the first.
|
||||
pub order: ChannelId,
|
||||
pub name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub topic: Option<String>,
|
||||
#[serde(default)]
|
||||
pub has_password: bool,
|
||||
/// `None` means unlimited.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub max_clients: Option<i32>,
|
||||
#[serde(default)]
|
||||
pub needed_subscribe_power: i32,
|
||||
#[serde(default)]
|
||||
pub needed_talk_power: i32,
|
||||
#[serde(default)]
|
||||
pub is_default: bool,
|
||||
/// Icon id (`channel_icon_id`); 0: none.
|
||||
#[serde(default, skip_serializing_if = "is_zero_u32")]
|
||||
pub icon: u32,
|
||||
/// The address of the channel's banner picture (TeamSpeak 6,
|
||||
/// `channel_banner_gfx_url`), drawn behind the channel.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub banner_gfx_url: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "is_default")]
|
||||
pub banner_mode: BannerMode,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ClientInfo {
|
||||
pub id: ClientId,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub uid: Option<String>,
|
||||
pub nickname: String,
|
||||
pub channel: ChannelId,
|
||||
/// ServerQuery clients (bots, our own relays). UIs normally hide them.
|
||||
#[serde(default)]
|
||||
pub is_query: bool,
|
||||
/// Away, with the away message (empty without one); `None`: not away.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub away: Option<String>,
|
||||
#[serde(default)]
|
||||
pub input_muted: bool,
|
||||
#[serde(default)]
|
||||
pub output_muted: bool,
|
||||
/// `None` when the source cannot tell (query sessions see no voice).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub talking: Option<bool>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub streaming: Option<bool>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub server_groups: Vec<GroupId>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub country: Option<String>,
|
||||
/// MD5 hash of the client's avatar (`client_flag_avatar`, hex); `None`:
|
||||
/// 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")]
|
||||
pub talk_power: i32,
|
||||
/// Allowed to talk regardless of talk power (`client_is_talker`).
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub talker: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub channel_group: Option<GroupId>,
|
||||
/// 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.
|
||||
#[serde(default, skip_serializing_if = "is_zero_u32")]
|
||||
pub icon: u32,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub recording: bool,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub priority_speaker: bool,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub channel_commander: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub database_id: Option<u64>,
|
||||
}
|
||||
|
||||
/// Badge GUIDs of a `client_badges` value
|
||||
/// (`Overwolf=0:badges=<guid>,<guid>`).
|
||||
pub fn parse_badges(value: &str) -> Vec<String> {
|
||||
value
|
||||
.split(':')
|
||||
.filter_map(|part| part.strip_prefix("badges="))
|
||||
.flat_map(|list| list.split(','))
|
||||
.map(str::trim)
|
||||
.filter(|g| !g.is_empty())
|
||||
.map(str::to_owned)
|
||||
.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")]
|
||||
pub enum GroupNamingMode {
|
||||
#[default]
|
||||
None,
|
||||
/// Before the nickname: `[Admin] Alice`.
|
||||
Before,
|
||||
/// After the nickname: `Alice [Admin]`.
|
||||
After,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum GroupType {
|
||||
/// For new virtual servers; nobody is a member.
|
||||
Template,
|
||||
#[default]
|
||||
Regular,
|
||||
/// ServerQuery clients.
|
||||
Query,
|
||||
}
|
||||
|
||||
/// A server or channel group.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct GroupInfo {
|
||||
pub id: GroupId,
|
||||
pub name: String,
|
||||
/// Icon id; 0: none.
|
||||
#[serde(default, skip_serializing_if = "is_zero_u32")]
|
||||
pub icon: u32,
|
||||
/// Display order: lower first, then by id.
|
||||
#[serde(default)]
|
||||
pub sort_id: i32,
|
||||
#[serde(default)]
|
||||
pub naming_mode: GroupNamingMode,
|
||||
#[serde(default)]
|
||||
pub group_type: GroupType,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PresenceSnapshot {
|
||||
pub server_name: String,
|
||||
pub channels: Vec<ChannelInfo>,
|
||||
pub clients: Vec<ClientInfo>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum PresenceDelta {
|
||||
ChannelAdded(ChannelInfo),
|
||||
ChannelChanged(ChannelInfo),
|
||||
ChannelRemoved { id: ChannelId },
|
||||
ClientJoined(ClientInfo),
|
||||
ClientChanged(ClientInfo),
|
||||
ClientMoved { id: ClientId, channel: ChannelId },
|
||||
ClientLeft { id: ClientId },
|
||||
ServerRenamed { name: String },
|
||||
}
|
||||
|
||||
/// Current state; apply deltas as they arrive.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Presence {
|
||||
pub server_name: String,
|
||||
pub channels: BTreeMap<ChannelId, ChannelInfo>,
|
||||
pub clients: BTreeMap<ClientId, ClientInfo>,
|
||||
/// What the source knows about the server (a voice connection: all of
|
||||
/// it; other sources: nothing).
|
||||
pub server: ServerDetails,
|
||||
pub server_groups: BTreeMap<GroupId, GroupInfo>,
|
||||
pub channel_groups: BTreeMap<GroupId, GroupInfo>,
|
||||
}
|
||||
|
||||
impl Presence {
|
||||
pub fn from_snapshot(s: PresenceSnapshot) -> Self {
|
||||
Self {
|
||||
server_name: s.server_name,
|
||||
channels: s.channels.into_iter().map(|c| (c.id, c)).collect(),
|
||||
clients: s.clients.into_iter().map(|c| (c.id, c)).collect(),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The client with this unique id, if present (the first of several
|
||||
/// connections with the same identity).
|
||||
pub fn client_by_uid(&self, uid: &str) -> Option<&ClientInfo> {
|
||||
self.clients.values().find(|c| c.uid.as_deref() == Some(uid))
|
||||
}
|
||||
|
||||
/// Groups in display order (sort id, then id).
|
||||
pub fn sorted_groups(groups: &BTreeMap<GroupId, GroupInfo>) -> Vec<&GroupInfo> {
|
||||
let mut sorted: Vec<_> = groups.values().collect();
|
||||
sorted.sort_by_key(|g| (g.sort_id, g.id));
|
||||
sorted
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> PresenceSnapshot {
|
||||
PresenceSnapshot {
|
||||
server_name: self.server_name.clone(),
|
||||
channels: self.channels.values().cloned().collect(),
|
||||
clients: self.clients.values().cloned().collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply a delta. Returns `false` if it referred to something unknown
|
||||
/// (the caller may want to resynchronise).
|
||||
pub fn apply(&mut self, delta: &PresenceDelta) -> bool {
|
||||
match delta {
|
||||
PresenceDelta::ChannelAdded(c) | PresenceDelta::ChannelChanged(c) => {
|
||||
self.channels.insert(c.id, c.clone());
|
||||
true
|
||||
}
|
||||
PresenceDelta::ChannelRemoved { id } => self.channels.remove(id).is_some(),
|
||||
PresenceDelta::ClientJoined(c) | PresenceDelta::ClientChanged(c) => {
|
||||
self.clients.insert(c.id, c.clone());
|
||||
true
|
||||
}
|
||||
PresenceDelta::ClientMoved { id, channel } => match self.clients.get_mut(id) {
|
||||
Some(c) => {
|
||||
c.channel = *channel;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
PresenceDelta::ClientLeft { id } => self.clients.remove(id).is_some(),
|
||||
PresenceDelta::ServerRenamed { name } => {
|
||||
self.server_name = name.clone();
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Deltas that turn `self` into `new`, for sources that poll.
|
||||
pub fn diff(&self, new: &Presence) -> Vec<PresenceDelta> {
|
||||
let mut out = Vec::new();
|
||||
if self.server_name != new.server_name {
|
||||
out.push(PresenceDelta::ServerRenamed { name: new.server_name.clone() });
|
||||
}
|
||||
for (id, c) in &new.channels {
|
||||
match self.channels.get(id) {
|
||||
None => out.push(PresenceDelta::ChannelAdded(c.clone())),
|
||||
Some(old) if old != c => out.push(PresenceDelta::ChannelChanged(c.clone())),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for (id, c) in &new.clients {
|
||||
match self.clients.get(id) {
|
||||
None => out.push(PresenceDelta::ClientJoined(c.clone())),
|
||||
Some(old) if old == c => {}
|
||||
Some(old) if ClientInfo { channel: c.channel, ..old.clone() } == *c => {
|
||||
out.push(PresenceDelta::ClientMoved { id: *id, channel: c.channel });
|
||||
}
|
||||
Some(_) => out.push(PresenceDelta::ClientChanged(c.clone())),
|
||||
}
|
||||
}
|
||||
for id in self.clients.keys().filter(|id| !new.clients.contains_key(id)) {
|
||||
out.push(PresenceDelta::ClientLeft { id: *id });
|
||||
}
|
||||
// Channels last, so clients leave a removed channel first.
|
||||
for id in self.channels.keys().filter(|id| !new.channels.contains_key(id)) {
|
||||
out.push(PresenceDelta::ChannelRemoved { id: *id });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Clients in a channel, excluding query clients.
|
||||
pub fn members(&self, channel: ChannelId) -> impl Iterator<Item = &ClientInfo> {
|
||||
self.clients.values().filter(move |c| c.channel == channel && !c.is_query)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ch(id: u64, name: &str) -> ChannelInfo {
|
||||
ChannelInfo { id, name: name.into(), ..Default::default() }
|
||||
}
|
||||
|
||||
fn cl(id: u16, name: &str, channel: u64) -> ClientInfo {
|
||||
ClientInfo { id, nickname: name.into(), channel, ..Default::default() }
|
||||
}
|
||||
|
||||
fn presence(channels: Vec<ChannelInfo>, clients: Vec<ClientInfo>) -> Presence {
|
||||
Presence::from_snapshot(PresenceSnapshot { server_name: "s".into(), channels, clients })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diff_then_apply_reaches_target() {
|
||||
let old = presence(
|
||||
vec![ch(1, "Lobby"), ch(2, "Games")],
|
||||
vec![cl(1, "Alice", 1), cl(2, "Bob", 1), cl(3, "Carol", 2)],
|
||||
);
|
||||
let mut muted = cl(2, "Bob", 1);
|
||||
muted.input_muted = true;
|
||||
let new = presence(
|
||||
vec![ch(1, "Lobby"), ch(3, "New")],
|
||||
vec![cl(1, "Alice", 3), muted, cl(4, "Dave", 1)],
|
||||
);
|
||||
let deltas = old.diff(&new);
|
||||
assert!(deltas.contains(&PresenceDelta::ClientMoved { id: 1, channel: 3 }));
|
||||
assert!(deltas.contains(&PresenceDelta::ClientLeft { id: 3 }));
|
||||
assert!(deltas.contains(&PresenceDelta::ChannelRemoved { id: 2 }));
|
||||
assert!(deltas.iter().any(|d| matches!(d, PresenceDelta::ClientChanged(c) if c.id == 2)));
|
||||
let mut state = old.clone();
|
||||
for d in &deltas {
|
||||
assert!(state.apply(d));
|
||||
}
|
||||
assert_eq!(state, new);
|
||||
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!(
|
||||
parse_badges(
|
||||
"Overwolf=0:badges=c9e97536-5a2d-4c8e-a135-af404587a472,450f81c1-ab41-4211-a338-222fa94ed157"
|
||||
),
|
||||
["c9e97536-5a2d-4c8e-a135-af404587a472", "450f81c1-ab41-4211-a338-222fa94ed157"]
|
||||
);
|
||||
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();
|
||||
assert_eq!(order, [2, 3, 1]);
|
||||
let mut alice = cl(1, "Alice", 1);
|
||||
alice.uid = Some("A=".into());
|
||||
let p = presence(vec![ch(1, "Lobby")], vec![alice, cl(2, "Bob", 1)]);
|
||||
assert_eq!(p.client_by_uid("A=").map(|c| c.id), Some(1));
|
||||
assert!(p.client_by_uid("B=").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_json_without_new_fields() {
|
||||
let c: ClientInfo =
|
||||
serde_json::from_str(r#"{"id":1,"nickname":"a","channel":2,"away":""}"#).unwrap();
|
||||
assert_eq!(c.away.as_deref(), Some(""));
|
||||
assert_eq!((c.talk_power, c.avatar.as_ref(), c.badges.len()), (0, None, 0));
|
||||
// Defaults stay off the wire.
|
||||
assert_eq!(
|
||||
serde_json::to_string(&cl(1, "a", 2)).unwrap(),
|
||||
r#"{"id":1,"nickname":"a","channel":2,"is_query":false,"input_muted":false,"output_muted":false}"#
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn members_skip_query_clients() {
|
||||
let mut bot = cl(9, "bot", 1);
|
||||
bot.is_query = true;
|
||||
let p = presence(vec![ch(1, "Lobby")], vec![cl(1, "Alice", 1), bot]);
|
||||
assert_eq!(p.members(1).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delta_json_is_tagged() {
|
||||
let json =
|
||||
serde_json::to_string(&PresenceDelta::ClientMoved { id: 1, channel: 3 }).unwrap();
|
||||
assert_eq!(json, r#"{"kind":"client_moved","id":1,"channel":3}"#);
|
||||
let back: PresenceDelta = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back, PresenceDelta::ClientMoved { id: 1, channel: 3 });
|
||||
}
|
||||
}
|
||||
@@ -1,250 +0,0 @@
|
||||
//! Server software detection and the capabilities that follow from it.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Parsed `virtualserver_version`, e.g. `3.13.8 [Build: 1779874471]` or
|
||||
/// `6.0.0-beta13.1 [Build: 1790080330]`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub struct ServerVersion {
|
||||
pub major: u32,
|
||||
pub minor: u32,
|
||||
pub patch: u32,
|
||||
/// Pre-release tag such as `beta13.1`.
|
||||
pub pre: Option<String>,
|
||||
/// Build timestamp (seconds since the Unix epoch).
|
||||
pub build: Option<u64>,
|
||||
}
|
||||
|
||||
impl ServerVersion {
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
let s = s.trim();
|
||||
let (version, rest) = s.split_once(' ').unwrap_or((s, ""));
|
||||
let build = rest
|
||||
.trim()
|
||||
.strip_prefix("[Build:")
|
||||
.and_then(|b| b.strip_suffix(']'))
|
||||
.and_then(|b| b.trim().parse().ok());
|
||||
let (numbers, pre) = match version.split_once('-') {
|
||||
Some((n, p)) => (n, Some(p.to_string())),
|
||||
None => (version, None),
|
||||
};
|
||||
let mut parts = numbers.split('.').map(|p| p.parse::<u32>());
|
||||
let major = parts.next()?.ok()?;
|
||||
let minor = parts.next().unwrap_or(Ok(0)).ok()?;
|
||||
let patch = parts.next().unwrap_or(Ok(0)).ok()?;
|
||||
Some(Self { major, minor, patch, pre, build })
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ServerVersion {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)?;
|
||||
if let Some(pre) = &self.pre {
|
||||
write!(f, "-{pre}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Which server software we are talking to.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum ServerFlavor {
|
||||
/// TeamSpeak 3 server (3.x).
|
||||
Ts3(ServerVersion),
|
||||
/// TeamSpeak 6 server (6.x; TeamSpeak 5 server betas are treated alike).
|
||||
Ts6(ServerVersion),
|
||||
/// Unparseable or unexpected version string.
|
||||
Unknown(String),
|
||||
}
|
||||
|
||||
impl ServerFlavor {
|
||||
/// Classify a `virtualserver_version` string.
|
||||
pub fn from_version_string(s: &str) -> Self {
|
||||
match ServerVersion::parse(s) {
|
||||
Some(v) if v.major == 3 => ServerFlavor::Ts3(v),
|
||||
Some(v) if v.major >= 5 => ServerFlavor::Ts6(v),
|
||||
_ => ServerFlavor::Unknown(s.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn version(&self) -> Option<&ServerVersion> {
|
||||
match self {
|
||||
ServerFlavor::Ts3(v) | ServerFlavor::Ts6(v) => Some(v),
|
||||
ServerFlavor::Unknown(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn capabilities(&self) -> Capabilities {
|
||||
match self {
|
||||
ServerFlavor::Ts3(_) => Capabilities {
|
||||
streams: false,
|
||||
raw_query: true,
|
||||
ssh_query: true,
|
||||
http_query: false,
|
||||
file_transfer: true,
|
||||
offline_messages: true,
|
||||
},
|
||||
// Verified against 6.0.0-beta13.1: file transfer and offline
|
||||
// messages work as on TeamSpeak 3.
|
||||
ServerFlavor::Ts6(_) => Capabilities {
|
||||
streams: true,
|
||||
raw_query: false,
|
||||
ssh_query: true,
|
||||
http_query: true,
|
||||
file_transfer: true,
|
||||
offline_messages: true,
|
||||
},
|
||||
ServerFlavor::Unknown(_) => Capabilities::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the host message shows.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum HostMessageMode {
|
||||
/// Not shown.
|
||||
#[default]
|
||||
None,
|
||||
/// In the chat log.
|
||||
Log,
|
||||
/// In a dialog.
|
||||
Modal,
|
||||
/// In a dialog; the connection ends when it is closed.
|
||||
ModalQuit,
|
||||
}
|
||||
|
||||
/// How a banner picture (the host banner, a TeamSpeak 6 channel banner) is
|
||||
/// scaled to its area: `0`, `1` and `2` on the wire.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum BannerMode {
|
||||
/// As it is.
|
||||
#[default]
|
||||
NoAdjust,
|
||||
/// Stretched to the banner area.
|
||||
IgnoreAspect,
|
||||
/// Scaled to fit, keeping its aspect ratio.
|
||||
KeepAspect,
|
||||
}
|
||||
|
||||
impl BannerMode {
|
||||
/// From its number on the wire; an unknown one shows the picture as it
|
||||
/// is.
|
||||
pub fn from_wire(value: &str) -> Self {
|
||||
match value.trim() {
|
||||
"1" => Self::IgnoreAspect,
|
||||
"2" => Self::KeepAspect,
|
||||
_ => Self::NoAdjust,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a server tells its (voice) clients about itself.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ServerDetails {
|
||||
pub name: String,
|
||||
/// `virtualserver_unique_identifier` (the key of its chat history).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub uid: Option<String>,
|
||||
#[serde(default)]
|
||||
pub welcome_message: String,
|
||||
#[serde(default)]
|
||||
pub host_message: String,
|
||||
#[serde(default)]
|
||||
pub host_message_mode: HostMessageMode,
|
||||
/// Where a click on the banner leads.
|
||||
#[serde(default)]
|
||||
pub banner_url: String,
|
||||
/// The banner image.
|
||||
#[serde(default)]
|
||||
pub banner_gfx_url: String,
|
||||
/// Reload the banner image this often (seconds); 0: never.
|
||||
#[serde(default)]
|
||||
pub banner_gfx_interval_s: u64,
|
||||
#[serde(default)]
|
||||
pub banner_mode: BannerMode,
|
||||
#[serde(default)]
|
||||
pub host_button_tooltip: String,
|
||||
#[serde(default)]
|
||||
pub host_button_url: String,
|
||||
/// The host button's image.
|
||||
#[serde(default)]
|
||||
pub host_button_gfx_url: String,
|
||||
/// Icon id (`virtualserver_icon_id`); 0: none.
|
||||
#[serde(default)]
|
||||
pub icon: u32,
|
||||
/// Server platform, e.g. `Linux`.
|
||||
#[serde(default)]
|
||||
pub platform: String,
|
||||
/// `virtualserver_version`, e.g. `3.13.8 [Build: 1779874471]`.
|
||||
#[serde(default)]
|
||||
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")]
|
||||
pub default_channel_group: Option<u64>,
|
||||
}
|
||||
|
||||
/// Features that depend on the server software.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct Capabilities {
|
||||
/// Screen sharing / video streams (TeamSpeak 6).
|
||||
pub streams: bool,
|
||||
/// Raw TCP ServerQuery (TeamSpeak 3 only; may still be disabled by the admin).
|
||||
pub raw_query: bool,
|
||||
/// SSH ServerQuery.
|
||||
pub ssh_query: bool,
|
||||
/// HTTP WebQuery (TeamSpeak 6), request/response only, no events.
|
||||
pub http_query: bool,
|
||||
/// Channel file browsers, avatars and icons (`ftinit*` over TCP).
|
||||
#[serde(default)]
|
||||
pub file_transfer: bool,
|
||||
/// Offline messages to a unique id (`messageadd`, `messagelist`, …).
|
||||
#[serde(default)]
|
||||
pub offline_messages: bool,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_ts3() {
|
||||
let v = ServerVersion::parse("3.13.8 [Build: 1779874471]").unwrap();
|
||||
assert_eq!((v.major, v.minor, v.patch), (3, 13, 8));
|
||||
assert_eq!(v.pre, None);
|
||||
assert_eq!(v.build, Some(1_779_874_471));
|
||||
let flavor = ServerFlavor::from_version_string("3.13.8 [Build: 1779874471]");
|
||||
assert!(matches!(flavor, ServerFlavor::Ts3(_)));
|
||||
assert!(!flavor.capabilities().streams);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_ts6_beta() {
|
||||
let s = "6.0.0-beta13.1 [Build: 1790080330]";
|
||||
let v = ServerVersion::parse(s).unwrap();
|
||||
assert_eq!(v.pre.as_deref(), Some("beta13.1"));
|
||||
assert_eq!(v.to_string(), "6.0.0-beta13.1");
|
||||
let flavor = ServerFlavor::from_version_string(s);
|
||||
assert!(matches!(flavor, ServerFlavor::Ts6(_)));
|
||||
assert!(flavor.capabilities().streams);
|
||||
assert!(!flavor.capabilities().raw_query);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_garbage() {
|
||||
assert!(matches!(ServerFlavor::from_version_string(""), ServerFlavor::Unknown(_)));
|
||||
assert!(matches!(ServerFlavor::from_version_string("x.y"), ServerFlavor::Unknown(_)));
|
||||
assert_eq!(ServerVersion::parse("3").unwrap().minor, 0);
|
||||
}
|
||||
}
|
||||
@@ -1,192 +0,0 @@
|
||||
//! Flatten presence into display rows in TeamSpeak's channel order, and
|
||||
//! read the names of spacer channels.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::presence::{ChannelId, ChannelInfo, ClientInfo, Presence};
|
||||
|
||||
/// One line of a channel tree.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum TreeRow<'a> {
|
||||
Channel { depth: usize, channel: &'a ChannelInfo },
|
||||
Client { depth: usize, client: &'a ClientInfo },
|
||||
}
|
||||
|
||||
/// Sort siblings by following the `order` links (each channel names the
|
||||
/// sibling directly above it). Channels whose predecessor is missing are
|
||||
/// appended at the end, sorted by id, so nothing is ever dropped.
|
||||
pub fn order_siblings(mut siblings: Vec<&ChannelInfo>) -> Vec<&ChannelInfo> {
|
||||
siblings.sort_by_key(|c| c.id);
|
||||
let mut by_prev: HashMap<ChannelId, &ChannelInfo> = HashMap::new();
|
||||
for c in &siblings {
|
||||
by_prev.entry(c.order).or_insert(c);
|
||||
}
|
||||
let mut sorted = Vec::with_capacity(siblings.len());
|
||||
let mut prev = 0;
|
||||
while let Some(c) = by_prev.remove(&prev) {
|
||||
sorted.push(c);
|
||||
prev = c.id;
|
||||
}
|
||||
for c in siblings {
|
||||
if !sorted.iter().any(|s| s.id == c.id) {
|
||||
sorted.push(c);
|
||||
}
|
||||
}
|
||||
sorted
|
||||
}
|
||||
|
||||
/// Channels and their (non-query) clients, depth-first. Clients are sorted by
|
||||
/// name; `collapsed` channels hide their sub-channels and clients.
|
||||
pub fn tree_rows<'a>(p: &'a Presence, collapsed: &dyn Fn(ChannelId) -> bool) -> Vec<TreeRow<'a>> {
|
||||
let mut rows = Vec::new();
|
||||
add_level(p, 0, 0, collapsed, &mut rows);
|
||||
rows
|
||||
}
|
||||
|
||||
fn add_level<'a>(
|
||||
p: &'a Presence,
|
||||
parent: ChannelId,
|
||||
depth: usize,
|
||||
collapsed: &dyn Fn(ChannelId) -> bool,
|
||||
rows: &mut Vec<TreeRow<'a>>,
|
||||
) {
|
||||
let siblings = order_siblings(p.channels.values().filter(|c| c.parent == parent).collect());
|
||||
for channel in siblings {
|
||||
rows.push(TreeRow::Channel { depth, channel });
|
||||
if collapsed(channel.id) {
|
||||
continue;
|
||||
}
|
||||
let mut members: Vec<_> = p.members(channel.id).collect();
|
||||
members.sort_by(|a, b| a.nickname.to_lowercase().cmp(&b.nickname.to_lowercase()));
|
||||
for client in members {
|
||||
rows.push(TreeRow::Client { depth: depth + 1, client });
|
||||
}
|
||||
add_level(p, channel.id, depth + 1, collapsed, rows);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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::*;
|
||||
use crate::presence::PresenceSnapshot;
|
||||
|
||||
fn ch(id: u64, parent: u64, order: u64, name: &str) -> ChannelInfo {
|
||||
ChannelInfo { id, parent, order, name: name.into(), ..Default::default() }
|
||||
}
|
||||
|
||||
fn cl(id: u16, name: &str, channel: u64) -> ClientInfo {
|
||||
ClientInfo { id, nickname: name.into(), channel, ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn follows_order_links() {
|
||||
let channels = [ch(5, 0, 3, "c"), ch(3, 0, 7, "b"), ch(7, 0, 0, "a")];
|
||||
let names: Vec<_> =
|
||||
order_siblings(channels.iter().collect()).iter().map(|c| c.name.as_str()).collect();
|
||||
assert_eq!(names, ["a", "b", "c"]);
|
||||
let broken = [ch(1, 0, 0, "a"), ch(2, 0, 99, "orphan")];
|
||||
assert_eq!(order_siblings(broken.iter().collect())[1].name, "orphan");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_depth_first_with_collapse() {
|
||||
let mut bot = cl(9, "bot", 1);
|
||||
bot.is_query = true;
|
||||
let p = Presence::from_snapshot(PresenceSnapshot {
|
||||
server_name: "s".into(),
|
||||
channels: vec![ch(1, 0, 0, "Lobby"), ch(2, 0, 1, "Games"), ch(3, 2, 0, "Squad")],
|
||||
clients: vec![cl(1, "zed", 1), cl(2, "Alice", 1), bot, cl(3, "Bob", 3)],
|
||||
});
|
||||
let describe = |rows: Vec<TreeRow>| -> Vec<String> {
|
||||
rows.iter()
|
||||
.map(|r| match r {
|
||||
TreeRow::Channel { depth, channel } => format!("{depth}#{}", channel.name),
|
||||
TreeRow::Client { depth, client } => format!("{depth}-{}", client.nickname),
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(
|
||||
describe(tree_rows(&p, &|_| false)),
|
||||
["0#Lobby", "1-Alice", "1-zed", "0#Games", "1#Squad", "2-Bob"]
|
||||
);
|
||||
assert_eq!(
|
||||
describe(tree_rows(&p, &|c| c == 2)),
|
||||
["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));
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ publish.workspace = true
|
||||
thiserror = "2"
|
||||
tokio = { version = "1", features = ["macros", "rt", "sync", "time"] }
|
||||
tracing = "0.1"
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
voelin-model = { workspace = true }
|
||||
voelin-query = { path = "../voelin-query" }
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
//! The desktop's proxy through a stand-in xdg-desktop-portal on the
|
||||
//! session bus. Run it on a private bus:
|
||||
//! `dbus-run-session -- cargo test -p voelin-platform --test proxy`;
|
||||
//! without a session bus it checks nothing. Its own test binary: answers
|
||||
//! are kept process-wide.
|
||||
//! The desktop's proxy through a stand-in xdg-desktop-portal on a session
|
||||
//! bus. The test runs itself again under `dbus-run-session` on a bus of its
|
||||
//! own that starts no services: on a desktop's bus the real portal is running
|
||||
//! or startable, and when the stand-in leaves the bus (as the test has it do)
|
||||
//! the real one is started and answers instead. Without `dbus-run-session`,
|
||||
//! or a bus daemon for it, the test says so and checks nothing. Its own test
|
||||
//! binary: answers are kept process-wide.
|
||||
|
||||
#![cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
|
||||
|
||||
@@ -11,6 +13,9 @@ use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
use voelin_platform::proxy::proxy_for;
|
||||
|
||||
/// Set for the run on the bus of its own.
|
||||
const ON_ITS_OWN_BUS: &str = "VOELIN_PROXY_TEST_ON_ITS_OWN_BUS";
|
||||
|
||||
/// What the GNOME portal answers: a SOCKS proxy for one host, none for the
|
||||
/// others.
|
||||
struct Resolver {
|
||||
@@ -34,10 +39,67 @@ impl Resolver {
|
||||
}
|
||||
}
|
||||
|
||||
/// The configuration of the bus of its own: a session bus without the service
|
||||
/// directories, so that nothing on it can be started by name. Its socket is
|
||||
/// made in `dir`.
|
||||
fn bus_config(dir: &std::path::Path) -> String {
|
||||
format!(
|
||||
r#"<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
|
||||
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
|
||||
<busconfig>
|
||||
<type>session</type>
|
||||
<listen>unix:tmpdir={}</listen>
|
||||
<auth>EXTERNAL</auth>
|
||||
<policy context="default">
|
||||
<allow send_destination="*" eavesdrop="true"/>
|
||||
<allow eavesdrop="true"/>
|
||||
<allow own="*"/>
|
||||
</policy>
|
||||
</busconfig>
|
||||
"#,
|
||||
dir.display()
|
||||
)
|
||||
}
|
||||
|
||||
/// Run this test again under `dbus-run-session` on a bus of its own, and say
|
||||
/// nothing was checked when that bus cannot be had.
|
||||
fn on_a_bus_of_its_own() {
|
||||
let dir = std::env::temp_dir();
|
||||
let config = dir.join(format!("voelin-proxy-test-bus-{}.conf", std::process::id()));
|
||||
std::fs::write(&config, bus_config(&dir)).unwrap();
|
||||
let run = std::process::Command::new("dbus-run-session")
|
||||
.arg(format!("--config-file={}", config.display()))
|
||||
.arg("--")
|
||||
.arg(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "the_portal_names_the_proxy", "--nocapture", "--test-threads=1"])
|
||||
.env(ON_ITS_OWN_BUS, "1")
|
||||
.output();
|
||||
let _ = std::fs::remove_file(&config);
|
||||
let run = match run {
|
||||
Ok(run) => run,
|
||||
Err(e) => {
|
||||
eprintln!("skipped, nothing was checked: dbus-run-session cannot be run ({e})");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let text =
|
||||
format!("{}{}", String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
|
||||
if run.status.success() {
|
||||
return;
|
||||
}
|
||||
// The test ran and failed, or the bus never came up.
|
||||
assert!(
|
||||
!text.contains("running 1 test"),
|
||||
"the test failed on its own bus ({}):\n{text}",
|
||||
run.status
|
||||
);
|
||||
eprintln!("skipped, nothing was checked: no bus of its own could be started:\n{text}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_portal_names_the_proxy() {
|
||||
if std::env::var_os("DBUS_SESSION_BUS_ADDRESS").is_none() {
|
||||
eprintln!("no session bus: run under dbus-run-session");
|
||||
if std::env::var_os(ON_ITS_OWN_BUS).is_none() {
|
||||
on_a_bus_of_its_own();
|
||||
return;
|
||||
}
|
||||
let lookups = Arc::new(AtomicU32::new(0));
|
||||
|
||||
@@ -19,7 +19,9 @@ rusqlite = { version = "0.40.2", features = ["bundled"] }
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_json = "1.0.151"
|
||||
thiserror = "2.0.21"
|
||||
tracing = "0.1.44"
|
||||
tsclientlib = { path = "../proto/tsclientlib" }
|
||||
voelin-identity = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,587 @@
|
||||
//! The `identities` table as a [`voelin_identity::KeyStore`].
|
||||
//!
|
||||
//! The table holds identities of more than one kind: the TeamSpeak identities
|
||||
//! the client has always had (`kind` `teamspeak`, `data` the JSON of a
|
||||
//! `tsproto::Identity`), a Voelin key (`voelin`), the record of the account the
|
||||
//! installation is signed in to (`account`) and whatever kind a later version
|
||||
//! adds, which passes through untouched. A row is addressed by its
|
||||
//! `(kind, uid)`, and `uid` stays `UNIQUE` across kinds: the uid forms of the
|
||||
//! kinds do not overlap (a TeamSpeak uid is base64, a Voelin uid 52 characters
|
||||
//! of `a-z2-7`, an account uid is written `account:<uid>`).
|
||||
//!
|
||||
//! Besides the blob a row carries the columns of the TeamSpeak-only world,
|
||||
//! which a [`KeyStore`] does not see and keeps when it replaces a row: `name`,
|
||||
//! `origin`, `is_default` and `created`. A blob of a new `(kind, uid)` becomes a
|
||||
//! row named after its uid, of origin `user` and not the default.
|
||||
//!
|
||||
//! The TeamSpeak security level is not stored: it is computed from the key and
|
||||
//! counter in `data`, as [`Store::identities`] always did, and the level of a
|
||||
//! blob a caller puts is ignored. A TeamSpeak row whose JSON cannot be read
|
||||
//! (it could only have been damaged outside this crate) lists and reads with
|
||||
//! level 0 instead of failing the whole list, and a [`KeyStore::put`] that only
|
||||
//! changes the binding of a row (the row of that `(kind, uid)` already holds
|
||||
//! that `data`, as [`KeyStore::get`] reads it) writes the four binding columns,
|
||||
//! does not look at `data` again and does not rewrite it. That is how
|
||||
//! [`KeyStore::sign_out`] unbinds a device-only secret: a row whose `data` was
|
||||
//! damaged outside this crate (JSON that is no identity, a BLOB, bytes that are
|
||||
//! no UTF-8) does not keep the sign-out from unbinding it, and its `data` is
|
||||
//! kept byte for byte.
|
||||
//!
|
||||
//! A row that is damaged elsewhere never fails a call that is not about it. A
|
||||
//! row whose binding columns cannot be read (`synced = 2`, an `account` that is
|
||||
//! no uid, a revision that is no integer; only something outside this crate
|
||||
//! writes them) is listed and read as unbound, and a warning names the row and
|
||||
//! the reason. [`KeyStore::list`] fails only when the database does, because
|
||||
//! the trait's [`KeyStore::sign_out`] starts with it and then reads the account
|
||||
//! record and the device key with [`KeyStore::get`]: one damaged row, the
|
||||
//! record's own included, would otherwise keep a sign-out from ever finishing,
|
||||
//! and with it the deletion of the key the user asked to forget. Unbound is the
|
||||
//! reading that never deletes on a guess: a sign-out neither deletes such a row
|
||||
//! as a synced copy nor writes it, it stays as it is until a `put` of it writes
|
||||
//! four good binding columns. A `data` column that is not text (a BLOB, or text
|
||||
//! of bytes that are no UTF-8) is read as text with the odd bytes replaced, so
|
||||
//! that a record that cannot be read is deleted by the sign-out, as the trait
|
||||
//! says, instead of its read failing. A [`KeyStore::put`] of the text that
|
||||
//! [`KeyStore::get`] returned for such a row is taken for the data that is
|
||||
//! there: it changes the binding and keeps the stored bytes, where any other
|
||||
//! text replaces them (a TeamSpeak blob still has to be an identity). A row
|
||||
//! whose `kind` or `uid` is not text cannot be addressed, and the list leaves it
|
||||
//! out with a warning.
|
||||
//!
|
||||
//! The rows are private keys, so a removed row is not left behind in the file:
|
||||
//! every connection sets `secure_delete`, which makes SQLite overwrite what it
|
||||
//! deletes, and [`KeyStore::remove`] truncates the write-ahead log after it, as
|
||||
//! [`Store::delete_identity`] does, so that the frame of the log that held the
|
||||
//! page with the key is gone too. [`KeyStore::sign_out`], which deletes with
|
||||
//! `remove`, truncates the log once, after its last step, not after each
|
||||
//! removal. The checkpoint waits for another connection for a moment at most
|
||||
//! (`Store::truncate_wal`): one that keeps reading an old snapshot blocks it,
|
||||
//! and then the removal still succeeds and a warning says that the deleted
|
||||
//! bytes may stay in the log file, until a later checkpoint truncates the log,
|
||||
//! later writes overwrite those frames, or the last connection to the database
|
||||
//! closes and the log is deleted.
|
||||
//!
|
||||
//! The device key is never a synced copy. The account record names the Voelin key
|
||||
//! that is the installation's device key, and [`KeyStore::sign_out`] deletes
|
||||
//! every identity bound with `synced = true` in its first step, before it reads
|
||||
//! the record, so a key stored that way would be deleted whatever the record
|
||||
//! says (a key that predates the account is to be kept). The store therefore
|
||||
//! refuses, with an error that says why, a [`KeyStore::put`] of a `voelin` blob
|
||||
//! with `synced = true` while an account record names its uid as the device, or
|
||||
//! while a record cannot be read, because then it cannot tell; and a put of an
|
||||
//! account record that names a key which is stored as a synced copy. A binding
|
||||
//! with `synced = false` is accepted: a sign-out unbinds such a key and then
|
||||
//! follows the record. The check and the write are done under the store's lock;
|
||||
//! a second process writing the same file at the same moment is not covered.
|
||||
//!
|
||||
//! A TeamSpeak blob that is refused says why in words that carry none of its
|
||||
//! input: its `data` is the identity's private key, and an error reaches log
|
||||
//! lines.
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Mutex, MutexGuard, PoisonError};
|
||||
|
||||
use rusqlite::types::ValueRef;
|
||||
use rusqlite::{OptionalExtension, params};
|
||||
use tsclientlib::Identity;
|
||||
use voelin_identity::migrate::SELECT_ACCOUNT_COLUMNS;
|
||||
use voelin_identity::{
|
||||
AccountBinding, BindingColumns, BlobError, DeviceKeyChoice, IdentityBlob, IdentityInfo,
|
||||
KIND_ACCOUNT, KIND_TEAMSPEAK, KIND_VOELIN, KeyStore, KeyStoreError, SignOut, Uid,
|
||||
};
|
||||
|
||||
use crate::{Error, Result, Store};
|
||||
|
||||
/// A result of the key store seam.
|
||||
type KsResult<T> = std::result::Result<T, KeyStoreError>;
|
||||
|
||||
/// The rows of [`KeyStore::list`]. The secret of a kind this crate does not
|
||||
/// interpret is never read; a TeamSpeak row's `data` is, for its level.
|
||||
const LIST: &str = "SELECT kind, uid, CASE WHEN kind = 'teamspeak' THEN data END,
|
||||
account, integration, integration_rev, synced, id
|
||||
FROM identities ORDER BY kind, uid";
|
||||
|
||||
/// Replace the binding of the row of this `(kind, uid)` if its `data` is
|
||||
/// exactly the blob's: nothing else of the row is written.
|
||||
const REBIND: &str = "UPDATE identities
|
||||
SET account = ?4, integration = ?5, integration_rev = ?6, synced = ?7
|
||||
WHERE kind = ?1 AND uid = ?2 AND data = ?3";
|
||||
|
||||
/// [`REBIND`] for a row whose `data` is not text and reads, as [`lossy_text`]
|
||||
/// reads it, as the blob's: the same four columns, and the stored bytes stay.
|
||||
const REBIND_BYTES: &str = "UPDATE identities
|
||||
SET account = ?3, integration = ?4, integration_rev = ?5, synced = ?6
|
||||
WHERE kind = ?1 AND uid = ?2";
|
||||
|
||||
/// Insert the blob, or replace the row of the same uid if it is of the same
|
||||
/// kind. A row of another kind is left alone: the statement then changes
|
||||
/// nothing, which `put` reports.
|
||||
const PUT: &str = "INSERT INTO identities
|
||||
(name, uid, data, kind, account, integration, integration_rev, synced)
|
||||
VALUES (?1, ?1, ?2, ?3, ?4, ?5, ?6, ?7)
|
||||
ON CONFLICT (uid) DO UPDATE SET
|
||||
data = excluded.data, account = excluded.account,
|
||||
integration = excluded.integration, integration_rev = excluded.integration_rev,
|
||||
synced = excluded.synced
|
||||
WHERE identities.kind = excluded.kind";
|
||||
|
||||
/// The identities of a client database as a [`KeyStore`]: every kind, with its
|
||||
/// account binding.
|
||||
///
|
||||
/// It owns a [`Store`] behind a mutex, because a [`KeyStore`] is `Sync` and a
|
||||
/// SQLite connection is not. Open it on the database file next to the
|
||||
/// other connections of the app (the settings writer and the chat history do
|
||||
/// the same): SQLite lets them share the file. [`Self::with_store`] gives
|
||||
/// access to the TeamSpeak methods of the same connection.
|
||||
///
|
||||
/// [`KeyStore::sign_out`] and the rest of the trait's provided methods work as
|
||||
/// `voelin-identity` defines them, on top of the five methods here; the
|
||||
/// sign-out only truncates the write-ahead log once, at its end.
|
||||
pub struct SqliteKeyStore {
|
||||
store: Mutex<Store>,
|
||||
}
|
||||
|
||||
impl SqliteKeyStore {
|
||||
/// The identities of an open [`Store`].
|
||||
pub fn new(store: Store) -> Self {
|
||||
Self { store: Mutex::new(store) }
|
||||
}
|
||||
|
||||
/// Open or create the database at `path`, migrating it.
|
||||
pub fn open(path: &Path) -> Result<Self> {
|
||||
Ok(Self::new(Store::open(path)?))
|
||||
}
|
||||
|
||||
/// A key store in memory: for tests.
|
||||
pub fn open_in_memory() -> Result<Self> {
|
||||
Ok(Self::new(Store::open_in_memory()?))
|
||||
}
|
||||
|
||||
/// Run `f` on the [`Store`] behind this key store, holding its lock: the
|
||||
/// TeamSpeak identity methods (`identities`, `default_identity`, ...) see
|
||||
/// the same rows on the same connection.
|
||||
pub fn with_store<R>(&self, f: impl FnOnce(&Store) -> R) -> R {
|
||||
f(&self.lock())
|
||||
}
|
||||
|
||||
fn lock(&self) -> MutexGuard<'_, Store> {
|
||||
// A panic in another thread cannot leave the table half-updated: every
|
||||
// write here is one statement, and `put` tries a second one only when
|
||||
// the first changed nothing.
|
||||
self.store.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
}
|
||||
|
||||
impl KeyStore for SqliteKeyStore {
|
||||
fn list(&self) -> KsResult<Vec<IdentityInfo>> {
|
||||
let store = self.lock();
|
||||
let mut statement = store.db.prepare_cached(LIST).map_err(backend)?;
|
||||
let rows = statement.query_map([], Columns::read).map_err(backend)?;
|
||||
let mut infos = Vec::new();
|
||||
for row in rows {
|
||||
infos.extend(row.map_err(backend)?.map(Columns::into_info));
|
||||
}
|
||||
Ok(infos)
|
||||
}
|
||||
|
||||
fn get(&self, kind: &str, uid: &str) -> KsResult<Option<IdentityBlob>> {
|
||||
let store = self.lock();
|
||||
let sql = format!(
|
||||
"SELECT {SELECT_ACCOUNT_COLUMNS}, id FROM identities WHERE kind = ?1 AND uid = ?2"
|
||||
);
|
||||
let mut statement = store.db.prepare_cached(&sql).map_err(backend)?;
|
||||
let mut rows = statement.query_map(params![kind, uid], Columns::read).map_err(backend)?;
|
||||
Ok(rows.next().transpose().map_err(backend)?.flatten().map(Columns::into_blob))
|
||||
}
|
||||
|
||||
fn put(&self, blob: &IdentityBlob) -> KsResult<()> {
|
||||
let columns = blob.binding_columns()?;
|
||||
let store = self.lock();
|
||||
match blob.kind.as_str() {
|
||||
KIND_VOELIN if blob.binding.is_some_and(|binding| binding.synced) => {
|
||||
refuse_synced_device_key(&store, &blob.uid)?;
|
||||
}
|
||||
KIND_ACCOUNT => refuse_record_of_synced_key(&store, blob)?,
|
||||
_ => {}
|
||||
}
|
||||
// A row that already holds this data changes its binding and nothing
|
||||
// else, and is not checked again: it may have been damaged outside this
|
||||
// crate, and a sign-out still has to unbind it. "Holds this data" is
|
||||
// meant as `get` reads it: for a `data` that is not text, `get` hands out
|
||||
// the text with the odd bytes replaced, `REBIND` cannot match that, and
|
||||
// the second statement takes the blob for the data that is there.
|
||||
let rebound = store
|
||||
.db
|
||||
.prepare_cached(REBIND)
|
||||
.map_err(backend)?
|
||||
.execute(params![
|
||||
blob.kind,
|
||||
blob.uid,
|
||||
blob.json,
|
||||
columns.account,
|
||||
columns.integration,
|
||||
columns.rev,
|
||||
columns.synced,
|
||||
])
|
||||
.map_err(backend)?;
|
||||
if rebound > 0 || rebind_stored_bytes(&store, blob, &columns)? {
|
||||
return Ok(());
|
||||
}
|
||||
if blob.kind == KIND_TEAMSPEAK {
|
||||
check_teamspeak(blob)?;
|
||||
}
|
||||
let changed = store
|
||||
.db
|
||||
.prepare_cached(PUT)
|
||||
.map_err(backend)?
|
||||
.execute(params![
|
||||
blob.uid,
|
||||
blob.json,
|
||||
blob.kind,
|
||||
columns.account,
|
||||
columns.integration,
|
||||
columns.rev,
|
||||
columns.synced,
|
||||
])
|
||||
.map_err(backend)?;
|
||||
if changed == 0 {
|
||||
let held_by: String = store
|
||||
.db
|
||||
.query_row("SELECT kind FROM identities WHERE uid = ?1", [&blob.uid], |r| r.get(0))
|
||||
.map_err(backend)?;
|
||||
return Err(KeyStoreError::backend(Refused::UidHeld {
|
||||
uid: blob.uid.clone(),
|
||||
kind: held_by,
|
||||
}));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove(&self, kind: &str, uid: &str) -> KsResult<bool> {
|
||||
let store = self.lock();
|
||||
let removed = delete_row(&store, kind, uid)?;
|
||||
if removed {
|
||||
// The row may be a key: leave nothing of it in the log either.
|
||||
store.truncate_wal();
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
/// The trait's sign-out, with the log truncated once after its last step
|
||||
/// instead of after each of its removals: it removes up to a handful of
|
||||
/// rows, and a checkpoint that another connection blocks costs a moment
|
||||
/// (`Store::truncate_wal`) each time. The steps are the trait's own; they
|
||||
/// run on a `SignOutPass`, which deletes like [`Self::remove`] and leaves
|
||||
/// the checkpoint to this method.
|
||||
fn sign_out(&self, account: &Uid, device_key: DeviceKeyChoice) -> KsResult<SignOut> {
|
||||
let pass = SignOutPass { store: self, deleted: AtomicBool::new(false) };
|
||||
let outcome = KeyStore::sign_out(&pass, account, device_key);
|
||||
// Also after a failure: the removals before it have happened.
|
||||
if pass.deleted.load(Ordering::Relaxed) {
|
||||
self.lock().truncate_wal();
|
||||
}
|
||||
outcome
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete the row of this `(kind, uid)`: whether there was one. The rows are
|
||||
/// overwritten (`secure_delete`); the log is the caller's to truncate.
|
||||
fn delete_row(store: &Store, kind: &str, uid: &str) -> KsResult<bool> {
|
||||
let removed = store
|
||||
.db
|
||||
.prepare_cached("DELETE FROM identities WHERE kind = ?1 AND uid = ?2")
|
||||
.map_err(backend)?
|
||||
.execute(params![kind, uid])
|
||||
.map_err(backend)?;
|
||||
Ok(removed > 0)
|
||||
}
|
||||
|
||||
/// A [`SqliteKeyStore`] for the length of one [`KeyStore::sign_out`]: the same
|
||||
/// rows, but `remove` only notes that it deleted something, so that the sign-out
|
||||
/// truncates the log once at its end.
|
||||
struct SignOutPass<'a> {
|
||||
store: &'a SqliteKeyStore,
|
||||
/// Whether a row was deleted.
|
||||
deleted: AtomicBool,
|
||||
}
|
||||
|
||||
impl KeyStore for SignOutPass<'_> {
|
||||
fn list(&self) -> KsResult<Vec<IdentityInfo>> {
|
||||
self.store.list()
|
||||
}
|
||||
|
||||
fn get(&self, kind: &str, uid: &str) -> KsResult<Option<IdentityBlob>> {
|
||||
self.store.get(kind, uid)
|
||||
}
|
||||
|
||||
fn put(&self, blob: &IdentityBlob) -> KsResult<()> {
|
||||
self.store.put(blob)
|
||||
}
|
||||
|
||||
fn remove(&self, kind: &str, uid: &str) -> KsResult<bool> {
|
||||
let removed = delete_row(&self.store.lock(), kind, uid)?;
|
||||
if removed {
|
||||
self.deleted.store(true, Ordering::Relaxed);
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
}
|
||||
|
||||
/// Change only the binding of the row of the blob's `(kind, uid)` if its `data`
|
||||
/// is not text but reads as exactly the blob's JSON, and say whether it did.
|
||||
///
|
||||
/// [`KeyStore::get`] reads a `data` that is a BLOB, or TEXT of bytes that are no
|
||||
/// UTF-8, as text with the odd bytes replaced ([`lossy_text`]). The blob that a
|
||||
/// sign-out puts back to unbind such a row carries that text, so `REBIND` finds
|
||||
/// nothing, and writing the blob would replace the stored bytes with the
|
||||
/// replaced text (and refuse a TeamSpeak row, whose replaced text is no
|
||||
/// identity, for ever). The text `get` handed out is taken for the data that is
|
||||
/// there, and the bytes are kept.
|
||||
///
|
||||
/// It is called after `REBIND` changed nothing, which is why the stored value is
|
||||
/// known not to be exactly the blob's text. Any other JSON does not match, and
|
||||
/// is a new identity for the uid as ever.
|
||||
fn rebind_stored_bytes(
|
||||
store: &Store,
|
||||
blob: &IdentityBlob,
|
||||
columns: &BindingColumns,
|
||||
) -> KsResult<bool> {
|
||||
let reads_as_blob = store
|
||||
.db
|
||||
.prepare_cached("SELECT data FROM identities WHERE kind = ?1 AND uid = ?2")
|
||||
.map_err(backend)?
|
||||
.query_row(params![blob.kind, blob.uid], |row| {
|
||||
Ok(lossy_text(row.get_ref(0)?).is_some_and(|text| text == blob.json))
|
||||
})
|
||||
.optional()
|
||||
.map_err(backend)?;
|
||||
if reads_as_blob != Some(true) {
|
||||
return Ok(false);
|
||||
}
|
||||
store
|
||||
.db
|
||||
.prepare_cached(REBIND_BYTES)
|
||||
.map_err(backend)?
|
||||
.execute(params![
|
||||
blob.kind,
|
||||
blob.uid,
|
||||
columns.account,
|
||||
columns.integration,
|
||||
columns.rev,
|
||||
columns.synced,
|
||||
])
|
||||
.map_err(backend)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// A TeamSpeak blob is stored only if it is what its kind says: the JSON of a
|
||||
/// `tsproto::Identity` whose key has the uid the blob names.
|
||||
///
|
||||
/// The first keeps one bad row, which a service or a damaged file could hand
|
||||
/// over, from failing the list of TeamSpeak identities for everyone. The
|
||||
/// second keeps a blob from overwriting, by its uid, the key of a different
|
||||
/// identity that is stored under that uid.
|
||||
///
|
||||
/// The parse error of serde is dropped, not forwarded: it can quote the text
|
||||
/// it choked on, which is a private key, into a log line.
|
||||
fn check_teamspeak(blob: &IdentityBlob) -> KsResult<()> {
|
||||
let Ok(identity) = serde_json::from_str::<Identity>(&blob.json) else {
|
||||
return Err(KeyStoreError::backend(Refused::NotATeamSpeakIdentity));
|
||||
};
|
||||
if identity.key().to_pub().get_uid() != blob.uid {
|
||||
return Err(KeyStoreError::Blob(BlobError::UidMismatch));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Refuse to store the Voelin key `uid` as a synced copy while the device key
|
||||
/// of the installation, as an account record names it, is this key.
|
||||
///
|
||||
/// A record that cannot be read could name it: it is refused then too, because
|
||||
/// the sign-out that follows would delete the key on that guess.
|
||||
fn refuse_synced_device_key(store: &Store, uid: &str) -> KsResult<()> {
|
||||
let mut statement = store
|
||||
.db
|
||||
.prepare_cached("SELECT uid, data FROM identities WHERE kind = 'account'")
|
||||
.map_err(backend)?;
|
||||
let mut rows = statement.query([]).map_err(backend)?;
|
||||
while let Some(row) = rows.next().map_err(backend)? {
|
||||
// A record whose uid is not text cannot be addressed; it is not read.
|
||||
let Ok(record_uid) = row.get_ref(0).map_err(backend)?.as_str() else { continue };
|
||||
let data = lossy_text(row.get_ref(1).map_err(backend)?).unwrap_or_default();
|
||||
match IdentityBlob::new(KIND_ACCOUNT, record_uid, 0, data).account_record() {
|
||||
Ok(record) if record.device.to_base32() == uid => {
|
||||
return Err(KeyStoreError::backend(Refused::SyncedDeviceKey {
|
||||
uid: uid.to_owned(),
|
||||
record: record_uid.to_owned(),
|
||||
}));
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(_) => {
|
||||
return Err(KeyStoreError::backend(Refused::UnreadableRecord {
|
||||
uid: uid.to_owned(),
|
||||
record: record_uid.to_owned(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Refuse to store an account record whose device key is stored as a synced
|
||||
/// copy: the same state as [`refuse_synced_device_key`] guards, reached from
|
||||
/// the other side. A blob that is no readable record is not checked here; the
|
||||
/// store has always kept what it is given for that kind, and a sign-out
|
||||
/// deletes it.
|
||||
fn refuse_record_of_synced_key(store: &Store, blob: &IdentityBlob) -> KsResult<()> {
|
||||
let Ok(record) = blob.account_record() else { return Ok(()) };
|
||||
let device = record.device.to_base32();
|
||||
let synced: bool = store
|
||||
.db
|
||||
.prepare_cached(
|
||||
"SELECT EXISTS (SELECT 1 FROM identities
|
||||
WHERE kind = 'voelin' AND uid = ?1 AND synced = 1)",
|
||||
)
|
||||
.map_err(backend)?
|
||||
.query_row([&device], |row| row.get(0))
|
||||
.map_err(backend)?;
|
||||
if synced {
|
||||
return Err(KeyStoreError::backend(Refused::RecordNamesSyncedKey {
|
||||
record: blob.uid.clone(),
|
||||
device,
|
||||
}));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A database error as the store's backend error.
|
||||
fn backend(error: impl Into<Error>) -> KeyStoreError {
|
||||
KeyStoreError::backend(error.into())
|
||||
}
|
||||
|
||||
/// A [`KeyStore::put`] this store refuses.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum Refused {
|
||||
/// The JSON is not that of a `tsproto::Identity`. The text is a private
|
||||
/// key, so the error does not repeat it, nor serde's account of it.
|
||||
#[error("the TeamSpeak identity JSON is not that of an identity")]
|
||||
NotATeamSpeakIdentity,
|
||||
/// `uid` is unique across kinds in this table.
|
||||
#[error("the uid {uid:?} is already stored as an identity of kind {kind:?}")]
|
||||
UidHeld { uid: String, kind: String },
|
||||
/// The Voelin key is the device key of an account record. A sign-out
|
||||
/// deletes a synced copy without reading the record, so the key the record
|
||||
/// says to keep would be deleted.
|
||||
#[error(
|
||||
"the Voelin key {uid:?} is the device key of the account record {record:?} and cannot be \
|
||||
stored as a synced copy (synced = true): a sign-out would delete it whatever the record says"
|
||||
)]
|
||||
SyncedDeviceKey { uid: String, record: String },
|
||||
/// An account record cannot be read, so the store cannot tell whether the
|
||||
/// Voelin key is its device key.
|
||||
#[error(
|
||||
"the Voelin key {uid:?} cannot be stored as a synced copy (synced = true): the account \
|
||||
record {record:?} cannot be read, so it may name this key as the device key"
|
||||
)]
|
||||
UnreadableRecord { uid: String, record: String },
|
||||
/// The device key of the record is stored as a synced copy already.
|
||||
#[error(
|
||||
"the account record {record:?} names the Voelin key {device:?} as the device key, which is \
|
||||
stored as a synced copy (synced = true): a sign-out would delete it whatever the record \
|
||||
says"
|
||||
)]
|
||||
RecordNamesSyncedKey { record: String, device: String },
|
||||
}
|
||||
|
||||
/// One row of the table as `LIST` and `SELECT_ACCOUNT_COLUMNS` select it (with
|
||||
/// the row id last), its binding already read.
|
||||
struct Columns {
|
||||
kind: String,
|
||||
uid: String,
|
||||
/// The identity itself. `LIST` leaves it out for kinds with no level.
|
||||
data: Option<String>,
|
||||
/// `None` for an unbound row and for one whose binding columns are damaged.
|
||||
binding: Option<AccountBinding>,
|
||||
}
|
||||
|
||||
/// Why binding columns cannot be read.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum Damage {
|
||||
#[error(transparent)]
|
||||
Binding(#[from] BlobError),
|
||||
#[error("a binding column holds a value of the wrong type")]
|
||||
WrongType,
|
||||
}
|
||||
|
||||
impl Columns {
|
||||
/// The row, or `None` for a row that cannot be addressed (its `kind` or
|
||||
/// `uid` is not text) and is left out with a warning.
|
||||
fn read(row: &rusqlite::Row<'_>) -> rusqlite::Result<Option<Self>> {
|
||||
let id: i64 = row.get(7)?;
|
||||
let (Ok(kind), Ok(uid)) = (row.get_ref(0)?.as_str(), row.get_ref(1)?.as_str()) else {
|
||||
tracing::warn!(id, "an identities row whose kind or uid is not text is left out");
|
||||
return Ok(None);
|
||||
};
|
||||
let binding = read_binding(row).unwrap_or_else(|damage| {
|
||||
tracing::warn!(
|
||||
id, kind, uid, %damage,
|
||||
"the binding columns of an identity cannot be read: it is treated as unbound",
|
||||
);
|
||||
None
|
||||
});
|
||||
Ok(Some(Self {
|
||||
kind: kind.to_owned(),
|
||||
uid: uid.to_owned(),
|
||||
data: lossy_text(row.get_ref(2)?),
|
||||
binding,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The security level of a TeamSpeak row, 0 for any other kind and for JSON
|
||||
/// that is no identity.
|
||||
fn level(&self) -> u8 {
|
||||
match &self.data {
|
||||
Some(json) if self.kind == KIND_TEAMSPEAK => {
|
||||
serde_json::from_str::<Identity>(json).map_or(0, |identity| identity.level())
|
||||
}
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn into_info(self) -> IdentityInfo {
|
||||
let level = self.level();
|
||||
IdentityInfo { kind: self.kind, uid: self.uid, level, binding: self.binding }
|
||||
}
|
||||
|
||||
fn into_blob(self) -> IdentityBlob {
|
||||
let level = self.level();
|
||||
let data = self.data.unwrap_or_default();
|
||||
IdentityBlob::from_row(&self.kind, self.uid, level, data).with_binding(self.binding)
|
||||
}
|
||||
}
|
||||
|
||||
/// The binding of a row from its four columns (3 to 6 of both selects).
|
||||
fn read_binding(row: &rusqlite::Row<'_>) -> std::result::Result<Option<AccountBinding>, Damage> {
|
||||
let column = |index| row.get_ref(index).map_err(|_| Damage::WrongType);
|
||||
let account = column(3)?.as_str_or_null().map_err(|_| Damage::WrongType)?;
|
||||
let integration = column(4)?.as_str_or_null().map_err(|_| Damage::WrongType)?;
|
||||
let rev = column(5)?.as_i64().map_err(|_| Damage::WrongType)?;
|
||||
let synced = column(6)?.as_i64().map_err(|_| Damage::WrongType)?;
|
||||
Ok(AccountBinding::from_columns(account, integration, rev, synced)?)
|
||||
}
|
||||
|
||||
/// A `data` column as text, whatever it holds. Bytes that are no UTF-8 and
|
||||
/// values of another type are damage; read as text they fail where the
|
||||
/// blob's kind is checked, with that kind's own error, instead of failing the
|
||||
/// read of the row.
|
||||
fn lossy_text(value: ValueRef<'_>) -> Option<String> {
|
||||
match value {
|
||||
ValueRef::Null => None,
|
||||
ValueRef::Integer(n) => Some(n.to_string()),
|
||||
ValueRef::Real(x) => Some(x.to_string()),
|
||||
ValueRef::Text(bytes) | ValueRef::Blob(bytes) => {
|
||||
Some(String::from_utf8_lossy(bytes).into_owned())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,16 @@
|
||||
//!
|
||||
//! The schema is versioned (`PRAGMA user_version`): opening a database runs
|
||||
//! the migrations it has not seen, each in one transaction, keeping the data.
|
||||
//!
|
||||
//! The `identities` table keeps identities of more than one kind. [`Store`]
|
||||
//! has the TeamSpeak identities the client has always had; [`SqliteKeyStore`]
|
||||
//! is the table as a `voelin_identity::KeyStore`: every kind (TeamSpeak, a
|
||||
//! Voelin key, the record of the signed-in account), each with the binding that
|
||||
//! says whether it belongs to an account, and the sign-out of that account.
|
||||
|
||||
pub mod chat;
|
||||
pub mod contacts;
|
||||
mod keystore;
|
||||
mod secrets;
|
||||
mod store;
|
||||
|
||||
@@ -18,6 +25,7 @@ pub use chat::{
|
||||
StoredMessage, SyncState, WriteOutcome, Written,
|
||||
};
|
||||
pub use contacts::{Contact, ContactSeen, Relation};
|
||||
pub use keystore::SqliteKeyStore;
|
||||
#[cfg(feature = "keyring")]
|
||||
pub use secrets::KeyringSecrets;
|
||||
pub use secrets::{MemorySecrets, Secrets};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The SQLite database.
|
||||
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
|
||||
use serde::de::DeserializeOwned;
|
||||
@@ -18,12 +19,21 @@ enum Migration {
|
||||
/// Schema migrations; entry `i` upgrades from version `i` to `i + 1`
|
||||
/// (`PRAGMA user_version`). Add new ones at the end; never change one that
|
||||
/// shipped.
|
||||
///
|
||||
/// Versions 6 and 7 are the identity migrations of `voelin-identity` (the
|
||||
/// protocol's Phase 2 tasks 7 and 28), run in this order: a `kind` column
|
||||
/// (every row that exists is a `teamspeak` identity) and then the four
|
||||
/// account-binding columns (every row that exists is unbound). Their SQL is
|
||||
/// the protocol's; `the_identity_migrations_are_pinned` keeps it from changing
|
||||
/// under a shipped version.
|
||||
const MIGRATIONS: &[Migration] = &[
|
||||
Migration::Sql(SCHEMA_1),
|
||||
Migration::Code(crate::chat::migrate_2),
|
||||
Migration::Sql(crate::contacts::SCHEMA_3),
|
||||
Migration::Sql(SCHEMA_4),
|
||||
Migration::Sql(crate::chat::SCHEMA_5),
|
||||
Migration::Sql(voelin_identity::migrate::ADD_KIND_COLUMN),
|
||||
Migration::Sql(voelin_identity::migrate::ADD_ACCOUNT_COLUMNS),
|
||||
];
|
||||
|
||||
/// Version 4: where each identity came from ([`IdentityOrigin`]) and which
|
||||
@@ -88,7 +98,7 @@ pub enum IdentityOrigin {
|
||||
/// Made by the app on its own because it had none; nobody chose it, so
|
||||
/// the official client's identity may take its place as the default.
|
||||
Created,
|
||||
/// From another client (`voelin_core::identity`).
|
||||
/// From another client (`voelin_core::ts::identity`).
|
||||
Imported,
|
||||
/// Made or chosen as the default by the user.
|
||||
User,
|
||||
@@ -228,6 +238,12 @@ impl Bookmark {
|
||||
}
|
||||
}
|
||||
|
||||
/// How long the checkpoint that follows the deletion of a key waits for another
|
||||
/// connection ([`Store::truncate_wal`]). Short on purpose: the connection's own
|
||||
/// busy timeout is seconds, and the checkpoint holds the writer lock while it
|
||||
/// waits.
|
||||
const CHECKPOINT_WAIT: Duration = Duration::from_millis(150);
|
||||
|
||||
pub struct Store {
|
||||
pub(crate) db: Connection,
|
||||
}
|
||||
@@ -261,6 +277,13 @@ impl Store {
|
||||
// Statements run through `prepare_cached` are parsed once per connection.
|
||||
db.set_prepared_statement_cache_capacity(64);
|
||||
db.pragma_update(None, "foreign_keys", true)?;
|
||||
// Identities hold private keys. By default a delete only unlinks the
|
||||
// row: its bytes stay in the free space of the page, and in earlier
|
||||
// frames of the write-ahead log. With this SQLite overwrites what it
|
||||
// deletes with zeros, and `truncate_wal` then folds the log into the
|
||||
// file after a key is removed. It is a setting of the connection, so
|
||||
// every connection that opens the file sets it here.
|
||||
db.pragma_update(None, "secure_delete", true)?;
|
||||
// Each migration with its version bump in one write transaction: a
|
||||
// second connection that opens the file at the same time (the
|
||||
// settings writer, the chat history) waits, then sees the new version.
|
||||
@@ -287,6 +310,10 @@ impl Store {
|
||||
pub const SCHEMA_VERSION: i64 = MIGRATIONS.len() as i64;
|
||||
|
||||
// Identities
|
||||
//
|
||||
// These methods are the TeamSpeak identities (kind `teamspeak`) the client
|
||||
// has always had, and act on those rows only: the other kinds of the
|
||||
// `identities` table (a Voelin key, the signed-in account) are not theirs.
|
||||
|
||||
/// Store an identity; it is the default when no other one is.
|
||||
pub fn add_identity(
|
||||
@@ -306,7 +333,8 @@ impl Store {
|
||||
|
||||
pub fn identities(&self) -> Result<Vec<IdentityEntry>> {
|
||||
let mut stmt = self.db.prepare(
|
||||
"SELECT id, name, uid, data, origin, is_default FROM identities ORDER BY id",
|
||||
"SELECT id, name, uid, data, origin, is_default FROM identities
|
||||
WHERE kind = 'teamspeak' ORDER BY id",
|
||||
)?;
|
||||
let rows = stmt.query_map([], |r| {
|
||||
Ok((
|
||||
@@ -339,7 +367,11 @@ impl Store {
|
||||
/// and is never replaced by an import again.
|
||||
pub fn set_default_identity(&self, id: i64, by_user: bool) -> Result<()> {
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
if tx.execute("UPDATE identities SET is_default = 1 WHERE id = ?1", [id])? == 0 {
|
||||
if tx.execute(
|
||||
"UPDATE identities SET is_default = 1 WHERE id = ?1 AND kind = 'teamspeak'",
|
||||
[id],
|
||||
)? == 0
|
||||
{
|
||||
return Err(Error::NotFound("identity", id));
|
||||
}
|
||||
tx.execute("UPDATE identities SET is_default = 0 WHERE id <> ?1", [id])?;
|
||||
@@ -356,7 +388,11 @@ impl Store {
|
||||
pub fn identity(&self, id: i64) -> Result<Identity> {
|
||||
let data: Option<String> = self
|
||||
.db
|
||||
.query_row("SELECT data FROM identities WHERE id = ?1", [id], |r| r.get(0))
|
||||
.query_row(
|
||||
"SELECT data FROM identities WHERE id = ?1 AND kind = 'teamspeak'",
|
||||
[id],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
let data = data.ok_or(Error::NotFound("identity", id))?;
|
||||
Ok(serde_json::from_str(&data)?)
|
||||
@@ -365,23 +401,82 @@ impl Store {
|
||||
/// Store an identity again, e.g. after its security level was improved.
|
||||
pub fn update_identity(&self, id: i64, identity: &Identity) -> Result<()> {
|
||||
let n = self.db.execute(
|
||||
"UPDATE identities SET data = ?2 WHERE id = ?1",
|
||||
"UPDATE identities SET data = ?2 WHERE id = ?1 AND kind = 'teamspeak'",
|
||||
params![id, serde_json::to_string(identity)?],
|
||||
)?;
|
||||
if n == 0 { Err(Error::NotFound("identity", id)) } else { Ok(()) }
|
||||
}
|
||||
|
||||
pub fn rename_identity(&self, id: i64, name: &str) -> Result<()> {
|
||||
let n =
|
||||
self.db.execute("UPDATE identities SET name = ?2 WHERE id = ?1", params![id, name])?;
|
||||
let n = self.db.execute(
|
||||
"UPDATE identities SET name = ?2 WHERE id = ?1 AND kind = 'teamspeak'",
|
||||
params![id, name],
|
||||
)?;
|
||||
if n == 0 { Err(Error::NotFound("identity", id)) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// Delete the identity, key included: SQLite overwrites the row
|
||||
/// (`secure_delete`) and the write-ahead log is truncated, so the key is
|
||||
/// in neither the database file nor its log afterwards
|
||||
/// (`truncate_wal` says when it cannot be).
|
||||
pub fn delete_identity(&self, id: i64) -> Result<()> {
|
||||
self.db.execute("DELETE FROM identities WHERE id = ?1", [id])?;
|
||||
let deleted =
|
||||
self.db.execute("DELETE FROM identities WHERE id = ?1 AND kind = 'teamspeak'", [id])?;
|
||||
if deleted > 0 {
|
||||
self.truncate_wal();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Fold the write-ahead log into the database file and truncate it to
|
||||
/// nothing. The delete of a key has overwritten its bytes in the page
|
||||
/// (`secure_delete`), but the frame of the log that held the page when the
|
||||
/// key was stored still has them until the log is reset, and a plain
|
||||
/// checkpoint only copies the frames. Call it after the rows of a key were
|
||||
/// deleted.
|
||||
///
|
||||
/// It is best effort, because the delete it follows has happened and a
|
||||
/// sign-out must still finish. A checkpoint that cannot complete (another
|
||||
/// connection keeps reading an old snapshot) or fails leaves the bytes in
|
||||
/// the log file, and a warning says so; they go when a later checkpoint
|
||||
/// truncates the log, when later writes overwrite those frames, or when the
|
||||
/// last connection to the database closes and the log is deleted. It does
|
||||
/// nothing to a database that is not in WAL mode and does not overwrite what
|
||||
/// was deleted before `secure_delete` was on (`VACUUM` does).
|
||||
///
|
||||
/// It waits for another connection for [`CHECKPOINT_WAIT`] at most, not for
|
||||
/// the busy timeout of the connection: while a checkpoint that truncates
|
||||
/// waits for readers it holds the writer lock of the log, so every other
|
||||
/// writer would wait with it, and fail with "database is locked" when its
|
||||
/// own timeout is shorter than the wait. The timeout the connection had is
|
||||
/// restored before this returns.
|
||||
pub(crate) fn truncate_wal(&self) {
|
||||
match self.checkpoint_truncate() {
|
||||
Ok(0) => {}
|
||||
Ok(_) => tracing::warn!(
|
||||
"a deleted key may stay in the write-ahead log: another connection blocked the checkpoint"
|
||||
),
|
||||
Err(error) => tracing::warn!(
|
||||
%error,
|
||||
"a deleted key may stay in the write-ahead log: the checkpoint failed"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// `PRAGMA wal_checkpoint(TRUNCATE)` under [`CHECKPOINT_WAIT`]: whether
|
||||
/// another connection blocked it (`1`) or not (`0`).
|
||||
fn checkpoint_truncate(&self) -> rusqlite::Result<i64> {
|
||||
let previous: i64 = self.db.pragma_query_value(None, "busy_timeout", |r| r.get(0))?;
|
||||
let previous = Duration::from_millis(u64::try_from(previous).unwrap_or_default());
|
||||
self.db.busy_timeout(CHECKPOINT_WAIT)?;
|
||||
let blocked =
|
||||
self.db.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |r| r.get::<_, i64>(0));
|
||||
if let Err(error) = self.db.busy_timeout(previous) {
|
||||
tracing::warn!(%error, "the busy timeout of the connection could not be restored");
|
||||
}
|
||||
blocked
|
||||
}
|
||||
|
||||
// Bookmarks
|
||||
|
||||
pub fn add_bookmark(&self, bookmark: &Bookmark) -> Result<i64> {
|
||||
@@ -506,6 +601,57 @@ mod tests {
|
||||
assert!(matches!(store.identity(id), Err(Error::NotFound(..))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_connection_overwrites_what_it_deletes() {
|
||||
let secure_delete = |store: &Store| -> i64 {
|
||||
store.db.pragma_query_value(None, "secure_delete", |r| r.get(0)).unwrap()
|
||||
};
|
||||
assert_eq!(secure_delete(&Store::open_in_memory().unwrap()), 1);
|
||||
let dir = scratch_dir("secure-delete");
|
||||
let path = dir.join("client.db");
|
||||
assert_eq!(secure_delete(&Store::open(&path).unwrap()), 1);
|
||||
// A second connection to the same file sets it for itself.
|
||||
assert_eq!(secure_delete(&Store::open(&path).unwrap()), 1);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blocked_checkpoint_waits_briefly_and_leaves_the_busy_timeout_as_it_was() {
|
||||
let dir = scratch_dir("blocked-checkpoint");
|
||||
let path = dir.join("client.db");
|
||||
let wal = dir.join("client.db-wal");
|
||||
let store = Store::open(&path).unwrap();
|
||||
store.add_identity("first", &Identity::create(), IdentityOrigin::User).unwrap();
|
||||
|
||||
// A reader whose snapshot is older than the last write keeps the log
|
||||
// from being reset.
|
||||
let reader = Connection::open(&path).unwrap();
|
||||
reader.execute_batch("BEGIN").unwrap();
|
||||
reader.query_row("SELECT count(*) FROM identities", [], |r| r.get::<_, i64>(0)).unwrap();
|
||||
store.add_identity("second", &Identity::create(), IdentityOrigin::User).unwrap();
|
||||
|
||||
// A value that is not the default, so that restoring a constant would show.
|
||||
let timeout = |store: &Store| -> i64 {
|
||||
store.db.pragma_query_value(None, "busy_timeout", |r| r.get(0)).unwrap()
|
||||
};
|
||||
store.db.busy_timeout(Duration::from_millis(2345)).unwrap();
|
||||
let started = std::time::Instant::now();
|
||||
store.truncate_wal();
|
||||
let elapsed = started.elapsed();
|
||||
assert!(elapsed < Duration::from_secs(1), "the checkpoint waited {elapsed:?}");
|
||||
assert!(std::fs::metadata(&wal).unwrap().len() > 0, "the reader should block the reset");
|
||||
assert_eq!(timeout(&store), 2345);
|
||||
|
||||
// Without the reader the same call resets the log.
|
||||
reader.execute_batch("COMMIT").unwrap();
|
||||
store.truncate_wal();
|
||||
assert_eq!(std::fs::metadata(&wal).unwrap().len(), 0);
|
||||
assert_eq!(timeout(&store), 2345);
|
||||
drop(reader);
|
||||
drop(store);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_identity() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
@@ -595,7 +741,7 @@ mod tests {
|
||||
.unwrap();
|
||||
}
|
||||
let store = Store::open(&path).unwrap();
|
||||
assert_eq!(Store::SCHEMA_VERSION, 5);
|
||||
assert_eq!(Store::SCHEMA_VERSION, 7);
|
||||
assert_eq!(store.schema_version().unwrap(), Store::SCHEMA_VERSION);
|
||||
let channel = ChatTarget::Channel(1);
|
||||
let rows = store.messages("srv", &channel, PageQuery::default()).unwrap();
|
||||
@@ -611,6 +757,350 @@ mod tests {
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// What `serde_json::to_string(&tsproto::Identity)` writes for the test
|
||||
/// identity of tsproto's own `identity_tests` (the fixture row of
|
||||
/// `voelin-identity`'s `tests/storage.rs`): its unique id and security
|
||||
/// level are checked against the real tsproto below.
|
||||
const TEAMSPEAK_JSON: &str = r#"{"key":"YTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=","counter":2792354,"max_counter":2792354}"#;
|
||||
const TEAMSPEAK_UID: &str = "test/9PZ9vww/Bpf5vJxtJhpz80=";
|
||||
const TEAMSPEAK_LEVEL: u8 = 21;
|
||||
|
||||
/// A `client.db` as it was at schema `version`: the migrations below
|
||||
/// `version` applied by the code that runs them, nothing else.
|
||||
fn database_at(path: &Path, version: usize) {
|
||||
let mut db = rusqlite::Connection::open(path).unwrap();
|
||||
for migration in &MIGRATIONS[..version] {
|
||||
match migration {
|
||||
Migration::Sql(sql) => db.execute_batch(sql).unwrap(),
|
||||
Migration::Code(migrate) => {
|
||||
let tx = db.transaction().unwrap();
|
||||
migrate(&tx).unwrap();
|
||||
tx.commit().unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
db.pragma_update(None, "user_version", version as i64).unwrap();
|
||||
}
|
||||
|
||||
fn scratch_dir(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("voelin-store-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_teamspeak_fixture_is_what_tsproto_writes() {
|
||||
let identity: Identity = serde_json::from_str(TEAMSPEAK_JSON).unwrap();
|
||||
assert_eq!(identity.key().to_pub().get_uid(), TEAMSPEAK_UID);
|
||||
assert_eq!(identity.level(), TEAMSPEAK_LEVEL);
|
||||
assert_eq!(serde_json::to_string(&identity).unwrap(), TEAMSPEAK_JSON);
|
||||
}
|
||||
|
||||
/// The identity migrations are `voelin-identity`'s SQL, and a shipped
|
||||
/// version never changes: a newer revision of the protocol repository
|
||||
/// that touched either string would fail here instead of changing what
|
||||
/// version 6 or 7 does to an installed database.
|
||||
#[test]
|
||||
fn the_identity_migrations_are_pinned() {
|
||||
let sql = |index: usize| match &MIGRATIONS[index] {
|
||||
Migration::Sql(sql) => *sql,
|
||||
Migration::Code(_) => panic!("migration {index} is code"),
|
||||
};
|
||||
assert_eq!(MIGRATIONS.len(), 7);
|
||||
assert_eq!(
|
||||
sql(5),
|
||||
"ALTER TABLE identities ADD COLUMN kind TEXT NOT NULL DEFAULT 'teamspeak';"
|
||||
);
|
||||
assert_eq!(
|
||||
sql(6),
|
||||
"ALTER TABLE identities ADD COLUMN account TEXT;\n\
|
||||
ALTER TABLE identities ADD COLUMN integration TEXT;\n\
|
||||
ALTER TABLE identities ADD COLUMN integration_rev INTEGER NOT NULL DEFAULT 0;\n\
|
||||
ALTER TABLE identities ADD COLUMN synced INTEGER NOT NULL DEFAULT 0;"
|
||||
);
|
||||
}
|
||||
|
||||
/// A database of version 5 (what 0.1 ships) gets the `kind` column and
|
||||
/// then the account columns in one open; every identity stays as it was:
|
||||
/// kind `teamspeak`, unbound, its JSON byte for byte, its origin and
|
||||
/// default flag, and the level computed from the key as before.
|
||||
#[test]
|
||||
fn migrates_version_5_identities_through_both_steps() {
|
||||
use voelin_identity::migrate::SELECT_ACCOUNT_COLUMNS;
|
||||
use voelin_identity::{AccountBinding, IdentityBlob, KIND_TEAMSPEAK};
|
||||
|
||||
let dir = scratch_dir("v5");
|
||||
let path = dir.join("client.db");
|
||||
let other = Identity::create();
|
||||
let other_json = serde_json::to_string(&other).unwrap();
|
||||
let other_uid = other.key().to_pub().get_uid();
|
||||
database_at(&path, 5);
|
||||
{
|
||||
let db = rusqlite::Connection::open(&path).unwrap();
|
||||
assert_eq!(
|
||||
db.pragma_query_value(None, "user_version", |r| r.get::<_, i64>(0)).unwrap(),
|
||||
5
|
||||
);
|
||||
for (name, uid, json, origin, default) in [
|
||||
("Main", TEAMSPEAK_UID, TEAMSPEAK_JSON, "imported", 1),
|
||||
("Other", other_uid.as_str(), other_json.as_str(), "user", 0),
|
||||
] {
|
||||
db.execute(
|
||||
"INSERT INTO identities (name, uid, data, origin, is_default)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
params![name, uid, json, origin, default],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
let store = Store::open(&path).unwrap();
|
||||
assert_eq!(Store::SCHEMA_VERSION, 7);
|
||||
assert_eq!(store.schema_version().unwrap(), 7);
|
||||
|
||||
// Read as the key store reads a row of the migrated table.
|
||||
let rows: Vec<_> = store
|
||||
.db
|
||||
.prepare(&format!("SELECT {SELECT_ACCOUNT_COLUMNS} FROM identities ORDER BY id"))
|
||||
.unwrap()
|
||||
.query_map([], |r| {
|
||||
Ok((
|
||||
r.get::<_, String>(0)?,
|
||||
r.get::<_, String>(1)?,
|
||||
r.get::<_, String>(2)?,
|
||||
r.get::<_, Option<String>>(3)?,
|
||||
r.get::<_, Option<String>>(4)?,
|
||||
r.get::<_, i64>(5)?,
|
||||
r.get::<_, i64>(6)?,
|
||||
))
|
||||
})
|
||||
.unwrap()
|
||||
.collect::<rusqlite::Result<_>>()
|
||||
.unwrap();
|
||||
assert_eq!(rows.len(), 2);
|
||||
for ((kind, uid, data, account, integration, rev, synced), (want_uid, want_json)) in
|
||||
rows.into_iter().zip([(TEAMSPEAK_UID, TEAMSPEAK_JSON), (&*other_uid, &*other_json)])
|
||||
{
|
||||
assert_eq!(kind, KIND_TEAMSPEAK);
|
||||
let binding = AccountBinding::from_columns(
|
||||
account.as_deref(),
|
||||
integration.as_deref(),
|
||||
rev,
|
||||
synced,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(binding, None, "an old row is unbound");
|
||||
assert_eq!((uid.as_str(), data.as_str()), (want_uid, want_json), "byte for byte");
|
||||
let blob = IdentityBlob::from_row(&kind, uid, 0, data);
|
||||
assert!(blob.is_teamspeak());
|
||||
}
|
||||
|
||||
// The old API sees what it saw before, origin and default included.
|
||||
let list = store.identities().unwrap();
|
||||
assert_eq!(list.len(), 2);
|
||||
assert_eq!((list[0].name.as_str(), list[0].uid.as_str()), ("Main", TEAMSPEAK_UID));
|
||||
assert_eq!(
|
||||
(list[0].level, list[0].origin, list[0].is_default),
|
||||
(21, IdentityOrigin::Imported, true)
|
||||
);
|
||||
assert_eq!((list[1].name.as_str(), list[1].uid.as_str()), ("Other", &*other_uid));
|
||||
assert_eq!(
|
||||
(list[1].level, list[1].origin, list[1].is_default),
|
||||
(other.level(), IdentityOrigin::User, false)
|
||||
);
|
||||
assert_eq!(store.default_identity().unwrap().unwrap().id, list[0].id);
|
||||
assert_eq!(store.identity(list[1].id).unwrap().counter(), other.counter());
|
||||
drop(store);
|
||||
|
||||
// Opened again, nothing runs twice.
|
||||
let store = Store::open(&path).unwrap();
|
||||
assert_eq!(store.schema_version().unwrap(), 7);
|
||||
assert_eq!(store.identities().unwrap(), list);
|
||||
drop(store);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// The acceptance of the migration for the key store: a `client.db` at the
|
||||
/// version before the identity migrations (5), and at the one between them
|
||||
/// (6), opens, and every identity loads through the key store unchanged:
|
||||
/// kind `teamspeak`, no binding, its JSON byte for byte, the level computed
|
||||
/// as before, and the origin and default flag the old API reports kept.
|
||||
#[test]
|
||||
fn a_migrated_database_loads_every_identity_unchanged_through_the_key_store() {
|
||||
use crate::SqliteKeyStore;
|
||||
use voelin_identity::{IdentityBlob, IdentityInfo, KIND_TEAMSPEAK, KeyStore};
|
||||
|
||||
for version in [5, 6] {
|
||||
let dir = scratch_dir(&format!("keys-v{version}"));
|
||||
let path = dir.join("client.db");
|
||||
let other = Identity::create();
|
||||
let other_json = serde_json::to_string(&other).unwrap();
|
||||
let other_uid = other.key().to_pub().get_uid();
|
||||
database_at(&path, version);
|
||||
{
|
||||
let db = rusqlite::Connection::open(&path).unwrap();
|
||||
for (name, uid, json, origin, default) in [
|
||||
("Main", TEAMSPEAK_UID, TEAMSPEAK_JSON, "imported", 1),
|
||||
("Other", other_uid.as_str(), other_json.as_str(), "created", 0),
|
||||
] {
|
||||
db.execute(
|
||||
"INSERT INTO identities (name, uid, data, origin, is_default)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
params![name, uid, json, origin, default],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
let keys = SqliteKeyStore::open(&path).unwrap();
|
||||
assert_eq!(keys.with_store(|s| s.schema_version().unwrap()), 7);
|
||||
let want = [
|
||||
(TEAMSPEAK_UID.to_owned(), TEAMSPEAK_JSON.to_owned(), TEAMSPEAK_LEVEL),
|
||||
(other_uid.clone(), other_json.clone(), other.level()),
|
||||
];
|
||||
let mut infos: Vec<_> = want
|
||||
.iter()
|
||||
.map(|(uid, _, level)| IdentityInfo {
|
||||
kind: KIND_TEAMSPEAK.into(),
|
||||
uid: uid.clone(),
|
||||
level: *level,
|
||||
binding: None,
|
||||
})
|
||||
.collect();
|
||||
infos.sort_by(|a, b| a.uid.cmp(&b.uid));
|
||||
assert_eq!(keys.list().unwrap(), infos, "version {version}");
|
||||
for (uid, json, level) in want {
|
||||
let blob = keys.get(KIND_TEAMSPEAK, &uid).unwrap().unwrap();
|
||||
assert_eq!(blob, IdentityBlob::teamspeak(&uid, level, &json), "version {version}");
|
||||
assert_eq!(blob.json, json, "byte for byte");
|
||||
assert_eq!(blob.binding, None);
|
||||
}
|
||||
|
||||
// What the TeamSpeak methods report is kept as well.
|
||||
let entries = keys.with_store(|s| s.identities().unwrap());
|
||||
let origin = |uid: &str| entries.iter().find(|e| e.uid == uid).unwrap();
|
||||
assert_eq!(
|
||||
(origin(TEAMSPEAK_UID).origin, origin(TEAMSPEAK_UID).is_default),
|
||||
(IdentityOrigin::Imported, true)
|
||||
);
|
||||
assert_eq!(
|
||||
(origin(&other_uid).origin, origin(&other_uid).is_default),
|
||||
(IdentityOrigin::Created, false)
|
||||
);
|
||||
drop(keys);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// A database of version 6 (the `kind` column, no account columns yet) takes
|
||||
/// the second step alone, and its rows of other kinds stay what they are.
|
||||
#[test]
|
||||
fn migrates_version_6_identities_to_accounts() {
|
||||
let dir = scratch_dir("v6");
|
||||
let path = dir.join("client.db");
|
||||
database_at(&path, 6);
|
||||
{
|
||||
let db = rusqlite::Connection::open(&path).unwrap();
|
||||
db.execute(
|
||||
"INSERT INTO identities (name, uid, data, origin, is_default)
|
||||
VALUES ('Main', ?1, ?2, 'created', 1)",
|
||||
params![TEAMSPEAK_UID, TEAMSPEAK_JSON],
|
||||
)
|
||||
.unwrap();
|
||||
db.execute(
|
||||
"INSERT INTO identities (name, uid, data, kind)
|
||||
VALUES ('key', 'abc', '{\"v\":1}', 'voelin')",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let store = Store::open(&path).unwrap();
|
||||
assert_eq!(store.schema_version().unwrap(), 7);
|
||||
let (kind, account, integration, rev, synced): (
|
||||
String,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
i64,
|
||||
i64,
|
||||
) = store
|
||||
.db
|
||||
.query_row(
|
||||
"SELECT kind, account, integration, integration_rev, synced FROM identities
|
||||
WHERE uid = 'abc'",
|
||||
[],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(kind.as_str(), account, integration, rev, synced),
|
||||
("voelin", None, None, 0, 0)
|
||||
);
|
||||
let list = store.identities().unwrap();
|
||||
assert_eq!(list.len(), 1, "the Voelin row is not a TeamSpeak identity");
|
||||
assert_eq!(
|
||||
(list[0].origin, list[0].is_default, list[0].level),
|
||||
(IdentityOrigin::Created, true, 21)
|
||||
);
|
||||
drop(store);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// Rows of other kinds share the table with the TeamSpeak identities and
|
||||
/// are none of the TeamSpeak methods' business: they are not listed, not
|
||||
/// read as an identity, not renamed, changed, made the default or deleted
|
||||
/// (the JSON of a Voelin key is not a `tsproto::Identity`, and listing
|
||||
/// would fail on it).
|
||||
#[test]
|
||||
fn the_teamspeak_methods_leave_other_kinds_alone() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
let mine = Identity::create();
|
||||
let id = store.add_identity("mine", &mine, IdentityOrigin::User).unwrap();
|
||||
let other_id = |kind: &str, uid: &str| {
|
||||
store
|
||||
.db
|
||||
.execute(
|
||||
"INSERT INTO identities (name, uid, data, kind) VALUES (?1, ?2, '{\"v\":1}', ?1)",
|
||||
params![kind, uid],
|
||||
)
|
||||
.unwrap();
|
||||
store.db.last_insert_rowid()
|
||||
};
|
||||
let voelin = other_id("voelin", "v1");
|
||||
let account = other_id("account", "account:a1");
|
||||
|
||||
let list = store.identities().unwrap();
|
||||
assert_eq!(list.iter().map(|e| e.id).collect::<Vec<_>>(), [id]);
|
||||
assert_eq!(store.default_identity().unwrap().unwrap().id, id);
|
||||
for other in [voelin, account] {
|
||||
assert!(matches!(store.identity(other), Err(Error::NotFound(..))));
|
||||
assert!(matches!(store.rename_identity(other, "x"), Err(Error::NotFound(..))));
|
||||
assert!(matches!(store.update_identity(other, &mine), Err(Error::NotFound(..))));
|
||||
assert!(matches!(store.set_default_identity(other, true), Err(Error::NotFound(..))));
|
||||
store.delete_identity(other).unwrap();
|
||||
}
|
||||
let rows: i64 =
|
||||
store.db.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap();
|
||||
assert_eq!(rows, 3, "nothing of another kind was deleted");
|
||||
let names: Vec<String> = store
|
||||
.db
|
||||
.prepare("SELECT name FROM identities ORDER BY id")
|
||||
.unwrap()
|
||||
.query_map([], |r| r.get(0))
|
||||
.unwrap()
|
||||
.collect::<rusqlite::Result<_>>()
|
||||
.unwrap();
|
||||
assert_eq!(names, ["mine", "voelin", "account"]);
|
||||
let defaults: i64 = store
|
||||
.db
|
||||
.query_row("SELECT count(*) FROM identities WHERE is_default", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(defaults, 1);
|
||||
// A TeamSpeak identity is deleted as before.
|
||||
store.delete_identity(id).unwrap();
|
||||
assert!(store.identities().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bookmarks_keep_order_and_fields() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -22,6 +22,9 @@ tokio = { version = "1", features = ["macros", "net", "rt", "sync", "time"] }
|
||||
tracing = "0.1"
|
||||
tsclientlib = { path = "../proto/tsclientlib" }
|
||||
tsproto-packets = { path = "../proto/tsproto-packets" }
|
||||
# The frame and simulcast layer types (`EncodedFrame`, `LayerSpec`), which the
|
||||
# media side owns; re-exported here.
|
||||
voelin-media = { path = "../voelin-media", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
anyhow = "1"
|
||||
|
||||
@@ -1,83 +1,13 @@
|
||||
//! Simulcast layers: several encodings of one stream, each with its own size,
|
||||
//! frame rate and bitrate.
|
||||
//! Simulcast layers of a stream. The types ([`LayerSpec`], [`LayerId`],
|
||||
//! [`LayerSet`]) are `voelin-media`'s; this module keeps how a streamer's
|
||||
//! offer lists its layers in the SDP, so that a Voelin viewer can pick one.
|
||||
//!
|
||||
//! The streamer encodes every layer of its [`LayerSpec`] list and tags each
|
||||
//! [`EncodedFrame`](crate::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.
|
||||
//! negotiate RID simulcast (`a=simulcast`) get all of them.
|
||||
|
||||
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))
|
||||
}
|
||||
}
|
||||
pub use voelin_media::layer::{LayerId, LayerSet, LayerSpec};
|
||||
|
||||
/// The session-level SDP attribute in which a Voelin streamer's offer lists
|
||||
/// its layers, so that a Voelin viewer can pick one (`Signal::Layer`):
|
||||
@@ -129,119 +59,10 @@ pub fn from_sdp(sdp: &str) -> Option<Vec<LayerSpec>> {
|
||||
Some(value.split_whitespace().filter_map(layer).collect())
|
||||
}
|
||||
|
||||
/// 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 layers_in_the_sdp() {
|
||||
let layers = vec![
|
||||
@@ -265,16 +86,4 @@ mod tests {
|
||||
[LayerSpec { id: 2, ..LayerSpec::single(700_000) }]
|
||||
);
|
||||
}
|
||||
|
||||
#[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));
|
||||
}
|
||||
}
|
||||
@@ -8,24 +8,10 @@ use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use str0m::media::{Frequency, MediaKind, MediaTime};
|
||||
pub use voelin_media::stream::EncodedFrame;
|
||||
|
||||
use crate::layer::{LayerId, LayerSpec};
|
||||
|
||||
/// One encoded video or audio frame.
|
||||
#[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,
|
||||
}
|
||||
|
||||
/// Produces encoded frames in real time.
|
||||
pub trait FrameSource: Send {
|
||||
/// Append the frames that are due at `now`.
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
[package]
|
||||
name = "voelin-ui-vm"
|
||||
version = "0.0.1-alpha"
|
||||
description = "Toolkit-free view models of the desktop client: engine state turned into plain rows, shared by the Slint and GPUI front ends."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lib]
|
||||
name = "voelin_ui_vm"
|
||||
path = "src/lib.rs"
|
||||
|
||||
# No UI toolkit here (no slint, no gpui): `cargo tree -p voelin-ui-vm -e normal`
|
||||
# must show neither. The front ends convert these types (docs/ui.md).
|
||||
[dependencies]
|
||||
chrono = { version = "0.4.45", default-features = false, features = ["clock"] }
|
||||
# Picture sizes (the header of a file); PNG and JPEG are listed as the
|
||||
# front end's toolkit used to bring them.
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp", "ico"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
# JSON values of the settings and the gateway's configuration keys.
|
||||
serde_json = "1"
|
||||
# The Twemoji archive's blocks (raw deflate).
|
||||
miniz_oxide = "0.8"
|
||||
# Grapheme clusters for emoji in chat text.
|
||||
unicode-segmentation = "1.13"
|
||||
voelin-audio = { path = "../voelin-audio", default-features = false }
|
||||
voelin-core = { path = "../voelin-core", default-features = false, features = ["media"] }
|
||||
voelin-gateway-proto = { path = "../voelin-gateway-proto" }
|
||||
voelin-model = { workspace = true }
|
||||
voelin-store = { path = "../voelin-store" }
|
||||
|
||||
[dev-dependencies]
|
||||
png = "0.18"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,11 @@
|
||||
# Bundled assets
|
||||
|
||||
- `twemoji.bin`: the Twemoji 15.0 SVGs (3720 emoji, from the `@twemoji/svg`
|
||||
15.0.0 package) packed by `scripts/pack-twemoji.py` into blocks of raw
|
||||
deflate with an index; `src/emoji.rs` reads it. Twemoji graphics by Twitter,
|
||||
Inc and other contributors, licensed under CC-BY 4.0
|
||||
(https://creativecommons.org/licenses/by/4.0/). The files are unchanged
|
||||
apart from surrounding whitespace.
|
||||
|
||||
It is credited in `THIRD_PARTY_NOTICES.md` and the About page, with the fonts
|
||||
and icons of the Slint front end (`crates/voelin-ui/assets/README.md`).
|
||||
File renamed without changes.
@@ -1,8 +1,10 @@
|
||||
//! Avatars without pictures: initials on a colour from the name.
|
||||
|
||||
use slint::Color;
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
use crate::color::Rgb;
|
||||
use crate::image::{ImageRef, ImageSource};
|
||||
|
||||
/// Background colours for initials; white text reads on all of them.
|
||||
const TINTS: [u32; 10] = [
|
||||
0x2d6bff, 0x7c4dff, 0xc2379a, 0xe0572e, 0xd08a00, 0x1f9d6b, 0x0c93b8, 0x5865f2, 0xa0439e,
|
||||
@@ -31,10 +33,10 @@ pub fn first_letter(initials: &str) -> String {
|
||||
initials.graphemes(true).next().unwrap_or_default().to_owned()
|
||||
}
|
||||
|
||||
/// A picture from the engine's cache (an avatar, a group icon), decoded
|
||||
/// once; an empty image when there is none.
|
||||
pub fn image(path: Option<&std::path::PathBuf>) -> slint::Image {
|
||||
path.map(|p| crate::images::file(p)).unwrap_or_default()
|
||||
/// A picture from the engine's cache (an avatar, a group icon); none when
|
||||
/// there is no path.
|
||||
pub fn image(path: Option<&std::path::PathBuf>) -> ImageRef {
|
||||
path.map(ImageSource::file).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A stable number for a name, in any case (FNV-1a).
|
||||
@@ -48,12 +50,12 @@ pub fn name_hash(name: &str) -> u32 {
|
||||
}
|
||||
|
||||
/// `0xrrggbb` as a colour.
|
||||
pub fn rgb(rgb: u32) -> Color {
|
||||
Color::from_rgb_u8((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8)
|
||||
pub fn rgb(rgb: u32) -> Rgb {
|
||||
Rgb::from(rgb)
|
||||
}
|
||||
|
||||
/// A stable colour for a name.
|
||||
pub fn tint(name: &str) -> Color {
|
||||
pub fn tint(name: &str) -> Rgb {
|
||||
rgb(TINTS[(name_hash(name) % TINTS.len() as u32) as usize])
|
||||
}
|
||||
|
||||
@@ -86,10 +88,7 @@ mod tests {
|
||||
fn tints_are_stable() {
|
||||
assert_eq!(tint("Alice"), tint("alice"));
|
||||
let distinct: std::collections::HashSet<_> =
|
||||
["Alice", "Bob", "Carol", "Dave", "Eve", "Mallory"]
|
||||
.iter()
|
||||
.map(|n| tint(n).as_argb_encoded())
|
||||
.collect();
|
||||
["Alice", "Bob", "Carol", "Dave", "Eve", "Mallory"].iter().map(|n| tint(n).0).collect();
|
||||
assert!(distinct.len() > 2);
|
||||
}
|
||||
}
|
||||
File renamed without changes.
Loaded 100 of 183 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user