Compare commits
12
Commits
423377bade
..
v0.1.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c65835f02a | ||
|
|
07c89f4939 | ||
|
|
2d9d2a86e9 | ||
|
|
2e77cf0a11 | ||
|
|
a0f91c2d64 | ||
|
|
00eb76128b | ||
|
|
83a15af9c5 | ||
|
|
6f3e7c9f35 | ||
|
|
1b971bc3f6 | ||
|
|
85fa64cfe6 | ||
|
|
4d30bd95ad | ||
|
|
2e2bc27acf |
No files matched your search
@@ -1,5 +1,5 @@
|
|||||||
# Release-Matrix: bei Tag v* → Tests → Artefakte für alle Plattformen →
|
# Release matrix: on tag v* -> tests -> artifacts for all platforms ->
|
||||||
# Gitea-Release mit Assets talk_<os>_<arch>[.exe] + checksums.txt.
|
# Gitea release with assets talk_<os>_<arch>[.exe] + checksums.txt.
|
||||||
name: release
|
name: release
|
||||||
|
|
||||||
on:
|
on:
|
||||||
@@ -14,27 +14,27 @@ jobs:
|
|||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0 # git describe braucht die Tags
|
fetch-depth: 0 # git describe needs the tags
|
||||||
- name: Go einrichten
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v5
|
uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version-file: go.mod
|
go-version-file: go.mod
|
||||||
- name: Tests
|
- name: Tests
|
||||||
run: go vet ./... && go test ./...
|
run: go vet ./... && go test ./...
|
||||||
- name: Artefakte bauen
|
- name: Build artifacts
|
||||||
run: scripts/release.sh "${{ github.ref_name }}"
|
run: scripts/release.sh "${{ github.ref_name }}"
|
||||||
- name: Gitea-Release anlegen und Assets hochladen
|
- name: Create Gitea release and upload assets
|
||||||
uses: https://gitea.com/actions/gitea-release-action@v1
|
uses: https://gitea.com/actions/gitea-release-action@v1
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
tag_name: ${{ github.ref_name }}
|
tag_name: ${{ github.ref_name }}
|
||||||
name: talk ${{ github.ref_name }}
|
name: talk ${{ github.ref_name }}
|
||||||
body: |
|
body: |
|
||||||
Statische Binaries (CGO_ENABLED=0), Prüfsummen in `checksums.txt`.
|
Static binaries (CGO_ENABLED=0), checksums in `checksums.txt`.
|
||||||
|
|
||||||
Installation: passendes `talk_<os>_<arch>` laden, Prüfsumme vergleichen,
|
Installation: download the matching `talk_<os>_<arch>`, verify the checksum,
|
||||||
als `talk` in den PATH legen, `talk doctor`. Der Daemon startet beim ersten
|
place it in your PATH as `talk`, run `talk doctor`. The daemon starts itself
|
||||||
Sprechbefehl von selbst.
|
on the first speak command.
|
||||||
files: |-
|
files: |-
|
||||||
dist/talk_*
|
dist/talk_*
|
||||||
dist/checksums.txt
|
dist/checksums.txt
|
||||||
@@ -10,17 +10,17 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
- name: Go einrichten
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v5
|
uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version-file: go.mod
|
go-version-file: go.mod
|
||||||
- name: go vet
|
- name: go vet
|
||||||
run: go vet ./...
|
run: go vet ./...
|
||||||
- name: gofmt-Check
|
- name: gofmt check
|
||||||
run: |
|
run: |
|
||||||
unformatted=$(gofmt -l .)
|
unformatted=$(gofmt -l .)
|
||||||
if [ -n "$unformatted" ]; then
|
if [ -n "$unformatted" ]; then
|
||||||
echo "Folgende Dateien sind nicht gofmt-formatiert:"
|
echo "The following files are not gofmt-formatted:"
|
||||||
echo "$unformatted"
|
echo "$unformatted"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|||||||
+4
-4
@@ -1,13 +1,13 @@
|
|||||||
# Go-Binaries
|
# Go binaries
|
||||||
/talk
|
/talk
|
||||||
/talk.exe
|
/talk.exe
|
||||||
*.test
|
*.test
|
||||||
*.out
|
*.out
|
||||||
|
|
||||||
# Release-Artefakte (GoReleaser, Task 11)
|
# Release artifacts (GoReleaser, task 11)
|
||||||
/dist/
|
/dist/
|
||||||
|
|
||||||
# SDD-Prozesszustand (Ledger, Briefs, Review-Diffs, Plan): liegt auf Branch sdd-state,
|
# SDD process state (ledger, briefs, review diffs, plan): lives on branch sdd-state,
|
||||||
# nicht im Produkt-Code. Wiederherstellen: git checkout sdd-state -- .scratch .superpowers && git reset -q
|
# not in the product code. Restore: git checkout sdd-state -- .scratch .superpowers && git reset -q
|
||||||
/.scratch/
|
/.scratch/
|
||||||
/.superpowers/
|
/.superpowers/
|
||||||
@@ -1,229 +1,303 @@
|
|||||||
|
<img src="assets/icon/talk.svg" alt="" width="96" align="right">
|
||||||
|
|
||||||
# talk
|
# talk
|
||||||
|
|
||||||
> **Status: WIP** — aktive Entwicklung (talk 2.0). Spezifikation mit
|
> **Status: WIP**, under active development. Specification with the decision
|
||||||
> Entscheidungs-Nachtrag: [`docs/spec.md`](docs/spec.md)
|
> addendum: [`docs/spec.md`](docs/spec.md)
|
||||||
|
|
||||||
**talk** macht Skripte und KI-Agenten hörbar: Ein Aufruf — `talk "Build fertig"` —
|
**talk** gives scripts and AI agents a voice: one call, `talk "Build done"`,
|
||||||
spricht eine kurze Nachricht über eine TTS-Provider-Kette
|
speaks a short announcement through a chain of TTS providers
|
||||||
(ElevenLabs → OpenAI → Edge-TTS → OS-Stimme), serialisiert durch einen
|
(ElevenLabs → OpenAI → Edge TTS → OS voice), serialized by a background
|
||||||
Hintergrund-Daemon, den talk beim ersten Aufruf selbst startet. Ein
|
daemon that talk starts itself on first use. One static binary,
|
||||||
statisches Binary, cross-platform (Windows/macOS/Linux, amd64/arm64), keine
|
cross-platform (Windows, macOS, Linux; amd64 and arm64), no runtime
|
||||||
Runtime-Abhängigkeiten.
|
dependencies.
|
||||||
|
|
||||||
## Befehle
|
## Commands
|
||||||
|
|
||||||
| Befehl | Zweck |
|
| Command | Purpose |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `talk "Text"` | Ansage — Abkürzung für `talk say`, non-blocking |
|
| `talk "text"` | announce; shorthand for `talk say`, non-blocking |
|
||||||
| `talk say "Text"` | Ansage (Text als Argument oder von stdin) |
|
| `talk say "text"` | announce (text as argument or from stdin) |
|
||||||
| `talk wrap -- <Befehl>` | Befehl ausführen, Erfolg/Misserfolg + Dauer ansagen |
|
| `talk wrap -- <command>` | run a command, announce success/failure and duration |
|
||||||
| `talk mute` / `talk unmute` | Ansagen dauerhaft stummschalten / Stummschaltung aufheben |
|
| `talk mute` / `talk unmute` | mute all announcements persistently / turn them back on |
|
||||||
| `talk status` | Daemon-Status (Queue, Mute, Provider, Version) |
|
| `talk status` | daemon status (queue, mute, provider, laws, version) |
|
||||||
| `talk cancel` | laufende und geplante Ansagen abbrechen |
|
| `talk cancel` | cancel the playing and all queued announcements |
|
||||||
| `talk daemon run\|start\|stop` | Daemon im Vordergrund betreiben / im Hintergrund starten / stoppen (normalerweise nicht nötig, siehe unten) |
|
| `talk uri <talk:…>` | handler behind the `talk:` links of notification buttons (Windows); not called by hand |
|
||||||
| `talk voices` | bekannte Stimmen je Provider/Sprache, Default markiert (`--provider`, `--lang`, `--json`) |
|
| `talk daemon run\|start\|stop` | run the daemon in the foreground / start it in the background / stop it (normally not needed, see below) |
|
||||||
| `talk test` | Testsatz sprechen; zeigt Provider und Zeiten (`--lang`, `--provider`, `--voice`) |
|
| `talk voices` | known voices per provider and language, default marked (`--provider`, `--lang`, `--json`) |
|
||||||
| `talk doctor` | Selbstdiagnose: Config, Daemon, Audio, Provider, Mute, Gesetze (`--probe`, `--json`) |
|
| `talk test` | speak a test sentence; shows provider and timings (`--lang`, `--provider`, `--voice`); `--toast` sends a test notification instead |
|
||||||
| `talk setup` | Ersteinrichtung in wenigen Fragen: Stimmen probehören, Ruhezeit, config.toml |
|
| `talk doctor` | self-diagnosis: config, daemon, audio, providers, notifications, mute, laws (`--probe`, `--json`) |
|
||||||
|
| `talk setup` | first-time setup in a few questions: language, voices with preview, quiet hours, config.toml |
|
||||||
|
| `talk version` | version and commit (also `talk --version`) |
|
||||||
|
|
||||||
Say-Flags (gelten auch für `talk "Text"`): `--wait`, `--now`, `--priority`,
|
Say flags (also for `talk "text"`): `--wait`, `--now`, `--priority`,
|
||||||
`--voice`, `--lang`, `--provider`.
|
`--voice`, `--lang`, `--provider`.
|
||||||
|
|
||||||
## Erste Schritte
|
## Installation
|
||||||
|
|
||||||
|
**Release binary** (Linux and Windows, amd64/arm64; macOS builds on
|
||||||
|
request, untested so far): download the matching `talk_<os>_<arch>` from
|
||||||
|
the [releases](https://code.m3ta.dev/m3tam3re/talk/releases), verify the
|
||||||
|
checksum against `checksums.txt`, put it in your PATH as `talk`. No other
|
||||||
|
dependencies. The download URL carries the version (Gitea has no
|
||||||
|
`latest/download` alias):
|
||||||
|
|
||||||
```console
|
```console
|
||||||
talk doctor # Was ist da, was fehlt? Eine Zeile pro Punkt.
|
V=v0.1.0
|
||||||
talk test # Hörst du etwas? Welche Stimme war das?
|
curl -LO https://code.m3ta.dev/m3tam3re/talk/releases/download/$V/talk_linux_amd64
|
||||||
talk setup # Stimme aussuchen, Ruhezeit, fertig.
|
sha256sum -c --ignore-missing <(curl -sL https://code.m3ta.dev/m3tam3re/talk/releases/download/$V/checksums.txt)
|
||||||
talk "Hallo Welt" # Ab jetzt: Skripte und Agenten rufen genau das.
|
install -m 755 talk_linux_amd64 ~/.local/bin/talk
|
||||||
```
|
```
|
||||||
|
|
||||||
Ohne jeden Key funktioniert talk sofort: Es nutzt die kostenlose Edge-
|
**Nix** (flake): `nix run git+https://code.m3ta.dev/m3tam3re/talk -- doctor`,
|
||||||
Stimme von Microsoft (Internet nötig) und sonst die Stimme des
|
or in your configuration `inputs.talk.url = "git+https://code.m3ta.dev/m3tam3re/talk";`
|
||||||
Betriebssystems. Wer eine Premium-Stimme will, setzt `TALK_ELEVENLABS_KEY`
|
and `inputs.talk.packages.${system}.talk` or `inputs.talk.overlays.default`.
|
||||||
oder `TALK_OPENAI_KEY` als Umgebungsvariable — Keys gehören nie in die
|
The package brings espeak-ng (OS voice) and libnotify (toast) along.
|
||||||
config.toml.
|
|
||||||
|
|
||||||
### Diagnose und Einrichtung
|
**From source:** `go install code.m3ta.dev/m3tam3re/talk/cmd/talk@latest`.
|
||||||
|
|
||||||
- **`talk doctor`** berichtet zeilenweise mit ✔ (ok), ⚠ (Hinweis), ✘
|
## Getting started
|
||||||
(Fehler): Config-Datei, Daemon (läuft / startet beim nächsten
|
|
||||||
Sprechbefehl / fremder Dienst auf dem Port), Audio-Ausgabe (oto
|
```console
|
||||||
initialisierbar? `null` = kein Ton), jede Provider-Stufe (Key vorhanden,
|
talk doctor # What is there, what is missing? One line per item.
|
||||||
Endpunkt, Default-Stimme; OS-Stimme: welcher Mechanismus gefunden
|
talk test # Do you hear something? Which voice was it?
|
||||||
wurde), Mute, Gesetze inkl. aktiver Ruhezeit. Exit 0 ohne ✘, sonst 1;
|
talk setup # Pick a language and voices, set quiet hours, done.
|
||||||
ein nicht laufender Daemon ist ⚠. `--probe` macht echte Synthese-Proben
|
talk "Hello world" # From now on scripts and agents call exactly this.
|
||||||
(Netz), `--json` liefert die Liste maschinenlesbar. Auf Windows-Konsolen
|
```
|
||||||
stehen `[OK]`/`[WARN]`/`[FAIL]` statt der Symbole.
|
|
||||||
- **`talk test`** spricht einen festen Testsatz direkt in diesem Prozess
|
talk works without any key: it uses Microsoft's free Edge voice (needs
|
||||||
(nicht über den Daemon; Mute und Ruhezeit gelten hier nicht, ein aktives
|
internet) and otherwise your operating system's voice. For a premium voice,
|
||||||
Mute wird genannt) und zeigt, welche Stufe gesprochen hat und wie lange
|
set `TALK_ELEVENLABS_KEY` or `TALK_OPENAI_KEY` as an environment variable.
|
||||||
Synthese und Wiedergabe gedauert haben.
|
Keys never go into config.toml.
|
||||||
- **`talk voices`** listet den kuratierten Stimmen-Katalog (ElevenLabs-
|
|
||||||
Premade, OpenAI, Edge-Neural je Locale) als Tabelle; `*` markiert die
|
### Diagnosis and setup
|
||||||
Stimme, die talk ohne `--voice` nimmt (config `voice.<provider>.<lang>`
|
|
||||||
oder Repo-Default). Config-Einträge außerhalb des Katalogs erscheinen
|
- **`talk doctor`** reports one line per item with ✔ (ok), ⚠ (note), ✘
|
||||||
als eigene Zeile. Jede Voice-ID des Providers funktioniert auch ohne
|
(error): config file, daemon (running / starts on the next speak command
|
||||||
Katalog-Eintrag.
|
/ foreign service on the port), audio output (can oto initialize? `null`
|
||||||
- **`talk setup`** fragt im Terminal: Keys (nur Hinweis — ohne Key läuft
|
= no sound), every provider tier (key present, endpoint, default voice;
|
||||||
die Edge-Stimme), Stimme für Deutsch und Englisch der aktiven Stufe
|
OS voice: which mechanism was found), notifications, mute, laws
|
||||||
(Nummer aus dem Katalog oder Voice-ID, probehören, übernehmen),
|
including an active quiet window. Exit 0 without ✘, else 1; a daemon that
|
||||||
Ruhezeit. Dann schreibt es die config.toml — eine bestehende Datei wird
|
is not running is ⚠. `--probe` runs real synthesis probes (network),
|
||||||
zusammengeführt (andere Einstellungen bleiben) und als `.bak` gesichert
|
`--json` returns the list for machines. Windows consoles get
|
||||||
— und spricht einen Testsatz. `q` bricht jederzeit ab, geschrieben wird
|
`[OK]`/`[WARN]`/`[FAIL]` instead of the symbols.
|
||||||
erst ganz am Ende. Ohne Terminal (Pipe, Agent) stellt setup keine Fragen
|
- **`talk test`** speaks a fixed test sentence directly in this process (not
|
||||||
und zeigt nur die wirksame Konfiguration.
|
via the daemon; mute and quiet hours do not apply here, an active mute is
|
||||||
|
mentioned) and shows which tier spoke and how long synthesis and playback
|
||||||
|
took. `talk test --toast` shows a test notification with the Cancel button
|
||||||
|
and waits for a click, so you can check the notification setup without
|
||||||
|
speaking anything.
|
||||||
|
- **`talk voices`** lists the curated voice catalog (ElevenLabs premade,
|
||||||
|
OpenAI, Edge neural voices per locale) as a table; `*` marks the voice
|
||||||
|
talk uses without `--voice` (config `voice.<provider>.<lang>` or the
|
||||||
|
built-in default). Config entries outside the catalog appear as their own
|
||||||
|
row. Any voice ID the provider knows works without a catalog entry.
|
||||||
|
- **`talk setup`** asks in the terminal: keys (only a hint; without a key
|
||||||
|
the Edge voice speaks), the fallback language, a voice for each language
|
||||||
|
of the active tier (number from the catalog or a voice ID, preview,
|
||||||
|
accept), quiet hours. Then it writes config.toml, merging an existing
|
||||||
|
file (other settings stay) and backing it up as `.bak`, and speaks a
|
||||||
|
test sentence. `q` aborts at any point; the file is written only at the
|
||||||
|
very end. Without a terminal (pipe, agent) setup asks nothing and only
|
||||||
|
shows the effective configuration.
|
||||||
|
|
||||||
|
### Notifications with a Cancel button
|
||||||
|
|
||||||
|
Every announcement that plays also shows a desktop notification with its
|
||||||
|
text and a **Cancel** button (German: Abbrechen) that stops that
|
||||||
|
announcement without a terminal. The notification disappears when the
|
||||||
|
announcement ends.
|
||||||
|
|
||||||
|
- **Linux:** talk talks to the freedesktop notification service on the
|
||||||
|
session bus directly (any daemon with the "actions" capability: mako,
|
||||||
|
dunst, GNOME Shell, KDE, quickshell) and receives the click over D-Bus.
|
||||||
|
The notification carries the talk icon. Without a session bus it falls
|
||||||
|
back to notify-send without a button.
|
||||||
|
- **Windows:** a toast from "talk" with its icon and a Cancel button. The
|
||||||
|
button opens a `talk:` link; the daemon registers that URL protocol for
|
||||||
|
the current user (HKCU, no admin rights) so Windows starts
|
||||||
|
`talk uri talk:cancel?id=…`, which tells the daemon to stop the
|
||||||
|
announcement. The toast identity (`AppUserModelId m3ta.talk`, also HKCU)
|
||||||
|
is registered the same way on the first daemon start or `talk test
|
||||||
|
--toast`; before that the toast appears under Windows PowerShell's
|
||||||
|
identity.
|
||||||
|
- **macOS:** Notification Center, no button and no icon yet.
|
||||||
|
|
||||||
|
The icon file lives next to the config (`talk.png` in the config
|
||||||
|
directory); talk writes it there itself.
|
||||||
|
|
||||||
|
Turn it off with:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[notify]
|
||||||
|
on_speak = false # env TALK_NOTIFY=false
|
||||||
|
```
|
||||||
|
|
||||||
|
`talk test --toast` shows one such notification, waits a few seconds for a
|
||||||
|
click on Cancel and reports what happened; `talk doctor` names the service
|
||||||
|
and whether it supports the button.
|
||||||
|
|
||||||
|
### Language
|
||||||
|
|
||||||
|
talk detects German and English per announcement (word lists plus umlauts;
|
||||||
|
no ML) and picks the voice accordingly. When it cannot tell (numbers,
|
||||||
|
single words, ties) it uses the configured fallback language, which is also
|
||||||
|
the language of talk's own announcements such as the `wrap` result:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
lang = "en" # de | en; default en (env TALK_LANG)
|
||||||
|
```
|
||||||
|
|
||||||
## Daemon
|
## Daemon
|
||||||
|
|
||||||
Es gibt genau ein Binary. Der Daemon ist `talk daemon run` — derselbe Code,
|
There is exactly one binary. The daemon is `talk daemon run`: the same code,
|
||||||
im Hintergrund. Er besitzt die Ansage-Queue und spricht seriell ab — genau
|
in the background. It owns the announcement queue and plays serially, exactly
|
||||||
eine Ansage gleichzeitig, Reihenfolge `now` > `high` > `normal` > `low`
|
one announcement at a time, in the order `now` > `high` > `normal` > `low`
|
||||||
(FIFO je Level). Der HTTP-Server lauscht nur auf `127.0.0.1`; Port: Default
|
(FIFO per level). The HTTP server listens on `127.0.0.1` only; port: default
|
||||||
`7800`, config `[server] port`, Env `TALK_PORT` (schlagen den Default).
|
`7800`, config `[server] port`, env `TALK_PORT`.
|
||||||
|
|
||||||
**Autostart:** Läuft kein Daemon, startet `talk say` (und `talk wrap`) ihn
|
**Autostart:** when no daemon runs, `talk say` (and `talk wrap`) start it on
|
||||||
beim ersten Sprechbefehl selbst — losgelöst vom Terminal, mit Protokoll in
|
the first speak command, detached from the terminal (on Windows also broken
|
||||||
`daemon.log` und Prozess-ID in `daemon.pid` im Config-Dir; stderr meldet
|
away from the caller's job object, so a WinRM, SSH or CI session does not
|
||||||
einmalig „Daemon gestartet". Der Daemon läuft dann weiter (Leerlauf kostet
|
take it down), logging to `daemon.log` with its PID in `daemon.pid` in the
|
||||||
nichts Nennenswertes), bis `talk daemon stop`, Abmelden oder Neustart.
|
config directory; stderr says "daemon started" once. The daemon then keeps running (idle costs next to nothing)
|
||||||
Parallele erste Aufrufe sind harmlos: Verliert einer das Port-Rennen,
|
until `talk daemon stop`, logout or reboot. Parallel first calls are
|
||||||
benutzt er den Daemon des anderen. Wer den Daemon selbst verwaltet
|
harmless: whoever loses the port race uses the other one's daemon. If you
|
||||||
(systemd, launchd, Task Scheduler mit `talk daemon run`), schaltet den
|
manage the daemon yourself (systemd, launchd, Task Scheduler with `talk
|
||||||
Autostart ab:
|
daemon run`), turn autostart off:
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[daemon]
|
[daemon]
|
||||||
autostart = false # Env TALK_AUTOSTART=false
|
autostart = false # env TALK_AUTOSTART=false
|
||||||
```
|
```
|
||||||
|
|
||||||
Steuerbefehle (`mute`, `unmute`, `status`, `cancel`) starten den Daemon
|
Control commands (`mute`, `unmute`, `status`, `cancel`) deliberately do not
|
||||||
bewusst nicht: `talk status` sagt dann „läuft nicht" (Exit 1), `talk mute`
|
start the daemon: `talk status` then says "not running" (exit 1), `talk
|
||||||
schreibt die Mute-Datei direkt.
|
mute` writes the mute file directly.
|
||||||
|
|
||||||
| Endpunkt | Wirkung |
|
| Endpoint | Effect |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `POST /speak` | `{text, priority?, provider?, voice?, lang?, now?}` → `202 {"id":"…"}` (+ `"truncated":true`, wenn auf `max_text` gekürzt); bei Mute: `202 {"id":"","muted":true}`; bei Gesetz-Verwurf: `202 {"id":"","discarded":"rate_limit"\|"quiet_hours"}` (+ `"toast":true` im Toast-Modus) — verworfen, dokumentiertes Verhalten |
|
| `POST /speak` | `{text, priority?, provider?, voice?, lang?, now?}` → `202 {"id":"…"}` (+ `"truncated":true` when cut to `max_text`); muted: `202 {"id":"","muted":true}`; law discard: `202 {"id":"","discarded":"rate_limit"\|"quiet_hours"}` (+ `"toast":true` in toast mode); documented behaviour, not an error |
|
||||||
| `OPTIONS /speak` | CORS-Preflight → `204` mit Freigabe-Headern, wenn die `Origin` in `server.allowed_origins` steht (siehe unten); sonst `204` ohne CORS-Header |
|
| `OPTIONS /speak` | CORS preflight → `204` with allow headers when the `Origin` is listed in `server.allowed_origins` (see below); otherwise `204` without CORS headers |
|
||||||
| `GET /status` | `{"version", "queue", "queue_ids", "current", "muted", "provider", "rate_limit": {"interval", "allow_high_burst", "next_slot"}, "quiet_hours": {"window", "active", "mode", "until"}, "limits": {"max_text", "max_age"}, "mcp": true, "cors": [origins]}` |
|
| `GET /status` | `{"version", "queue", "queue_ids", "current", "muted", "provider", "rate_limit": {"interval", "allow_high_burst", "next_slot"}, "quiet_hours": {"window", "active", "mode", "until"}, "limits": {"max_text", "max_age"}, "mcp": true, "cors": [origins]}` |
|
||||||
| `POST /cancel` | bricht die laufende Ansage ab + leert die Queue → `200 {"cancelled":n}` |
|
| `POST /cancel` | aborts the playing announcement and empties the queue → `200 {"cancelled":n}` |
|
||||||
| `POST /mute` / `POST /unmute` | persistenter Mute-State → `200 {"muted":bool}` |
|
| `POST /cancel-item` | `{"id":"…"}` cancels only that announcement if it is playing (notification Cancel button) → `200 {"cancelled":bool}` |
|
||||||
| `POST /shutdown` | fährt den Daemon herunter (`talk daemon stop`) → `200 {"ok":true}` |
|
| `POST /mute` / `POST /unmute` | persistent mute state → `200 {"muted":bool}` |
|
||||||
| `POST /mcp` | MCP (Streamable HTTP): JSON-RPC `initialize`, `notifications/initialized`, `ping`, `tools/list`, `tools/call` — ein Tool `speak` (siehe unten) |
|
| `POST /shutdown` | shuts the daemon down (`talk daemon stop`) → `200 {"ok":true}` |
|
||||||
| `GET /mcp` | `405` — der Daemon bietet keine server-initiierten Streams an |
|
| `POST /mcp` | MCP (Streamable HTTP): JSON-RPC `initialize`, `notifications/initialized`, `ping`, `tools/list`, `tools/call`; one tool `speak` (see below) |
|
||||||
|
| `GET /mcp` | `405`; the daemon offers no server-initiated streams |
|
||||||
|
|
||||||
- **CLI-Verhalten:** `talk say` (und `talk "Text"`) erkennt den Daemon via
|
- **CLI behaviour:** `talk say` (and `talk "text"`) detects the daemon via
|
||||||
`GET /status`. Läuft er: enqueue + sofortige Rückkehr (non-blocking,
|
`GET /status`. If it runs: enqueue and return at once (non-blocking,
|
||||||
stdout erhält die Item-ID); `--wait` pollt bis zur Fertigstellung;
|
stdout gets the item ID); `--wait` polls until spoken; `--now` jumps the
|
||||||
`--now` springt vor die Warteschlange; bei Mute sagt die CLI `muted`,
|
queue; when muted the CLI prints `muted`, on a law discard
|
||||||
bei Gesetz-Verwurf `discarded: <grund>`. `talk mute`/`unmute`/`status`/
|
`discarded: <reason>`. `talk mute`/`unmute`/`status`/`cancel` are daemon
|
||||||
`cancel` sind Daemon-Aufrufe mit plain Output.
|
calls with plain output.
|
||||||
- **Mute ist persistent** (Datei `mute` im Config-Dir, Inhalt `true`/
|
- **Mute is persistent** (file `mute` in the config directory, content
|
||||||
`false`) und überlebt Daemon-Restarts. `talk mute` ohne laufenden Daemon
|
`true`/`false`) and survives daemon restarts. `talk mute` without a
|
||||||
schreibt die Datei direkt — der Daemon liest sie bei jeder Ansage neu,
|
running daemon writes the file directly; the daemon re-reads it on every
|
||||||
der Zustand greift also auch offline.
|
announcement, so the state applies offline too.
|
||||||
- **Direkt-Pfad:** Ist kein Daemon erreichbar und keiner startbar
|
- **Direct path:** if no daemon is reachable and none can be started
|
||||||
(Autostart aus, Port fremd belegt, Start gescheitert), spricht `talk`
|
(autostart off, port taken by something else, start failed), `talk`
|
||||||
direkt im eigenen Prozess — blockierend, ohne Warteschlange (parallele
|
speaks directly in its own process: blocking, without a queue (parallel
|
||||||
Aufrufe können überlappen), mit Hinweis und Grund auf stderr. Mute wird
|
calls may overlap), with a note and the reason on stderr. Mute is
|
||||||
auch hier respektiert. Nichts bricht still.
|
honoured here too. Nothing fails silently.
|
||||||
|
|
||||||
### Rate-Limit + Ruhezeiten (Task 05)
|
### Rate limit, quiet hours, length and age
|
||||||
|
|
||||||
Der Daemon erzwingt das Anti-Spam-Gesetz als Backstop unter allem
|
The daemon enforces the anti-spam laws as a backstop under whatever a
|
||||||
Prompt-Verhalten. **Rate-Limit:** Jede *gestartete* Ansage bucht ein
|
prompt does. **Rate limit:** every *started* announcement books a time
|
||||||
Zeitfenster — Default **1 Ansage / 30 s**. Bis zum Fenster-Ablauf gilt:
|
window, default **1 announcement / 30 s**. Until the window elapses:
|
||||||
|
|
||||||
- `priority=low` wird **verworfen** (schon beim Eintritt, die 202-Antwort
|
- `priority=low` is **discarded** (already on admission; the 202 response
|
||||||
nennt `discarded: "rate_limit"`); war das Fenster beim Eintritt noch
|
says `discarded: "rate_limit"`); if the window was open on admission, the
|
||||||
frei, entscheidet der Worker später.
|
worker decides later.
|
||||||
- `normal` **parkt** in der Queue und spielt zum freien Slot (in `/status`
|
- `normal` **parks** in the queue and plays at the next open slot (visible
|
||||||
als `rate_limit.next_slot` sichtbar).
|
in `/status` as `rate_limit.next_slot`).
|
||||||
- `priority=high` darf mit `queue.allow_high_burst = true` (Default)
|
- `priority=high` may **deliberately break** the limit with
|
||||||
**bewusst verstoßen**; ohne Burst-Recht wartet high wie normal.
|
`queue.allow_high_burst = true` (default); without burst rights high
|
||||||
- `now:true` **umgeht auch das Rate-Limit** — der dokumentierte Ausbruch
|
waits like normal.
|
||||||
für Dringendes (startet trotzdem ein neues Fenster).
|
- `now:true` **bypasses the rate limit too**; the documented escape for
|
||||||
|
urgent matters (it still books a new window).
|
||||||
|
|
||||||
**Ruhezeiten:** `quiet_hours = "18:00-08:00"` (lokale Zeit, überspannt
|
**Quiet hours:** `quiet_hours = "18:00-08:00"` (local time, may span
|
||||||
Mitternacht; leer/`off` = aus — bewusst kein Default-Fenster, Ruhezeiten
|
midnight; empty/`off` = disabled; deliberately no default window, quiet
|
||||||
sind Opt-in wie Mute). In der Ruhezeit verfällt Audio, auch für high
|
hours are opt-in like mute). During quiet hours audio is dropped, also for
|
||||||
(Burst ist ein Rate-Recht, kein Ruhe-Recht):
|
high (burst is a rate right, not a quiet right):
|
||||||
|
|
||||||
- `quiet_mode = "discard"` (Default): still verwerfen.
|
- `quiet_mode = "discard"` (default): drop silently.
|
||||||
- `quiet_mode = "toast"`: Benachrichtigung statt Audio — derzeit eine
|
- `quiet_mode = "toast"`: a desktop notification instead of audio (the
|
||||||
Protokoll-Zeile über den Notification-Pfad (OS-Toast folgt mit der
|
notification service or the system's own tool, see "Notifications"), best
|
||||||
Notification-Anbindung).
|
effort: if nothing is available, only the log line remains and
|
||||||
- `now:true` **bricht auch die Ruhezeit** (bewusster Ausbruch).
|
`talk doctor` shows it under "Toast".
|
||||||
|
- `now:true` **breaks out of quiet hours too** (a deliberate interruption).
|
||||||
|
|
||||||
**Länge und Alter:** Zwei weitere Gesetze gegen das, was Prompts gern tun
|
**Length and age:** two more laws against what prompts like to do, reading
|
||||||
— die Langantwort vorlesen und Ansagen stapeln:
|
out the long answer and piling up announcements:
|
||||||
|
|
||||||
- `max_text` (Default **400 Zeichen**, etwa zwei bis drei Sätze): Längere
|
- `max_text` (default **400 characters**, two to three sentences): longer
|
||||||
Texte werden beim Eintritt an einer Wortgrenze **gekürzt** und so
|
texts are **cut** at a word boundary on admission and spoken like that;
|
||||||
gesprochen; die Antwort meldet `"truncated": true`, die CLI warnt auf
|
the response reports `"truncated": true`, the CLI warns on stderr, the
|
||||||
stderr, das MCP-Ergebnis sagt es im Text. Der Nutzer hört den Anfang
|
MCP result says so in its text. The user hears the beginning instead of a
|
||||||
statt zehn Minuten Vortrag, das API-Budget bleibt begrenzt.
|
ten-minute lecture, and the API budget stays bounded.
|
||||||
- `max_age` (Default **2 Minuten**): Was länger in der Queue parkt (Rate-
|
- `max_age` (default **2 minutes**): whatever parks longer in the queue
|
||||||
Limit, Stau), ist keine Nachricht mehr und wird beim Fälligwerden
|
(rate limit, backlog) is no longer news and is **discarded** when it
|
||||||
**verworfen** (`discarded: "expired"` im Protokoll; die 202-Antwort beim
|
comes due (`discarded: "expired"` in the log; the 202 on admission stays a
|
||||||
Eintritt bleibt eine Zusage, denn beim Eintritt ist nichts veraltet).
|
promise, because nothing is stale on admission). `now:true` never waits
|
||||||
`now:true` wartet nie lange und ist ausgenommen.
|
long and is exempt.
|
||||||
|
|
||||||
**Rangordnung:** manuelles Mute gewinnt immer > `now` > veraltet (`max_age`)
|
**Precedence:** manual mute always wins > `now` > stale (`max_age`) > quiet
|
||||||
> Ruhezeit > Rate-Limit; `max_text` greift beim Eintritt auf alles.
|
hours > rate limit; `max_text` applies on admission to everything.
|
||||||
Konfiguration (config.toml, Env schlägt Datei):
|
Configuration (config.toml; env beats the file):
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[queue]
|
[queue]
|
||||||
rate_limit = "30s" # Dauer; "0s" = unbegrenzt (TALK_RATE_LIMIT)
|
rate_limit = "30s" # duration; "0s" = unlimited (TALK_RATE_LIMIT)
|
||||||
allow_high_burst = true # high darf verstoßen (TALK_ALLOW_HIGH_BURST)
|
allow_high_burst = true # high may break the limit (TALK_ALLOW_HIGH_BURST)
|
||||||
max_text = 400 # Zeichen; 0 = unbegrenzt (TALK_MAX_TEXT)
|
max_text = 400 # characters; 0 = unlimited (TALK_MAX_TEXT)
|
||||||
max_age = "2m" # Wartezeit; "0s" = unbegrenzt (TALK_MAX_AGE)
|
max_age = "2m" # longest wait; "0s" = unlimited (TALK_MAX_AGE)
|
||||||
|
|
||||||
quiet_hours = "18:00-08:00" # leer = aus; Env TALK_QUIET_HOURS ("off" = aus)
|
quiet_hours = "18:00-08:00" # empty = off; env TALK_QUIET_HOURS ("off" = off)
|
||||||
quiet_mode = "discard" # discard | toast (TALK_QUIET_MODE)
|
quiet_mode = "discard" # discard | toast (TALK_QUIET_MODE)
|
||||||
```
|
```
|
||||||
|
|
||||||
`talk status` zeigt den Gesetz-State: `rate-limit: 30s (high-burst
|
`talk status` shows the law state: `rate-limit: 30s (high burst allowed),
|
||||||
erlaubt), nächster slot …`, `ruhezeit: 18:00-08:00 (modus discard,
|
next slot …`, `quiet-hours: 18:00-08:00 (mode discard, active until 08:00)`
|
||||||
aktiv bis 08:00)` und `limits: max. 400 Zeichen, max. Wartezeit 2m0s`.
|
and `limits: max 400 characters, max wait 2m0s`.
|
||||||
|
|
||||||
### CORS-Tür + MCP-Endpoint (Task 06)
|
### CORS door and MCP endpoint
|
||||||
|
|
||||||
**CORS** gilt bewusst nur für `POST /speak` — genau die eine Tür, die eine
|
**CORS** applies to `POST /speak` only, the one door a later browser
|
||||||
spätere Browser-Anbindung (z. B. LibreChat) braucht; Steuer-Endpunkte
|
integration (for example a web chat UI) needs; control endpoints stay out of
|
||||||
bleiben browserseitig unerreicht. Die Erlaubnis ist eine exakte Origin-
|
reach of browsers. The allow-list holds exact origins; `"*"` is allowed but
|
||||||
Liste; `"*"` ist erlaubt, aber nicht Default; **leere Liste (Default) =
|
not the default; **an empty list (default) means no CORS headers at all**:
|
||||||
gar keine CORS-Header = der Browser blockt**:
|
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[server]
|
[server]
|
||||||
allowed_origins = ["https://chat.az-gruppe.com"] # Env TALK_ALLOWED_ORIGINS
|
allowed_origins = ["https://chat.example.com"] # env TALK_ALLOWED_ORIGINS
|
||||||
```
|
```
|
||||||
|
|
||||||
- `OPTIONS /speak` (Preflight) von gelisteter Origin → `204` mit
|
- `OPTIONS /speak` (preflight) from a listed origin → `204` with
|
||||||
`Access-Control-Allow-Origin` (die Origin bzw. `*`), `-Methods: POST,
|
`Access-Control-Allow-Origin` (the origin or `*`), `-Methods: POST,
|
||||||
OPTIONS`, `-Headers: Content-Type`, `Max-Age: 600`.
|
OPTIONS`, `-Headers: Content-Type`, `Max-Age: 600`.
|
||||||
- Echter `POST /speak` mit gelisteter `Origin` trägt denselben ACAO-Header.
|
- A real `POST /speak` with a listed `Origin` carries the same header.
|
||||||
- **Die Tür ist serverseitig zu, nicht nur browserseitig.** CORS allein
|
- **The door is shut server-side, not only browser-side.** CORS alone only
|
||||||
verhindert nur das *Lesen* der Antwort; einen POST mit `text/plain`-Body
|
prevents *reading* the response; any web page can send a POST with a
|
||||||
oder einen Formular-POST schickt jede Webseite ohne Preflight ab. Deshalb
|
`text/plain` body or a form POST without a preflight. Therefore the
|
||||||
lehnt der Daemon jede Anfrage mit fremdem `Origin`-Header mit `403` ab, die
|
daemon rejects every request with a foreign `Origin` header with `403`
|
||||||
nicht POST /speak von einer gelisteten Origin ist — also ungelistete
|
unless it is POST /speak from a listed origin: unlisted origins on
|
||||||
Origins auf /speak, jeden Browser-Zugriff auf `/status`, `/mute`,
|
/speak, and any browser access to `/status`, `/mute`, `/unmute`,
|
||||||
`/unmute`, `/cancel` und `/mcp`, auch von gelisteten Origins. Nur der
|
`/cancel` and `/mcp`, even from listed origins. Only the preflight
|
||||||
Preflight `OPTIONS /speak` bleibt für ungelistete Origins ein `204` ohne
|
`OPTIONS /speak` stays a `204` without CORS headers for unlisted origins
|
||||||
CORS-Header (ohne Wirkung; der Browser verwirft den geplanten POST).
|
(it has no effect; the browser drops the planned POST). CLI, curl and MCP
|
||||||
CLI, curl und MCP-Clients senden keinen `Origin`-Header und sind nicht
|
clients send no `Origin` header and are unaffected.
|
||||||
betroffen.
|
|
||||||
|
|
||||||
**MCP** (`POST /mcp`, Streamable HTTP): schlanke eigene Implementierung
|
**MCP** (`POST /mcp`, Streamable HTTP): a lean own implementation of the
|
||||||
des JSON-RPC-Subsets ohne SDK — `initialize` (angefragte
|
JSON-RPC subset, no SDK: `initialize` (the requested `protocolVersion` is
|
||||||
`protocolVersion` wird geechot; Ergebnis `protocolVersion`,
|
echoed; result `protocolVersion`, `capabilities: {tools:{}}`,
|
||||||
`capabilities: {tools:{}}`, `serverInfo`), `notifications/initialized`
|
`serverInfo`), `notifications/initialized` (notification → `202` without
|
||||||
(Notification → `202` ohne Body), `ping`, `tools/list`,
|
body), `ping`, `tools/list`, `tools/call`. The server is stateless (no
|
||||||
`tools/call`. Der Server ist zustandslos (keine Session-IDs) und pusht
|
session IDs) and pushes nothing (hence `GET /mcp` → `405`). One tool:
|
||||||
nichts (daher `GET /mcp` → `405`). Ein Tool:
|
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{"name": "speak",
|
{"name": "speak",
|
||||||
@@ -236,13 +310,13 @@ nichts (daher `GET /mcp` → `405`). Ein Tool:
|
|||||||
"required": ["text"]}}
|
"required": ["text"]}}
|
||||||
```
|
```
|
||||||
|
|
||||||
`tools/call` fährt exakt denselben Aufnahme-Pfad wie `POST /speak`
|
`tools/call` takes exactly the same admission path as `POST /speak`
|
||||||
(inklusive Mute, Rate-Limit, Ruhezeiten). Ergebnis ist immer Text-Content:
|
(including mute, rate limit, quiet hours, truncation). The result is always
|
||||||
`"queued: <id>"` bei Aufnahme; `muted`/`discarded: <grund>` mit Erklärung
|
text content: `"queued: <id>"` on admission; `muted`/`discarded: <reason>`
|
||||||
— bewusst `isError: false`, denn ein Verwurf ist das korrekte
|
with an explanation, deliberately `isError: false`, because a discard is
|
||||||
dokumentierte Ergebnis, kein Protokollfehler. Validierungsfehler
|
the correct documented result, not a protocol error. Validation errors
|
||||||
(fehlender Text, ungültige Priorität, unbekanntes Tool) sind dagegen
|
(missing text, invalid priority, unknown tool) are JSON-RPC errors
|
||||||
JSON-RPC-Fehler (`-32602`). Handshake als curl-Sequenz:
|
(`-32602`). Handshake as a curl sequence:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
curl -s http://127.0.0.1:7800/mcp -H 'Content-Type: application/json' \
|
curl -s http://127.0.0.1:7800/mcp -H 'Content-Type: application/json' \
|
||||||
@@ -250,118 +324,148 @@ curl -s http://127.0.0.1:7800/mcp -H 'Content-Type: application/json' \
|
|||||||
curl -s http://127.0.0.1:7800/mcp -H 'Content-Type: application/json' \
|
curl -s http://127.0.0.1:7800/mcp -H 'Content-Type: application/json' \
|
||||||
-d '{"jsonrpc":"2.0","method":"notifications/initialized"}'
|
-d '{"jsonrpc":"2.0","method":"notifications/initialized"}'
|
||||||
curl -s http://127.0.0.1:7800/mcp -H 'Content-Type: application/json' \
|
curl -s http://127.0.0.1:7800/mcp -H 'Content-Type: application/json' \
|
||||||
-d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"speak","arguments":{"text":"Build fertig"}}}'
|
-d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"speak","arguments":{"text":"Build done"}}}'
|
||||||
```
|
```
|
||||||
|
|
||||||
### Provider-Kette (Task 03)
|
### Provider chain
|
||||||
|
|
||||||
Ohne Pin läuft die Vier-Stufen-Fallback-Kette
|
Without a pin, the four-tier fallback chain runs
|
||||||
**ElevenLabs → OpenAI TTS → Edge-TTS → OS built-in**: Bei fehlendem Key,
|
**ElevenLabs → OpenAI TTS → Edge TTS → OS built-in**: on a missing key, an
|
||||||
HTTP-Fehler, Timeout oder Netz-Problem fällt die Kette automatisch auf die
|
HTTP error, a timeout or a network problem the chain falls through to the
|
||||||
nächste Stufe; jeder Fallback wird auf stderr protokolliert (nie still).
|
next tier automatically; every fallback is logged to stderr (never silent).
|
||||||
Pinnen per `--provider=<name>` oder `provider = "<name>"` in der
|
Pin with `--provider=<name>` or `provider = "<name>"` in config.toml.
|
||||||
config.toml.
|
|
||||||
|
|
||||||
| Stufe | Key (Env) | Default-Endpunkt | Audio |
|
| Tier | Key (env) | Default endpoint | Audio |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| `elevenlabs` | `TALK_ELEVENLABS_KEY` | `https://api.elevenlabs.io` | mp3 |
|
| `elevenlabs` | `TALK_ELEVENLABS_KEY` | `https://api.elevenlabs.io` | mp3 |
|
||||||
| `openai` | `TALK_OPENAI_KEY` | `https://api.openai.com` | mp3 |
|
| `openai` | `TALK_OPENAI_KEY` | `https://api.openai.com` | mp3 |
|
||||||
| `edge` | — (kostenlos) | `wss://speech.platform.bing.com/...` | mp3 |
|
| `edge` | none (free) | `wss://speech.platform.bing.com/...` | mp3 |
|
||||||
| `osbuiltin` | — | lokale OS-TTS | WAV/PCM |
|
| `osbuiltin` | none | local OS TTS | WAV/PCM |
|
||||||
|
|
||||||
Keys laufen ausschließlich über Env-Variablen (nie in die config.toml).
|
Keys come exclusively from environment variables (never config.toml).
|
||||||
Endpunkte sind konfigurierbar — Datei `[providers.<name>] endpoint = "…"`
|
Endpoints are configurable: file `[providers.<name>] endpoint = "…"` or env
|
||||||
bzw. Env `TALK_ELEVENLABS_ENDPOINT` / `TALK_OPENAI_ENDPOINT` /
|
`TALK_ELEVENLABS_ENDPOINT` / `TALK_OPENAI_ENDPOINT` / `TALK_EDGE_ENDPOINT`
|
||||||
`TALK_EDGE_ENDPOINT` (Env schlägt Datei; so zeigen Tests/CI die Kette auf
|
(env beats the file; this is how tests and CI point the chain at fake
|
||||||
Fake-Server). Das OpenAI-Modell ist konfigurierbar
|
servers). The OpenAI model is configurable (`[providers.openai] model`,
|
||||||
(`[providers.openai] model`, Default `tts-1`).
|
default `tts-1`).
|
||||||
|
|
||||||
Stimmen: neutralen Repo-Defaults je Provider+Sprache (ElevenLabs
|
Voices: the neutral built-in defaults per provider and language (ElevenLabs
|
||||||
„Rachel", OpenAI „alloy", Edge `de-DE-KatjaNeural`/`en-US-AriaNeural`)
|
"Rachel", OpenAI "alloy", Edge `de-DE-KatjaNeural`/`en-US-AriaNeural`) can
|
||||||
kann man pro Sprache überordnen — config.toml:
|
be overridden per language in config.toml:
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[voice.elevenlabs]
|
[voice.elevenlabs]
|
||||||
de = "21m00Tcm4TlvDq8ikWAM" # eigene Stimme je Sprache
|
de = "21m00Tcm4TlvDq8ikWAM" # your own voice per language
|
||||||
en = "21m00Tcm4TlvDq8ikWAM"
|
en = "21m00Tcm4TlvDq8ikWAM"
|
||||||
|
|
||||||
[voice.edge]
|
[voice.edge]
|
||||||
de = "de-DE-KatjaNeural"
|
de = "de-DE-KatjaNeural"
|
||||||
```
|
```
|
||||||
|
|
||||||
Rangfolge: `--voice`-Flag > `voice.<provider>.<lang>` > Repo-Default.
|
Precedence: `--voice` flag > `voice.<provider>.<lang>` > built-in default.
|
||||||
MP3 wird von der Binärdatei selbst dekodiert (reiner Go-Dekoder, kein
|
MP3 is decoded by the binary itself (pure Go decoder, no ffmpeg, CGO-free).
|
||||||
ffmpeg, CGO-frei).
|
|
||||||
|
|
||||||
### OS-TTS auf Linux (Dev-Abhängigkeit espeak)
|
Edge TTS is an undocumented Microsoft endpoint with a DRM token scheme that
|
||||||
|
Microsoft changes now and then. When that happens, the edge tier fails with
|
||||||
|
a clear "protocol changed?" error and the chain falls through to the OS
|
||||||
|
voice; `talk doctor --probe` makes it visible.
|
||||||
|
|
||||||
Der OS-Provider `osbuiltin` nutzt auf Linux zwei Wege:
|
### OS TTS on Linux
|
||||||
|
|
||||||
- **Audio-Bytes** (Wiedergabe über den eingebauten oto-Sink): benötigt
|
The `osbuiltin` provider uses two routes on Linux:
|
||||||
`espeak` (oder `espeak-ng`). Auf NixOS als Dev-Abhängigkeit:
|
|
||||||
|
- **Audio bytes** (playback through the built-in oto sink): needs
|
||||||
|
`espeak-ng` (or `espeak`). On NixOS as a dev dependency:
|
||||||
`nix shell nixpkgs#espeak-ng`.
|
`nix shell nixpkgs#espeak-ng`.
|
||||||
- **Direktansage** ohne espeak: `spd-say` (speech-dispatcher) — spielt
|
- **Direct speech** without espeak: `spd-say` (speech-dispatcher) plays by
|
||||||
selbst über den Daemon ab, kann aber nach `spd-say --help` keine Bytes
|
itself through its daemon but cannot deliver bytes to a file or pipe.
|
||||||
in Dateien/Pipes liefern. `talk` nutzt diesen Weg automatisch, wenn
|
`talk` takes this route automatically when espeak is missing.
|
||||||
kein espeak vorhanden ist.
|
|
||||||
|
|
||||||
`TALK_AUDIO_SINK=null` (oder `audio.sink = "null"` in der config.toml)
|
`TALK_AUDIO_SINK=null` (or `audio.sink = "null"` in config.toml) turns all
|
||||||
schaltet jede Tongabe ab — für CI und Server.
|
sound off, for CI and servers.
|
||||||
|
|
||||||
## `talk wrap` — Befehle annoncieren (Task 07)
|
## `talk wrap`: announce commands
|
||||||
|
|
||||||
`talk wrap -- <Befehl> [Argumente …]` führt den Befehl aus und macht das
|
`talk wrap -- <command> [args …]` runs the command and makes the result
|
||||||
Ergebnis hörbar: stdin/stdout/stderr werden durchgereicht — stdout gehört
|
audible: stdin/stdout/stderr are passed through; stdout belongs to the
|
||||||
allein dem Befehl, Informationszeilen von talk (z. B. die Item-ID der
|
command alone, talk's information lines (for example the announcement's
|
||||||
Ansage) gehen auf stderr, damit Pipes und Redirects sauber bleiben. Die
|
item ID) go to stderr so pipes and redirects stay clean. Wall time is
|
||||||
Wandzeit wird gemessen und nach dem Ende des Befehls angesagt:
|
measured and announced after the command ends:
|
||||||
|
|
||||||
- Erfolg: „sleep erfolgreich. Dauer: 2 Sekunden."
|
- success: "sleep succeeded. Duration: 2 seconds."
|
||||||
- Misserfolg: „sh fehlgeschlagen, Code 2." (ohne Dauer)
|
- failure: "sh failed, code 2." (without duration)
|
||||||
|
|
||||||
```console
|
```console
|
||||||
talk wrap -- sleep 2
|
talk wrap -- sleep 2
|
||||||
talk wrap --wait -- make test
|
talk wrap --wait -- make test
|
||||||
```
|
```
|
||||||
|
|
||||||
- **`--` schirmt den Befehl komplett ab:** Das erste allein stehende `--`
|
- **`--` shields the command completely:** the first standalone `--` ends
|
||||||
beendet die talk-Flag-Auswertung — alles danach geht unverändert an den
|
talk's flag parsing; everything after it goes to the command unchanged.
|
||||||
Befehl. `talk wrap -- foo --bar` reicht `--bar` an foo weiter, statt es
|
`talk wrap -- foo --bar` passes `--bar` to foo instead of misreading it
|
||||||
als talk-Flag zu fehlzuinterpretieren. talk-Flags für die Ansage stehen
|
as a talk flag. talk's flags for the announcement therefore go before it
|
||||||
deshalb davor (`talk wrap --wait -- …`); ohne `--` gelten die üblichen
|
(`talk wrap --wait -- …`); without `--` the usual rules apply (flags
|
||||||
Regeln (Flags überall, auch nach Positionalargumenten).
|
anywhere, also after positional arguments).
|
||||||
- **Label** der Ansage: `wrap.label` in der config.toml (Env
|
- **Label** of the announcement: `wrap.label` in config.toml (env
|
||||||
`TALK_WRAP_LABEL` schlägt die Datei) oder der Basisname des Befehls
|
`TALK_WRAP_LABEL` beats the file) or the command's base name
|
||||||
(`/usr/bin/make` → „make"). Die Sprache erkennt langdetect am Label
|
(`/usr/bin/make` → "make"). Language detection runs on the label (de/en,
|
||||||
(de/en, deutscher Default); `--lang` überschreibt.
|
falling back to the configured `lang`); `--lang` overrides.
|
||||||
- **Exit-Code-Politik:** wrap exitet immer mit dem Code des Befehls —
|
- **Exit code policy:** wrap always exits with the command's code; if the
|
||||||
scheitert die Ansage selbst, bleibt der Befehls-Code trotzdem (nur eine
|
announcement itself fails, the command's code still stands (only a
|
||||||
Warning auf stderr; talk-Fehler ≠ Befehls-Fehler). Nicht startbare
|
warning on stderr; talk errors are not command errors). Commands that
|
||||||
Befehle (Binary nicht gefunden) zählen als 127 (Shell-Konvention),
|
cannot start (binary not found) count as 127 (shell convention), signal
|
||||||
Signaltode portabel als 1. Benutzungsfehler von talk selbst (kein
|
deaths portably as 1. Usage errors of talk itself (no command, invalid
|
||||||
Befehl, ungültige Flags) scheitern vor dem Start des Befehls.
|
flags) fail before the command starts.
|
||||||
- **Ansageweg:** derselbe wie say — Daemon (enqueue, non-blocking;
|
- **Announcement path:** the same as say: daemon (enqueue, non-blocking;
|
||||||
`--wait` respektiert; Autostart), ohne Daemon der Direkt-Pfad.
|
`--wait` honoured; autostart), without a daemon the direct path. wrap
|
||||||
wrap erbt die say-Flags (`--wait`, `--now`, `--priority`, `--voice`,
|
inherits the say flags (`--wait`, `--now`, `--priority`, `--voice`,
|
||||||
`--lang`, `--provider`) und reicht sie an die Ansage durch.
|
`--lang`, `--provider`) and passes them on.
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[wrap]
|
[wrap]
|
||||||
label = "Deployment" # Ansage-Label statt Befehls-Basisname (TALK_WRAP_LABEL)
|
label = "Deployment" # announcement label instead of the command's base name (TALK_WRAP_LABEL)
|
||||||
```
|
```
|
||||||
|
|
||||||
## Entwicklung
|
## For agents: skill and standing order
|
||||||
|
|
||||||
|
[`skills/talk/SKILL.md`](skills/talk/SKILL.md) is the etiquette as a skill
|
||||||
|
artifact: **strict opt-in** (speak only when asked in the session or by a
|
||||||
|
standing order in the project's AGENTS.md, session-sticky until revoked),
|
||||||
|
content = status · next step · what the user is needed for, never the long
|
||||||
|
answer, honour `muted`/`discarded`. The three-line block for project
|
||||||
|
AGENTS.md files is in
|
||||||
|
[`skills/talk/AGENTS-snippet.md`](skills/talk/AGENTS-snippet.md). The daemon
|
||||||
|
enforces rate limit, length and age limits, mute and quiet hours regardless
|
||||||
|
of what the prompt says.
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
```console
|
```console
|
||||||
go build ./... # bauen
|
go build ./... # build
|
||||||
go test ./... # Tests
|
go test ./... # tests
|
||||||
go vet ./... # statische Analyse
|
go vet ./... # static analysis
|
||||||
gofmt -l . # Formatierung prüfen (leerer Output = ok)
|
gofmt -l . # formatting check (empty output = ok)
|
||||||
|
nix develop # devShell with go, gopls, espeak-ng, libnotify
|
||||||
```
|
```
|
||||||
|
|
||||||
CI: `.gitea/workflows/test.yml` (Gitea Actions) läuft vet, gofmt-Check, Tests
|
CI: `.gitea/workflows/test.yml` (Gitea Actions) runs vet, the gofmt check,
|
||||||
und Build bei jedem Push und Pull Request.
|
tests and build on every push and pull request.
|
||||||
|
|
||||||
## Lizenz
|
**Icon:** the source is `assets/icon/talk.svg`. `go run assets/icon/gen.go`
|
||||||
|
(needs inkscape) renders the embedded PNG (`internal/icon/talk.png`), the
|
||||||
|
Windows `talk.ico` and the resource objects `cmd/talk/rsrc_windows_*.syso`
|
||||||
|
that give `talk.exe` its icon; all of them are committed, so a normal build
|
||||||
|
needs no resource compiler.
|
||||||
|
|
||||||
MIT — siehe [LICENSE](LICENSE).
|
**Release:** push a `v*` tag → `.gitea/workflows/release.yml` tests, builds
|
||||||
|
the six targets with `scripts/release.sh` (static, `CGO_ENABLED=0`, version
|
||||||
|
via ldflags) and creates a Gitea release with `talk_<os>_<arch>[.exe]` and
|
||||||
|
`checksums.txt`. Locally: `scripts/release.sh 1.2.3` → `dist/`. Deliberately
|
||||||
|
without GoReleaser: a shell script around `go build` yields the same
|
||||||
|
artifact locally and in CI without another tool. `nix build .#talk` builds
|
||||||
|
the Nix package (after changes to go.mod, update the `vendorHash` in
|
||||||
|
flake.nix; `nix build` prints the expected value).
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT, see [LICENSE](LICENSE).
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
//go:build ignore
|
||||||
|
|
||||||
|
// gen renders the talk icon from assets/icon/talk.svg into everything the
|
||||||
|
// build embeds, so no resource compiler is needed:
|
||||||
|
//
|
||||||
|
// internal/icon/talk.png 256 px, embedded in the binary (toast
|
||||||
|
// and notification icon)
|
||||||
|
// assets/icon/talk.ico multi-size Windows icon
|
||||||
|
// cmd/talk/rsrc_windows_<arch>.syso COFF resource object with the icon;
|
||||||
|
// go build links it into talk.exe
|
||||||
|
//
|
||||||
|
// Run from the repository root (needs inkscape in PATH):
|
||||||
|
//
|
||||||
|
// go run assets/icon/gen.go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/binary"
|
||||||
|
"fmt"
|
||||||
|
"image/color"
|
||||||
|
"image/png"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
// sizes are the icon sizes Windows asks for (Explorer, taskbar, Alt-Tab,
|
||||||
|
// toast header); 256 is stored as PNG, the rest as plain bitmaps.
|
||||||
|
var sizes = []int{16, 20, 24, 32, 40, 48, 64, 128, 256}
|
||||||
|
|
||||||
|
const svgPath = "assets/icon/talk.svg"
|
||||||
|
|
||||||
|
// iconImage is one size of the icon in the form ICO files and RT_ICON
|
||||||
|
// resources store it.
|
||||||
|
type iconImage struct {
|
||||||
|
size int
|
||||||
|
data []byte // PNG (256) or BITMAPINFOHEADER + pixels + mask
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
if _, err := os.Stat("go.mod"); err != nil {
|
||||||
|
fail("run from the repository root: %v", err)
|
||||||
|
}
|
||||||
|
tmp, err := os.MkdirTemp("", "talk-icon-")
|
||||||
|
if err != nil {
|
||||||
|
fail("%v", err)
|
||||||
|
}
|
||||||
|
defer os.RemoveAll(tmp)
|
||||||
|
|
||||||
|
var images []iconImage
|
||||||
|
for _, s := range sizes {
|
||||||
|
out := filepath.Join(tmp, fmt.Sprintf("%d.png", s))
|
||||||
|
cmd := exec.Command("inkscape", svgPath, "-w", fmt.Sprint(s), "-h", fmt.Sprint(s), "-o", out)
|
||||||
|
if b, err := cmd.CombinedOutput(); err != nil {
|
||||||
|
fail("inkscape %d px: %v: %s", s, err, b)
|
||||||
|
}
|
||||||
|
b, err := os.ReadFile(out)
|
||||||
|
if err != nil {
|
||||||
|
fail("%v", err)
|
||||||
|
}
|
||||||
|
if s == 256 {
|
||||||
|
write("internal/icon/talk.png", b)
|
||||||
|
images = append(images, iconImage{s, b})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
dib, err := toDIB(b)
|
||||||
|
if err != nil {
|
||||||
|
fail("%d px: %v", s, err)
|
||||||
|
}
|
||||||
|
images = append(images, iconImage{s, dib})
|
||||||
|
}
|
||||||
|
write("assets/icon/talk.ico", buildICO(images))
|
||||||
|
for arch, machine := range map[string]uint16{"amd64": 0x8664, "arm64": 0xAA64} {
|
||||||
|
write("cmd/talk/rsrc_windows_"+arch+".syso", buildSyso(machine, images))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func write(path string, b []byte) {
|
||||||
|
if err := os.WriteFile(path, b, 0o644); err != nil {
|
||||||
|
fail("%v", err)
|
||||||
|
}
|
||||||
|
fmt.Printf("wrote %s (%d bytes)\n", path, len(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
func fail(format string, a ...any) {
|
||||||
|
fmt.Fprintf(os.Stderr, "gen: "+format+"\n", a...)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// toDIB converts a PNG into the classic icon bitmap: BITMAPINFOHEADER with
|
||||||
|
// doubled height, 32-bit BGRA rows bottom-up, then the 1-bit AND mask.
|
||||||
|
func toDIB(pngData []byte) ([]byte, error) {
|
||||||
|
img, err := png.Decode(bytes.NewReader(pngData))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
b := img.Bounds()
|
||||||
|
w, h := b.Dx(), b.Dy()
|
||||||
|
maskRow := ((w + 31) / 32) * 4
|
||||||
|
var buf bytes.Buffer
|
||||||
|
hdr := []uint32{40, uint32(w), uint32(2 * h)}
|
||||||
|
binary.Write(&buf, binary.LittleEndian, hdr)
|
||||||
|
binary.Write(&buf, binary.LittleEndian, []uint16{1, 32}) // planes, bit count
|
||||||
|
binary.Write(&buf, binary.LittleEndian, []uint32{0, uint32(w*h*4 + maskRow*h), 0, 0, 0, 0})
|
||||||
|
for y := h - 1; y >= 0; y-- {
|
||||||
|
for x := 0; x < w; x++ {
|
||||||
|
c := color.NRGBAModel.Convert(img.At(b.Min.X+x, b.Min.Y+y)).(color.NRGBA)
|
||||||
|
buf.Write([]byte{c.B, c.G, c.R, c.A})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for y := h - 1; y >= 0; y-- {
|
||||||
|
row := make([]byte, maskRow)
|
||||||
|
for x := 0; x < w; x++ {
|
||||||
|
if _, _, _, a := img.At(b.Min.X+x, b.Min.Y+y).RGBA(); a == 0 {
|
||||||
|
row[x/8] |= 0x80 >> (x % 8)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
buf.Write(row)
|
||||||
|
}
|
||||||
|
return buf.Bytes(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// dirEntry writes the 12 bytes ICONDIRENTRY and GRPICONDIRENTRY share.
|
||||||
|
func dirEntry(buf *bytes.Buffer, im iconImage) {
|
||||||
|
dim := byte(im.size)
|
||||||
|
if im.size >= 256 {
|
||||||
|
dim = 0
|
||||||
|
}
|
||||||
|
buf.Write([]byte{dim, dim, 0, 0})
|
||||||
|
binary.Write(buf, binary.LittleEndian, []uint16{1, 32})
|
||||||
|
binary.Write(buf, binary.LittleEndian, uint32(len(im.data)))
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildICO lays out an .ico file: ICONDIR, one ICONDIRENTRY per image with
|
||||||
|
// the file offset of its data, then the images.
|
||||||
|
func buildICO(images []iconImage) []byte {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
binary.Write(&buf, binary.LittleEndian, []uint16{0, 1, uint16(len(images))})
|
||||||
|
offset := 6 + 16*len(images)
|
||||||
|
for _, im := range images {
|
||||||
|
dirEntry(&buf, im)
|
||||||
|
binary.Write(&buf, binary.LittleEndian, uint32(offset))
|
||||||
|
offset += len(im.data)
|
||||||
|
}
|
||||||
|
for _, im := range images {
|
||||||
|
buf.Write(im.data)
|
||||||
|
}
|
||||||
|
return buf.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildGroupIcon is the RT_GROUP_ICON payload: like ICONDIR, but each entry
|
||||||
|
// ends with the RT_ICON resource id instead of a file offset.
|
||||||
|
func buildGroupIcon(images []iconImage) []byte {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
binary.Write(&buf, binary.LittleEndian, []uint16{0, 1, uint16(len(images))})
|
||||||
|
for i, im := range images {
|
||||||
|
dirEntry(&buf, im)
|
||||||
|
binary.Write(&buf, binary.LittleEndian, uint16(i+1))
|
||||||
|
}
|
||||||
|
return buf.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
rtIcon = 3
|
||||||
|
rtGroupIcon = 14
|
||||||
|
langNeutral = 0x0409
|
||||||
|
)
|
||||||
|
|
||||||
|
// resource is one leaf of the .rsrc tree: type/id/language and its data.
|
||||||
|
type resource struct {
|
||||||
|
typ, id uint32
|
||||||
|
data []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildSyso writes a COFF object with a single .rsrc section the Go linker
|
||||||
|
// merges into the PE resource table: the directory tree (type → id →
|
||||||
|
// language → data entry), the data, one ADDR32NB relocation per data entry
|
||||||
|
// (the linker turns the section offsets into image RVAs), and the section
|
||||||
|
// symbol the relocations refer to.
|
||||||
|
func buildSyso(machine uint16, images []iconImage) []byte {
|
||||||
|
var res []resource
|
||||||
|
for i, im := range images {
|
||||||
|
res = append(res, resource{rtIcon, uint32(i + 1), im.data})
|
||||||
|
}
|
||||||
|
res = append(res, resource{rtGroupIcon, 1, buildGroupIcon(images)})
|
||||||
|
|
||||||
|
// Layout: root dir, the two type dirs, one language dir per resource,
|
||||||
|
// one data entry per resource, then the data.
|
||||||
|
const dirHdr, dirEnt, dataEnt = 16, 8, 16
|
||||||
|
types := []uint32{rtIcon, rtGroupIcon}
|
||||||
|
byType := map[uint32][]resource{}
|
||||||
|
for _, r := range res {
|
||||||
|
byType[r.typ] = append(byType[r.typ], r)
|
||||||
|
}
|
||||||
|
rootOff := uint32(0)
|
||||||
|
typeDirOff := map[uint32]uint32{}
|
||||||
|
off := uint32(dirHdr + dirEnt*len(types))
|
||||||
|
for _, t := range types {
|
||||||
|
typeDirOff[t] = off
|
||||||
|
off += uint32(dirHdr + dirEnt*len(byType[t]))
|
||||||
|
}
|
||||||
|
langDirOff := make([]uint32, len(res))
|
||||||
|
for i := range res {
|
||||||
|
langDirOff[i] = off
|
||||||
|
off += dirHdr + dirEnt
|
||||||
|
}
|
||||||
|
dataEntOff := make([]uint32, len(res))
|
||||||
|
for i := range res {
|
||||||
|
dataEntOff[i] = off
|
||||||
|
off += dataEnt
|
||||||
|
}
|
||||||
|
dataOff := make([]uint32, len(res))
|
||||||
|
for i, r := range res {
|
||||||
|
off = (off + 7) &^ 7
|
||||||
|
dataOff[i] = off
|
||||||
|
off += uint32(len(r.data))
|
||||||
|
}
|
||||||
|
sectionSize := off
|
||||||
|
|
||||||
|
var sec bytes.Buffer
|
||||||
|
le := binary.LittleEndian
|
||||||
|
dir := func(entries int) {
|
||||||
|
binary.Write(&sec, le, []uint32{0, 0})
|
||||||
|
binary.Write(&sec, le, []uint16{0, 0, 0, uint16(entries)})
|
||||||
|
}
|
||||||
|
sub := func(id, target uint32) { binary.Write(&sec, le, []uint32{id, target | 0x80000000}) }
|
||||||
|
leaf := func(id, target uint32) { binary.Write(&sec, le, []uint32{id, target}) }
|
||||||
|
index := func(r resource) int {
|
||||||
|
for i := range res {
|
||||||
|
if res[i].typ == r.typ && res[i].id == r.id {
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
panic("unreachable")
|
||||||
|
}
|
||||||
|
_ = rootOff
|
||||||
|
dir(len(types))
|
||||||
|
for _, t := range types {
|
||||||
|
sub(t, typeDirOff[t])
|
||||||
|
}
|
||||||
|
for _, t := range types {
|
||||||
|
dir(len(byType[t]))
|
||||||
|
for _, r := range byType[t] {
|
||||||
|
sub(r.id, langDirOff[index(r)])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i := range res {
|
||||||
|
dir(1)
|
||||||
|
leaf(langNeutral, dataEntOff[i])
|
||||||
|
}
|
||||||
|
var relocs []uint32
|
||||||
|
for i, r := range res {
|
||||||
|
relocs = append(relocs, uint32(sec.Len()))
|
||||||
|
binary.Write(&sec, le, []uint32{dataOff[i], uint32(len(r.data)), 0, 0})
|
||||||
|
}
|
||||||
|
for i, r := range res {
|
||||||
|
sec.Write(make([]byte, int(dataOff[i])-sec.Len()))
|
||||||
|
sec.Write(r.data)
|
||||||
|
}
|
||||||
|
if uint32(sec.Len()) != sectionSize {
|
||||||
|
fail("section layout mismatch: %d != %d", sec.Len(), sectionSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
relocType := uint16(0x0003) // IMAGE_REL_AMD64_ADDR32NB
|
||||||
|
if machine == 0xAA64 {
|
||||||
|
relocType = 0x0002 // IMAGE_REL_ARM64_ADDR32NB
|
||||||
|
}
|
||||||
|
const fileHdr, secHdr, relocSize, symSize = 20, 40, 10, 18
|
||||||
|
rawOff := uint32(fileHdr + secHdr)
|
||||||
|
relocOff := rawOff + sectionSize
|
||||||
|
symOff := relocOff + uint32(relocSize*len(relocs))
|
||||||
|
|
||||||
|
var out bytes.Buffer
|
||||||
|
binary.Write(&out, le, machine)
|
||||||
|
binary.Write(&out, le, uint16(1)) // sections
|
||||||
|
binary.Write(&out, le, uint32(0)) // timestamp
|
||||||
|
binary.Write(&out, le, symOff) // symbol table
|
||||||
|
binary.Write(&out, le, uint32(1)) // symbols
|
||||||
|
binary.Write(&out, le, uint16(0)) // optional header
|
||||||
|
binary.Write(&out, le, uint16(0x0104)) // 32-bit machine, line numbers stripped
|
||||||
|
name := [8]byte{'.', 'r', 's', 'r', 'c'}
|
||||||
|
out.Write(name[:])
|
||||||
|
binary.Write(&out, le, []uint32{0, 0, sectionSize, rawOff, relocOff, 0})
|
||||||
|
binary.Write(&out, le, []uint16{uint16(len(relocs)), 0})
|
||||||
|
binary.Write(&out, le, uint32(0x40000040)) // initialized data, readable
|
||||||
|
out.Write(sec.Bytes())
|
||||||
|
for _, at := range relocs {
|
||||||
|
binary.Write(&out, le, []uint32{at, 0})
|
||||||
|
binary.Write(&out, le, relocType)
|
||||||
|
}
|
||||||
|
out.Write(name[:])
|
||||||
|
binary.Write(&out, le, uint32(0)) // value
|
||||||
|
binary.Write(&out, le, int16(1)) // section number
|
||||||
|
binary.Write(&out, le, uint16(0)) // type
|
||||||
|
out.Write([]byte{3, 0}) // static, no aux symbols
|
||||||
|
binary.Write(&out, le, uint32(4)) // empty string table
|
||||||
|
return out.Bytes()
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 112 KiB |
@@ -0,0 +1,8 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256">
|
||||||
|
<path fill="#0F6E86" d="M56 28h144c22 0 40 18 40 40v96c0 22-18 40-40 40H112l-48 36c-6 5-16 1-16-8v-28H56c-22 0-40-18-40-40V68c0-22 18-40 40-40z"/>
|
||||||
|
<g fill="#FFFFFF">
|
||||||
|
<rect x="76" y="100" width="24" height="56" rx="12"/>
|
||||||
|
<rect x="116" y="72" width="24" height="112" rx="12"/>
|
||||||
|
<rect x="156" y="88" width="24" height="80" rx="12"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 447 B |
+133
-141
@@ -8,162 +8,170 @@ import (
|
|||||||
"slices"
|
"slices"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Exit-Codes.
|
// Exit codes.
|
||||||
const (
|
const (
|
||||||
exitOK = 0 // Erfolg (auch --help, --version)
|
exitOK = 0 // success (also --help, --version)
|
||||||
exitFailure = 1 // Befehl fehlgeschlagen oder noch nicht implementiert
|
exitFailure = 1 // command failed
|
||||||
exitUsage = 2 // Falsche Benutzung (unbekannte Flags, kein Befehl)
|
exitUsage = 2 // wrong usage (unknown flags, missing command)
|
||||||
)
|
)
|
||||||
|
|
||||||
// command ist ein Eintrag der Befehlstabelle. Die Tabelle ist bewusst
|
// command is an entry of the command table. The table is data-driven on
|
||||||
// datengetrieben: Spätere Tasks (z. B. die TUI-Befehle aus Task 09) ergänzen
|
// purpose: new commands add an entry instead of touching the dispatch in
|
||||||
// hier Einträge bzw. Register-Funktionen, ohne die Dispatch-Logik in run()
|
// run(). register attaches the command's flags to the FlagSet and returns the
|
||||||
// anzufassen. register hängt die Flags des Befehls an den FlagSet und liefert
|
// bound options; handler executes the command.
|
||||||
// die gebundenen say-Options (derzeit der einzige Befehl mit eigenen Flags;
|
|
||||||
// erhält ein weiterer Befehl eigene Flags, wird die Signatur verallgemeinert).
|
|
||||||
type command struct {
|
type command struct {
|
||||||
name string // Subcommand-Name (bindende CLI-Surface aus der Spec)
|
name string // subcommand name (part of the CLI surface)
|
||||||
short string // Kurzbeschreibung für `talk --help`
|
short string // one-liner for `talk --help`
|
||||||
args string // Positionsargumente-Hinweis für die Usage-Zeile
|
args string // positional arguments hint for the usage line
|
||||||
detail string // Beschreibung für `talk <Befehl> --help`
|
detail string // description for `talk <command> --help`
|
||||||
register func(fs *flag.FlagSet) *sayOptions // hängt die Flags des Befehls an den FlagSet
|
register func(fs *flag.FlagSet) *sayOptions // attaches the command's flags to the FlagSet
|
||||||
handler func(args []string, o *sayOptions, stdin io.Reader, stdout, stderr io.Writer) int // Ausführung (fehlt sie: Stub)
|
handler func(args []string, o *sayOptions, stdin io.Reader, stdout, stderr io.Writer) int // execution
|
||||||
}
|
}
|
||||||
|
|
||||||
// commands ist die vollständige Befehlstabelle. Die Namen sind Teil der
|
// commands is the complete command table. The names are part of the CLI
|
||||||
// bindenden CLI-Surface (Spec: „CLI-Surface (exakt)“) — nicht umbenennen.
|
// surface; do not rename.
|
||||||
var commands = []command{
|
var commands = []command{
|
||||||
{
|
{
|
||||||
name: "say",
|
name: "say",
|
||||||
short: "Text ansagen (Default-Befehl)",
|
short: "speak a text (default command)",
|
||||||
args: `"Text"`,
|
args: `"text"`,
|
||||||
detail: "Spricht den Text über die Provider-Kette aus. Ohne Text-Argument wird stdin gelesen. `talk \"Text\"` ist die Abkürzung für `talk say \"Text\"`.",
|
detail: "Speaks the text through the provider chain. Without a text argument, stdin is read. `talk \"text\"` is shorthand for `talk say \"text\"`.",
|
||||||
register: addSayFlags,
|
register: addSayFlags,
|
||||||
handler: runSay,
|
handler: runSay,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "wrap",
|
name: "wrap",
|
||||||
short: "Befehl ausführen und Ergebnis ansagen",
|
short: "run a command and announce the result",
|
||||||
args: "-- <Befehl> [Argumente …]",
|
args: "-- <command> [args …]",
|
||||||
detail: "Führt den Befehl aus (stdin/stdout/stderr werden durchgereicht) und spricht danach Erfolg bzw. Misserfolg und Dauer. Das erste „--\" schirmt den Befehl komplett von den talk-Flags ab: `talk wrap -- foo --bar` reicht --bar an foo weiter. Der Exit-Code des Befehls wird durchgereicht; scheitert die Ansage selbst, bleibt er trotzdem. Label der Ansage: config `wrap.label` oder der Basisname des Befehls. wrap erbt die say-Flags (--wait, --now, --priority, --voice, --lang, --provider).",
|
detail: "Runs the command (stdin/stdout/stderr are passed through) and then announces success or failure and the duration. The first \"--\" shields the command completely from talk's flags: `talk wrap -- foo --bar` passes --bar to foo. The command's exit code is passed through; if the announcement itself fails, the code still stands. Announcement label: config `wrap.label` or the command's base name. wrap inherits the say flags (--wait, --now, --priority, --voice, --lang, --provider).",
|
||||||
register: addSayFlags,
|
register: addSayFlags,
|
||||||
handler: runWrap,
|
handler: runWrap,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "mute",
|
name: "mute",
|
||||||
short: "Ansagen dauerhaft stummschalten",
|
short: "mute all announcements persistently",
|
||||||
detail: "Aktiviert den persistenten Mute-State (Datei `mute` im Config-Verzeichnis). Läuft der Daemon, wird er darüber informiert; andernfalls schreibt talk die Datei direkt — der Zustand überlebt Daemon-Restarts.",
|
detail: "Turns on the persistent mute state (file `mute` in the config directory). A running daemon is told; otherwise talk writes the file directly. The state survives daemon restarts.",
|
||||||
handler: runMute,
|
handler: runMute,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "unmute",
|
name: "unmute",
|
||||||
short: "Stummschaltung aufheben",
|
short: "turn announcements back on",
|
||||||
detail: "Hebt den persistenten Mute-State wieder auf (Daemon-Aufruf; ohne Daemon direkt über die Datei).",
|
detail: "Clears the persistent mute state (daemon call; without a daemon directly via the file).",
|
||||||
handler: runUnmute,
|
handler: runUnmute,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "status",
|
name: "status",
|
||||||
short: "Daemon-Status anzeigen",
|
short: "show the daemon status",
|
||||||
detail: "Zeigt Queue, aktuelles Item, Mute-State, aktiven Provider und Daemon-Version (plain, eine Zeile pro Feld).",
|
detail: "Shows queue, current item, mute state, active provider, laws and daemon version (plain, one line per field). Does not start the daemon.",
|
||||||
handler: runStatus,
|
handler: runStatus,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "daemon",
|
name: "daemon",
|
||||||
short: "Hintergrundprozess steuern (run | start | stop)",
|
short: "control the background process (run | start | stop)",
|
||||||
args: "[run|start|stop]",
|
args: "[run|start|stop]",
|
||||||
detail: "run (Default) betreibt den Daemon im Vordergrund — für systemd, launchd oder ein Terminal. start startet ihn im Hintergrund (Log: daemon.log im Config-Verzeichnis), stop fährt einen laufenden Daemon herunter. Normalerweise nicht nötig: talk startet den Daemon beim ersten Sprechbefehl selbst (daemon.autostart, Default an).",
|
detail: "run (default) runs the daemon in the foreground, for systemd, launchd or a terminal. start launches it in the background (log: daemon.log in the config directory), stop shuts a running daemon down. Normally not needed: talk starts the daemon itself on the first speak command (daemon.autostart, default on).",
|
||||||
handler: runDaemon,
|
handler: runDaemon,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "cancel",
|
name: "cancel",
|
||||||
short: "Laufende und geplante Ansagen abbrechen",
|
short: "cancel the playing and all queued announcements",
|
||||||
detail: "Bricht die laufende Ansage ab und leert die Queue des Daemons; Ausgabe ist die Zahl der abgebrochenen Ansagen.",
|
detail: "Aborts the playing announcement and empties the daemon's queue; prints the number of cancelled announcements.",
|
||||||
handler: runCancel,
|
handler: runCancel,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "uri",
|
||||||
|
short: "handle a talk: link (notification buttons)",
|
||||||
|
args: "<talk:…>",
|
||||||
|
detail: "The handler behind the talk: URL protocol: a toast's Cancel button opens talk:cancel?id=<id>&port=<port>, Windows starts `talk uri` with it, and talk tells the daemon to cancel that announcement. Registered for the current user by the daemon on Windows; not needed elsewhere.",
|
||||||
|
handler: runURI,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "voices",
|
name: "voices",
|
||||||
short: "Verfügbare Stimmen anzeigen",
|
short: "list known voices",
|
||||||
detail: "Listet bekannte Stimmen je Provider und Sprache als Tabelle; „*“ markiert die Stimme, die talk ohne --voice nimmt (config voice.<provider>.<lang> oder Repo-Default). Filter: --provider, --lang. --json für Maschinen. Jede Voice-ID des Providers funktioniert auch ohne Katalog-Eintrag.",
|
detail: "Lists known voices per provider and language as a table; \"*\" marks the voice talk uses without --voice (config voice.<provider>.<lang> or the built-in default). Filters: --provider, --lang. --json for machines. Any voice ID the provider knows works without a catalog entry.",
|
||||||
register: addVoicesFlags,
|
register: addVoicesFlags,
|
||||||
handler: runVoices,
|
handler: runVoices,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "test",
|
name: "test",
|
||||||
short: "Test-Ansage ausgeben",
|
short: "speak a test sentence",
|
||||||
detail: "Spricht eine feste Testphrase direkt in diesem Prozess (ohne Daemon, auch bei Mute) und zeigt, welcher Provider gesprochen hat und wie lange Synthese und Wiedergabe gedauert haben. --lang de|en wählt die Phrase, --provider/--voice pinnen wie bei say.",
|
detail: "Speaks a fixed test sentence directly in this process (not via the daemon, even when muted) and shows which provider spoke and how long synthesis and playback took. --lang de|en picks the sentence, --provider/--voice pin like say. --toast sends a test desktop notification instead (the path quiet_mode = toast uses).",
|
||||||
register: addTestFlags,
|
register: addTestFlags,
|
||||||
handler: runTest,
|
handler: runTest,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "doctor",
|
name: "doctor",
|
||||||
short: "Setup-Diagnose anzeigen",
|
short: "diagnose the setup",
|
||||||
detail: "Prüft Config, Daemon, Audio-Ausgabe, jede Provider-Stufe, Mute und Gesetze und berichtet zeilenweise mit ✔ (ok), ⚠ (Hinweis), ✘ (Fehler). Exit 0 ohne ✘, sonst 1; ein nicht laufender Daemon ist ⚠, kein Fehler. --probe macht echte Synthese-Proben bei allen verfügbaren Providern (Netz). --json für Maschinen.",
|
detail: "Checks config, daemon, audio output, every provider tier, notifications, mute and laws and reports one line each with ✔ (ok), ⚠ (note), ✘ (error). Exit 0 without ✘, else 1; a daemon that is not running is ⚠, not an error. --probe runs real synthesis probes against every available provider (network). --json for machines.",
|
||||||
register: addDoctorFlags,
|
register: addDoctorFlags,
|
||||||
handler: runDoctor,
|
handler: runDoctor,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "setup",
|
name: "setup",
|
||||||
short: "Geführte Ersteinrichtung",
|
short: "guided first-time setup",
|
||||||
detail: "Fragt in wenigen Schritten nach dem, was talk zum Loslegen braucht: Keys (optional — ohne Key spricht die kostenlose Edge-Stimme), Stimme je Sprache mit Probehören, Ruhezeit — und schreibt die config.toml (bestehende Datei wird zusammengeführt, Sicherung .bak). Ohne Terminal: zeigt nur die wirksame Konfiguration.",
|
detail: "Asks a few questions for what talk needs to get going: keys (optional; without a key the free Edge voice speaks), a voice per language with preview, quiet hours, and writes config.toml (an existing file is merged, backup .bak). Without a terminal: only shows the effective configuration.",
|
||||||
handler: runSetup,
|
handler: runSetup,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "version",
|
||||||
|
short: "show the version",
|
||||||
|
detail: "Prints the version and, when built from git, the commit. Same as `talk --version`; exists so that a bare `talk version` is not spoken as an announcement.",
|
||||||
|
handler: func(_ []string, _ *sayOptions, _ io.Reader, stdout, _ io.Writer) int {
|
||||||
|
fmt.Fprintln(stdout, versionString())
|
||||||
|
return exitOK
|
||||||
|
},
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
// addSayFlags registriert die Flags des say-Befehls und bindet sie an die
|
// addSayFlags registers the say flags and binds them to the returned options
|
||||||
// zurückgegebene Options-Struct. Sie gelten auch für den Default-Pfad
|
// struct. They also apply to the default form `talk "text"`. A pointer is
|
||||||
// `talk "Text"` (gleiche Flag-Oberfläche, festgelegt in der Spec). Verhalten
|
// returned on purpose: flag.Var binds to the fields of exactly this struct.
|
||||||
// seit Task 04: läuft ein Daemon, wird enqueue (non-blocking); --wait pollt
|
|
||||||
// bis zur Fertigstellung, --now springt vor. Ohne Daemon: Degraded Mode.
|
|
||||||
//
|
|
||||||
// Rückgabe ist bewusst ein Pointer: flag.Var bindet an die Felder genau
|
|
||||||
// dieser Struct — eine Wertkopie hätte nach dem Parse weiterhin die
|
|
||||||
// Defaults.
|
|
||||||
func addSayFlags(fs *flag.FlagSet) *sayOptions {
|
func addSayFlags(fs *flag.FlagSet) *sayOptions {
|
||||||
o := &sayOptions{}
|
o := &sayOptions{}
|
||||||
fs.BoolVar(&o.wait, "wait", false, "warten, bis die Ansage fertig abgespielt ist")
|
fs.BoolVar(&o.wait, "wait", false, "wait until the announcement has been spoken")
|
||||||
fs.BoolVar(&o.now, "now", false, "Ansage sofort ausgeben (springt die Warteschlange)")
|
fs.BoolVar(&o.now, "now", false, "speak immediately (jumps the queue; breaks out of rate limit and quiet hours)")
|
||||||
fs.StringVar(&o.priority, "priority", "normal", "Priorität: low | normal | high")
|
fs.StringVar(&o.priority, "priority", "normal", "priority: low | normal | high")
|
||||||
fs.StringVar(&o.voice, "voice", "", "Stimme als provider-spezifische ID")
|
fs.StringVar(&o.voice, "voice", "", "voice as a provider-specific ID")
|
||||||
fs.StringVar(&o.lang, "lang", "", "Sprache: de | en (Default: automatische Erkennung)")
|
fs.StringVar(&o.lang, "lang", "", "language: de | en (default: detected)")
|
||||||
fs.StringVar(&o.provider, "provider", "", "Provider pinnen: elevenlabs | openai | edge | osbuiltin")
|
fs.StringVar(&o.provider, "provider", "", "pin a provider: elevenlabs | openai | edge | osbuiltin")
|
||||||
return o
|
return o
|
||||||
}
|
}
|
||||||
|
|
||||||
// addVoicesFlags registriert die Flags von voices (Filter + JSON).
|
// addVoicesFlags registers the voices flags (filters + JSON).
|
||||||
func addVoicesFlags(fs *flag.FlagSet) *sayOptions {
|
func addVoicesFlags(fs *flag.FlagSet) *sayOptions {
|
||||||
o := &sayOptions{}
|
o := &sayOptions{}
|
||||||
fs.StringVar(&o.provider, "provider", "", "nur dieser Provider: elevenlabs | openai | edge | osbuiltin")
|
fs.StringVar(&o.provider, "provider", "", "only this provider: elevenlabs | openai | edge | osbuiltin")
|
||||||
fs.StringVar(&o.lang, "lang", "", "nur diese Sprache: de | en")
|
fs.StringVar(&o.lang, "lang", "", "only this language: de | en")
|
||||||
fs.BoolVar(&o.jsonOut, "json", false, "maschinenlesbare JSON-Ausgabe")
|
fs.BoolVar(&o.jsonOut, "json", false, "machine-readable JSON output")
|
||||||
return o
|
return o
|
||||||
}
|
}
|
||||||
|
|
||||||
// addTestFlags registriert die Flags von test (Phrase + Pins).
|
// addTestFlags registers the test flags (sentence + pins).
|
||||||
func addTestFlags(fs *flag.FlagSet) *sayOptions {
|
func addTestFlags(fs *flag.FlagSet) *sayOptions {
|
||||||
o := &sayOptions{}
|
o := &sayOptions{}
|
||||||
fs.StringVar(&o.lang, "lang", "", "Sprache der Testphrase: de | en (Default de)")
|
fs.StringVar(&o.lang, "lang", "", "language of the test sentence: de | en (default: configured lang)")
|
||||||
fs.StringVar(&o.provider, "provider", "", "Provider pinnen: elevenlabs | openai | edge | osbuiltin")
|
fs.StringVar(&o.provider, "provider", "", "pin a provider: elevenlabs | openai | edge | osbuiltin")
|
||||||
fs.StringVar(&o.voice, "voice", "", "Stimme als provider-spezifische ID")
|
fs.StringVar(&o.voice, "voice", "", "voice as a provider-specific ID")
|
||||||
|
fs.BoolVar(&o.toast, "toast", false, "send a test desktop notification instead of speaking")
|
||||||
return o
|
return o
|
||||||
}
|
}
|
||||||
|
|
||||||
// addDoctorFlags registriert die Flags von doctor.
|
// addDoctorFlags registers the doctor flags.
|
||||||
func addDoctorFlags(fs *flag.FlagSet) *sayOptions {
|
func addDoctorFlags(fs *flag.FlagSet) *sayOptions {
|
||||||
o := &sayOptions{}
|
o := &sayOptions{}
|
||||||
fs.BoolVar(&o.jsonOut, "json", false, "maschinenlesbare JSON-Ausgabe")
|
fs.BoolVar(&o.jsonOut, "json", false, "machine-readable JSON output")
|
||||||
fs.BoolVar(&o.probe, "probe", false, "echte Synthese-Probe bei jedem verfügbaren Provider (Netz-Aufrufe)")
|
fs.BoolVar(&o.probe, "probe", false, "real synthesis probe for every available provider (network calls)")
|
||||||
return o
|
return o
|
||||||
}
|
}
|
||||||
|
|
||||||
// run ist der Einstiegspunkt der CLI (Argumente ohne Programmnamen). Alle
|
// run is the CLI entry point (arguments without the program name). All
|
||||||
// Ausgaben gehen auf die übergebenen Writer, stdin ist als Reader injiziert
|
// output goes to the given writers, stdin is injected, so run is testable
|
||||||
// — damit ist run direkt und ohne Prozessstart testbar (auch der stdin-
|
// without starting a process. The return value is the exit code.
|
||||||
// Pfad aus Task 02). Rückgabe ist der Exit-Code.
|
|
||||||
func run(argv []string, stdin io.Reader, stdout, stderr io.Writer) int {
|
func run(argv []string, stdin io.Reader, stdout, stderr io.Writer) int {
|
||||||
if len(argv) == 0 {
|
if len(argv) == 0 {
|
||||||
// Kein Befehl und kein Argument: Der Text könnte über stdin
|
// No command and no argument: the text may come via stdin (pipe).
|
||||||
// kommen (Pipe). An einem Terminal gibt es keinen Text — dann
|
// At a terminal there is no text, so this is a usage error; talk
|
||||||
// Benutzungsfehler, damit talk nie auf Eingaben wartet.
|
// must never sit waiting for input.
|
||||||
if isCharDevice(stdin) {
|
if isCharDevice(stdin) {
|
||||||
writeUsage(stderr)
|
writeUsage(stderr)
|
||||||
return exitUsage
|
return exitUsage
|
||||||
@@ -177,7 +185,7 @@ func run(argv []string, stdin io.Reader, stdout, stderr io.Writer) int {
|
|||||||
writeCommandHelp(cmd, stdout)
|
writeCommandHelp(cmd, stdout)
|
||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
fmt.Fprintf(stderr, "talk: unbekannter Befehl %q\n", argv[1])
|
fmt.Fprintf(stderr, "talk: unknown command %q\n", argv[1])
|
||||||
return exitUsage
|
return exitUsage
|
||||||
}
|
}
|
||||||
writeUsage(stdout)
|
writeUsage(stdout)
|
||||||
@@ -188,30 +196,25 @@ func run(argv []string, stdin io.Reader, stdout, stderr io.Writer) int {
|
|||||||
return runCommand(cmd, argv[1:], stdin, stdout, stderr)
|
return runCommand(cmd, argv[1:], stdin, stdout, stderr)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Kein bekannter Befehl: Default-Pfad `talk "Text"` (mappt auf say)
|
// No known command: default form `talk "text"` (maps to say) or root
|
||||||
// bzw. Root-Flags (--version, --help).
|
// flags (--version, --help).
|
||||||
return runDefault(argv, stdin, stdout, stderr)
|
return runDefault(argv, stdin, stdout, stderr)
|
||||||
}
|
}
|
||||||
|
|
||||||
// parseInterspersed parst Flags, die überall in argv stehen dürfen. Die
|
// parseInterspersed parses flags that may appear anywhere in argv. The
|
||||||
// Go-stdlib-flag stoppt beim ersten Nicht-Flag-Argument; die CLI-Surface
|
// standard flag package stops at the first non-flag argument, but the CLI
|
||||||
// verlangt aber `talk "Text" --provider=x` (Abnahmekriterium Task 03)
|
// accepts `talk "text" --provider=x` as well as `talk --provider=x "text"`.
|
||||||
// genauso wie `talk --provider=x "Text"`. Trick: Parse über den Rest
|
// Trick: repeat the parse over the rest, taking one positional argument
|
||||||
// wiederholen und jeweils das Positionsargument vor dem Weiterparsen
|
// before each round. Errors (unknown flags, -h) come from the FlagSet.
|
||||||
// entnehmen. Fehler (unbekannte Flags, -h) kommen wie gewohnt vom FlagSet.
|
|
||||||
//
|
//
|
||||||
// Seit Task 07 schirmt das erste „--" (als eigenständiges Argument) alles
|
// The first standalone "--" shields everything after it completely (the
|
||||||
// dahinter vollständig ab — die Stdlib-Terminator-Semantik, die der
|
// standard terminator semantics the interspersed loop used to defeat: it
|
||||||
// Interspersed-Loop zuvor aushebelte: Er nahm nach jedem Positionsargument
|
// resumed parsing after every positional and ate flags meant for the
|
||||||
// das Parsen wieder auf und fraß damit Flags, die für den NACHFOLGENDEN
|
// wrapped command; `talk wrap -- foo --bar` failed on --bar). argv is split
|
||||||
// Befehl gemeint waren (`talk wrap -- foo --bar` wäre an --bar als
|
// at the first "--": only the part before it is parsed interspersed, the
|
||||||
// vermeintlichem talk-Flag gescheitert). Jetzt wird argv am ersten „--"
|
// rest is positional unconditionally, for say (`talk -- "text --flag"`) as
|
||||||
// getrennt: Nur der Teil davor wird interspersed geparst, der Rest ist
|
// well as wrap (`talk wrap -- foo --bar`). A "--" as a flag VALUE (right
|
||||||
// bedingungslos Positionsargument — für say (`talk -- "Text --flag"`)
|
// after --voice) does not split, because only a standalone "--" does.
|
||||||
// genauso wie für wrap (`talk wrap -- foo --bar`). Die Abnahme-Form
|
|
||||||
// `talk "Text" --provider=x` (Flag nach dem Text, ohne „--") ist davon
|
|
||||||
// unberührt. Ein „--" als Flag-Wert (unmittelbar nach --voice) trifft
|
|
||||||
// diese Trennung nicht, weil nur ein allein stehendes „--" trennt.
|
|
||||||
func parseInterspersed(fs *flag.FlagSet, argv []string) ([]string, error) {
|
func parseInterspersed(fs *flag.FlagSet, argv []string) ([]string, error) {
|
||||||
if i := slices.Index(argv, "--"); i >= 0 {
|
if i := slices.Index(argv, "--"); i >= 0 {
|
||||||
positional, err := parseInterspersedLoop(fs, argv[:i])
|
positional, err := parseInterspersedLoop(fs, argv[:i])
|
||||||
@@ -223,8 +226,8 @@ func parseInterspersed(fs *flag.FlagSet, argv []string) ([]string, error) {
|
|||||||
return parseInterspersedLoop(fs, argv)
|
return parseInterspersedLoop(fs, argv)
|
||||||
}
|
}
|
||||||
|
|
||||||
// parseInterspersedLoop ist der Interspersed-Durchlauf — argv enthält kein
|
// parseInterspersedLoop is the interspersed pass; argv holds no standalone
|
||||||
// allein stehendes „--" mehr (parseInterspersed hat davor getrennt).
|
// "--" any more (parseInterspersed split before).
|
||||||
func parseInterspersedLoop(fs *flag.FlagSet, argv []string) ([]string, error) {
|
func parseInterspersedLoop(fs *flag.FlagSet, argv []string) ([]string, error) {
|
||||||
var positional []string
|
var positional []string
|
||||||
rest := argv
|
rest := argv
|
||||||
@@ -236,7 +239,7 @@ func parseInterspersedLoop(fs *flag.FlagSet, argv []string) ([]string, error) {
|
|||||||
if len(args) == 0 {
|
if len(args) == 0 {
|
||||||
return positional, nil
|
return positional, nil
|
||||||
}
|
}
|
||||||
// args[0] ist das Argument, an dem Parse gestoppt hat.
|
// args[0] is the argument Parse stopped at.
|
||||||
positional = append(positional, args[0])
|
positional = append(positional, args[0])
|
||||||
rest = args[1:]
|
rest = args[1:]
|
||||||
}
|
}
|
||||||
@@ -251,10 +254,9 @@ func lookupCommand(name string) (command, bool) {
|
|||||||
return command{}, false
|
return command{}, false
|
||||||
}
|
}
|
||||||
|
|
||||||
// newCommandFlagSet baut den FlagSet eines Befehls: eigene Flags plus ein
|
// newCommandFlagSet builds a command's FlagSet: its own flags plus an
|
||||||
// explizites --help und die gebundenen say-Options. Die Default-Usage wird
|
// explicit --help and the bound options. The default usage is silenced so
|
||||||
// stummgeschaltet, damit Hilfetext ausschließlich über writeCommandHelp
|
// help text comes from writeCommandHelp only (one source).
|
||||||
// (eine Quelle) ausgegeben wird.
|
|
||||||
func newCommandFlagSet(cmd command, out io.Writer) (*flag.FlagSet, *bool, *sayOptions) {
|
func newCommandFlagSet(cmd command, out io.Writer) (*flag.FlagSet, *bool, *sayOptions) {
|
||||||
fs := flag.NewFlagSet("talk "+cmd.name, flag.ContinueOnError)
|
fs := flag.NewFlagSet("talk "+cmd.name, flag.ContinueOnError)
|
||||||
fs.SetOutput(out)
|
fs.SetOutput(out)
|
||||||
@@ -263,24 +265,22 @@ func newCommandFlagSet(cmd command, out io.Writer) (*flag.FlagSet, *bool, *sayOp
|
|||||||
if cmd.register != nil {
|
if cmd.register != nil {
|
||||||
sayOpts = cmd.register(fs)
|
sayOpts = cmd.register(fs)
|
||||||
}
|
}
|
||||||
help := fs.Bool("help", false, "Hilfe zu diesem Befehl anzeigen")
|
help := fs.Bool("help", false, "show help for this command")
|
||||||
return fs, help, sayOpts
|
return fs, help, sayOpts
|
||||||
}
|
}
|
||||||
|
|
||||||
// runCommand führt einen benannten Subcommand aus. Implementiert: say
|
// runCommand executes a named subcommand. Flags may follow the text
|
||||||
// (Task 02/04) sowie mute/unmute/status/cancel als Daemon-Aufrufe (Task
|
// (parseInterspersed).
|
||||||
// 04); die restlichen sind Stubs bis zu ihren Tasks. Flags dürfen auch
|
|
||||||
// nach dem Text stehen (parseInterspersed).
|
|
||||||
func runCommand(cmd command, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
|
func runCommand(cmd command, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
|
||||||
fs, help, sayOpts := newCommandFlagSet(cmd, stderr)
|
fs, help, sayOpts := newCommandFlagSet(cmd, stderr)
|
||||||
positional, err := parseInterspersed(fs, args)
|
positional, err := parseInterspersed(fs, args)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, flag.ErrHelp) { // z. B. nacktes -h
|
if errors.Is(err, flag.ErrHelp) { // for example a bare -h
|
||||||
writeCommandHelp(cmd, stdout)
|
writeCommandHelp(cmd, stdout)
|
||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
// Die Fehlermeldung selbst hat der FlagSet bereits ausgegeben.
|
// The FlagSet has already printed the error itself.
|
||||||
fmt.Fprintf(stderr, "Hinweis: `talk %s --help` zeigt die Verwendung.\n", cmd.name)
|
fmt.Fprintf(stderr, "hint: `talk %s --help` shows the usage.\n", cmd.name)
|
||||||
return exitUsage
|
return exitUsage
|
||||||
}
|
}
|
||||||
if *help {
|
if *help {
|
||||||
@@ -290,17 +290,18 @@ func runCommand(cmd command, args []string, stdin io.Reader, stdout, stderr io.W
|
|||||||
if cmd.handler != nil {
|
if cmd.handler != nil {
|
||||||
return cmd.handler(positional, sayOpts, stdin, stdout, stderr)
|
return cmd.handler(positional, sayOpts, stdin, stdout, stderr)
|
||||||
}
|
}
|
||||||
return notImplemented(cmd.name, stderr)
|
fmt.Fprintf(stderr, "talk %s is not implemented yet\n", cmd.name)
|
||||||
|
return exitFailure
|
||||||
}
|
}
|
||||||
|
|
||||||
// runDefault behandelt Aufrufe ohne bekannten Subcommand: `talk "Text"`,
|
// runDefault handles calls without a known subcommand: `talk "text"`,
|
||||||
// `talk --version`, `talk --help` sowie say-Flags vor oder nach dem Text.
|
// `talk --version`, `talk --help`, and say flags before or after the text.
|
||||||
func runDefault(argv []string, stdin io.Reader, stdout, stderr io.Writer) int {
|
func runDefault(argv []string, stdin io.Reader, stdout, stderr io.Writer) int {
|
||||||
fs := flag.NewFlagSet("talk", flag.ContinueOnError)
|
fs := flag.NewFlagSet("talk", flag.ContinueOnError)
|
||||||
fs.SetOutput(stderr)
|
fs.SetOutput(stderr)
|
||||||
fs.Usage = func() {}
|
fs.Usage = func() {}
|
||||||
showVersion := fs.Bool("version", false, "Version anzeigen")
|
showVersion := fs.Bool("version", false, "show the version")
|
||||||
help := fs.Bool("help", false, "diese Hilfe anzeigen")
|
help := fs.Bool("help", false, "show this help")
|
||||||
sayOpts := addSayFlags(fs)
|
sayOpts := addSayFlags(fs)
|
||||||
|
|
||||||
positional, err := parseInterspersed(fs, argv)
|
positional, err := parseInterspersed(fs, argv)
|
||||||
@@ -309,7 +310,7 @@ func runDefault(argv []string, stdin io.Reader, stdout, stderr io.Writer) int {
|
|||||||
writeUsage(stdout)
|
writeUsage(stdout)
|
||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
fmt.Fprintln(stderr, "Hinweis: `talk --help` zeigt die Verwendung.")
|
fmt.Fprintln(stderr, "hint: `talk --help` shows the usage.")
|
||||||
return exitUsage
|
return exitUsage
|
||||||
}
|
}
|
||||||
if *showVersion {
|
if *showVersion {
|
||||||
@@ -323,50 +324,44 @@ func runDefault(argv []string, stdin io.Reader, stdout, stderr io.Writer) int {
|
|||||||
return runSay(positional, sayOpts, stdin, stdout, stderr)
|
return runSay(positional, sayOpts, stdin, stdout, stderr)
|
||||||
}
|
}
|
||||||
|
|
||||||
// versionString rendert die Versionsausgabe: `talk version <version>` plus
|
// versionString renders the version output: `talk version <version>` plus
|
||||||
// Commit-Hash in Klammern, falls per ldflags injiziert.
|
// the commit hash in parentheses when injected.
|
||||||
func versionString() string {
|
func versionString() string {
|
||||||
return "talk version " + buildVersion()
|
return "talk version " + buildVersion()
|
||||||
}
|
}
|
||||||
|
|
||||||
// notImplemented meldet einen noch nicht implementierten Befehl auf stderr
|
// writeUsage writes the overall help; the command list is generated from the
|
||||||
// und liefert den dafür vorgesehenen Exit-Code (non-zero).
|
// command table so help and dispatch never drift apart.
|
||||||
func notImplemented(name string, stderr io.Writer) int {
|
|
||||||
fmt.Fprintf(stderr, "talk %s is not implemented yet\n", name)
|
|
||||||
return exitFailure
|
|
||||||
}
|
|
||||||
|
|
||||||
// writeUsage schreibt die Gesamt-Hilfe; die Befehlsliste wird direkt aus der
|
|
||||||
// Befehlstabelle generiert, damit Hilfe und Dispatch nicht auseinanderlaufen.
|
|
||||||
func writeUsage(w io.Writer) {
|
func writeUsage(w io.Writer) {
|
||||||
fmt.Fprint(w, `talk — Sprach-Ausgaben für Skripte und KI-Agenten
|
fmt.Fprint(w, `talk: voice notifications for scripts and AI agents
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
talk [Flags] "Text" Text ansagen (Abkürzung für: talk say)
|
talk [flags] "text" speak a text (shorthand for: talk say)
|
||||||
talk <Befehl> [Flags] Befehl ausführen
|
talk <command> [flags] run a command
|
||||||
talk help [Befehl] Hilfe anzeigen
|
talk help [command] show help
|
||||||
|
|
||||||
Befehle:
|
Commands:
|
||||||
`)
|
`)
|
||||||
for _, cmd := range commands {
|
for _, cmd := range commands {
|
||||||
fmt.Fprintf(w, " %-8s %s\n", cmd.name, cmd.short)
|
fmt.Fprintf(w, " %-8s %s\n", cmd.name, cmd.short)
|
||||||
}
|
}
|
||||||
fmt.Fprint(w, `
|
fmt.Fprint(w, `
|
||||||
Flags:
|
Flags:
|
||||||
--version Version anzeigen
|
--version show the version
|
||||||
--help diese Hilfe anzeigen
|
--help show this help
|
||||||
|
|
||||||
Die Flags von say gelten auch für talk "Text"; Details: talk say --help
|
The say flags also apply to talk "text"; details: talk say --help
|
||||||
|
Getting started: talk doctor, then talk test, then talk setup.
|
||||||
`)
|
`)
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeCommandHelp schreibt die Hilfe eines einzelnen Befehls inkl. Flags.
|
// writeCommandHelp writes the help of a single command including its flags.
|
||||||
func writeCommandHelp(cmd command, w io.Writer) {
|
func writeCommandHelp(cmd command, w io.Writer) {
|
||||||
fmt.Fprintf(w, "Usage:\n talk %s", cmd.name)
|
fmt.Fprintf(w, "Usage:\n talk %s", cmd.name)
|
||||||
if cmd.args != "" {
|
if cmd.args != "" {
|
||||||
fmt.Fprintf(w, " %s", cmd.args)
|
fmt.Fprintf(w, " %s", cmd.args)
|
||||||
}
|
}
|
||||||
fmt.Fprintln(w, " [Flags]")
|
fmt.Fprintln(w, " [flags]")
|
||||||
fmt.Fprintln(w)
|
fmt.Fprintln(w)
|
||||||
if cmd.detail != "" {
|
if cmd.detail != "" {
|
||||||
fmt.Fprintf(w, "%s\n\n", cmd.detail)
|
fmt.Fprintf(w, "%s\n\n", cmd.detail)
|
||||||
@@ -374,7 +369,4 @@ func writeCommandHelp(cmd command, w io.Writer) {
|
|||||||
fmt.Fprintln(w, "Flags:")
|
fmt.Fprintln(w, "Flags:")
|
||||||
fs, _, _ := newCommandFlagSet(cmd, w)
|
fs, _, _ := newCommandFlagSet(cmd, w)
|
||||||
fs.PrintDefaults()
|
fs.PrintDefaults()
|
||||||
if cmd.handler == nil {
|
|
||||||
fmt.Fprintln(w, "\nStatus: noch nicht implementiert (WIP).")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
+40
-35
@@ -7,24 +7,24 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
// wantSubcommands ist die bindende CLI-Surface aus der Spec — bewusst als
|
// wantSubcommands is the CLI surface, deliberately tested as a hard-coded
|
||||||
// hartkodierte Liste getestet (nicht aus der Befehlstabelle abgeleitet),
|
// list (not derived from the command table) so the tests fire when table and
|
||||||
// damit die Tests anschlagen, wenn Tabelle und Spec auseinanderlaufen.
|
// documentation drift apart.
|
||||||
var wantSubcommands = []string{
|
var wantSubcommands = []string{
|
||||||
"say", "wrap", "mute", "unmute", "status", "cancel", "voices", "test", "doctor", "setup",
|
"say", "wrap", "mute", "unmute", "status", "daemon", "cancel", "uri", "voices", "test", "doctor", "setup",
|
||||||
}
|
}
|
||||||
|
|
||||||
// runCLI ist der Test-Einstieg in run mit leerem stdin (kein Text über
|
// runCLI is the test entry into run with empty stdin (no text via pipe), the
|
||||||
// Pipe) — dem üblichen Aufruf ohne Eingabe.
|
// usual call without input.
|
||||||
func runCLI(argv []string, stdout, stderr io.Writer) int {
|
func runCLI(argv []string, stdout, stderr io.Writer) int {
|
||||||
return run(argv, strings.NewReader(""), stdout, stderr)
|
return run(argv, strings.NewReader(""), stdout, stderr)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestHelpListetAlleSubcommands(t *testing.T) {
|
func TestHelpListsAllSubcommands(t *testing.T) {
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"--help"}, &out, &errBuf)
|
code := runCLI([]string{"--help"}, &out, &errBuf)
|
||||||
if code != exitOK {
|
if code != exitOK {
|
||||||
t.Fatalf("--help: Exit-Code = %d, want %d (stderr: %q)", code, exitOK, errBuf.String())
|
t.Fatalf("--help: exit code = %d, want %d (stderr: %q)", code, exitOK, errBuf.String())
|
||||||
}
|
}
|
||||||
lines := strings.Split(out.String(), "\n")
|
lines := strings.Split(out.String(), "\n")
|
||||||
for _, name := range wantSubcommands {
|
for _, name := range wantSubcommands {
|
||||||
@@ -36,7 +36,7 @@ func TestHelpListetAlleSubcommands(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !found {
|
if !found {
|
||||||
t.Errorf("--help listet Befehl %q nicht (Output: %q)", name, out.String())
|
t.Errorf("--help does not list command %q (output: %q)", name, out.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -45,14 +45,26 @@ func TestVersionDefault(t *testing.T) {
|
|||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"--version"}, &out, &errBuf)
|
code := runCLI([]string{"--version"}, &out, &errBuf)
|
||||||
if code != exitOK {
|
if code != exitOK {
|
||||||
t.Fatalf("--version: Exit-Code = %d, want %d", code, exitOK)
|
t.Fatalf("--version: exit code = %d, want %d", code, exitOK)
|
||||||
}
|
}
|
||||||
if got, want := out.String(), "talk version dev\n"; got != want {
|
if got, want := out.String(), "talk version dev\n"; got != want {
|
||||||
t.Errorf("--version Output = %q, want %q", got, want)
|
t.Errorf("--version output = %q, want %q", got, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestVersionStringMitCommit(t *testing.T) {
|
// TestVersionSubcommand: `talk version` prints the version instead of
|
||||||
|
// speaking the word.
|
||||||
|
func TestVersionSubcommand(t *testing.T) {
|
||||||
|
var out, errBuf bytes.Buffer
|
||||||
|
if code := runCLI([]string{"version"}, &out, &errBuf); code != exitOK {
|
||||||
|
t.Fatalf("version: exit code = %d, stderr %q", code, errBuf.String())
|
||||||
|
}
|
||||||
|
if got, want := out.String(), versionString()+"\n"; got != want {
|
||||||
|
t.Errorf("version output = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestVersionStringWithCommit(t *testing.T) {
|
||||||
oldCommit := commit
|
oldCommit := commit
|
||||||
commit = "c0ffee1"
|
commit = "c0ffee1"
|
||||||
defer func() { commit = oldCommit }()
|
defer func() { commit = oldCommit }()
|
||||||
@@ -62,70 +74,63 @@ func TestVersionStringMitCommit(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSayHelpZeigtFlags(t *testing.T) {
|
func TestSayHelpShowsFlags(t *testing.T) {
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"say", "--help"}, &out, &errBuf)
|
code := runCLI([]string{"say", "--help"}, &out, &errBuf)
|
||||||
if code != exitOK {
|
if code != exitOK {
|
||||||
t.Fatalf("talk say --help: Exit-Code = %d, want %d", code, exitOK)
|
t.Fatalf("talk say --help: exit code = %d, want %d", code, exitOK)
|
||||||
}
|
}
|
||||||
for _, f := range []string{"-wait", "-now", "-priority", "-voice", "-lang", "-provider"} {
|
for _, f := range []string{"-wait", "-now", "-priority", "-voice", "-lang", "-provider"} {
|
||||||
if !strings.Contains(out.String(), f) {
|
if !strings.Contains(out.String(), f) {
|
||||||
t.Errorf("talk say --help zeigt Flag %s nicht (Output: %q)", f, out.String())
|
t.Errorf("talk say --help does not show flag %s (output: %q)", f, out.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if strings.Contains(out.String(), "noch nicht implementiert") {
|
|
||||||
t.Errorf("talk say --help soll say nicht mehr als Stub markieren: %q", out.String())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestWrapHelpZeigtSayFlags: wrap erbt die say-Flags (mindestens --wait)
|
// TestWrapHelpShowsSayFlags: wrap inherits the say flags (at least --wait).
|
||||||
// und ist kein Stub mehr.
|
func TestWrapHelpShowsSayFlags(t *testing.T) {
|
||||||
func TestWrapHelpZeigtSayFlags(t *testing.T) {
|
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"wrap", "--help"}, &out, &errBuf)
|
code := runCLI([]string{"wrap", "--help"}, &out, &errBuf)
|
||||||
if code != exitOK {
|
if code != exitOK {
|
||||||
t.Fatalf("talk wrap --help: Exit-Code = %d, want %d (stderr: %q)", code, exitOK, errBuf.String())
|
t.Fatalf("talk wrap --help: exit code = %d, want %d (stderr: %q)", code, exitOK, errBuf.String())
|
||||||
}
|
}
|
||||||
for _, f := range []string{"-wait", "-provider"} {
|
for _, f := range []string{"-wait", "-provider"} {
|
||||||
if !strings.Contains(out.String(), f) {
|
if !strings.Contains(out.String(), f) {
|
||||||
t.Errorf("talk wrap --help zeigt Flag %s nicht (Output: %q)", f, out.String())
|
t.Errorf("talk wrap --help does not show flag %s (output: %q)", f, out.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if strings.Contains(out.String(), "noch nicht implementiert") {
|
|
||||||
t.Errorf("talk wrap --help soll wrap nicht als Stub markieren: %q", out.String())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestHelpSubcommand(t *testing.T) {
|
func TestHelpSubcommand(t *testing.T) {
|
||||||
t.Run("ohne Argument", func(t *testing.T) {
|
t.Run("without argument", func(t *testing.T) {
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
if code := runCLI([]string{"help"}, &out, &errBuf); code != exitOK {
|
if code := runCLI([]string{"help"}, &out, &errBuf); code != exitOK {
|
||||||
t.Fatalf("talk help: Exit-Code = %d, want %d", code, exitOK)
|
t.Fatalf("talk help: exit code = %d, want %d", code, exitOK)
|
||||||
}
|
}
|
||||||
for _, name := range wantSubcommands {
|
for _, name := range wantSubcommands {
|
||||||
if !strings.Contains(out.String(), name) {
|
if !strings.Contains(out.String(), name) {
|
||||||
t.Errorf("talk help listet %q nicht", name)
|
t.Errorf("talk help does not list %q", name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
t.Run("mit Befehl", func(t *testing.T) {
|
t.Run("with command", func(t *testing.T) {
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
if code := runCLI([]string{"help", "mute"}, &out, &errBuf); code != exitOK {
|
if code := runCLI([]string{"help", "mute"}, &out, &errBuf); code != exitOK {
|
||||||
t.Fatalf("talk help mute: Exit-Code = %d, want %d", code, exitOK)
|
t.Fatalf("talk help mute: exit code = %d, want %d", code, exitOK)
|
||||||
}
|
}
|
||||||
if !strings.Contains(out.String(), "talk mute") {
|
if !strings.Contains(out.String(), "talk mute") {
|
||||||
t.Errorf("talk help mute zeigt Usage von mute nicht: %q", out.String())
|
t.Errorf("talk help mute does not show mute's usage: %q", out.String())
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestUnbekanntesFlag(t *testing.T) {
|
func TestUnknownFlag(t *testing.T) {
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"--bogus"}, &out, &errBuf)
|
code := runCLI([]string{"--bogus"}, &out, &errBuf)
|
||||||
if code != exitUsage {
|
if code != exitUsage {
|
||||||
t.Fatalf("talk --bogus: Exit-Code = %d, want %d", code, exitUsage)
|
t.Fatalf("talk --bogus: exit code = %d, want %d", code, exitUsage)
|
||||||
}
|
}
|
||||||
if !strings.Contains(errBuf.String(), "bogus") {
|
if !strings.Contains(errBuf.String(), "bogus") {
|
||||||
t.Errorf("talk --bogus: Fehlermeldung fehlt auf stderr: %q", errBuf.String())
|
t.Errorf("talk --bogus: error message missing on stderr: %q", errBuf.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+53
-54
@@ -12,26 +12,26 @@ import (
|
|||||||
"code.m3ta.dev/m3tam3re/talk/internal/queue"
|
"code.m3ta.dev/m3tam3re/talk/internal/queue"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Die Steuer-Befehle (Task 04) sind Daemon-Aufrufe mit plain Output:
|
// The control commands are daemon calls with plain output: stdout carries a
|
||||||
// stdout führt eine maschinenlesbare Zeile (muted/unmuted, cancelled: N
|
// machine-readable line (muted/unmuted, cancelled: N, or the status block),
|
||||||
// bzw. den Status-Block), stderr menschliche Hinweise.
|
// stderr human notes. They deliberately do NOT start the daemon (only
|
||||||
|
// speaking does): muting needs no running process, and status should show
|
||||||
|
// reality rather than change it.
|
||||||
|
|
||||||
// runMute implementiert `talk mute`: POST /mute an den Daemon. Ist kein
|
// runMute implements `talk mute`: POST /mute to the daemon. When no daemon
|
||||||
// Daemon erreichbar, wird die Mute-Datei direkt geschrieben — dieselbe
|
// is reachable, the mute file is written directly; it is the same
|
||||||
// Persistenz-Quelle, die der Daemon bei jeder Ansage neu liest; der
|
// persistence the daemon re-reads on every announcement, so the state takes
|
||||||
// Zustand greift also auch offline und überlebt Daemon-Restarts. Die
|
// effect offline too and survives daemon restarts.
|
||||||
// Steuer-Befehle starten den Daemon bewusst NICHT (nur Sprechen tut das):
|
|
||||||
// Stummschalten braucht keinen laufenden Prozess.
|
|
||||||
func runMute(args []string, opts *sayOptions, stdin io.Reader, stdout, stderr io.Writer) int {
|
func runMute(args []string, opts *sayOptions, stdin io.Reader, stdout, stderr io.Writer) int {
|
||||||
return setMute(true, stdout, stderr)
|
return setMute(true, stdout, stderr)
|
||||||
}
|
}
|
||||||
|
|
||||||
// runUnmute implementiert `talk unmute` (analog zu runMute).
|
// runUnmute implements `talk unmute` (like runMute).
|
||||||
func runUnmute(args []string, opts *sayOptions, stdin io.Reader, stdout, stderr io.Writer) int {
|
func runUnmute(args []string, opts *sayOptions, stdin io.Reader, stdout, stderr io.Writer) int {
|
||||||
return setMute(false, stdout, stderr)
|
return setMute(false, stdout, stderr)
|
||||||
}
|
}
|
||||||
|
|
||||||
// setMute ist der gemeinsame Kern von mute/unmute.
|
// setMute is the shared core of mute/unmute.
|
||||||
func setMute(muted bool, stdout, stderr io.Writer) int {
|
func setMute(muted bool, stdout, stderr io.Writer) int {
|
||||||
cfg, err := config.Load(config.Options{Getenv: getenv})
|
cfg, err := config.Load(config.Options{Getenv: getenv})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -41,29 +41,29 @@ func setMute(muted bool, stdout, stderr io.Writer) int {
|
|||||||
client := api.NewClient(cfg.Server.Port)
|
client := api.NewClient(cfg.Server.Port)
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), daemonCallTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), daemonCallTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
if err := client.SetMute(ctx, muted); err == nil {
|
callErr := client.SetMute(ctx, muted)
|
||||||
|
if callErr == nil {
|
||||||
printMuteState(muted, stdout)
|
printMuteState(muted, stdout)
|
||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
|
|
||||||
// Daemon-Aufruf fehlgeschlagen (meist: nicht erreichbar): Datei direkt
|
// Daemon call failed (usually: not running): write the file directly;
|
||||||
// schreiben — der Daemon (und der Degraded Mode) liest sie bei jeder
|
// the daemon (and the direct path) re-read it on every announcement.
|
||||||
// Ansage neu.
|
fmt.Fprintf(stderr, "talk: no daemon (%v); writing the mute file directly\n", callErr)
|
||||||
fmt.Fprintf(stderr, "talk: Daemon-Aufruf fehlgeschlagen (%v) — Mute-Datei wird direkt geschrieben\n", err)
|
|
||||||
dir, err := config.Dir(getenv)
|
dir, err := config.Dir(getenv)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(stderr, "talk: %v\n", err)
|
fmt.Fprintf(stderr, "talk: %v\n", err)
|
||||||
return exitFailure
|
return exitFailure
|
||||||
}
|
}
|
||||||
if err := (queue.MuteStore{Path: filepath.Join(dir, queue.MuteFileName)}).Set(muted); err != nil {
|
if err := (queue.MuteStore{Path: filepath.Join(dir, queue.MuteFileName)}).Set(muted); err != nil {
|
||||||
fmt.Fprintf(stderr, "talk: Mute-Datei schreiben: %v\n", err)
|
fmt.Fprintf(stderr, "talk: writing the mute file: %v\n", err)
|
||||||
return exitFailure
|
return exitFailure
|
||||||
}
|
}
|
||||||
printMuteState(muted, stdout)
|
printMuteState(muted, stdout)
|
||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
|
|
||||||
// printMuteState schreibt den Zustand als plain Token auf stdout.
|
// printMuteState writes the state as a plain token to stdout.
|
||||||
func printMuteState(muted bool, stdout io.Writer) {
|
func printMuteState(muted bool, stdout io.Writer) {
|
||||||
if muted {
|
if muted {
|
||||||
fmt.Fprintln(stdout, "muted")
|
fmt.Fprintln(stdout, "muted")
|
||||||
@@ -72,11 +72,10 @@ func printMuteState(muted bool, stdout io.Writer) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// runStatus implementiert `talk status`: plain Block aus GET /status —
|
// runStatus implements `talk status`: a plain block from GET /status (daemon
|
||||||
// Daemon-Adresse + Version, Queue-Länge, aktuelles Item, Mute-State,
|
// address + version, queue length, current item, mute state, active
|
||||||
// aktiver Provider, Gesetz-State (Rate-Limit, Ruhezeit). Läuft kein Daemon,
|
// provider, laws). When no daemon runs, status says exactly that (exit 1)
|
||||||
// sagt status genau das (Exit 1) und startet ihn nicht — status soll die
|
// without starting one.
|
||||||
// Wirklichkeit zeigen, nicht verändern.
|
|
||||||
func runStatus(args []string, opts *sayOptions, stdin io.Reader, stdout, stderr io.Writer) int {
|
func runStatus(args []string, opts *sayOptions, stdin io.Reader, stdout, stderr io.Writer) int {
|
||||||
cfg, err := config.Load(config.Options{Getenv: getenv})
|
cfg, err := config.Load(config.Options{Getenv: getenv})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -88,44 +87,44 @@ func runStatus(args []string, opts *sayOptions, stdin io.Reader, stdout, stderr
|
|||||||
defer cancel()
|
defer cancel()
|
||||||
st, err := client.Status(ctx)
|
st, err := client.Status(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(stdout, "daemon: läuft nicht (%s)\n", client.BaseURL)
|
fmt.Fprintf(stdout, "daemon: not running (%s)\n", client.BaseURL)
|
||||||
fmt.Fprintln(stderr, "talk: kein Daemon — er startet beim nächsten Sprechbefehl von selbst (oder: talk daemon start)")
|
fmt.Fprintln(stderr, "talk: no daemon; it starts by itself on the next speak command (or: talk daemon start)")
|
||||||
return exitFailure
|
return exitFailure
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Fprintf(stdout, "daemon: %s (version %s)\n", client.BaseURL, st.Version)
|
fmt.Fprintf(stdout, "daemon: %s (version %s)\n", client.BaseURL, st.Version)
|
||||||
fmt.Fprintf(stdout, "queue: %d\n", st.Queue)
|
fmt.Fprintf(stdout, "queue: %d\n", st.Queue)
|
||||||
if st.Current != nil {
|
if st.Current != nil {
|
||||||
fmt.Fprintf(stdout, "current: %s %q (Priorität %s)\n", st.Current.ID, st.Current.Text, st.Current.Priority)
|
fmt.Fprintf(stdout, "current: %s %q (priority %s)\n", st.Current.ID, st.Current.Text, st.Current.Priority)
|
||||||
} else {
|
} else {
|
||||||
fmt.Fprintln(stdout, "current: –")
|
fmt.Fprintln(stdout, "current: -")
|
||||||
}
|
}
|
||||||
muteState := "aus"
|
muteState := "off"
|
||||||
if st.Muted {
|
if st.Muted {
|
||||||
muteState = "an"
|
muteState = "on"
|
||||||
}
|
}
|
||||||
fmt.Fprintf(stdout, "mute: %s\n", muteState)
|
fmt.Fprintf(stdout, "mute: %s\n", muteState)
|
||||||
fmt.Fprintf(stdout, "provider: %s\n", st.Provider)
|
fmt.Fprintf(stdout, "provider: %s\n", st.Provider)
|
||||||
printLawState(stdout, st)
|
printLawState(stdout, st)
|
||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
|
|
||||||
// printLawState schreibt den Gesetz-State (Task 05) aus GET /status:
|
// printLawState writes the law state from GET /status: rate limit with
|
||||||
// Rate-Limit mit Burst-Recht und nächstem Slot sowie das Ruhezeit-Fenster.
|
// burst rights and next slot, quiet window, length and age limits.
|
||||||
func printLawState(stdout io.Writer, st *api.StatusResponse) {
|
func printLawState(stdout io.Writer, st *api.StatusResponse) {
|
||||||
if st.RateLimit != nil {
|
if st.RateLimit != nil {
|
||||||
interval := st.RateLimit.Interval
|
interval := st.RateLimit.Interval
|
||||||
if interval == "0s" {
|
if interval == "0s" {
|
||||||
interval = "aus (unbegrenzt)"
|
interval = "off (unlimited)"
|
||||||
}
|
}
|
||||||
burst := "verboten"
|
burst := "not allowed"
|
||||||
if st.RateLimit.AllowHighBurst {
|
if st.RateLimit.AllowHighBurst {
|
||||||
burst = "erlaubt"
|
burst = "allowed"
|
||||||
}
|
}
|
||||||
line := fmt.Sprintf("rate-limit: %s (high-burst %s)", interval, burst)
|
line := fmt.Sprintf("rate-limit: %s (high burst %s)", interval, burst)
|
||||||
if st.RateLimit.NextSlot != nil {
|
if st.RateLimit.NextSlot != nil {
|
||||||
if ts, err := time.Parse(time.RFC3339, *st.RateLimit.NextSlot); err == nil {
|
if ts, err := time.Parse(time.RFC3339, *st.RateLimit.NextSlot); err == nil {
|
||||||
line += fmt.Sprintf(", nächster slot %s", ts.Format("15:04:05"))
|
line += fmt.Sprintf(", next slot %s", ts.Format("15:04:05"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fmt.Fprintln(stdout, line)
|
fmt.Fprintln(stdout, line)
|
||||||
@@ -133,35 +132,35 @@ func printLawState(stdout io.Writer, st *api.StatusResponse) {
|
|||||||
if st.QuietHours != nil {
|
if st.QuietHours != nil {
|
||||||
window := st.QuietHours.Window
|
window := st.QuietHours.Window
|
||||||
if window == "" {
|
if window == "" {
|
||||||
window = "aus"
|
window = "off"
|
||||||
}
|
}
|
||||||
state := "inaktiv"
|
state := "inactive"
|
||||||
if st.QuietHours.Active {
|
if st.QuietHours.Active {
|
||||||
state = "aktiv"
|
state = "active"
|
||||||
if st.QuietHours.Until != nil {
|
if st.QuietHours.Until != nil {
|
||||||
if ts, err := time.Parse(time.RFC3339, *st.QuietHours.Until); err == nil {
|
if ts, err := time.Parse(time.RFC3339, *st.QuietHours.Until); err == nil {
|
||||||
state += " bis " + ts.Format("15:04")
|
state += " until " + ts.Format("15:04")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fmt.Fprintf(stdout, "ruhezeit: %s (modus %s, %s)\n", window, st.QuietHours.Mode, state)
|
fmt.Fprintf(stdout, "quiet-hours: %s (mode %s, %s)\n", window, st.QuietHours.Mode, state)
|
||||||
}
|
}
|
||||||
if st.Limits != nil {
|
if st.Limits != nil {
|
||||||
text := fmt.Sprintf("max. %d Zeichen", st.Limits.MaxText)
|
text := fmt.Sprintf("max %d characters", st.Limits.MaxText)
|
||||||
if st.Limits.MaxText == 0 {
|
if st.Limits.MaxText == 0 {
|
||||||
text = "Länge unbegrenzt"
|
text = "unlimited length"
|
||||||
}
|
}
|
||||||
age := "max. Wartezeit " + st.Limits.MaxAge
|
age := "max wait " + st.Limits.MaxAge
|
||||||
if st.Limits.MaxAge == "0s" {
|
if st.Limits.MaxAge == "0s" {
|
||||||
age = "Wartezeit unbegrenzt"
|
age = "unlimited wait"
|
||||||
}
|
}
|
||||||
fmt.Fprintf(stdout, "limits: %s, %s\n", text, age)
|
fmt.Fprintf(stdout, "limits: %s, %s\n", text, age)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// runCancel implementiert `talk cancel`: POST /cancel — bricht die laufende
|
// runCancel implements `talk cancel`: POST /cancel aborts the playing
|
||||||
// Ansage ab und leert die Queue; stdout meldet die Zahl der abgebrochenen
|
// announcement and empties the queue; stdout reports the number of cancelled
|
||||||
// Ansagen. Ohne Daemon gibt es nichts, was talk abbrechen könnte.
|
// announcements. Without a daemon there is nothing to cancel.
|
||||||
func runCancel(args []string, opts *sayOptions, stdin io.Reader, stdout, stderr io.Writer) int {
|
func runCancel(args []string, opts *sayOptions, stdin io.Reader, stdout, stderr io.Writer) int {
|
||||||
cfg, err := config.Load(config.Options{Getenv: getenv})
|
cfg, err := config.Load(config.Options{Getenv: getenv})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -173,7 +172,7 @@ func runCancel(args []string, opts *sayOptions, stdin io.Reader, stdout, stderr
|
|||||||
defer cancel()
|
defer cancel()
|
||||||
n, err := client.Cancel(ctx)
|
n, err := client.Cancel(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(stderr, "talk: Daemon nicht erreichbar unter %s — nichts zu abbrechen\n", client.BaseURL)
|
fmt.Fprintf(stderr, "talk: no daemon at %s; nothing to cancel\n", client.BaseURL)
|
||||||
return exitFailure
|
return exitFailure
|
||||||
}
|
}
|
||||||
fmt.Fprintf(stdout, "cancelled: %d\n", n)
|
fmt.Fprintf(stdout, "cancelled: %d\n", n)
|
||||||
|
|||||||
+44
-45
@@ -10,111 +10,110 @@ import (
|
|||||||
"code.m3ta.dev/m3tam3re/talk/internal/queue"
|
"code.m3ta.dev/m3tam3re/talk/internal/queue"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Diese Tests decken die Steuer-Befehle ohne Daemon ab (in-process über
|
// These tests cover the control commands without a daemon (in-process via
|
||||||
// die run-Seam; TALK_PORT=1 aus der setGetenv-Grundausstattung → Daemon-
|
// the run seam; TALK_PORT=1 from the setGetenv base makes daemon detection
|
||||||
// Erkennung schlägt sofort fehl). Das Verhalten MIT Daemon testen die
|
// fail immediately). Behaviour WITH a daemon is covered by the process
|
||||||
// Prozessgrenzen-Tests in /test.
|
// boundary tests in /test.
|
||||||
|
|
||||||
// TestStatusOhneDaemon: `talk status` ohne Daemon ist ein klarer Fehler
|
// TestStatusWithoutDaemon: `talk status` without a daemon is a clear error
|
||||||
// (Exit 1) mit Hinweis auf stderr — und stdout nennt den Zustand trotzdem
|
// (exit 1) with a note on stderr, and stdout still names the state as a
|
||||||
// als Status-Zeile, damit der Block nie leer bleibt. Status startet den
|
// status line so the block is never empty. status does not start the
|
||||||
// Daemon nicht.
|
// daemon.
|
||||||
func TestStatusOhneDaemon(t *testing.T) {
|
func TestStatusWithoutDaemon(t *testing.T) {
|
||||||
setGetenv(t, nil)
|
setGetenv(t, nil)
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"status"}, &out, &errBuf)
|
code := runCLI([]string{"status"}, &out, &errBuf)
|
||||||
if code != exitFailure {
|
if code != exitFailure {
|
||||||
t.Fatalf("talk status ohne Daemon: Exit-Code = %d, want %d", code, exitFailure)
|
t.Fatalf("talk status without daemon: exit code = %d, want %d", code, exitFailure)
|
||||||
}
|
}
|
||||||
if !strings.Contains(errBuf.String(), "kein Daemon") {
|
if !strings.Contains(errBuf.String(), "no daemon") {
|
||||||
t.Errorf("stderr = %q, will Hinweis auf fehlenden Daemon", errBuf.String())
|
t.Errorf("stderr = %q, want a note about the missing daemon", errBuf.String())
|
||||||
}
|
}
|
||||||
if !strings.HasPrefix(out.String(), "daemon: läuft nicht") {
|
if !strings.HasPrefix(out.String(), "daemon: not running") {
|
||||||
t.Errorf("stdout = %q, will Status-Zeile „läuft nicht“", out.String())
|
t.Errorf("stdout = %q, want the status line \"not running\"", out.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestCancelOhneDaemon: ohne Daemon gibt es nichts zu abbrechen — klarer
|
// TestCancelWithoutDaemon: without a daemon there is nothing to cancel; a
|
||||||
// Fehler.
|
// clear error.
|
||||||
func TestCancelOhneDaemon(t *testing.T) {
|
func TestCancelWithoutDaemon(t *testing.T) {
|
||||||
setGetenv(t, nil)
|
setGetenv(t, nil)
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"cancel"}, &out, &errBuf)
|
code := runCLI([]string{"cancel"}, &out, &errBuf)
|
||||||
if code != exitFailure {
|
if code != exitFailure {
|
||||||
t.Fatalf("talk cancel ohne Daemon: Exit-Code = %d, want %d", code, exitFailure)
|
t.Fatalf("talk cancel without daemon: exit code = %d, want %d", code, exitFailure)
|
||||||
}
|
}
|
||||||
if !strings.Contains(errBuf.String(), "nichts zu abbrechen") {
|
if !strings.Contains(errBuf.String(), "nothing to cancel") {
|
||||||
t.Errorf("stderr = %q, will Hinweis", errBuf.String())
|
t.Errorf("stderr = %q, want a note", errBuf.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestMuteOhneDaemonSchreibtDatei: `talk mute` ohne Daemon schreibt die
|
// TestMuteWithoutDaemonWritesFile: `talk mute` without a daemon writes the
|
||||||
// Mute-Datei direkt — und genau diese Datei respektiert der Degraded Mode
|
// mute file directly, and the direct path of say honours exactly that file.
|
||||||
// von say anschließend.
|
func TestMuteWithoutDaemonWritesFile(t *testing.T) {
|
||||||
func TestMuteOhneDaemonSchreibtDatei(t *testing.T) {
|
|
||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
setGetenv(t, map[string]string{"XDG_CONFIG_HOME": root})
|
setGetenv(t, map[string]string{"XDG_CONFIG_HOME": root})
|
||||||
mutePath := filepath.Join(root, "talk", queue.MuteFileName)
|
mutePath := filepath.Join(root, "talk", queue.MuteFileName)
|
||||||
|
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
if code := runCLI([]string{"mute"}, &out, &errBuf); code != exitOK {
|
if code := runCLI([]string{"mute"}, &out, &errBuf); code != exitOK {
|
||||||
t.Fatalf("talk mute ohne Daemon: Exit-Code = %d, want %d (stderr: %q)", code, exitOK, errBuf.String())
|
t.Fatalf("talk mute without daemon: exit code = %d, want %d (stderr: %q)", code, exitOK, errBuf.String())
|
||||||
}
|
}
|
||||||
if got := out.String(); got != "muted\n" {
|
if got := out.String(); got != "muted\n" {
|
||||||
t.Errorf("talk mute stdout = %q, want %q", got, "muted\n")
|
t.Errorf("talk mute stdout = %q, want %q", got, "muted\n")
|
||||||
}
|
}
|
||||||
if !strings.Contains(errBuf.String(), "direkt") {
|
if !strings.Contains(errBuf.String(), "directly") {
|
||||||
t.Errorf("stderr = %q, will Hinweis auf direkten Datei-Schreib", errBuf.String())
|
t.Errorf("stderr = %q, want a note about writing the file directly", errBuf.String())
|
||||||
}
|
}
|
||||||
b, err := os.ReadFile(mutePath)
|
b, err := os.ReadFile(mutePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Mute-Datei fehlt: %v", err)
|
t.Fatalf("mute file missing: %v", err)
|
||||||
}
|
}
|
||||||
if strings.TrimSpace(string(b)) != "true" {
|
if strings.TrimSpace(string(b)) != "true" {
|
||||||
t.Errorf("Mute-Datei = %q, want true", b)
|
t.Errorf("mute file = %q, want true", b)
|
||||||
}
|
}
|
||||||
|
|
||||||
// say im Degraded Mode respektiert dieselbe Datei (tonlos verworfen,
|
// say on the direct path honours the same file (discarded silently,
|
||||||
// ohne irgendeinen Provider zu brauchen).
|
// without needing any provider).
|
||||||
out.Reset()
|
out.Reset()
|
||||||
errBuf.Reset()
|
errBuf.Reset()
|
||||||
if code := runCLI([]string{"say", "stille bitte"}, &out, &errBuf); code != exitOK {
|
if code := runCLI([]string{"say", "quiet please"}, &out, &errBuf); code != exitOK {
|
||||||
t.Fatalf("talk say (mute an): Exit-Code = %d, want %d (stderr: %q)", code, exitOK, errBuf.String())
|
t.Fatalf("talk say (muted): exit code = %d, want %d (stderr: %q)", code, exitOK, errBuf.String())
|
||||||
}
|
}
|
||||||
if got := out.String(); got != "muted\n" {
|
if got := out.String(); got != "muted\n" {
|
||||||
t.Errorf("talk say (mute an) stdout = %q, want %q", got, "muted\n")
|
t.Errorf("talk say (muted) stdout = %q, want %q", got, "muted\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
// unmute hebt es auf (Datei false).
|
// unmute lifts it (file false).
|
||||||
out.Reset()
|
out.Reset()
|
||||||
errBuf.Reset()
|
errBuf.Reset()
|
||||||
if code := runCLI([]string{"unmute"}, &out, &errBuf); code != exitOK {
|
if code := runCLI([]string{"unmute"}, &out, &errBuf); code != exitOK {
|
||||||
t.Fatalf("talk unmute: Exit-Code = %d (stderr: %q)", code, errBuf.String())
|
t.Fatalf("talk unmute: exit code = %d (stderr: %q)", code, errBuf.String())
|
||||||
}
|
}
|
||||||
if got := out.String(); got != "unmuted\n" {
|
if got := out.String(); got != "unmuted\n" {
|
||||||
t.Errorf("talk unmute stdout = %q, want %q", got, "unmuted\n")
|
t.Errorf("talk unmute stdout = %q, want %q", got, "unmuted\n")
|
||||||
}
|
}
|
||||||
b, err = os.ReadFile(mutePath)
|
b, err = os.ReadFile(mutePath)
|
||||||
if err != nil || strings.TrimSpace(string(b)) != "false" {
|
if err != nil || strings.TrimSpace(string(b)) != "false" {
|
||||||
t.Errorf("Mute-Datei nach unmute = %q (%v), want false", b, err)
|
t.Errorf("mute file after unmute = %q (%v), want false", b, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSayOhneConfigDir: Degraded Mode ohne Config-Dir (kein HOME) spielt
|
// TestSayWithoutConfigDir: the direct path without a config directory (no
|
||||||
// weiter statt zu scheitern — Best-effort ohne Lock und Mute.
|
// HOME) keeps speaking instead of failing; best effort without mute.
|
||||||
func TestSayOhneConfigDir(t *testing.T) {
|
func TestSayWithoutConfigDir(t *testing.T) {
|
||||||
seen := withFakeEspeak(t)
|
seen := withFakeEspeak(t)
|
||||||
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
||||||
|
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"Hallo"}, &out, &errBuf)
|
code := runCLI([]string{"Hello"}, &out, &errBuf)
|
||||||
if code != exitOK {
|
if code != exitOK {
|
||||||
t.Fatalf("talk ohne HOME: Exit-Code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
t.Fatalf("talk without HOME: exit code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
||||||
}
|
}
|
||||||
if _, err := os.Stat(seen); err != nil {
|
if _, err := os.Stat(seen); err != nil {
|
||||||
t.Errorf("fake espeak nicht gerufen: %v", err)
|
t.Errorf("fake espeak not called: %v", err)
|
||||||
}
|
}
|
||||||
if !strings.Contains(errBuf.String(), "spreche direkt") {
|
if !strings.Contains(errBuf.String(), "speaking directly") {
|
||||||
t.Errorf("stderr = %q, will Degraded-Hinweis", errBuf.String())
|
t.Errorf("stderr = %q, want the direct-path note", errBuf.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+57
-59
@@ -15,21 +15,21 @@ import (
|
|||||||
"code.m3ta.dev/m3tam3re/talk/internal/queue"
|
"code.m3ta.dev/m3tam3re/talk/internal/queue"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Zeit-Budgets der Daemon-Kommunikation. Die Daemon-Erkennung (GET /status)
|
// Time budgets for talking to the daemon. Detection (GET /status) is short:
|
||||||
// hält kurz: Auf einem freien Port wird die Verbindung sofort abgelehnt;
|
// on a free port the connection is refused immediately; the budget only
|
||||||
// das Budget deckt nur unglückliche Fälle (gefilterte Ports), damit talk
|
// covers unlucky cases (filtered ports) so talk never dawdles without a
|
||||||
// ohne Daemon nicht spürbar trödelt.
|
// daemon.
|
||||||
const (
|
const (
|
||||||
daemonProbeTimeout = time.Second // Daemon-Erkennung (GET /status)
|
daemonProbeTimeout = time.Second // daemon detection (GET /status)
|
||||||
daemonCallTimeout = 5 * time.Second // einzelne Daemon-Aufrufe
|
daemonCallTimeout = 5 * time.Second // individual daemon calls
|
||||||
daemonStartTimeout = 5 * time.Second // Autostart: so lange auf /status warten
|
daemonStartTimeout = 5 * time.Second // autostart: how long to wait for /status
|
||||||
daemonStartPoll = 50 * time.Millisecond // Autostart-Poll-Frequenz
|
daemonStartPoll = 50 * time.Millisecond // autostart poll interval
|
||||||
waitPollInterval = 100 * time.Millisecond // --wait-Poll-Frequenz
|
waitPollInterval = 100 * time.Millisecond // --wait poll interval
|
||||||
)
|
)
|
||||||
|
|
||||||
// daemonAlive meldet, ob unter dem Client ein Daemon antwortet (GET /status
|
// daemonAlive reports whether a daemon answers under the client (GET
|
||||||
// mit 200). Jeder Fehler — Verbindung abgelehnt, Timeout, fremder Dienst
|
// /status with 200). Every error (connection refused, timeout, a foreign
|
||||||
// mit anderem Status — zählt als „kein Daemon".
|
// service with another status) counts as "no daemon".
|
||||||
func daemonAlive(client *api.Client, timeout time.Duration) bool {
|
func daemonAlive(client *api.Client, timeout time.Duration) bool {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
@@ -37,11 +37,11 @@ func daemonAlive(client *api.Client, timeout time.Duration) bool {
|
|||||||
return err == nil
|
return err == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ensureDaemon liefert einen Client zu einem laufenden Daemon und startet
|
// ensureDaemon returns a client to a running daemon, starting one if needed
|
||||||
// ihn bei Bedarf selbst (daemon.autostart, Default an). ok=false heißt:
|
// (daemon.autostart, default on). ok=false means: no daemon reachable and
|
||||||
// kein Daemon erreichbar und keiner startbar (Autostart aus, Start
|
// none startable (autostart off, start failed); the caller then speaks
|
||||||
// gescheitert) — der Aufrufer spricht dann direkt. Gründe stehen auf
|
// directly. Reasons go to stderr; the daemon itself logs to daemon.log in
|
||||||
// stderr; der Daemon selbst protokolliert in daemon.log im Config-Dir.
|
// the config directory.
|
||||||
func ensureDaemon(cfg config.Config, stderr io.Writer) (client *api.Client, ok bool) {
|
func ensureDaemon(cfg config.Config, stderr io.Writer) (client *api.Client, ok bool) {
|
||||||
client = api.NewClient(cfg.Server.Port)
|
client = api.NewClient(cfg.Server.Port)
|
||||||
if daemonAlive(client, daemonProbeTimeout) {
|
if daemonAlive(client, daemonProbeTimeout) {
|
||||||
@@ -53,14 +53,14 @@ func ensureDaemon(cfg config.Config, stderr io.Writer) (client *api.Client, ok b
|
|||||||
return client, startDaemon(client, stderr)
|
return client, startDaemon(client, stderr)
|
||||||
}
|
}
|
||||||
|
|
||||||
// startDaemon startet den Daemon im Hintergrund (dasselbe Binary mit
|
// startDaemon starts the daemon in the background (the same binary with
|
||||||
// `daemon run`) und wartet, bis er auf /status antwortet. Endet das Kind
|
// `daemon run`) and waits until it answers on /status. If the child exits
|
||||||
// vorher (typisch: Port belegt, weil ein paralleler talk-Aufruf schneller
|
// first (typically: port taken because a parallel talk call was faster), we
|
||||||
// war), wird noch einmal geprüft — der Daemon des anderen zählt genauso.
|
// probe once more: the other call's daemon counts just as well.
|
||||||
func startDaemon(client *api.Client, stderr io.Writer) bool {
|
func startDaemon(client *api.Client, stderr io.Writer) bool {
|
||||||
exe, err := os.Executable()
|
exe, err := os.Executable()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(stderr, "talk: eigenes Binary nicht bestimmbar — Daemon-Start ausgesetzt (%v)\n", err)
|
fmt.Fprintf(stderr, "talk: cannot determine own binary; daemon start skipped (%v)\n", err)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
logPath := ""
|
logPath := ""
|
||||||
@@ -77,50 +77,49 @@ func startDaemon(client *api.Client, stderr io.Writer) bool {
|
|||||||
}
|
}
|
||||||
logHint := ""
|
logHint := ""
|
||||||
if logPath != "" {
|
if logPath != "" {
|
||||||
logHint = " (Log: " + logPath + ")"
|
logHint = " (log: " + logPath + ")"
|
||||||
}
|
}
|
||||||
deadline := time.Now().Add(daemonStartTimeout)
|
deadline := time.Now().Add(daemonStartTimeout)
|
||||||
for {
|
for {
|
||||||
if daemonAlive(client, daemonStartPoll*4) {
|
if daemonAlive(client, daemonStartPoll*4) {
|
||||||
fmt.Fprintf(stderr, "talk: Daemon gestartet unter %s%s\n", client.BaseURL, logHint)
|
fmt.Fprintf(stderr, "talk: daemon started at %s%s\n", client.BaseURL, logHint)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
select {
|
select {
|
||||||
case err := <-exited:
|
case err := <-exited:
|
||||||
if daemonAlive(client, daemonProbeTimeout) {
|
if daemonAlive(client, daemonProbeTimeout) {
|
||||||
return true // ein anderer Aufruf hat den Daemon gestartet
|
return true // another call started the daemon
|
||||||
}
|
}
|
||||||
fmt.Fprintf(stderr, "talk: Daemon-Start fehlgeschlagen (%v)%s\n", exitReason(err), logHint)
|
fmt.Fprintf(stderr, "talk: daemon start failed (%s)%s\n", exitReason(err), logHint)
|
||||||
return false
|
return false
|
||||||
case <-time.After(daemonStartPoll):
|
case <-time.After(daemonStartPoll):
|
||||||
}
|
}
|
||||||
if time.Now().After(deadline) {
|
if time.Now().After(deadline) {
|
||||||
fmt.Fprintf(stderr, "talk: Daemon antwortet nicht binnen %s%s\n", daemonStartTimeout, logHint)
|
fmt.Fprintf(stderr, "talk: daemon not answering within %s%s\n", daemonStartTimeout, logHint)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// exitReason macht das Wait-Ergebnis eines beendeten Kindes lesbar.
|
// exitReason makes the Wait result of an exited child readable.
|
||||||
func exitReason(err error) string {
|
func exitReason(err error) string {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return "Prozess hat sich sofort beendet"
|
return "process exited immediately"
|
||||||
}
|
}
|
||||||
return err.Error()
|
return err.Error()
|
||||||
}
|
}
|
||||||
|
|
||||||
// sayViaDaemon reicht eine Ansage beim Daemon ein (POST /speak). Default:
|
// sayViaDaemon submits an announcement to the daemon (POST /speak). Default:
|
||||||
// sofort zurückkehren (non-blocking), info erhält die Item-ID; --wait pollt
|
// return at once (non-blocking), info receives the item ID; --wait polls
|
||||||
// /status, bis die Ansage weder läuft noch wartet. Bei aktivem Mute
|
// /status until the announcement is neither playing nor waiting. When muted
|
||||||
// verwirft der Daemon — info sagt „muted"; Gesetz-Verwürfe nennen den
|
// the daemon discards and info says "muted"; law discards name the reason.
|
||||||
// Grund. info ist der Writer für diese Informations-Token: say reicht
|
// info is the writer for these information tokens: say passes stdout, wrap
|
||||||
// stdout, wrap stderr durch (stdout eines gewrappten Befehls darf nicht um
|
// stderr (a wrapped command's stdout must not be polluted by talk lines).
|
||||||
// talk-Zeilen verunreinigt werden).
|
|
||||||
//
|
//
|
||||||
// handled=false heißt: Netz-Fehler (Daemon zwischen Erkennung und Aufruf
|
// handled=false means: network error (daemon died between detection and
|
||||||
// gestorben) → der Aufrufer spricht direkt. Eine Daemon-Antwort mit
|
// call), so the caller speaks directly. A daemon response with an error
|
||||||
// Fehlerstatus (z. B. 400) wird dagegen angezeigt — die Ansage war beim
|
// status (for example 400) is reported instead: the announcement reached
|
||||||
// Daemon angekommen und wurde bewusst abgelehnt.
|
// the daemon and was rejected deliberately.
|
||||||
func sayViaDaemon(client *api.Client, text string, opts *sayOptions, info, stderr io.Writer) (code int, handled bool) {
|
func sayViaDaemon(client *api.Client, text string, opts *sayOptions, info, stderr io.Writer) (code int, handled bool) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), daemonCallTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), daemonCallTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
@@ -135,20 +134,20 @@ func sayViaDaemon(client *api.Client, text string, opts *sayOptions, info, stder
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
var httpErr *api.HTTPError
|
var httpErr *api.HTTPError
|
||||||
if errors.As(err, &httpErr) {
|
if errors.As(err, &httpErr) {
|
||||||
fmt.Fprintf(stderr, "talk: Daemon hat die Ansage abgelehnt: %v\n", err)
|
fmt.Fprintf(stderr, "talk: the daemon rejected the announcement: %v\n", err)
|
||||||
return exitFailure, true
|
return exitFailure, true
|
||||||
}
|
}
|
||||||
return 0, false
|
return 0, false
|
||||||
}
|
}
|
||||||
if resp.Muted {
|
if resp.Muted {
|
||||||
fmt.Fprintln(info, "muted")
|
fmt.Fprintln(info, "muted")
|
||||||
fmt.Fprintln(stderr, "talk: stumm geschaltet (mute) — Ansage verworfen")
|
fmt.Fprintln(stderr, "talk: muted; announcement discarded")
|
||||||
return exitOK, true
|
return exitOK, true
|
||||||
}
|
}
|
||||||
if resp.Discarded != "" {
|
if resp.Discarded != "" {
|
||||||
// Gesetz-Verwurf (Rate-Limit-Budget / Ruhezeit): dokumentiertes
|
// Law discard (rate limit budget / quiet hours): documented behaviour
|
||||||
// Verhalten wie bei Mute — plain Token statt Fehler; --wait hat
|
// like mute, a plain token instead of an error; --wait has nothing to
|
||||||
// nichts zu warten, es gibt keine Item-ID.
|
// wait for, there is no item ID.
|
||||||
line := "discarded: " + resp.Discarded
|
line := "discarded: " + resp.Discarded
|
||||||
if resp.Toast {
|
if resp.Toast {
|
||||||
line += " (toast)"
|
line += " (toast)"
|
||||||
@@ -159,7 +158,7 @@ func sayViaDaemon(client *api.Client, text string, opts *sayOptions, info, stder
|
|||||||
}
|
}
|
||||||
fmt.Fprintln(info, resp.ID)
|
fmt.Fprintln(info, resp.ID)
|
||||||
if resp.Truncated {
|
if resp.Truncated {
|
||||||
fmt.Fprintln(stderr, "talk: Text war zu lang und wurde gekürzt (queue.max_text) — Ansagen sind 1–2 Sätze")
|
fmt.Fprintln(stderr, "talk: text was too long and has been truncated (queue.max_text); announcements are 1 to 2 sentences")
|
||||||
}
|
}
|
||||||
if !opts.wait {
|
if !opts.wait {
|
||||||
return exitOK, true
|
return exitOK, true
|
||||||
@@ -167,36 +166,35 @@ func sayViaDaemon(client *api.Client, text string, opts *sayOptions, info, stder
|
|||||||
return waitForItem(client, resp.ID, stderr), true
|
return waitForItem(client, resp.ID, stderr), true
|
||||||
}
|
}
|
||||||
|
|
||||||
// discardHint übersetzt den Verwurfs-Grund der Daemon-Antwort in einen
|
// discardHint translates the daemon's discard reason into a human note.
|
||||||
// menschlichen Hinweis.
|
|
||||||
func discardHint(reason string, toast bool) string {
|
func discardHint(reason string, toast bool) string {
|
||||||
switch reason {
|
switch reason {
|
||||||
case queue.DiscardQuietHours:
|
case queue.DiscardQuietHours:
|
||||||
if toast {
|
if toast {
|
||||||
return "Ruhezeit aktiv — Ansage durch Toast ersetzt (kein Audio)"
|
return "quiet hours active; announcement replaced by a toast (no audio)"
|
||||||
}
|
}
|
||||||
return "Ruhezeit aktiv — Ansage verworfen (quiet_mode = discard; now bricht bewusst aus)"
|
return "quiet hours active; announcement discarded (quiet_mode = discard; --now deliberately breaks out)"
|
||||||
case queue.DiscardRateLimit:
|
case queue.DiscardRateLimit:
|
||||||
return "Rate-Limit — Ansage verworfen (Priorität low über dem Fenster-Budget)"
|
return "rate limit; announcement discarded (priority low over the window budget)"
|
||||||
case queue.DiscardExpired:
|
case queue.DiscardExpired:
|
||||||
return "Ansage verworfen — sie hat länger gewartet als queue.max_age erlaubt (veraltet)"
|
return "announcement discarded; it waited longer than queue.max_age allows (stale)"
|
||||||
default:
|
default:
|
||||||
return "Ansage verworfen (" + reason + ")"
|
return "announcement discarded (" + reason + ")"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// waitForItem pollt /status, bis die Ansage id weder läuft noch wartet —
|
// waitForItem polls /status until the announcement id is neither playing
|
||||||
// sie ist dann fertig (oder abgebrochen; in beiden Fällen hat der Aufrufer
|
// nor waiting; it is then done (or cancelled; either way there is nothing
|
||||||
// nichts mehr zu warten). Stirbt der Daemon während des Wartens, ist das
|
// left to wait for). If the daemon dies while waiting, that is an error:
|
||||||
// ein Fehler: Der Zustand der Ansage ist unbekannt, und still warten wäre
|
// the announcement's state is unknown, and waiting silently would be the
|
||||||
// das Gegenteil von --wait.
|
// opposite of --wait.
|
||||||
func waitForItem(client *api.Client, id string, stderr io.Writer) int {
|
func waitForItem(client *api.Client, id string, stderr io.Writer) int {
|
||||||
for {
|
for {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), daemonCallTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), daemonCallTimeout)
|
||||||
st, err := client.Status(ctx)
|
st, err := client.Status(ctx)
|
||||||
cancel()
|
cancel()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(stderr, "talk: Daemon beim Warten nicht mehr erreichbar (%v)\n", err)
|
fmt.Fprintf(stderr, "talk: daemon no longer reachable while waiting (%v)\n", err)
|
||||||
return exitFailure
|
return exitFailure
|
||||||
}
|
}
|
||||||
if !st.PendingOrCurrent(id) {
|
if !st.PendingOrCurrent(id) {
|
||||||
|
|||||||
+20
-21
@@ -14,27 +14,26 @@ import (
|
|||||||
"code.m3ta.dev/m3tam3re/talk/internal/daemon"
|
"code.m3ta.dev/m3tam3re/talk/internal/daemon"
|
||||||
)
|
)
|
||||||
|
|
||||||
// daemonStopTimeout ist die Frist, in der ein per /shutdown angestoßener
|
// daemonStopTimeout is how long a daemon told to shut down via /shutdown may
|
||||||
// Daemon verschwunden sein muss.
|
// take to disappear.
|
||||||
const daemonStopTimeout = 5 * time.Second
|
const daemonStopTimeout = 5 * time.Second
|
||||||
|
|
||||||
// runDaemon implementiert `talk daemon [run|start|stop]`:
|
// runDaemon implements `talk daemon [run|start|stop]`:
|
||||||
//
|
//
|
||||||
// - run (Default): Daemon im Vordergrund bis SIGINT/SIGTERM — der Modus
|
// - run (default): the daemon in the foreground until SIGINT/SIGTERM; the
|
||||||
// für systemd/launchd/Task Scheduler oder ein Terminal. Protokoll auf
|
// mode for systemd/launchd/Task Scheduler or a terminal. Log on stderr.
|
||||||
// stderr.
|
// - start: start the daemon in the background (the same as say's
|
||||||
// - start: Daemon im Hintergrund starten (dasselbe wie der Autostart von
|
// autostart, only explicit and independent of daemon.autostart) and
|
||||||
// say, nur explizit und unabhängig von daemon.autostart) und melden,
|
// report where it runs. Already running: no error.
|
||||||
// wo er läuft. Läuft schon einer: kein Fehler.
|
// - stop: shut a running daemon down via POST /shutdown and wait until it
|
||||||
// - stop: laufenden Daemon per POST /shutdown herunterfahren und warten,
|
// is gone. None running: a note, exit 0 (idempotent).
|
||||||
// bis er weg ist. Läuft keiner: Hinweis, Exit 0 (idempotent).
|
|
||||||
func runDaemon(args []string, _ *sayOptions, _ io.Reader, stdout, stderr io.Writer) int {
|
func runDaemon(args []string, _ *sayOptions, _ io.Reader, stdout, stderr io.Writer) int {
|
||||||
sub := "run"
|
sub := "run"
|
||||||
if len(args) > 0 {
|
if len(args) > 0 {
|
||||||
sub = args[0]
|
sub = args[0]
|
||||||
}
|
}
|
||||||
if len(args) > 1 {
|
if len(args) > 1 {
|
||||||
fmt.Fprintln(stderr, "talk daemon: zu viele Argumente — Verwendung: talk daemon [run|start|stop]")
|
fmt.Fprintln(stderr, "talk daemon: too many arguments; usage: talk daemon [run|start|stop]")
|
||||||
return exitUsage
|
return exitUsage
|
||||||
}
|
}
|
||||||
cfg, err := config.Load(config.Options{Getenv: getenv})
|
cfg, err := config.Load(config.Options{Getenv: getenv})
|
||||||
@@ -50,7 +49,7 @@ func runDaemon(args []string, _ *sayOptions, _ io.Reader, stdout, stderr io.Writ
|
|||||||
case "stop":
|
case "stop":
|
||||||
return daemonStop(cfg, stdout, stderr)
|
return daemonStop(cfg, stdout, stderr)
|
||||||
default:
|
default:
|
||||||
fmt.Fprintf(stderr, "talk daemon: unbekanntes Unterkommando %q (erlaubt: run, start, stop)\n", sub)
|
fmt.Fprintf(stderr, "talk daemon: unknown subcommand %q (allowed: run, start, stop)\n", sub)
|
||||||
return exitUsage
|
return exitUsage
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -74,20 +73,20 @@ func daemonRun(cfg config.Config, stderr io.Writer) int {
|
|||||||
func daemonStart(cfg config.Config, stdout, stderr io.Writer) int {
|
func daemonStart(cfg config.Config, stdout, stderr io.Writer) int {
|
||||||
client := api.NewClient(cfg.Server.Port)
|
client := api.NewClient(cfg.Server.Port)
|
||||||
if daemonAlive(client, daemonProbeTimeout) {
|
if daemonAlive(client, daemonProbeTimeout) {
|
||||||
fmt.Fprintf(stdout, "daemon: läuft bereits unter %s\n", client.BaseURL)
|
fmt.Fprintf(stdout, "daemon: already running at %s\n", client.BaseURL)
|
||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
if !startDaemon(client, stderr) {
|
if !startDaemon(client, stderr) {
|
||||||
return exitFailure
|
return exitFailure
|
||||||
}
|
}
|
||||||
fmt.Fprintf(stdout, "daemon: gestartet unter %s\n", client.BaseURL)
|
fmt.Fprintf(stdout, "daemon: started at %s\n", client.BaseURL)
|
||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
|
|
||||||
func daemonStop(cfg config.Config, stdout, stderr io.Writer) int {
|
func daemonStop(cfg config.Config, stdout, stderr io.Writer) int {
|
||||||
client := api.NewClient(cfg.Server.Port)
|
client := api.NewClient(cfg.Server.Port)
|
||||||
if !daemonAlive(client, daemonProbeTimeout) {
|
if !daemonAlive(client, daemonProbeTimeout) {
|
||||||
fmt.Fprintf(stdout, "daemon: läuft nicht (%s)\n", client.BaseURL)
|
fmt.Fprintf(stdout, "daemon: not running (%s)\n", client.BaseURL)
|
||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), daemonCallTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), daemonCallTimeout)
|
||||||
@@ -96,9 +95,9 @@ func daemonStop(cfg config.Config, stdout, stderr io.Writer) int {
|
|||||||
fmt.Fprintf(stderr, "talk daemon stop: %v\n", err)
|
fmt.Fprintf(stderr, "talk daemon stop: %v\n", err)
|
||||||
return exitFailure
|
return exitFailure
|
||||||
}
|
}
|
||||||
// Warten, bis der Daemon wirklich weg ist: erst verstummt HTTP, dann
|
// Wait until the daemon is really gone: first HTTP falls silent, then it
|
||||||
// bricht er die laufende Ansage ab und löscht als Letztes die PID-Datei.
|
// aborts the playing announcement and deletes the PID file as its last
|
||||||
// Ohne Config-Dir (keine PID-Datei) genügt das HTTP-Ende.
|
// act. Without a config directory (no PID file) the HTTP end suffices.
|
||||||
pidDir := ""
|
pidDir := ""
|
||||||
if dir, err := config.Dir(getenv); err == nil {
|
if dir, err := config.Dir(getenv); err == nil {
|
||||||
pidDir = dir
|
pidDir = dir
|
||||||
@@ -106,12 +105,12 @@ func daemonStop(cfg config.Config, stdout, stderr io.Writer) int {
|
|||||||
deadline := time.Now().Add(daemonStopTimeout)
|
deadline := time.Now().Add(daemonStopTimeout)
|
||||||
for daemonAlive(client, daemonStartPoll*4) || (pidDir != "" && daemon.ReadPID(pidDir) != 0) {
|
for daemonAlive(client, daemonStartPoll*4) || (pidDir != "" && daemon.ReadPID(pidDir) != 0) {
|
||||||
if time.Now().After(deadline) {
|
if time.Now().After(deadline) {
|
||||||
fmt.Fprintf(stderr, "talk daemon stop: Daemon ist nach %s noch nicht beendet — PID siehe %s im Config-Verzeichnis\n",
|
fmt.Fprintf(stderr, "talk daemon stop: daemon has not exited after %s; see %s in the config directory for its PID\n",
|
||||||
daemonStopTimeout, daemon.PIDFileName)
|
daemonStopTimeout, daemon.PIDFileName)
|
||||||
return exitFailure
|
return exitFailure
|
||||||
}
|
}
|
||||||
time.Sleep(daemonStartPoll)
|
time.Sleep(daemonStartPoll)
|
||||||
}
|
}
|
||||||
fmt.Fprintln(stdout, "daemon: gestoppt")
|
fmt.Fprintln(stdout, "daemon: stopped")
|
||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
+72
-82
@@ -22,31 +22,31 @@ import (
|
|||||||
"code.m3ta.dev/m3tam3re/talk/internal/speak"
|
"code.m3ta.dev/m3tam3re/talk/internal/speak"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Status einer doctor-Prüfung.
|
// Status of a doctor check.
|
||||||
const (
|
const (
|
||||||
statusOK = "ok" // ✔ in Ordnung
|
statusOK = "ok" // ✔ fine
|
||||||
statusWarn = "warn" // ⚠ Hinweis — funktioniert, aber eingeschränkt oder beachtenswert
|
statusWarn = "warn" // ⚠ note: works, but limited or worth knowing
|
||||||
statusFail = "fail" // ✘ Fehler — so wird nichts zu hören sein (Exit 1)
|
statusFail = "fail" // ✘ error: nothing will be heard like this (exit 1)
|
||||||
)
|
)
|
||||||
|
|
||||||
// check ist eine Zeile des doctor-Berichts (auch die JSON-Form).
|
// check is one line of the doctor report (also the JSON form).
|
||||||
type check struct {
|
type check struct {
|
||||||
Check string `json:"check"`
|
Check string `json:"check"`
|
||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
Detail string `json:"detail"`
|
Detail string `json:"detail"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// probeTimeout ist das Budget je Synthese-Probe (--probe).
|
// probeTimeout is the budget per synthesis probe (--probe).
|
||||||
const probeTimeout = 20 * time.Second
|
const probeTimeout = 20 * time.Second
|
||||||
|
|
||||||
// runDoctor implementiert `talk doctor`: eine Zeile je Prüfpunkt — Config,
|
// runDoctor implements `talk doctor`: one line per check (config, daemon,
|
||||||
// Daemon, Audio, jede Provider-Stufe, Mute, Gesetze — mit klarem Satz, was
|
// audio, every provider tier, notifications, mute, laws) with a plain
|
||||||
// Sache ist und was zu tun wäre. Exit 0 ohne ✘, sonst 1; ein nicht
|
// sentence saying what is up and what to do. Exit 0 without ✘, else 1; a
|
||||||
// laufender Daemon ist ⚠ (er startet beim nächsten Sprechbefehl). --probe
|
// daemon that is not running is ⚠ (it starts on the next speak command).
|
||||||
// macht echte Synthese-Proben (Netz); --json liefert die Liste als JSON.
|
// --probe runs real synthesis probes (network); --json returns the list.
|
||||||
func runDoctor(args []string, opts *sayOptions, _ io.Reader, stdout, stderr io.Writer) int {
|
func runDoctor(args []string, opts *sayOptions, _ io.Reader, stdout, stderr io.Writer) int {
|
||||||
if len(args) > 0 {
|
if len(args) > 0 {
|
||||||
fmt.Fprintln(stderr, "talk doctor: keine Argumente erwartet (Flags: --probe, --json)")
|
fmt.Fprintln(stderr, "talk doctor: no arguments expected (flags: --probe, --json)")
|
||||||
return exitUsage
|
return exitUsage
|
||||||
}
|
}
|
||||||
checks := doctorChecks(opts.probe)
|
checks := doctorChecks(opts.probe)
|
||||||
@@ -65,9 +65,9 @@ func runDoctor(args []string, opts *sayOptions, _ io.Reader, stdout, stderr io.W
|
|||||||
fmt.Fprintf(stdout, "%s %-11s %s\n", symbol(c.Status), c.Check, c.Detail)
|
fmt.Fprintf(stdout, "%s %-11s %s\n", symbol(c.Status), c.Check, c.Detail)
|
||||||
}
|
}
|
||||||
if failed {
|
if failed {
|
||||||
fmt.Fprintln(stdout, "\nMindestens ein Punkt verhindert Ton (✘). Behebe ihn und prüfe mit `talk test`.")
|
fmt.Fprintln(stdout, "\nAt least one item prevents sound (✘). Fix it, then check with `talk test`.")
|
||||||
} else {
|
} else {
|
||||||
fmt.Fprintln(stdout, "\nAlles bereit. Probiere: talk test")
|
fmt.Fprintln(stdout, "\nAll set. Try: talk test")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if failed {
|
if failed {
|
||||||
@@ -76,8 +76,8 @@ func runDoctor(args []string, opts *sayOptions, _ io.Reader, stdout, stderr io.W
|
|||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
|
|
||||||
// symbol rendert den Status: Unicode-Zeichen, auf Windows-Konsolen (oft
|
// symbol renders the status: Unicode marks, short words on Windows consoles
|
||||||
// ohne UTF-8) kurze Wörter.
|
// (often without UTF-8).
|
||||||
func symbol(status string) string {
|
func symbol(status string) string {
|
||||||
win := runtime.GOOS == "windows"
|
win := runtime.GOOS == "windows"
|
||||||
switch status {
|
switch status {
|
||||||
@@ -99,34 +99,19 @@ func symbol(status string) string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// doctorChecks führt alle Prüfungen aus. Jede Prüfung ist unabhängig: Ein
|
// doctorChecks runs all checks. Each one is independent: a failure in one
|
||||||
// Fehler in einer (z. B. kaputte Config) verhindert die anderen nicht —
|
// (for example a broken config) does not prevent the others; they run with
|
||||||
// dann laufen sie mit Defaults, damit der Bericht vollständig bleibt.
|
// defaults so the report stays complete.
|
||||||
func doctorChecks(probe bool) []check {
|
func doctorChecks(probe bool) []check {
|
||||||
var out []check
|
var out []check
|
||||||
|
|
||||||
// 1. Config
|
|
||||||
cfg, cfgCheck := checkConfig()
|
cfg, cfgCheck := checkConfig()
|
||||||
out = append(out, cfgCheck)
|
out = append(out, cfgCheck)
|
||||||
|
|
||||||
// 2. Daemon
|
|
||||||
out = append(out, checkDaemon(cfg))
|
out = append(out, checkDaemon(cfg))
|
||||||
|
|
||||||
// 3. Audio
|
|
||||||
out = append(out, checkAudio(cfg))
|
out = append(out, checkAudio(cfg))
|
||||||
|
|
||||||
// 4. Provider-Stufen (+ 5. Gesamt-Verfügbarkeit)
|
|
||||||
out = append(out, checkProviders(cfg, probe)...)
|
out = append(out, checkProviders(cfg, probe)...)
|
||||||
|
|
||||||
// 6. Benachrichtigungen (Ruhezeit-Toast)
|
|
||||||
out = append(out, checkNotify(cfg))
|
out = append(out, checkNotify(cfg))
|
||||||
|
|
||||||
// 7. Mute
|
|
||||||
out = append(out, checkMute())
|
out = append(out, checkMute())
|
||||||
|
|
||||||
// 8. Gesetze
|
|
||||||
out = append(out, checkLaws(cfg))
|
out = append(out, checkLaws(cfg))
|
||||||
|
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -135,16 +120,20 @@ func checkConfig() (config.Config, check) {
|
|||||||
cfg, err := config.Load(config.Options{Getenv: getenv})
|
cfg, err := config.Load(config.Options{Getenv: getenv})
|
||||||
switch {
|
switch {
|
||||||
case err != nil:
|
case err != nil:
|
||||||
// Mit Defaults weiterprüfen, aber den Fehler klar nennen.
|
// Keep checking with defaults, but name the error clearly.
|
||||||
cfg, _ = config.Load(config.Options{Getenv: func(string) string { return "" }})
|
cfg, _ = config.Load(config.Options{Getenv: func(string) string { return "" }})
|
||||||
return cfg, check{"Config", statusFail, fmt.Sprintf("%v — bitte beheben, talk läuft sonst nicht", err)}
|
return cfg, check{"Config", statusFail, fmt.Sprintf("%v; fix it, talk does not run otherwise", err)}
|
||||||
case perr != nil:
|
case perr != nil:
|
||||||
return cfg, check{"Config", statusWarn, "kein Config-Verzeichnis (HOME bzw. APPDATA fehlt) — Defaults + Env; Mute und Daemon-Dateien deaktiviert"}
|
return cfg, check{"Config", statusWarn, "no config directory (HOME or APPDATA not set); defaults + env, mute and daemon files disabled"}
|
||||||
}
|
}
|
||||||
if _, statErr := os.Stat(path); statErr != nil {
|
if _, statErr := os.Stat(path); statErr != nil {
|
||||||
return cfg, check{"Config", statusOK, fmt.Sprintf("keine Datei unter %s — Defaults gelten (talk setup legt eine an)", path)}
|
return cfg, check{"Config", statusOK, fmt.Sprintf("no file at %s; defaults apply (talk setup creates one)", path)}
|
||||||
}
|
}
|
||||||
return cfg, check{"Config", statusOK, path + " geladen"}
|
if len(cfg.Unknown) > 0 {
|
||||||
|
return cfg, check{"Config", statusWarn, fmt.Sprintf("%s loaded, but it has keys talk does not know: %s. A top-level key written below a [table] header belongs to that table; move it above the first [table]",
|
||||||
|
path, strings.Join(cfg.Unknown, ", "))}
|
||||||
|
}
|
||||||
|
return cfg, check{"Config", statusOK, path + " loaded"}
|
||||||
}
|
}
|
||||||
|
|
||||||
func checkDaemon(cfg config.Config) check {
|
func checkDaemon(cfg config.Config) check {
|
||||||
@@ -153,32 +142,32 @@ func checkDaemon(cfg config.Config) check {
|
|||||||
defer cancel()
|
defer cancel()
|
||||||
st, err := client.Status(ctx)
|
st, err := client.Status(ctx)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
detail := fmt.Sprintf("läuft unter %s (version %s, %d in der Queue)", client.BaseURL, st.Version, st.Queue)
|
detail := fmt.Sprintf("running at %s (version %s, %d queued)", client.BaseURL, st.Version, st.Queue)
|
||||||
if dir, derr := config.Dir(getenv); derr == nil {
|
if dir, derr := config.Dir(getenv); derr == nil {
|
||||||
detail += ", Log: " + filepath.Join(dir, daemon.LogFileName)
|
detail += ", log: " + filepath.Join(dir, daemon.LogFileName)
|
||||||
}
|
}
|
||||||
return check{"Daemon", statusOK, detail}
|
return check{"Daemon", statusOK, detail}
|
||||||
}
|
}
|
||||||
var httpErr *api.HTTPError
|
var httpErr *api.HTTPError
|
||||||
if errors.As(err, &httpErr) {
|
if errors.As(err, &httpErr) {
|
||||||
return check{"Daemon", statusFail, fmt.Sprintf("unter %s antwortet ein fremder Dienst (HTTP %d) — anderen Port wählen: [server] port bzw. TALK_PORT", client.BaseURL, httpErr.Status)}
|
return check{"Daemon", statusFail, fmt.Sprintf("a foreign service answers at %s (HTTP %d); choose another port: [server] port or TALK_PORT", client.BaseURL, httpErr.Status)}
|
||||||
}
|
}
|
||||||
if cfg.Daemon.Autostart {
|
if cfg.Daemon.Autostart {
|
||||||
return check{"Daemon", statusWarn, fmt.Sprintf("läuft nicht (%s) — startet beim nächsten Sprechbefehl von selbst", client.BaseURL)}
|
return check{"Daemon", statusWarn, fmt.Sprintf("not running (%s); starts by itself on the next speak command", client.BaseURL)}
|
||||||
}
|
}
|
||||||
return check{"Daemon", statusWarn, fmt.Sprintf("läuft nicht (%s), Autostart ist aus — `talk daemon start` oder Dienst einrichten; bis dahin spricht talk direkt", client.BaseURL)}
|
return check{"Daemon", statusWarn, fmt.Sprintf("not running (%s), autostart is off; `talk daemon start` or set up a service; until then talk speaks directly", client.BaseURL)}
|
||||||
}
|
}
|
||||||
|
|
||||||
func checkAudio(cfg config.Config) check {
|
func checkAudio(cfg config.Config) check {
|
||||||
if cfg.Audio.Sink == config.SinkNull {
|
if cfg.Audio.Sink == config.SinkNull {
|
||||||
return check{"Audio", statusWarn, "audio.sink = null — kein Ton (für CI/Server gedacht; TALK_AUDIO_SINK=oto für Wiedergabe)"}
|
return check{"Audio", statusWarn, "audio.sink = null; no sound (meant for CI/servers; TALK_AUDIO_SINK=oto for playback)"}
|
||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
if err := audio.Check(ctx, cfg.Audio.Sink); err != nil {
|
if err := audio.Check(ctx, cfg.Audio.Sink); err != nil {
|
||||||
return check{"Audio", statusFail, fmt.Sprintf("%v — kein Audiogerät oder Audio-Bibliothek fehlt (Linux: PulseAudio/ALSA)", err)}
|
return check{"Audio", statusFail, fmt.Sprintf("%v; no audio device, or the audio library is missing (Linux: PulseAudio/ALSA)", err)}
|
||||||
}
|
}
|
||||||
return check{"Audio", statusOK, "Audiogerät bereit (oto)"}
|
return check{"Audio", statusOK, "audio device ready (oto)"}
|
||||||
}
|
}
|
||||||
|
|
||||||
func checkProviders(cfg config.Config, probe bool) []check {
|
func checkProviders(cfg config.Config, probe bool) []check {
|
||||||
@@ -199,9 +188,9 @@ func checkProviders(cfg config.Config, probe bool) []check {
|
|||||||
out = append(out, c)
|
out = append(out, c)
|
||||||
}
|
}
|
||||||
if available == 0 {
|
if available == 0 {
|
||||||
out = append(out, check{"Provider", statusFail, "keine Stufe verfügbar — ohne Key und ohne OS-Stimme kann talk nicht sprechen (espeak-ng installieren oder TALK_ELEVENLABS_KEY/TALK_OPENAI_KEY setzen)"})
|
out = append(out, check{"Provider", statusFail, "no tier available; without a key and without an OS voice talk cannot speak (install espeak-ng or set TALK_ELEVENLABS_KEY/TALK_OPENAI_KEY)"})
|
||||||
} else if cfg.Provider != "" {
|
} else if cfg.Provider != "" {
|
||||||
out = append(out, check{"Provider", statusOK, fmt.Sprintf("Kette auf %q gepinnt (config provider) — kein Fallback", cfg.Provider)})
|
out = append(out, check{"Provider", statusOK, fmt.Sprintf("chain pinned to %q (config provider); no fallback", cfg.Provider)})
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
@@ -215,42 +204,42 @@ func checkTier(p provider.Provider, cfg config.Config) check {
|
|||||||
envKey = provider.EnvOpenAIKey
|
envKey = provider.EnvOpenAIKey
|
||||||
}
|
}
|
||||||
if !p.Available(context.Background()) {
|
if !p.Available(context.Background()) {
|
||||||
return check{name, statusWarn, fmt.Sprintf("kein Key (%s) — Stufe wird übersprungen", envKey)}
|
return check{name, statusWarn, fmt.Sprintf("no key (%s); tier is skipped", envKey)}
|
||||||
}
|
}
|
||||||
detail := fmt.Sprintf("Key gesetzt (%s)", envKey)
|
detail := fmt.Sprintf("key set (%s)", envKey)
|
||||||
if ep := cfg.Providers[name].Endpoint; ep != "" {
|
if ep := cfg.Providers[name].Endpoint; ep != "" {
|
||||||
detail += ", Endpunkt " + ep
|
detail += ", endpoint " + ep
|
||||||
}
|
}
|
||||||
if v := provider.DefaultVoice(name, "de", cfg.Voice); v != "" {
|
if v := provider.DefaultVoice(name, cfg.Lang, cfg.Voice); v != "" {
|
||||||
detail += ", Stimme de: " + voiceLabel(name, v)
|
detail += fmt.Sprintf(", voice %s: %s", cfg.Lang, voiceLabel(name, v))
|
||||||
}
|
}
|
||||||
return check{name, statusOK, detail}
|
return check{name, statusOK, detail}
|
||||||
case "edge":
|
case "edge":
|
||||||
if !p.Available(context.Background()) {
|
if !p.Available(context.Background()) {
|
||||||
return check{name, statusWarn, "kein Endpunkt konfiguriert — Stufe wird übersprungen"}
|
return check{name, statusWarn, "no endpoint configured; tier is skipped"}
|
||||||
}
|
}
|
||||||
return check{name, statusOK, "kostenlos, ohne Key (braucht Internet), Stimme de: " + voiceLabel(name, provider.DefaultVoice(name, "de", cfg.Voice))}
|
return check{name, statusOK, fmt.Sprintf("free, no key (needs internet), voice %s: %s", cfg.Lang, voiceLabel(name, provider.DefaultVoice(name, cfg.Lang, cfg.Voice)))}
|
||||||
case "osbuiltin":
|
case "osbuiltin":
|
||||||
desc := "OS-Stimme"
|
desc := "OS voice"
|
||||||
if d, ok := p.(interface{ Describe() string }); ok {
|
if d, ok := p.(interface{ Describe() string }); ok {
|
||||||
desc = d.Describe()
|
desc = d.Describe()
|
||||||
}
|
}
|
||||||
if !p.Available(context.Background()) {
|
if !p.Available(context.Background()) {
|
||||||
return check{name, statusWarn, desc + " — letzte Stufe fehlt; ohne Netz bleibt talk stumm"}
|
return check{name, statusWarn, desc + "; the last tier is missing, talk stays silent without network"}
|
||||||
}
|
}
|
||||||
if strings.Contains(desc, "nur Direktansage") {
|
if strings.Contains(desc, "direct speech only") {
|
||||||
return check{name, statusWarn, desc}
|
return check{name, statusWarn, desc}
|
||||||
}
|
}
|
||||||
return check{name, statusOK, desc}
|
return check{name, statusOK, desc}
|
||||||
default:
|
default:
|
||||||
if p.Available(context.Background()) {
|
if p.Available(context.Background()) {
|
||||||
return check{name, statusOK, "verfügbar"}
|
return check{name, statusOK, "available"}
|
||||||
}
|
}
|
||||||
return check{name, statusWarn, "nicht verfügbar"}
|
return check{name, statusWarn, "not available"}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// voiceLabel rendert eine Voice-ID mit Katalog-Namen, falls bekannt.
|
// voiceLabel renders a voice ID with its catalog name when known.
|
||||||
func voiceLabel(prov, id string) string {
|
func voiceLabel(prov, id string) string {
|
||||||
if n := provider.VoiceName(prov, id); n != "" {
|
if n := provider.VoiceName(prov, id); n != "" {
|
||||||
return fmt.Sprintf("%s (%s)", n, id)
|
return fmt.Sprintf("%s (%s)", n, id)
|
||||||
@@ -258,68 +247,69 @@ func voiceLabel(prov, id string) string {
|
|||||||
return id
|
return id
|
||||||
}
|
}
|
||||||
|
|
||||||
// probeTier macht eine echte Synthese-Probe (kein Abspielen) und meldet
|
// probeTier runs a real synthesis probe (no playback) and reports bytes and
|
||||||
// Bytes und Dauer bzw. den Fehler.
|
// duration, or the error.
|
||||||
func probeTier(p provider.Provider) string {
|
func probeTier(p provider.Provider) string {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), probeTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), probeTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
data, err := p.Synthesize(ctx, "Test", "de")
|
data, err := p.Synthesize(ctx, "Test", "en")
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, provider.ErrNoByteOutput):
|
case errors.Is(err, provider.ErrNoByteOutput):
|
||||||
return "Probe: liefert keine Bytes (spricht nur direkt) — ok"
|
return "probe: yields no bytes (speaks directly only); ok"
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return "Probe FEHLGESCHLAGEN: " + err.Error()
|
return "probe FAILED: " + err.Error()
|
||||||
default:
|
default:
|
||||||
return fmt.Sprintf("Probe ok: %d Bytes in %s", len(data), time.Since(start).Round(time.Millisecond))
|
return fmt.Sprintf("probe ok: %d bytes in %s", len(data), time.Since(start).Round(time.Millisecond))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func checkNotify(cfg config.Config) check {
|
func checkNotify(cfg config.Config) check {
|
||||||
if notify.Available() {
|
if notify.Available() {
|
||||||
return check{"Toast", statusOK, notify.Describe() + " — für quiet_mode = toast"}
|
return check{"Notify", statusOK, notify.Describe() + "; used for quiet_mode = toast"}
|
||||||
}
|
}
|
||||||
if cfg.QuietMode == queue.QuietModeToast {
|
if cfg.QuietMode == queue.QuietModeToast {
|
||||||
return check{"Toast", statusWarn, notify.Describe() + " — quiet_mode = toast wird nur protokolliert"}
|
return check{"Notify", statusWarn, notify.Describe() + "; quiet_mode = toast is only logged"}
|
||||||
}
|
}
|
||||||
return check{"Toast", statusOK, notify.Describe() + " (nur für quiet_mode = toast relevant)"}
|
return check{"Notify", statusOK, notify.Describe() + " (only relevant for quiet_mode = toast)"}
|
||||||
}
|
}
|
||||||
|
|
||||||
func checkMute() check {
|
func checkMute() check {
|
||||||
dir, err := config.Dir(getenv)
|
dir, err := config.Dir(getenv)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return check{"Mute", statusOK, "aus (kein Config-Dir, Mute nicht verfügbar)"}
|
return check{"Mute", statusOK, "off (no config directory, mute unavailable)"}
|
||||||
}
|
}
|
||||||
if (queue.MuteStore{Path: filepath.Join(dir, queue.MuteFileName)}).Muted() {
|
if (queue.MuteStore{Path: filepath.Join(dir, queue.MuteFileName)}).Muted() {
|
||||||
return check{"Mute", statusWarn, "AN — alle Ansagen werden verworfen, bis `talk unmute`"}
|
return check{"Mute", statusWarn, "ON; every announcement is discarded until `talk unmute`"}
|
||||||
}
|
}
|
||||||
return check{"Mute", statusOK, "aus"}
|
return check{"Mute", statusOK, "off"}
|
||||||
}
|
}
|
||||||
|
|
||||||
func checkLaws(cfg config.Config) check {
|
func checkLaws(cfg config.Config) check {
|
||||||
parts := []string{
|
parts := []string{
|
||||||
fmt.Sprintf("rate-limit %s", durationOrOff(cfg.Queue.RateLimit)),
|
fmt.Sprintf("rate limit %s", durationOrOff(cfg.Queue.RateLimit)),
|
||||||
fmt.Sprintf("max. %d Zeichen", cfg.Queue.MaxText),
|
fmt.Sprintf("max %d characters", cfg.Queue.MaxText),
|
||||||
fmt.Sprintf("max. Wartezeit %s", durationOrOff(cfg.Queue.MaxAge)),
|
fmt.Sprintf("max wait %s", durationOrOff(cfg.Queue.MaxAge)),
|
||||||
|
fmt.Sprintf("fallback language %s", cfg.Lang),
|
||||||
}
|
}
|
||||||
status := statusOK
|
status := statusOK
|
||||||
if cfg.QuietHours == "" {
|
if cfg.QuietHours == "" {
|
||||||
parts = append(parts, "Ruhezeit aus")
|
parts = append(parts, "quiet hours off")
|
||||||
} else {
|
} else {
|
||||||
q, err := queue.ParseQuietHours(cfg.QuietHours)
|
q, err := queue.ParseQuietHours(cfg.QuietHours)
|
||||||
if err == nil && q.Active(time.Now()) {
|
if err == nil && q.Active(time.Now()) {
|
||||||
status = statusWarn
|
status = statusWarn
|
||||||
parts = append(parts, fmt.Sprintf("Ruhezeit %s AKTIV bis %s (modus %s) — Ansagen werden gerade verworfen", cfg.QuietHours, q.Until(time.Now()).Format("15:04"), cfg.QuietMode))
|
parts = append(parts, fmt.Sprintf("quiet hours %s ACTIVE until %s (mode %s); announcements are being discarded right now", cfg.QuietHours, q.Until(time.Now()).Format("15:04"), cfg.QuietMode))
|
||||||
} else {
|
} else {
|
||||||
parts = append(parts, fmt.Sprintf("Ruhezeit %s (modus %s)", cfg.QuietHours, cfg.QuietMode))
|
parts = append(parts, fmt.Sprintf("quiet hours %s (mode %s)", cfg.QuietHours, cfg.QuietMode))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return check{"Gesetze", status, strings.Join(parts, ", ")}
|
return check{"Laws", status, strings.Join(parts, ", ")}
|
||||||
}
|
}
|
||||||
|
|
||||||
func durationOrOff(d time.Duration) string {
|
func durationOrOff(d time.Duration) string {
|
||||||
if d <= 0 {
|
if d <= 0 {
|
||||||
return "aus"
|
return "off"
|
||||||
}
|
}
|
||||||
return d.String()
|
return d.String()
|
||||||
}
|
}
|
||||||
+48
-27
@@ -18,30 +18,30 @@ func checkByName(t *testing.T, checks []check, name string) check {
|
|||||||
return c
|
return c
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
t.Fatalf("Prüfung %q fehlt in %+v", name, checks)
|
t.Fatalf("check %q missing in %+v", name, checks)
|
||||||
return check{}
|
return check{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestDoctorOhneDaemon: toter Daemon ist ⚠ (kein Fehler), sink null ist ⚠,
|
// TestDoctorWithoutDaemon: a dead daemon is ⚠ (no error), sink null is ⚠,
|
||||||
// Cloud-Stufen ohne Key ⚠, edge ✔ — Exit 0, Abschlusszeile „Alles bereit".
|
// cloud tiers without keys ⚠, edge ✔; exit 0, closing line "All set".
|
||||||
func TestDoctorOhneDaemon(t *testing.T) {
|
func TestDoctorWithoutDaemon(t *testing.T) {
|
||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null", "XDG_CONFIG_HOME": root})
|
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null", "XDG_CONFIG_HOME": root})
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"doctor"}, &out, &errBuf)
|
code := runCLI([]string{"doctor"}, &out, &errBuf)
|
||||||
if code != exitOK {
|
if code != exitOK {
|
||||||
t.Fatalf("talk doctor: Exit %d, stdout %q, stderr %q", code, out.String(), errBuf.String())
|
t.Fatalf("talk doctor: exit %d, stdout %q, stderr %q", code, out.String(), errBuf.String())
|
||||||
}
|
}
|
||||||
for _, want := range []string{"⚠ Daemon", "läuft nicht", "⚠ Audio", "⚠ elevenlabs", "TALK_ELEVENLABS_KEY", "✔ edge", "✔ Mute", "✔ Gesetze", "Alles bereit"} {
|
for _, want := range []string{"⚠ Daemon", "not running", "⚠ Audio", "⚠ elevenlabs", "TALK_ELEVENLABS_KEY", "✔ edge", "✔ Mute", "✔ Laws", "All set"} {
|
||||||
if !strings.Contains(out.String(), want) {
|
if !strings.Contains(out.String(), want) {
|
||||||
t.Errorf("stdout ohne %q:\n%s", want, out.String())
|
t.Errorf("stdout without %q:\n%s", want, out.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestDoctorJSONUndMute: --json liefert die Prüfliste; eine Mute-Datei
|
// TestDoctorJSONAndMute: --json yields the check list; a mute file makes
|
||||||
// macht Mute zu warn; ein Key macht die Stufe ok.
|
// Mute warn; a key makes the tier ok.
|
||||||
func TestDoctorJSONUndMute(t *testing.T) {
|
func TestDoctorJSONAndMute(t *testing.T) {
|
||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
setGetenv(t, map[string]string{
|
setGetenv(t, map[string]string{
|
||||||
"TALK_AUDIO_SINK": "null",
|
"TALK_AUDIO_SINK": "null",
|
||||||
@@ -56,45 +56,45 @@ func TestDoctorJSONUndMute(t *testing.T) {
|
|||||||
}
|
}
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
if code := runCLI([]string{"doctor", "--json"}, &out, &errBuf); code != exitOK {
|
if code := runCLI([]string{"doctor", "--json"}, &out, &errBuf); code != exitOK {
|
||||||
t.Fatalf("talk doctor --json: Exit %d, stderr %q", code, errBuf.String())
|
t.Fatalf("talk doctor --json: exit %d, stderr %q", code, errBuf.String())
|
||||||
}
|
}
|
||||||
var checks []check
|
var checks []check
|
||||||
if err := json.Unmarshal(out.Bytes(), &checks); err != nil {
|
if err := json.Unmarshal(out.Bytes(), &checks); err != nil {
|
||||||
t.Fatalf("JSON = %q (%v)", out.String(), err)
|
t.Fatalf("JSON = %q (%v)", out.String(), err)
|
||||||
}
|
}
|
||||||
if c := checkByName(t, checks, "Mute"); c.Status != statusWarn || !strings.Contains(c.Detail, "unmute") {
|
if c := checkByName(t, checks, "Mute"); c.Status != statusWarn || !strings.Contains(c.Detail, "unmute") {
|
||||||
t.Errorf("Mute = %+v, want warn mit unmute-Hinweis", c)
|
t.Errorf("Mute = %+v, want warn with an unmute hint", c)
|
||||||
}
|
}
|
||||||
if c := checkByName(t, checks, "elevenlabs"); c.Status != statusOK || !strings.Contains(c.Detail, "Rachel") {
|
if c := checkByName(t, checks, "elevenlabs"); c.Status != statusOK || !strings.Contains(c.Detail, "Rachel") {
|
||||||
t.Errorf("elevenlabs = %+v, want ok mit Default-Stimme", c)
|
t.Errorf("elevenlabs = %+v, want ok with the default voice", c)
|
||||||
}
|
}
|
||||||
if c := checkByName(t, checks, "Daemon"); c.Status != statusWarn {
|
if c := checkByName(t, checks, "Daemon"); c.Status != statusWarn {
|
||||||
t.Errorf("Daemon = %+v, want warn", c)
|
t.Errorf("Daemon = %+v, want warn", c)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestDoctorFremderDienstAufPort: Antwortet unter dem Port etwas anderes als
|
// TestDoctorForeignServiceOnPort: if something other than talk answers on
|
||||||
// talk, ist das ✘ mit Port-Hinweis — Exit 1.
|
// the port, that is ✘ with a port hint; exit 1.
|
||||||
func TestDoctorFremderDienstAufPort(t *testing.T) {
|
func TestDoctorForeignServiceOnPort(t *testing.T) {
|
||||||
fremd := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
foreign := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
}))
|
}))
|
||||||
t.Cleanup(fremd.Close)
|
t.Cleanup(foreign.Close)
|
||||||
port := fremd.URL[strings.LastIndex(fremd.URL, ":")+1:]
|
port := foreign.URL[strings.LastIndex(foreign.URL, ":")+1:]
|
||||||
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null", "TALK_PORT": port})
|
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null", "TALK_PORT": port})
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"doctor"}, &out, &errBuf)
|
code := runCLI([]string{"doctor"}, &out, &errBuf)
|
||||||
if code != exitFailure {
|
if code != exitFailure {
|
||||||
t.Fatalf("talk doctor (fremder Dienst): Exit %d, want 1\n%s", code, out.String())
|
t.Fatalf("talk doctor (foreign service): exit %d, want 1\n%s", code, out.String())
|
||||||
}
|
}
|
||||||
if !strings.Contains(out.String(), "✘ Daemon") || !strings.Contains(out.String(), "fremder Dienst") || !strings.Contains(out.String(), "TALK_PORT") {
|
if !strings.Contains(out.String(), "✘ Daemon") || !strings.Contains(out.String(), "foreign service") || !strings.Contains(out.String(), "TALK_PORT") {
|
||||||
t.Errorf("stdout = %q", out.String())
|
t.Errorf("stdout = %q", out.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestDoctorKaputteConfig: Eine unlesbare config.toml ist ✘, die übrigen
|
// TestDoctorBrokenConfig: an unreadable config.toml is ✘, the other checks
|
||||||
// Prüfungen laufen trotzdem (mit Defaults) — der Bericht bleibt vollständig.
|
// still run (with defaults); the report stays complete.
|
||||||
func TestDoctorKaputteConfig(t *testing.T) {
|
func TestDoctorBrokenConfig(t *testing.T) {
|
||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null", "XDG_CONFIG_HOME": root})
|
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null", "XDG_CONFIG_HOME": root})
|
||||||
if err := os.MkdirAll(filepath.Join(root, "talk"), 0o755); err != nil {
|
if err := os.MkdirAll(filepath.Join(root, "talk"), 0o755); err != nil {
|
||||||
@@ -106,11 +106,32 @@ func TestDoctorKaputteConfig(t *testing.T) {
|
|||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"doctor"}, &out, &errBuf)
|
code := runCLI([]string{"doctor"}, &out, &errBuf)
|
||||||
if code != exitFailure || !strings.Contains(out.String(), "✘ Config") {
|
if code != exitFailure || !strings.Contains(out.String(), "✘ Config") {
|
||||||
t.Errorf("Exit %d, stdout %q — want ✘ Config und Exit 1", code, out.String())
|
t.Errorf("exit %d, stdout %q; want ✘ Config and exit 1", code, out.String())
|
||||||
}
|
}
|
||||||
for _, want := range []string{"Daemon", "edge", "Mute", "Gesetze"} {
|
for _, want := range []string{"Daemon", "edge", "Mute", "Laws"} {
|
||||||
if !strings.Contains(out.String(), want) {
|
if !strings.Contains(out.String(), want) {
|
||||||
t.Errorf("Prüfung %q fehlt trotz Config-Fehler:\n%s", want, out.String())
|
t.Errorf("check %q missing despite the config error:\n%s", want, out.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestDoctorUnknownConfigKeys: a key filed under the wrong table is ⚠ with a
|
||||||
|
// hint, not an error.
|
||||||
|
func TestDoctorUnknownConfigKeys(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null", "XDG_CONFIG_HOME": root})
|
||||||
|
if err := os.MkdirAll(filepath.Join(root, "talk"), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(root, "talk", "config.toml"), []byte("[voice]\nlang = \"de\"\n[voice.edge]\nde = \"de-DE-KatjaNeural\"\n"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var out, errBuf bytes.Buffer
|
||||||
|
code := runCLI([]string{"doctor"}, &out, &errBuf)
|
||||||
|
if code != exitOK {
|
||||||
|
t.Fatalf("exit %d, want 0 (unknown keys are a warning)\n%s", code, out.String())
|
||||||
|
}
|
||||||
|
if !strings.Contains(out.String(), "⚠ Config") || !strings.Contains(out.String(), "voice.lang") || !strings.Contains(out.String(), "[table]") {
|
||||||
|
t.Errorf("stdout = %q", out.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
+14
-14
@@ -1,14 +1,14 @@
|
|||||||
// talk ist das eine Binary von talk 2.0: CLI und Daemon.
|
// talk is the single binary of talk: CLI and daemon.
|
||||||
//
|
//
|
||||||
// say (und der Default-Aufruf `talk "Text"`) reicht Ansagen in den Daemon
|
// say (and the default form `talk "Text"`) hands announcements to the
|
||||||
// ein — non-blocking, --wait pollt bis zur Fertigstellung, --now springt
|
// daemon: non-blocking, --wait polls until spoken, --now jumps the queue.
|
||||||
// vor. Läuft kein Daemon, startet talk ihn selbst im Hintergrund
|
// When no daemon runs, talk starts one itself in the background
|
||||||
// (daemon.autostart); gelingt auch das nicht, spricht talk direkt (ohne
|
// (daemon.autostart); if that fails too, talk speaks directly (no queue,
|
||||||
// Warteschlange, mit Hinweis) — nichts bricht still. `talk daemon run`
|
// with a note). Nothing fails silently. `talk daemon run` runs the daemon in
|
||||||
// betreibt den Daemon im Vordergrund, start/stop steuern ihn explizit.
|
// the foreground, start/stop control it explicitly. mute/unmute/status/
|
||||||
// mute/unmute/status/cancel sind Daemon-Aufrufe mit plain Output;
|
// cancel are daemon calls with plain output; `talk wrap -- <command>` runs
|
||||||
// `talk wrap -- <Befehl>` führt Befehle aus und sagt das Ergebnis an. Die
|
// commands and announces the result; doctor/test/voices/setup cover
|
||||||
// übrigen Befehle sind Stubs.
|
// diagnostics and onboarding.
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -16,18 +16,18 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Build-Informationen. Werden beim Release per -ldflags injiziert, z. B.
|
// Build information, injected at release time via -ldflags, for example
|
||||||
//
|
//
|
||||||
// go build -ldflags "-X main.version=1.0.0 -X main.commit=abc1234" ./cmd/talk
|
// go build -ldflags "-X main.version=1.0.0 -X main.commit=abc1234" ./cmd/talk
|
||||||
//
|
//
|
||||||
// Defaults: version "dev", commit leer (siehe auch .goreleaser.yaml, Task 11).
|
// Defaults: version "dev", commit empty (see scripts/release.sh).
|
||||||
var (
|
var (
|
||||||
version = "dev"
|
version = "dev"
|
||||||
commit = ""
|
commit = ""
|
||||||
)
|
)
|
||||||
|
|
||||||
// buildVersion rendert Version plus Commit-Hash in Klammern, falls injiziert
|
// buildVersion renders the version plus the commit hash in parentheses when
|
||||||
// — der Wert, den der Daemon in /status und MCP serverInfo meldet.
|
// injected; the value the daemon reports in /status and MCP serverInfo.
|
||||||
func buildVersion() string {
|
func buildVersion() string {
|
||||||
if commit == "" {
|
if commit == "" {
|
||||||
return version
|
return version
|
||||||
|
|||||||
+23
-24
@@ -7,12 +7,11 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestParseInterspersedDoubleDash (Regression, Task 07): Das erste allein
|
// TestParseInterspersedDoubleDash (regression): the first standalone "--"
|
||||||
// stehende „--" schirmt alles Folgenden von der Flag-Auswertung ab — der
|
// shields everything after it from flag parsing, the core of the wrap form
|
||||||
// Kern der wrap-Aufrufform `talk wrap -- foo --bar`. Vorher nahm der
|
// `talk wrap -- foo --bar`. Previously the interspersed loop resumed parsing
|
||||||
// Interspersed-Loop nach jedem Positionsargument das Parsen wieder auf und
|
// after every positional and ate the wrapped command's flags. At the same
|
||||||
// fraß damit Flags des nachfolgenden Befehls. Gleichzeitig bleibt die
|
// time the "flag after the text" form (without "--") stays intact.
|
||||||
// Abnahme-Form „Flag nach dem Text" (ohne „--") intakt.
|
|
||||||
func TestParseInterspersedDoubleDash(t *testing.T) {
|
func TestParseInterspersedDoubleDash(t *testing.T) {
|
||||||
newWrapFS := func() (*flag.FlagSet, *sayOptions) {
|
newWrapFS := func() (*flag.FlagSet, *sayOptions) {
|
||||||
fs := flag.NewFlagSet("talk wrap", flag.ContinueOnError)
|
fs := flag.NewFlagSet("talk wrap", flag.ContinueOnError)
|
||||||
@@ -21,78 +20,78 @@ func TestParseInterspersedDoubleDash(t *testing.T) {
|
|||||||
return fs, addSayFlags(fs)
|
return fs, addSayFlags(fs)
|
||||||
}
|
}
|
||||||
|
|
||||||
t.Run("Doppelminus schirmt Befehls-Flags", func(t *testing.T) {
|
t.Run("double dash shields command flags", func(t *testing.T) {
|
||||||
fs, opts := newWrapFS()
|
fs, opts := newWrapFS()
|
||||||
positional, err := parseInterspersed(fs, []string{"--", "foo", "--bar"})
|
positional, err := parseInterspersed(fs, []string{"--", "foo", "--bar"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("parse: %v", err)
|
t.Fatalf("parse: %v", err)
|
||||||
}
|
}
|
||||||
if strings.Join(positional, " ") != "foo --bar" {
|
if strings.Join(positional, " ") != "foo --bar" {
|
||||||
t.Errorf("Positionsargumente = %q, want %q", positional, []string{"foo", "--bar"})
|
t.Errorf("positional = %q, want %q", positional, []string{"foo", "--bar"})
|
||||||
}
|
}
|
||||||
if opts.wait {
|
if opts.wait {
|
||||||
t.Error("--bar darf kein talk-Flag geworden sein (Shielding kaputt)")
|
t.Error("--bar must not have become a talk flag (shielding broken)")
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("talk-Flags vor dem Doppelminus gelten", func(t *testing.T) {
|
t.Run("talk flags before the double dash apply", func(t *testing.T) {
|
||||||
fs, opts := newWrapFS()
|
fs, opts := newWrapFS()
|
||||||
positional, err := parseInterspersed(fs, []string{"--wait", "--", "sleep", "1"})
|
positional, err := parseInterspersed(fs, []string{"--wait", "--", "sleep", "1"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("parse: %v", err)
|
t.Fatalf("parse: %v", err)
|
||||||
}
|
}
|
||||||
if !opts.wait {
|
if !opts.wait {
|
||||||
t.Error("--wait vor dem -- muss als talk-Flag gelten")
|
t.Error("--wait before the -- must count as a talk flag")
|
||||||
}
|
}
|
||||||
if strings.Join(positional, " ") != "sleep 1" {
|
if strings.Join(positional, " ") != "sleep 1" {
|
||||||
t.Errorf("Positionsargumente = %q, want %q", positional, []string{"sleep", "1"})
|
t.Errorf("positional = %q, want %q", positional, []string{"sleep", "1"})
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Positional vor dem Doppelminus wird mitgeschleppt", func(t *testing.T) {
|
t.Run("positional before the double dash is carried along", func(t *testing.T) {
|
||||||
fs, _ := newWrapFS()
|
fs, _ := newWrapFS()
|
||||||
positional, err := parseInterspersed(fs, []string{"foo", "--", "--bar"})
|
positional, err := parseInterspersed(fs, []string{"foo", "--", "--bar"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("parse: %v", err)
|
t.Fatalf("parse: %v", err)
|
||||||
}
|
}
|
||||||
if strings.Join(positional, " ") != "foo --bar" {
|
if strings.Join(positional, " ") != "foo --bar" {
|
||||||
t.Errorf("Positionsargumente = %q, want %q", positional, []string{"foo", "--bar"})
|
t.Errorf("positional = %q, want %q", positional, []string{"foo", "--bar"})
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("abgeschirmtes talk-Flag setzt den Flag nicht", func(t *testing.T) {
|
t.Run("shielded talk flag does not set the flag", func(t *testing.T) {
|
||||||
fs, opts := newWrapFS()
|
fs, opts := newWrapFS()
|
||||||
positional, err := parseInterspersed(fs, []string{"--", "--wait", "true"})
|
positional, err := parseInterspersed(fs, []string{"--", "--wait", "true"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("parse: %v", err)
|
t.Fatalf("parse: %v", err)
|
||||||
}
|
}
|
||||||
if opts.wait {
|
if opts.wait {
|
||||||
t.Error("--wait NACH dem -- gehört dem Befehl, nicht talk")
|
t.Error("--wait AFTER the -- belongs to the command, not talk")
|
||||||
}
|
}
|
||||||
if strings.Join(positional, " ") != "--wait true" {
|
if strings.Join(positional, " ") != "--wait true" {
|
||||||
t.Errorf("Positionsargumente = %q, want %q", positional, []string{"--wait", "true"})
|
t.Errorf("positional = %q, want %q", positional, []string{"--wait", "true"})
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Flag nach dem Text ohne Doppelminus bleibt erlaubt", func(t *testing.T) {
|
t.Run("flag after the text without double dash stays allowed", func(t *testing.T) {
|
||||||
fs, opts := newWrapFS()
|
fs, opts := newWrapFS()
|
||||||
positional, err := parseInterspersed(fs, []string{"Text", "--lang=en"})
|
positional, err := parseInterspersed(fs, []string{"Text", "--lang=en"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("parse: %v (Abnahme-Form Flag-nach-Text kaputt)", err)
|
t.Fatalf("parse: %v (flag-after-text form broken)", err)
|
||||||
}
|
}
|
||||||
if strings.Join(positional, " ") != "Text" || opts.lang != "en" {
|
if strings.Join(positional, " ") != "Text" || opts.lang != "en" {
|
||||||
t.Errorf("Positionsargumente = %q, lang = %q — Flag-nach-Text muss weitergehen", positional, opts.lang)
|
t.Errorf("positional = %q, lang = %q; flag-after-text must keep working", positional, opts.lang)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Text nach dem Doppelminus kommt vollständig durch (say)", func(t *testing.T) {
|
t.Run("text after the double dash comes through completely (say)", func(t *testing.T) {
|
||||||
fs, _ := newWrapFS()
|
fs, _ := newWrapFS()
|
||||||
positional, err := parseInterspersed(fs, []string{"--", "Bericht", "mit --flag", "fertig"})
|
positional, err := parseInterspersed(fs, []string{"--", "Report", "with --flag", "done"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("parse: %v", err)
|
t.Fatalf("parse: %v", err)
|
||||||
}
|
}
|
||||||
if strings.Join(positional, " ") != "Bericht mit --flag fertig" {
|
if strings.Join(positional, " ") != "Report with --flag done" {
|
||||||
t.Errorf("Positionsargumente = %q, want Wörter unverändert", positional)
|
t.Errorf("positional = %q, want the words unchanged", positional)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
Binary file not shown.
Binary file not shown.
+35
-35
@@ -13,13 +13,13 @@ import (
|
|||||||
"code.m3ta.dev/m3tam3re/talk/internal/speak"
|
"code.m3ta.dev/m3tam3re/talk/internal/speak"
|
||||||
)
|
)
|
||||||
|
|
||||||
// getenv ist die Env-Seam von run (Tests injizieren hier TALK_AUDIO_SINK,
|
// getenv is the CLI's environment seam (tests inject TALK_AUDIO_SINK,
|
||||||
// TALK_PORT etc., ohne den Prozess-Environment anzufassen). Default:
|
// TALK_PORT etc. without touching the process environment). Default:
|
||||||
// os.Getenv.
|
// os.Getenv.
|
||||||
var getenv = os.Getenv
|
var getenv = os.Getenv
|
||||||
|
|
||||||
// sayOptions bündelt die Flags von say (identisch im Default-Pfad
|
// sayOptions bundles the say flags (identical for the default form
|
||||||
// `talk "Text"`).
|
// `talk "text"`).
|
||||||
type sayOptions struct {
|
type sayOptions struct {
|
||||||
wait bool
|
wait bool
|
||||||
now bool
|
now bool
|
||||||
@@ -28,40 +28,40 @@ type sayOptions struct {
|
|||||||
lang string
|
lang string
|
||||||
provider string
|
provider string
|
||||||
|
|
||||||
// Diagnose-Flags (doctor, voices): maschinenlesbare Ausgabe und echte
|
// Diagnostic flags (doctor, voices): machine-readable output and real
|
||||||
// Netz-Proben. Liegen in derselben Struct, damit die Befehlstabelle
|
// network probes. They live in the same struct so the command table
|
||||||
// eine Flag-Signatur behält; say ignoriert sie.
|
// keeps one flag signature; say ignores them.
|
||||||
jsonOut bool
|
jsonOut bool
|
||||||
probe bool
|
probe bool
|
||||||
|
toast bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// runSay ist der say-Eingangspfad: Text aus Argumenten oder stdin sammeln
|
// runSay is the say entry point: collect the text from arguments or stdin,
|
||||||
// und validieren, dann über den Daemon sprechen — non-blocking als
|
// validate, then speak through the daemon (non-blocking by default, --wait
|
||||||
// Default, --wait pollt bis zur Fertigstellung, --now springt vor; Läuft
|
// polls until spoken, --now jumps the queue). When no daemon runs, talk
|
||||||
// kein Daemon, startet talk ihn selbst (daemon.autostart). Geht auch das
|
// starts one itself (daemon.autostart). If that fails too, talk speaks
|
||||||
// nicht, spricht talk direkt im eigenen Prozess (sayDirect) — ohne
|
// directly in this process (sayDirect): no queue, but never silent.
|
||||||
// Warteschlange, aber nie still.
|
|
||||||
func runSay(args []string, opts *sayOptions, stdin io.Reader, stdout, stderr io.Writer) int {
|
func runSay(args []string, opts *sayOptions, stdin io.Reader, stdout, stderr io.Writer) int {
|
||||||
text := strings.Join(args, " ")
|
text := strings.Join(args, " ")
|
||||||
if text == "" {
|
if text == "" {
|
||||||
if isCharDevice(stdin) {
|
if isCharDevice(stdin) {
|
||||||
fmt.Fprintln(stderr, "talk: kein Text — bitte als Argument übergeben oder über stdin pipen")
|
fmt.Fprintln(stderr, "talk: no text given; pass it as an argument or pipe it via stdin")
|
||||||
return exitUsage
|
return exitUsage
|
||||||
}
|
}
|
||||||
b, err := io.ReadAll(stdin)
|
b, err := io.ReadAll(stdin)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(stderr, "talk: stdin lesen: %v\n", err)
|
fmt.Fprintf(stderr, "talk: reading stdin: %v\n", err)
|
||||||
return exitFailure
|
return exitFailure
|
||||||
}
|
}
|
||||||
text = strings.TrimSpace(string(b))
|
text = strings.TrimSpace(string(b))
|
||||||
if text == "" {
|
if text == "" {
|
||||||
fmt.Fprintln(stderr, "talk: kein Text (Argument und stdin sind leer)")
|
fmt.Fprintln(stderr, "talk: no text given (argument and stdin are empty)")
|
||||||
return exitFailure
|
return exitFailure
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validierung vor jedem Daemon-Kontakt (auch wrap erbt die say-Flags):
|
// Validate before any daemon contact (wrap inherits the say flags):
|
||||||
// Benutzungsfehler sollen schnell und ohne Netzwerk-Umwege auffallen.
|
// usage errors should fail fast and without network round trips.
|
||||||
if code, bad := validateSayOptions(opts, stderr); bad {
|
if code, bad := validateSayOptions(opts, stderr); bad {
|
||||||
return code
|
return code
|
||||||
}
|
}
|
||||||
@@ -74,30 +74,30 @@ func runSay(args []string, opts *sayOptions, stdin io.Reader, stdout, stderr io.
|
|||||||
return announce(cfg, text, opts, stdout, stderr)
|
return announce(cfg, text, opts, stdout, stderr)
|
||||||
}
|
}
|
||||||
|
|
||||||
// announce ist der gemeinsame Ansage-Weg von say und wrap: Daemon sicher-
|
// announce is the shared announcement path of say and wrap: ensure a daemon
|
||||||
// stellen (ggf. starten) und einreihen; ohne Daemon direkt sprechen. info
|
// (start one if needed) and enqueue; without a daemon speak directly. info
|
||||||
// ist der Writer für Informations-Token (Item-ID, muted, discarded).
|
// is the writer for the information tokens (item ID, muted, discarded).
|
||||||
func announce(cfg config.Config, text string, opts *sayOptions, info, stderr io.Writer) int {
|
func announce(cfg config.Config, text string, opts *sayOptions, info, stderr io.Writer) int {
|
||||||
if client, ok := ensureDaemon(cfg, stderr); ok {
|
if client, ok := ensureDaemon(cfg, stderr); ok {
|
||||||
if code, handled := sayViaDaemon(client, text, opts, info, stderr); handled {
|
if code, handled := sayViaDaemon(client, text, opts, info, stderr); handled {
|
||||||
return code
|
return code
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fmt.Fprintln(stderr, "talk: kein Daemon erreichbar — spreche direkt (ohne Warteschlange)")
|
fmt.Fprintln(stderr, "talk: no daemon reachable; speaking directly (no queue)")
|
||||||
return sayDirect(cfg, text, opts, info, stderr)
|
return sayDirect(cfg, text, opts, info, stderr)
|
||||||
}
|
}
|
||||||
|
|
||||||
// sayDirect ist der Notfallpfad ohne Daemon: Mute respektieren (dieselbe
|
// sayDirect is the emergency path without a daemon: honour mute (the same
|
||||||
// Datei, die der Daemon liest), dann über den Sprech-Kern sprechen —
|
// file the daemon reads), then speak via the engine, blocking in the CLI
|
||||||
// blockierend im CLI-Prozess, unserialisiert (zwei gleichzeitige Aufrufe
|
// process and unserialized (two simultaneous calls may overlap; the daemon
|
||||||
// können überlappen; der Daemon ist der Normalfall). Ohne Config-Dir läuft
|
// is the normal case). Without a config directory it runs without mute
|
||||||
// es ohne Mute weiter, statt zu scheitern.
|
// rather than failing.
|
||||||
func sayDirect(cfg config.Config, text string, opts *sayOptions, info, stderr io.Writer) int {
|
func sayDirect(cfg config.Config, text string, opts *sayOptions, info, stderr io.Writer) int {
|
||||||
if dir, err := config.Dir(getenv); err == nil {
|
if dir, err := config.Dir(getenv); err == nil {
|
||||||
mute := queue.MuteStore{Path: filepath.Join(dir, queue.MuteFileName)}
|
mute := queue.MuteStore{Path: filepath.Join(dir, queue.MuteFileName)}
|
||||||
if mute.Muted() {
|
if mute.Muted() {
|
||||||
fmt.Fprintln(info, "muted")
|
fmt.Fprintln(info, "muted")
|
||||||
fmt.Fprintln(stderr, "talk: stumm geschaltet (mute) — Ansage verworfen")
|
fmt.Fprintln(stderr, "talk: muted; announcement discarded")
|
||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -119,23 +119,23 @@ func sayDirect(cfg config.Config, text string, opts *sayOptions, info, stderr io
|
|||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
|
|
||||||
// validateSayOptions prüft die say-Flags (wrap erbt sie): --lang auf de |
|
// validateSayOptions checks the say flags (wrap inherits them): --lang must
|
||||||
// en, --priority auf low | normal | high. Rückgabe (code, true) heißt:
|
// be de | en, --priority low | normal | high. (code, true) means: usage
|
||||||
// Benutzungsfehler, bereits auf stderr gemeldet.
|
// error, already reported on stderr.
|
||||||
func validateSayOptions(opts *sayOptions, stderr io.Writer) (int, bool) {
|
func validateSayOptions(opts *sayOptions, stderr io.Writer) (int, bool) {
|
||||||
if opts.lang != "" && opts.lang != "de" && opts.lang != "en" {
|
if opts.lang != "" && opts.lang != "de" && opts.lang != "en" {
|
||||||
fmt.Fprintf(stderr, "talk: --lang: ungültiger Wert %q (erlaubt: de, en)\n", opts.lang)
|
fmt.Fprintf(stderr, "talk: --lang: invalid value %q (allowed: de, en)\n", opts.lang)
|
||||||
return exitFailure, true
|
return exitFailure, true
|
||||||
}
|
}
|
||||||
if opts.priority != "" && !queue.Priority(opts.priority).Valid() {
|
if opts.priority != "" && !queue.Priority(opts.priority).Valid() {
|
||||||
fmt.Fprintf(stderr, "talk: --priority: ungültiger Wert %q (erlaubt: low, normal, high)\n", opts.priority)
|
fmt.Fprintf(stderr, "talk: --priority: invalid value %q (allowed: low, normal, high)\n", opts.priority)
|
||||||
return exitFailure, true
|
return exitFailure, true
|
||||||
}
|
}
|
||||||
return 0, false
|
return 0, false
|
||||||
}
|
}
|
||||||
|
|
||||||
// isCharDevice meldet, ob r ein Terminal ist (dann darf talk nicht auf
|
// isCharDevice reports whether r is a terminal (then talk must not wait for
|
||||||
// stdin-Input warten, sondern meldet einen Benutzungsfehler).
|
// stdin input but report a usage error).
|
||||||
func isCharDevice(r io.Reader) bool {
|
func isCharDevice(r io.Reader) bool {
|
||||||
f, ok := r.(*os.File)
|
f, ok := r.(*os.File)
|
||||||
if !ok {
|
if !ok {
|
||||||
|
|||||||
+159
-146
@@ -10,22 +10,31 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
// setGetenv überschreibt die Env-Seam der CLI für einen Test. Grundaus-
|
// TestMain cuts the test binary off from the developer's real session bus:
|
||||||
// stattung jedes Tests: TALK_EDGE_ENDPOINT zeigt auf einen garantiert
|
// the notify package would otherwise show real notifications (doctor, test
|
||||||
// toten Loopback-Port (Verbindung wird sofort abgelehnt) — die Default-
|
// --toast) and wait for clicks. With an unreachable address the D-Bus path
|
||||||
// Kette enthält edge, und kein Test darf je den echten Microsoft-Endpunkt
|
// fails fast and the tests observe the notify-send fallback.
|
||||||
// anfassen. Dasselbe gilt seit Task 04 für TALK_PORT: Die Daemon-Erkennung
|
func TestMain(m *testing.M) {
|
||||||
// von say zeigt auf einen toten Port, damit die Tests hier Deterministisch
|
os.Setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path=/nonexistent/talk-test-bus")
|
||||||
// den Direkt-Pfad laufen (und nie einen zufällig laufenden echten Daemon
|
os.Exit(m.Run())
|
||||||
// treffen); TALK_AUTOSTART=false verhindert, dass ein Test das Test-Binary
|
}
|
||||||
// selbst als Daemon spawnt. Wer einen dieser Ports bewusst anders braucht, überschreibt
|
|
||||||
// den Key.
|
// setGetenv overrides the CLI's environment seam for one test. Base kit of
|
||||||
|
// every test: TALK_EDGE_ENDPOINT points at a guaranteed dead loopback port
|
||||||
|
// (connection refused at once); the default chain contains edge, and no
|
||||||
|
// test may ever touch the real Microsoft endpoint. The same goes for
|
||||||
|
// TALK_PORT: daemon detection points at a dead port so the tests here run
|
||||||
|
// the direct path deterministically (and never hit a real daemon that
|
||||||
|
// happens to run); TALK_AUTOSTART=false prevents a test from spawning the
|
||||||
|
// test binary as a daemon. Whoever needs one of these different overrides
|
||||||
|
// the key.
|
||||||
func setGetenv(t *testing.T, kv map[string]string) {
|
func setGetenv(t *testing.T, kv map[string]string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
base := map[string]string{
|
base := map[string]string{
|
||||||
"TALK_EDGE_ENDPOINT": "ws://127.0.0.1:1/",
|
"TALK_EDGE_ENDPOINT": "ws://127.0.0.1:1/",
|
||||||
"TALK_PORT": "1",
|
"TALK_PORT": "1",
|
||||||
"TALK_AUTOSTART": "false", // In-Prozess-Tests dürfen nie das Test-Binary als Daemon starten
|
"TALK_AUTOSTART": "false", // in-process tests must never start the test binary as a daemon
|
||||||
|
"TALK_NOTIFY": "false", // and never pop up notifications on the developer's desktop
|
||||||
}
|
}
|
||||||
for k, v := range kv {
|
for k, v := range kv {
|
||||||
base[k] = v
|
base[k] = v
|
||||||
@@ -40,9 +49,9 @@ func setGetenv(t *testing.T, kv map[string]string) {
|
|||||||
t.Cleanup(func() { getenv = old })
|
t.Cleanup(func() { getenv = old })
|
||||||
}
|
}
|
||||||
|
|
||||||
// fakeTTSBin schreibt ein ausführbares Shell-Skript namens name in dir
|
// fakeTTSBin writes an executable shell script named name into dir (same
|
||||||
// (gleicher Mechanismus wie im provider-Paket: echter Prozess, PATH-
|
// mechanism as in the provider package: real process, PATH manipulation, no
|
||||||
// Manipulation, kein Mock-Framework).
|
// mock framework).
|
||||||
func fakeTTSBin(t *testing.T, dir, name, body string) {
|
func fakeTTSBin(t *testing.T, dir, name, body string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
script := "#!/bin/sh\n" + body + "\n"
|
script := "#!/bin/sh\n" + body + "\n"
|
||||||
@@ -52,9 +61,8 @@ func fakeTTSBin(t *testing.T, dir, name, body string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// withFakeEspeak stellt ein fake espeak bereit, das WAV-Bytes auf stdout
|
// withFakeEspeak provides a fake espeak that writes WAV bytes to stdout and
|
||||||
// schreibt und den Aufruf in seen protokolliert. Zurück kommt der Pfad der
|
// records the call in seen. Returns the path of the record file.
|
||||||
// Protokolldatei.
|
|
||||||
func withFakeEspeak(t *testing.T) string {
|
func withFakeEspeak(t *testing.T) string {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
@@ -69,79 +77,86 @@ cat "`+wav+`"`)
|
|||||||
return seen
|
return seen
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSayArgumentMitNullSink: `talk "Hallo Welt"` läuft mit
|
// TestSayArgumentWithNullSink: `talk "Hello world"` runs silently with
|
||||||
// TALK_AUDIO_SINK=null tonlos durch (Abnahmekriterium) — Synthese läuft
|
// TALK_AUDIO_SINK=null: synthesis happens (fake espeak was called) and
|
||||||
// (fake espeak wurde gerufen), und die Wiedergabe wird mit sichtbarer
|
// playback is discarded with a visible line on stderr (observable behaviour
|
||||||
// Verwurf-Zeile auf stderr verworfen (extern beobachtbares Verhalten des
|
// of the null sink on the CLI path).
|
||||||
// null-Sinks auf dem CLI-Pfad).
|
func TestSayArgumentWithNullSink(t *testing.T) {
|
||||||
func TestSayArgumentMitNullSink(t *testing.T) {
|
|
||||||
seen := withFakeEspeak(t)
|
seen := withFakeEspeak(t)
|
||||||
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
||||||
|
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"Hallo Welt"}, &out, &errBuf)
|
code := runCLI([]string{"Hello world"}, &out, &errBuf)
|
||||||
if code != exitOK {
|
if code != exitOK {
|
||||||
t.Fatalf(`talk "Hallo Welt" (sink=null): Exit-Code = %d, want %d; stderr = %q`, code, exitOK, errBuf.String())
|
t.Fatalf(`talk "Hello world" (sink=null): exit code = %d, want %d; stderr = %q`, code, exitOK, errBuf.String())
|
||||||
}
|
}
|
||||||
if _, err := os.Stat(seen); err != nil {
|
if _, err := os.Stat(seen); err != nil {
|
||||||
t.Errorf("Synthese lief nicht (fake espeak nicht gerufen): %v", err)
|
t.Errorf("synthesis did not run (fake espeak not called): %v", err)
|
||||||
}
|
}
|
||||||
if !strings.Contains(errBuf.String(), "verworfen (null sink)") {
|
if !strings.Contains(errBuf.String(), "discarded (null sink)") {
|
||||||
t.Errorf("stderr = %q, will Verwurf-Zeile des null-Sinks (Synthese war erfolgreich)", errBuf.String())
|
t.Errorf("stderr = %q, want the null sink's discard line (synthesis succeeded)", errBuf.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSaySubcommandWieDefault: `talk say "Text"` verhält sich wie der
|
// TestSaySubcommandLikeDefault: `talk say "text"` behaves like the default
|
||||||
// Default-Pfad.
|
// path.
|
||||||
func TestSaySubcommandWieDefault(t *testing.T) {
|
func TestSaySubcommandLikeDefault(t *testing.T) {
|
||||||
seen := withFakeEspeak(t)
|
seen := withFakeEspeak(t)
|
||||||
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
||||||
|
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
if code := runCLI([]string{"say", "Hallo"}, &out, &errBuf); code != exitOK {
|
if code := runCLI([]string{"say", "Hello"}, &out, &errBuf); code != exitOK {
|
||||||
t.Fatalf("talk say: Exit-Code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
t.Fatalf("talk say: exit code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
||||||
}
|
}
|
||||||
if _, err := os.Stat(seen); err != nil {
|
if _, err := os.Stat(seen); err != nil {
|
||||||
t.Errorf("fake espeak nicht gerufen: %v", err)
|
t.Errorf("fake espeak not called: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSayViaStdin: ohne Text-Argument wird stdin gelesen.
|
// TestSayViaStdin: without a text argument stdin is read.
|
||||||
func TestSayViaStdin(t *testing.T) {
|
func TestSayViaStdin(t *testing.T) {
|
||||||
withFakeEspeak(t)
|
withFakeEspeak(t)
|
||||||
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
||||||
|
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := run([]string{}, strings.NewReader("Hallo Welt\n"), &out, &errBuf)
|
code := run([]string{}, strings.NewReader("Hello world\n"), &out, &errBuf)
|
||||||
if code != exitOK {
|
if code != exitOK {
|
||||||
t.Fatalf("talk < stdin: Exit-Code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
t.Fatalf("talk < stdin: exit code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSaySprachwahl: englisches Argument übergibt -v en an den Provider,
|
// TestSayLanguageChoice: an English argument passes -v en to the provider, a
|
||||||
// deutsches -v de; --lang überschreibt die Erkennung.
|
// German one -v de; undecidable text takes the configured fallback; --lang
|
||||||
func TestSaySprachwahl(t *testing.T) {
|
// overrides detection.
|
||||||
|
func TestSayLanguageChoice(t *testing.T) {
|
||||||
cases := []struct {
|
cases := []struct {
|
||||||
name string
|
name string
|
||||||
|
env map[string]string
|
||||||
argv []string
|
argv []string
|
||||||
want string
|
want string
|
||||||
}{
|
}{
|
||||||
{"erkannt de", []string{"Der Build ist fertig"}, "-v de --stdout Der Build ist fertig"},
|
{"detected de", nil, []string{"Der Build ist fertig"}, "-v de --stdout Der Build ist fertig"},
|
||||||
{"erkannt en", []string{"The build is done"}, "-v en --stdout The build is done"},
|
{"detected en", nil, []string{"The build is done"}, "-v en --stdout The build is done"},
|
||||||
{"flag pinnt en", []string{"--lang=en", "Guten Morgen"}, "-v en --stdout Guten Morgen"},
|
{"undecidable → default en", nil, []string{"Build 42"}, "-v en --stdout Build 42"},
|
||||||
|
{"undecidable → configured de", map[string]string{"TALK_LANG": "de"}, []string{"Build 42"}, "-v de --stdout Build 42"},
|
||||||
|
{"flag pins en", nil, []string{"--lang=en", "Guten Morgen"}, "-v en --stdout Guten Morgen"},
|
||||||
}
|
}
|
||||||
for _, tc := range cases {
|
for _, tc := range cases {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
seen := withFakeEspeak(t)
|
seen := withFakeEspeak(t)
|
||||||
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
kv := map[string]string{"TALK_AUDIO_SINK": "null"}
|
||||||
|
for k, v := range tc.env {
|
||||||
|
kv[k] = v
|
||||||
|
}
|
||||||
|
setGetenv(t, kv)
|
||||||
|
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
if code := runCLI(tc.argv, &out, &errBuf); code != exitOK {
|
if code := runCLI(tc.argv, &out, &errBuf); code != exitOK {
|
||||||
t.Fatalf("Exit-Code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
t.Fatalf("exit code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
||||||
}
|
}
|
||||||
args, err := os.ReadFile(seen)
|
args, err := os.ReadFile(seen)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("fake espeak nicht gerufen: %v", err)
|
t.Fatalf("fake espeak not called: %v", err)
|
||||||
}
|
}
|
||||||
if got := strings.TrimSpace(string(args)); got != tc.want {
|
if got := strings.TrimSpace(string(args)); got != tc.want {
|
||||||
t.Errorf("espeak ARGS = %q, want %q", got, tc.want)
|
t.Errorf("espeak ARGS = %q, want %q", got, tc.want)
|
||||||
@@ -150,135 +165,135 @@ func TestSaySprachwahl(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSayOhneText: leeres stdin und kein Argument → klarer Fehler.
|
// TestSayWithoutText: empty stdin and no argument is a clear error.
|
||||||
func TestSayOhneText(t *testing.T) {
|
func TestSayWithoutText(t *testing.T) {
|
||||||
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI(nil, &out, &errBuf)
|
code := runCLI(nil, &out, &errBuf)
|
||||||
if code != exitFailure {
|
if code != exitFailure {
|
||||||
t.Fatalf("talk ohne Text: Exit-Code = %d, want %d", code, exitFailure)
|
t.Fatalf("talk without text: exit code = %d, want %d", code, exitFailure)
|
||||||
}
|
}
|
||||||
if !strings.Contains(errBuf.String(), "kein Text") {
|
if !strings.Contains(errBuf.String(), "no text") {
|
||||||
t.Errorf("stderr = %q, will klaren Hinweis auf fehlenden Text", errBuf.String())
|
t.Errorf("stderr = %q, want a clear note about the missing text", errBuf.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSayUngueltigeSprache: --lang mit Unsinn ist ein klarer Fehler.
|
// TestSayInvalidLanguage: --lang with garbage is a clear error.
|
||||||
func TestSayUngueltigeSprache(t *testing.T) {
|
func TestSayInvalidLanguage(t *testing.T) {
|
||||||
withFakeEspeak(t)
|
withFakeEspeak(t)
|
||||||
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"--lang=fr", "Bonjour"}, &out, &errBuf)
|
code := runCLI([]string{"--lang=fr", "Bonjour"}, &out, &errBuf)
|
||||||
if code != exitFailure {
|
if code != exitFailure {
|
||||||
t.Fatalf("talk --lang=fr: Exit-Code = %d, want %d", code, exitFailure)
|
t.Fatalf("talk --lang=fr: exit code = %d, want %d", code, exitFailure)
|
||||||
}
|
}
|
||||||
if !strings.Contains(errBuf.String(), "--lang") {
|
if !strings.Contains(errBuf.String(), "--lang") {
|
||||||
t.Errorf("stderr = %q, will --lang-Fehler", errBuf.String())
|
t.Errorf("stderr = %q, want a --lang error", errBuf.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSayUnbekannterProvider: --provider mit unbekanntem Namen ist ein
|
// TestSayUnknownProvider: --provider with an unknown name is a clear error
|
||||||
// klarer Fehler, der die verfügbaren Provider nennt (Task 03: Kette).
|
// naming the available providers.
|
||||||
func TestSayUnbekannterProvider(t *testing.T) {
|
func TestSayUnknownProvider(t *testing.T) {
|
||||||
withFakeEspeak(t)
|
withFakeEspeak(t)
|
||||||
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"--provider=gibtsnicht", "Test"}, &out, &errBuf)
|
code := runCLI([]string{"--provider=nosuch", "Test"}, &out, &errBuf)
|
||||||
if code != exitFailure {
|
if code != exitFailure {
|
||||||
t.Fatalf("talk --provider=gibtsnicht: Exit-Code = %d, want %d", code, exitFailure)
|
t.Fatalf("talk --provider=nosuch: exit code = %d, want %d", code, exitFailure)
|
||||||
}
|
}
|
||||||
if !strings.Contains(errBuf.String(), "gibtsnicht") || !strings.Contains(errBuf.String(), "osbuiltin") || !strings.Contains(errBuf.String(), "edge") {
|
if !strings.Contains(errBuf.String(), "nosuch") || !strings.Contains(errBuf.String(), "osbuiltin") || !strings.Contains(errBuf.String(), "edge") {
|
||||||
t.Errorf("stderr = %q, will Provider-Fehler mit verfügbaren Namen", errBuf.String())
|
t.Errorf("stderr = %q, want a provider error with the available names", errBuf.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSayUngueltigerSink: TALK_AUDIO_SINK=Müll ist ein klarer Fehler aus
|
// TestSayInvalidSink: TALK_AUDIO_SINK=garbage is a clear error from config
|
||||||
// der Config-Validierung.
|
// validation.
|
||||||
func TestSayUngueltigerSink(t *testing.T) {
|
func TestSayInvalidSink(t *testing.T) {
|
||||||
withFakeEspeak(t)
|
withFakeEspeak(t)
|
||||||
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "mpv"})
|
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "mpv"})
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"Test"}, &out, &errBuf)
|
code := runCLI([]string{"Test"}, &out, &errBuf)
|
||||||
if code != exitFailure {
|
if code != exitFailure {
|
||||||
t.Fatalf("talk mit TALK_AUDIO_SINK=mpv: Exit-Code = %d, want %d", code, exitFailure)
|
t.Fatalf("talk with TALK_AUDIO_SINK=mpv: exit code = %d, want %d", code, exitFailure)
|
||||||
}
|
}
|
||||||
if !strings.Contains(errBuf.String(), "audio.sink") {
|
if !strings.Contains(errBuf.String(), "audio.sink") {
|
||||||
t.Errorf("stderr = %q, will audio.sink-Validierungsfehler", errBuf.String())
|
t.Errorf("stderr = %q, want an audio.sink validation error", errBuf.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSayOhneTTS: ohne jedes TTS-Binary ist Available false → klarer
|
// TestSayWithoutTTS: without any TTS binary Available is false; a clear
|
||||||
// Fehler, kein Panik.
|
// error, no panic.
|
||||||
func TestSayOhneTTS(t *testing.T) {
|
func TestSayWithoutTTS(t *testing.T) {
|
||||||
t.Setenv("PATH", t.TempDir())
|
t.Setenv("PATH", t.TempDir())
|
||||||
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"Hallo"}, &out, &errBuf)
|
code := runCLI([]string{"Hello"}, &out, &errBuf)
|
||||||
if code != exitFailure {
|
if code != exitFailure {
|
||||||
t.Fatalf("talk ohne TTS: Exit-Code = %d, want %d", code, exitFailure)
|
t.Fatalf("talk without TTS: exit code = %d, want %d", code, exitFailure)
|
||||||
}
|
}
|
||||||
if !strings.Contains(errBuf.String(), "nicht verfügbar") {
|
if !strings.Contains(errBuf.String(), "not available") {
|
||||||
t.Errorf("stderr = %q, will Verfügbarkeits-Fehler", errBuf.String())
|
t.Errorf("stderr = %q, want an availability error", errBuf.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSayDirektesFallbeckenOhneEspeak: Linux ohne espeak (nur fake spd-say)
|
// TestSayDirectFallbackWithoutEspeak: Linux without espeak (only fake
|
||||||
// und sink=null verwirft tonlos mit Exit 0 — das spd-say wird NICHT gerufen
|
// spd-say) and sink=null discards silently with exit 0; spd-say is NOT
|
||||||
// (null-Sink darf nie Ton erzeugen).
|
// called (the null sink must never produce sound).
|
||||||
func TestSayDirektesFallbeckenOhneEspeak(t *testing.T) {
|
func TestSayDirectFallbackWithoutEspeak(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
seen := filepath.Join(dir, "seen.txt")
|
seen := filepath.Join(dir, "seen.txt")
|
||||||
fakeTTSBin(t, dir, "spd-say", `printf '%s\n' "$*" > "`+seen+`"`)
|
fakeTTSBin(t, dir, "spd-say", `printf '%s\n' "$*" > "`+seen+`"`)
|
||||||
// PATH NUR auf das fake-spd-say-Verzeichnis: kein echtes espeak, kein
|
// PATH ONLY the fake spd-say directory: no real espeak, no real spd-say.
|
||||||
// echtes spd-say dazwischen.
|
|
||||||
t.Setenv("PATH", dir)
|
t.Setenv("PATH", dir)
|
||||||
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
||||||
|
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"Hallo Welt"}, &out, &errBuf)
|
code := runCLI([]string{"Hello world"}, &out, &errBuf)
|
||||||
if code != exitOK {
|
if code != exitOK {
|
||||||
t.Fatalf("talk (Linux ohne espeak, sink=null): Exit-Code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
t.Fatalf("talk (Linux without espeak, sink=null): exit code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
||||||
}
|
}
|
||||||
if _, err := os.Stat(seen); err == nil {
|
if _, err := os.Stat(seen); err == nil {
|
||||||
t.Error("spd-say wurde gerufen — null-Sink hätte die Ansage verworfen müssen")
|
t.Error("spd-say was called; the null sink should have discarded the announcement")
|
||||||
}
|
}
|
||||||
if !strings.Contains(errBuf.String(), "verworfen") {
|
if !strings.Contains(errBuf.String(), "discarded") {
|
||||||
t.Errorf("stderr = %q, will Verwurf-Hinweis", errBuf.String())
|
t.Errorf("stderr = %q, want a discard note", errBuf.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSayDirektesFallbeckenMitOtoSink: ohne espeak, mit (fake) spd-say und
|
// TestSayDirectFallbackWithOtoSink: without espeak, with (fake) spd-say and
|
||||||
// dem Default-Sink oto muss die Direktansage über spd-say laufen.
|
// the default sink oto, direct speech must go through spd-say.
|
||||||
func TestSayDirektesFallbeckenMitOtoSink(t *testing.T) {
|
func TestSayDirectFallbackWithOtoSink(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
seen := filepath.Join(dir, "seen.txt")
|
seen := filepath.Join(dir, "seen.txt")
|
||||||
fakeTTSBin(t, dir, "spd-say", `printf '%s\n' "$*" > "`+seen+`"`)
|
fakeTTSBin(t, dir, "spd-say", `printf '%s\n' "$*" > "`+seen+`"`)
|
||||||
t.Setenv("PATH", dir)
|
t.Setenv("PATH", dir)
|
||||||
setGetenv(t, nil) // Default-Sink oto, keine Env-Overrides
|
setGetenv(t, nil) // default sink oto, no env overrides
|
||||||
|
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"Hallo Welt"}, &out, &errBuf)
|
code := runCLI([]string{"Der Build ist fertig"}, &out, &errBuf)
|
||||||
if code != exitOK {
|
if code != exitOK {
|
||||||
t.Fatalf("talk (Direktansage): Exit-Code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
t.Fatalf("talk (direct speech): exit code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
||||||
}
|
}
|
||||||
args, err := os.ReadFile(seen)
|
args, err := os.ReadFile(seen)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("fake spd-say nicht gerufen: %v", err)
|
t.Fatalf("fake spd-say not called: %v", err)
|
||||||
}
|
}
|
||||||
if got := strings.TrimSpace(string(args)); got != "-w -l de Hallo Welt" {
|
if got := strings.TrimSpace(string(args)); got != "-w -l de Der Build ist fertig" {
|
||||||
t.Errorf("spd-say ARGS = %q, want %q", got, "-w -l de Hallo Welt")
|
t.Errorf("spd-say ARGS = %q, want %q", got, "-w -l de Der Build ist fertig")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// fakeCloudServer startet einen httptest-HTTP-Fake, der status mit body
|
// fakeCloudReq records what the fake cloud endpoint saw.
|
||||||
// antwortet und den letzten Request aufzeichnet (Struktur wie im
|
|
||||||
// provider-Paket; die CLI-Tests beobachten nur extern: Exit-Code, stderr,
|
|
||||||
// ob der Fake gerufen wurde und mit welchem Pfad).
|
|
||||||
type fakeCloudReq struct {
|
type fakeCloudReq struct {
|
||||||
path string
|
path string
|
||||||
apiKey string
|
apiKey string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// fakeCloudServer starts an httptest fake that answers status with body and
|
||||||
|
// records each request (structure as in the provider package; the CLI tests
|
||||||
|
// only observe externally: exit code, stderr, whether the fake was called
|
||||||
|
// and with which path).
|
||||||
func fakeCloudServer(t *testing.T, status int, body []byte) (url string, reqs chan fakeCloudReq) {
|
func fakeCloudServer(t *testing.T, status int, body []byte) (url string, reqs chan fakeCloudReq) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
reqs = make(chan fakeCloudReq, 8)
|
reqs = make(chan fakeCloudReq, 8)
|
||||||
@@ -291,11 +306,11 @@ func fakeCloudServer(t *testing.T, status int, body []byte) (url string, reqs ch
|
|||||||
return ts.URL, reqs
|
return ts.URL, reqs
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSayCloudProviderMitFake: `talk "Text" --provider=elevenlabs` mit Key
|
// TestSayCloudProviderWithFake: `talk "text" --provider=elevenlabs` with a
|
||||||
// + Fake-Endpunkt und sink=null läuft mit Exit 0 durch — Synthese lief
|
// key, a fake endpoint and sink=null exits 0: synthesis ran (fake called,
|
||||||
// (Fake gerufen, korrekter Pfad inkl. neutraler Default-Stimme, Key im
|
// correct path with the neutral default voice, key in the header), playback
|
||||||
// Header), Wiedergabe verworfen.
|
// discarded.
|
||||||
func TestSayCloudProviderMitFake(t *testing.T) {
|
func TestSayCloudProviderWithFake(t *testing.T) {
|
||||||
url, reqs := fakeCloudServer(t, 200, []byte("\xff\xfb\x90\x00mp3"))
|
url, reqs := fakeCloudServer(t, 200, []byte("\xff\xfb\x90\x00mp3"))
|
||||||
setGetenv(t, map[string]string{
|
setGetenv(t, map[string]string{
|
||||||
"TALK_AUDIO_SINK": "null",
|
"TALK_AUDIO_SINK": "null",
|
||||||
@@ -306,26 +321,26 @@ func TestSayCloudProviderMitFake(t *testing.T) {
|
|||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"--provider=elevenlabs", "Test"}, &out, &errBuf)
|
code := runCLI([]string{"--provider=elevenlabs", "Test"}, &out, &errBuf)
|
||||||
if code != exitOK {
|
if code != exitOK {
|
||||||
t.Fatalf("talk --provider=elevenlabs (Fake): Exit-Code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
t.Fatalf("talk --provider=elevenlabs (fake): exit code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
||||||
}
|
}
|
||||||
select {
|
select {
|
||||||
case req := <-reqs:
|
case req := <-reqs:
|
||||||
if want := "/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM"; req.path != want {
|
if want := "/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM"; req.path != want {
|
||||||
t.Errorf("Pfad = %q, want %q (neutrales Default)", req.path, want)
|
t.Errorf("path = %q, want %q (neutral default)", req.path, want)
|
||||||
}
|
}
|
||||||
if req.apiKey != "cli-testkey" {
|
if req.apiKey != "cli-testkey" {
|
||||||
t.Errorf("xi-api-key = %q", req.apiKey)
|
t.Errorf("xi-api-key = %q", req.apiKey)
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
t.Error("Fake-Endpunkt wurde nicht gerufen")
|
t.Error("fake endpoint was not called")
|
||||||
}
|
}
|
||||||
if !strings.Contains(errBuf.String(), "verworfen (null sink)") {
|
if !strings.Contains(errBuf.String(), "discarded (null sink)") {
|
||||||
t.Errorf("stderr = %q, will Verwurf-Zeile", errBuf.String())
|
t.Errorf("stderr = %q, want the discard line", errBuf.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSayVoiceFlagAmCloudProvider: --voice landet im Request-Pfad.
|
// TestSayVoiceFlagAtCloudProvider: --voice lands in the request path.
|
||||||
func TestSayVoiceFlagAmCloudProvider(t *testing.T) {
|
func TestSayVoiceFlagAtCloudProvider(t *testing.T) {
|
||||||
url, reqs := fakeCloudServer(t, 200, []byte("\xff\xfb\x90\x00mp3"))
|
url, reqs := fakeCloudServer(t, 200, []byte("\xff\xfb\x90\x00mp3"))
|
||||||
setGetenv(t, map[string]string{
|
setGetenv(t, map[string]string{
|
||||||
"TALK_AUDIO_SINK": "null",
|
"TALK_AUDIO_SINK": "null",
|
||||||
@@ -334,43 +349,42 @@ func TestSayVoiceFlagAmCloudProvider(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
if code := runCLI([]string{"--provider=elevenlabs", "--voice=MeineStimme", "Test"}, &out, &errBuf); code != exitOK {
|
if code := runCLI([]string{"--provider=elevenlabs", "--voice=MyVoice", "Test"}, &out, &errBuf); code != exitOK {
|
||||||
t.Fatalf("Exit-Code = %d, stderr = %q", code, errBuf.String())
|
t.Fatalf("exit code = %d, stderr = %q", code, errBuf.String())
|
||||||
}
|
}
|
||||||
select {
|
select {
|
||||||
case req := <-reqs:
|
case req := <-reqs:
|
||||||
if want := "/v1/text-to-speech/MeineStimme"; req.path != want {
|
if want := "/v1/text-to-speech/MyVoice"; req.path != want {
|
||||||
t.Errorf("Pfad = %q, want %q", req.path, want)
|
t.Errorf("path = %q, want %q", req.path, want)
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
t.Error("Fake-Endpunkt wurde nicht gerufen")
|
t.Error("fake endpoint was not called")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSayCloudOhneKey: gepinnter Cloud-Provider ohne Key → klarer Fehler
|
// TestSayCloudWithoutKey: a pinned cloud provider without a key is a clear
|
||||||
// (Stufe nicht verfügbar, Exit 1).
|
// error (tier not available, exit 1).
|
||||||
func TestSayCloudOhneKey(t *testing.T) {
|
func TestSayCloudWithoutKey(t *testing.T) {
|
||||||
url, _ := fakeCloudServer(t, 200, []byte("x"))
|
url, _ := fakeCloudServer(t, 200, []byte("x"))
|
||||||
setGetenv(t, map[string]string{
|
setGetenv(t, map[string]string{
|
||||||
"TALK_AUDIO_SINK": "null",
|
"TALK_AUDIO_SINK": "null",
|
||||||
"TALK_ELEVENLABS_ENDPOINT": url, // Endpunkt, aber kein Key
|
"TALK_ELEVENLABS_ENDPOINT": url, // endpoint, but no key
|
||||||
})
|
})
|
||||||
|
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"--provider=elevenlabs", "Test"}, &out, &errBuf)
|
code := runCLI([]string{"--provider=elevenlabs", "Test"}, &out, &errBuf)
|
||||||
if code != exitFailure {
|
if code != exitFailure {
|
||||||
t.Fatalf("Exit-Code = %d, want %d", code, exitFailure)
|
t.Fatalf("exit code = %d, want %d", code, exitFailure)
|
||||||
}
|
}
|
||||||
if !strings.Contains(errBuf.String(), "nicht verfügbar") {
|
if !strings.Contains(errBuf.String(), "not available") {
|
||||||
t.Errorf("stderr = %q, will Verfügbarkeits-Hinweis", errBuf.String())
|
t.Errorf("stderr = %q, want an availability note", errBuf.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSayCloud500FaelltAufOsbuiltin: gepinnt wäre kurzfristig — hier ohne
|
// TestSayCloud500FallsBackToOsbuiltin: without a pin: elevenlabs (fake, 500)
|
||||||
// Pin: elevenlabs (Fake, 500) → openai (kein Key) → edge (tot) → osbuiltin
|
// → openai (no key) → edge (dead) → osbuiltin (fake espeak) yields the
|
||||||
// (fake espeak) liefert die Bytes. Der CLI-Ketten-Fallback ist end-to-end
|
// bytes. The CLI chain fallback is observable end to end via the env seam.
|
||||||
// über die Env-Seam beobachtbar.
|
func TestSayCloud500FallsBackToOsbuiltin(t *testing.T) {
|
||||||
func TestSayCloud500FaelltAufOsbuiltin(t *testing.T) {
|
|
||||||
url, _ := fakeCloudServer(t, 500, []byte("boom"))
|
url, _ := fakeCloudServer(t, 500, []byte("boom"))
|
||||||
seen := withFakeEspeak(t)
|
seen := withFakeEspeak(t)
|
||||||
setGetenv(t, map[string]string{
|
setGetenv(t, map[string]string{
|
||||||
@@ -380,22 +394,21 @@ func TestSayCloud500FaelltAufOsbuiltin(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"Ketten Test"}, &out, &errBuf)
|
code := runCLI([]string{"Chain test"}, &out, &errBuf)
|
||||||
if code != exitOK {
|
if code != exitOK {
|
||||||
t.Fatalf("talk mit 500-Cloud-Stufe: Exit-Code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
t.Fatalf("talk with a 500 cloud tier: exit code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
||||||
}
|
}
|
||||||
if _, err := os.Stat(seen); err != nil {
|
if _, err := os.Stat(seen); err != nil {
|
||||||
t.Errorf("fake espeak nicht gerufen (Kette nicht bis osbuiltin gefallen): %v", err)
|
t.Errorf("fake espeak not called (chain did not fall through to osbuiltin): %v", err)
|
||||||
}
|
}
|
||||||
if !strings.Contains(errBuf.String(), "500") || !strings.Contains(errBuf.String(), "Fallback") {
|
if !strings.Contains(errBuf.String(), "500") || !strings.Contains(errBuf.String(), "falling back") {
|
||||||
t.Errorf("stderr = %q, will sichtbaren 500-Fallback", errBuf.String())
|
t.Errorf("stderr = %q, want a visible 500 fallback", errBuf.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSayFlagNachDemText: `talk "Text" --provider=…` (Flag NACH dem Text,
|
// TestSayFlagAfterText: `talk "text" --provider=…` (flag AFTER the text)
|
||||||
// Abnahme-Aufrufform) pinnt den Provider — nur die gepinnte Stufe wird
|
// pins the provider: only the pinned tier is asked.
|
||||||
// angefragt.
|
func TestSayFlagAfterText(t *testing.T) {
|
||||||
func TestSayFlagNachDemText(t *testing.T) {
|
|
||||||
url, reqs := fakeCloudServer(t, 200, []byte("\xff\xfb\x90\x00mp3"))
|
url, reqs := fakeCloudServer(t, 200, []byte("\xff\xfb\x90\x00mp3"))
|
||||||
setGetenv(t, map[string]string{
|
setGetenv(t, map[string]string{
|
||||||
"TALK_AUDIO_SINK": "null",
|
"TALK_AUDIO_SINK": "null",
|
||||||
@@ -404,30 +417,30 @@ func TestSayFlagNachDemText(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"Test ansage", "--provider=elevenlabs"}, &out, &errBuf)
|
code := runCLI([]string{"Test announcement", "--provider=elevenlabs"}, &out, &errBuf)
|
||||||
if code != exitOK {
|
if code != exitOK {
|
||||||
t.Fatalf("talk \"Text\" --provider=elevenlabs: Exit-Code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
t.Fatalf("talk \"text\" --provider=elevenlabs: exit code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
||||||
}
|
}
|
||||||
select {
|
select {
|
||||||
case req := <-reqs:
|
case req := <-reqs:
|
||||||
if !strings.Contains(req.path, "/v1/text-to-speech/") {
|
if !strings.Contains(req.path, "/v1/text-to-speech/") {
|
||||||
t.Errorf("Pfad = %q, want TTS-Pfad", req.path)
|
t.Errorf("path = %q, want a TTS path", req.path)
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
t.Error("Fake-Endpunkt wurde nicht gerufen")
|
t.Error("fake endpoint was not called")
|
||||||
}
|
}
|
||||||
// Zwei Argumente mit verteilten Flags: Text bleibt vollständig.
|
// Two arguments with interspersed flags: the text stays complete.
|
||||||
seen := withFakeEspeak(t)
|
seen := withFakeEspeak(t)
|
||||||
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
||||||
code = runCLI([]string{"Erster", "--lang=en", "zweiter Teil"}, &out, &errBuf)
|
code = runCLI([]string{"First", "--lang=en", "second part"}, &out, &errBuf)
|
||||||
if code != exitOK {
|
if code != exitOK {
|
||||||
t.Fatalf("talk Erster --lang=en zweiter Teil: Exit-Code = %d, stderr = %q", code, errBuf.String())
|
t.Fatalf("talk First --lang=en second part: exit code = %d, stderr = %q", code, errBuf.String())
|
||||||
}
|
}
|
||||||
args, err := os.ReadFile(seen)
|
args, err := os.ReadFile(seen)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("fake espeak nicht gerufen: %v", err)
|
t.Fatalf("fake espeak not called: %v", err)
|
||||||
}
|
}
|
||||||
if got := strings.TrimSpace(string(args)); got != "-v en --stdout Erster zweiter Teil" {
|
if got := strings.TrimSpace(string(args)); got != "-v en --stdout First second part" {
|
||||||
t.Errorf("espeak ARGS = %q, want %q", got, "-v en --stdout Erster zweiter Teil")
|
t.Errorf("espeak ARGS = %q, want %q", got, "-v en --stdout First second part")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+148
-106
@@ -21,64 +21,65 @@ import (
|
|||||||
"code.m3ta.dev/m3tam3re/talk/internal/speak"
|
"code.m3ta.dev/m3tam3re/talk/internal/speak"
|
||||||
)
|
)
|
||||||
|
|
||||||
// setupInteractive entscheidet, ob der Wizard Fragen stellen darf (stdin
|
// setupInteractive decides whether the wizard may ask questions (stdin is a
|
||||||
// ist ein Terminal). Tests überschreiben die Seam und füttern Antworten
|
// terminal). Tests override the seam and feed answers via stdin.
|
||||||
// über stdin.
|
|
||||||
var setupInteractive = isCharDevice
|
var setupInteractive = isCharDevice
|
||||||
|
|
||||||
// setupSample ist der Probehör-Satz je Sprache.
|
// setupSample is the preview sentence per language.
|
||||||
var setupSample = map[string]string{
|
var setupSample = map[string]string{
|
||||||
"de": "Hallo, so klinge ich. Build fertig.",
|
"de": "Hallo, so klinge ich. Build fertig.",
|
||||||
"en": "Hello, this is how I sound. Build finished.",
|
"en": "Hello, this is how I sound. Build finished.",
|
||||||
}
|
}
|
||||||
|
|
||||||
// runSetup implementiert `talk setup`: wenige Fragen, dann config.toml.
|
// runSetup implements `talk setup`: a few questions, then config.toml.
|
||||||
//
|
//
|
||||||
// 1. Daemon/Version, Audio.
|
// 1. Daemon, audio.
|
||||||
// 2. Keys: gefunden → Premium; keiner → Erklärung, dass die kostenlose
|
// 2. Keys: found → premium; none → explanation that the free Edge voice
|
||||||
// Edge-Stimme (Internet) bzw. die OS-Stimme ohnehin funktionieren.
|
// (internet) or the OS voice work regardless.
|
||||||
// 3. Stimme je Sprache (de, en) für die aktive Stufe: Nummer aus dem
|
// 3. Language: which language talk assumes when it cannot tell (and speaks
|
||||||
// Katalog wählen, probehören, übernehmen.
|
// its own announcements in).
|
||||||
// 4. Ruhezeit (optional).
|
// 4. Voice per language (de, en) for the active tier: pick a catalog
|
||||||
// 5. config.toml schreiben (bestehende zusammenführen, .bak), Test-Satz.
|
// number, preview, accept.
|
||||||
|
// 5. Quiet hours (optional).
|
||||||
|
// 6. Write config.toml (merge an existing one, .bak), test sentence.
|
||||||
//
|
//
|
||||||
// Ohne Terminal (Pipe, Agent) stellt setup keine Fragen: Es zeigt die
|
// Without a terminal (pipe, agent) setup asks nothing: it shows the
|
||||||
// wirksame Konfiguration und endet mit Exit 0 — nichts bricht, nichts
|
// effective configuration and exits 0; nothing breaks, nothing waits.
|
||||||
// wartet. Abbruch mit Ctrl-C oder leerer Eingabe bei „q": nichts
|
// Abort with Ctrl-C or "q": nothing half-written (the file is written only
|
||||||
// halbfertig geschrieben (geschrieben wird erst ganz am Ende).
|
// at the very end).
|
||||||
func runSetup(args []string, _ *sayOptions, stdin io.Reader, stdout, stderr io.Writer) int {
|
func runSetup(args []string, _ *sayOptions, stdin io.Reader, stdout, stderr io.Writer) int {
|
||||||
if len(args) > 0 {
|
if len(args) > 0 {
|
||||||
fmt.Fprintln(stderr, "talk setup: keine Argumente erwartet")
|
fmt.Fprintln(stderr, "talk setup: no arguments expected")
|
||||||
return exitUsage
|
return exitUsage
|
||||||
}
|
}
|
||||||
cfg, err := config.Load(config.Options{Getenv: getenv})
|
cfg, err := config.Load(config.Options{Getenv: getenv})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(stderr, "talk setup: %v\nBitte zuerst die Config-Datei reparieren oder umbenennen.\n", err)
|
fmt.Fprintf(stderr, "talk setup: %v\nPlease fix or rename the config file first.\n", err)
|
||||||
return exitFailure
|
return exitFailure
|
||||||
}
|
}
|
||||||
path, perr := config.Path(getenv)
|
path, perr := config.Path(getenv)
|
||||||
if perr != nil {
|
if perr != nil {
|
||||||
fmt.Fprintf(stderr, "talk setup: %v — ohne Config-Verzeichnis kann setup nichts speichern\n", perr)
|
fmt.Fprintf(stderr, "talk setup: %v; without a config directory setup cannot save anything\n", perr)
|
||||||
return exitFailure
|
return exitFailure
|
||||||
}
|
}
|
||||||
|
|
||||||
if !setupInteractive(stdin) {
|
if !setupInteractive(stdin) {
|
||||||
fmt.Fprintln(stdout, "talk setup braucht ein Terminal, um Fragen zu stellen. Wirksame Konfiguration:")
|
fmt.Fprintln(stdout, "talk setup needs a terminal to ask questions. Effective configuration:")
|
||||||
printEffective(stdout, cfg, path)
|
printEffective(stdout, cfg, path)
|
||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
|
|
||||||
w := &wizard{in: bufio.NewReader(stdin), out: stdout, err: stderr, cfg: cfg}
|
w := &wizard{in: bufio.NewReader(stdin), out: stdout, err: stderr, cfg: cfg}
|
||||||
fmt.Fprintln(stdout, "talk einrichten — ein paar Fragen, Enter übernimmt den Vorschlag in [Klammern], q bricht ab.")
|
fmt.Fprintln(stdout, "Setting up talk: a few questions. Enter takes the suggestion in [brackets], q aborts.")
|
||||||
fmt.Fprintln(stdout)
|
fmt.Fprintln(stdout)
|
||||||
|
|
||||||
// 1. Umgebung
|
// 1. Environment
|
||||||
fmt.Fprintf(stdout, "Audio-Ausgabe: %s\n", audioSummary(cfg))
|
fmt.Fprintf(stdout, "Audio output: %s\n", audioSummary(cfg))
|
||||||
client := api.NewClient(cfg.Server.Port)
|
client := api.NewClient(cfg.Server.Port)
|
||||||
if daemonAlive(client, daemonProbeTimeout) {
|
if daemonAlive(client, daemonProbeTimeout) {
|
||||||
fmt.Fprintf(stdout, "Daemon: läuft unter %s\n", client.BaseURL)
|
fmt.Fprintf(stdout, "Daemon: running at %s\n", client.BaseURL)
|
||||||
} else {
|
} else {
|
||||||
fmt.Fprintln(stdout, "Daemon: startet beim ersten Sprechbefehl von selbst")
|
fmt.Fprintln(stdout, "Daemon: starts by itself on the first speak command")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Keys
|
// 2. Keys
|
||||||
@@ -91,83 +92,98 @@ func runSetup(args []string, _ *sayOptions, stdin io.Reader, stdout, stderr io.W
|
|||||||
fmt.Fprintln(stdout)
|
fmt.Fprintln(stdout)
|
||||||
switch {
|
switch {
|
||||||
case getenv(provider.EnvElevenLabsKey) != "":
|
case getenv(provider.EnvElevenLabsKey) != "":
|
||||||
fmt.Fprintln(stdout, "Stimmen: ElevenLabs-Key gefunden (TALK_ELEVENLABS_KEY) — Premium-Stimme.")
|
fmt.Fprintln(stdout, "Voices: ElevenLabs key found (TALK_ELEVENLABS_KEY); premium voice.")
|
||||||
case getenv(provider.EnvOpenAIKey) != "":
|
case getenv(provider.EnvOpenAIKey) != "":
|
||||||
fmt.Fprintln(stdout, "Stimmen: OpenAI-Key gefunden (TALK_OPENAI_KEY).")
|
fmt.Fprintln(stdout, "Voices: OpenAI key found (TALK_OPENAI_KEY).")
|
||||||
default:
|
default:
|
||||||
fmt.Fprintln(stdout, "Stimmen: kein Key gefunden — das ist ok. talk nutzt die kostenlose Edge-Stimme von")
|
fmt.Fprintln(stdout, "Voices: no key found; that is fine. talk uses Microsoft's free Edge voice")
|
||||||
fmt.Fprintln(stdout, " Microsoft (braucht Internet) und sonst die Stimme deines Betriebssystems.")
|
fmt.Fprintln(stdout, " (needs internet) and otherwise your operating system's voice.")
|
||||||
fmt.Fprintln(stdout, " Für Premium-Stimmen später TALK_ELEVENLABS_KEY oder TALK_OPENAI_KEY als")
|
fmt.Fprintln(stdout, " For premium voices, set TALK_ELEVENLABS_KEY or TALK_OPENAI_KEY as an")
|
||||||
fmt.Fprintln(stdout, " Umgebungsvariable setzen (nie in die config.toml).")
|
fmt.Fprintln(stdout, " environment variable later (never in config.toml).")
|
||||||
}
|
}
|
||||||
if active == speak.NoProvider {
|
if active == speak.NoProvider {
|
||||||
fmt.Fprintln(stderr, "talk setup: derzeit ist keine Stimme verfügbar — `talk doctor` zeigt, was fehlt. Einstellungen werden trotzdem gespeichert.")
|
fmt.Fprintln(stderr, "talk setup: no voice is available right now; `talk doctor` shows what is missing. Settings are saved anyway.")
|
||||||
} else {
|
} else {
|
||||||
fmt.Fprintf(stdout, "Aktive Stufe: %s\n", active)
|
fmt.Fprintf(stdout, "Active tier: %s\n", active)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Stimmen
|
// 3. Language
|
||||||
voices := map[string]string{}
|
|
||||||
if active != speak.NoProvider && active != "osbuiltin" {
|
|
||||||
for _, lang := range []string{"de", "en"} {
|
|
||||||
id, ok := w.chooseVoice(engine, active, lang)
|
|
||||||
if !ok {
|
|
||||||
fmt.Fprintln(stdout, "Abgebrochen — nichts geschrieben.")
|
|
||||||
return exitOK
|
|
||||||
}
|
|
||||||
if id != "" {
|
|
||||||
voices[lang] = id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if active == "osbuiltin" {
|
|
||||||
fmt.Fprintln(stdout, "\nDie OS-Stimme wählt dein Betriebssystem; es gibt hier nichts einzustellen.")
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. Ruhezeit
|
|
||||||
fmt.Fprintln(stdout)
|
fmt.Fprintln(stdout)
|
||||||
quiet, ok := w.askQuietHours(cfg.QuietHours)
|
lang, ok := w.askLang(cfg.Lang)
|
||||||
if !ok {
|
if !ok {
|
||||||
fmt.Fprintln(stdout, "Abgebrochen — nichts geschrieben.")
|
fmt.Fprintln(stdout, "Aborted; nothing written.")
|
||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. Schreiben
|
// 4. Voices
|
||||||
changes := map[string]any{}
|
voices := map[string]string{}
|
||||||
|
if active != speak.NoProvider && active != "osbuiltin" {
|
||||||
|
for _, l := range []string{lang, otherLang(lang)} {
|
||||||
|
id, ok := w.chooseVoice(engine, active, l)
|
||||||
|
if !ok {
|
||||||
|
fmt.Fprintln(stdout, "Aborted; nothing written.")
|
||||||
|
return exitOK
|
||||||
|
}
|
||||||
|
if id != "" {
|
||||||
|
voices[l] = id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if active == "osbuiltin" {
|
||||||
|
fmt.Fprintln(stdout, "\nThe OS voice is chosen by your operating system; nothing to set here.")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Quiet hours
|
||||||
|
fmt.Fprintln(stdout)
|
||||||
|
quiet, ok := w.askQuietHours(cfg.QuietHours)
|
||||||
|
if !ok {
|
||||||
|
fmt.Fprintln(stdout, "Aborted; nothing written.")
|
||||||
|
return exitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. Write
|
||||||
|
changes := map[string]any{"lang": lang, "quiet_hours": quiet}
|
||||||
if len(voices) > 0 {
|
if len(voices) > 0 {
|
||||||
changes["voice"] = map[string]any{active: toAny(voices)}
|
changes["voice"] = map[string]any{active: toAny(voices)}
|
||||||
}
|
}
|
||||||
changes["quiet_hours"] = quiet
|
|
||||||
backup, err := writeConfig(path, changes)
|
backup, err := writeConfig(path, changes)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(stderr, "talk setup: config schreiben: %v\n", err)
|
fmt.Fprintf(stderr, "talk setup: writing config: %v\n", err)
|
||||||
return exitFailure
|
return exitFailure
|
||||||
}
|
}
|
||||||
fmt.Fprintln(stdout)
|
fmt.Fprintln(stdout)
|
||||||
fmt.Fprintf(stdout, "Gespeichert: %s\n", path)
|
fmt.Fprintf(stdout, "Saved: %s\n", path)
|
||||||
if backup != "" {
|
if backup != "" {
|
||||||
fmt.Fprintf(stdout, "Sicherung: %s\n", backup)
|
fmt.Fprintf(stdout, "Backup: %s\n", backup)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Abschluss: Testsatz über die neue Config.
|
// Finish: a test sentence through the new config.
|
||||||
if active != speak.NoProvider {
|
if active != speak.NoProvider {
|
||||||
fmt.Fprintln(stdout, "\nTestsatz …")
|
fmt.Fprintln(stdout, "\nTest sentence …")
|
||||||
if cfg2, err := config.Load(config.Options{Getenv: getenv}); err == nil {
|
if cfg2, err := config.Load(config.Options{Getenv: getenv}); err == nil {
|
||||||
if eng2, err := speak.New(cfg2, getenv, io.Discard); err == nil {
|
if eng2, err := speak.New(cfg2, getenv, io.Discard); err == nil {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
if out, err := eng2.Speak(ctx, speak.Request{Text: testPhrase["de"], Lang: "de"}); err != nil {
|
if out, err := eng2.Speak(ctx, speak.Request{Text: testPhrase[lang], Lang: lang}); err != nil {
|
||||||
fmt.Fprintf(stderr, "talk setup: Testsatz fehlgeschlagen: %v (siehe talk doctor)\n", err)
|
fmt.Fprintf(stderr, "talk setup: test sentence failed: %v (see talk doctor)\n", err)
|
||||||
} else {
|
} else {
|
||||||
fmt.Fprintf(stdout, "Gesprochen über %s.\n", out.Provider)
|
fmt.Fprintf(stdout, "Spoken via %s.\n", out.Provider)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fmt.Fprintln(stdout, "\nFertig. Probiere: talk \"Hallo Welt\" — Status: talk status — Stumm: talk mute")
|
fmt.Fprintln(stdout, "\nDone. Try: talk \"Hello world\" / status: talk status / silence: talk mute")
|
||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
|
|
||||||
// wizard hält Ein-/Ausgabe des Setups.
|
// otherLang returns the other supported language.
|
||||||
|
func otherLang(lang string) string {
|
||||||
|
if lang == "de" {
|
||||||
|
return "en"
|
||||||
|
}
|
||||||
|
return "de"
|
||||||
|
}
|
||||||
|
|
||||||
|
// wizard holds the setup's input and output.
|
||||||
type wizard struct {
|
type wizard struct {
|
||||||
in *bufio.Reader
|
in *bufio.Reader
|
||||||
out io.Writer
|
out io.Writer
|
||||||
@@ -175,8 +191,8 @@ type wizard struct {
|
|||||||
cfg config.Config
|
cfg config.Config
|
||||||
}
|
}
|
||||||
|
|
||||||
// ask stellt eine Frage mit Vorschlag; Enter liefert den Vorschlag, „q"
|
// ask asks a question with a suggestion; Enter returns the suggestion, "q"
|
||||||
// bricht ab (ok=false). EOF zählt als Abbruch.
|
// aborts (ok=false). EOF counts as abort.
|
||||||
func (w *wizard) ask(prompt, def string) (string, bool) {
|
func (w *wizard) ask(prompt, def string) (string, bool) {
|
||||||
if def != "" {
|
if def != "" {
|
||||||
fmt.Fprintf(w.out, "%s [%s]: ", prompt, def)
|
fmt.Fprintf(w.out, "%s [%s]: ", prompt, def)
|
||||||
@@ -197,12 +213,27 @@ func (w *wizard) ask(prompt, def string) (string, bool) {
|
|||||||
return line, true
|
return line, true
|
||||||
}
|
}
|
||||||
|
|
||||||
// chooseVoice lässt eine Stimme für provider/lang wählen: nummerierte
|
// askLang asks for the fallback language (de | en).
|
||||||
// Katalog-Liste, aktueller Default markiert; Probehören; übernehmen oder
|
func (w *wizard) askLang(current string) (string, bool) {
|
||||||
// neu wählen. Rückgabe: gewählte ID ("" = Default behalten) und ok=false
|
fmt.Fprintln(w.out, "Language: talk detects German and English automatically. Which one should it assume when it cannot tell?")
|
||||||
// bei Abbruch.
|
for {
|
||||||
|
answer, ok := w.ask("Language (de/en)", current)
|
||||||
|
if !ok {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
answer = strings.ToLower(answer)
|
||||||
|
if answer == "de" || answer == "en" {
|
||||||
|
return answer, true
|
||||||
|
}
|
||||||
|
fmt.Fprintln(w.out, "Please answer de or en.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// chooseVoice lets the user pick a voice for provider/lang: numbered catalog
|
||||||
|
// list with the current default marked; preview; accept or choose again.
|
||||||
|
// Returns the chosen ID ("" = keep the default) and ok=false on abort.
|
||||||
func (w *wizard) chooseVoice(engine *speak.Engine, prov, lang string) (string, bool) {
|
func (w *wizard) chooseVoice(engine *speak.Engine, prov, lang string) (string, bool) {
|
||||||
langName := map[string]string{"de": "Deutsch", "en": "Englisch"}[lang]
|
langName := map[string]string{"de": "German", "en": "English"}[lang]
|
||||||
current := provider.DefaultVoice(prov, lang, w.cfg.Voice)
|
current := provider.DefaultVoice(prov, lang, w.cfg.Voice)
|
||||||
var list []provider.Voice
|
var list []provider.Voice
|
||||||
for _, v := range provider.Catalog() {
|
for _, v := range provider.Catalog() {
|
||||||
@@ -210,7 +241,7 @@ func (w *wizard) chooseVoice(engine *speak.Engine, prov, lang string) (string, b
|
|||||||
list = append(list, v)
|
list = append(list, v)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fmt.Fprintf(w.out, "\nStimme für %s (%s):\n", langName, prov)
|
fmt.Fprintf(w.out, "\nVoice for %s (%s):\n", langName, prov)
|
||||||
defIdx := ""
|
defIdx := ""
|
||||||
for i, v := range list {
|
for i, v := range list {
|
||||||
mark := " "
|
mark := " "
|
||||||
@@ -221,17 +252,17 @@ func (w *wizard) chooseVoice(engine *speak.Engine, prov, lang string) (string, b
|
|||||||
fmt.Fprintf(w.out, " %s %d) %s\n", mark, i+1, v.Name)
|
fmt.Fprintf(w.out, " %s %d) %s\n", mark, i+1, v.Name)
|
||||||
}
|
}
|
||||||
if defIdx == "" && current != "" {
|
if defIdx == "" && current != "" {
|
||||||
fmt.Fprintf(w.out, " * aktuell: %s (aus config.toml)\n", current)
|
fmt.Fprintf(w.out, " * current: %s (from config.toml)\n", current)
|
||||||
}
|
}
|
||||||
for {
|
for {
|
||||||
answer, ok := w.ask("Nummer wählen, oder eine Voice-ID eintippen", defIdx)
|
answer, ok := w.ask("Pick a number, or type a voice ID", defIdx)
|
||||||
if !ok {
|
if !ok {
|
||||||
return "", false
|
return "", false
|
||||||
}
|
}
|
||||||
id := answer
|
id := answer
|
||||||
if n, err := strconv.Atoi(answer); err == nil {
|
if n, err := strconv.Atoi(answer); err == nil {
|
||||||
if n < 1 || n > len(list) {
|
if n < 1 || n > len(list) {
|
||||||
fmt.Fprintf(w.out, "Bitte 1–%d.\n", len(list))
|
fmt.Fprintf(w.out, "Please pick 1 to %d.\n", len(list))
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
id = list[n-1].ID
|
id = list[n-1].ID
|
||||||
@@ -239,63 +270,72 @@ func (w *wizard) chooseVoice(engine *speak.Engine, prov, lang string) (string, b
|
|||||||
if id == "" {
|
if id == "" {
|
||||||
return "", true
|
return "", true
|
||||||
}
|
}
|
||||||
hear, ok := w.ask("Probehören?", "J")
|
hear, ok := w.ask("Preview?", "Y")
|
||||||
if !ok {
|
if !ok {
|
||||||
return "", false
|
return "", false
|
||||||
}
|
}
|
||||||
if strings.EqualFold(hear, "j") || strings.EqualFold(hear, "ja") || strings.EqualFold(hear, "y") {
|
if isYes(hear) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||||
_, err := engine.Speak(ctx, speak.Request{Text: setupSample[lang], Lang: lang, Provider: prov, Voice: id})
|
_, err := engine.Speak(ctx, speak.Request{Text: setupSample[lang], Lang: lang, Provider: prov, Voice: id})
|
||||||
cancel()
|
cancel()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(w.err, "Probehören fehlgeschlagen: %v\n", err)
|
fmt.Fprintf(w.err, "preview failed: %v\n", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
take, ok := w.ask("Übernehmen?", "J")
|
take, ok := w.ask("Use this voice?", "Y")
|
||||||
if !ok {
|
if !ok {
|
||||||
return "", false
|
return "", false
|
||||||
}
|
}
|
||||||
if strings.EqualFold(take, "j") || strings.EqualFold(take, "ja") || strings.EqualFold(take, "y") {
|
if isYes(take) {
|
||||||
if id == current {
|
if id == current {
|
||||||
return "", true // Default behalten — nichts in die Datei schreiben
|
return "", true // keep the default: nothing to write
|
||||||
}
|
}
|
||||||
return id, true
|
return id, true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// askQuietHours fragt das Ruhezeit-Fenster ab (leer = keine).
|
// isYes accepts y/yes/j/ja in any case.
|
||||||
|
func isYes(s string) bool {
|
||||||
|
switch strings.ToLower(s) {
|
||||||
|
case "y", "yes", "j", "ja":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// askQuietHours asks for the quiet window (empty = none).
|
||||||
func (w *wizard) askQuietHours(current string) (string, bool) {
|
func (w *wizard) askQuietHours(current string) (string, bool) {
|
||||||
fmt.Fprintln(w.out, "Ruhezeit: In diesem Fenster bleibt talk still (z. B. 22:00-07:00). Leer lassen = keine Ruhezeit.")
|
fmt.Fprintln(w.out, "Quiet hours: talk stays silent in this window (for example 22:00-07:00). Leave empty for none.")
|
||||||
def := current
|
def := current
|
||||||
if def == "" {
|
if def == "" {
|
||||||
def = "keine"
|
def = "none"
|
||||||
}
|
}
|
||||||
for {
|
for {
|
||||||
answer, ok := w.ask("Ruhezeit", def)
|
answer, ok := w.ask("Quiet hours", def)
|
||||||
if !ok {
|
if !ok {
|
||||||
return "", false
|
return "", false
|
||||||
}
|
}
|
||||||
if answer == "keine" || answer == "-" || answer == "aus" {
|
if answer == "none" || answer == "-" || answer == "off" {
|
||||||
return "", true
|
return "", true
|
||||||
}
|
}
|
||||||
if _, err := queue.ParseQuietHours(answer); err != nil {
|
if _, err := queue.ParseQuietHours(answer); err != nil {
|
||||||
fmt.Fprintf(w.out, "Format HH:MM-HH:MM, z. B. 22:00-07:00 (%v).\n", err)
|
fmt.Fprintf(w.out, "Format HH:MM-HH:MM, for example 22:00-07:00 (%v).\n", err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
return answer, true
|
return answer, true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeConfig führt changes in die bestehende config.toml ein (fehlende
|
// writeConfig merges changes into the existing config.toml (missing file:
|
||||||
// Datei: neu) und schreibt sie atomar; eine vorhandene Datei wird vorher
|
// new) and writes it atomically; an existing file is backed up as .bak
|
||||||
// als .bak gesichert. Verschachtelte Tabellen (voice.<provider>) werden
|
// first. Nested tables (voice.<provider>) are merged, not replaced. Returns
|
||||||
// zusammengeführt, nicht ersetzt. Rückgabe: Pfad der Sicherung oder "".
|
// the backup path or "".
|
||||||
func writeConfig(path string, changes map[string]any) (backup string, err error) {
|
func writeConfig(path string, changes map[string]any) (backup string, err error) {
|
||||||
existing := map[string]any{}
|
existing := map[string]any{}
|
||||||
if raw, rerr := os.ReadFile(path); rerr == nil {
|
if raw, rerr := os.ReadFile(path); rerr == nil {
|
||||||
if _, derr := toml.Decode(string(raw), &existing); derr != nil {
|
if _, derr := toml.Decode(string(raw), &existing); derr != nil {
|
||||||
return "", fmt.Errorf("bestehende %s unlesbar: %w", path, derr)
|
return "", fmt.Errorf("existing %s unreadable: %w", path, derr)
|
||||||
}
|
}
|
||||||
backup = path + ".bak"
|
backup = path + ".bak"
|
||||||
if werr := os.WriteFile(backup, raw, 0o644); werr != nil {
|
if werr := os.WriteFile(backup, raw, 0o644); werr != nil {
|
||||||
@@ -305,12 +345,12 @@ func writeConfig(path string, changes map[string]any) (backup string, err error)
|
|||||||
return "", rerr
|
return "", rerr
|
||||||
}
|
}
|
||||||
mergeInto(existing, changes)
|
mergeInto(existing, changes)
|
||||||
// Leere Ruhezeit heißt: Schlüssel raus, statt "" zu schreiben.
|
// Empty quiet hours means: drop the key rather than writing "".
|
||||||
if v, ok := existing["quiet_hours"]; ok && v == "" {
|
if v, ok := existing["quiet_hours"]; ok && v == "" {
|
||||||
delete(existing, "quiet_hours")
|
delete(existing, "quiet_hours")
|
||||||
}
|
}
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
buf.WriteString("# talk — geschrieben von `talk setup`. Keys gehören NICHT hierher (TALK_*-Umgebungsvariablen).\n\n")
|
buf.WriteString("# talk: written by `talk setup`. Keys do NOT belong here (TALK_* environment variables).\n\n")
|
||||||
if err := toml.NewEncoder(&buf).Encode(existing); err != nil {
|
if err := toml.NewEncoder(&buf).Encode(existing); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
@@ -328,7 +368,7 @@ func writeConfig(path string, changes map[string]any) (backup string, err error)
|
|||||||
return backup, nil
|
return backup, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// mergeInto schreibt src rekursiv in dst (Tabellen zusammenführen).
|
// mergeInto writes src recursively into dst (merging tables).
|
||||||
func mergeInto(dst, src map[string]any) {
|
func mergeInto(dst, src map[string]any) {
|
||||||
for k, v := range src {
|
for k, v := range src {
|
||||||
if sv, ok := v.(map[string]any); ok {
|
if sv, ok := v.(map[string]any); ok {
|
||||||
@@ -349,27 +389,29 @@ func toAny(m map[string]string) map[string]any {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
// printEffective zeigt die wirksame Konfiguration (Nicht-Terminal-Pfad).
|
// printEffective shows the effective configuration (non-terminal path).
|
||||||
func printEffective(w io.Writer, cfg config.Config, path string) {
|
func printEffective(w io.Writer, cfg config.Config, path string) {
|
||||||
fmt.Fprintf(w, " config: %s\n", path)
|
fmt.Fprintf(w, " config: %s\n", path)
|
||||||
fmt.Fprintf(w, " audio: %s\n", audioSummary(cfg))
|
fmt.Fprintf(w, " audio: %s\n", audioSummary(cfg))
|
||||||
fmt.Fprintf(w, " provider: %s\n", orDefault(cfg.Provider, "Kette "+strings.Join(provider.DefaultOrder, " → ")))
|
fmt.Fprintf(w, " language: %s (fallback)\n", cfg.Lang)
|
||||||
|
fmt.Fprintf(w, " provider: %s\n", orDefault(cfg.Provider, "chain "+strings.Join(provider.DefaultOrder, " → ")))
|
||||||
for _, p := range provider.DefaultOrder {
|
for _, p := range provider.DefaultOrder {
|
||||||
for _, lang := range []string{"de", "en"} {
|
for _, lang := range []string{"de", "en"} {
|
||||||
if id := cfg.Voice[p][lang]; id != "" {
|
if id := cfg.Voice[p][lang]; id != "" {
|
||||||
fmt.Fprintf(w, " voice: %s/%s = %s\n", p, lang, id)
|
fmt.Fprintf(w, " voice: %s/%s = %s\n", p, lang, id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fmt.Fprintf(w, " ruhezeit: %s\n", orDefault(cfg.QuietHours, "keine"))
|
fmt.Fprintf(w, " quiet hours: %s\n", orDefault(cfg.QuietHours, "none"))
|
||||||
fmt.Fprintf(w, " autostart: %v\n", cfg.Daemon.Autostart)
|
fmt.Fprintf(w, " autostart: %v\n", cfg.Daemon.Autostart)
|
||||||
|
fmt.Fprintf(w, " notify: %v (desktop notification per announcement)\n", cfg.Notify.OnSpeak)
|
||||||
}
|
}
|
||||||
|
|
||||||
func audioSummary(cfg config.Config) string {
|
func audioSummary(cfg config.Config) string {
|
||||||
if cfg.Audio.Sink == config.SinkNull {
|
if cfg.Audio.Sink == config.SinkNull {
|
||||||
return "null (kein Ton — CI/Server)"
|
return "null (no sound; CI/servers)"
|
||||||
}
|
}
|
||||||
return "eingebaute Wiedergabe (oto)"
|
return "built-in playback (oto)"
|
||||||
}
|
}
|
||||||
|
|
||||||
func orDefault(v, def string) string {
|
func orDefault(v, def string) string {
|
||||||
|
|||||||
+47
-43
@@ -16,9 +16,9 @@ import (
|
|||||||
|
|
||||||
func readFile(path string) ([]byte, error) { return os.ReadFile(path) }
|
func readFile(path string) ([]byte, error) { return os.ReadFile(path) }
|
||||||
|
|
||||||
// setupEnv stellt den Wizard auf „interaktiv“ und pinnt die Kette auf einen
|
// setupEnv makes the wizard "interactive" and pins the chain to a fake
|
||||||
// Fake-ElevenLabs-Endpunkt (sink null) — Probehören und Testsatz laufen
|
// ElevenLabs endpoint (sink null): preview and test sentence hit the fake.
|
||||||
// gegen den Fake. Rückgabe: Zähler der Synthese-Aufrufe.
|
// Returns the counter of synthesis calls.
|
||||||
func setupEnv(t *testing.T, root string, extra map[string]string) *atomic.Int32 {
|
func setupEnv(t *testing.T, root string, extra map[string]string) *atomic.Int32 {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
var calls atomic.Int32
|
var calls atomic.Int32
|
||||||
@@ -44,52 +44,56 @@ func setupEnv(t *testing.T, root string, extra map[string]string) *atomic.Int32
|
|||||||
return &calls
|
return &calls
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSetupSchreibtConfig: Antworten über stdin — Stimme 2 für Deutsch
|
// TestSetupWritesConfig: answers via stdin (language en; voice 2 for
|
||||||
// (probehören, übernehmen), Englisch Default behalten, Ruhezeit setzen —
|
// English, preview, accept; German keeps the default; quiet hours) yield a
|
||||||
// ergeben eine config.toml mit genau diesen Werten; Probehören und
|
// config.toml with exactly those values; preview and test sentence hit the
|
||||||
// Testsatz treffen den Fake.
|
// fake.
|
||||||
func TestSetupSchreibtConfig(t *testing.T) {
|
func TestSetupWritesConfig(t *testing.T) {
|
||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
calls := setupEnv(t, root, nil)
|
calls := setupEnv(t, root, nil)
|
||||||
stdin := strings.NewReader("2\nj\nj\n\nn\nj\n22:00-07:00\n")
|
stdin := strings.NewReader("en\n2\ny\ny\n\nn\ny\n22:00-07:00\n")
|
||||||
|
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := run([]string{"setup"}, stdin, &out, &errBuf)
|
code := run([]string{"setup"}, stdin, &out, &errBuf)
|
||||||
if code != exitOK {
|
if code != exitOK {
|
||||||
t.Fatalf("talk setup: Exit %d\nstdout: %s\nstderr: %s", code, out.String(), errBuf.String())
|
t.Fatalf("talk setup: exit %d\nstdout: %s\nstderr: %s", code, out.String(), errBuf.String())
|
||||||
}
|
}
|
||||||
path := filepath.Join(root, "talk", "config.toml")
|
path := filepath.Join(root, "talk", "config.toml")
|
||||||
var got struct {
|
var got struct {
|
||||||
|
Lang string `toml:"lang"`
|
||||||
QuietHours string `toml:"quiet_hours"`
|
QuietHours string `toml:"quiet_hours"`
|
||||||
Voice map[string]map[string]string `toml:"voice"`
|
Voice map[string]map[string]string `toml:"voice"`
|
||||||
}
|
}
|
||||||
if _, err := toml.DecodeFile(path, &got); err != nil {
|
if _, err := toml.DecodeFile(path, &got); err != nil {
|
||||||
t.Fatalf("config lesen: %v", err)
|
t.Fatalf("reading config: %v", err)
|
||||||
|
}
|
||||||
|
if got.Lang != "en" {
|
||||||
|
t.Errorf("lang = %q, want en", got.Lang)
|
||||||
}
|
}
|
||||||
if got.QuietHours != "22:00-07:00" {
|
if got.QuietHours != "22:00-07:00" {
|
||||||
t.Errorf("quiet_hours = %q", got.QuietHours)
|
t.Errorf("quiet_hours = %q", got.QuietHours)
|
||||||
}
|
}
|
||||||
if got.Voice["elevenlabs"]["de"] != "pNInz6obpgDQGcFmaJgB" { // Nr. 2 = Adam
|
if got.Voice["elevenlabs"]["en"] != "pNInz6obpgDQGcFmaJgB" { // no. 2 = Adam
|
||||||
t.Errorf("voice.elevenlabs.de = %q, want Adam", got.Voice["elevenlabs"]["de"])
|
t.Errorf("voice.elevenlabs.en = %q, want Adam", got.Voice["elevenlabs"]["en"])
|
||||||
}
|
}
|
||||||
if _, ok := got.Voice["elevenlabs"]["en"]; ok {
|
if _, ok := got.Voice["elevenlabs"]["de"]; ok {
|
||||||
t.Errorf("voice.elevenlabs.en gesetzt, obwohl Default behalten wurde: %v", got.Voice)
|
t.Errorf("voice.elevenlabs.de set although the default was kept: %v", got.Voice)
|
||||||
}
|
}
|
||||||
if n := calls.Load(); n != 2 { // 1× Probehören de + 1× Testsatz
|
if n := calls.Load(); n != 2 { // 1× preview en + 1× test sentence
|
||||||
t.Errorf("Fake-Aufrufe = %d, want 2 (Probehören + Testsatz)", n)
|
t.Errorf("fake calls = %d, want 2 (preview + test sentence)", n)
|
||||||
}
|
}
|
||||||
if _, err := os.Stat(path + ".bak"); !os.IsNotExist(err) {
|
if _, err := os.Stat(path + ".bak"); !os.IsNotExist(err) {
|
||||||
t.Errorf("Sicherung ohne Vorgänger-Datei angelegt")
|
t.Errorf("backup created without a previous file")
|
||||||
}
|
}
|
||||||
if !strings.Contains(out.String(), "Gespeichert") || !strings.Contains(out.String(), "Gesprochen über elevenlabs") {
|
if !strings.Contains(out.String(), "Saved") || !strings.Contains(out.String(), "Spoken via elevenlabs") {
|
||||||
t.Errorf("stdout = %q", out.String())
|
t.Errorf("stdout = %q", out.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSetupMergtBestehendeConfig: Vorhandene Werte (anderer Port, andere
|
// TestSetupMergesExistingConfig: existing values (other port, another
|
||||||
// Provider-Stimme) bleiben erhalten, es gibt eine .bak, und „keine“ löscht
|
// provider's voice) survive, there is a .bak, and "none" removes an existing
|
||||||
// eine vorhandene Ruhezeit.
|
// quiet window.
|
||||||
func TestSetupMergtBestehendeConfig(t *testing.T) {
|
func TestSetupMergesExistingConfig(t *testing.T) {
|
||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
setupEnv(t, root, nil)
|
setupEnv(t, root, nil)
|
||||||
dir := filepath.Join(root, "talk")
|
dir := filepath.Join(root, "talk")
|
||||||
@@ -101,63 +105,63 @@ func TestSetupMergtBestehendeConfig(t *testing.T) {
|
|||||||
if err := os.WriteFile(path, []byte(orig), 0o644); err != nil {
|
if err := os.WriteFile(path, []byte(orig), 0o644); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
// Das Setup selbst muss auf den Default-Port 7800 zeigen, nicht 7900 aus
|
// The setup itself must not touch port 7900 from the file: TALK_PORT=1
|
||||||
// der Datei — sonst würde die Daemon-Erkennung einen fremden Port
|
// from setGetenv beats the file.
|
||||||
// anfassen. TALK_PORT=1 aus setGetenv schlägt die Datei.
|
stdin := strings.NewReader("\n1\nn\ny\n1\nn\ny\nnone\n")
|
||||||
stdin := strings.NewReader("1\nn\nj\n1\nn\nj\nkeine\n")
|
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
if code := run([]string{"setup"}, stdin, &out, &errBuf); code != exitOK {
|
if code := run([]string{"setup"}, stdin, &out, &errBuf); code != exitOK {
|
||||||
t.Fatalf("talk setup: Exit %d\n%s\n%s", code, out.String(), errBuf.String())
|
t.Fatalf("talk setup: exit %d\n%s\n%s", code, out.String(), errBuf.String())
|
||||||
}
|
}
|
||||||
bak, err := os.ReadFile(path + ".bak")
|
bak, err := os.ReadFile(path + ".bak")
|
||||||
if err != nil || string(bak) != orig {
|
if err != nil || string(bak) != orig {
|
||||||
t.Errorf(".bak = %q (%v), want Original", bak, err)
|
t.Errorf(".bak = %q (%v), want the original", bak, err)
|
||||||
}
|
}
|
||||||
var got map[string]any
|
var got map[string]any
|
||||||
if _, err := toml.DecodeFile(path, &got); err != nil {
|
if _, err := toml.DecodeFile(path, &got); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if _, ok := got["quiet_hours"]; ok {
|
if _, ok := got["quiet_hours"]; ok {
|
||||||
t.Errorf("quiet_hours nicht entfernt: %v", got)
|
t.Errorf("quiet_hours not removed: %v", got)
|
||||||
}
|
}
|
||||||
if srv, _ := got["server"].(map[string]any); srv["port"] != int64(7900) {
|
if srv, _ := got["server"].(map[string]any); srv["port"] != int64(7900) {
|
||||||
t.Errorf("server.port verloren: %v", got["server"])
|
t.Errorf("server.port lost: %v", got["server"])
|
||||||
}
|
}
|
||||||
voice, _ := got["voice"].(map[string]any)
|
voice, _ := got["voice"].(map[string]any)
|
||||||
if edge, _ := voice["edge"].(map[string]any); edge["de"] != "de-DE-ConradNeural" {
|
if edge, _ := voice["edge"].(map[string]any); edge["de"] != "de-DE-ConradNeural" {
|
||||||
t.Errorf("voice.edge.de verloren: %v", voice)
|
t.Errorf("voice.edge.de lost: %v", voice)
|
||||||
}
|
}
|
||||||
// Default behalten (Nr. 1 = Rachel = Repo-Default) → kein elevenlabs-Eintrag.
|
// Default kept (no. 1 = Rachel = built-in default) → no elevenlabs entry.
|
||||||
if _, ok := voice["elevenlabs"]; ok {
|
if _, ok := voice["elevenlabs"]; ok {
|
||||||
t.Errorf("voice.elevenlabs geschrieben, obwohl Default behalten: %v", voice)
|
t.Errorf("voice.elevenlabs written although the default was kept: %v", voice)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSetupAbbruchSchreibtNichts: „q“ bricht ab, keine Datei entsteht.
|
// TestSetupAbortWritesNothing: "q" aborts, no file is created.
|
||||||
func TestSetupAbbruchSchreibtNichts(t *testing.T) {
|
func TestSetupAbortWritesNothing(t *testing.T) {
|
||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
setupEnv(t, root, nil)
|
setupEnv(t, root, nil)
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
if code := run([]string{"setup"}, strings.NewReader("q\n"), &out, &errBuf); code != exitOK {
|
if code := run([]string{"setup"}, strings.NewReader("q\n"), &out, &errBuf); code != exitOK {
|
||||||
t.Fatalf("Exit %d, stderr %q", code, errBuf.String())
|
t.Fatalf("exit %d, stderr %q", code, errBuf.String())
|
||||||
}
|
}
|
||||||
if !strings.Contains(out.String(), "Abgebrochen") {
|
if !strings.Contains(out.String(), "Aborted") {
|
||||||
t.Errorf("stdout = %q", out.String())
|
t.Errorf("stdout = %q", out.String())
|
||||||
}
|
}
|
||||||
if _, err := os.Stat(filepath.Join(root, "talk", "config.toml")); !os.IsNotExist(err) {
|
if _, err := os.Stat(filepath.Join(root, "talk", "config.toml")); !os.IsNotExist(err) {
|
||||||
t.Error("config.toml trotz Abbruch angelegt")
|
t.Error("config.toml created despite abort")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSetupOhneTerminal: Pipe → keine Fragen, wirksame Konfiguration, Exit 0.
|
// TestSetupWithoutTerminal: a pipe → no questions, effective configuration,
|
||||||
func TestSetupOhneTerminal(t *testing.T) {
|
// exit 0.
|
||||||
|
func TestSetupWithoutTerminal(t *testing.T) {
|
||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
setGetenv(t, map[string]string{"XDG_CONFIG_HOME": root, "TALK_AUDIO_SINK": "null"})
|
setGetenv(t, map[string]string{"XDG_CONFIG_HOME": root, "TALK_AUDIO_SINK": "null"})
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
if code := runCLI([]string{"setup"}, &out, &errBuf); code != exitOK {
|
if code := runCLI([]string{"setup"}, &out, &errBuf); code != exitOK {
|
||||||
t.Fatalf("Exit %d, stderr %q", code, errBuf.String())
|
t.Fatalf("exit %d, stderr %q", code, errBuf.String())
|
||||||
}
|
}
|
||||||
if !strings.Contains(out.String(), "Wirksame Konfiguration") || !strings.Contains(out.String(), "ruhezeit: keine") {
|
if !strings.Contains(out.String(), "Effective configuration") || !strings.Contains(out.String(), "quiet hours: none") {
|
||||||
t.Errorf("stdout = %q", out.String())
|
t.Errorf("stdout = %q", out.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+90
-20
@@ -4,49 +4,62 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"code.m3ta.dev/m3tam3re/talk/internal/config"
|
"code.m3ta.dev/m3tam3re/talk/internal/config"
|
||||||
|
"code.m3ta.dev/m3tam3re/talk/internal/notify"
|
||||||
"code.m3ta.dev/m3tam3re/talk/internal/queue"
|
"code.m3ta.dev/m3tam3re/talk/internal/queue"
|
||||||
"code.m3ta.dev/m3tam3re/talk/internal/speak"
|
"code.m3ta.dev/m3tam3re/talk/internal/speak"
|
||||||
)
|
)
|
||||||
|
|
||||||
// testPhrase ist die feste Testphrase je Sprache.
|
// testPhrase is the fixed test sentence per language.
|
||||||
var testPhrase = map[string]string{
|
var testPhrase = map[string]string{
|
||||||
"de": "Dies ist eine Testansage von talk. Wenn du das hörst, funktioniert alles.",
|
"de": "Dies ist eine Testansage von talk. Wenn du das hörst, funktioniert alles.",
|
||||||
"en": "This is a test announcement from talk. If you can hear this, everything works.",
|
"en": "This is a test announcement from talk. If you can hear this, everything works.",
|
||||||
}
|
}
|
||||||
|
|
||||||
// runTest implementiert `talk test`: spricht die Testphrase DIREKT in diesem
|
// toastPhrase is the text of the test notification per language.
|
||||||
// Prozess (nicht über den Daemon) — so sieht der Befehl, welche Stufe
|
var toastPhrase = map[string]string{
|
||||||
// wirklich gesprochen hat und wie lange Synthese und Wiedergabe dauerten.
|
"de": "Dies ist eine Testbenachrichtigung von talk. So sehen Ansagen in der Ruhezeit aus.",
|
||||||
// Mute und Ruhezeit gelten hier bewusst nicht (der Nutzer will gerade
|
"en": "This is a test notification from talk. This is what announcements look like during quiet hours.",
|
||||||
// testen); ein aktives Mute wird aber genannt.
|
}
|
||||||
|
|
||||||
|
// runTest implements `talk test`: speaks the test sentence DIRECTLY in this
|
||||||
|
// process (not via the daemon), so the command sees which tier really spoke
|
||||||
|
// and how long synthesis and playback took. Mute and quiet hours
|
||||||
|
// deliberately do not apply (the user is testing right now); an active mute
|
||||||
|
// is mentioned. With --toast it sends a test desktop notification instead,
|
||||||
|
// through the same path quiet_mode = toast uses, so the notification setup
|
||||||
|
// can be checked without a quiet window and a daemon restart.
|
||||||
func runTest(args []string, opts *sayOptions, _ io.Reader, stdout, stderr io.Writer) int {
|
func runTest(args []string, opts *sayOptions, _ io.Reader, stdout, stderr io.Writer) int {
|
||||||
if len(args) > 0 {
|
if len(args) > 0 {
|
||||||
fmt.Fprintln(stderr, "talk test: keine Argumente erwartet (Sprache: --lang de|en)")
|
fmt.Fprintln(stderr, "talk test: no arguments expected (language: --lang de|en)")
|
||||||
return exitUsage
|
return exitUsage
|
||||||
}
|
}
|
||||||
if code, bad := validateSayOptions(opts, stderr); bad {
|
if code, bad := validateSayOptions(opts, stderr); bad {
|
||||||
return code
|
return code
|
||||||
}
|
}
|
||||||
lang := opts.lang
|
|
||||||
if lang == "" {
|
|
||||||
lang = "de"
|
|
||||||
}
|
|
||||||
cfg, err := config.Load(config.Options{Getenv: getenv})
|
cfg, err := config.Load(config.Options{Getenv: getenv})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(stderr, "talk: %v\n", err)
|
fmt.Fprintf(stderr, "talk: %v\n", err)
|
||||||
return exitFailure
|
return exitFailure
|
||||||
}
|
}
|
||||||
|
lang := opts.lang
|
||||||
|
if lang == "" {
|
||||||
|
lang = cfg.Lang
|
||||||
|
}
|
||||||
|
if opts.toast {
|
||||||
|
return runToastTest(lang, getenv, stdout, stderr)
|
||||||
|
}
|
||||||
if dir, err := config.Dir(getenv); err == nil {
|
if dir, err := config.Dir(getenv); err == nil {
|
||||||
if (queue.MuteStore{Path: filepath.Join(dir, queue.MuteFileName)}).Muted() {
|
if (queue.MuteStore{Path: filepath.Join(dir, queue.MuteFileName)}).Muted() {
|
||||||
fmt.Fprintln(stderr, "talk test: Mute ist an — der Test spielt trotzdem; normale Ansagen bleiben stumm (talk unmute)")
|
fmt.Fprintln(stderr, "talk test: mute is on; the test plays anyway, normal announcements stay silent (talk unmute)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if cfg.Audio.Sink == config.SinkNull {
|
if cfg.Audio.Sink == config.SinkNull {
|
||||||
fmt.Fprintln(stderr, "talk test: audio.sink = null — es wird kein Ton ausgegeben")
|
fmt.Fprintln(stderr, "talk test: audio.sink = null; no sound will be produced")
|
||||||
}
|
}
|
||||||
|
|
||||||
engine, err := speak.New(cfg, getenv, stderr)
|
engine, err := speak.New(cfg, getenv, stderr)
|
||||||
@@ -59,19 +72,76 @@ func runTest(args []string, opts *sayOptions, _ io.Reader, stdout, stderr io.Wri
|
|||||||
out, err := engine.Speak(ctx, speak.Request{Text: testPhrase[lang], Lang: lang, Provider: opts.provider, Voice: opts.voice})
|
out, err := engine.Speak(ctx, speak.Request{Text: testPhrase[lang], Lang: lang, Provider: opts.provider, Voice: opts.voice})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(stderr, "talk test: %v\n", err)
|
fmt.Fprintf(stderr, "talk test: %v\n", err)
|
||||||
fmt.Fprintln(stderr, "Hinweis: `talk doctor` zeigt, welche Stufe warum fehlt.")
|
fmt.Fprintln(stderr, "hint: `talk doctor` shows which tier is missing and why.")
|
||||||
return exitFailure
|
return exitFailure
|
||||||
}
|
}
|
||||||
fmt.Fprintf(stdout, "provider: %s\n", out.Provider)
|
fmt.Fprintf(stdout, "provider: %s\n", out.Provider)
|
||||||
fmt.Fprintf(stdout, "sprache: %s\n", lang)
|
fmt.Fprintf(stdout, "language: %s\n", lang)
|
||||||
switch {
|
switch {
|
||||||
case out.Discarded:
|
case out.Discarded:
|
||||||
fmt.Fprintln(stdout, "wiedergabe: verworfen (audio.sink = null)")
|
fmt.Fprintln(stdout, "playback: discarded (audio.sink = null)")
|
||||||
case out.Direct:
|
case out.Direct:
|
||||||
fmt.Fprintf(stdout, "dauer: %s (Direktansage über das OS)\n", out.Synthesis.Round(time.Millisecond))
|
fmt.Fprintf(stdout, "duration: %s (direct speech via the OS)\n", out.Synthesis.Round(time.Millisecond))
|
||||||
default:
|
default:
|
||||||
fmt.Fprintf(stdout, "synthese: %s (%d Bytes)\n", out.Synthesis.Round(time.Millisecond), out.Bytes)
|
fmt.Fprintf(stdout, "synthesis: %s (%d bytes)\n", out.Synthesis.Round(time.Millisecond), out.Bytes)
|
||||||
fmt.Fprintf(stdout, "wiedergabe: %s\n", out.Playback.Round(time.Millisecond))
|
fmt.Fprintf(stdout, "playback: %s\n", out.Playback.Round(time.Millisecond))
|
||||||
}
|
}
|
||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// runToastTest shows the test notification the way a playing announcement
|
||||||
|
// gets one (with a Cancel button where supported), waits a few seconds for a
|
||||||
|
// click and reports what happened. Exit 1 when no tool exists or the call
|
||||||
|
// fails.
|
||||||
|
func runToastTest(lang string, getenv func(string) string, stdout, stderr io.Writer) int {
|
||||||
|
// Same desktop setup as the daemon, so the test shows what announcements
|
||||||
|
// will show (icon, identity, Cancel button).
|
||||||
|
if dir, err := config.Dir(getenv); err == nil {
|
||||||
|
exe, _ := os.Executable()
|
||||||
|
if err := notify.Setup(dir, exe); err != nil {
|
||||||
|
fmt.Fprintf(stderr, "talk test: %v\n", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "toast: %s\n", notify.Describe())
|
||||||
|
if !notify.Available() {
|
||||||
|
fmt.Fprintln(stderr, "talk test: no notification path found; on Linux install libnotify (notify-send) or run a notification daemon, macOS and Windows have one built in")
|
||||||
|
return exitFailure
|
||||||
|
}
|
||||||
|
label := "Cancel"
|
||||||
|
if lang == "de" {
|
||||||
|
label = "Abbrechen"
|
||||||
|
}
|
||||||
|
clicked := make(chan struct{}, 1)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
start := time.Now()
|
||||||
|
closeFn, err := notify.Announce(ctx, notify.Announcement{Text: toastPhrase[lang], CancelLabel: label, CancelURI: "talk:test", Tag: "test"}, func() {
|
||||||
|
select {
|
||||||
|
case clicked <- struct{}{}:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "talk test: %v\n", err)
|
||||||
|
fmt.Fprintln(stderr, "hint: on Linux a notification daemon (mako, dunst, GNOME Shell, KDE) must be running.")
|
||||||
|
return exitFailure
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "sent: %s\n", time.Since(start).Round(time.Millisecond))
|
||||||
|
if !notify.SupportsCancel() {
|
||||||
|
fmt.Fprintln(stdout, "cancel: not available on this platform (notification without button)")
|
||||||
|
fmt.Fprintln(stdout, "If no notification appeared, your notification daemon did not show it (talk only hands it over).")
|
||||||
|
return exitOK
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "cancel: button %q shown; waiting up to %s for a click …\n", label, toastWait)
|
||||||
|
select {
|
||||||
|
case <-clicked:
|
||||||
|
fmt.Fprintln(stdout, "cancel: clicked, works")
|
||||||
|
case <-time.After(toastWait):
|
||||||
|
fmt.Fprintln(stdout, "cancel: not clicked (that is fine); closing the notification")
|
||||||
|
}
|
||||||
|
closeFn()
|
||||||
|
return exitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
// toastWait is how long `talk test --toast` waits for a click on Cancel.
|
||||||
|
const toastWait = 8 * time.Second
|
||||||
+53
-11
@@ -2,36 +2,78 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestTestBefehl: `talk test` spricht direkt über die Kette (hier: fake
|
// TestTestCommand: `talk test` speaks directly through the chain (here: fake
|
||||||
// espeak → osbuiltin) und nennt den Provider; sink null wird angesagt.
|
// espeak → osbuiltin) and names the provider; sink null is announced.
|
||||||
func TestTestBefehl(t *testing.T) {
|
func TestTestCommand(t *testing.T) {
|
||||||
seen := withFakeEspeak(t)
|
seen := withFakeEspeak(t)
|
||||||
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null", "TALK_PROVIDER": "osbuiltin"})
|
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null", "TALK_PROVIDER": "osbuiltin"})
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"test", "--lang", "en"}, &out, &errBuf)
|
code := runCLI([]string{"test", "--lang", "en"}, &out, &errBuf)
|
||||||
if code != exitOK {
|
if code != exitOK {
|
||||||
t.Fatalf("talk test: Exit %d, stderr %q", code, errBuf.String())
|
t.Fatalf("talk test: exit %d, stderr %q", code, errBuf.String())
|
||||||
}
|
}
|
||||||
if !strings.Contains(out.String(), "provider: osbuiltin") || !strings.Contains(out.String(), "sprache: en") {
|
if !strings.Contains(out.String(), "provider: osbuiltin") || !strings.Contains(out.String(), "language: en") {
|
||||||
t.Errorf("stdout = %q", out.String())
|
t.Errorf("stdout = %q", out.String())
|
||||||
}
|
}
|
||||||
if !strings.Contains(errBuf.String(), "kein Ton") {
|
if !strings.Contains(errBuf.String(), "no sound") {
|
||||||
t.Errorf("stderr = %q, will Hinweis auf sink null", errBuf.String())
|
t.Errorf("stderr = %q, want a note about sink null", errBuf.String())
|
||||||
}
|
}
|
||||||
if _, err := readFile(seen); err != nil {
|
if _, err := readFile(seen); err != nil {
|
||||||
t.Errorf("fake espeak nicht gerufen: %v", err)
|
t.Errorf("fake espeak not called: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestTestBefehlUngueltigeSprache: --lang prüft wie say.
|
// TestTestCommandInvalidLanguage: --lang is validated like say.
|
||||||
func TestTestBefehlUngueltigeSprache(t *testing.T) {
|
func TestTestCommandInvalidLanguage(t *testing.T) {
|
||||||
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
if code := runCLI([]string{"test", "--lang", "fr"}, &out, &errBuf); code == exitOK || !strings.Contains(errBuf.String(), "--lang") {
|
if code := runCLI([]string{"test", "--lang", "fr"}, &out, &errBuf); code == exitOK || !strings.Contains(errBuf.String(), "--lang") {
|
||||||
t.Errorf("Exit %d, stderr %q", code, errBuf.String())
|
t.Errorf("exit %d, stderr %q", code, errBuf.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestTestToast: --toast sends the test notification through notify-send
|
||||||
|
// (fake in PATH) with title and text and reports the tool; without a tool it
|
||||||
|
// is a clear error.
|
||||||
|
func TestTestToast(t *testing.T) {
|
||||||
|
if runtime.GOOS != "linux" {
|
||||||
|
t.Skip("fake notify-send exists on Linux only")
|
||||||
|
}
|
||||||
|
// No session bus in the test binary (TestMain): the fallback through
|
||||||
|
// notify-send is what we observe here.
|
||||||
|
dir := t.TempDir()
|
||||||
|
seen := filepath.Join(dir, "seen.txt")
|
||||||
|
fakeTTSBin(t, dir, "notify-send", `printf '%s\n' "$@" > "`+seen+`"`)
|
||||||
|
t.Setenv("PATH", dir)
|
||||||
|
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
||||||
|
|
||||||
|
var out, errBuf bytes.Buffer
|
||||||
|
code := runCLI([]string{"test", "--toast", "--lang", "de"}, &out, &errBuf)
|
||||||
|
if code != exitOK {
|
||||||
|
t.Fatalf("talk test --toast: exit %d, stderr %q", code, errBuf.String())
|
||||||
|
}
|
||||||
|
if !strings.Contains(out.String(), "toast: notify-send") || !strings.Contains(out.String(), "sent:") {
|
||||||
|
t.Errorf("stdout = %q", out.String())
|
||||||
|
}
|
||||||
|
b, err := os.ReadFile(seen)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("fake notify-send not called: %v", err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(b), "talk\n") || !strings.Contains(string(b), "Testbenachrichtigung") {
|
||||||
|
t.Errorf("notify-send args = %q, want title talk and the German test text", b)
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Setenv("PATH", t.TempDir())
|
||||||
|
out.Reset()
|
||||||
|
errBuf.Reset()
|
||||||
|
if code := runCLI([]string{"test", "--toast"}, &out, &errBuf); code != exitFailure || !strings.Contains(errBuf.String(), "no notification path") {
|
||||||
|
t.Errorf("without tool: exit %d, stderr %q", code, errBuf.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"code.m3ta.dev/m3tam3re/talk/internal/api"
|
||||||
|
"code.m3ta.dev/m3tam3re/talk/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
// runURI implements `talk uri <talk:…>`: the handler behind the talk: URL
|
||||||
|
// protocol that Windows opens when the Cancel button of a toast is clicked
|
||||||
|
// (registered by the daemon in HKCU). Links:
|
||||||
|
//
|
||||||
|
// talk:cancel?id=<announcement id>&port=<daemon port> cancel that announcement
|
||||||
|
// talk:test the test toast's button; nothing to do
|
||||||
|
//
|
||||||
|
// It never fails loudly: a stale id or a gone daemon is simply nothing to
|
||||||
|
// cancel. Output is one line so a console flash, if any, says what happened.
|
||||||
|
func runURI(args []string, _ *sayOptions, _ io.Reader, stdout, stderr io.Writer) int {
|
||||||
|
if len(args) != 1 {
|
||||||
|
fmt.Fprintln(stderr, "talk uri: expects exactly one talk: link")
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
u, err := url.Parse(args[0])
|
||||||
|
if err != nil || u.Scheme != "talk" {
|
||||||
|
fmt.Fprintf(stderr, "talk uri: not a talk: link: %q\n", args[0])
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
action := u.Opaque
|
||||||
|
if action == "" {
|
||||||
|
action = u.Host + u.Path
|
||||||
|
}
|
||||||
|
if i := indexByte(action, '?'); i >= 0 {
|
||||||
|
action = action[:i]
|
||||||
|
}
|
||||||
|
switch action {
|
||||||
|
case "cancel":
|
||||||
|
id := u.Query().Get("id")
|
||||||
|
if id == "" {
|
||||||
|
fmt.Fprintln(stderr, "talk uri: cancel link without id")
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
port := config.DefaultServerPort
|
||||||
|
if p := u.Query().Get("port"); p != "" {
|
||||||
|
if n, err := strconv.Atoi(p); err == nil && n > 0 && n < 65536 {
|
||||||
|
port = n
|
||||||
|
}
|
||||||
|
} else if cfg, err := config.Load(config.Options{Getenv: getenv}); err == nil {
|
||||||
|
port = cfg.Server.Port
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), daemonCallTimeout)
|
||||||
|
defer cancel()
|
||||||
|
hit, err := api.NewClient(port).CancelItem(ctx, id)
|
||||||
|
switch {
|
||||||
|
case err != nil:
|
||||||
|
fmt.Fprintf(stdout, "nothing to cancel (no daemon at port %d)\n", port)
|
||||||
|
case hit:
|
||||||
|
fmt.Fprintf(stdout, "cancelled %s\n", id)
|
||||||
|
default:
|
||||||
|
fmt.Fprintf(stdout, "%s is not playing any more\n", id)
|
||||||
|
}
|
||||||
|
return exitOK
|
||||||
|
case "test":
|
||||||
|
fmt.Fprintln(stdout, "talk: the Cancel button works")
|
||||||
|
return exitOK
|
||||||
|
default:
|
||||||
|
fmt.Fprintf(stderr, "talk uri: unknown action %q\n", action)
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func indexByte(s string, c byte) int {
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
if s[i] == c {
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"code.m3ta.dev/m3tam3re/talk/internal/api"
|
||||||
|
"code.m3ta.dev/m3tam3re/talk/internal/queue"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestURICancelsPlayingItem: `talk uri talk:cancel?id=…&port=…` tells the
|
||||||
|
// daemon at that port to cancel exactly that announcement; a stale id and a
|
||||||
|
// dead daemon are plain outcomes, not errors; garbage links are usage
|
||||||
|
// errors.
|
||||||
|
func TestURICancelsPlayingItem(t *testing.T) {
|
||||||
|
setGetenv(t, nil)
|
||||||
|
started := make(chan queue.Item, 4)
|
||||||
|
release := make(chan struct{})
|
||||||
|
q := queue.New(queue.Laws{}, func(ctx context.Context, item queue.Item) error {
|
||||||
|
started <- item
|
||||||
|
select {
|
||||||
|
case <-release:
|
||||||
|
return nil
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
}, nil)
|
||||||
|
defer q.Close()
|
||||||
|
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
srv := httptest.NewUnstartedServer(api.NewHandler(api.HandlerConfig{Queue: q, KnownProviders: []string{"edge"}}))
|
||||||
|
srv.Listener = ln
|
||||||
|
srv.Start()
|
||||||
|
defer srv.Close()
|
||||||
|
port := strconv.Itoa(ln.Addr().(*net.TCPAddr).Port)
|
||||||
|
|
||||||
|
adm, _ := q.Enqueue(queue.Item{Text: "playing"})
|
||||||
|
waiting, _ := q.Enqueue(queue.Item{Text: "waiting"})
|
||||||
|
<-started
|
||||||
|
|
||||||
|
var out, errBuf bytes.Buffer
|
||||||
|
if code := runCLI([]string{"uri", "talk:cancel?id=" + waiting.ID + "&port=" + port}, &out, &errBuf); code != exitOK || !strings.Contains(out.String(), "not playing") {
|
||||||
|
t.Errorf("waiting id: exit %d, stdout %q", code, out.String())
|
||||||
|
}
|
||||||
|
out.Reset()
|
||||||
|
if code := runCLI([]string{"uri", "talk:cancel?id=" + adm.ID + "&port=" + port}, &out, &errBuf); code != exitOK || !strings.Contains(out.String(), "cancelled "+adm.ID) {
|
||||||
|
t.Errorf("playing id: exit %d, stdout %q, stderr %q", code, out.String(), errBuf.String())
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case it := <-started:
|
||||||
|
if it.ID != waiting.ID {
|
||||||
|
t.Errorf("after cancel the next started item = %+v, want the waiting one", it)
|
||||||
|
}
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("waiting item did not start after the playing one was cancelled")
|
||||||
|
}
|
||||||
|
close(release)
|
||||||
|
|
||||||
|
out.Reset()
|
||||||
|
if code := runCLI([]string{"uri", "talk:cancel?id=abc&port=1"}, &out, &errBuf); code != exitOK || !strings.Contains(out.String(), "nothing to cancel") {
|
||||||
|
t.Errorf("dead daemon: exit %d, stdout %q", code, out.String())
|
||||||
|
}
|
||||||
|
out.Reset()
|
||||||
|
if code := runCLI([]string{"uri", "talk:test"}, &out, &errBuf); code != exitOK || !strings.Contains(out.String(), "works") {
|
||||||
|
t.Errorf("talk:test: exit %d, stdout %q", code, out.String())
|
||||||
|
}
|
||||||
|
for _, bad := range []string{"http://example.com", "talk:cancel", "talk:fly"} {
|
||||||
|
if code := runCLI([]string{"uri", bad}, &out, &errBuf); code != exitUsage {
|
||||||
|
t.Errorf("%q: exit %d, want usage error", bad, code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = http.StatusOK
|
||||||
|
}
|
||||||
+13
-13
@@ -11,7 +11,7 @@ import (
|
|||||||
"code.m3ta.dev/m3tam3re/talk/internal/provider"
|
"code.m3ta.dev/m3tam3re/talk/internal/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
// voiceRow ist eine Zeile von `talk voices` (auch die JSON-Form).
|
// voiceRow is one row of `talk voices` (also the JSON form).
|
||||||
type voiceRow struct {
|
type voiceRow struct {
|
||||||
Provider string `json:"provider"`
|
Provider string `json:"provider"`
|
||||||
Lang string `json:"lang"`
|
Lang string `json:"lang"`
|
||||||
@@ -20,21 +20,21 @@ type voiceRow struct {
|
|||||||
Default bool `json:"default"`
|
Default bool `json:"default"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// runVoices implementiert `talk voices`: Katalog der bekannten Stimmen plus
|
// runVoices implements `talk voices`: the catalog of known voices plus the
|
||||||
// die in der config.toml gesetzten (auch wenn sie nicht im Katalog stehen),
|
// ones set in config.toml (even when not in the catalog), filtered by
|
||||||
// gefiltert nach --provider/--lang; „*“ markiert die effektive Default-
|
// --provider/--lang; "*" marks the effective default voice per provider and
|
||||||
// Stimme je Provider und Sprache. osbuiltin erscheint als eine Zeile ohne
|
// language. osbuiltin appears as one row without an ID: the operating system
|
||||||
// ID — das Betriebssystem wählt die Stimme.
|
// picks the voice.
|
||||||
func runVoices(args []string, opts *sayOptions, _ io.Reader, stdout, stderr io.Writer) int {
|
func runVoices(args []string, opts *sayOptions, _ io.Reader, stdout, stderr io.Writer) int {
|
||||||
if len(args) > 0 {
|
if len(args) > 0 {
|
||||||
fmt.Fprintln(stderr, "talk voices: keine Argumente erwartet (Filter: --provider, --lang)")
|
fmt.Fprintln(stderr, "talk voices: no arguments expected (filters: --provider, --lang)")
|
||||||
return exitUsage
|
return exitUsage
|
||||||
}
|
}
|
||||||
if code, bad := validateSayOptions(opts, stderr); bad {
|
if code, bad := validateSayOptions(opts, stderr); bad {
|
||||||
return code
|
return code
|
||||||
}
|
}
|
||||||
if opts.provider != "" && !slices.Contains(provider.Names(), opts.provider) {
|
if opts.provider != "" && !slices.Contains(provider.Names(), opts.provider) {
|
||||||
fmt.Fprintf(stderr, "talk voices: unbekannter Provider %q (verfügbar: %v)\n", opts.provider, provider.Names())
|
fmt.Fprintf(stderr, "talk voices: unknown provider %q (available: %v)\n", opts.provider, provider.Names())
|
||||||
return exitFailure
|
return exitFailure
|
||||||
}
|
}
|
||||||
cfg, err := config.Load(config.Options{Getenv: getenv})
|
cfg, err := config.Load(config.Options{Getenv: getenv})
|
||||||
@@ -60,11 +60,11 @@ func runVoices(args []string, opts *sayOptions, _ io.Reader, stdout, stderr io.W
|
|||||||
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\n", r.Provider, r.Lang, r.ID, r.Name, mark)
|
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\n", r.Provider, r.Lang, r.ID, r.Name, mark)
|
||||||
}
|
}
|
||||||
tw.Flush()
|
tw.Flush()
|
||||||
fmt.Fprintln(stderr, "Stimme setzen: --voice <id> einmalig, oder dauerhaft in der config.toml unter [voice.<provider>] de = \"<id>\".")
|
fmt.Fprintln(stderr, "Pick a voice: --voice <id> once, or permanently in config.toml under [voice.<provider>] de = \"<id>\".")
|
||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
|
|
||||||
// voiceRows baut die Tabelle: Katalog + Config-Einträge, gefiltert.
|
// voiceRows builds the table: catalog + config entries, filtered.
|
||||||
func voiceRows(cfg config.Config, onlyProvider, onlyLang string) []voiceRow {
|
func voiceRows(cfg config.Config, onlyProvider, onlyLang string) []voiceRow {
|
||||||
var rows []voiceRow
|
var rows []voiceRow
|
||||||
seen := map[[3]string]bool{}
|
seen := map[[3]string]bool{}
|
||||||
@@ -84,11 +84,11 @@ func voiceRows(cfg config.Config, onlyProvider, onlyLang string) []voiceRow {
|
|||||||
}
|
}
|
||||||
for _, name := range provider.DefaultOrder {
|
for _, name := range provider.DefaultOrder {
|
||||||
for _, lang := range []string{"de", "en"} {
|
for _, lang := range []string{"de", "en"} {
|
||||||
// Config-Eintrag zuerst, damit er oben steht (auch ohne Katalog).
|
// Config entry first so it appears on top (also without catalog).
|
||||||
if id := cfg.Voice[name][lang]; id != "" {
|
if id := cfg.Voice[name][lang]; id != "" {
|
||||||
label := provider.VoiceName(name, id)
|
label := provider.VoiceName(name, id)
|
||||||
if label == "" {
|
if label == "" {
|
||||||
label = "(aus config.toml)"
|
label = "(from config.toml)"
|
||||||
}
|
}
|
||||||
add(name, lang, id, label)
|
add(name, lang, id, label)
|
||||||
}
|
}
|
||||||
@@ -98,7 +98,7 @@ func voiceRows(cfg config.Config, onlyProvider, onlyLang string) []voiceRow {
|
|||||||
add(v.Provider, v.Lang, v.ID, v.Name)
|
add(v.Provider, v.Lang, v.ID, v.Name)
|
||||||
}
|
}
|
||||||
for _, lang := range []string{"de", "en"} {
|
for _, lang := range []string{"de", "en"} {
|
||||||
add("osbuiltin", lang, "", "Stimme des Betriebssystems (wählt das OS)")
|
add("osbuiltin", lang, "", "operating system voice (the OS picks)")
|
||||||
}
|
}
|
||||||
return rows
|
return rows
|
||||||
}
|
}
|
||||||
+22
-22
@@ -9,25 +9,25 @@ import (
|
|||||||
"code.m3ta.dev/m3tam3re/talk/internal/config"
|
"code.m3ta.dev/m3tam3re/talk/internal/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestVoiceRowsDefaultUndConfig: Ohne Config markiert „*“ den Repo-Default;
|
// TestVoiceRowsDefaultAndConfig: without config "*" marks the built-in
|
||||||
// ein Config-Mapping verschiebt die Markierung und steht als eigene Zeile
|
// default; a config mapping moves the mark and appears as its own row on
|
||||||
// oben — auch für IDs außerhalb des Katalogs. Filter greifen.
|
// top, also for IDs outside the catalog. Filters apply.
|
||||||
func TestVoiceRowsDefaultUndConfig(t *testing.T) {
|
func TestVoiceRowsDefaultAndConfig(t *testing.T) {
|
||||||
cfg := config.Defaults()
|
cfg := config.Defaults()
|
||||||
rows := voiceRows(cfg, "edge", "de")
|
rows := voiceRows(cfg, "edge", "de")
|
||||||
if len(rows) == 0 || rows[0].ID != "de-DE-KatjaNeural" || !rows[0].Default {
|
if len(rows) == 0 || rows[0].ID != "de-DE-KatjaNeural" || !rows[0].Default {
|
||||||
t.Fatalf("edge/de ohne Config: erste Zeile = %+v, want Katja als Default", rows)
|
t.Fatalf("edge/de without config: first row = %+v, want Katja as default", rows)
|
||||||
}
|
}
|
||||||
for _, r := range rows {
|
for _, r := range rows {
|
||||||
if r.Provider != "edge" || r.Lang != "de" {
|
if r.Provider != "edge" || r.Lang != "de" {
|
||||||
t.Errorf("Filter verletzt: %+v", r)
|
t.Errorf("filter violated: %+v", r)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg.Voice = map[string]map[string]string{"edge": {"de": "de-DE-EigeneNeural"}}
|
cfg.Voice = map[string]map[string]string{"edge": {"de": "de-DE-CustomNeural"}}
|
||||||
rows = voiceRows(cfg, "edge", "de")
|
rows = voiceRows(cfg, "edge", "de")
|
||||||
if rows[0].ID != "de-DE-EigeneNeural" || !rows[0].Default || rows[0].Name != "(aus config.toml)" {
|
if rows[0].ID != "de-DE-CustomNeural" || !rows[0].Default || rows[0].Name != "(from config.toml)" {
|
||||||
t.Errorf("Config-ID außerhalb des Katalogs: erste Zeile = %+v", rows[0])
|
t.Errorf("config ID outside the catalog: first row = %+v", rows[0])
|
||||||
}
|
}
|
||||||
defaults := 0
|
defaults := 0
|
||||||
for _, r := range rows {
|
for _, r := range rows {
|
||||||
@@ -35,45 +35,45 @@ func TestVoiceRowsDefaultUndConfig(t *testing.T) {
|
|||||||
defaults++
|
defaults++
|
||||||
}
|
}
|
||||||
if r.ID == "de-DE-KatjaNeural" && r.Default {
|
if r.ID == "de-DE-KatjaNeural" && r.Default {
|
||||||
t.Error("Katja weiter als Default markiert, obwohl Config eine andere Stimme setzt")
|
t.Error("Katja still marked as default although config sets another voice")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if defaults != 1 {
|
if defaults != 1 {
|
||||||
t.Errorf("%d Default-Markierungen, want genau 1", defaults)
|
t.Errorf("%d default marks, want exactly 1", defaults)
|
||||||
}
|
}
|
||||||
|
|
||||||
// osbuiltin erscheint ohne ID, nie als Default.
|
// osbuiltin appears without an ID, never as default.
|
||||||
all := voiceRows(cfg, "", "")
|
all := voiceRows(cfg, "", "")
|
||||||
found := false
|
found := false
|
||||||
for _, r := range all {
|
for _, r := range all {
|
||||||
if r.Provider == "osbuiltin" {
|
if r.Provider == "osbuiltin" {
|
||||||
found = true
|
found = true
|
||||||
if r.ID != "" || r.Default {
|
if r.ID != "" || r.Default {
|
||||||
t.Errorf("osbuiltin-Zeile = %+v, want leere ID ohne Default", r)
|
t.Errorf("osbuiltin row = %+v, want empty ID without default", r)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !found {
|
if !found {
|
||||||
t.Error("osbuiltin fehlt in der Gesamtliste")
|
t.Error("osbuiltin missing from the full list")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestVoicesCLI: Tabelle mit Kopfzeile, --json als Liste, unbekannter
|
// TestVoicesCLI: table with header, --json as a list, unknown provider is an
|
||||||
// Provider ist ein Fehler.
|
// error.
|
||||||
func TestVoicesCLI(t *testing.T) {
|
func TestVoicesCLI(t *testing.T) {
|
||||||
setGetenv(t, nil)
|
setGetenv(t, nil)
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
if code := runCLI([]string{"voices", "--lang", "en"}, &out, &errBuf); code != exitOK {
|
if code := runCLI([]string{"voices", "--lang", "en"}, &out, &errBuf); code != exitOK {
|
||||||
t.Fatalf("talk voices: Exit %d, stderr %q", code, errBuf.String())
|
t.Fatalf("talk voices: exit %d, stderr %q", code, errBuf.String())
|
||||||
}
|
}
|
||||||
if !strings.HasPrefix(out.String(), "PROVIDER") || !strings.Contains(out.String(), "en-US-AriaNeural") {
|
if !strings.HasPrefix(out.String(), "PROVIDER") || !strings.Contains(out.String(), "en-US-AriaNeural") {
|
||||||
t.Errorf("Tabelle = %q", out.String())
|
t.Errorf("table = %q", out.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
out.Reset()
|
out.Reset()
|
||||||
errBuf.Reset()
|
errBuf.Reset()
|
||||||
if code := runCLI([]string{"voices", "--json", "--provider", "openai"}, &out, &errBuf); code != exitOK {
|
if code := runCLI([]string{"voices", "--json", "--provider", "openai"}, &out, &errBuf); code != exitOK {
|
||||||
t.Fatalf("talk voices --json: Exit %d, stderr %q", code, errBuf.String())
|
t.Fatalf("talk voices --json: exit %d, stderr %q", code, errBuf.String())
|
||||||
}
|
}
|
||||||
var rows []voiceRow
|
var rows []voiceRow
|
||||||
if err := json.Unmarshal(out.Bytes(), &rows); err != nil || len(rows) == 0 {
|
if err := json.Unmarshal(out.Bytes(), &rows); err != nil || len(rows) == 0 {
|
||||||
@@ -81,13 +81,13 @@ func TestVoicesCLI(t *testing.T) {
|
|||||||
}
|
}
|
||||||
for _, r := range rows {
|
for _, r := range rows {
|
||||||
if r.Provider != "openai" {
|
if r.Provider != "openai" {
|
||||||
t.Errorf("--provider openai liefert %+v", r)
|
t.Errorf("--provider openai yields %+v", r)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
out.Reset()
|
out.Reset()
|
||||||
errBuf.Reset()
|
errBuf.Reset()
|
||||||
if code := runCLI([]string{"voices", "--provider", "siri"}, &out, &errBuf); code == exitOK || !strings.Contains(errBuf.String(), "unbekannter Provider") {
|
if code := runCLI([]string{"voices", "--provider", "siri"}, &out, &errBuf); code == exitOK || !strings.Contains(errBuf.String(), "unknown provider") {
|
||||||
t.Errorf("unbekannter Provider: Exit %d, stderr %q", code, errBuf.String())
|
t.Errorf("unknown provider: exit %d, stderr %q", code, errBuf.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+79
-74
@@ -13,33 +13,33 @@ import (
|
|||||||
"code.m3ta.dev/m3tam3re/talk/internal/langdetect"
|
"code.m3ta.dev/m3tam3re/talk/internal/langdetect"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Kind nicht gefunden — Shell-Konvention 127.
|
// exitNotFound is the shell convention for "command not found".
|
||||||
const exitNotFound = 127
|
const exitNotFound = 127
|
||||||
|
|
||||||
// runWrap ist der wrap-Eingangspfad (Task 07): `talk wrap -- <Befehl>
|
// runWrap is the wrap entry point: `talk wrap -- <command> [args …]` runs
|
||||||
// [Argumente …]` führt den Befehl aus — stdin/stdout/stderr werden
|
// the command (stdin/stdout/stderr passed through; stdout belongs to the
|
||||||
// durchgereicht, stdout gehört allein dem Befehl —, misst die Wandzeit und
|
// command alone), measures wall time and announces the result afterwards:
|
||||||
// sagt danach das Ergebnis an: „<label> erfolgreich. Dauer: X." bzw.
|
// "<label> succeeded. Duration: X." or "<label> failed, code N." (label =
|
||||||
// „<label> fehlgeschlagen, Code N." (Label = config `wrap.label` oder der
|
// config `wrap.label` or the command's base name; localized de/en by
|
||||||
// Basisname des Befehls; lokalisiert de/en nach langdetect des Labels).
|
// language detection on the label, falling back to the configured lang).
|
||||||
// Die Ansage läuft über denselben Weg wie say: Daemon (enqueue, non-
|
// The announcement takes the same path as say: daemon (enqueue, non-
|
||||||
// blocking; --wait respektiert; Autostart), ohne Daemon direkt. wrap erbt
|
// blocking; --wait honoured; autostart), without a daemon directly. wrap
|
||||||
// die say-Flags und reicht sie an die Ansage durch.
|
// inherits the say flags and passes them on.
|
||||||
//
|
//
|
||||||
// Exit-Code-Politik: wrap exitet IMMER mit dem Code des Befehls (talk-
|
// Exit code policy: wrap ALWAYS exits with the command's code (talk errors
|
||||||
// Fehler ≠ Befehls-Fehler). Scheitert die Ansage, gibt es eine Warning auf
|
// are not command errors). If the announcement fails, there is a warning on
|
||||||
// stderr — der Befehls-Code bleibt. Benutzungsfehler von talk selbst
|
// stderr and the command's code stands. Usage errors of talk itself (no
|
||||||
// (kein Befehl, unbekannte Flags, ungültiges --lang) fallen dagegen VOR
|
// command, unknown flags, invalid --lang) fail BEFORE the command starts,
|
||||||
// dem Start des Befehls auf: Er läuft dann gar nicht erst. Nur
|
// so it does not run at all. Only configuration errors (broken config.toml
|
||||||
// Konfigurations-Fehler (kaputte config.toml/Env) treten nach dem Lauf
|
// or env) surface after the run: the command has run, the announcement is
|
||||||
// auf — der Befehl bleibt gelaufen, die Ansage wird mit Warning ausgesetzt.
|
// skipped with a warning.
|
||||||
//
|
//
|
||||||
// Die Positionsargumente sind die Befehlszeile (Befehl + Argumente); das
|
// The positional arguments are the command line (command + args); the "--"
|
||||||
// „--" selbst hat parseInterspersed bereits konsumiert — alles dahinter
|
// itself was consumed by parseInterspersed, everything after it came
|
||||||
// kam unverändert durch den Flag-Schutz hindurch.
|
// through untouched.
|
||||||
func runWrap(args []string, opts *sayOptions, stdin io.Reader, stdout, stderr io.Writer) int {
|
func runWrap(args []string, opts *sayOptions, stdin io.Reader, stdout, stderr io.Writer) int {
|
||||||
if len(args) == 0 {
|
if len(args) == 0 {
|
||||||
fmt.Fprintln(stderr, "talk wrap: kein Befehl — Verwendung: talk wrap [Flags] -- <Befehl> [Argumente …]")
|
fmt.Fprintln(stderr, "talk wrap: no command given; usage: talk wrap [flags] -- <command> [args …]")
|
||||||
return exitUsage
|
return exitUsage
|
||||||
}
|
}
|
||||||
if code, bad := validateSayOptions(opts, stderr); bad {
|
if code, bad := validateSayOptions(opts, stderr); bad {
|
||||||
@@ -50,47 +50,47 @@ func runWrap(args []string, opts *sayOptions, stdin io.Reader, stdout, stderr io
|
|||||||
runErr := execChild(args, stdin, stdout, stderr)
|
runErr := execChild(args, stdin, stdout, stderr)
|
||||||
duration := time.Since(start)
|
duration := time.Since(start)
|
||||||
code := childExitCode(runErr)
|
code := childExitCode(runErr)
|
||||||
if runErr != nil {
|
if runErr != nil && !isPlainExit(runErr) {
|
||||||
// Z. B. Binary nicht gefunden oder Signal-Tod: Der Hinweis gehört
|
// Binary not found or killed by a signal: the command never produced
|
||||||
// auf stderr; die Ansage nennt denselben Code, mit dem wrap exitet.
|
// an exit code of its own, so say why wrap exits with the one it
|
||||||
fmt.Fprintf(stderr, "talk wrap: Befehl nicht sauber beendet: %v\n", runErr)
|
// does. A plain non-zero exit code needs no note; the announcement
|
||||||
|
// and the exit code carry it.
|
||||||
|
fmt.Fprintf(stderr, "talk wrap: command did not exit cleanly: %v\n", runErr)
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg, err := config.Load(config.Options{Getenv: getenv})
|
cfg, err := config.Load(config.Options{Getenv: getenv})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(stderr, "talk wrap: Ansage ausgesetzt — Config: %v (Exit-Code %d des Befehls bleibt)\n", err, code)
|
fmt.Fprintf(stderr, "talk wrap: announcement skipped; config: %v (the command's exit code %d stands)\n", err, code)
|
||||||
return code
|
return code
|
||||||
}
|
}
|
||||||
|
|
||||||
label := wrapLabel(cfg.Wrap.Label, args[0])
|
label := wrapLabel(cfg.Wrap.Label, args[0])
|
||||||
lang := opts.lang
|
lang := opts.lang
|
||||||
if lang == "" {
|
if lang == "" {
|
||||||
lang = langdetect.Detect(label)
|
lang = langdetect.Detect(label, cfg.Lang)
|
||||||
}
|
}
|
||||||
announceWrap(cfg, announcementText(label, code, duration, lang), opts, code, stderr)
|
announceWrap(cfg, announcementText(label, code, duration, lang), opts, code, stderr)
|
||||||
return code
|
return code
|
||||||
}
|
}
|
||||||
|
|
||||||
// announceWrap bringt die wrap-Ansage unter — über denselben Weg wie say
|
// announceWrap delivers the wrap announcement the same way say does
|
||||||
// (announce: Daemon, ggf. Autostart, sonst direkt). Der Exit-Code der
|
// (announce: daemon, autostart if needed, otherwise direct). The
|
||||||
// Ansage-Maschinerie verwirft NIE den Code des Befehls: Scheitert sie,
|
// announcement machinery NEVER overrides the command's exit code: if it
|
||||||
// gibt es eine Warning auf stderr (talk-Fehler ≠ Befehls-Fehler).
|
// fails, there is a warning on stderr. Information lines of the
|
||||||
// Informationszeilen der Ansage (Item-ID, muted, discarded) gehen bei wrap
|
// announcement (item ID, muted, discarded) go to stderr for wrap: stdout
|
||||||
// auf stderr — stdout gehört allein dem (bereits beendeten) Befehl, damit
|
// belongs to the (already finished) command, so its pipes and redirects
|
||||||
// Pipes und Redirects des Befehls nicht durch talk-Ausgaben verunreinigt
|
// stay clean.
|
||||||
// werden.
|
|
||||||
func announceWrap(cfg config.Config, text string, opts *sayOptions, commandCode int, stderr io.Writer) {
|
func announceWrap(cfg config.Config, text string, opts *sayOptions, commandCode int, stderr io.Writer) {
|
||||||
if announce(cfg, text, opts, stderr, stderr) != exitOK {
|
if announce(cfg, text, opts, stderr, stderr) != exitOK {
|
||||||
fmt.Fprintf(stderr, "talk wrap: Ansage fehlgeschlagen — Exit-Code %d des Befehls bleibt\n", commandCode)
|
fmt.Fprintf(stderr, "talk wrap: announcement failed; the command's exit code %d stands\n", commandCode)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// execChild startet argv als Kindprozess und wartet auf sein Ende.
|
// execChild starts argv as a child process and waits for it. stdin/stdout/
|
||||||
// stdin/stdout/stderr werden unverändert durchgereicht — der Befehl
|
// stderr are passed through unchanged: the command owns the console, talk
|
||||||
// besitzt die Konsole, talk mischt sich nicht ein (die Ansage selbst geht
|
// does not interfere (the announcement goes out only AFTER the command has
|
||||||
// erst NACH dem Ende des Befehls raus). Reines os/exec ohne
|
// ended). Plain os/exec without platform-specific calls: runs unchanged on
|
||||||
// plattformspezifische Aufrufe: läuft unverändert auf Windows, macOS und
|
// Windows, macOS and Linux.
|
||||||
// Linux (Kindprozesse startet das jeweilige Betriebssystem-Exec selbst).
|
|
||||||
func execChild(argv []string, stdin io.Reader, stdout, stderr io.Writer) error {
|
func execChild(argv []string, stdin io.Reader, stdout, stderr io.Writer) error {
|
||||||
cmd := exec.Command(argv[0], argv[1:]...)
|
cmd := exec.Command(argv[0], argv[1:]...)
|
||||||
cmd.Stdin = stdin
|
cmd.Stdin = stdin
|
||||||
@@ -99,17 +99,16 @@ func execChild(argv []string, stdin io.Reader, stdout, stderr io.Writer) error {
|
|||||||
return cmd.Run()
|
return cmd.Run()
|
||||||
}
|
}
|
||||||
|
|
||||||
// childExitCode übersetzt das Run-Ergebnis des Kindprozesses in den
|
// childExitCode translates the child's Run result into the exit code wrap
|
||||||
// Exit-Code, mit dem wrap selbst exitet (Durchreich-Vertrag):
|
// itself exits with (pass-through contract):
|
||||||
//
|
//
|
||||||
// - normales Ende: der Exit-Code des Befehls (0 = Erfolg).
|
// - normal exit: the command's exit code (0 = success).
|
||||||
// - Ende durch Signal: portabel auf 1 normiert. Die Unix-Konvention
|
// - killed by a signal: normalized to 1, portably. The Unix convention
|
||||||
// 128+Signalnummer bräuchte syscall.WaitStatus (Signaltode meldet Go
|
// 128+signal would need syscall.WaitStatus (Go reports signal deaths as
|
||||||
// als ExitCode -1) und wäre nicht mehr frei cross-compilierbar; die
|
// ExitCode -1) and would no longer cross-compile freely; the
|
||||||
// Ansage nennt bewusst denselben normierten Code, mit dem wrap exitet.
|
// announcement deliberately names the same normalized code.
|
||||||
// - Start fehlgeschlagen (Binary nicht gefunden/nicht ausführbar):
|
// - start failed (binary not found/not executable): 127, the shell
|
||||||
// 127, die Shell-Konvention — der Befehl ist gescheitert, ohne je
|
// convention; the command failed without ever running.
|
||||||
// gelaufen zu sein.
|
|
||||||
func childExitCode(runErr error) int {
|
func childExitCode(runErr error) int {
|
||||||
if runErr == nil {
|
if runErr == nil {
|
||||||
return 0
|
return 0
|
||||||
@@ -124,9 +123,16 @@ func childExitCode(runErr error) int {
|
|||||||
return exitNotFound
|
return exitNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
// wrapLabel löst das Ansage-Label: config `wrap.label` (Env-Override
|
// isPlainExit reports whether runErr is just a non-zero exit code of a
|
||||||
// TALK_WRAP_LABEL) schlägt den Basisnamen des Befehls
|
// command that ran and exited normally.
|
||||||
// (`/usr/bin/make` → „make").
|
func isPlainExit(runErr error) bool {
|
||||||
|
var ee *exec.ExitError
|
||||||
|
return errors.As(runErr, &ee) && ee.ExitCode() >= 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// wrapLabel resolves the announcement label: config `wrap.label` (env
|
||||||
|
// override TALK_WRAP_LABEL) beats the command's base name
|
||||||
|
// (`/usr/bin/make` → "make").
|
||||||
func wrapLabel(cfgLabel, command string) string {
|
func wrapLabel(cfgLabel, command string) string {
|
||||||
if cfgLabel != "" {
|
if cfgLabel != "" {
|
||||||
return cfgLabel
|
return cfgLabel
|
||||||
@@ -134,16 +140,16 @@ func wrapLabel(cfgLabel, command string) string {
|
|||||||
return filepath.Base(command)
|
return filepath.Base(command)
|
||||||
}
|
}
|
||||||
|
|
||||||
// formatDuration macht eine Wandzeit menschenlesbar, lokalisiert de/en:
|
// formatDuration renders wall time for humans, localized de/en: "3 Minuten
|
||||||
// „3 Minuten 42 Sekunden" / „3 minutes 42 seconds". Gerundet auf ganze
|
// 42 Sekunden" / "3 minutes 42 seconds". Rounded to whole seconds (half
|
||||||
// Sekunden (halb aufwärts); Nullteile fallen weg („1 Minute"), nur bei
|
// up); zero parts are dropped ("1 Minute"), only an overall zero keeps
|
||||||
// insgesamt null bleibt „0 Sekunden" stehen. Die Einzahl wird dekliniert
|
// "0 Sekunden". Singulars are declined ("1 Sekunde", "1 minute").
|
||||||
// („1 Sekunde", „1 minute"). Alles über einer Stunde nennt auch Stunden.
|
// Anything over an hour names hours too.
|
||||||
func formatDuration(d time.Duration, lang string) string {
|
func formatDuration(d time.Duration, lang string) string {
|
||||||
type unit struct{ singular, plural string }
|
type unit struct{ singular, plural string }
|
||||||
units := []unit{{"Stunde", "Stunden"}, {"Minute", "Minuten"}, {"Sekunde", "Sekunden"}}
|
units := []unit{{"hour", "hours"}, {"minute", "minutes"}, {"second", "seconds"}}
|
||||||
if lang == "en" {
|
if lang == "de" {
|
||||||
units = []unit{{"hour", "hours"}, {"minute", "minutes"}, {"second", "seconds"}}
|
units = []unit{{"Stunde", "Stunden"}, {"Minute", "Minuten"}, {"Sekunde", "Sekunden"}}
|
||||||
}
|
}
|
||||||
secs := int64(d.Round(time.Second) / time.Second)
|
secs := int64(d.Round(time.Second) / time.Second)
|
||||||
n := []int64{secs / 3600, secs / 60 % 60, secs % 60}
|
n := []int64{secs / 3600, secs / 60 % 60, secs % 60}
|
||||||
@@ -164,21 +170,20 @@ func formatDuration(d time.Duration, lang string) string {
|
|||||||
return strings.Join(parts, " ")
|
return strings.Join(parts, " ")
|
||||||
}
|
}
|
||||||
|
|
||||||
// announcementText baut die wrap-Ansage nach Brief: Erfolg
|
// announcementText builds the wrap announcement: success "<label>
|
||||||
// „<label> erfolgreich. Dauer: X." bzw. Misserfolg
|
// succeeded. Duration: X." / failure "<label> failed, code N.", in German
|
||||||
// „<label> fehlgeschlagen, Code N." — lokalisiert (englisch:
|
// "<label> erfolgreich. Dauer: X." / "<label> fehlgeschlagen, Code N.". The
|
||||||
// „<label> succeeded. Duration: X." / „<label> failed, code N."). Die
|
// language comes from detection on the label (or --lang); anything but
|
||||||
// Sprache bestimmt die Spracherkennung des Labels (oder --lang, falls
|
// "de" speaks English.
|
||||||
// gesetzt); alles außer "en" spricht deutsch (langdetect-Default).
|
|
||||||
func announcementText(label string, code int, d time.Duration, lang string) string {
|
func announcementText(label string, code int, d time.Duration, lang string) string {
|
||||||
if lang == "en" {
|
if lang == "de" {
|
||||||
if code == 0 {
|
if code == 0 {
|
||||||
return fmt.Sprintf("%s succeeded. Duration: %s.", label, formatDuration(d, lang))
|
return fmt.Sprintf("%s erfolgreich. Dauer: %s.", label, formatDuration(d, lang))
|
||||||
}
|
}
|
||||||
return fmt.Sprintf("%s failed, code %d.", label, code)
|
return fmt.Sprintf("%s fehlgeschlagen, Code %d.", label, code)
|
||||||
}
|
}
|
||||||
if code == 0 {
|
if code == 0 {
|
||||||
return fmt.Sprintf("%s erfolgreich. Dauer: %s.", label, formatDuration(d, lang))
|
return fmt.Sprintf("%s succeeded. Duration: %s.", label, formatDuration(d, lang))
|
||||||
}
|
}
|
||||||
return fmt.Sprintf("%s fehlgeschlagen, Code %d.", label, code)
|
return fmt.Sprintf("%s failed, code %d.", label, code)
|
||||||
}
|
}
|
||||||
+101
-87
@@ -12,9 +12,9 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestFormatDuration ist tischgesteuert für die menschliche Dauer-Format
|
// TestFormatDuration is table-driven for the human duration format (de/en):
|
||||||
// (de/en): Gerundung auf ganze Sekunden, Nullteile fallen weg, Einzahl
|
// rounding to whole seconds, zero parts dropped, singulars declined, hours
|
||||||
// wird dekliniert, Stunden ab einer Stunde, „0 Sekunden" als Fallback.
|
// from one hour on, "0 seconds" as the fallback.
|
||||||
func TestFormatDuration(t *testing.T) {
|
func TestFormatDuration(t *testing.T) {
|
||||||
cases := []struct {
|
cases := []struct {
|
||||||
d time.Duration
|
d time.Duration
|
||||||
@@ -23,7 +23,7 @@ func TestFormatDuration(t *testing.T) {
|
|||||||
}{
|
}{
|
||||||
{0, "0 Sekunden", "0 seconds"},
|
{0, "0 Sekunden", "0 seconds"},
|
||||||
{300 * time.Millisecond, "0 Sekunden", "0 seconds"},
|
{300 * time.Millisecond, "0 Sekunden", "0 seconds"},
|
||||||
{500 * time.Millisecond, "1 Sekunde", "1 second"}, // halb aufwärts
|
{500 * time.Millisecond, "1 Sekunde", "1 second"}, // half up
|
||||||
{1500 * time.Millisecond, "2 Sekunden", "2 seconds"},
|
{1500 * time.Millisecond, "2 Sekunden", "2 seconds"},
|
||||||
{1 * time.Second, "1 Sekunde", "1 second"},
|
{1 * time.Second, "1 Sekunde", "1 second"},
|
||||||
{42 * time.Second, "42 Sekunden", "42 seconds"},
|
{42 * time.Second, "42 Sekunden", "42 seconds"},
|
||||||
@@ -45,8 +45,8 @@ func TestFormatDuration(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestAnnouncementText: die Ansage-Texte nach Brief, lokalisiert de/en —
|
// TestAnnouncementText: the announcement texts, localized de/en: success
|
||||||
// Erfolg mit Dauer, Misserfolg mit Code (ohne Dauer).
|
// with duration, failure with code (without duration).
|
||||||
func TestAnnouncementText(t *testing.T) {
|
func TestAnnouncementText(t *testing.T) {
|
||||||
d := 222 * time.Second
|
d := 222 * time.Second
|
||||||
cases := []struct {
|
cases := []struct {
|
||||||
@@ -66,7 +66,7 @@ func TestAnnouncementText(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestWrapLabel: config-Label schlägt den Basisnamen des Befehls.
|
// TestWrapLabel: the config label beats the command's base name.
|
||||||
func TestWrapLabel(t *testing.T) {
|
func TestWrapLabel(t *testing.T) {
|
||||||
if got := wrapLabel("", "/usr/bin/make"); got != "make" {
|
if got := wrapLabel("", "/usr/bin/make"); got != "make" {
|
||||||
t.Errorf("wrapLabel(\"\", /usr/bin/make) = %q, want %q", got, "make")
|
t.Errorf("wrapLabel(\"\", /usr/bin/make) = %q, want %q", got, "make")
|
||||||
@@ -79,37 +79,37 @@ func TestWrapLabel(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestWrapOhneBefehl: `talk wrap` ohne Befehl ist ein klarer
|
// TestWrapWithoutCommand: `talk wrap` without a command is a clear usage
|
||||||
// Benutzungsfehler — der Befehl (nicht vorhanden) läuft natürlich nicht.
|
// error; the (absent) command naturally does not run.
|
||||||
func TestWrapOhneBefehl(t *testing.T) {
|
func TestWrapWithoutCommand(t *testing.T) {
|
||||||
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"wrap"}, &out, &errBuf)
|
code := runCLI([]string{"wrap"}, &out, &errBuf)
|
||||||
if code != exitUsage {
|
if code != exitUsage {
|
||||||
t.Fatalf("talk wrap ohne Befehl: Exit-Code = %d, want %d", code, exitUsage)
|
t.Fatalf("talk wrap without command: exit code = %d, want %d", code, exitUsage)
|
||||||
}
|
}
|
||||||
if !strings.Contains(errBuf.String(), "kein Befehl") {
|
if !strings.Contains(errBuf.String(), "no command") {
|
||||||
t.Errorf("stderr = %q, will Hinweis auf fehlenden Befehl", errBuf.String())
|
t.Errorf("stderr = %q, want a note about the missing command", errBuf.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestWrapValidiertSayFlagsVorDemStart: ungültige geerbte say-Flags
|
// TestWrapValidatesSayFlagsBeforeStart: invalid inherited say flags fail
|
||||||
// scheitern VOR dem Befehlsstart (Benutzungsfehler laufen nie den Befehl).
|
// BEFORE the command starts (usage errors never run the command).
|
||||||
func TestWrapValidiertSayFlagsVorDemStart(t *testing.T) {
|
func TestWrapValidatesSayFlagsBeforeStart(t *testing.T) {
|
||||||
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
setGetenv(t, map[string]string{"TALK_AUDIO_SINK": "null"})
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"wrap", "--lang=fr", "--", "true"}, &out, &errBuf)
|
code := runCLI([]string{"wrap", "--lang=fr", "--", "true"}, &out, &errBuf)
|
||||||
if code != exitFailure {
|
if code != exitFailure {
|
||||||
t.Fatalf("talk wrap --lang=fr: Exit-Code = %d, want %d", code, exitFailure)
|
t.Fatalf("talk wrap --lang=fr: exit code = %d, want %d", code, exitFailure)
|
||||||
}
|
}
|
||||||
if !strings.Contains(errBuf.String(), "--lang") {
|
if !strings.Contains(errBuf.String(), "--lang") {
|
||||||
t.Errorf("stderr = %q, will --lang-Fehler", errBuf.String())
|
t.Errorf("stderr = %q, want a --lang error", errBuf.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// wrapFakeTTS ist ein ElevenLabs-Fake, der den ANSAGE-TEXT aufzeichnet
|
// wrapFakeTTS is an ElevenLabs fake recording the ANNOUNCEMENT TEXT (the
|
||||||
// (der CLI-Fake in say_test.go beobachtet nur Pfad/Key — wrap braucht den
|
// CLI fake in say_test.go only observes path/key; wrap needs the spoken text
|
||||||
// gesprochenen Text als Beobachtung).
|
// as its observation).
|
||||||
func wrapFakeTTS(t *testing.T, status int) (url string, texts chan string) {
|
func wrapFakeTTS(t *testing.T, status int) (url string, texts chan string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
texts = make(chan string, 8)
|
texts = make(chan string, 8)
|
||||||
@@ -126,10 +126,10 @@ func wrapFakeTTS(t *testing.T, status int) (url string, texts chan string) {
|
|||||||
return ts.URL, texts
|
return ts.URL, texts
|
||||||
}
|
}
|
||||||
|
|
||||||
// wrapEnv ist die Degraded-Grundausstattung der In-Prozess-wrap-Tests:
|
// wrapEnv is the base kit of the in-process wrap tests: daemon guaranteed
|
||||||
// Daemon garantiert tot (TALK_PORT=1), Kette auf den Fake gepinnt — die
|
// dead (TALK_PORT=1), chain pinned to the fake; the announcement runs
|
||||||
// Ansage läuft deterministisch lokal gegen den Fake (sink null). extra
|
// deterministically on the direct path against the fake (sink null). extra
|
||||||
// ergänzt weitere Env-Werte (ein Aufruf, kein Verdrängen der Basis).
|
// adds env values (one call, no displacing of the base).
|
||||||
func wrapEnv(t *testing.T, endpoint string, extra map[string]string) {
|
func wrapEnv(t *testing.T, endpoint string, extra map[string]string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
kv := map[string]string{
|
kv := map[string]string{
|
||||||
@@ -144,19 +144,19 @@ func wrapEnv(t *testing.T, endpoint string, extra map[string]string) {
|
|||||||
setGetenv(t, kv)
|
setGetenv(t, kv)
|
||||||
}
|
}
|
||||||
|
|
||||||
// needUnixBin überspringt den Test, wenn das Binary fehlt (die
|
// needUnixBin skips the test when the binary is missing (the in-process
|
||||||
// In-Prozess-Tests starten echte Kinder: true/sh — auf dem Linux-Dev-Host
|
// tests start real children: true/sh; always present on Linux and in CI).
|
||||||
// und in CI immer vorhanden).
|
|
||||||
func needUnixBin(t *testing.T, name string) {
|
func needUnixBin(t *testing.T, name string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
if _, err := exec.LookPath(name); err != nil {
|
if _, err := exec.LookPath(name); err != nil {
|
||||||
t.Skipf("%s fehlt: %v", name, err)
|
t.Skipf("%s missing: %v", name, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestWrapDurchreichungErfolg: `talk wrap -- true` (Daemon tot → Degraded,
|
// TestWrapPassThroughSuccess: `talk wrap -- true` (daemon dead → direct,
|
||||||
// Ansage gegen den Fake) exitet 0 und sagt den Erfolg mit Dauer.
|
// announcement against the fake) exits 0 and announces success with the
|
||||||
func TestWrapDurchreichungErfolg(t *testing.T) {
|
// duration, in English by default.
|
||||||
|
func TestWrapPassThroughSuccess(t *testing.T) {
|
||||||
needUnixBin(t, "true")
|
needUnixBin(t, "true")
|
||||||
url, texts := wrapFakeTTS(t, 200)
|
url, texts := wrapFakeTTS(t, 200)
|
||||||
wrapEnv(t, url, nil)
|
wrapEnv(t, url, nil)
|
||||||
@@ -164,103 +164,117 @@ func TestWrapDurchreichungErfolg(t *testing.T) {
|
|||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"wrap", "--", "true"}, &out, &errBuf)
|
code := runCLI([]string{"wrap", "--", "true"}, &out, &errBuf)
|
||||||
if code != exitOK {
|
if code != exitOK {
|
||||||
t.Fatalf("talk wrap -- true: Exit-Code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
t.Fatalf("talk wrap -- true: exit code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
||||||
}
|
}
|
||||||
select {
|
select {
|
||||||
case text := <-texts:
|
case text := <-texts:
|
||||||
// true läuft Millisekunden — Dauer rund 0; unter Last auch gern
|
// true runs for milliseconds: duration about 0; under load also
|
||||||
// 1 Sekunde (Einzahl). Nur Struktur verifiziert.
|
// 1 second (singular). Only the structure is verified.
|
||||||
if !regexp.MustCompile(`^true erfolgreich\. Dauer: \d+ Sekunden?\.$`).MatchString(text) {
|
if !regexp.MustCompile(`^true succeeded\. Duration: \d+ seconds?\.$`).MatchString(text) {
|
||||||
t.Errorf("Ansage = %q, will „true erfolgreich. Dauer: N Sekunde(n).“", text)
|
t.Errorf("announcement = %q, want \"true succeeded. Duration: N second(s).\"", text)
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
t.Error("Ansage lief nicht (Fake nicht gerufen)")
|
t.Error("announcement did not run (fake not called)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestWrapDurchreichungFehlschlag: `talk wrap -- sh -c "exit 3"` exitet 3
|
// TestWrapPassThroughFailure: `talk wrap -- sh -c "exit 3"` exits 3 and
|
||||||
// und sagt den Misserfolg mit genau diesem Code.
|
// announces the failure with exactly that code; with TALK_LANG=de in German.
|
||||||
func TestWrapDurchreichungFehlschlag(t *testing.T) {
|
func TestWrapPassThroughFailure(t *testing.T) {
|
||||||
needUnixBin(t, "sh")
|
needUnixBin(t, "sh")
|
||||||
url, texts := wrapFakeTTS(t, 200)
|
for _, tc := range []struct {
|
||||||
wrapEnv(t, url, nil)
|
lang string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"", "sh failed, code 3."},
|
||||||
|
{"de", "sh fehlgeschlagen, Code 3."},
|
||||||
|
} {
|
||||||
|
t.Run("lang="+tc.lang, func(t *testing.T) {
|
||||||
|
url, texts := wrapFakeTTS(t, 200)
|
||||||
|
extra := map[string]string{}
|
||||||
|
if tc.lang != "" {
|
||||||
|
extra["TALK_LANG"] = tc.lang
|
||||||
|
}
|
||||||
|
wrapEnv(t, url, extra)
|
||||||
|
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"wrap", "--", "sh", "-c", "exit 3"}, &out, &errBuf)
|
code := runCLI([]string{"wrap", "--", "sh", "-c", "exit 3"}, &out, &errBuf)
|
||||||
if code != 3 {
|
if code != 3 {
|
||||||
t.Fatalf("talk wrap -- sh -c 'exit 3': Exit-Code = %d, want 3", code)
|
t.Fatalf("talk wrap -- sh -c 'exit 3': exit code = %d, want 3", code)
|
||||||
}
|
}
|
||||||
select {
|
select {
|
||||||
case text := <-texts:
|
case text := <-texts:
|
||||||
if text != "sh fehlgeschlagen, Code 3." {
|
if text != tc.want {
|
||||||
t.Errorf("Ansage = %q, want %q", text, "sh fehlgeschlagen, Code 3.")
|
t.Errorf("announcement = %q, want %q", text, tc.want)
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
t.Error("Ansage lief nicht (Fake nicht gerufen)")
|
t.Error("announcement did not run (fake not called)")
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestWrapStdoutGehoertBefehl: stdout der wrap-CLI führt NUR die Ausgabe
|
// TestWrapStdoutBelongsToCommand: the wrap CLI's stdout carries ONLY the
|
||||||
// des Befehls — die Informationszeilen der Ansage (hier: Degraded-Protokoll
|
// command's output; the announcement's information lines (direct-path note
|
||||||
// und Ketten-Logs) gehen auf stderr. Pipes des Befehls bleiben sauber.
|
// and chain logs) go to stderr. The command's pipes stay clean.
|
||||||
func TestWrapStdoutGehoertBefehl(t *testing.T) {
|
func TestWrapStdoutBelongsToCommand(t *testing.T) {
|
||||||
needUnixBin(t, "sh")
|
needUnixBin(t, "sh")
|
||||||
url, _ := wrapFakeTTS(t, 200)
|
url, _ := wrapFakeTTS(t, 200)
|
||||||
wrapEnv(t, url, nil)
|
wrapEnv(t, url, nil)
|
||||||
|
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"wrap", "--", "sh", "-c", "echo kinderausgabe"}, &out, &errBuf)
|
code := runCLI([]string{"wrap", "--", "sh", "-c", "echo child-output"}, &out, &errBuf)
|
||||||
if code != exitOK {
|
if code != exitOK {
|
||||||
t.Fatalf("talk wrap -- sh -c echo: Exit-Code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
t.Fatalf("talk wrap -- sh -c echo: exit code = %d, want %d; stderr = %q", code, exitOK, errBuf.String())
|
||||||
}
|
}
|
||||||
if out.String() != "kinderausgabe\n" {
|
if out.String() != "child-output\n" {
|
||||||
t.Errorf("stdout = %q, will ausschließlich die Befehlsausgabe %q", out.String(), "kinderausgabe\n")
|
t.Errorf("stdout = %q, want only the command's output %q", out.String(), "child-output\n")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestWrapAnsageScheitertCodeBleibt: Stirbt die Ansage (Endpunkt tot,
|
// TestWrapAnnouncementFailsCodeStands: if the announcement dies (endpoint
|
||||||
// Kette gepinnt → kein Fallback), bleibt der Exit-Code des Befehls
|
// dead, chain pinned → no fallback), the command's exit code still stands;
|
||||||
// trotzdem — nur eine Warning auf stderr (talk-Fehler ≠ Befehls-Fehler).
|
// only a warning on stderr (talk errors are not command errors).
|
||||||
func TestWrapAnsageScheitertCodeBleibt(t *testing.T) {
|
func TestWrapAnnouncementFailsCodeStands(t *testing.T) {
|
||||||
needUnixBin(t, "sh")
|
needUnixBin(t, "sh")
|
||||||
wrapEnv(t, "http://127.0.0.1:1/", nil) // Endpunkt garantiert tot
|
wrapEnv(t, "http://127.0.0.1:1/", nil) // endpoint guaranteed dead
|
||||||
|
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"wrap", "--", "sh", "-c", "exit 4"}, &out, &errBuf)
|
code := runCLI([]string{"wrap", "--", "sh", "-c", "exit 4"}, &out, &errBuf)
|
||||||
if code != 4 {
|
if code != 4 {
|
||||||
t.Fatalf("talk wrap (Ansage scheitert): Exit-Code = %d, want 4 (Befehl gewinnt)", code)
|
t.Fatalf("talk wrap (announcement fails): exit code = %d, want 4 (command wins)", code)
|
||||||
}
|
}
|
||||||
if !strings.Contains(errBuf.String(), "Ansage fehlgeschlagen") {
|
if !strings.Contains(errBuf.String(), "announcement failed") {
|
||||||
t.Errorf("stderr = %q, will Warning, dass die Ansage scheiterte", errBuf.String())
|
t.Errorf("stderr = %q, want a warning that the announcement failed", errBuf.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestWrapBefehlNichtGefunden: unbekannter Befehl → Shell-Konvention 127,
|
// TestWrapCommandNotFound: unknown command → shell convention 127, the
|
||||||
// Ansage nennt denselben Code.
|
// announcement names the same code.
|
||||||
func TestWrapBefehlNichtGefunden(t *testing.T) {
|
func TestWrapCommandNotFound(t *testing.T) {
|
||||||
url, texts := wrapFakeTTS(t, 200)
|
url, texts := wrapFakeTTS(t, 200)
|
||||||
wrapEnv(t, url, nil)
|
wrapEnv(t, url, nil)
|
||||||
|
|
||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"wrap", "--", "diesen-befehl-gibt-es-nicht"}, &out, &errBuf)
|
code := runCLI([]string{"wrap", "--", "this-command-does-not-exist"}, &out, &errBuf)
|
||||||
if code != exitNotFound {
|
if code != exitNotFound {
|
||||||
t.Fatalf("talk wrap -- <unbekannt>: Exit-Code = %d, want %d", code, exitNotFound)
|
t.Fatalf("talk wrap -- <unknown>: exit code = %d, want %d", code, exitNotFound)
|
||||||
}
|
}
|
||||||
if !strings.Contains(errBuf.String(), "nicht sauber beendet") {
|
if !strings.Contains(errBuf.String(), "did not exit cleanly") {
|
||||||
t.Errorf("stderr = %q, will Hinweis auf den Startfehler", errBuf.String())
|
t.Errorf("stderr = %q, want a note about the start failure", errBuf.String())
|
||||||
}
|
}
|
||||||
select {
|
select {
|
||||||
case text := <-texts:
|
case text := <-texts:
|
||||||
if text != "diesen-befehl-gibt-es-nicht fehlgeschlagen, Code 127." {
|
if text != "this-command-does-not-exist failed, code 127." {
|
||||||
t.Errorf("Ansage = %q, want Code-127-Ansage", text)
|
t.Errorf("announcement = %q, want the code 127 announcement", text)
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
t.Error("Ansage lief nicht (Fake nicht gerufen)")
|
t.Error("announcement did not run (fake not called)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestWrapLabelAusEnv: TALK_WRAP_LABEL ersetzt den Basisnamen.
|
// TestWrapLabelFromEnv: TALK_WRAP_LABEL replaces the base name.
|
||||||
func TestWrapLabelAusEnv(t *testing.T) {
|
func TestWrapLabelFromEnv(t *testing.T) {
|
||||||
needUnixBin(t, "false")
|
needUnixBin(t, "false")
|
||||||
url, texts := wrapFakeTTS(t, 200)
|
url, texts := wrapFakeTTS(t, 200)
|
||||||
wrapEnv(t, url, map[string]string{"TALK_WRAP_LABEL": "Deployment"})
|
wrapEnv(t, url, map[string]string{"TALK_WRAP_LABEL": "Deployment"})
|
||||||
@@ -268,14 +282,14 @@ func TestWrapLabelAusEnv(t *testing.T) {
|
|||||||
var out, errBuf bytes.Buffer
|
var out, errBuf bytes.Buffer
|
||||||
code := runCLI([]string{"wrap", "--", "false"}, &out, &errBuf)
|
code := runCLI([]string{"wrap", "--", "false"}, &out, &errBuf)
|
||||||
if code != 1 {
|
if code != 1 {
|
||||||
t.Fatalf("talk wrap -- false: Exit-Code = %d, want 1", code)
|
t.Fatalf("talk wrap -- false: exit code = %d, want 1", code)
|
||||||
}
|
}
|
||||||
select {
|
select {
|
||||||
case text := <-texts:
|
case text := <-texts:
|
||||||
if text != "Deployment fehlgeschlagen, Code 1." {
|
if text != "Deployment failed, code 1." {
|
||||||
t.Errorf("Ansage = %q, want %q", text, "Deployment fehlgeschlagen, Code 1.")
|
t.Errorf("announcement = %q, want %q", text, "Deployment failed, code 1.")
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
t.Error("Ansage lief nicht (Fake nicht gerufen)")
|
t.Error("announcement did not run (fake not called)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+105
-92
@@ -1,126 +1,139 @@
|
|||||||
# Spec: talk 2.0 — Cross-Platform Voice Notifications für KI-Agenten
|
# Spec: talk 2.0: Cross-Platform Voice Notifications for AI Agents
|
||||||
|
|
||||||
Status: ready-for-agent
|
Status: ready-for-agent
|
||||||
Created: 2026-10-18
|
Created: 2026-10-18
|
||||||
Source: Grilling-Session 2026-10-18 (shared understanding, alle Äste besucht)
|
Source: grilling session 2026-10-18 (shared understanding, all branches visited)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Problem Statement
|
## Problem Statement
|
||||||
|
|
||||||
KI-Agenten (Coding-Agenten wie opencode/Claude Code, Firmen-Chats, Hintergrund-Jobs) können mich heute nur visuell erreichen — Terminal-Output, Toast, push notification. Wenn ich weg vom Bildschirm bin (Kaffee, anderes Fenster, Meeting am zweiten Monitor), verpasse ich, dass ein Build fertig ist, ein Agent auf meine Freigabe wartet oder ein Job gecrasht ist.
|
Today, AI agents (coding agents such as opencode/Claude Code, company chats, background jobs) can only reach me visually: terminal output, toast, push notification. When I am away from the screen (coffee, another window, a meeting on the second monitor), I miss that a build has finished, that an agent is waiting for my approval, or that a job has crashed.
|
||||||
|
|
||||||
Der bestehende talk/crunch-Stack löst das prinzipiell, ist aber unbrauchbar als Basis: bash + mpv + notify-send + agenix = Linux-Desktop-only, ElevenLabs-only (Key pro Host, in der Praxis nur auf einem bestätigt funktionierend), kein natives Tool-Interface für Agenten (nur Shell-Umwege), keine Queue (Audio überlappt), flüchtiger Mute-Toggle, und null Geschichte auf dem Windows-Fleet der Firma.
|
The existing talk/crunch stack solves this in principle but is unusable as a foundation: bash + mpv + notify-send + agenix means Linux desktop only, ElevenLabs only (key per host, in practice confirmed working on just one), no native tool interface for agents (shell workarounds only), no queue (audio overlaps), a volatile mute toggle, and no story at all for the company's Windows fleet.
|
||||||
|
|
||||||
## Solution
|
## Solution
|
||||||
|
|
||||||
**talk 2.0**: Ein cross-platform Werkzeug (Windows/macOS/Linux, amd64+arm64) in Go als statische Binaries — `talk` (CLI mit Bubble-Tea-TUI) und `talkd` (Daemon mit Queue). Jeder KI-Agent, der ein Programm ausführen kann, kann damit sprechen: `talk "Build fertig"`. Lokale MCP-Clients bekommen zusätzlich einen nativen MCP-Endpoint auf localhost. Die TTS-Qualität skaliert mit verfügbaren Keys über eine Vier-Stufen-Fallback-Kette bis hinunter zu kostenlosen/offline-Stimmen — Stimme funktioniert also überall ab Minute eins. Sprechen ist striktes Opt-in durch den Nutzer; der Daemon erzwingt Rate-Limit, Mute und Ruhezeiten als Backstop unter allem Prompt-Verhalten.
|
**talk 2.0**: a cross-platform tool (Windows/macOS/Linux, amd64+arm64) written in Go as static binaries: `talk` (CLI with a Bubble Tea TUI) and `talkd` (daemon with queue). Any AI agent that can run a program can speak with it: `talk "Build done"`. Local MCP clients additionally get a native MCP endpoint on localhost. TTS quality scales with the available keys through a four-stage fallback chain down to free/offline voices, so voice works everywhere from minute one. Speaking is strictly opt-in by the user; the daemon enforces rate limit, mute and quiet hours as a backstop beneath all prompt behaviour.
|
||||||
|
|
||||||
Verteilung: Gitea-Releases nach agent-lib-Muster (Asset-Schema `talk_<os>_<arch>` + sha256); Firma: interne Spiegelung + Fleet-Role (Ansible, Program Files + PATH); privat: Nix-Flake. Skill lebt im Repo und rollt in der Firma über az-agent-defaults/agent-lib aus.
|
Distribution: Gitea releases following the agent-lib pattern (asset schema `talk_<os>_<arch>` + sha256); company: internal mirror + fleet role (Ansible, Program Files + PATH); private: Nix flake. The skill lives in the repo and rolls out in the company via az-agent-defaults/agent-lib.
|
||||||
|
|
||||||
## User Stories
|
## User Stories
|
||||||
|
|
||||||
1. Als **Nutzer** will ich `talk "Text"` aufrufen können, damit ich sofort weiß, wie die Schnittstelle funktioniert, ohne Doku zu lesen.
|
1. As a **user** I want to call `talk "text"` so that I immediately know how the interface works without reading docs.
|
||||||
2. Als **Nutzer** will ich, dass der Aufruf non-blocking zurückkehrt, damit mein Skript/Agent nicht auf das Audio wartet.
|
2. As a **user** I want the call to return non-blocking so that my script/agent does not wait for the audio.
|
||||||
3. Als **Skript-Autor** will ich `talk "Text" --wait`, damit Cron-Jobs erst nach der Ansage weiterlaufen bzw. enden.
|
3. As a **script author** I want `talk "text" --wait` so that cron jobs only continue or exit after the announcement.
|
||||||
4. Als **Nutzer** will ich `talk wrap -- <befehl>` nutzen können, damit mir Dauer + Erfolg/Misserfolg eines beliebigen Befehls angesagt werden.
|
4. As a **user** I want to use `talk wrap -- <command>` so that the duration and success/failure of any command are announced to me.
|
||||||
5. Als **KI-Agent** will ich das Programm mit Argument oder via stdin füttern können, damit ich es aus jeder Umgebung heraus aufrufen kann.
|
5. As an **AI agent** I want to feed the program via argument or stdin so that I can call it from any environment.
|
||||||
6. Als **KI-Agent (MCP-fähig)** will ich einen lokalen MCP-Endpoint mit einem speak-Tool nutzen können, damit ich Voice nativ als Tool habe statt Shell-Umwege.
|
6. As an **AI agent (MCP-capable)** I want a local MCP endpoint with a speak tool so that I have voice natively as a tool instead of shell workarounds.
|
||||||
7. Als **Browser-KI-Chat (später)** will ich `POST /speak` auf localhost mit CORS-Erlaubnis rufen können, damit eine Web-UI (z. B. LibreChat) mich ansprechen kann, ohne dass talk dafür geändert werden muss.
|
7. As a **browser AI chat (later)** I want to call `POST /speak` on localhost with CORS permission so that a web UI (e.g. LibreChat) can address me without talk having to change.
|
||||||
8. Als **Nutzer mit ElevenLabs-Key** will ich die Premium-Stimme bekommen, damit Ansagen so klingen wie gewohnt.
|
8. As a **user with an ElevenLabs key** I want the premium voice so that announcements sound the way I am used to.
|
||||||
9. Als **Nutzer mit nur einem OpenAI-Key** will ich OpenAI-TTS als Provider nutzen können, damit ich keinen zweiten Account brauche.
|
9. As a **user with only an OpenAI key** I want to use OpenAI TTS as a provider so that I do not need a second account.
|
||||||
10. Als **Nutzer ohne jeden Key** will ich automatisch Edge-TTS (kostenlos) bekommen, damit Stimme out-of-the-box funktioniert.
|
10. As a **user without any key** I want to get Edge TTS (free) automatically so that voice works out of the box.
|
||||||
11. Als **Offline-Nutzer** will ich auf OS-eingebaute TTS-Stimmen (say/SAPI/espeak) zurückfallen, damit auch ohne Netz/Key gesprochen wird.
|
11. As an **offline user** I want to fall back to OS built-in TTS voices (say/SAPI/espeak) so that speech works even without network or key.
|
||||||
12. Als **Nutzer** will ich, dass die Provider-Kette automatisch durchfällt (Key ungültig, Kontingent leer, Netz weg), damit nie stumm bleibt, wenn nicht sein muss.
|
12. As a **user** I want the provider chain to fall through automatically (invalid key, quota exhausted, network gone) so that it never stays silent when it does not have to.
|
||||||
13. Als **Nutzer** will ich die Sprache des Texts automatisch erkannt bekommen (de/en), damit englische Agent-Antworten nicht mit deutscher Stimme verhackstückt werden.
|
13. As a **user** I want the language of the text detected automatically (de/en) so that English agent replies are not mangled by a German voice.
|
||||||
14. Als **Nutzer** will ich pro Provider und Sprache eine Stimme in der config.toml setzen, damit meine gewohnte Stimme überall gleich klingt.
|
14. As a **user** I want to set a voice per provider and language in config.toml so that my familiar voice sounds the same everywhere.
|
||||||
15. Als **Nutzer** will ich `talk setup` als geführten Wizard (Stimmen probehören, Key testen, Config schreiben), damit ich ohne Terminal-Erfahrung in 2 Minuten eingerichtet bin.
|
15. As a **user** I want `talk setup` as a guided wizard (preview voices, test key, write config) so that I am set up in 2 minutes without terminal experience.
|
||||||
16. Als **Nutzer** will ich `talk status` als Live-Dashboard (Queue, Mute, aktiver Provider, Version), damit ich immer weiß, was das Tool gerade tut.
|
16. As a **user** I want `talk status` as a live dashboard (queue, mute, active provider, version) so that I always know what the tool is doing.
|
||||||
17. Als **Nutzer** will ich `talk voices` als interaktive Liste mit Vorhör-Preview, damit ich Stimmen ohne IDs auswendig zu lernen vergleichen kann.
|
17. As a **user** I want `talk voices` as an interactive list with audio preview so that I can compare voices without memorising IDs.
|
||||||
18. Als **Nutzer** will ich `talk mute` / `talk unmute` als persistenten Schalter, damit alle Agenten und Skripte still sind, bis ich es erlaube.
|
18. As a **user** I want `talk mute` / `talk unmute` as a persistent switch so that all agents and scripts stay silent until I allow it.
|
||||||
19. Als **Nutzer** will ich konfigurierbare Ruhezeiten (`quiet_hours = "18:00-08:00"`), damit 23:47-Uhr-Cron-Jobs mich nicht wecken.
|
19. As a **user** I want configurable quiet hours (`quiet_hours = "18:00-08:00"`) so that 23:47 cron jobs do not wake me.
|
||||||
20. Als **Nutzer** will ich `talk cancel`, damit eine laufende oder geplante Ansage sofort stoppt.
|
20. As a **user** I want `talk cancel` so that a running or scheduled announcement stops immediately.
|
||||||
21. Als **Nutzer** will ich `--priority`, damit Dringendes die Queue vorn überspringt und Gedrängel bei Rate-Limit verworfen werden darf.
|
21. As a **user** I want `--priority` so that urgent items skip to the front of the queue and crowding under the rate limit may be discarded.
|
||||||
22. Als **Nutzer** will ich, dass sich Audio-Nachrichten nie überlappen (Queue serialisiert), damit bei drei gleichzeitigen Agenten alles verständlich bleibt.
|
22. As a **user** I want audio messages to never overlap (the queue serialises) so that everything stays intelligible with three agents at once.
|
||||||
23. Als **Nutzer** will ich ein Rate-Limit als Daemon-Gesetz (Standard ~1 Ansage/30 s), damit kein Agent-Spam möglich ist, egal was im Prompt steht.
|
23. As a **user** I want a rate limit as daemon law (default ~1 announcement/30 s) so that agent spam is impossible, whatever the prompt says.
|
||||||
24. Als **Agent-nutzender Nutzer** will ich Opt-in-Etikette im Skill dokumentiert: Agent spricht nur auf meine Anweisung oder Standing-Order in der AGENTS.md, session-sticky bis Widerruf, damit keine Agentin von sich aus plappert.
|
24. As an **agent-using user** I want opt-in etiquette documented in the skill: the agent speaks only on my instruction or a standing order in AGENTS.md, session-sticky until revoked, so that no agent chatters on its own.
|
||||||
25. Als **Agent-nutzender Nutzer** will ich, dass die Ansage nützlich ist (Status / nächster Schritt / wofür ich gebraucht werde), nicht die vorgelesene Langantwort, damit 10 Sekunden Ansage reichen.
|
25. As an **agent-using user** I want the announcement to be useful (status / next step / what I am needed for), not the long answer read aloud, so that 10 seconds of announcement are enough.
|
||||||
26. Als **Fleet-Administrator** will ich statische Binaries von Gitea-Releases versionpinnt + sha256-verifiziert ausrollen (agent-lib/officecli-Muster), damit das Ansible-Rollout deterministisch ist.
|
26. As a **fleet administrator** I want to roll out static binaries from Gitea releases, version-pinned and sha256-verified (agent-lib/officecli pattern), so that the Ansible rollout is deterministic.
|
||||||
27. Als **Fleet-Administrator** will ich Keys user-spezifisch als Env-Variablen (`TALK_*`) ausrollen nach unserem AZ_FLEET-Muster, damit kein Secret in Config-Dateien landet.
|
27. As a **fleet administrator** I want to roll out keys per user as environment variables (`TALK_*`) following our AZ_FLEET pattern so that no secret ends up in config files.
|
||||||
28. Als **Fleet-Administrator** will ich `talk doctor` als Diagnose-Output, damit „kein Ton bei Kollege X" in 5 Sekunden selbsterklärend ist.
|
28. As a **fleet administrator** I want `talk doctor` as diagnostic output so that "no sound at colleague X" is self-explanatory in 5 seconds.
|
||||||
29. Als **Fleet-Benutzer ohne Adminrechte** will ich, dass talk ohne Runtime-Abhängigkeiten (kein ffmpeg, kein Player, kein Python) läuft, damit es auf jedem Firmenrechner einfach funktioniert.
|
29. As a **fleet user without admin rights** I want talk to run without runtime dependencies (no ffmpeg, no player, no Python) so that it simply works on every company machine.
|
||||||
30. Als **Nutzer auf einem Rechner ohne laufenden Daemon** will ich einen Degraded Mode (Lock-File, sequenziell), damit talk auch ohne talkd nie kaputt ist.
|
30. As a **user on a machine without a running daemon** I want a degraded mode (lock file, sequential) so that talk is never broken even without talkd.
|
||||||
31. Als **Privatnutzer mit NixOS-Hosts** will ich einen Flake-Output im Repo, damit meine Hosts talk wie gewohnt deklarativ beziehen.
|
31. As a **private user with NixOS hosts** I want a flake output in the repo so that my hosts pull talk declaratively as usual.
|
||||||
32. Als **OS-Nutzer** will ich eine Desktop-Notification parallel zum Audio mit Abbrechen-Button, wo das OS es hergibt, damit ich stummschalten kann, ohne ein Terminal zu öffnen.
|
32. As an **OS user** I want a desktop notification alongside the audio with a cancel button, where the OS allows it, so that I can silence it without opening a terminal.
|
||||||
33. Als **Nicht-Terminal-Nutzer** will ich, dass TUI-Befehle ohne TTY auf plain Output zurückfallen, damit Pipes und Automatisierung niemals brechen.
|
33. As a **non-terminal user** I want TUI commands to fall back to plain output without a TTY so that pipes and automation never break.
|
||||||
34. Als **Projekt-Betreuer** will ich PR-getriebene Tests + Release-Matrix in Gitea Actions, damit jeder Tag automatisch konsistent gebaute Artefakte für alle Plattformen produziert.
|
34. As a **project maintainer** I want PR-driven tests + a release matrix in Gitea Actions so that every tag automatically produces consistently built artifacts for all platforms.
|
||||||
|
|
||||||
## Implementation Decisions
|
## Implementation Decisions
|
||||||
|
|
||||||
- **Sprache/Laufzeit**: Go; statische Binaries für win/mac/linux × amd64/arm64. Keine Runtime-Abhängigkeiten.
|
- **Language/runtime**: Go; static binaries for win/mac/linux x amd64/arm64. No runtime dependencies.
|
||||||
- **Binaries**: `talk` (CLI) + `talkd` (Daemon). Repo: `code.m3ta.dev/m3tam3re/talk`, MIT-Lizenz.
|
- **Binaries**: `talk` (CLI) + `talkd` (daemon). Repo: `code.m3ta.dev/m3tam3re/talk`, MIT licence.
|
||||||
- **Daemon**: talkd besitzt die Queue (Serialisierung, Prioritäten, Rate-Limit, Verwerfen bei Gedrängel), den persistenten Mute-State, die Ruhezeiten-Fenster (lokale Zeit, still verwerfen oder toast-only, konfigurierbar), die HTTP-API (`POST /speak` auf 127.0.0.1, CORS-Domains konfigurierbar) und einen MCP-Endpoint (Streamable HTTP, localhost).
|
- **Daemon**: talkd owns the queue (serialisation, priorities, rate limit, discarding under crowding), the persistent mute state, the quiet-hours windows (local time, discard silently or toast-only, configurable), the HTTP API (`POST /speak` on 127.0.0.1, CORS domains configurable) and an MCP endpoint (Streamable HTTP, localhost).
|
||||||
- **Degraded Mode**: ohne laufenden talkd fällt das CLI auf Lock-File-Sequential zurück; nichts bricht still.
|
- **Degraded mode**: without a running talkd the CLI falls back to lock-file sequential; nothing breaks silently.
|
||||||
- **Audio**: embedded Playback (oto) — kein mpv/ffmpeg nötig. Audio-Sink wählbar inkl. `null` (CI, Server, doctor).
|
- **Audio**: embedded playback (oto), no mpv/ffmpeg needed. Audio sink selectable, including `null` (CI, server, doctor).
|
||||||
- **Notifications**: best effort über beeep (notify-send / macOS Notification Center / Windows Toast); Cancel-Button, wo das OS ihn hergibt.
|
- **Notifications**: best effort via beeep (notify-send / macOS Notification Center / Windows toast); cancel button where the OS allows it.
|
||||||
- **Provider-Kette V1** (Auto-Fallback in dieser Reihenfolge, überschreibbar per Config/Flag): ElevenLabs → OpenAI TTS → Edge-TTS (frei, kein Key) → OS built-in (macOS say / Windows SAPI / Linux espeak).
|
- **Provider chain V1** (auto-fallback in this order, overridable via config/flag): ElevenLabs -> OpenAI TTS -> Edge TTS (free, no key) -> OS built-in (macOS say / Windows SAPI / Linux espeak).
|
||||||
- **Keys/Config**: Env-first (`TALK_ELEVENLABS_KEY`, `TALK_OPENAI_KEY`, …) plus optionale `config.toml` im platform-nativen Config-Dir (`~/.config/talk` / `~/Library/Application Support/talk` / `%APPDATA%\talk`). Provider-Endpunkte konfigurierbar (Testbarkeit, Firmenserver später). Per-User-Keys in V1; zentraler Firmenserver/Gateway bewusst später.
|
- **Keys/config**: env-first (`TALK_ELEVENLABS_KEY`, `TALK_OPENAI_KEY`, ...) plus an optional `config.toml` in the platform-native config dir (`~/.config/talk` / `~/Library/Application Support/talk` / `%APPDATA%\talk`). Provider endpoints configurable (testability, company server later). Per-user keys in V1; a central company server/gateway deliberately later.
|
||||||
- **Sprache/Stimmen**: de/en-Heuristik (reine Funktion, kein ML); `voice.<provider>.<lang>`-Mapping in der config.toml; persönliche ElevenLabs-Stimme (KXxZ…) als privater Default, neutrale Defaults im Repo.
|
- **Language/voices**: de/en heuristic (pure function, no ML); `voice.<provider>.<lang>` mapping in config.toml; personal ElevenLabs voice (KXxZ...) as private default, neutral defaults in the repo.
|
||||||
- **CLI-Verhalten**: non-blocking Default; Flags `--wait`, `--now` (Queue-Überprung für Dringendes), `--priority`, `--voice`, `--lang`, `--provider`. Befehle: say, wrap, mute, unmute, status, cancel, voices, test, doctor, setup.
|
- **CLI behaviour**: non-blocking by default; flags `--wait`, `--now` (queue bypass for urgent items), `--priority`, `--voice`, `--lang`, `--provider`. Commands: say, wrap, mute, unmute, status, cancel, voices, test, doctor, setup.
|
||||||
- **TUI (Bubble Tea)**: interaktiv = setup (Wizard), status (Live-Dashboard), voices (Picker mit Preview); plain & scriptbar = say, wrap, mute, cancel, test, doctor; kein TTY → immer plain.
|
- **TUI (Bubble Tea)**: interactive = setup (wizard), status (live dashboard), voices (picker with preview); plain and scriptable = say, wrap, mute, cancel, test, doctor; no TTY -> always plain.
|
||||||
- **Etikette (Skill-Policy)**: striktes Opt-in — Sprechen nur auf Nutzer-Trigger des Skills oder Standing-Order in der AGENTS.md; session-sticky bis Widerruf (Prompt-Level, kein Daemon-Session-State); Ansageinhalt = Status/nächster Schritt/wofür der Nutzer gebraucht wird, nie die Langantwort. Daemon-Backstop: Rate-Limit + Mute + Ruhezeiten gelten unabhängig vom Prompt.
|
- **Etiquette (skill policy)**: strict opt-in. Speaking only on a user trigger of the skill or a standing order in AGENTS.md; session-sticky until revoked (prompt level, no daemon session state); announcement content = status / next step / what the user is needed for, never the long answer. Daemon backstop: rate limit + mute + quiet hours apply regardless of the prompt.
|
||||||
- **Verteilung**: GoReleaser → Gitea-Releases, Asset-Schema `talk_<os>_<arch>` + sha256 (agent-lib-Vertrag); Firma spiegelt intern (pin_mirror-Muster) + Fleet-Role nach agent-lib/officecli-Vorbild (Program Files + Machine-PATH, admin-geschützte ProgramData-Config); Skill-Rollout Firma via az-agent-defaults → agent-lib Three-State-Sync; privat via flake.nix.
|
- **Distribution**: GoReleaser -> Gitea releases, asset schema `talk_<os>_<arch>` + sha256 (agent-lib contract); the company mirrors internally (pin_mirror pattern) + fleet role modelled on agent-lib/officecli (Program Files + machine PATH, admin-protected ProgramData config); company skill rollout via az-agent-defaults -> agent-lib three-state sync; private via flake.nix.
|
||||||
- **CI**: Gitea Actions — PR → Tests, Tag → Release-Matrix.
|
- **CI**: Gitea Actions: PR -> tests, tag -> release matrix.
|
||||||
- **Legacy-Abriss**: alte voice-notify/crunch-jobs-Skills (AGENTS-Repo) werden Redirect-Stubs; nixpkgs-PRs #24/#7 werden als superseded geschlossen; m3ta-nixpkgs talk/crunch nach Migration deprecatet; ElevenLabs-Key (exponiert in altem Prototyp-Skript) wird rotiert, danach das Skript gelöscht.
|
- **Legacy teardown**: the old voice-notify/crunch-jobs skills (AGENTS repo) become redirect stubs; nixpkgs PRs #24/#7 are closed as superseded; m3ta-nixpkgs talk/crunch deprecated after migration; the ElevenLabs key (exposed in the old prototype script) is rotated, then the script is deleted.
|
||||||
- **Naming**: Name bleibt `talk` (akzeptierte Kollision mit historischem Unix-talk; `say` vermieden wegen macOS).
|
- **Naming**: the name stays `talk` (accepted collision with the historical Unix talk; `say` avoided because of macOS).
|
||||||
|
|
||||||
## Testing Decisions
|
## Testing Decisions
|
||||||
|
|
||||||
- **Guter Test** testet ausschließlich extern beobachtbares Verhalten an der Schnittstelle, nie Implementationsdetails.
|
- **A good test** tests only externally observable behaviour at the interface, never implementation details.
|
||||||
- **Primäre Seam (eine)**: die Prozessgrenze von talkd — Daemon + CLI als Black Box, mit zwei über die Config injizierbaren Fakes: (1) Provider-Endpunkte zeigen im Test auf einen Fake-HTTP-Server mit Audio-Bytes; (2) `audio.sink = "null"` schaltet echtes Playback ab. An dieser Seam werden getestet: Queue-Serialisierung/Priorität/Rate-Limit/Verwerfen, Mute-Persistenz, Ruhezeiten, Fallback-Kette (Fake-Provider 500 → nächster Provider), non-blocking + `--wait`, Degraded Mode, HTTP-`/speak`-Vertrag inkl. CORS, MCP-Endpoint-Grundvertrag, status/cancel/doctor-Output.
|
- **Primary seam (one)**: the process boundary of talkd. Daemon + CLI as a black box, with two fakes injectable via config: (1) provider endpoints point to a fake HTTP server serving audio bytes in tests; (2) `audio.sink = "null"` disables real playback. Tested at this seam: queue serialisation/priority/rate limit/discarding, mute persistence, quiet hours, fallback chain (fake provider 500 -> next provider), non-blocking + `--wait`, degraded mode, HTTP `/speak` contract including CORS, MCP endpoint basic contract, status/cancel/doctor output.
|
||||||
- **Zwei reine Neben-Seams** (tischgesteuerte Unit-Tests, keine Mocks): Spracherkennung (de/en) und Config-Auflösung (Env + TOML-Merge).
|
- **Two pure side seams** (table-driven unit tests, no mocks): language detection (de/en) and config resolution (env + TOML merge).
|
||||||
- **Bewusst ungetestet** (hardware-/OS-gebunden): echtes Audio-Rendering und OS-Toasts — abgedeckt durch `talk doctor` als manuelles Diagnosewerkzeug.
|
- **Deliberately untested** (hardware/OS-bound): real audio rendering and OS toasts, covered by `talk doctor` as a manual diagnostic tool.
|
||||||
- **Vorläufer**: keine — grüne Wiese. CI läuft von Ticket 1 an in Gitea Actions mit.
|
- **Predecessors**: none, greenfield. CI runs in Gitea Actions from ticket 1 onwards.
|
||||||
|
|
||||||
## Out of Scope
|
## Out of Scope
|
||||||
|
|
||||||
- LibreChat-Frontend-Anbindung (CORS-Tür wird gebaut, Integration selbst nicht)
|
- LibreChat frontend integration (the CORS door is built, the integration itself is not)
|
||||||
- Browser-Extension als Brücke
|
- Browser extension as a bridge
|
||||||
- Zentraler Company-Gateway-Server (ein Key für alle)
|
- Central company gateway server (one key for everyone)
|
||||||
- Timer/Scheduling (`crunch at|in|daily` bleibt OS-nativ: cron/systemd/Task Scheduler)
|
- Timers/scheduling (`crunch at|in|daily` stays OS-native: cron/systemd/Task Scheduler)
|
||||||
- Lokale Neural-Stimmen (Piper/Kokoro) — späterer Ausbau
|
- Local neural voices (Piper/Kokoro), later expansion
|
||||||
- Kalenderbewusste Ruhezeiten (nur statische Zeitfenster in V1)
|
- Calendar-aware quiet hours (static time windows only in V1)
|
||||||
- Homebrew/Scoop/AUR-Feeds — später optional
|
- Homebrew/Scoop/AUR feeds, optional later
|
||||||
- Mehrnutzer-Maschinen (Ein-Nutzer-pro-Host wie im Fleet)
|
- Multi-user machines (one user per host as in the fleet)
|
||||||
|
|
||||||
## Further Notes
|
## Further Notes
|
||||||
|
|
||||||
- **Pending (Nutzer)**: ElevenLabs-Key-Rotation im Dashboard VOR Löschung des alten Prototyp-Skripts.
|
- **Pending (user)**: rotate the ElevenLabs key in the dashboard BEFORE deleting the old prototype script.
|
||||||
- Persönlicher Default-Voice: ElevenLabs `KXxZd16DiBqt82nbarJx` (aus altem Stack übernommen als privater Default, nicht Repo-Default).
|
- Personal default voice: ElevenLabs `KXxZd16DiBqt82nbarJx` (carried over from the old stack as private default, not the repo default).
|
||||||
- Session-Stickiness der Etikette ist Prompt/Skill-Level — der Daemon kennt keine Agent-Sessions.
|
- Session stickiness of the etiquette is prompt/skill level; the daemon knows nothing about agent sessions.
|
||||||
- Offene Später-Entscheidung: LibreChat-Anbindung via Frontend-Patch vs. Browser-Extension — blockiert nichts, Tür steht mit CORS-fähiger HTTP-API.
|
- Open decision for later: LibreChat integration via frontend patch vs. browser extension. Blocks nothing; the door is open with the CORS-capable HTTP API.
|
||||||
- Verwandte Firmen-ADRs: 0009 (agent-lib), 0012/0013 (Secrets-Env-Bridge/Machine-Env-Keys), 0016/0017 (user-scharfe Keys, MCP-Audience-Scoping) — talk folgt diesen Mustern.
|
- Related company ADRs: 0009 (agent-lib), 0012/0013 (secrets env bridge / machine env keys), 0016/0017 (user-scoped keys, MCP audience scoping). talk follows these patterns.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Nachtrag 2026-10-24 — Entscheidungen nach Architektur-Review
|
## Addendum 2026-10-24: decisions after the architecture review
|
||||||
|
|
||||||
Diese Punkte ersetzen die entsprechenden Aussagen oben (Grilling-Stand
|
These points replace the corresponding statements above (grilling state of
|
||||||
2026-10-18):
|
2026-10-18):
|
||||||
|
|
||||||
- **Ein Binary statt `talk` + `talkd`.** Der Daemon ist `talk daemon run`;
|
- **One binary instead of `talk` + `talkd`.** The daemon is `talk daemon run`;
|
||||||
`talk say`/`talk wrap` starten ihn beim ersten Sprechbefehl selbst im
|
`talk say`/`talk wrap` start it themselves in the background on the first
|
||||||
Hintergrund (`daemon.autostart`, Default an; `talk daemon start|stop`
|
speak command (`daemon.autostart`, on by default; `talk daemon start|stop`
|
||||||
explizit). Der Degraded Mode mit Lock-Datei entfällt; ohne erreichbaren
|
explicitly). The degraded mode with a lock file is dropped; without a
|
||||||
oder startbaren Daemon spricht talk direkt (unserialisiert, mit Hinweis).
|
reachable or startable daemon, talk speaks directly (unserialised, with a
|
||||||
- **CLI ist die Agenten-Schnittstelle.** MCP bleibt als Tür bestehen, ist
|
notice).
|
||||||
aber kein Fokus mehr; Browser-Zugriff ist serverseitig auf POST /speak
|
- **The CLI is the agent interface.** MCP remains as a door but is no longer
|
||||||
von gelisteten Origins beschränkt (Origin-Guard, nicht nur CORS).
|
a focus; browser access is restricted server-side to POST /speak from
|
||||||
- **`now:true` bricht bewusst aus der Ruhezeit aus** (bestätigt).
|
listed origins (origin guard, not just CORS).
|
||||||
- **Zwei weitere Gesetze:** `queue.max_text` (400 Zeichen, Kürzung an der
|
- **`now:true` deliberately breaks out of quiet hours** (confirmed).
|
||||||
Wortgrenze) und `queue.max_age` (2 min, veraltete Stau-Ansagen
|
- **Two more laws:** `queue.max_text` (400 characters, truncated at a word
|
||||||
verfallen).
|
boundary) and `queue.max_age` (2 min, stale backlog announcements expire).
|
||||||
- **Zielbild Veröffentlichung:** talk soll perspektivisch öffentlich
|
- **Target picture for publication:** talk should eventually be usable
|
||||||
nutzbar sein. Oberstes Kriterium ist Usability für Nicht-Terminal-
|
publicly. The top criterion is usability for non-terminal users; the
|
||||||
Nutzer; die Bubble-Tea-TUI ist kein Selbstzweck — einfache, klare
|
Bubble Tea TUI is not an end in itself. Simple, clear commands (`doctor`,
|
||||||
Befehle (`doctor`, `setup`, `test`, `voices`) haben Vorrang.
|
`setup`, `test`, `voices`) take precedence.
|
||||||
|
- **Release without GoReleaser:** `scripts/release.sh` builds the six targets
|
||||||
|
with `go build`; `.gitea/workflows/release.yml` creates the Gitea release
|
||||||
|
on tag `v*`. Asset contract unchanged (`talk_<os>_<arch>[.exe]` +
|
||||||
|
`checksums.txt`). `flake.nix` provides package, app, overlay and devShell.
|
||||||
|
- **Notifications without beeep:** desktop toast via the OS's own tools
|
||||||
|
(notify-send / osascript / PowerShell), exec-based like osbuiltin;
|
||||||
|
initially only for `quiet_mode = "toast"`. Cancel button: later.
|
||||||
|
- **Icon and toast identity (2026-10-25):** one SVG icon (speech bubble
|
||||||
|
with level bars), rendered into the binary: PNG for notifications (Linux
|
||||||
|
app_icon, Windows toast), `.syso` resources for talk.exe. On Windows the
|
||||||
|
daemon registers talk's own AppUserModelID `m3ta.talk` under HKCU (no
|
||||||
|
shortcut, no admin), so toasts appear as "talk" with the icon instead of
|
||||||
|
Windows PowerShell.
|
||||||
Generated
+27
@@ -0,0 +1,27 @@
|
|||||||
|
{
|
||||||
|
"nodes": {
|
||||||
|
"nixpkgs": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1792502884,
|
||||||
|
"narHash": "sha256-IoNisKcGbUjdd45qCqywGMCYmZ5EnkxezvLII0FWwNA=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "02c087f3fe673c9e317f206a627cb6b910336dbe",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixos-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs": "nixpkgs"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": "root",
|
||||||
|
"version": 7
|
||||||
|
}
|
||||||
@@ -1,13 +1,13 @@
|
|||||||
{
|
{
|
||||||
# talk — Sprach-Ausgaben für Skripte und KI-Agenten.
|
# talk: voice notifications for scripts and AI agents.
|
||||||
#
|
#
|
||||||
# Nutzung in einer NixOS-/Home-Manager-Konfiguration:
|
# Usage in a NixOS / Home Manager configuration:
|
||||||
# inputs.talk.url = "git+https://code.m3ta.dev/m3tam3re/talk";
|
# inputs.talk.url = "git+https://code.m3ta.dev/m3tam3re/talk";
|
||||||
# environment.systemPackages = [ inputs.talk.packages.${system}.talk ];
|
# environment.systemPackages = [ inputs.talk.packages.${system}.talk ];
|
||||||
# oder als Overlay: nixpkgs.overlays = [ inputs.talk.overlays.default ];
|
# or as an overlay: nixpkgs.overlays = [ inputs.talk.overlays.default ];
|
||||||
#
|
#
|
||||||
# Dieses Flake ersetzt langfristig m3ta-nixpkgs talk/crunch (bash + mpv).
|
# In the long run this flake replaces m3ta-nixpkgs talk/crunch (bash + mpv).
|
||||||
description = "talk — Voice-Notifications für Skripte und KI-Agenten (ein Binary, Daemon mit Queue)";
|
description = "talk: voice notifications for scripts and AI agents (one binary, daemon with queue)";
|
||||||
|
|
||||||
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||||
|
|
||||||
@@ -21,16 +21,16 @@
|
|||||||
inherit version;
|
inherit version;
|
||||||
src = self;
|
src = self;
|
||||||
subPackages = [ "cmd/talk" ];
|
subPackages = [ "cmd/talk" ];
|
||||||
# Nach Änderungen an go.mod/go.sum neu setzen: `nix build` nennt den
|
# Update after changes to go.mod/go.sum: `nix build` prints the
|
||||||
# erwarteten Hash.
|
# expected hash.
|
||||||
vendorHash = "sha256-CbF3juTA7V05hh1ElKKACddsCn4bIPeLZxsz2EZxs9I=";
|
vendorHash = "sha256-Cne8FiMlpsrFfntMJVtV4D3CzEWQ4Jnd+tIEHF9ecEc=";
|
||||||
env.CGO_ENABLED = 0;
|
env.CGO_ENABLED = 0;
|
||||||
ldflags = [ "-s" "-w" "-X" "main.version=${version}" "-X" "main.commit=${self.shortRev or "dirty"}" ];
|
ldflags = [ "-s" "-w" "-X" "main.version=${version}" "-X" "main.commit=${self.shortRev or "dirty"}" ];
|
||||||
# Prozessgrenzen-Tests starten Daemons und binden Ports — nicht in der Sandbox.
|
# The process-boundary tests start daemons and bind ports; not in the sandbox.
|
||||||
doCheck = false;
|
doCheck = false;
|
||||||
# Audio: oto spricht PulseAudio/PipeWire direkt (reines Go) und fällt auf
|
# Audio: oto talks to PulseAudio/PipeWire directly (pure Go) and falls
|
||||||
# ALSA zurück, das es zur Laufzeit per dlopen lädt — auf NixOS nur
|
# back to ALSA, which it loads at runtime via dlopen; on NixOS that is
|
||||||
# auffindbar, wenn wir es in den Pfad legen. OS-Stimme: espeak-ng.
|
# only found if we put it on the path. OS voice: espeak-ng.
|
||||||
nativeBuildInputs = pkgs.lib.optionals pkgs.stdenv.isLinux [ pkgs.makeWrapper ];
|
nativeBuildInputs = pkgs.lib.optionals pkgs.stdenv.isLinux [ pkgs.makeWrapper ];
|
||||||
postInstall = pkgs.lib.optionalString pkgs.stdenv.isLinux ''
|
postInstall = pkgs.lib.optionalString pkgs.stdenv.isLinux ''
|
||||||
wrapProgram $out/bin/talk \
|
wrapProgram $out/bin/talk \
|
||||||
@@ -38,7 +38,7 @@
|
|||||||
--prefix PATH : ${pkgs.lib.makeBinPath [ pkgs.espeak-ng pkgs.libnotify ]}
|
--prefix PATH : ${pkgs.lib.makeBinPath [ pkgs.espeak-ng pkgs.libnotify ]}
|
||||||
'';
|
'';
|
||||||
meta = with pkgs.lib; {
|
meta = with pkgs.lib; {
|
||||||
description = "Voice-Notifications für Skripte und KI-Agenten";
|
description = "Voice notifications for scripts and AI agents";
|
||||||
homepage = "https://code.m3ta.dev/m3tam3re/talk";
|
homepage = "https://code.m3ta.dev/m3tam3re/talk";
|
||||||
license = licenses.mit;
|
license = licenses.mit;
|
||||||
mainProgram = "talk";
|
mainProgram = "talk";
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ go 1.26.8
|
|||||||
require (
|
require (
|
||||||
github.com/BurntSushi/toml v1.6.0
|
github.com/BurntSushi/toml v1.6.0
|
||||||
github.com/ebitengine/oto/v3 v3.5.0
|
github.com/ebitengine/oto/v3 v3.5.0
|
||||||
|
github.com/godbus/dbus/v5 v5.2.4
|
||||||
github.com/gorilla/websocket v1.5.3
|
github.com/gorilla/websocket v1.5.3
|
||||||
github.com/hajimehoshi/go-mp3 v0.3.4
|
github.com/hajimehoshi/go-mp3 v0.3.4
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ github.com/ebitengine/oto/v3 v3.5.0 h1:8ZDhKP3Hhslyb9NL3g4HWvhRQqwI+hKOHAXAqD6GP
|
|||||||
github.com/ebitengine/oto/v3 v3.5.0/go.mod h1:Elkm7yzTRns3w2efvibzVOoQ65YOwmec9a76dCiK10o=
|
github.com/ebitengine/oto/v3 v3.5.0/go.mod h1:Elkm7yzTRns3w2efvibzVOoQ65YOwmec9a76dCiK10o=
|
||||||
github.com/ebitengine/purego v0.11.0 h1:jhp/D+Nyv7UUW8HAcmcjt2N2rYrYi9m3SL21k0Ua/NI=
|
github.com/ebitengine/purego v0.11.0 h1:jhp/D+Nyv7UUW8HAcmcjt2N2rYrYi9m3SL21k0Ua/NI=
|
||||||
github.com/ebitengine/purego v0.11.0/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ=
|
github.com/ebitengine/purego v0.11.0/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ=
|
||||||
|
github.com/godbus/dbus/v5 v5.2.4 h1:F2gUCy++NMIxGmo9J+z5le/+ZC8W1OgeR51P4i9ZB/U=
|
||||||
|
github.com/godbus/dbus/v5 v5.2.4/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
|
||||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
github.com/hajimehoshi/go-mp3 v0.3.4 h1:NUP7pBYH8OguP4diaTZ9wJbUbk3tC0KlfzsEpWmYj68=
|
github.com/hajimehoshi/go-mp3 v0.3.4 h1:NUP7pBYH8OguP4diaTZ9wJbUbk3tC0KlfzsEpWmYj68=
|
||||||
|
|||||||
+29
-20
@@ -11,19 +11,19 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Client ist der HTTP-Client der CLI für den Daemon auf 127.0.0.1 —
|
// Client is the CLI's HTTP client for the daemon on 127.0.0.1; the same
|
||||||
// dieselbe Vertragsschnittstelle, die server.go bedient.
|
// contract that server.go serves.
|
||||||
type Client struct {
|
type Client struct {
|
||||||
// BaseURL ist die Daemon-Adresse (http://127.0.0.1:<port>).
|
// BaseURL is the daemon address (http://127.0.0.1:<port>).
|
||||||
BaseURL string
|
BaseURL string
|
||||||
|
|
||||||
// HTTP ist der verwendete Client; nil wird von NewClient gesetzt.
|
// HTTP is the client in use; NewClient sets it when nil.
|
||||||
HTTP *http.Client
|
HTTP *http.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewClient baut den Client für einen Daemon-Port. Zeit-Budgets steuert der
|
// NewClient builds the client for a daemon port. The caller controls time
|
||||||
// Aufrufer pro Aufruf über den Context (Daemon-Erkennung kurz, /speak
|
// budgets per call via the context (daemon detection short, /speak more
|
||||||
// großzügiger); das Client-Timeout ist nur die harte Decke.
|
// generous); the client timeout is only the hard ceiling.
|
||||||
func NewClient(port int) *Client {
|
func NewClient(port int) *Client {
|
||||||
return &Client{
|
return &Client{
|
||||||
BaseURL: fmt.Sprintf("http://127.0.0.1:%d", port),
|
BaseURL: fmt.Sprintf("http://127.0.0.1:%d", port),
|
||||||
@@ -31,10 +31,10 @@ func NewClient(port int) *Client {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// HTTPError ist eine Daemon-Antwort mit unerwartetem Status-Code (z. B.
|
// HTTPError is a daemon response with an unexpected status code (e.g. 400
|
||||||
// 400 Validierung). Netz-Fehler (Daemon tot) sind dagegen reguläre
|
// validation). Network errors (daemon dead) are regular *url.Error values
|
||||||
// *url.Error-Werte — die CLI unterscheidet danach: HTTP-Fehler anzeigen,
|
// instead; the CLI distinguishes by that: show HTTP errors, fall into
|
||||||
// Netz-Fehler → Degraded Mode.
|
// degraded mode on network errors.
|
||||||
type HTTPError struct {
|
type HTTPError struct {
|
||||||
Status int
|
Status int
|
||||||
Body string
|
Body string
|
||||||
@@ -44,7 +44,7 @@ func (e *HTTPError) Error() string {
|
|||||||
return fmt.Sprintf("HTTP %d: %s", e.Status, e.Body)
|
return fmt.Sprintf("HTTP %d: %s", e.Status, e.Body)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Status ruft GET /status (Daemon-Erkennung, --wait-Polling).
|
// Status calls GET /status (daemon detection, --wait polling).
|
||||||
func (c *Client) Status(ctx context.Context) (*StatusResponse, error) {
|
func (c *Client) Status(ctx context.Context) (*StatusResponse, error) {
|
||||||
var st StatusResponse
|
var st StatusResponse
|
||||||
if err := c.do(ctx, http.MethodGet, "/status", nil, http.StatusOK, &st); err != nil {
|
if err := c.do(ctx, http.MethodGet, "/status", nil, http.StatusOK, &st); err != nil {
|
||||||
@@ -53,7 +53,7 @@ func (c *Client) Status(ctx context.Context) (*StatusResponse, error) {
|
|||||||
return &st, nil
|
return &st, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Speak ruft POST /speak (enqueue).
|
// Speak calls POST /speak (enqueue).
|
||||||
func (c *Client) Speak(ctx context.Context, req SpeakRequest) (*SpeakResponse, error) {
|
func (c *Client) Speak(ctx context.Context, req SpeakRequest) (*SpeakResponse, error) {
|
||||||
var resp SpeakResponse
|
var resp SpeakResponse
|
||||||
if err := c.do(ctx, http.MethodPost, "/speak", req, http.StatusAccepted, &resp); err != nil {
|
if err := c.do(ctx, http.MethodPost, "/speak", req, http.StatusAccepted, &resp); err != nil {
|
||||||
@@ -62,8 +62,7 @@ func (c *Client) Speak(ctx context.Context, req SpeakRequest) (*SpeakResponse, e
|
|||||||
return &resp, nil
|
return &resp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cancel ruft POST /cancel; Rückgabe ist die Zahl der abgebrochenen
|
// Cancel calls POST /cancel; returns the number of cancelled announcements.
|
||||||
// Ansagen.
|
|
||||||
func (c *Client) Cancel(ctx context.Context) (int, error) {
|
func (c *Client) Cancel(ctx context.Context) (int, error) {
|
||||||
var resp CancelResponse
|
var resp CancelResponse
|
||||||
if err := c.do(ctx, http.MethodPost, "/cancel", nil, http.StatusOK, &resp); err != nil {
|
if err := c.do(ctx, http.MethodPost, "/cancel", nil, http.StatusOK, &resp); err != nil {
|
||||||
@@ -72,7 +71,17 @@ func (c *Client) Cancel(ctx context.Context) (int, error) {
|
|||||||
return resp.Cancelled, nil
|
return resp.Cancelled, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetMute ruft POST /mute (muted=true) bzw. POST /unmute (muted=false).
|
// CancelItem calls POST /cancel-item; it reports whether the id was the
|
||||||
|
// playing announcement.
|
||||||
|
func (c *Client) CancelItem(ctx context.Context, id string) (bool, error) {
|
||||||
|
var resp CancelItemResponse
|
||||||
|
if err := c.do(ctx, http.MethodPost, "/cancel-item", CancelItemRequest{ID: id}, http.StatusOK, &resp); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return resp.Cancelled, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetMute calls POST /mute (muted=true) or POST /unmute (muted=false).
|
||||||
func (c *Client) SetMute(ctx context.Context, muted bool) error {
|
func (c *Client) SetMute(ctx context.Context, muted bool) error {
|
||||||
path := "/mute"
|
path := "/mute"
|
||||||
if !muted {
|
if !muted {
|
||||||
@@ -81,14 +90,14 @@ func (c *Client) SetMute(ctx context.Context, muted bool) error {
|
|||||||
return c.do(ctx, http.MethodPost, path, nil, http.StatusOK, nil)
|
return c.do(ctx, http.MethodPost, path, nil, http.StatusOK, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Shutdown ruft POST /shutdown (`talk daemon stop`).
|
// Shutdown calls POST /shutdown (`talk daemon stop`).
|
||||||
func (c *Client) Shutdown(ctx context.Context) error {
|
func (c *Client) Shutdown(ctx context.Context) error {
|
||||||
return c.do(ctx, http.MethodPost, "/shutdown", nil, http.StatusOK, nil)
|
return c.do(ctx, http.MethodPost, "/shutdown", nil, http.StatusOK, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
// do ist der gemeinsame Kern: Request bauen, senden, Status prüfen,
|
// do is the shared core: build the request, send it, check the status,
|
||||||
// dekodieren. Netz-Fehler kommen ungefiltert zurück (Aufrufer unterscheidet
|
// decode. Network errors are returned unfiltered (the caller distinguishes
|
||||||
// über errors.As(&HTTPError)).
|
// via errors.As(&HTTPError)).
|
||||||
func (c *Client) do(ctx context.Context, method, path string, body any, wantStatus int, out any) error {
|
func (c *Client) do(ctx context.Context, method, path string, body any, wantStatus int, out any) error {
|
||||||
var rd io.Reader
|
var rd io.Reader
|
||||||
if body != nil {
|
if body != nil {
|
||||||
|
|||||||
+39
-42
@@ -5,28 +5,26 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CORS-Tür für POST /speak (Task 06) — und NUR für diesen Endpunkt: Ein
|
// CORS door for POST /speak, and ONLY for this endpoint: a browser (e.g. a
|
||||||
// Browser (z. B. eine spätere LibreChat-Integration) darf genau die Ansage-
|
// later LibreChat integration) may call exactly the announcement interface
|
||||||
// Schnittstelle cross-origin rufen, keine Steuer-Endpunkte. Die Erlaubnis
|
// cross-origin, never the control endpoints. Permission comes exclusively
|
||||||
// kommt ausschließlich aus der Config-Liste server.allowed_origins
|
// from the config list server.allowed_origins (env TALK_ALLOWED_ORIGINS):
|
||||||
// (Env TALK_ALLOWED_ORIGINS): exakte Origins wie
|
// exact origins such as "https://chat.example.com"; the entry "*" explicitly
|
||||||
// "https://chat.az-gruppe.com"; der Eintrag "*" erlaubt jede Origin
|
// allows any origin. Deliberate default: EMPTY. The daemon then sends no
|
||||||
// ausdrücklich. Bewusster Default: LEER — dann sendet der Daemon gar keine
|
// CORS headers at all and the browser blocks (door closed until configured).
|
||||||
// CORS-Header und der Browser blockt (Tür zu, bis sie konfiguriert wird).
|
|
||||||
//
|
//
|
||||||
// Die Tür ist serverseitig zu, nicht nur browserseitig (originGuard): CORS
|
// The door is closed server-side, not only browser-side (originGuard): CORS
|
||||||
// allein verhindert nur das LESEN der Antwort, nicht die Wirkung — ein
|
// alone only prevents READING the response, not the effect. A browser sends
|
||||||
// Browser schickt einen POST mit text/plain-Body oder ein Formular ohne
|
// a POST with a text/plain body or a form without preflight, and a server
|
||||||
// Preflight ab, und ein Server, der den Body dennoch als JSON liest, hätte
|
// that still reads the body as JSON would have spoken, muted or cancelled.
|
||||||
// gesprochen, gemutet oder abgebrochen. Deshalb lehnt talkd jede Anfrage
|
// Therefore talkd rejects every request with a foreign Origin header (403)
|
||||||
// mit fremdem Origin-Header ab (403), die nicht der erlaubte Weg über
|
// that is not the permitted path via /speak. Only the preflight OPTIONS
|
||||||
// /speak ist. Nur der Preflight OPTIONS /speak bleibt für ungelistete
|
// /speak stays a 204 without CORS headers for unlisted origins (it has no
|
||||||
// Origins ein 204 ohne CORS-Header (er hat keine Wirkung; der Browser
|
// effect; the browser drops the planned POST). CLI, curl and other
|
||||||
// verwirft den geplanten POST). CLI, curl und andere Nicht-Browser-Clients
|
// non-browser clients send no Origin header and are unaffected.
|
||||||
// senden keinen Origin-Header und sind nicht betroffen.
|
|
||||||
|
|
||||||
// CORS-Antwort-Header (Namen zentral, damit Preflight und echter POST
|
// CORS response headers (names in one place so preflight and the real POST
|
||||||
// dieselben setzen).
|
// set the same ones).
|
||||||
const (
|
const (
|
||||||
headerAllowOrigin = "Access-Control-Allow-Origin"
|
headerAllowOrigin = "Access-Control-Allow-Origin"
|
||||||
headerAllowMethods = "Access-Control-Allow-Methods"
|
headerAllowMethods = "Access-Control-Allow-Methods"
|
||||||
@@ -35,13 +33,13 @@ const (
|
|||||||
headerVary = "Vary"
|
headerVary = "Vary"
|
||||||
)
|
)
|
||||||
|
|
||||||
// preflightAge ist die Preflight-Cache-Dauer: 10 Minuten reichen für eine
|
// preflightAge is the preflight cache duration: 10 minutes cover a chat
|
||||||
// Chat-Session und halten den OPTIONS-Chatter klein.
|
// session and keep the OPTIONS chatter small.
|
||||||
const preflightAge = "600"
|
const preflightAge = "600"
|
||||||
|
|
||||||
// corsACAOLiefert den Wert für Access-Control-Allow-Origin: bei Wildcard-
|
// corsACAO returns the value for Access-Control-Allow-Origin: the literal
|
||||||
// Konfiguration das literale "*", sonst die exakt gematchte Origin (die
|
// "*" for a wildcard configuration, otherwise the exactly matched origin
|
||||||
// identisch mit dem Config-Eintrag ist). Leer heißt: nicht erlaubt.
|
// (identical to the config entry). Empty means: not allowed.
|
||||||
func (h *handler) corsACAO(r *http.Request) string {
|
func (h *handler) corsACAO(r *http.Request) string {
|
||||||
origin := r.Header.Get("Origin")
|
origin := r.Header.Get("Origin")
|
||||||
if origin == "" {
|
if origin == "" {
|
||||||
@@ -58,10 +56,9 @@ func (h *handler) corsACAO(r *http.Request) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// setSpeakCors setzt die CORS-Header auf echten POST-/speak-Antworten,
|
// setSpeakCors sets the CORS headers on real POST /speak responses when the
|
||||||
// wenn die Anfrage-Origin erlaubt ist. Vary: Origin steht immer (auch bei
|
// request origin is allowed. Vary: Origin is always present (even with the
|
||||||
// geschlossener Tür), damit Caches die Antwort nie fälschlich origin-
|
// door closed) so caches never wrongly reuse the response across origins.
|
||||||
// übergreifend wiederverwenden.
|
|
||||||
func (h *handler) setSpeakCors(w http.ResponseWriter, r *http.Request) {
|
func (h *handler) setSpeakCors(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Add(headerVary, "Origin")
|
w.Header().Add(headerVary, "Origin")
|
||||||
if acao := h.corsACAO(r); acao != "" {
|
if acao := h.corsACAO(r); acao != "" {
|
||||||
@@ -69,11 +66,11 @@ func (h *handler) setSpeakCors(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// speakPreflight behandelt OPTIONS /speak (CORS-Preflight): 204 mit den
|
// speakPreflight handles OPTIONS /speak (CORS preflight): 204 with the
|
||||||
// Freigabe-Headern bei gelisteter Origin, 204 ohne jegliche CORS-Header
|
// permission headers for a listed origin, 204 without any CORS headers
|
||||||
// sonst (ungelistet, fehlend oder Tür komplett zu) — der Browser verwirft
|
// otherwise (unlisted, missing or door completely closed). The browser
|
||||||
// den eigentlichen Request, während der Daemon für Nicht-Browser-Clients
|
// drops the actual request while the daemon stays reachable for
|
||||||
// erreichbar bleibt.
|
// non-browser clients.
|
||||||
func (h *handler) speakPreflight(w http.ResponseWriter, r *http.Request) {
|
func (h *handler) speakPreflight(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Add(headerVary, "Origin")
|
w.Header().Add(headerVary, "Origin")
|
||||||
if acao := h.corsACAO(r); acao != "" {
|
if acao := h.corsACAO(r); acao != "" {
|
||||||
@@ -85,13 +82,13 @@ func (h *handler) speakPreflight(w http.ResponseWriter, r *http.Request) {
|
|||||||
w.WriteHeader(http.StatusNoContent)
|
w.WriteHeader(http.StatusNoContent)
|
||||||
}
|
}
|
||||||
|
|
||||||
// originGuard ist die Middleware vor dem Router: Anfragen mit Origin-Header
|
// originGuard is the middleware in front of the router: requests with an
|
||||||
// (also aus einem Browser) kommen nur als OPTIONS /speak (Preflight, ohne
|
// Origin header (i.e. from a browser) only pass as OPTIONS /speak (preflight,
|
||||||
// Wirkung) oder als POST /speak von gelisteter Origin durch. Alles andere —
|
// no effect) or as POST /speak from a listed origin. Everything else
|
||||||
// ungelistete Origin auf /speak, jeder Browser-Zugriff auf Steuer-Endpunkte
|
// (unlisted origin on /speak, any browser access to control endpoints and
|
||||||
// und /mcp — wird mit 403 abgelehnt, bevor ein Body gelesen oder eine
|
// /mcp) is rejected with 403 before a body is read or an effect is
|
||||||
// Wirkung ausgelöst wird. Ohne Origin-Header (CLI, curl, MCP-Clients)
|
// triggered. Without an Origin header (CLI, curl, MCP clients) nothing
|
||||||
// passiert nichts.
|
// happens.
|
||||||
func (h *handler) originGuard(next http.Handler) http.Handler {
|
func (h *handler) originGuard(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
origin := r.Header.Get("Origin")
|
origin := r.Header.Get("Origin")
|
||||||
@@ -106,6 +103,6 @@ func (h *handler) originGuard(next http.Handler) http.Handler {
|
|||||||
}
|
}
|
||||||
w.Header().Add(headerVary, "Origin")
|
w.Header().Add(headerVary, "Origin")
|
||||||
writeError(w, http.StatusForbidden,
|
writeError(w, http.StatusForbidden,
|
||||||
"Origin "+origin+" ist nicht erlaubt (Browser-Zugriff nur auf POST /speak von gelisteten Origins in server.allowed_origins)")
|
"origin "+origin+" is not allowed (browsers may only POST /speak from origins listed in server.allowed_origins)")
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
+9
-10
@@ -1,11 +1,10 @@
|
|||||||
// Package api definiert die HTTP-Oberfläche des Daemons auf 127.0.0.1:
|
// Package api defines the daemon's HTTP surface on 127.0.0.1: POST /speak
|
||||||
// POST /speak (enqueue, 202 {id}; bei Mute 202 {muted:true}; bei Gesetz-
|
// (enqueue, 202 {id}; 202 {muted:true} when muted; 202
|
||||||
// Verwurf 202 {discarded:"rate_limit"|"quiet_hours"} — Task 05),
|
// {discarded:"rate_limit"|"quiet_hours"} when a law discards), GET /status
|
||||||
// GET /status (inkl. Gesetz-State, mcp/cors — Task 06), POST /cancel,
|
// (including law state, mcp/cors), POST /cancel, POST /mute, POST /unmute.
|
||||||
// POST /mute, POST /unmute. Task 06 ergänzt die CORS-Tür für POST /speak
|
// It also provides the CORS door for POST /speak (OPTIONS preflight + ACAO
|
||||||
// (OPTIONS-Preflight + ACAO aus server.allowed_origins, siehe cors.go)
|
// from server.allowed_origins, see cors.go) and the MCP endpoint POST /mcp
|
||||||
// und den MCP-Endpoint POST /mcp als schlankes eigenes JSON-RPC-Subset
|
// as a lean JSON-RPC subset of its own (initialize,
|
||||||
// (initialize, notifications/initialized, tools/list, tools/call mit dem
|
// notifications/initialized, tools/list, tools/call with the speak tool;
|
||||||
// speak-Tool — siehe mcp.go). Der Client-Teil ist die CLI-Seite derselben
|
// see mcp.go). The client part is the CLI side of the same contract.
|
||||||
// Vertragsschnittstelle.
|
|
||||||
package api
|
package api
|
||||||
+94
-98
@@ -10,33 +10,32 @@ import (
|
|||||||
"code.m3ta.dev/m3tam3re/talk/internal/queue"
|
"code.m3ta.dev/m3tam3re/talk/internal/queue"
|
||||||
)
|
)
|
||||||
|
|
||||||
// MCP-Endpoint (Task 06): Streamable HTTP auf POST /mcp — eine eigene,
|
// MCP endpoint: Streamable HTTP on POST /mcp, a lean implementation of our
|
||||||
// schlanke Implementierung des JSON-RPC-2.0-Subsets, das MCP tatsächlich
|
// own of the JSON-RPC 2.0 subset that MCP actually needs (deliberately NO
|
||||||
// braucht (bewusst KEIN SDK-Dependency; der Protokollumfang hier ist vier
|
// SDK dependency; the protocol scope here is four methods plus ping).
|
||||||
// Methoden plus ping). Semantik nach MCP 2025-06-18, mit zwei
|
// Semantics per MCP 2025-06-18, with two documented simplifications the
|
||||||
// dokumentierten Vereinfachungen, die der Transport hergibt:
|
// transport allows:
|
||||||
//
|
//
|
||||||
// - Zustandslos: Jeder POST ist unabhängig; es gibt keine Session-IDs
|
// - Stateless: every POST is independent; there are no session IDs
|
||||||
// (Mcp-Session-Id wird ignoriert) und damit auch keine Durchsetzung
|
// (Mcp-Session-Id is ignored) and therefore no enforcement of the
|
||||||
// der Initialize-vor-allem-Regel — ein curl kann tools/call direkt
|
// initialize-first rule; a curl can call tools/call directly. MCP
|
||||||
// rufen. MCP-Clients stört das nicht: Sie fahren den Handshake
|
// clients do not mind: they run the handshake voluntarily.
|
||||||
// freiwillig.
|
// - No server-initiated streams: talkd never pushes (the tool list is
|
||||||
// - Keine server-initiierten Streams: talkd pusht nie (die Tool-Liste
|
// static). GET /mcp therefore answers 405, the response the Streamable
|
||||||
// ist statisch). GET /mcp antwortet daher 405 — die vom Streamable-
|
// HTTP transport specifies for servers without an SSE stream.
|
||||||
// HTTP-Transport vorgesehene Antwort für Server ohne SSE-Stream.
|
|
||||||
//
|
//
|
||||||
// Antworten: Requests → 200 application/json (JSON-RPC-Fehlerobjekte
|
// Responses: requests get 200 application/json (JSON-RPC error objects also
|
||||||
// ebenfalls 200 — der HTTP-Teil war ja erfolgreich); Notifications → 202
|
// 200; the HTTP part did succeed); notifications get 202 without a body
|
||||||
// ohne Body (JSON-RPC 2.0). Batches (Arrays) sind seit 2025-06-18 nicht
|
// (JSON-RPC 2.0). Batches (arrays) are no longer part of MCP since
|
||||||
// mehr Teil von MCP → -32600.
|
// 2025-06-18 and yield -32600.
|
||||||
|
|
||||||
// mcpProtocolVersion ist die Version, die talkd selbst spricht, wenn der
|
// mcpProtocolVersion is the version talkd itself speaks when the client
|
||||||
// Client keine angibt (initialize ohne protocolVersion). Angefragte
|
// names none (initialize without protocolVersion). Requested versions are
|
||||||
// Versionen werden akzeptiert und zurückgegeben (Echo) — inhaltlich
|
// accepted and echoed back; what is implemented is the 2025-06-18 scope
|
||||||
// implementiert ist der oben dokumentierte 2025-06-18-Umfang.
|
// documented above.
|
||||||
const mcpProtocolVersion = "2025-06-18"
|
const mcpProtocolVersion = "2025-06-18"
|
||||||
|
|
||||||
// JSON-RPC-2.0-Fehlercodes (benutztes Subset).
|
// JSON-RPC 2.0 error codes (subset in use).
|
||||||
const (
|
const (
|
||||||
rpcParseError = -32700
|
rpcParseError = -32700
|
||||||
rpcInvalidRequest = -32600
|
rpcInvalidRequest = -32600
|
||||||
@@ -45,12 +44,11 @@ const (
|
|||||||
rpcInternalError = -32603
|
rpcInternalError = -32603
|
||||||
)
|
)
|
||||||
|
|
||||||
// mcpServerName ist der serverInfo-Name im Initialize-Ergebnis.
|
// mcpServerName is the serverInfo name in the initialize result.
|
||||||
const mcpServerName = "talkd"
|
const mcpServerName = "talkd"
|
||||||
|
|
||||||
// jsonRPCRequest ist eine eingehende JSON-RPC-Nachricht. ID als
|
// jsonRPCRequest is an incoming JSON-RPC message. ID as RawMessage keeps
|
||||||
// RawMessage: So bleibt zwischen „Feld fehlt" (Notification) und id:0
|
// "field missing" (notification) distinguishable from id:0 or id:string.
|
||||||
// bzw. id:string unterscheidbar.
|
|
||||||
type jsonRPCRequest struct {
|
type jsonRPCRequest struct {
|
||||||
JSONRPC string `json:"jsonrpc"`
|
JSONRPC string `json:"jsonrpc"`
|
||||||
ID json.RawMessage `json:"id"`
|
ID json.RawMessage `json:"id"`
|
||||||
@@ -58,9 +56,9 @@ type jsonRPCRequest struct {
|
|||||||
Params json.RawMessage `json:"params"`
|
Params json.RawMessage `json:"params"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// jsonRPCResponse ist eine ausgehende JSON-RPC-Nachricht. Genau eines aus
|
// jsonRPCResponse is an outgoing JSON-RPC message. Exactly one of
|
||||||
// Result/Error ist gesetzt. ID ist nie weggelassen — bei Parse-Fehlern
|
// Result/Error is set. ID is never omitted; null on parse errors without a
|
||||||
// ohne bekannte ID null (JSON-RPC 2.0).
|
// known ID (JSON-RPC 2.0).
|
||||||
type jsonRPCResponse struct {
|
type jsonRPCResponse struct {
|
||||||
JSONRPC string `json:"jsonrpc"`
|
JSONRPC string `json:"jsonrpc"`
|
||||||
ID json.RawMessage `json:"id"`
|
ID json.RawMessage `json:"id"`
|
||||||
@@ -68,112 +66,112 @@ type jsonRPCResponse struct {
|
|||||||
Error *rpcError `json:"error,omitempty"`
|
Error *rpcError `json:"error,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// rpcError ist das Fehlerobjekt einer JSON-RPC-Antwort.
|
// rpcError is the error object of a JSON-RPC response.
|
||||||
type rpcError struct {
|
type rpcError struct {
|
||||||
Code int `json:"code"`
|
Code int `json:"code"`
|
||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// mcpInitializeParams sind die relevanten Teile der initialize-Parameter
|
// mcpInitializeParams holds the relevant parts of the initialize params
|
||||||
// (Client-Capabilities interessieren talkd nicht — Tools genügen).
|
// (client capabilities do not interest talkd; tools suffice).
|
||||||
type mcpInitializeParams struct {
|
type mcpInitializeParams struct {
|
||||||
ProtocolVersion string `json:"protocolVersion"`
|
ProtocolVersion string `json:"protocolVersion"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// mcpServerInfo beschreibt den Server im Initialize-Ergebnis.
|
// mcpServerInfo describes the server in the initialize result.
|
||||||
type mcpServerInfo struct {
|
type mcpServerInfo struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Version string `json:"version"`
|
Version string `json:"version"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// mcpCapabilities meldet im Initialize-Ergebnis, was talkd anbietet:
|
// mcpCapabilities reports in the initialize result what talkd offers:
|
||||||
// Tools (speak) — sonst nichts.
|
// tools (speak), nothing else.
|
||||||
type mcpCapabilities struct {
|
type mcpCapabilities struct {
|
||||||
Tools map[string]any `json:"tools"`
|
Tools map[string]any `json:"tools"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// mcpInitializeResult ist das Ergebnis von initialize: die (geechote)
|
// mcpInitializeResult is the result of initialize: the (echoed) protocol
|
||||||
// Protokollversion, die Fähigkeiten und die Server-Info — 2025-06-18-Form.
|
// version, the capabilities and the server info, in 2025-06-18 form.
|
||||||
type mcpInitializeResult struct {
|
type mcpInitializeResult struct {
|
||||||
ProtocolVersion string `json:"protocolVersion"`
|
ProtocolVersion string `json:"protocolVersion"`
|
||||||
Capabilities mcpCapabilities `json:"capabilities"`
|
Capabilities mcpCapabilities `json:"capabilities"`
|
||||||
ServerInfo mcpServerInfo `json:"serverInfo"`
|
ServerInfo mcpServerInfo `json:"serverInfo"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// mcpToolsListResult ist das Ergebnis von tools/list: genau ein Tool
|
// mcpToolsListResult is the result of tools/list: exactly one tool (speak);
|
||||||
// (speak); ohne nextCursor (die Liste passt immer in eine Seite).
|
// no nextCursor (the list always fits on one page).
|
||||||
type mcpToolsListResult struct {
|
type mcpToolsListResult struct {
|
||||||
Tools []mcpTool `json:"tools"`
|
Tools []mcpTool `json:"tools"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// mcpTool ist ein Tool-Eintrag in tools/list.
|
// mcpTool is a tool entry in tools/list.
|
||||||
type mcpTool struct {
|
type mcpTool struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Description string `json:"description"`
|
Description string `json:"description"`
|
||||||
InputSchema mcpSchema `json:"inputSchema"`
|
InputSchema mcpSchema `json:"inputSchema"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// mcpSchema ist das JSON-Schema-Objekt eines Tool-Inputs.
|
// mcpSchema is the JSON Schema object of a tool input.
|
||||||
type mcpSchema struct {
|
type mcpSchema struct {
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
Properties map[string]mcpProperty `json:"properties"`
|
Properties map[string]mcpProperty `json:"properties"`
|
||||||
Required []string `json:"required"`
|
Required []string `json:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// mcpProperty ist eine einzelne Schema-Property.
|
// mcpProperty is a single schema property.
|
||||||
type mcpProperty struct {
|
type mcpProperty struct {
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
Description string `json:"description,omitempty"`
|
Description string `json:"description,omitempty"`
|
||||||
Enum []string `json:"enum,omitempty"`
|
Enum []string `json:"enum,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// mcpToolCallParams sind die Parameter von tools/call.
|
// mcpToolCallParams are the parameters of tools/call.
|
||||||
type mcpToolCallParams struct {
|
type mcpToolCallParams struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Arguments json.RawMessage `json:"arguments"`
|
Arguments json.RawMessage `json:"arguments"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// mcpContent ist ein Content-Block eines Tool-Ergebnisses (hier: Text).
|
// mcpContent is a content block of a tool result (here: text).
|
||||||
type mcpContent struct {
|
type mcpContent struct {
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
Text string `json:"text"`
|
Text string `json:"text"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// mcpToolResult ist das Ergebnis von tools/call. isError:false (weggelassen)
|
// mcpToolResult is the result of tools/call. isError:false (omitted) also
|
||||||
// auch bei muted/discarded — das ist ein ERGEBNIS der Aufnahme, kein
|
// for muted/discarded: that is a RESULT of admission, not a protocol error
|
||||||
// Protokollfehler (bewusste Entscheidung, siehe speakToolResult).
|
// (deliberate decision, see speakToolResult).
|
||||||
type mcpToolResult struct {
|
type mcpToolResult struct {
|
||||||
Content []mcpContent `json:"content"`
|
Content []mcpContent `json:"content"`
|
||||||
IsError bool `json:"isError,omitempty"`
|
IsError bool `json:"isError,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// serveMCP behandelt POST /mcp: eine JSON-RPC-Nachricht pro Request.
|
// serveMCP handles POST /mcp: one JSON-RPC message per request.
|
||||||
func (h *handler) serveMCP(w http.ResponseWriter, r *http.Request) {
|
func (h *handler) serveMCP(w http.ResponseWriter, r *http.Request) {
|
||||||
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBodyBytes))
|
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBodyBytes))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeRPCError(w, nil, rpcParseError, "Body lesen: "+err.Error())
|
writeRPCError(w, nil, rpcParseError, "reading body: "+err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if strings.HasPrefix(strings.TrimLeft(string(body), " \t\r\n"), "[") {
|
if strings.HasPrefix(strings.TrimLeft(string(body), " \t\r\n"), "[") {
|
||||||
writeRPCError(w, nil, rpcInvalidRequest,
|
writeRPCError(w, nil, rpcInvalidRequest,
|
||||||
"Batch-Requests werden nicht unterstützt (MCP 2025-06-18 hat Batches entfernt) — eine Nachricht pro POST")
|
"batch requests are not supported (MCP 2025-06-18 removed batches); one message per POST")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var req jsonRPCRequest
|
var req jsonRPCRequest
|
||||||
if err := json.Unmarshal(body, &req); err != nil {
|
if err := json.Unmarshal(body, &req); err != nil {
|
||||||
writeRPCError(w, nil, rpcParseError, "ungültiges JSON: "+err.Error())
|
writeRPCError(w, nil, rpcParseError, "invalid JSON: "+err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if req.JSONRPC != "2.0" {
|
if req.JSONRPC != "2.0" {
|
||||||
writeRPCError(w, nil, rpcInvalidRequest,
|
writeRPCError(w, nil, rpcInvalidRequest,
|
||||||
`jsonrpc muss "2.0" sein (erhalten: `+strconv.Quote(req.JSONRPC)+`)`)
|
`jsonrpc must be "2.0" (got `+strconv.Quote(req.JSONRPC)+`)`)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if isNotification(req.ID) {
|
if isNotification(req.ID) {
|
||||||
// Notifications (notifications/initialized, …) bekommen nie eine
|
// Notifications (notifications/initialized, ...) never get a
|
||||||
// JSON-RPC-Antwort — nur den 202-Vermerk des Transports. Unbekannte
|
// JSON-RPC response, only the transport's 202. Unknown
|
||||||
// Notifications werden still ignoriert (JSON-RPC 2.0).
|
// notifications are silently ignored (JSON-RPC 2.0).
|
||||||
w.WriteHeader(http.StatusAccepted)
|
w.WriteHeader(http.StatusAccepted)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -182,8 +180,8 @@ func (h *handler) serveMCP(w http.ResponseWriter, r *http.Request) {
|
|||||||
case "initialize":
|
case "initialize":
|
||||||
h.mcpInitialize(w, req)
|
h.mcpInitialize(w, req)
|
||||||
case "notifications/initialized":
|
case "notifications/initialized":
|
||||||
// Mit ID gesendet: kein regulärer Client — die korrekte Antwort
|
// Sent with an ID: not a regular client; the correct answer is an
|
||||||
// ist ein leeres Ergebnis, kein Fehler.
|
// empty result, not an error.
|
||||||
writeRPCResult(w, req.ID, struct{}{})
|
writeRPCResult(w, req.ID, struct{}{})
|
||||||
case "ping":
|
case "ping":
|
||||||
writeRPCResult(w, req.ID, struct{}{})
|
writeRPCResult(w, req.ID, struct{}{})
|
||||||
@@ -193,26 +191,26 @@ func (h *handler) serveMCP(w http.ResponseWriter, r *http.Request) {
|
|||||||
h.mcpToolsCall(w, req)
|
h.mcpToolsCall(w, req)
|
||||||
default:
|
default:
|
||||||
writeRPCError(w, req.ID, rpcMethodNotFound,
|
writeRPCError(w, req.ID, rpcMethodNotFound,
|
||||||
"Methode "+strconv.Quote(req.Method)+" ist nicht implementiert (verfügbar: initialize, notifications/initialized, ping, tools/list, tools/call)")
|
"method "+strconv.Quote(req.Method)+" is not implemented (available: initialize, notifications/initialized, ping, tools/list, tools/call)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// mcpGet behandelt GET /mcp: 405 mit Allow — talkd bietet keine
|
// mcpGet handles GET /mcp: 405 with Allow. talkd offers no server-initiated
|
||||||
// server-initiierten Streams an (die dafür vorgesehene Streamable-HTTP-
|
// streams (the Streamable HTTP response for that case); there are no tool
|
||||||
// Antwort), Tools-Änderungen gibt es nicht.
|
// changes.
|
||||||
func (h *handler) mcpGet(w http.ResponseWriter, r *http.Request) {
|
func (h *handler) mcpGet(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Allow", "POST, OPTIONS")
|
w.Header().Set("Allow", "POST, OPTIONS")
|
||||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||||
}
|
}
|
||||||
|
|
||||||
// mcpInitialize behandelt initialize: Die angefragte Protokollversion wird
|
// mcpInitialize handles initialize: the requested protocol version is
|
||||||
// geechot (akzeptiert) — leer → die eigene (2025-06-18). Capabilities:
|
// echoed (accepted); empty means our own (2025-06-18). Capabilities: tools;
|
||||||
// Tools; serverInfo: talkd + Daemon-Version.
|
// serverInfo: talkd + daemon version.
|
||||||
func (h *handler) mcpInitialize(w http.ResponseWriter, req jsonRPCRequest) {
|
func (h *handler) mcpInitialize(w http.ResponseWriter, req jsonRPCRequest) {
|
||||||
var params mcpInitializeParams
|
var params mcpInitializeParams
|
||||||
if len(req.Params) > 0 {
|
if len(req.Params) > 0 {
|
||||||
if err := json.Unmarshal(req.Params, ¶ms); err != nil {
|
if err := json.Unmarshal(req.Params, ¶ms); err != nil {
|
||||||
writeRPCError(w, req.ID, rpcInvalidParams, "initialize-params: "+err.Error())
|
writeRPCError(w, req.ID, rpcInvalidParams, "initialize params: "+err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -227,18 +225,18 @@ func (h *handler) mcpInitialize(w http.ResponseWriter, req jsonRPCRequest) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// mcpToolsCall behandelt tools/call: genau ein Tool (speak), dessen
|
// mcpToolsCall handles tools/call: exactly one tool (speak) whose arguments
|
||||||
// Argumente denselben Aufnahme-Pfad wie POST /speak fahren — inklusive
|
// take the same admission path as POST /speak, including mute and the laws
|
||||||
// Mute und Gesetz (Rate-Limit/Ruhezeit).
|
// (rate limit/quiet hours).
|
||||||
func (h *handler) mcpToolsCall(w http.ResponseWriter, req jsonRPCRequest) {
|
func (h *handler) mcpToolsCall(w http.ResponseWriter, req jsonRPCRequest) {
|
||||||
var params mcpToolCallParams
|
var params mcpToolCallParams
|
||||||
if err := json.Unmarshal(req.Params, ¶ms); err != nil {
|
if err := json.Unmarshal(req.Params, ¶ms); err != nil {
|
||||||
writeRPCError(w, req.ID, rpcInvalidParams, "tools/call-params: "+err.Error())
|
writeRPCError(w, req.ID, rpcInvalidParams, "tools/call params: "+err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if params.Name != "speak" {
|
if params.Name != "speak" {
|
||||||
writeRPCError(w, req.ID, rpcInvalidParams,
|
writeRPCError(w, req.ID, rpcInvalidParams,
|
||||||
"unbekanntes Tool "+strconv.Quote(params.Name)+" (verfügbar: speak)")
|
"unknown tool "+strconv.Quote(params.Name)+" (available: speak)")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -254,8 +252,8 @@ func (h *handler) mcpToolsCall(w http.ResponseWriter, req jsonRPCRequest) {
|
|||||||
|
|
||||||
adm := h.admitSpeak(speakReq)
|
adm := h.admitSpeak(speakReq)
|
||||||
if adm.status != http.StatusAccepted {
|
if adm.status != http.StatusAccepted {
|
||||||
// Validierungs-/Interner-Fehler (HTTP-Äquivalent 400/503): als
|
// Validation/internal error (HTTP equivalent 400/503): report as a
|
||||||
// JSON-RPC-Fehler melden — das war kein Aufnahme-Ergebnis.
|
// JSON-RPC error; this was not an admission result.
|
||||||
code := rpcInvalidParams
|
code := rpcInvalidParams
|
||||||
if adm.status != http.StatusBadRequest {
|
if adm.status != http.StatusBadRequest {
|
||||||
code = rpcInternalError
|
code = rpcInternalError
|
||||||
@@ -266,38 +264,37 @@ func (h *handler) mcpToolsCall(w http.ResponseWriter, req jsonRPCRequest) {
|
|||||||
writeRPCResult(w, req.ID, speakToolResult(adm.resp))
|
writeRPCResult(w, req.ID, speakToolResult(adm.resp))
|
||||||
}
|
}
|
||||||
|
|
||||||
// speakTool ist die Tool-Beschreibung von speak: Input-Schema aus dem
|
// speakTool is the tool description of speak: input schema with text
|
||||||
// Task-06-Brief (text Pflicht; priority/provider/lang/now optional).
|
// required; priority/provider/lang/now optional.
|
||||||
func speakTool() mcpTool {
|
func speakTool() mcpTool {
|
||||||
return mcpTool{
|
return mcpTool{
|
||||||
Name: "speak",
|
Name: "speak",
|
||||||
Description: "Spricht eine kurze Ansage (Status, nächster Schritt, " +
|
Description: "Speaks a short announcement (status, next step, what the user is needed for; " +
|
||||||
"Freigabe-Bedarf — nie Langantworten). Läuft über den Daemon: " +
|
"never long answers). Goes through the daemon: queue, rate limit, mute and quiet hours apply.",
|
||||||
"Queue, Rate-Limit, Mute und Ruhezeiten gelten.",
|
|
||||||
InputSchema: mcpSchema{
|
InputSchema: mcpSchema{
|
||||||
Type: "object",
|
Type: "object",
|
||||||
Properties: map[string]mcpProperty{
|
Properties: map[string]mcpProperty{
|
||||||
"text": {
|
"text": {
|
||||||
Type: "string",
|
Type: "string",
|
||||||
Description: "Der Ansage-Text (1–2 Sätze Etikette)",
|
Description: "The announcement text (1 to 2 sentences by etiquette)",
|
||||||
},
|
},
|
||||||
"priority": {
|
"priority": {
|
||||||
Type: "string",
|
Type: "string",
|
||||||
Enum: []string{"low", "normal", "high"},
|
Enum: []string{"low", "normal", "high"},
|
||||||
Description: "Abarbeitungs-Priorität (Default normal)",
|
Description: "Processing priority (default normal)",
|
||||||
},
|
},
|
||||||
"provider": {
|
"provider": {
|
||||||
Type: "string",
|
Type: "string",
|
||||||
Description: "Provider pin (elevenlabs, openai, edge, osbuiltin); leer = Default-Kette",
|
Description: "Provider pin (elevenlabs, openai, edge, osbuiltin); empty = default chain",
|
||||||
},
|
},
|
||||||
"lang": {
|
"lang": {
|
||||||
Type: "string",
|
Type: "string",
|
||||||
Enum: []string{"de", "en"},
|
Enum: []string{"de", "en"},
|
||||||
Description: "Sprache pin; leer = automatische Erkennung",
|
Description: "Language pin; empty = automatic detection",
|
||||||
},
|
},
|
||||||
"now": {
|
"now": {
|
||||||
Type: "boolean",
|
Type: "boolean",
|
||||||
Description: "Springt vor die Warteschlange und bricht bewusst aus Rate-Limit und Ruhezeit aus",
|
Description: "Jumps ahead of the queue and deliberately bypasses rate limit and quiet hours",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
Required: []string{"text"},
|
Required: []string{"text"},
|
||||||
@@ -305,27 +302,26 @@ func speakTool() mcpTool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// speakToolResult übersetzt eine /speak-Aufnahme-Antwort in das MCP-Tool-
|
// speakToolResult translates a /speak admission response into the MCP tool
|
||||||
// Ergebnis. Mute- und Gesetz-Verwürfe sind bewusst KEIN isError: Sie sind
|
// result. Mute and law discards are deliberately NOT isError: they are the
|
||||||
// das korrekte dokumentierte Ergebnis der Aufnahme (kein Protokollfehler)
|
// correct, documented result of admission (no protocol error); the agent
|
||||||
// — der Agent soll den Grund lesen, nicht crashen. Erfolgreiche Aufnahme:
|
// should read the reason, not crash. Successful admission: "queued: <id>".
|
||||||
// "queued: <id>".
|
|
||||||
func speakToolResult(resp SpeakResponse) mcpToolResult {
|
func speakToolResult(resp SpeakResponse) mcpToolResult {
|
||||||
switch {
|
switch {
|
||||||
case resp.Muted:
|
case resp.Muted:
|
||||||
return mcpToolResult{Content: []mcpContent{{
|
return mcpToolResult{Content: []mcpContent{{
|
||||||
Type: "text",
|
Type: "text",
|
||||||
Text: "muted: Ansage verworfen (Mute ist aktiv)",
|
Text: "muted: announcement discarded (mute is on)",
|
||||||
}}}
|
}}}
|
||||||
case resp.Discarded == queue.DiscardRateLimit:
|
case resp.Discarded == queue.DiscardRateLimit:
|
||||||
return mcpToolResult{Content: []mcpContent{{
|
return mcpToolResult{Content: []mcpContent{{
|
||||||
Type: "text",
|
Type: "text",
|
||||||
Text: "discarded: rate_limit — Ansage verworfen (Priorität low über dem Fenster-Budget)",
|
Text: "discarded: rate_limit; announcement discarded (priority low over the window budget)",
|
||||||
}}}
|
}}}
|
||||||
case resp.Discarded == queue.DiscardQuietHours:
|
case resp.Discarded == queue.DiscardQuietHours:
|
||||||
text := "discarded: quiet_hours — Ruhezeit aktiv, Ansage verworfen"
|
text := "discarded: quiet_hours; quiet hours active, announcement discarded"
|
||||||
if resp.Toast {
|
if resp.Toast {
|
||||||
text += " (durch Toast ersetzt, kein Audio)"
|
text += " (replaced by a toast, no audio)"
|
||||||
}
|
}
|
||||||
return mcpToolResult{Content: []mcpContent{{Type: "text", Text: text}}}
|
return mcpToolResult{Content: []mcpContent{{Type: "text", Text: text}}}
|
||||||
case resp.Discarded != "":
|
case resp.Discarded != "":
|
||||||
@@ -336,26 +332,26 @@ func speakToolResult(resp SpeakResponse) mcpToolResult {
|
|||||||
default:
|
default:
|
||||||
text := "queued: " + resp.ID
|
text := "queued: " + resp.ID
|
||||||
if resp.Truncated {
|
if resp.Truncated {
|
||||||
text += " (Text auf max_text gekürzt — Ansagen sind 1–2 Sätze, keine Langantworten)"
|
text += " (text truncated to max_text; announcements are 1 to 2 sentences, not long answers)"
|
||||||
}
|
}
|
||||||
return mcpToolResult{Content: []mcpContent{{Type: "text", Text: text}}}
|
return mcpToolResult{Content: []mcpContent{{Type: "text", Text: text}}}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// isNotification meldet, ob die ID eine Notification anzeigt (Feld fehlt
|
// isNotification reports whether the ID marks a notification (field missing
|
||||||
// oder explizit null — beides nach JSON-RPC 2.0 ohne Antwort).
|
// or explicitly null; both get no response per JSON-RPC 2.0).
|
||||||
func isNotification(id json.RawMessage) bool {
|
func isNotification(id json.RawMessage) bool {
|
||||||
return len(id) == 0 || strings.TrimSpace(string(id)) == "null"
|
return len(id) == 0 || strings.TrimSpace(string(id)) == "null"
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeRPCResult schreibt eine erfolgreiche JSON-RPC-Antwort (200,
|
// writeRPCResult writes a successful JSON-RPC response (200,
|
||||||
// application/json).
|
// application/json).
|
||||||
func writeRPCResult(w http.ResponseWriter, id json.RawMessage, result any) {
|
func writeRPCResult(w http.ResponseWriter, id json.RawMessage, result any) {
|
||||||
writeRPC(w, jsonRPCResponse{JSONRPC: "2.0", ID: id, Result: result})
|
writeRPC(w, jsonRPCResponse{JSONRPC: "2.0", ID: id, Result: result})
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeRPCError schreibt eine JSON-RPC-Fehler-Antwort; id null, wenn die
|
// writeRPCError writes a JSON-RPC error response; id null when the request
|
||||||
// Anfrage-ID unbekannt ist (Parse-Fehler).
|
// ID is unknown (parse error).
|
||||||
func writeRPCError(w http.ResponseWriter, id json.RawMessage, code int, msg string) {
|
func writeRPCError(w http.ResponseWriter, id json.RawMessage, code int, msg string) {
|
||||||
writeRPC(w, jsonRPCResponse{
|
writeRPC(w, jsonRPCResponse{
|
||||||
JSONRPC: "2.0",
|
JSONRPC: "2.0",
|
||||||
@@ -364,7 +360,7 @@ func writeRPCError(w http.ResponseWriter, id json.RawMessage, code int, msg stri
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeRPC schreibt die JSON-RPC-Antwort in den Response-Writer.
|
// writeRPC writes the JSON-RPC response to the response writer.
|
||||||
func writeRPC(w http.ResponseWriter, resp jsonRPCResponse) {
|
func writeRPC(w http.ResponseWriter, resp jsonRPCResponse) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
|
|||||||
+83
-64
@@ -10,45 +10,45 @@ import (
|
|||||||
"code.m3ta.dev/m3tam3re/talk/internal/queue"
|
"code.m3ta.dev/m3tam3re/talk/internal/queue"
|
||||||
)
|
)
|
||||||
|
|
||||||
// maxBodyBytes begrenzt Anfrage-Körper (Ansagen sind kurz; Schutz gegen
|
// maxBodyBytes limits request bodies (announcements are short; protection
|
||||||
// versehentliche Riesen-Payloads).
|
// against accidental huge payloads).
|
||||||
const maxBodyBytes = 64 << 10
|
const maxBodyBytes = 64 << 10
|
||||||
|
|
||||||
// HandlerConfig bündelt die Abhängigkeiten der HTTP-Oberfläche. Der Handler
|
// HandlerConfig bundles the dependencies of the HTTP surface. The handler
|
||||||
// kennt weder Config-Dateien noch Env — alles wird vom Daemon (cmd/talkd)
|
// knows neither config files nor env; the daemon injects everything, and
|
||||||
// injiziert; Prozessgrenzen-Tests fahren genau diese Oberfläche als Black Box.
|
// process-boundary tests drive exactly this surface as a black box.
|
||||||
type HandlerConfig struct {
|
type HandlerConfig struct {
|
||||||
// Queue ist die Daemon-Queue (Enqueue/Cancel/Current/Pending).
|
// Queue is the daemon queue (Enqueue/Cancel/Current/Pending).
|
||||||
Queue *queue.Queue
|
Queue *queue.Queue
|
||||||
|
|
||||||
// Mute ist der persistente Mute-State (Datei mute im Config-Dir).
|
// Mute is the persistent mute state (file mute in the config dir).
|
||||||
Mute queue.MuteStore
|
Mute queue.MuteStore
|
||||||
|
|
||||||
// Version ist die Daemon-Version für GET /status und serverInfo.
|
// Version is the daemon version for GET /status and serverInfo.
|
||||||
Version string
|
Version string
|
||||||
|
|
||||||
// KnownProviders sind die gültigen Provider-Namen (Validierung des
|
// KnownProviders are the valid provider names (validation of the
|
||||||
// provider-Felds in POST /speak; talkd liefert provider.Names()).
|
// provider field in POST /speak; the daemon passes provider.Names()).
|
||||||
KnownProviders []string
|
KnownProviders []string
|
||||||
|
|
||||||
// Provider löst den aktiven Provider für GET /status auf (Daemon-seitig:
|
// Provider resolves the active provider for GET /status (daemon side:
|
||||||
// Pin des laufenden Items bzw. erste verfügbare Ketten-Stufe). Optional.
|
// pin of the running item or first available chain tier). Optional.
|
||||||
Provider func() string
|
Provider func() string
|
||||||
|
|
||||||
// AllowedOrigins ist die CORS-Erlaubnisliste für POST /speak (leer =
|
// AllowedOrigins is the CORS allow list for POST /speak (empty = no CORS
|
||||||
// keine CORS-Header, der Browser blockt; siehe cors.go).
|
// headers, the browser blocks; see cors.go).
|
||||||
AllowedOrigins []string
|
AllowedOrigins []string
|
||||||
|
|
||||||
// Shutdown fährt den Daemon herunter (POST /shutdown, `talk daemon
|
// Shutdown shuts the daemon down (POST /shutdown, `talk daemon stop`).
|
||||||
// stop`). Muss nicht blockieren und mehrfach aufrufbar sein. Optional:
|
// Must not block and must be callable more than once. Optional: nil
|
||||||
// nil → der Endpunkt antwortet 501.
|
// means the endpoint answers 501.
|
||||||
Shutdown func()
|
Shutdown func()
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewHandler liefert die HTTP-Routen des Daemons. Methoden-Bindung per
|
// NewHandler returns the daemon's HTTP routes. Method binding via ServeMux
|
||||||
// ServeMux-Muster: falsche Methode → 405, unbekannter Pfad → 404. Vor dem
|
// patterns: wrong method 405, unknown path 404. The originGuard (cors.go)
|
||||||
// Router steht der originGuard (cors.go): Browser-Anfragen (Origin-Header)
|
// sits in front of the router: browser requests (Origin header) only reach
|
||||||
// erreichen nur POST /speak von gelisteten Origins; alles andere ist 403.
|
// POST /speak from listed origins; everything else is 403.
|
||||||
func NewHandler(cfg HandlerConfig) http.Handler {
|
func NewHandler(cfg HandlerConfig) http.Handler {
|
||||||
h := &handler{
|
h := &handler{
|
||||||
queue: cfg.Queue,
|
queue: cfg.Queue,
|
||||||
@@ -64,18 +64,19 @@ func NewHandler(cfg HandlerConfig) http.Handler {
|
|||||||
}
|
}
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
mux.HandleFunc("POST /speak", h.speak)
|
mux.HandleFunc("POST /speak", h.speak)
|
||||||
mux.HandleFunc("OPTIONS /speak", h.speakPreflight) // CORS-Preflight (Task 06)
|
mux.HandleFunc("OPTIONS /speak", h.speakPreflight) // CORS preflight
|
||||||
mux.HandleFunc("GET /status", h.status)
|
mux.HandleFunc("GET /status", h.status)
|
||||||
mux.HandleFunc("POST /cancel", h.cancel)
|
mux.HandleFunc("POST /cancel", h.cancel)
|
||||||
|
mux.HandleFunc("POST /cancel-item", h.cancelItem)
|
||||||
mux.HandleFunc("POST /mute", h.muteEndpoint(true))
|
mux.HandleFunc("POST /mute", h.muteEndpoint(true))
|
||||||
mux.HandleFunc("POST /unmute", h.muteEndpoint(false))
|
mux.HandleFunc("POST /unmute", h.muteEndpoint(false))
|
||||||
mux.HandleFunc("POST /shutdown", h.shutdownEndpoint)
|
mux.HandleFunc("POST /shutdown", h.shutdownEndpoint)
|
||||||
mux.HandleFunc("POST /mcp", h.serveMCP) // MCP Streamable HTTP (Task 06)
|
mux.HandleFunc("POST /mcp", h.serveMCP) // MCP Streamable HTTP
|
||||||
mux.HandleFunc("GET /mcp", h.mcpGet) // 405: keine server-initiierten Streams
|
mux.HandleFunc("GET /mcp", h.mcpGet) // 405: no server-initiated streams
|
||||||
return h.originGuard(mux)
|
return h.originGuard(mux)
|
||||||
}
|
}
|
||||||
|
|
||||||
// handler ist der interne Zustand der HTTP-Oberfläche.
|
// handler is the internal state of the HTTP surface.
|
||||||
type handler struct {
|
type handler struct {
|
||||||
queue *queue.Queue
|
queue *queue.Queue
|
||||||
mute queue.MuteStore
|
mute queue.MuteStore
|
||||||
@@ -86,18 +87,18 @@ type handler struct {
|
|||||||
shutdown func()
|
shutdown func()
|
||||||
}
|
}
|
||||||
|
|
||||||
// speak behandelt POST /speak: validieren, bei Mute verwerfen (202,
|
// speak handles POST /speak: validate, discard when muted (202, documented
|
||||||
// dokumentiertes Verhalten — bewusst kein Fehler, damit Aufrufer keine
|
// behaviour; deliberately not an error so callers need no special
|
||||||
// Sonderbehandlung brauchen), sonst enqueue → 202 {id}. Das Gesetz
|
// handling), otherwise enqueue and answer 202 {id}. The laws (rate-limit
|
||||||
// (Rate-Limit-Budget, Ruhezeit) kann beim Eintritt ebenfalls verwerfen —
|
// budget, quiet hours) may also discard on admission; the response then
|
||||||
// die Antwort nennt dann den Grund ({"discarded":"…"}). CORS-Header nur
|
// names the reason ({"discarded":"..."}). CORS headers only here and only
|
||||||
// hier und nur bei gelisteter Origin (siehe cors.go).
|
// for a listed origin (see cors.go).
|
||||||
func (h *handler) speak(w http.ResponseWriter, r *http.Request) {
|
func (h *handler) speak(w http.ResponseWriter, r *http.Request) {
|
||||||
h.setSpeakCors(w, r)
|
h.setSpeakCors(w, r)
|
||||||
|
|
||||||
var req SpeakRequest
|
var req SpeakRequest
|
||||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodyBytes)).Decode(&req); err != nil {
|
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodyBytes)).Decode(&req); err != nil {
|
||||||
writeError(w, http.StatusBadRequest, "ungültiger JSON-Body: "+err.Error())
|
writeError(w, http.StatusBadRequest, "invalid JSON body: "+err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
adm := h.admitSpeak(req)
|
adm := h.admitSpeak(req)
|
||||||
@@ -108,38 +109,38 @@ func (h *handler) speak(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSON(w, adm.status, adm.resp)
|
writeJSON(w, adm.status, adm.resp)
|
||||||
}
|
}
|
||||||
|
|
||||||
// speakAdmission ist das Ergebnis des gemeinsamen Aufnahme-Pfads von
|
// speakAdmission is the result of the shared admission path of POST /speak
|
||||||
// POST /speak und dem MCP-Tool speak: HTTP-Status-Äquivalent plus Body —
|
// and the MCP tool speak: an HTTP status equivalent plus body. 202 with
|
||||||
// 202 mit {id}/{muted}/{discarded} als Aufnahme-Ergebnis, 400/503 mit
|
// {id}/{muted}/{discarded} as the admission result, 400/503 with errMsg as
|
||||||
// errMsg als Fehler (MCP übersetzt beides, siehe mcp.go).
|
// an error (MCP translates both, see mcp.go).
|
||||||
type speakAdmission struct {
|
type speakAdmission struct {
|
||||||
status int
|
status int
|
||||||
resp SpeakResponse
|
resp SpeakResponse
|
||||||
errMsg string
|
errMsg string
|
||||||
}
|
}
|
||||||
|
|
||||||
// admitSpeak ist der eine Aufnahme-Pfad hinter POST /speak und dem
|
// admitSpeak is the one admission path behind POST /speak and the MCP tool
|
||||||
// MCP-Tool speak (Task 06): Validierung, Mute-Check, Enqueue inklusive
|
// speak: validation, mute check, enqueue including the laws (rate-limit
|
||||||
// Gesetz (Rate-Limit-Budget, Ruhezeit) — identische Semantik für beide
|
// budget, quiet hours). Identical semantics for both doors, no contract
|
||||||
// Türen, kein Contract-Drift.
|
// drift.
|
||||||
func (h *handler) admitSpeak(req SpeakRequest) speakAdmission {
|
func (h *handler) admitSpeak(req SpeakRequest) speakAdmission {
|
||||||
if strings.TrimSpace(req.Text) == "" {
|
if strings.TrimSpace(req.Text) == "" {
|
||||||
return speakAdmission{status: http.StatusBadRequest, errMsg: "text fehlt oder ist leer"}
|
return speakAdmission{status: http.StatusBadRequest, errMsg: "text is missing or empty"}
|
||||||
}
|
}
|
||||||
if req.Priority == "" {
|
if req.Priority == "" {
|
||||||
req.Priority = string(queue.PriorityNormal)
|
req.Priority = string(queue.PriorityNormal)
|
||||||
}
|
}
|
||||||
if !queue.Priority(req.Priority).Valid() {
|
if !queue.Priority(req.Priority).Valid() {
|
||||||
return speakAdmission{status: http.StatusBadRequest,
|
return speakAdmission{status: http.StatusBadRequest,
|
||||||
errMsg: fmt.Sprintf("priority: ungültiger Wert %q (erlaubt: low, normal, high)", req.Priority)}
|
errMsg: fmt.Sprintf("priority: invalid value %q (allowed: low, normal, high)", req.Priority)}
|
||||||
}
|
}
|
||||||
if req.Provider != "" && !h.known[req.Provider] {
|
if req.Provider != "" && !h.known[req.Provider] {
|
||||||
return speakAdmission{status: http.StatusBadRequest,
|
return speakAdmission{status: http.StatusBadRequest,
|
||||||
errMsg: fmt.Sprintf("provider: unbekannter Wert %q", req.Provider)}
|
errMsg: fmt.Sprintf("provider: unknown value %q", req.Provider)}
|
||||||
}
|
}
|
||||||
if req.Lang != "" && req.Lang != "de" && req.Lang != "en" {
|
if req.Lang != "" && req.Lang != "de" && req.Lang != "en" {
|
||||||
return speakAdmission{status: http.StatusBadRequest,
|
return speakAdmission{status: http.StatusBadRequest,
|
||||||
errMsg: fmt.Sprintf("lang: ungültiger Wert %q (erlaubt: de, en)", req.Lang)}
|
errMsg: fmt.Sprintf("lang: invalid value %q (allowed: de, en)", req.Lang)}
|
||||||
}
|
}
|
||||||
|
|
||||||
if h.mute.Muted() {
|
if h.mute.Muted() {
|
||||||
@@ -158,18 +159,18 @@ func (h *handler) admitSpeak(req SpeakRequest) speakAdmission {
|
|||||||
return speakAdmission{status: http.StatusServiceUnavailable, errMsg: "enqueue: " + err.Error()}
|
return speakAdmission{status: http.StatusServiceUnavailable, errMsg: "enqueue: " + err.Error()}
|
||||||
}
|
}
|
||||||
if adm.Discarded != "" {
|
if adm.Discarded != "" {
|
||||||
// Gesetz-Verwurf (Rate-Limit-Budget / Ruhezeit): dokumentiertes
|
// Law discard (rate-limit budget / quiet hours): documented
|
||||||
// Verhalten wie bei Mute — 202 mit Grund statt Fehler, damit
|
// behaviour like mute, 202 with a reason instead of an error, so
|
||||||
// Aufrufer keine Sonderbehandlung brauchen.
|
// callers need no special handling.
|
||||||
return speakAdmission{status: http.StatusAccepted,
|
return speakAdmission{status: http.StatusAccepted,
|
||||||
resp: SpeakResponse{Discarded: adm.Discarded, Toast: adm.Toast}}
|
resp: SpeakResponse{Discarded: adm.Discarded, Toast: adm.Toast}}
|
||||||
}
|
}
|
||||||
return speakAdmission{status: http.StatusAccepted, resp: SpeakResponse{ID: adm.ID, Truncated: adm.Truncated}}
|
return speakAdmission{status: http.StatusAccepted, resp: SpeakResponse{ID: adm.ID, Truncated: adm.Truncated}}
|
||||||
}
|
}
|
||||||
|
|
||||||
// status behandelt GET /status: Queue-Länge (+ wartende IDs), aktuelles
|
// status handles GET /status: queue length (+ waiting IDs), current item,
|
||||||
// Item, Mute-State, aktiver Provider, Version — und seit Task 05 den
|
// mute state, active provider, version, and the law state (rate limit with
|
||||||
// Gesetz-State (Rate-Limit mit nächstem Slot, Ruhezeit-Fenster).
|
// next slot, quiet-hours window).
|
||||||
func (h *handler) status(w http.ResponseWriter, r *http.Request) {
|
func (h *handler) status(w http.ResponseWriter, r *http.Request) {
|
||||||
pending := h.queue.Pending()
|
pending := h.queue.Pending()
|
||||||
ids := make([]string, len(pending))
|
ids := make([]string, len(pending))
|
||||||
@@ -201,17 +202,17 @@ func (h *handler) status(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSON(w, http.StatusOK, st)
|
writeJSON(w, http.StatusOK, st)
|
||||||
}
|
}
|
||||||
|
|
||||||
// corsList kopiert die Erlaubnisliste als JSON-[] statt null: Der Status
|
// corsList copies the allow list as a JSON [] instead of null: the status
|
||||||
// soll "cors": [] zeigen, wenn die Tür zu ist.
|
// should show "cors": [] when the door is closed.
|
||||||
func corsList(origins []string) []string {
|
func corsList(origins []string) []string {
|
||||||
out := make([]string, len(origins))
|
out := make([]string, len(origins))
|
||||||
copy(out, origins)
|
copy(out, origins)
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
// lawState überführt die Gesetz-Sicht der Queue in die JSON-Form von
|
// lawState converts the queue's law view into the JSON form of /status:
|
||||||
// /status: Zeitstempel nur, wenn sie in der Zukunft liegen (null = Slot
|
// timestamps only when they lie in the future (null = slot free / quiet
|
||||||
// frei / Ruhezeit inaktiv).
|
// hours inactive).
|
||||||
func lawState(l queue.LawState) (*RateLimitState, *QuietHoursState) {
|
func lawState(l queue.LawState) (*RateLimitState, *QuietHoursState) {
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
rl := &RateLimitState{
|
rl := &RateLimitState{
|
||||||
@@ -234,13 +235,31 @@ func lawState(l queue.LawState) (*RateLimitState, *QuietHoursState) {
|
|||||||
return rl, qh
|
return rl, qh
|
||||||
}
|
}
|
||||||
|
|
||||||
// cancel behandelt POST /cancel: laufende Ansage abbrechen + Queue leeren.
|
// cancel handles POST /cancel: cancel the running announcement and clear
|
||||||
|
// the queue.
|
||||||
func (h *handler) cancel(w http.ResponseWriter, r *http.Request) {
|
func (h *handler) cancel(w http.ResponseWriter, r *http.Request) {
|
||||||
writeJSON(w, http.StatusOK, CancelResponse{Cancelled: h.queue.Cancel()})
|
writeJSON(w, http.StatusOK, CancelResponse{Cancelled: h.queue.Cancel()})
|
||||||
}
|
}
|
||||||
|
|
||||||
// muteEndpoint behandelt POST /mute bzw. POST /unmute: persistenter
|
// cancelItem handles POST /cancel-item: cancels the announcement with the
|
||||||
// Mute-State (Datei im Config-Dir, überlebt Daemon-Restarts).
|
// given id if it is the one playing (the Cancel button of its notification;
|
||||||
|
// on Windows it arrives through the talk: protocol handler). Waiting items
|
||||||
|
// stay. A stale id is not an error: {"cancelled": false}.
|
||||||
|
func (h *handler) cancelItem(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req CancelItemRequest
|
||||||
|
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodyBytes)).Decode(&req); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid JSON body: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.ID) == "" {
|
||||||
|
writeError(w, http.StatusBadRequest, "id is missing or empty")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, CancelItemResponse{Cancelled: h.queue.CancelItem(req.ID)})
|
||||||
|
}
|
||||||
|
|
||||||
|
// muteEndpoint handles POST /mute and POST /unmute: persistent mute state
|
||||||
|
// (file in the config dir, survives daemon restarts).
|
||||||
func (h *handler) muteEndpoint(muted bool) http.HandlerFunc {
|
func (h *handler) muteEndpoint(muted bool) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
if err := h.mute.Set(muted); err != nil {
|
if err := h.mute.Set(muted); err != nil {
|
||||||
@@ -251,26 +270,26 @@ func (h *handler) muteEndpoint(muted bool) http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// shutdownEndpoint behandelt POST /shutdown (`talk daemon stop`): Antwort
|
// shutdownEndpoint handles POST /shutdown (`talk daemon stop`): response
|
||||||
// zuerst, dann der Shutdown-Trigger — der Aufrufer bekommt sein 200, bevor
|
// first, then the shutdown trigger, so the caller gets its 200 before the
|
||||||
// der Server die Verbindung schließt.
|
// server closes the connection.
|
||||||
func (h *handler) shutdownEndpoint(w http.ResponseWriter, r *http.Request) {
|
func (h *handler) shutdownEndpoint(w http.ResponseWriter, r *http.Request) {
|
||||||
if h.shutdown == nil {
|
if h.shutdown == nil {
|
||||||
writeError(w, http.StatusNotImplemented, "dieser Daemon kennt keinen Shutdown-Trigger")
|
writeError(w, http.StatusNotImplemented, "this daemon has no shutdown trigger")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, ShutdownResponse{OK: true})
|
writeJSON(w, http.StatusOK, ShutdownResponse{OK: true})
|
||||||
h.shutdown()
|
h.shutdown()
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeJSON schreibt eine JSON-Antwort mit Status-Code.
|
// writeJSON writes a JSON response with a status code.
|
||||||
func writeJSON(w http.ResponseWriter, code int, body any) {
|
func writeJSON(w http.ResponseWriter, code int, body any) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
w.WriteHeader(code)
|
w.WriteHeader(code)
|
||||||
_ = json.NewEncoder(w).Encode(body)
|
_ = json.NewEncoder(w).Encode(body)
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeError schreibt einen Fehler als {"error": "…"} mit Status-Code.
|
// writeError writes an error as {"error": "..."} with a status code.
|
||||||
func writeError(w http.ResponseWriter, code int, msg string) {
|
func writeError(w http.ResponseWriter, code int, msg string) {
|
||||||
writeJSON(w, code, map[string]string{"error": msg})
|
writeJSON(w, code, map[string]string{"error": msg})
|
||||||
}
|
}
|
||||||
+68
-55
@@ -1,53 +1,53 @@
|
|||||||
package api
|
package api
|
||||||
|
|
||||||
// Request/Response-Typen des Daemon-HTTP-Vertrags (Task-04-Brief, bindende
|
// Request/response types of the daemon HTTP contract (binding fields). The
|
||||||
// Felder). Die CLI und spätere Konsumenten (MCP, Task 06) benutzen dieselben
|
// CLI and other consumers (MCP) use the same types: one source, no contract
|
||||||
// Typen — eine Quelle, kein Contract-Drift zwischen Daemon und Client.
|
// drift between daemon and client.
|
||||||
|
|
||||||
// SpeakRequest ist der Body von POST /speak.
|
// SpeakRequest is the body of POST /speak.
|
||||||
type SpeakRequest struct {
|
type SpeakRequest struct {
|
||||||
// Text ist der Ansage-Text (Pflicht).
|
// Text is the announcement text (required).
|
||||||
Text string `json:"text"`
|
Text string `json:"text"`
|
||||||
|
|
||||||
// Priority: low | normal | high (Default normal, wenn leer).
|
// Priority: low | normal | high (default normal when empty).
|
||||||
Priority string `json:"priority,omitempty"`
|
Priority string `json:"priority,omitempty"`
|
||||||
|
|
||||||
// Provider pinnt die Provider-Kette (--provider).
|
// Provider pins the provider chain (--provider).
|
||||||
Provider string `json:"provider,omitempty"`
|
Provider string `json:"provider,omitempty"`
|
||||||
|
|
||||||
// Voice pinnt eine Voice-ID (--voice).
|
// Voice pins a voice ID (--voice).
|
||||||
Voice string `json:"voice,omitempty"`
|
Voice string `json:"voice,omitempty"`
|
||||||
|
|
||||||
// Lang pinnt die Sprache de | en (leer = automatische Erkennung).
|
// Lang pins the language de | en (empty = automatic detection).
|
||||||
Lang string `json:"lang,omitempty"`
|
Lang string `json:"lang,omitempty"`
|
||||||
|
|
||||||
// Now lässt die Ansage vor allen wartenden springen (--now).
|
// Now lets the announcement jump ahead of all waiting ones (--now).
|
||||||
Now bool `json:"now,omitempty"`
|
Now bool `json:"now,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// SpeakResponse ist die Antwort von POST /speak: 202 {"id":"…"} — bei
|
// SpeakResponse is the response of POST /speak: 202 {"id":"..."}; with mute
|
||||||
// aktivem Mute 202 {"id":"","muted":true} (Ansage verworfen; dokumentiertes
|
// active 202 {"id":"","muted":true} (announcement discarded; documented
|
||||||
// Verhalten, kein Fehler). Seit Task 05 meldet verworfenen Spam ebenso
|
// behaviour, not an error). Discarded spam is reported just as
|
||||||
// dokumentiert: 202 {"id":"","discarded":"rate_limit"|"quiet_hours"} —
|
// documented: 202 {"id":"","discarded":"rate_limit"|"quiet_hours"}, plus
|
||||||
// plus "toast":true, wenn die Ruhezeit-Ansage durch eine Benachrichtigung
|
// "toast":true when the quiet-hours announcement was replaced by a
|
||||||
// ersetzt wurde (quiet_mode = "toast").
|
// notification (quiet_mode = "toast").
|
||||||
type SpeakResponse struct {
|
type SpeakResponse struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Muted bool `json:"muted,omitempty"`
|
Muted bool `json:"muted,omitempty"`
|
||||||
|
|
||||||
// Discarded ist der Verwurfs-Grund ("rate_limit" | "quiet_hours");
|
// Discarded is the discard reason ("rate_limit" | "quiet_hours"); empty
|
||||||
// leer, wenn die Ansage aufgenommen wurde.
|
// when the announcement was admitted.
|
||||||
Discarded string `json:"discarded,omitempty"`
|
Discarded string `json:"discarded,omitempty"`
|
||||||
|
|
||||||
// Toast meldet die Ersetzung durch eine Benachrichtigung.
|
// Toast reports the replacement by a notification.
|
||||||
Toast bool `json:"toast,omitempty"`
|
Toast bool `json:"toast,omitempty"`
|
||||||
|
|
||||||
// Truncated meldet, dass der Text auf queue.max_text gekürzt und so
|
// Truncated reports that the text was cut to queue.max_text and
|
||||||
// aufgenommen wurde (Gesetz gegen vorgelesene Langantworten).
|
// admitted that way (the law against read-aloud long answers).
|
||||||
Truncated bool `json:"truncated,omitempty"`
|
Truncated bool `json:"truncated,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// CurrentItem beschreibt das laufende Item in GET /status.
|
// CurrentItem describes the running item in GET /status.
|
||||||
type CurrentItem struct {
|
type CurrentItem struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Text string `json:"text"`
|
Text string `json:"text"`
|
||||||
@@ -55,12 +55,12 @@ type CurrentItem struct {
|
|||||||
Now bool `json:"now"`
|
Now bool `json:"now"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StatusResponse ist die Antwort von GET /status: Queue-Länge, aktuelles
|
// StatusResponse is the response of GET /status: queue length, current item
|
||||||
// Item (null im Leerlauf), Mute-State, aktiver Provider, Daemon-Version.
|
// (null when idle), mute state, active provider, daemon version. QueueIDs
|
||||||
// QueueIDs ist die Ergänzung der wartenden IDs in Abarbeitungs-Reihenfolge
|
// lists the waiting IDs in processing order; the CLI needs them for its
|
||||||
// — die CLI braucht sie für ihr --wait-Polling. Task 05 ergänzt additiv
|
// --wait polling. The law state (rate_limit, quiet_hours) and mcp/cors
|
||||||
// den Gesetz-State (rate_limit, quiet_hours); Task 06 additiv mcp/cors
|
// (compat fields: MCP endpoint present, configured CORS origins) are
|
||||||
// (Compat-Felder: MCP-Endpoint vorhanden, konfigurierte CORS-Origins).
|
// additive.
|
||||||
type StatusResponse struct {
|
type StatusResponse struct {
|
||||||
Version string `json:"version"`
|
Version string `json:"version"`
|
||||||
Queue int `json:"queue"`
|
Queue int `json:"queue"`
|
||||||
@@ -72,59 +72,60 @@ type StatusResponse struct {
|
|||||||
QuietHours *QuietHoursState `json:"quiet_hours,omitempty"`
|
QuietHours *QuietHoursState `json:"quiet_hours,omitempty"`
|
||||||
Limits *LimitsState `json:"limits,omitempty"`
|
Limits *LimitsState `json:"limits,omitempty"`
|
||||||
|
|
||||||
// MCP meldet, dass der Daemon den MCP-Endpoint anbietet (immer true;
|
// MCP reports that the daemon offers the MCP endpoint (always true; the
|
||||||
// Feld existiert für additive Compat-Sicht von Clients/Browsern).
|
// field exists for an additive compat view of clients/browsers).
|
||||||
MCP bool `json:"mcp"`
|
MCP bool `json:"mcp"`
|
||||||
|
|
||||||
// Cors ist die konfigurierte CORS-Erlaubnisliste von POST /speak
|
// Cors is the configured CORS allow list of POST /speak (empty [] =
|
||||||
// (leeres [] = Tür zu). Immer vorhanden (auch leer), nicht omitempty.
|
// door closed). Always present (even when empty), not omitempty.
|
||||||
Cors []string `json:"cors"`
|
Cors []string `json:"cors"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// RateLimitState ist der Rate-Limit-State in GET /status (Task 05).
|
// RateLimitState is the rate-limit state in GET /status.
|
||||||
type RateLimitState struct {
|
type RateLimitState struct {
|
||||||
// Interval ist der konfigurierte Mindestabstand als Dauer-String
|
// Interval is the configured minimum spacing as a duration string
|
||||||
// ("30s"; "0s" = unbegrenzt).
|
// ("30s"; "0s" = unlimited).
|
||||||
Interval string `json:"interval"`
|
Interval string `json:"interval"`
|
||||||
|
|
||||||
// AllowHighBurst meldet, ob priority=high verstoßen darf.
|
// AllowHighBurst reports whether priority=high may violate it.
|
||||||
AllowHighBurst bool `json:"allow_high_burst"`
|
AllowHighBurst bool `json:"allow_high_burst"`
|
||||||
|
|
||||||
// NextSlot ist der nächste freie Ansage-Slot als RFC3339-Zeitstempel;
|
// NextSlot is the next free announcement slot as an RFC3339 timestamp;
|
||||||
// null, wenn sofort gespielt werden dürfte (oder unbegrenzt).
|
// null when playback would be allowed immediately (or unlimited).
|
||||||
NextSlot *string `json:"next_slot"`
|
NextSlot *string `json:"next_slot"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// LimitsState sind die Längen- und Alters-Gesetze in GET /status.
|
// LimitsState holds the length and age laws in GET /status.
|
||||||
type LimitsState struct {
|
type LimitsState struct {
|
||||||
// MaxText ist die Obergrenze der Ansage-Länge in Zeichen (0 = unbegrenzt).
|
// MaxText is the upper bound of the announcement length in characters
|
||||||
|
// (0 = unlimited).
|
||||||
MaxText int `json:"max_text"`
|
MaxText int `json:"max_text"`
|
||||||
|
|
||||||
// MaxAge ist die längste Wartezeit in der Queue als Dauer-String
|
// MaxAge is the longest wait in the queue as a duration string ("2m0s";
|
||||||
// ("2m0s"; "0s" = unbegrenzt).
|
// "0s" = unlimited).
|
||||||
MaxAge string `json:"max_age"`
|
MaxAge string `json:"max_age"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// QuietHoursState ist der Ruhezeit-State in GET /status (Task 05).
|
// QuietHoursState is the quiet-hours state in GET /status.
|
||||||
type QuietHoursState struct {
|
type QuietHoursState struct {
|
||||||
// Window ist das konfigurierte Fenster ("18:00-08:00"; "" = deaktiviert).
|
// Window is the configured window ("18:00-08:00"; "" = disabled).
|
||||||
Window string `json:"window"`
|
Window string `json:"window"`
|
||||||
|
|
||||||
// Active meldet, ob die lokale Zeit gerade im Fenster liegt.
|
// Active reports whether local time is currently inside the window.
|
||||||
Active bool `json:"active"`
|
Active bool `json:"active"`
|
||||||
|
|
||||||
// Mode ist der konfigurierte Ruhezeit-Modus ("discard" | "toast").
|
// Mode is the configured quiet-hours mode ("discard" | "toast").
|
||||||
Mode string `json:"mode"`
|
Mode string `json:"mode"`
|
||||||
|
|
||||||
// Until ist das Fenster-Ende als RFC3339-Zeitstempel, wenn aktiv;
|
// Until is the window end as an RFC3339 timestamp when active;
|
||||||
// sonst null.
|
// otherwise null.
|
||||||
Until *string `json:"until"`
|
Until *string `json:"until"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// PendingOrCurrent meldet, ob die Ansage mit der ID noch wartet oder
|
// PendingOrCurrent reports whether the announcement with the ID is still
|
||||||
// gerade läuft — Grundlage des --wait-Pollings der CLI. Ist die Ansage
|
// waiting or currently playing; the basis of the CLI's --wait polling. If
|
||||||
// weder wartend noch laufend, ist sie fertig (oder abgebrochen) — in
|
// it is neither waiting nor playing, it is done (or cancelled); in both
|
||||||
// beiden Fällen hat der Aufrufer nichts mehr zu warten.
|
// cases the caller has nothing left to wait for.
|
||||||
func (s StatusResponse) PendingOrCurrent(id string) bool {
|
func (s StatusResponse) PendingOrCurrent(id string) bool {
|
||||||
if s.Current != nil && s.Current.ID == id {
|
if s.Current != nil && s.Current.ID == id {
|
||||||
return true
|
return true
|
||||||
@@ -137,17 +138,29 @@ func (s StatusResponse) PendingOrCurrent(id string) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// CancelResponse ist die Antwort von POST /cancel.
|
// CancelResponse is the response of POST /cancel.
|
||||||
type CancelResponse struct {
|
type CancelResponse struct {
|
||||||
Cancelled int `json:"cancelled"`
|
Cancelled int `json:"cancelled"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// MuteResponse ist die Antwort von POST /mute und POST /unmute.
|
// MuteResponse is the response of POST /mute and POST /unmute.
|
||||||
type MuteResponse struct {
|
type MuteResponse struct {
|
||||||
Muted bool `json:"muted"`
|
Muted bool `json:"muted"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ShutdownResponse ist die Antwort von POST /shutdown.
|
// ShutdownResponse is the response of POST /shutdown.
|
||||||
type ShutdownResponse struct {
|
type ShutdownResponse struct {
|
||||||
OK bool `json:"ok"`
|
OK bool `json:"ok"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CancelItemRequest is the body of POST /cancel-item: the id of the
|
||||||
|
// announcement to cancel, if it is the one playing.
|
||||||
|
type CancelItemRequest struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CancelItemResponse is the answer of POST /cancel-item: whether the id was
|
||||||
|
// the playing announcement and has been cancelled.
|
||||||
|
type CancelItemResponse struct {
|
||||||
|
Cancelled bool `json:"cancelled"`
|
||||||
|
}
|
||||||
+19
-19
@@ -6,28 +6,28 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Sink-Namen (Teil des öffentlichen Vertrags; Spec: audio.sink = "oto"|"null").
|
// Sink names (part of the public contract; spec: audio.sink = "oto"|"null").
|
||||||
const (
|
const (
|
||||||
NameOto = "oto"
|
NameOto = "oto"
|
||||||
NameNull = "null"
|
NameNull = "null"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Sink gibt Audio-Bytes wieder. Die Bytes stammen aus Provider.Synthesize;
|
// Sink plays audio bytes. The bytes come from Provider.Synthesize; oto
|
||||||
// oto versteht RIFF/WAVE (PCM — das Lieferformat von osbuiltin) und MP3
|
// understands RIFF/WAVE (PCM, the delivery format of osbuiltin) and MP3
|
||||||
// (das Lieferformat der Cloud-Provider ElevenLabs/OpenAI/Edge).
|
// (the delivery format of the cloud providers ElevenLabs/OpenAI/Edge).
|
||||||
type Sink interface {
|
type Sink interface {
|
||||||
// Play spielt die Daten blockierend ab (bis zum Ende oder bis ctx
|
// Play plays the data and blocks until the end or until ctx is
|
||||||
// abgebrochen wird).
|
// cancelled.
|
||||||
Play(ctx context.Context, data []byte) error
|
Play(ctx context.Context, data []byte) error
|
||||||
|
|
||||||
// Name liefert den Sink-Namen (audio.sink-Konfiguration).
|
// Name returns the sink name (audio.sink configuration).
|
||||||
Name() string
|
Name() string
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewSink liefert den Sink zum konfigurierten Namen ("oto" oder "null").
|
// NewSink returns the sink for the configured name ("oto" or "null"). log
|
||||||
// log ist ein optionaler Log-Output — die CLI übergibt ihr stderr, über den
|
// is an optional log output: the CLI passes its stderr so the null sink can
|
||||||
// der null-Sink seine Verwurf-Zeile schreibt (nil = still verwerfen); der
|
// write its discard line (nil = discard silently); the oto sink needs no
|
||||||
// oto-Sink braucht kein Log. Unbekannte Namen sind ein klarer Fehler.
|
// log. Unknown names are a clear error.
|
||||||
func NewSink(name string, log io.Writer) (Sink, error) {
|
func NewSink(name string, log io.Writer) (Sink, error) {
|
||||||
switch name {
|
switch name {
|
||||||
case NameOto:
|
case NameOto:
|
||||||
@@ -35,24 +35,24 @@ func NewSink(name string, log io.Writer) (Sink, error) {
|
|||||||
case NameNull:
|
case NameNull:
|
||||||
return NullSink{W: log}, nil
|
return NullSink{W: log}, nil
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unbekannter audio sink %q (erlaubt: %q, %q)", name, NameOto, NameNull)
|
return nil, fmt.Errorf("unknown audio sink %q (allowed: %q, %q)", name, NameOto, NameNull)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// NullSink verwirft jede Ansage ohne Ton — für CI, Server und Tests. Wurde
|
// NullSink discards every announcement without sound; for CI, servers and
|
||||||
// ein W gesetzt (NewSink reicht dafür den Log-Output der CLI durch), loggt
|
// tests. If W is set (NewSink passes the CLI's log output), Play logs one
|
||||||
// Play eine Zeile darüber, damit „läuft ohne Ton durch" sichtbar bleibt.
|
// line about it so "runs through silently" stays visible.
|
||||||
type NullSink struct {
|
type NullSink struct {
|
||||||
W io.Writer // optionaler Log-Output; nil = still verwerfen
|
W io.Writer // optional log output; nil = discard silently
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name implementiert Sink.
|
// Name implements Sink.
|
||||||
func (NullSink) Name() string { return NameNull }
|
func (NullSink) Name() string { return NameNull }
|
||||||
|
|
||||||
// Play implementiert Sink: verwirft die Daten.
|
// Play implements Sink: discards the data.
|
||||||
func (n NullSink) Play(ctx context.Context, data []byte) error {
|
func (n NullSink) Play(ctx context.Context, data []byte) error {
|
||||||
if n.W != nil {
|
if n.W != nil {
|
||||||
fmt.Fprintf(n.W, "audio: %d Bytes verworfen (null sink)\n", len(data))
|
fmt.Fprintf(n.W, "audio: %d bytes discarded (null sink)\n", len(data))
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -10,9 +10,9 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
// buildWAV baut nach RIFF-Spezifikation eine WAV-Datei (unabhängig vom
|
// buildWAV builds a WAV file per the RIFF specification (implemented
|
||||||
// Parser implementiert, damit Parser und Test-Fixture nicht denselben
|
// independently of the parser so parser and test fixture cannot share the
|
||||||
// Fehler teilen).
|
// same bug).
|
||||||
func buildWAV(audioFormat uint16, channels, rate, bits int, samples []byte) []byte {
|
func buildWAV(audioFormat uint16, channels, rate, bits int, samples []byte) []byte {
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
buf.WriteString("RIFF")
|
buf.WriteString("RIFF")
|
||||||
@@ -44,22 +44,22 @@ func TestDecodeWAV(t *testing.T) {
|
|||||||
t.Fatalf("decodeWAV: %v", err)
|
t.Fatalf("decodeWAV: %v", err)
|
||||||
}
|
}
|
||||||
if f.SampleRate != 22050 || f.Channels != 1 || f.BitsPerCoded != 16 || f.Float {
|
if f.SampleRate != 22050 || f.Channels != 1 || f.BitsPerCoded != 16 || f.Float {
|
||||||
t.Errorf("Format = %+v", f)
|
t.Errorf("format = %+v", f)
|
||||||
}
|
}
|
||||||
if string(pcm) != "\x01\x02\x03\x04" {
|
if string(pcm) != "\x01\x02\x03\x04" {
|
||||||
t.Errorf("PCM = %x", pcm)
|
t.Errorf("PCM = %x", pcm)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
t.Run("8-bit stereo mit Extra-Chunk", func(t *testing.T) {
|
t.Run("8-bit stereo with extra chunk", func(t *testing.T) {
|
||||||
wav := buildWAV(1, 2, 8000, 8, []byte{7, 8, 9})
|
wav := buildWAV(1, 2, 8000, 8, []byte{7, 8, 9})
|
||||||
// LIST-Chunk (word-aligned, ungerade Länge) zwischen fmt und data einfügen
|
// insert a LIST chunk (word-aligned, odd length) between fmt and data
|
||||||
withList := append(wav[:36], append([]byte("LIST\x03\x00\x00\x00abc\x00"), wav[36:]...)...)
|
withList := append(wav[:36], append([]byte("LIST\x03\x00\x00\x00abc\x00"), wav[36:]...)...)
|
||||||
f, pcm, err := decodeWAV(withList)
|
f, pcm, err := decodeWAV(withList)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("decodeWAV: %v", err)
|
t.Fatalf("decodeWAV: %v", err)
|
||||||
}
|
}
|
||||||
if f.BitsPerCoded != 8 || f.Channels != 2 {
|
if f.BitsPerCoded != 8 || f.Channels != 2 {
|
||||||
t.Errorf("Format = %+v", f)
|
t.Errorf("format = %+v", f)
|
||||||
}
|
}
|
||||||
if string(pcm) != "\x07\x08\x09" {
|
if string(pcm) != "\x07\x08\x09" {
|
||||||
t.Errorf("PCM = %x", pcm)
|
t.Errorf("PCM = %x", pcm)
|
||||||
@@ -72,42 +72,42 @@ func TestDecodeWAV(t *testing.T) {
|
|||||||
t.Fatalf("decodeWAV: %v", err)
|
t.Fatalf("decodeWAV: %v", err)
|
||||||
}
|
}
|
||||||
if !f.Float || f.BitsPerCoded != 32 {
|
if !f.Float || f.BitsPerCoded != 32 {
|
||||||
t.Errorf("Format = %+v, want Float32", f)
|
t.Errorf("format = %+v, want Float32", f)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
t.Run("leerer data-Chunk ist erlaubt", func(t *testing.T) {
|
t.Run("empty data chunk is allowed", func(t *testing.T) {
|
||||||
wav := buildWAV(1, 1, 22050, 16, nil)
|
wav := buildWAV(1, 1, 22050, 16, nil)
|
||||||
_, pcm, err := decodeWAV(wav)
|
_, pcm, err := decodeWAV(wav)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("decodeWAV: %v", err)
|
t.Fatalf("decodeWAV: %v", err)
|
||||||
}
|
}
|
||||||
if len(pcm) != 0 {
|
if len(pcm) != 0 {
|
||||||
t.Errorf("PCM = %x, want leer", pcm)
|
t.Errorf("PCM = %x, want empty", pcm)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestDecodeWAVFehler(t *testing.T) {
|
func TestDecodeWAVErrors(t *testing.T) {
|
||||||
cases := []struct {
|
cases := []struct {
|
||||||
name string
|
name string
|
||||||
data []byte
|
data []byte
|
||||||
want string
|
want string
|
||||||
}{
|
}{
|
||||||
{"zu kurz", []byte("RIFF"), "zu kurz"},
|
{"too short", []byte("RIFF"), "too short"},
|
||||||
{"kein riff", []byte("RIFX" + "\x00\x00\x00\x00" + "WAVE"), "RIFF"},
|
{"no riff", []byte("RIFX" + "\x00\x00\x00\x00" + "WAVE"), "RIFF"},
|
||||||
{"24-bit pcm", buildWAV(1, 1, 44100, 24, []byte{1, 2, 3}), "nicht unterstütztes Format"},
|
{"24-bit pcm", buildWAV(1, 1, 44100, 24, []byte{1, 2, 3}), "unsupported format"},
|
||||||
{"3 kanäle", buildWAV(1, 3, 44100, 16, []byte{1, 2, 3, 4, 5, 6}), "Kanäle"},
|
{"3 channels", buildWAV(1, 3, 44100, 16, []byte{1, 2, 3, 4, 5, 6}), "channels"},
|
||||||
{"ohne data", func() []byte {
|
{"without data", func() []byte {
|
||||||
wav := buildWAV(1, 1, 22050, 16, []byte{1, 2})
|
wav := buildWAV(1, 1, 22050, 16, []byte{1, 2})
|
||||||
return wav[:36] // nur fmt-Chunk behalten
|
return wav[:36] // keep only the fmt chunk
|
||||||
}(), "data"},
|
}(), "data"},
|
||||||
{"kaputter chunk", append(buildWAV(1, 1, 22050, 16, nil), "data\xff\xff\xff\xff"...), "überragt"},
|
{"broken chunk", append(buildWAV(1, 1, 22050, 16, nil), "data\xff\xff\xff\xff"...), "exceeds"},
|
||||||
}
|
}
|
||||||
for _, tc := range cases {
|
for _, tc := range cases {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
_, _, err := decodeWAV(tc.data)
|
_, _, err := decodeWAV(tc.data)
|
||||||
if err == nil || !strings.Contains(err.Error(), tc.want) {
|
if err == nil || !strings.Contains(err.Error(), tc.want) {
|
||||||
t.Errorf("decodeWAV-Fehler = %v, will Meldung mit %q", err, tc.want)
|
t.Errorf("decodeWAV error = %v, want message containing %q", err, tc.want)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -124,9 +124,9 @@ func TestNewSink(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if _, err := NewSink("mpv", nil); err == nil {
|
if _, err := NewSink("mpv", nil); err == nil {
|
||||||
t.Error("NewSink(\"mpv\") soll fehlschlagen")
|
t.Error("NewSink(\"mpv\") should fail")
|
||||||
}
|
}
|
||||||
t.Run("null-Sink loggt über den Factory-Writer", func(t *testing.T) {
|
t.Run("null sink logs via the factory writer", func(t *testing.T) {
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
s, err := NewSink(NameNull, &buf)
|
s, err := NewSink(NameNull, &buf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -135,49 +135,49 @@ func TestNewSink(t *testing.T) {
|
|||||||
if err := s.Play(context.Background(), []byte("audio")); err != nil {
|
if err := s.Play(context.Background(), []byte("audio")); err != nil {
|
||||||
t.Fatalf("Play: %v", err)
|
t.Fatalf("Play: %v", err)
|
||||||
}
|
}
|
||||||
if !strings.Contains(buf.String(), "verworfen (null sink)") {
|
if !strings.Contains(buf.String(), "discarded (null sink)") {
|
||||||
t.Errorf("Log = %q, will Verwurf-Zeile über den Factory-Writer", buf.String())
|
t.Errorf("log = %q, want discard line via the factory writer", buf.String())
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNullSinkVerwirftUndLoggt(t *testing.T) {
|
func TestNullSinkDiscardsAndLogs(t *testing.T) {
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
sink := NullSink{W: &buf}
|
sink := NullSink{W: &buf}
|
||||||
if err := sink.Play(context.Background(), []byte("audio")); err != nil {
|
if err := sink.Play(context.Background(), []byte("audio")); err != nil {
|
||||||
t.Fatalf("NullSink.Play: %v", err)
|
t.Fatalf("NullSink.Play: %v", err)
|
||||||
}
|
}
|
||||||
if !strings.Contains(buf.String(), "verworfen") {
|
if !strings.Contains(buf.String(), "discarded") {
|
||||||
t.Errorf("NullSink-Log = %q, will Verwurf-Zeile", buf.String())
|
t.Errorf("NullSink log = %q, want discard line", buf.String())
|
||||||
}
|
}
|
||||||
if sink.Name() != NameNull {
|
if sink.Name() != NameNull {
|
||||||
t.Errorf("Name() = %q", sink.Name())
|
t.Errorf("Name() = %q", sink.Name())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestOtoSinkUngueltigeDaten: OtoSink.Play muss an der WAV-Dekodierung
|
// TestOtoSinkInvalidData: OtoSink.Play must fail at WAV decoding before any
|
||||||
// scheitern, bevor irgend ein Audio-Gerät angefasst wird — das ist der
|
// audio device is touched; this is the CI/server-safe error path of the oto
|
||||||
// CI-/Server-sichere Fehlerpfad des oto-Sinks.
|
// sink.
|
||||||
func TestOtoSinkUngueltigeDaten(t *testing.T) {
|
func TestOtoSinkInvalidData(t *testing.T) {
|
||||||
err := (OtoSink{}).Play(context.Background(), []byte("kein audio"))
|
err := (OtoSink{}).Play(context.Background(), []byte("not audio"))
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Fatal("OtoSink.Play mit Müll: kein Fehler")
|
t.Fatal("OtoSink.Play with garbage: no error")
|
||||||
}
|
}
|
||||||
if !strings.Contains(err.Error(), "wav:") {
|
if !strings.Contains(err.Error(), "wav:") {
|
||||||
t.Errorf("Fehler soll aus dem WAV-Parser kommen: %v", err)
|
t.Errorf("error should come from the WAV parser: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestOtoSinkEchteWiedergabe läuft nur mit TALK_TEST_REAL_AUDIO=1 (erzeugt
|
// TestOtoSinkRealPlayback runs only with TALK_TEST_REAL_AUDIO=1 (produces
|
||||||
// echten Ton); Standard-Testläufe bleiben stumm.
|
// real sound); default test runs stay silent.
|
||||||
func TestOtoSinkEchteWiedergabe(t *testing.T) {
|
func TestOtoSinkRealPlayback(t *testing.T) {
|
||||||
if testing.Short() {
|
if testing.Short() {
|
||||||
t.Skip("Übersprungen (-short)")
|
t.Skip("skipped (-short)")
|
||||||
}
|
}
|
||||||
if os.Getenv("TALK_TEST_REAL_AUDIO") != "1" {
|
if os.Getenv("TALK_TEST_REAL_AUDIO") != "1" {
|
||||||
t.Skip("Übersprungen (hörbar) — mit TALK_TEST_REAL_AUDIO=1 ausführen")
|
t.Skip("skipped (audible); run with TALK_TEST_REAL_AUDIO=1")
|
||||||
}
|
}
|
||||||
// 0,1 s 440-Hz-Sinus, 16 Bit mono 22050 Hz.
|
// 0.1 s 440 Hz sine, 16 bit mono 22050 Hz.
|
||||||
const rate = 22050
|
const rate = 22050
|
||||||
samples := make([]byte, rate/10*2)
|
samples := make([]byte, rate/10*2)
|
||||||
for i := 0; i < rate/10; i++ {
|
for i := 0; i < rate/10; i++ {
|
||||||
|
|||||||
@@ -6,11 +6,11 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Check prüft, ob der Sink name einsatzbereit ist, ohne Ton zu erzeugen:
|
// Check verifies that the sink name is ready without producing sound: null
|
||||||
// null ist immer bereit; oto initialisiert den Audio-Kontext (Standard-
|
// is always ready; oto initializes the audio context (default format 44.1
|
||||||
// Format 44,1 kHz Stereo 16 Bit) und wartet auf dessen Bereitschaft — so
|
// kHz stereo 16 bit) and waits for it to become ready, so "no audio device"
|
||||||
// fällt „kein Audiogerät" (Server, Container, fehlende PulseAudio/ALSA-
|
// (servers, containers, missing PulseAudio/ALSA library) shows up in
|
||||||
// Bibliothek) in `talk doctor` auf, nicht erst bei der ersten Ansage.
|
// `talk doctor` rather than at the first announcement.
|
||||||
func Check(ctx context.Context, name string) error {
|
func Check(ctx context.Context, name string) error {
|
||||||
switch name {
|
switch name {
|
||||||
case NameNull:
|
case NameNull:
|
||||||
@@ -23,15 +23,15 @@ func Check(ctx context.Context, name string) error {
|
|||||||
select {
|
select {
|
||||||
case <-c.ready:
|
case <-c.ready:
|
||||||
if err := c.ctx.Err(); err != nil {
|
if err := c.ctx.Err(); err != nil {
|
||||||
return fmt.Errorf("oto: Initialisierung fehlgeschlagen: %w", err)
|
return fmt.Errorf("oto: initialization failed: %w", err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
return fmt.Errorf("oto: Audio-Gerät antwortet nicht (%v)", ctx.Err())
|
return fmt.Errorf("oto: audio device not responding (%v)", ctx.Err())
|
||||||
case <-time.After(5 * time.Second):
|
case <-time.After(5 * time.Second):
|
||||||
return fmt.Errorf("oto: Audio-Gerät antwortet nicht binnen 5 s")
|
return fmt.Errorf("oto: audio device not responding within 5 s")
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
return fmt.Errorf("unbekannter audio sink %q (erlaubt: %q, %q)", name, NameOto, NameNull)
|
return fmt.Errorf("unknown audio sink %q (allowed: %q, %q)", name, NameOto, NameNull)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
// Package audio implementiert die Audio-Ausgabe von talk über das
|
// Package audio implements talk's audio output behind the Sink interface:
|
||||||
// Sink-Interface: Playback embedded via oto (RIFF/WAVE-PCM und MP3, per
|
// embedded playback via oto (RIFF/WAVE PCM and MP3, via a pure Go decoder)
|
||||||
// reinem Go-Dekodierer) und ein null-Sink, das verwirft (CI, Server,
|
// and a null sink that discards (CI, servers, tests). Selected via config
|
||||||
// Tests). Auswahl per Config audio.sink = "oto" | "null" (Default oto).
|
// audio.sink = "oto" | "null" (default oto).
|
||||||
package audio
|
package audio
|
||||||
+22
-24
@@ -8,23 +8,21 @@ import (
|
|||||||
mpg "github.com/hajimehoshi/go-mp3"
|
mpg "github.com/hajimehoshi/go-mp3"
|
||||||
)
|
)
|
||||||
|
|
||||||
// decodeMP3 dekodiert MP3-Daten — das Lieferformat der Cloud-Provider ab
|
// decodeMP3 decodes MP3 data, the delivery format of the cloud providers
|
||||||
// Task 03 (ElevenLabs, OpenAI TTS, Edge-TTS) — in rohe PCM-Samples für
|
// (ElevenLabs, OpenAI TTS, Edge TTS), into raw PCM samples for oto.
|
||||||
// oto.
|
|
||||||
//
|
//
|
||||||
// Entscheidung mp3-Dekodierung (Task 03): eingebauter, reiner Go-Dekoder
|
// Decision: a built-in pure Go decoder (github.com/hajimehoshi/go-mp3
|
||||||
// github.com/hajimehoshi/go-mp3 v0.3.4 statt WAV/PCM-Anforderung bei den
|
// v0.3.4) instead of requesting WAV/PCM from the APIs. Reasons: (1) all
|
||||||
// APIs. Begründung: (1) Alle drei Cloud-Provider liefern mp3 als ihr
|
// three cloud providers deliver mp3 as their native format; only OpenAI
|
||||||
// natives Format; nur OpenAI kennt response_format "wav"/"pcm", ElevenLabs
|
// knows response_format "wav"/"pcm", ElevenLabs and Edge TTS do not, so a
|
||||||
// und Edge-TTS aber nicht — eine einheitliche mp3-Pipeline hält die Kette
|
// single mp3 pipeline keeps the chain symmetric. (2) The decoder is free of
|
||||||
// symmetrisch. (2) Der Dekoder ist nachweislich frei von CGO (kein
|
// CGO (no import "C" in the module), which keeps the cross-compile
|
||||||
// import "C" im Modul), damit bleibt die Cross-Compile-Verpflichtung
|
// commitment (CGO_ENABLED=0 for all 6 targets) intact, verified by a
|
||||||
// (CGO_ENABLED=0 für alle 6 Targets) unangetastet — verifiziert per
|
// GOOS/GOARCH matrix build.
|
||||||
// GOOS/GOARCH-Matrix-Build, siehe Task-03-Report.
|
|
||||||
//
|
//
|
||||||
// Der Dekoder liefert immer 16-Bit-PCM little-endian mit 2 Kanälen — auch
|
// The decoder always yields 16-bit little-endian PCM with 2 channels; mono
|
||||||
// für Mono-Quellen (etwa Edge-TTS: 24 kHz mono) wird auf Stereo
|
// sources (such as Edge TTS: 24 kHz mono) are mirrored to stereo. The
|
||||||
// gespiegelt; die Sample-Rate stammt aus dem ersten MP3-Frame.
|
// sample rate comes from the first MP3 frame.
|
||||||
func decodeMP3(data []byte) (pcmFormat, []byte, error) {
|
func decodeMP3(data []byte) (pcmFormat, []byte, error) {
|
||||||
dec, err := mpg.NewDecoder(bytes.NewReader(data))
|
dec, err := mpg.NewDecoder(bytes.NewReader(data))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -32,21 +30,21 @@ func decodeMP3(data []byte) (pcmFormat, []byte, error) {
|
|||||||
}
|
}
|
||||||
pcm, err := io.ReadAll(dec)
|
pcm, err := io.ReadAll(dec)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return pcmFormat{}, nil, fmt.Errorf("mp3: dekodieren: %w", err)
|
return pcmFormat{}, nil, fmt.Errorf("mp3: decoding: %w", err)
|
||||||
}
|
}
|
||||||
if len(pcm) == 0 {
|
if len(pcm) == 0 {
|
||||||
return pcmFormat{}, nil, fmt.Errorf("mp3: Dekodierung lieferte keine Samples")
|
return pcmFormat{}, nil, fmt.Errorf("mp3: decoding produced no samples")
|
||||||
}
|
}
|
||||||
return pcmFormat{
|
return pcmFormat{
|
||||||
SampleRate: dec.SampleRate(),
|
SampleRate: dec.SampleRate(),
|
||||||
Channels: 2, // go-mp3 dekodiert grundsätzlich 2 Kanäle (s. doc)
|
Channels: 2, // go-mp3 always decodes to 2 channels (see its docs)
|
||||||
BitsPerCoded: 16,
|
BitsPerCoded: 16,
|
||||||
}, pcm, nil
|
}, pcm, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// looksLikeMP3 meldet, ob data nach MP3 aussieht: ID3v2-Tag (führt mit
|
// looksLikeMP3 reports whether data looks like MP3: an ID3v2 tag (leading
|
||||||
// "ID3") oder ein roher Frame-Sync (erstes Byte 0xFF, oberste 3 Bits des
|
// "ID3") or a raw frame sync (first byte 0xFF, top 3 bits of the second
|
||||||
// zweiten Bytes gesetzt).
|
// byte set).
|
||||||
func looksLikeMP3(data []byte) bool {
|
func looksLikeMP3(data []byte) bool {
|
||||||
if len(data) >= 3 && string(data[0:3]) == "ID3" {
|
if len(data) >= 3 && string(data[0:3]) == "ID3" {
|
||||||
return true
|
return true
|
||||||
@@ -54,9 +52,9 @@ func looksLikeMP3(data []byte) bool {
|
|||||||
return len(data) >= 2 && data[0] == 0xFF && data[1]&0xE0 == 0xE0
|
return len(data) >= 2 && data[0] == 0xFF && data[1]&0xE0 == 0xE0
|
||||||
}
|
}
|
||||||
|
|
||||||
// decodeAudio ist die Format-Weiche der Sinks: RIFF/WAVE (PCM) nach
|
// decodeAudio is the format switch of the sinks: RIFF/WAVE (PCM) goes to
|
||||||
// decodeWAV, MP3 (ID3-Tag oder Frame-Sync) nach decodeMP3. Alles andere
|
// decodeWAV, MP3 (ID3 tag or frame sync) to decodeMP3. Everything else
|
||||||
// fällt durch zu decodeWAV, das den präzisen „kein RIFF"-Fehler liefert.
|
// falls through to decodeWAV, which yields the precise "no RIFF" error.
|
||||||
func decodeAudio(data []byte) (pcmFormat, []byte, error) {
|
func decodeAudio(data []byte) (pcmFormat, []byte, error) {
|
||||||
if len(data) >= 4 && string(data[0:4]) == "RIFF" {
|
if len(data) >= 4 && string(data[0:4]) == "RIFF" {
|
||||||
return decodeWAV(data)
|
return decodeWAV(data)
|
||||||
|
|||||||
+40
-44
@@ -6,16 +6,15 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Zwei einmalig erzeugte, echte MP3-Fixtures (ffmpeg am Dev-Host, in den
|
// Two real MP3 fixtures generated once (ffmpeg on the dev host, embedded in
|
||||||
// Test eingebettet — Tests bleiben zur Laufzeit frei von Werkzeug-Abhängig-
|
// the test so tests stay free of tool dependencies at runtime). Both match
|
||||||
// keiten). Beide entsprechen dem Lieferformat der Cloud-Provider aus
|
// the delivery format of the cloud providers:
|
||||||
// Task 03:
|
|
||||||
//
|
//
|
||||||
// fixtureMP3Mono: 0,15 s Stille, 24 kHz mono 48 kbit/s — exakt das
|
// fixtureMP3Mono: 0.15 s silence, 24 kHz mono 48 kbit/s; exactly the
|
||||||
// Edge-TTS-Ausgabeformat (audio-24khz-48kbitrate-mono-
|
// Edge TTS output format (audio-24khz-48kbitrate-mono-
|
||||||
// mp3); übt den Mono→Stereo-Upsample-Pfad des Dekoders.
|
// mp3); exercises the decoder's mono-to-stereo path.
|
||||||
// fixtureMP3Stereo: 0,15 s 440-Hz-Sinus, 44,1 kHz stereo 64 kbit/s — das
|
// fixtureMP3Stereo: 0.15 s 440 Hz sine, 44.1 kHz stereo 64 kbit/s; the
|
||||||
// typische ElevenLabs/OpenAI-Format.
|
// typical ElevenLabs/OpenAI format.
|
||||||
const fixtureMP3MonoB64 = "SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjYwLjE2LjEwMQAAAAAAAAAAAAAA//OEwAAAAAAAAAAAAEluZm8AAAAPAAAACQAABdAAOTk5OTk5OTk5OTlSUlJSUlJSUlJSUmtra2tra2tra2trhISEhISEhISEhIScnJycnJycnJycnLW1tbW1tbW1tbW1zs7Ozs7Ozs7Ozs7n5+fn5+fn5+fn5///////////////AAAAAExhdmM2MC4zMQAAAAAAAAAAAAAAACQD8AAAAAAAAAXQx638BQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//NkxAAAAANIAAAAAExBTUVVVVVMQU1FNC4wVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//NkxHwAAANIAAAAAFVVVVVVVVVMQU1FNC4wVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//NkxHwAAANIAAAAAFVVVVVVVVVMQU1FNC4wVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//NkxHwAAANIAAAAAFVVVVVVVVVMQU1FNC4wVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//NkxHwAAANIAAAAAFVVVVVVVVVMQU1FNC4wVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//NkxHwAAANIAAAAAFVVVVVVVVVMQU1FNC4wVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//NkxHwAAANIAAAAAFVVVVVVVVVMQU1FNC4wVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//NkxHwAAANIAAAAAFVVVVVVVVVMQU1FNC4wVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//NkxHwAAANIAAAAAFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV"
|
const fixtureMP3MonoB64 = "SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjYwLjE2LjEwMQAAAAAAAAAAAAAA//OEwAAAAAAAAAAAAEluZm8AAAAPAAAACQAABdAAOTk5OTk5OTk5OTlSUlJSUlJSUlJSUmtra2tra2tra2trhISEhISEhISEhIScnJycnJycnJycnLW1tbW1tbW1tbW1zs7Ozs7Ozs7Ozs7n5+fn5+fn5+fn5///////////////AAAAAExhdmM2MC4zMQAAAAAAAAAAAAAAACQD8AAAAAAAAAXQx638BQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//NkxAAAAANIAAAAAExBTUVVVVVMQU1FNC4wVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//NkxHwAAANIAAAAAFVVVVVVVVVMQU1FNC4wVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//NkxHwAAANIAAAAAFVVVVVVVVVMQU1FNC4wVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//NkxHwAAANIAAAAAFVVVVVVVVVMQU1FNC4wVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//NkxHwAAANIAAAAAFVVVVVVVVVMQU1FNC4wVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//NkxHwAAANIAAAAAFVVVVVVVVVMQU1FNC4wVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//NkxHwAAANIAAAAAFVVVVVVVVVMQU1FNC4wVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//NkxHwAAANIAAAAAFVVVVVVVVVMQU1FNC4wVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//NkxHwAAANIAAAAAFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV"
|
||||||
|
|
||||||
const fixtureMP3StereoB64 = "SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjYwLjE2LjEwMQAAAAAAAAAAAAAA//tQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASW5mbwAAAA8AAAAHAAAGhgA/Pz8/Pz8/Pz8/Pz8/P19fX19fX19fX19fX19ff39/f39/f39/f39/f3+fn5+fn5+fn5+fn5+fn5+/v7+/v7+/v7+/v7+/v9/f39/f39/f39/f39/f//////////////////8AAAAATGF2YzYwLjMxAAAAAAAAAAAAAAAAJANpAAAAAAAABoYxZN5VAAAAAAAAAAAAAAAAAAAAAP/7UGQAAAGPB1PVMCAMAAANIKAAAQtkrUe5tQAAAAA0gwAAAAAAWLlbSAEsSzOM4EAEAaEx+7b9wfPggCAIawf1AgCByXB8P4gBCDju/o8/ynn+U9/QAAB54AwKBwMBwMBQAAFQYGzUQALpOGBjRoAS+wRiXRL4oTPxwxscc7rrbANAE+BRFYRX4CwgQbQbf8QQFYCkKoNv/iJIh8KxCPf/xVIh8PiEej3+oGhKEga/6AAAApR2UEOC4IEAFJQRgMbD4SaWFOYlBOYKASCQCLL/+1JkD4jxxgdL53QADAAADSDgAAEGsCEUDftiQAAANIAAAARAoAmvdKzM8GvTr7RI79DR2VcAU20f7f//oSHMQEjMz03SSMSce03/PSzfLHvMSwKQ4NnM9RTNDwzV1MZFVqS/AHAT+e8a7q9+L/6U/+z6FQAAwGRkDDijFFTKrjabzCXGENGzGA0TxejCIBdNEYs6apxxagJ1trIcXd1/JeZ/X/b/1+i936xuCQSSghxU5gAd/mCwEoZaKkBlfBKGC2BKeoGIwBGAMJiS/APLqv/7UmQuiPG2B8bLXsiQAAANIAAAAQZcHyVMewJQAAA0gAAABHKvo6//9u//q/7Nv1ogDEBcxUkMiRzSZwwMIINMWLQbzFZAgEwK8CEMwXMKCNMZNvIM+GXrLrPfy/0dBBK8xQOM5NTeoQxNRxzhW4hOCMckxOgmjhWUztHMwPjL30xUZXRK8Ac+5n3dP8U+jp/993R/1QAAABhG0CAAXeBgIBQM7kwRQ5jJeegMk8OAwPALy4SxQUY1PL0xYN871ZmKO7X/s/1f///oT4MeHNco//tSZFAN8XoIxYt/0JAAAA0gAAABBrQhFA37YkAAADSAAAAEPXrMRAXg3c72DdEF8MRUH8+VI2Do0rU0WoxhJl9JmCf/1f//////SgAAcCBADChEw0eMWPzNYwwlh3TRv77NE4dMwhQeDIZBxRxGnjoAsl+zwbtQl9P2Vywc//29RAABYoMCCKFka6wsBjBQuObW04mcTGIbCA2hPQBoB2V2wIYzS/1q///6k////+0AAD2/T7fb/b0YCAAACXCJpXpktZdKRqMMiYljiZYRljn/+1JkdA3xqAdI6z7AmAAADSAAAAEFtCEWDXtCQAAANIAAAAS1qIWFQOGBu1BDXyALuvctJN0DKUQSBydaGrcUrx5+AghClCpXselWdBCLUOQJbMQULhJKl5UtMt63+FjfdbQTuGrApeyZav7/e/////+LP9DMeiUThj/Ihg0EmkMQAAHEiVkSKOHEQCE4SASTkRCVR6IniVx4jOxjwVce/EU7vK1MQU1FNC4wVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/7UmSZAPGrB8ZLfsiQAAANIAAAAQXUHTWVwAAwAAA0goAABFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//tSZL2AA+cuVO5nIAQAAA0gwAAABJgm3HxggAAAADSDgAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVU="
|
const fixtureMP3StereoB64 = "SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjYwLjE2LjEwMQAAAAAAAAAAAAAA//tQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASW5mbwAAAA8AAAAHAAAGhgA/Pz8/Pz8/Pz8/Pz8/P19fX19fX19fX19fX19ff39/f39/f39/f39/f3+fn5+fn5+fn5+fn5+fn5+/v7+/v7+/v7+/v7+/v9/f39/f39/f39/f39/f//////////////////8AAAAATGF2YzYwLjMxAAAAAAAAAAAAAAAAJANpAAAAAAAABoYxZN5VAAAAAAAAAAAAAAAAAAAAAP/7UGQAAAGPB1PVMCAMAAANIKAAAQtkrUe5tQAAAAA0gwAAAAAAWLlbSAEsSzOM4EAEAaEx+7b9wfPggCAIawf1AgCByXB8P4gBCDju/o8/ynn+U9/QAAB54AwKBwMBwMBQAAFQYGzUQALpOGBjRoAS+wRiXRL4oTPxwxscc7rrbANAE+BRFYRX4CwgQbQbf8QQFYCkKoNv/iJIh8KxCPf/xVIh8PiEej3+oGhKEga/6AAAApR2UEOC4IEAFJQRgMbD4SaWFOYlBOYKASCQCLL/+1JkD4jxxgdL53QADAAADSDgAAEGsCEUDftiQAAANIAAAARAoAmvdKzM8GvTr7RI79DR2VcAU20f7f//oSHMQEjMz03SSMSce03/PSzfLHvMSwKQ4NnM9RTNDwzV1MZFVqS/AHAT+e8a7q9+L/6U/+z6FQAAwGRkDDijFFTKrjabzCXGENGzGA0TxejCIBdNEYs6apxxagJ1trIcXd1/JeZ/X/b/1+i936xuCQSSghxU5gAd/mCwEoZaKkBlfBKGC2BKeoGIwBGAMJiS/APLqv/7UmQuiPG2B8bLXsiQAAANIAAAAQZcHyVMewJQAAA0gAAABHKvo6//9u//q/7Nv1ogDEBcxUkMiRzSZwwMIINMWLQbzFZAgEwK8CEMwXMKCNMZNvIM+GXrLrPfy/0dBBK8xQOM5NTeoQxNRxzhW4hOCMckxOgmjhWUztHMwPjL30xUZXRK8Ac+5n3dP8U+jp/993R/1QAAABhG0CAAXeBgIBQM7kwRQ5jJeegMk8OAwPALy4SxQUY1PL0xYN871ZmKO7X/s/1f///oT4MeHNco//tSZFAN8XoIxYt/0JAAAA0gAAABBrQhFA37YkAAADSAAAAEPXrMRAXg3c72DdEF8MRUH8+VI2Do0rU0WoxhJl9JmCf/1f//////SgAAcCBADChEw0eMWPzNYwwlh3TRv77NE4dMwhQeDIZBxRxGnjoAsl+zwbtQl9P2Vywc//29RAABYoMCCKFka6wsBjBQuObW04mcTGIbCA2hPQBoB2V2wIYzS/1q///6k////+0AAD2/T7fb/b0YCAAACXCJpXpktZdKRqMMiYljiZYRljn/+1JkdA3xqAdI6z7AmAAADSAAAAEFtCEWDXtCQAAANIAAAAS1qIWFQOGBu1BDXyALuvctJN0DKUQSBydaGrcUrx5+AghClCpXselWdBCLUOQJbMQULhJKl5UtMt63+FjfdbQTuGrApeyZav7/e/////+LP9DMeiUThj/Ihg0EmkMQAAHEiVkSKOHEQCE4SASTkRCVR6IniVx4jOxjwVce/EU7vK1MQU1FNC4wVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/7UmSZAPGrB8ZLfsiQAAANIAAAAQXUHTWVwAAwAAA0goAABFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//tSZL2AA+cuVO5nIAQAAA0gwAAABJgm3HxggAAAADSDgAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVU="
|
||||||
@@ -24,14 +23,14 @@ func fixture(t *testing.T, b64 string) []byte {
|
|||||||
t.Helper()
|
t.Helper()
|
||||||
data, err := base64.StdEncoding.DecodeString(b64)
|
data, err := base64.StdEncoding.DecodeString(b64)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Fixture dekodieren: %v", err)
|
t.Fatalf("decoding fixture: %v", err)
|
||||||
}
|
}
|
||||||
return data
|
return data
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestDecodeMP3Mono: das Edge-Format (24 kHz mono) dekodiert zu 16-Bit-PCM
|
// TestDecodeMP3Mono: the Edge format (24 kHz mono) decodes to 16-bit PCM
|
||||||
// stereo — der Dekoder spiegelt Mono auf zwei Kanäle, Samples sind 4 Bytes
|
// stereo; the decoder mirrors mono onto two channels, samples are aligned
|
||||||
// (2 Kanäle × 2 Bytes) aligned.
|
// to 4 bytes (2 channels x 2 bytes).
|
||||||
func TestDecodeMP3Mono(t *testing.T) {
|
func TestDecodeMP3Mono(t *testing.T) {
|
||||||
f, pcm, err := decodeMP3(fixture(t, fixtureMP3MonoB64))
|
f, pcm, err := decodeMP3(fixture(t, fixtureMP3MonoB64))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -41,60 +40,57 @@ func TestDecodeMP3Mono(t *testing.T) {
|
|||||||
t.Errorf("SampleRate = %d, want 24000", f.SampleRate)
|
t.Errorf("SampleRate = %d, want 24000", f.SampleRate)
|
||||||
}
|
}
|
||||||
if f.Channels != 2 || f.BitsPerCoded != 16 || f.Float {
|
if f.Channels != 2 || f.BitsPerCoded != 16 || f.Float {
|
||||||
t.Errorf("Format = %+v, want 2 Kanäle/16 Bit/int", f)
|
t.Errorf("format = %+v, want 2 channels/16 bit/int", f)
|
||||||
}
|
}
|
||||||
if len(pcm) == 0 || len(pcm)%4 != 0 {
|
if len(pcm) == 0 || len(pcm)%4 != 0 {
|
||||||
t.Errorf("PCM-Länge = %d, want > 0 und durch 4 teilbar (16-Bit-Samples stereo)", len(pcm))
|
t.Errorf("PCM length = %d, want > 0 and divisible by 4 (16-bit stereo samples)", len(pcm))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestDecodeMP3Stereo: ElevenLabs/OpenAI-typisches Format (44,1 kHz stereo).
|
// TestDecodeMP3Stereo: the ElevenLabs/OpenAI-typical format (44.1 kHz stereo).
|
||||||
func TestDecodeMP3Stereo(t *testing.T) {
|
func TestDecodeMP3Stereo(t *testing.T) {
|
||||||
f, pcm, err := decodeMP3(fixture(t, fixtureMP3StereoB64))
|
f, pcm, err := decodeMP3(fixture(t, fixtureMP3StereoB64))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("decodeMP3 (stereo): %v", err)
|
t.Fatalf("decodeMP3 (stereo): %v", err)
|
||||||
}
|
}
|
||||||
if f.SampleRate != 44100 || f.Channels != 2 || f.BitsPerCoded != 16 {
|
if f.SampleRate != 44100 || f.Channels != 2 || f.BitsPerCoded != 16 {
|
||||||
t.Errorf("Format = %+v, want 44100 Hz stereo 16 Bit", f)
|
t.Errorf("format = %+v, want 44100 Hz stereo 16 bit", f)
|
||||||
}
|
}
|
||||||
if len(pcm) == 0 || len(pcm)%4 != 0 {
|
if len(pcm) == 0 || len(pcm)%4 != 0 {
|
||||||
t.Errorf("PCM-Länge = %d, want > 0 und durch 4 teilbar", len(pcm))
|
t.Errorf("PCM length = %d, want > 0 and divisible by 4", len(pcm))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestDecodeMP3Fehler: Daten, die nach MP3 aussehen, aber keine Frames
|
// TestDecodeMP3Errors: data that looks like MP3 but contains no frames is a
|
||||||
// enthalten, sind ein klarer mp3-Fehler (nicht der WAV-Fehlerpfad).
|
// clear mp3 error (not the WAV error path).
|
||||||
func TestDecodeMP3Fehler(t *testing.T) {
|
func TestDecodeMP3Errors(t *testing.T) {
|
||||||
cases := []struct{ name, want string }{
|
cases := []struct {
|
||||||
{"Müll mit Frame-Sync", "mp3:"},
|
name string
|
||||||
{"ID3-Tag ohne Frames", "mp3:"},
|
data []byte
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"garbage with frame sync", []byte{0xFF, 0xFB, 'n', 'o', 't', ' ', 'm', 'p', '3'}, "mp3:"},
|
||||||
|
{"ID3 tag without frames", []byte("ID3\x04\x00\x00\x00\x00\x00\x00"), "mp3:"},
|
||||||
}
|
}
|
||||||
for _, tc := range cases {
|
for _, tc := range cases {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
var data []byte
|
_, _, err := decodeMP3(tc.data)
|
||||||
switch tc.name {
|
|
||||||
case "Müll mit Frame-Sync":
|
|
||||||
data = []byte{0xFF, 0xFB, 'k', 'e', 'i', 'n', ' ', 'm', 'p', '3'}
|
|
||||||
case "ID3-Tag ohne Frames":
|
|
||||||
data = []byte("ID3\x04\x00\x00\x00\x00\x00\x00")
|
|
||||||
}
|
|
||||||
_, _, err := decodeMP3(data)
|
|
||||||
if err == nil || !strings.Contains(err.Error(), tc.want) {
|
if err == nil || !strings.Contains(err.Error(), tc.want) {
|
||||||
t.Errorf("decodeMP3-Fehler = %v, will Meldung mit %q", err, tc.want)
|
t.Errorf("decodeMP3 error = %v, want message containing %q", err, tc.want)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestLooksLikeMP3 pinnt die Format-Erkennung.
|
// TestLooksLikeMP3 pins the format detection.
|
||||||
func TestLooksLikeMP3(t *testing.T) {
|
func TestLooksLikeMP3(t *testing.T) {
|
||||||
yes := [][]byte{
|
yes := [][]byte{
|
||||||
fixture(t, fixtureMP3StereoB64), // ID3-Tag
|
fixture(t, fixtureMP3StereoB64), // ID3 tag
|
||||||
{0xFF, 0xFB, 0x00, 0x00}, // roher Frame-Sync
|
{0xFF, 0xFB, 0x00, 0x00}, // raw frame sync
|
||||||
}
|
}
|
||||||
no := [][]byte{
|
no := [][]byte{
|
||||||
[]byte("RIFF....WAVE"),
|
[]byte("RIFF....WAVE"),
|
||||||
[]byte("kein audio"),
|
[]byte("not audio"),
|
||||||
{0xFF},
|
{0xFF},
|
||||||
{},
|
{},
|
||||||
}
|
}
|
||||||
@@ -110,18 +106,18 @@ func TestLooksLikeMP3(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestDecodeAudioWeiche: RIFF geht an den WAV-Parser, MP3 an den MP3-
|
// TestDecodeAudioSwitch: RIFF goes to the WAV parser, MP3 to the MP3
|
||||||
// Dekoder, alles andere fällt mit dem WAV-Fehler durch.
|
// decoder, everything else falls through with the WAV error.
|
||||||
func TestDecodeAudioWeiche(t *testing.T) {
|
func TestDecodeAudioSwitch(t *testing.T) {
|
||||||
f, _, err := decodeAudio(buildWAV(1, 1, 22050, 16, []byte{1, 2, 3, 4}))
|
f, _, err := decodeAudio(buildWAV(1, 1, 22050, 16, []byte{1, 2, 3, 4}))
|
||||||
if err != nil || f.SampleRate != 22050 {
|
if err != nil || f.SampleRate != 22050 {
|
||||||
t.Errorf("decodeAudio(WAV) = %+v, %v — soll den WAV-Pfad nehmen", f, err)
|
t.Errorf("decodeAudio(WAV) = %+v, %v; should take the WAV path", f, err)
|
||||||
}
|
}
|
||||||
f, _, err = decodeAudio(fixture(t, fixtureMP3MonoB64))
|
f, _, err = decodeAudio(fixture(t, fixtureMP3MonoB64))
|
||||||
if err != nil || f.SampleRate != 24000 {
|
if err != nil || f.SampleRate != 24000 {
|
||||||
t.Errorf("decodeAudio(MP3) = %+v, %v — soll den MP3-Pfad nehmen", f, err)
|
t.Errorf("decodeAudio(MP3) = %+v, %v; should take the MP3 path", f, err)
|
||||||
}
|
}
|
||||||
if _, _, err = decodeAudio([]byte("kein audio")); err == nil || !strings.Contains(err.Error(), "wav:") {
|
if _, _, err = decodeAudio([]byte("not audio")); err == nil || !strings.Contains(err.Error(), "wav:") {
|
||||||
t.Errorf("decodeAudio(Müll) = %v, will WAV-Fehler", err)
|
t.Errorf("decodeAudio(garbage) = %v, want WAV error", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+22
-20
@@ -10,20 +10,18 @@ import (
|
|||||||
"github.com/ebitengine/oto/v3"
|
"github.com/ebitengine/oto/v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
// OtoSink spielt Audio embedded über oto (github.com/ebitengine/oto/v3,
|
// OtoSink plays audio embedded via oto (github.com/ebitengine/oto/v3,
|
||||||
// gepinnt auf v3.5.0) ab — kein externer Player nötig. oto lädt die
|
// pinned to v3.5.0); no external player needed. oto loads the audio drivers
|
||||||
// Audiotreiber zur Laufzeit ohne CGO (purego), dadurch bleibt talk
|
// at runtime without CGO (purego), which keeps talk cross-compilable.
|
||||||
// cross-compilierbar.
|
|
||||||
type OtoSink struct{}
|
type OtoSink struct{}
|
||||||
|
|
||||||
// Name implementiert Sink.
|
// Name implements Sink.
|
||||||
func (OtoSink) Name() string { return NameOto }
|
func (OtoSink) Name() string { return NameOto }
|
||||||
|
|
||||||
// contextCache hält je PCM-Format einen oto-Kontext vor: oto unterstützt
|
// contextCache keeps one oto context per PCM format: oto supports only ONE
|
||||||
// nur EINEN Kontext pro Prozess ("Creating multiple contexts is NOT
|
// context per process ("Creating multiple contexts is NOT supported"), and
|
||||||
// supported"), und ein Kontext ist an genau ein Format gebunden. Die CLI
|
// a context is bound to exactly one format. The CLI plays once per process;
|
||||||
// spielt pro Prozess einmal (Task 02); der Daemon (Task 04) profitiert vom
|
// the daemon benefits from the cache.
|
||||||
// Cache.
|
|
||||||
var contextCache = struct {
|
var contextCache = struct {
|
||||||
sync.Mutex
|
sync.Mutex
|
||||||
byFormat map[pcmFormat]*otoContext
|
byFormat map[pcmFormat]*otoContext
|
||||||
@@ -34,7 +32,7 @@ type otoContext struct {
|
|||||||
ready chan struct{}
|
ready chan struct{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// otoFormat mappt ein PCM-Format auf das oto-Format.
|
// otoFormat maps a PCM format to the oto format.
|
||||||
func (f pcmFormat) otoFormat() oto.Format {
|
func (f pcmFormat) otoFormat() oto.Format {
|
||||||
switch {
|
switch {
|
||||||
case f.Float:
|
case f.Float:
|
||||||
@@ -46,7 +44,7 @@ func (f pcmFormat) otoFormat() oto.Format {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// contextFor liefert den (gecachten) oto-Kontext für ein Format.
|
// contextFor returns the (cached) oto context for a format.
|
||||||
func contextFor(f pcmFormat) (*otoContext, error) {
|
func contextFor(f pcmFormat) (*otoContext, error) {
|
||||||
contextCache.Lock()
|
contextCache.Lock()
|
||||||
defer contextCache.Unlock()
|
defer contextCache.Unlock()
|
||||||
@@ -60,17 +58,16 @@ func contextFor(f pcmFormat) (*otoContext, error) {
|
|||||||
}
|
}
|
||||||
ctx, ready, err := oto.NewContext(op)
|
ctx, ready, err := oto.NewContext(op)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("oto: Kontext (Audio-Gerät?) fehlgeschlagen: %w", err)
|
return nil, fmt.Errorf("oto: creating context failed (no audio device?): %w", err)
|
||||||
}
|
}
|
||||||
c := &otoContext{ctx: ctx, ready: ready}
|
c := &otoContext{ctx: ctx, ready: ready}
|
||||||
contextCache.byFormat[f] = c
|
contextCache.byFormat[f] = c
|
||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Play implementiert Sink: dekodiert die Daten (RIFF/WAVE-PCM von osbuiltin
|
// Play implements Sink: decodes the data (RIFF/WAVE PCM from osbuiltin or
|
||||||
// oder MP3 von den Cloud-Providern, siehe mp3.go) und spielt die Samples
|
// MP3 from the cloud providers, see mp3.go) and plays the samples, blocking.
|
||||||
// blockierend ab. Fehler des Audio-Geräts oder des Formats werden klar
|
// Audio device and format errors are reported clearly.
|
||||||
// gemeldet.
|
|
||||||
func (OtoSink) Play(ctx context.Context, data []byte) error {
|
func (OtoSink) Play(ctx context.Context, data []byte) error {
|
||||||
f, pcm, err := decodeAudio(data)
|
f, pcm, err := decodeAudio(data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -83,7 +80,7 @@ func (OtoSink) Play(ctx context.Context, data []byte) error {
|
|||||||
select {
|
select {
|
||||||
case <-c.ready:
|
case <-c.ready:
|
||||||
if err := c.ctx.Err(); err != nil {
|
if err := c.ctx.Err(); err != nil {
|
||||||
return fmt.Errorf("oto: Initialisierung fehlgeschlagen: %w", err)
|
return fmt.Errorf("oto: initialization failed: %w", err)
|
||||||
}
|
}
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
return ctx.Err()
|
return ctx.Err()
|
||||||
@@ -94,11 +91,16 @@ func (OtoSink) Play(ctx context.Context, data []byte) error {
|
|||||||
player.Play()
|
player.Play()
|
||||||
for player.IsPlaying() {
|
for player.IsPlaying() {
|
||||||
if err := ctx.Err(); err != nil {
|
if err := ctx.Err(); err != nil {
|
||||||
player.Close()
|
// Cancel: stop the sound NOW. oto's Close is a no-op that
|
||||||
|
// relies on the garbage collector's finalizer, so a cancelled
|
||||||
|
// announcement would play on to its end; Pause takes the
|
||||||
|
// player out of the mix immediately (only the device buffer,
|
||||||
|
// about 100 ms, drains).
|
||||||
|
player.Pause()
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if err := player.Err(); err != nil {
|
if err := player.Err(); err != nil {
|
||||||
return fmt.Errorf("oto: Wiedergabe fehlgeschlagen: %w", err)
|
return fmt.Errorf("oto: playback failed: %w", err)
|
||||||
}
|
}
|
||||||
time.Sleep(5 * time.Millisecond)
|
time.Sleep(5 * time.Millisecond)
|
||||||
}
|
}
|
||||||
|
|||||||
+17
-18
@@ -5,28 +5,27 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
// pcmFormat beschreibt rohe PCM-Samples, wie sie oto zur Wiedergabe
|
// pcmFormat describes raw PCM samples as oto needs them for playback.
|
||||||
// braucht.
|
|
||||||
type pcmFormat struct {
|
type pcmFormat struct {
|
||||||
SampleRate int
|
SampleRate int
|
||||||
Channels int
|
Channels int
|
||||||
BitsPerCoded int // 8 (unsigned), 16 (signed LE), 32 (nur IEEE float)
|
BitsPerCoded int // 8 (unsigned), 16 (signed LE), 32 (IEEE float only)
|
||||||
Float bool
|
Float bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// decodeWAV zerlegt RIFF/WAVE-Bytes in Format und PCM-Daten.
|
// decodeWAV splits RIFF/WAVE bytes into format and PCM data.
|
||||||
//
|
//
|
||||||
// Unterstützt: PCM (AudioFormat 1) mit 8/16 Bit sowie IEEE-Float
|
// Supported: PCM (AudioFormat 1) with 8/16 bit and IEEE float (AudioFormat
|
||||||
// (AudioFormat 3) mit 32 Bit; Mono und Stereo. Alles andere — erst recht
|
// 3) with 32 bit; mono and stereo. Everything else, compressed formats in
|
||||||
// komprimierte Formate — ist ein klarer Fehler; die OS-TTS-Wege von
|
// particular, is a clear error; the OS TTS paths of osbuiltin deliver
|
||||||
// osbuiltin liefern ausschließlich 16-Bit-PCM-WAV.
|
// 16-bit PCM WAV exclusively.
|
||||||
func decodeWAV(data []byte) (pcmFormat, []byte, error) {
|
func decodeWAV(data []byte) (pcmFormat, []byte, error) {
|
||||||
var f pcmFormat
|
var f pcmFormat
|
||||||
if len(data) < 12 {
|
if len(data) < 12 {
|
||||||
return f, nil, fmt.Errorf("wav: zu kurz für RIFF-Header (%d Bytes)", len(data))
|
return f, nil, fmt.Errorf("wav: too short for a RIFF header (%d bytes)", len(data))
|
||||||
}
|
}
|
||||||
if string(data[0:4]) != "RIFF" || string(data[8:12]) != "WAVE" {
|
if string(data[0:4]) != "RIFF" || string(data[8:12]) != "WAVE" {
|
||||||
return f, nil, fmt.Errorf("wav: kein RIFF/WAVE-Header")
|
return f, nil, fmt.Errorf("wav: no RIFF/WAVE header")
|
||||||
}
|
}
|
||||||
|
|
||||||
var haveFmt bool
|
var haveFmt bool
|
||||||
@@ -37,12 +36,12 @@ func decodeWAV(data []byte) (pcmFormat, []byte, error) {
|
|||||||
size := int(binary.LittleEndian.Uint32(data[pos+4 : pos+8]))
|
size := int(binary.LittleEndian.Uint32(data[pos+4 : pos+8]))
|
||||||
body := pos + 8
|
body := pos + 8
|
||||||
if body+size > len(data) {
|
if body+size > len(data) {
|
||||||
return f, nil, fmt.Errorf("wav: Chunk %q überragt die Datei (Size %d)", id, size)
|
return f, nil, fmt.Errorf("wav: chunk %q exceeds the data (size %d)", id, size)
|
||||||
}
|
}
|
||||||
switch id {
|
switch id {
|
||||||
case "fmt ":
|
case "fmt ":
|
||||||
if size < 16 {
|
if size < 16 {
|
||||||
return f, nil, fmt.Errorf("wav: fmt-Chunk zu kurz (%d)", size)
|
return f, nil, fmt.Errorf("wav: fmt chunk too short (%d)", size)
|
||||||
}
|
}
|
||||||
audioFormat := binary.LittleEndian.Uint16(data[body : body+2])
|
audioFormat := binary.LittleEndian.Uint16(data[body : body+2])
|
||||||
f.Channels = int(binary.LittleEndian.Uint16(data[body+2 : body+4]))
|
f.Channels = int(binary.LittleEndian.Uint16(data[body+2 : body+4]))
|
||||||
@@ -53,29 +52,29 @@ func decodeWAV(data []byte) (pcmFormat, []byte, error) {
|
|||||||
case audioFormat == 3 && f.BitsPerCoded == 32:
|
case audioFormat == 3 && f.BitsPerCoded == 32:
|
||||||
f.Float = true
|
f.Float = true
|
||||||
default:
|
default:
|
||||||
return f, nil, fmt.Errorf("wav: nicht unterstütztes Format (AudioFormat %d, %d Bit) — erlaubt: PCM 8/16 Bit, Float 32 Bit",
|
return f, nil, fmt.Errorf("wav: unsupported format (AudioFormat %d, %d bit); allowed: PCM 8/16 bit, float 32 bit",
|
||||||
audioFormat, f.BitsPerCoded)
|
audioFormat, f.BitsPerCoded)
|
||||||
}
|
}
|
||||||
if f.Channels < 1 || f.Channels > 2 {
|
if f.Channels < 1 || f.Channels > 2 {
|
||||||
return f, nil, fmt.Errorf("wav: %d Kanäle (erlaubt: 1, 2)", f.Channels)
|
return f, nil, fmt.Errorf("wav: %d channels (allowed: 1, 2)", f.Channels)
|
||||||
}
|
}
|
||||||
if f.SampleRate <= 0 {
|
if f.SampleRate <= 0 {
|
||||||
return f, nil, fmt.Errorf("wav: SampleRate %d", f.SampleRate)
|
return f, nil, fmt.Errorf("wav: sample rate %d", f.SampleRate)
|
||||||
}
|
}
|
||||||
haveFmt = true
|
haveFmt = true
|
||||||
case "data":
|
case "data":
|
||||||
payload = data[body : body+size]
|
payload = data[body : body+size]
|
||||||
}
|
}
|
||||||
pos = body + size
|
pos = body + size
|
||||||
if size%2 == 1 { // Chunks sind word-aligned
|
if size%2 == 1 { // chunks are word-aligned
|
||||||
pos++
|
pos++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !haveFmt {
|
if !haveFmt {
|
||||||
return f, nil, fmt.Errorf("wav: kein fmt-Chunk")
|
return f, nil, fmt.Errorf("wav: no fmt chunk")
|
||||||
}
|
}
|
||||||
if payload == nil {
|
if payload == nil {
|
||||||
return f, nil, fmt.Errorf("wav: kein data-Chunk")
|
return f, nil, fmt.Errorf("wav: no data chunk")
|
||||||
}
|
}
|
||||||
return f, payload, nil
|
return f, payload, nil
|
||||||
}
|
}
|
||||||
+195
-117
@@ -5,6 +5,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -14,183 +15,199 @@ import (
|
|||||||
"code.m3ta.dev/m3tam3re/talk/internal/queue"
|
"code.m3ta.dev/m3tam3re/talk/internal/queue"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Erlaubte Werte für audio.sink (Teil des öffentlichen Vertrags; Spec:
|
// Allowed values for audio.sink (public contract).
|
||||||
// „Audio-Sink wählbar inkl. null").
|
|
||||||
const (
|
const (
|
||||||
SinkOto = "oto"
|
SinkOto = "oto"
|
||||||
SinkNull = "null"
|
SinkNull = "null"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DefaultServerPort ist der Default-Port des Daemon-HTTP-Servers auf
|
// DefaultServerPort is the daemon's default HTTP port on 127.0.0.1.
|
||||||
// 127.0.0.1 (Task-04-Brief: „Port Default 7800").
|
|
||||||
const DefaultServerPort = 7800
|
const DefaultServerPort = 7800
|
||||||
|
|
||||||
// DefaultRateLimit ist das Daemon-Gesetz gegen Spam (Task-05-Brief):
|
// DefaultRateLimit is the anti-spam law's default: one announcement per
|
||||||
// Default 1 Ansage / 30 s. „0s" schaltet das Limit ab.
|
// 30 seconds. "0s" disables the limit.
|
||||||
const DefaultRateLimit = 30 * time.Second
|
const DefaultRateLimit = 30 * time.Second
|
||||||
|
|
||||||
// DefaultMaxText ist die Default-Obergrenze der Ansage-Länge in Zeichen —
|
// DefaultMaxText is the default cap on announcement length in characters:
|
||||||
// etwa zwei bis drei Sätze, rund 25 Sekunden Sprache. 0 = unbegrenzt.
|
// two to three sentences, roughly 25 seconds of speech. 0 = unlimited.
|
||||||
const DefaultMaxText = 400
|
const DefaultMaxText = 400
|
||||||
|
|
||||||
// DefaultMaxAge ist die Default-Höchstwartezeit einer Ansage in der Queue;
|
// DefaultMaxAge is the default longest wait in the queue; whatever parks
|
||||||
// was länger parkt, ist veraltet und wird verworfen. „0s" = unbegrenzt.
|
// longer is stale and gets discarded. "0s" = unlimited.
|
||||||
const DefaultMaxAge = 2 * time.Minute
|
const DefaultMaxAge = 2 * time.Minute
|
||||||
|
|
||||||
// Config ist der effektiv geladene Konfigurations-Stand von talk. Task 02
|
// DefaultLang is the language assumed when detection cannot decide (empty,
|
||||||
// führt audio.sink; Task 03 ergänzt den Provider-Pin, Provider-Endpunkte
|
// numbers, ties). Also the language of talk's own announcements such as the
|
||||||
// und das Voice-Mapping; Task 04 den Daemon-Port (server.port, TALK_PORT);
|
// wrap result when the label gives no hint.
|
||||||
// Task 05 die Anti-Spam-Gesetze (queue.rate_limit, queue.allow_high_burst,
|
const DefaultLang = "en"
|
||||||
// quiet_hours, quiet_mode); spätere Tasks ergänzen weitere Felder, ohne die
|
|
||||||
// Auflösungs-Reihenfolge zu ändern.
|
// Config is the effective configuration after all layers were applied.
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Audio Audio `toml:"audio"`
|
Audio Audio `toml:"audio"`
|
||||||
|
|
||||||
// Server steuert den Daemon-HTTP-Server (talkd) auf 127.0.0.1.
|
// Server configures the daemon's HTTP server on 127.0.0.1.
|
||||||
Server Server `toml:"server"`
|
Server Server `toml:"server"`
|
||||||
|
|
||||||
// Queue steuert die Anti-Spam-Gesetze des Daemons (Task 05).
|
// Queue holds the daemon's anti-spam laws.
|
||||||
Queue Queue `toml:"queue"`
|
Queue Queue `toml:"queue"`
|
||||||
|
|
||||||
// Daemon steuert den Hintergrundprozess (Autostart).
|
// Daemon configures the background process (autostart).
|
||||||
Daemon Daemon `toml:"daemon"`
|
Daemon Daemon `toml:"daemon"`
|
||||||
|
|
||||||
// Provider pinnt die Kette auf genau einen Provider (z. B.
|
// Notify configures desktop notifications.
|
||||||
// `provider = "elevenlabs"`); leer = komplette Default-Kette
|
Notify Notify `toml:"notify"`
|
||||||
// (elevenlabs → openai → edge → osbuiltin). Das CLI-Flag --provider
|
|
||||||
// schlägt diesen Wert. Gültige Namen prüft die Provider-Schicht.
|
// Lang is the fallback language (de | en) when detection cannot decide,
|
||||||
|
// and the language of talk's own announcements. Default "en"; env
|
||||||
|
// TALK_LANG.
|
||||||
|
Lang string `toml:"lang"`
|
||||||
|
|
||||||
|
// Provider pins the chain to exactly one provider (for example
|
||||||
|
// `provider = "elevenlabs"`); empty = the full default chain
|
||||||
|
// (elevenlabs → openai → edge → osbuiltin). The --provider flag beats
|
||||||
|
// this value. Valid names are checked by the provider layer.
|
||||||
Provider string `toml:"provider"`
|
Provider string `toml:"provider"`
|
||||||
|
|
||||||
// Providers enthält per Provider-Einstellungen (Endpunkt, Modell) —
|
// Providers holds per-provider settings (endpoint, model):
|
||||||
// TOML `[providers.elevenlabs] endpoint = "…"`. Key `providers`
|
// `[providers.elevenlabs] endpoint = "…"`. The key is plural so the pin
|
||||||
// (Mehrzahl), damit der Pin ( singular `provider`) und die
|
// (`provider`) and the settings table can coexist in TOML.
|
||||||
// Einstellungs-Tabelle in TOML nebeneinander existieren können.
|
|
||||||
Providers map[string]ProviderSettings `toml:"providers"`
|
Providers map[string]ProviderSettings `toml:"providers"`
|
||||||
|
|
||||||
// Voice ist das Voice-Mapping `voice.<provider>.<lang> = id` — z. B.
|
// Voice is the voice mapping `voice.<provider>.<lang> = id`, for example
|
||||||
// `[voice.elevenlabs] de = "21m00Tcm4TlvDq8ikWAM"`. Schlägt die
|
// `[voice.elevenlabs] de = "21m00Tcm4TlvDq8ikWAM"`. It beats the built-in
|
||||||
// eingebauten neutralen Defaults; das CLI-Flag --voice schlägt alles.
|
// neutral defaults; the --voice flag beats everything.
|
||||||
Voice map[string]map[string]string `toml:"voice"`
|
Voice map[string]map[string]string `toml:"voice"`
|
||||||
|
|
||||||
// Wrap steuert die Befehlsummwicklung `talk wrap` (Task 07).
|
// Wrap configures `talk wrap`.
|
||||||
Wrap Wrap `toml:"wrap"`
|
Wrap Wrap `toml:"wrap"`
|
||||||
|
|
||||||
// QuietHours ist das Ruhezeit-Fenster "HH:MM-HH:MM" in lokaler Zeit
|
// QuietHours is the quiet window "HH:MM-HH:MM" in local time (may span
|
||||||
// (überspannt Mitternacht, z. B. "18:00-08:00"); leer = deaktiviert.
|
// midnight, for example "18:00-08:00"); empty = disabled. Deliberately
|
||||||
// Bewusst kein Default-Fenster: Ein aktives Gesetz, das nach Uhrzeit
|
// no default window: a law that discards by time of day would silence
|
||||||
// verwirft, würde jeden Cron/Test in den Abendstunden stilllegen —
|
// every evening cron job; quiet hours are opt-in like mute.
|
||||||
// Ruhezeiten sind Opt-in wie Mute.
|
|
||||||
QuietHours string `toml:"quiet_hours"`
|
QuietHours string `toml:"quiet_hours"`
|
||||||
|
|
||||||
// QuietMode bestimmt das Verhalten in der Ruhezeit: "discard" (Default,
|
// QuietMode is the behaviour during quiet hours: "discard" (default,
|
||||||
// still verwerfen) oder "toast" (Benachrichtigung statt Audio).
|
// drop silently) or "toast" (desktop notification instead of audio).
|
||||||
QuietMode string `toml:"quiet_mode"`
|
QuietMode string `toml:"quiet_mode"`
|
||||||
|
|
||||||
|
// Unknown lists keys in config.toml that talk does not know (dotted,
|
||||||
|
// for example "voice.lang"). Not an error, because an older talk must
|
||||||
|
// still read a newer file, but `talk doctor` reports them: the classic
|
||||||
|
// trap is a top-level key written below a [table] header, which TOML
|
||||||
|
// then files under that table.
|
||||||
|
Unknown []string `toml:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Audio steuert die Audio-Ausgabe.
|
// Audio configures playback.
|
||||||
type Audio struct {
|
type Audio struct {
|
||||||
// Sink wählt die Wiedergabe: "oto" (embedded Playback, Default) oder
|
// Sink selects playback: "oto" (embedded playback, default) or "null"
|
||||||
// "null" (verwirft — CI, Server, Tests).
|
// (discard; CI, servers, tests).
|
||||||
Sink string `toml:"sink"`
|
Sink string `toml:"sink"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Server sind die Netz-Einstellungen des Daemons (nur Loopback; Binding
|
// Server holds the daemon's network settings (loopback only; the daemon
|
||||||
// auf 127.0.0.1 macht cmd/talkd, die Config liefert nur den Port).
|
// binds 127.0.0.1, the config only supplies the port).
|
||||||
type Server struct {
|
type Server struct {
|
||||||
// Port des Daemon-HTTP-Servers auf 127.0.0.1 — config
|
// Port of the daemon's HTTP server on 127.0.0.1: `[server] port = 7800`,
|
||||||
// `[server] port = 7800`, Env-Override TALK_PORT, Default 7800.
|
// env override TALK_PORT, default 7800.
|
||||||
Port int `toml:"port"`
|
Port int `toml:"port"`
|
||||||
|
|
||||||
// AllowedOrigins ist die CORS-Erlaubnisliste für POST /speak (Task 06):
|
// AllowedOrigins is the CORS allow-list for POST /speak: exact origins
|
||||||
// exakte Origins wie "https://chat.az-gruppe.com". Der Eintrag "*"
|
// such as "https://chat.example.com". The entry "*" allows every origin
|
||||||
// erlaubt jede Origin ausdrücklich. Bewusster Default: LEER — ohne
|
// explicitly. Deliberate default: EMPTY, meaning no CORS headers at all
|
||||||
// Einträge sendet der Daemon gar keine CORS-Header und der Browser
|
// and the server-side origin guard rejects browser requests; the door
|
||||||
// blockt Cross-Origin-Anfragen; die Tür ist zu, bis sie konfiguriert
|
// stays shut until configured (env TALK_ALLOWED_ORIGINS, comma-separated;
|
||||||
// wird (Env-Override TALK_ALLOWED_ORIGINS, kommagetrennt; "off" leert).
|
// "off" clears it).
|
||||||
AllowedOrigins []string `toml:"allowed_origins"`
|
AllowedOrigins []string `toml:"allowed_origins"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Daemon sind die Einstellungen des Hintergrundprozesses (TOML `[daemon]`).
|
// Daemon holds the background process settings (TOML `[daemon]`).
|
||||||
type Daemon struct {
|
type Daemon struct {
|
||||||
// Autostart lässt talk den Daemon beim ersten Sprechbefehl selbst im
|
// Autostart lets talk start the daemon itself in the background on the
|
||||||
// Hintergrund starten (Default true; Env TALK_AUTOSTART). false ist für
|
// first speak command (default true; env TALK_AUTOSTART). false is for
|
||||||
// Setups, die den Daemon selbst verwalten (systemd, launchd, Task
|
// setups that manage the daemon themselves (systemd, launchd, Task
|
||||||
// Scheduler): say spricht dann ohne Daemon direkt, mit Hinweis.
|
// Scheduler): without a daemon, say then speaks directly, with a note.
|
||||||
Autostart bool `toml:"autostart"`
|
Autostart bool `toml:"autostart"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wrap sind die Einstellungen von `talk wrap` (TOML `[wrap]`).
|
// Notify holds the desktop notification settings (TOML `[notify]`).
|
||||||
|
type Notify struct {
|
||||||
|
// OnSpeak shows a desktop notification for every announcement that is
|
||||||
|
// playing, with a Cancel button where the platform supports it (Linux
|
||||||
|
// with a freedesktop notification service), so a long announcement can
|
||||||
|
// be stopped without a terminal. Default true; env TALK_NOTIFY.
|
||||||
|
OnSpeak bool `toml:"on_speak"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wrap holds the `talk wrap` settings (TOML `[wrap]`).
|
||||||
type Wrap struct {
|
type Wrap struct {
|
||||||
// Label ersetzt den Basisnamen des Befehls in der Ansage — z. B.
|
// Label replaces the command's base name in the announcement, for
|
||||||
// `label = "Deployment"` für „Deployment erfolgreich. Dauer: …"
|
// example `label = "Deployment"` to hear "Deployment succeeded" instead
|
||||||
// statt „terraform erfolgreich. Dauer: …" (Env-Override
|
// of "terraform succeeded" (env override TALK_WRAP_LABEL).
|
||||||
// TALK_WRAP_LABEL schlägt die Datei).
|
|
||||||
Label string `toml:"label"`
|
Label string `toml:"label"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Queue sind die Rate-Limit-Gesetze des Daemons (TOML `[queue]`).
|
// Queue holds the daemon's anti-spam laws (TOML `[queue]`).
|
||||||
type Queue struct {
|
type Queue struct {
|
||||||
// RateLimit ist der Mindestabstand zwischen zwei Ansage-Starten als
|
// RateLimit is the minimum gap between two announcement starts, as a
|
||||||
// Dauer-String (z. B. "30s"; "0s" = unbegrenzt). Default: 30 s.
|
// duration string ("30s"; "0s" = unlimited). Default 30 s.
|
||||||
RateLimit time.Duration `toml:"rate_limit"`
|
RateLimit time.Duration `toml:"rate_limit"`
|
||||||
|
|
||||||
// AllowHighBurst erlaubt priority=high, das Rate-Limit bewusst zu
|
// AllowHighBurst lets priority=high deliberately break the rate limit
|
||||||
// verstoßen (Default true). Die Ruhezeit gilt davon unberührt.
|
// (default true). Quiet hours still apply.
|
||||||
AllowHighBurst bool `toml:"allow_high_burst"`
|
AllowHighBurst bool `toml:"allow_high_burst"`
|
||||||
|
|
||||||
// MaxText ist die Obergrenze der Ansage-Länge in Zeichen; längere
|
// MaxText caps announcement length in characters; longer texts are cut
|
||||||
// Texte werden an einer Wortgrenze gekürzt (Default 400; 0 =
|
// at a word boundary (default 400; 0 = unlimited; env TALK_MAX_TEXT).
|
||||||
// unbegrenzt; Env TALK_MAX_TEXT).
|
|
||||||
MaxText int `toml:"max_text"`
|
MaxText int `toml:"max_text"`
|
||||||
|
|
||||||
// MaxAge ist die längste Wartezeit einer Ansage in der Queue; ältere
|
// MaxAge is the longest an announcement may wait in the queue; older
|
||||||
// werden beim Fälligwerden verworfen (Default "2m"; "0s" = unbegrenzt;
|
// ones are discarded when they come due (default "2m"; "0s" =
|
||||||
// Env TALK_MAX_AGE).
|
// unlimited; env TALK_MAX_AGE).
|
||||||
MaxAge time.Duration `toml:"max_age"`
|
MaxAge time.Duration `toml:"max_age"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProviderSettings sind die per Provider konfigurierbaren Endpunkte und
|
// ProviderSettings are the per-provider endpoint and model (TOML
|
||||||
// Modelle (TOML `[providers.<name>]`). Leer = eingebaute Defaults; die
|
// `[providers.<name>]`). Empty = built-in defaults; the env overrides
|
||||||
// Env-Overrides TALK_ELEVENLABS_ENDPOINT / TALK_OPENAI_ENDPOINT /
|
// TALK_ELEVENLABS_ENDPOINT / TALK_OPENAI_ENDPOINT / TALK_EDGE_ENDPOINT
|
||||||
// TALK_EDGE_ENDPOINT (ausgewertet in der Provider-Schicht) schlagen die
|
// (read by the provider layer) beat the file. Keys come exclusively from
|
||||||
// Datei — Keys laufen ausschließlich über TALK_ELEVENLABS_KEY bzw.
|
// TALK_ELEVENLABS_KEY / TALK_OPENAI_KEY and are never written to the file.
|
||||||
// TALK_OPENAI_KEY und werden nie in die Datei geschrieben.
|
|
||||||
type ProviderSettings struct {
|
type ProviderSettings struct {
|
||||||
Endpoint string `toml:"endpoint"`
|
Endpoint string `toml:"endpoint"`
|
||||||
Model string `toml:"model"` // nur openai (Default "tts-1")
|
Model string `toml:"model"` // openai only (default "tts-1")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Defaults liefert die eingebaute Default-Konfiguration (unterste Schicht
|
// Defaults returns the built-in default configuration (the lowest layer).
|
||||||
// der Auflösung).
|
|
||||||
func Defaults() Config {
|
func Defaults() Config {
|
||||||
return Config{
|
return Config{
|
||||||
Audio: Audio{Sink: SinkOto},
|
Audio: Audio{Sink: SinkOto},
|
||||||
Server: Server{Port: DefaultServerPort},
|
Server: Server{Port: DefaultServerPort},
|
||||||
Queue: Queue{RateLimit: DefaultRateLimit, AllowHighBurst: true, MaxText: DefaultMaxText, MaxAge: DefaultMaxAge},
|
Queue: Queue{RateLimit: DefaultRateLimit, AllowHighBurst: true, MaxText: DefaultMaxText, MaxAge: DefaultMaxAge},
|
||||||
Daemon: Daemon{Autostart: true},
|
Daemon: Daemon{Autostart: true},
|
||||||
|
Notify: Notify{OnSpeak: true},
|
||||||
|
Lang: DefaultLang,
|
||||||
QuietMode: queue.QuietModeDiscard,
|
QuietMode: queue.QuietModeDiscard,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Options steuert Load. Alle Felder sind injizierbar, damit die Unit-Tests
|
// Options controls Load. Every field is injectable so unit tests run without
|
||||||
// ohne echte HOME-/Env-Umgebung und ohne echte Dateien auskommen.
|
// a real HOME, environment or files.
|
||||||
type Options struct {
|
type Options struct {
|
||||||
// File überschreibt den platform-nativen Pfad der config.toml (Tests
|
// File overrides the platform-native path of config.toml (tests inject
|
||||||
// injizieren hier eine Temp-Datei). Leer: Dir() + "config.toml".
|
// a temp file). Empty: Dir() + "config.toml".
|
||||||
File string
|
File string
|
||||||
|
|
||||||
// Getenv liefert Umgebungsvariablen (Default: os.Getenv). Über TALK_*
|
// Getenv supplies environment variables (default os.Getenv): the TALK_*
|
||||||
// laufen die Env-Overrides sowie die Pfadauflösung (HOME,
|
// overrides and the path resolution (HOME, XDG_CONFIG_HOME, APPDATA).
|
||||||
// XDG_CONFIG_HOME, APPDATA).
|
|
||||||
Getenv func(string) string
|
Getenv func(string) string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load löst die Konfiguration schichtweise auf: Defaults → config.toml
|
// Load resolves the configuration in layers: defaults → config.toml (if
|
||||||
// (falls vorhanden) → Env-Overrides (TALK_* schlägt die Datei). Env- und
|
// present) → env overrides (TALK_* beats the file). Env and file validation
|
||||||
// Datei-Validierungsfehler werden als klarer Fehler gemeldet, nie still
|
// errors are reported clearly, never ignored. If the config directory
|
||||||
// ignoriert. Fehlt das Config-Verzeichnis (z. B. keine HOME-Variable),
|
// cannot be determined (no HOME), talk runs with defaults + env: the file is
|
||||||
// läuft talk mit Defaults + Env weiter — die Datei ist optional, kaputte
|
// optional, a broken environment must not make talk unusable.
|
||||||
// Umgebungen dürfen talk nicht unbrauchbar machen.
|
|
||||||
func Load(opts Options) (Config, error) {
|
func Load(opts Options) (Config, error) {
|
||||||
if opts.Getenv == nil {
|
if opts.Getenv == nil {
|
||||||
opts.Getenv = os.Getenv
|
opts.Getenv = os.Getenv
|
||||||
@@ -201,21 +218,39 @@ func Load(opts Options) (Config, error) {
|
|||||||
if path == "" {
|
if path == "" {
|
||||||
dir, err := Dir(opts.Getenv)
|
dir, err := Dir(opts.Getenv)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// Kein auffindbares Config-Verzeichnis: optionale Datei entfällt.
|
|
||||||
return applyEnv(cfg, opts.Getenv)
|
return applyEnv(cfg, opts.Getenv)
|
||||||
}
|
}
|
||||||
path = filepath.Join(dir, fileName)
|
path = filepath.Join(dir, fileName)
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := toml.DecodeFile(path, &cfg); err != nil {
|
md, err := toml.DecodeFile(path, &cfg)
|
||||||
|
if err != nil {
|
||||||
if !errors.Is(err, os.ErrNotExist) {
|
if !errors.Is(err, os.ErrNotExist) {
|
||||||
return cfg, fmt.Errorf("config %s: %w", path, err)
|
return cfg, fmt.Errorf("config %s: %w", path, err)
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
// The decoder lists an unknown table and its keys; keep the keys,
|
||||||
|
// which say more than the table.
|
||||||
|
undecoded := md.Undecoded()
|
||||||
|
for i, key := range undecoded {
|
||||||
|
prefix := key.String() + "."
|
||||||
|
isTable := false
|
||||||
|
for j, other := range undecoded {
|
||||||
|
if i != j && strings.HasPrefix(other.String(), prefix) {
|
||||||
|
isTable = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !isTable {
|
||||||
|
cfg.Unknown = append(cfg.Unknown, key.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cfg.Unknown = append(cfg.Unknown, strayVoiceKeys(cfg.Voice)...)
|
||||||
}
|
}
|
||||||
return applyEnv(cfg, opts.Getenv)
|
return applyEnv(cfg, opts.Getenv)
|
||||||
}
|
}
|
||||||
|
|
||||||
// applyEnv wendet die Env-Overrides an und validiert das Ergebnis.
|
// applyEnv applies the env overrides and validates the result.
|
||||||
func applyEnv(cfg Config, getenv func(string) string) (Config, error) {
|
func applyEnv(cfg Config, getenv func(string) string) (Config, error) {
|
||||||
if v := getenv("TALK_AUDIO_SINK"); v != "" {
|
if v := getenv("TALK_AUDIO_SINK"); v != "" {
|
||||||
cfg.Audio.Sink = v
|
cfg.Audio.Sink = v
|
||||||
@@ -223,10 +258,13 @@ func applyEnv(cfg Config, getenv func(string) string) (Config, error) {
|
|||||||
if v := getenv("TALK_PROVIDER"); v != "" {
|
if v := getenv("TALK_PROVIDER"); v != "" {
|
||||||
cfg.Provider = v
|
cfg.Provider = v
|
||||||
}
|
}
|
||||||
|
if v := getenv("TALK_LANG"); v != "" {
|
||||||
|
cfg.Lang = v
|
||||||
|
}
|
||||||
if v := getenv("TALK_PORT"); v != "" {
|
if v := getenv("TALK_PORT"); v != "" {
|
||||||
port, err := strconv.Atoi(v)
|
port, err := strconv.Atoi(v)
|
||||||
if err != nil || port < 1 || port > 65535 {
|
if err != nil || port < 1 || port > 65535 {
|
||||||
return cfg, fmt.Errorf("TALK_PORT: ungültiger Wert %q (1–65535)", v)
|
return cfg, fmt.Errorf("TALK_PORT: invalid value %q (1–65535)", v)
|
||||||
}
|
}
|
||||||
cfg.Server.Port = port
|
cfg.Server.Port = port
|
||||||
}
|
}
|
||||||
@@ -244,38 +282,45 @@ func applyEnv(cfg Config, getenv func(string) string) (Config, error) {
|
|||||||
if v := getenv("TALK_MAX_TEXT"); v != "" {
|
if v := getenv("TALK_MAX_TEXT"); v != "" {
|
||||||
n, err := strconv.Atoi(v)
|
n, err := strconv.Atoi(v)
|
||||||
if err != nil || n < 0 {
|
if err != nil || n < 0 {
|
||||||
return cfg, fmt.Errorf("TALK_MAX_TEXT: ungültiger Wert %q (Zeichen; 0 = unbegrenzt)", v)
|
return cfg, fmt.Errorf("TALK_MAX_TEXT: invalid value %q (characters; 0 = unlimited)", v)
|
||||||
}
|
}
|
||||||
cfg.Queue.MaxText = n
|
cfg.Queue.MaxText = n
|
||||||
}
|
}
|
||||||
if v := getenv("TALK_MAX_AGE"); v != "" {
|
if v := getenv("TALK_MAX_AGE"); v != "" {
|
||||||
d, err := time.ParseDuration(v)
|
d, err := time.ParseDuration(v)
|
||||||
if err != nil || d < 0 {
|
if err != nil || d < 0 {
|
||||||
return cfg, fmt.Errorf("TALK_MAX_AGE: ungültiger Wert %q (Dauer, z. B. \"2m\"; \"0s\" = unbegrenzt)", v)
|
return cfg, fmt.Errorf("TALK_MAX_AGE: invalid value %q (duration such as \"2m\"; \"0s\" = unlimited)", v)
|
||||||
}
|
}
|
||||||
cfg.Queue.MaxAge = d
|
cfg.Queue.MaxAge = d
|
||||||
}
|
}
|
||||||
if v := getenv("TALK_AUTOSTART"); v != "" {
|
if v := getenv("TALK_AUTOSTART"); v != "" {
|
||||||
b, err := strconv.ParseBool(v)
|
b, err := strconv.ParseBool(v)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cfg, fmt.Errorf("TALK_AUTOSTART: ungültiger Wert %q (true/false)", v)
|
return cfg, fmt.Errorf("TALK_AUTOSTART: invalid value %q (true/false)", v)
|
||||||
}
|
}
|
||||||
cfg.Daemon.Autostart = b
|
cfg.Daemon.Autostart = b
|
||||||
}
|
}
|
||||||
|
if v := getenv("TALK_NOTIFY"); v != "" {
|
||||||
|
b, err := strconv.ParseBool(v)
|
||||||
|
if err != nil {
|
||||||
|
return cfg, fmt.Errorf("TALK_NOTIFY: invalid value %q (true/false)", v)
|
||||||
|
}
|
||||||
|
cfg.Notify.OnSpeak = b
|
||||||
|
}
|
||||||
if v := getenv("TALK_WRAP_LABEL"); v != "" {
|
if v := getenv("TALK_WRAP_LABEL"); v != "" {
|
||||||
cfg.Wrap.Label = v
|
cfg.Wrap.Label = v
|
||||||
}
|
}
|
||||||
if v := getenv("TALK_RATE_LIMIT"); v != "" {
|
if v := getenv("TALK_RATE_LIMIT"); v != "" {
|
||||||
d, err := time.ParseDuration(v)
|
d, err := time.ParseDuration(v)
|
||||||
if err != nil || d < 0 {
|
if err != nil || d < 0 {
|
||||||
return cfg, fmt.Errorf("TALK_RATE_LIMIT: ungültiger Wert %q (Dauer, z. B. \"30s\"; \"0s\" = unbegrenzt)", v)
|
return cfg, fmt.Errorf("TALK_RATE_LIMIT: invalid value %q (duration such as \"30s\"; \"0s\" = unlimited)", v)
|
||||||
}
|
}
|
||||||
cfg.Queue.RateLimit = d
|
cfg.Queue.RateLimit = d
|
||||||
}
|
}
|
||||||
if v := getenv("TALK_ALLOW_HIGH_BURST"); v != "" {
|
if v := getenv("TALK_ALLOW_HIGH_BURST"); v != "" {
|
||||||
b, err := strconv.ParseBool(v)
|
b, err := strconv.ParseBool(v)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cfg, fmt.Errorf("TALK_ALLOW_HIGH_BURST: ungültiger Wert %q (true/false)", v)
|
return cfg, fmt.Errorf("TALK_ALLOW_HIGH_BURST: invalid value %q (true/false)", v)
|
||||||
}
|
}
|
||||||
cfg.Queue.AllowHighBurst = b
|
cfg.Queue.AllowHighBurst = b
|
||||||
}
|
}
|
||||||
@@ -284,37 +329,39 @@ func applyEnv(cfg Config, getenv func(string) string) (Config, error) {
|
|||||||
cfg.QuietHours = ""
|
cfg.QuietHours = ""
|
||||||
} else {
|
} else {
|
||||||
if _, err := queue.ParseQuietHours(v); err != nil {
|
if _, err := queue.ParseQuietHours(v); err != nil {
|
||||||
return cfg, fmt.Errorf("TALK_QUIET_HOURS: ungültiges Fenster %q (HH:MM-HH:MM, \"off\" = deaktiviert)", v)
|
return cfg, fmt.Errorf("TALK_QUIET_HOURS: invalid window %q (HH:MM-HH:MM, \"off\" = disabled)", v)
|
||||||
}
|
}
|
||||||
cfg.QuietHours = v
|
cfg.QuietHours = v
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if v := getenv("TALK_QUIET_MODE"); v != "" {
|
if v := getenv("TALK_QUIET_MODE"); v != "" {
|
||||||
if v != queue.QuietModeDiscard && v != queue.QuietModeToast {
|
if v != queue.QuietModeDiscard && v != queue.QuietModeToast {
|
||||||
return cfg, fmt.Errorf("TALK_QUIET_MODE: ungültiger Wert %q (erlaubt: %q, %q)",
|
return cfg, fmt.Errorf("TALK_QUIET_MODE: invalid value %q (allowed: %q, %q)",
|
||||||
v, queue.QuietModeDiscard, queue.QuietModeToast)
|
v, queue.QuietModeDiscard, queue.QuietModeToast)
|
||||||
}
|
}
|
||||||
cfg.QuietMode = v
|
cfg.QuietMode = v
|
||||||
}
|
}
|
||||||
if cfg.Queue.MaxText < 0 || cfg.Queue.MaxAge < 0 || cfg.Queue.RateLimit < 0 {
|
if cfg.Queue.MaxText < 0 || cfg.Queue.MaxAge < 0 || cfg.Queue.RateLimit < 0 {
|
||||||
return cfg, fmt.Errorf("queue: max_text, max_age und rate_limit dürfen nicht negativ sein (0 = unbegrenzt)")
|
return cfg, fmt.Errorf("queue: max_text, max_age and rate_limit must not be negative (0 = unlimited)")
|
||||||
}
|
}
|
||||||
switch cfg.Audio.Sink {
|
switch cfg.Audio.Sink {
|
||||||
case SinkOto, SinkNull:
|
case SinkOto, SinkNull:
|
||||||
default:
|
default:
|
||||||
return cfg, fmt.Errorf("audio.sink: ungültiger Wert %q (erlaubt: %q, %q)",
|
return cfg, fmt.Errorf("audio.sink: invalid value %q (allowed: %q, %q)",
|
||||||
cfg.Audio.Sink, SinkOto, SinkNull)
|
cfg.Audio.Sink, SinkOto, SinkNull)
|
||||||
}
|
}
|
||||||
// allowed_origins aus der Datei prüfen (Env wurde oben geparst): Eine
|
if cfg.Lang != "de" && cfg.Lang != "en" {
|
||||||
// leere Liste ist gültig (Tür zu), einzelne Einträge müssen aber
|
return cfg, fmt.Errorf("lang: invalid value %q (allowed: de, en)", cfg.Lang)
|
||||||
// substanziell sein — klarer Fehler statt stiller Ignoranz.
|
}
|
||||||
|
// Validate allowed_origins from the file (env was parsed above): an empty
|
||||||
|
// list is fine (door shut), but entries must have substance.
|
||||||
for _, o := range cfg.Server.AllowedOrigins {
|
for _, o := range cfg.Server.AllowedOrigins {
|
||||||
if strings.TrimSpace(o) == "" {
|
if strings.TrimSpace(o) == "" {
|
||||||
return cfg, fmt.Errorf("server.allowed_origins: leerer Eintrag in %v", cfg.Server.AllowedOrigins)
|
return cfg, fmt.Errorf("server.allowed_origins: empty entry in %v", cfg.Server.AllowedOrigins)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// quiet_hours aus der Datei validieren (Env wurde oben geprüft) und
|
// Validate quiet_hours from the file (env was checked above) and lift an
|
||||||
// quiet_mode leer (Datei ohne Wert) auf den Default heben.
|
// empty quiet_mode to the default.
|
||||||
if cfg.QuietHours != "" {
|
if cfg.QuietHours != "" {
|
||||||
if _, err := queue.ParseQuietHours(cfg.QuietHours); err != nil {
|
if _, err := queue.ParseQuietHours(cfg.QuietHours); err != nil {
|
||||||
return cfg, err
|
return cfg, err
|
||||||
@@ -326,16 +373,47 @@ func applyEnv(cfg Config, getenv func(string) string) (Config, error) {
|
|||||||
return cfg, nil
|
return cfg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// splitOrigins zerlegt eine kommagetrennte Origin-Liste (Env-Form von
|
// strayVoiceKeys finds keys under [voice.<provider>] that are not languages
|
||||||
// server.allowed_origins, z. B. "https://a.example, https://b.example").
|
// (de | en) and voice entries that are not a table of languages at all. The
|
||||||
// Whitespace um Einträge toleriert, leere Einträge sind ein klarer Fehler.
|
// decoder accepts anything there because the mapping is open; a top-level
|
||||||
|
// key such as `lang` written below [voice] lands here by accident.
|
||||||
|
func strayVoiceKeys(voice map[string]map[string]string) []string {
|
||||||
|
var out []string
|
||||||
|
providers := make([]string, 0, len(voice))
|
||||||
|
for p := range voice {
|
||||||
|
providers = append(providers, p)
|
||||||
|
}
|
||||||
|
sort.Strings(providers)
|
||||||
|
for _, p := range providers {
|
||||||
|
langs := voice[p]
|
||||||
|
if len(langs) == 0 {
|
||||||
|
out = append(out, "voice."+p)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
keys := make([]string, 0, len(langs))
|
||||||
|
for k := range langs {
|
||||||
|
keys = append(keys, k)
|
||||||
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
for _, k := range keys {
|
||||||
|
if k != "de" && k != "en" {
|
||||||
|
out = append(out, "voice."+p+"."+k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// splitOrigins splits a comma-separated origin list (the env form of
|
||||||
|
// server.allowed_origins, for example "https://a.example, https://b.example").
|
||||||
|
// Whitespace around entries is tolerated; empty entries are an error.
|
||||||
func splitOrigins(v string) ([]string, error) {
|
func splitOrigins(v string) ([]string, error) {
|
||||||
parts := strings.Split(v, ",")
|
parts := strings.Split(v, ",")
|
||||||
origins := make([]string, 0, len(parts))
|
origins := make([]string, 0, len(parts))
|
||||||
for _, p := range parts {
|
for _, p := range parts {
|
||||||
p = strings.TrimSpace(p)
|
p = strings.TrimSpace(p)
|
||||||
if p == "" {
|
if p == "" {
|
||||||
return nil, fmt.Errorf("leerer Eintrag in %q (komma-getrennte Origins oder \"off\")", v)
|
return nil, fmt.Errorf("empty entry in %q (comma-separated origins, or \"off\")", v)
|
||||||
}
|
}
|
||||||
origins = append(origins, p)
|
origins = append(origins, p)
|
||||||
}
|
}
|
||||||
|
|||||||
+231
-348
@@ -14,7 +14,23 @@ func env(kv map[string]string) func(string) string {
|
|||||||
return func(k string) string { return kv[k] }
|
return func(k string) string { return kv[k] }
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestDirForPlattformpfade(t *testing.T) {
|
// writeTOML writes content to a temp config.toml and returns its path.
|
||||||
|
func writeTOML(t *testing.T, content string) string {
|
||||||
|
t.Helper()
|
||||||
|
path := filepath.Join(t.TempDir(), "config.toml")
|
||||||
|
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
|
||||||
|
// missingFile returns a path that does not exist (defaults + env only).
|
||||||
|
func missingFile(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
return filepath.Join(t.TempDir(), "does-not-exist.toml")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDirForPlatformPaths(t *testing.T) {
|
||||||
cases := []struct {
|
cases := []struct {
|
||||||
name string
|
name string
|
||||||
goos string
|
goos string
|
||||||
@@ -22,66 +38,26 @@ func TestDirForPlattformpfade(t *testing.T) {
|
|||||||
want string
|
want string
|
||||||
errMsg string
|
errMsg string
|
||||||
}{
|
}{
|
||||||
{
|
{"linux with HOME", "linux", map[string]string{"HOME": "/home/u"}, "/home/u/.config/talk", ""},
|
||||||
name: "linux mit HOME",
|
{"linux XDG wins", "linux", map[string]string{"HOME": "/home/u", "XDG_CONFIG_HOME": "/xdg"}, "/xdg/talk", ""},
|
||||||
goos: "linux",
|
{"linux relative XDG is ignored", "linux", map[string]string{"HOME": "/home/u", "XDG_CONFIG_HOME": "relative"}, "/home/u/.config/talk", ""},
|
||||||
env: map[string]string{"HOME": "/home/u"},
|
{"linux without HOME is an error", "linux", map[string]string{}, "", ErrNoHome.Error()},
|
||||||
want: "/home/u/.config/talk",
|
{"macos", "darwin", map[string]string{"HOME": "/Users/u"}, "/Users/u/Library/Application Support/talk", ""},
|
||||||
},
|
{"macos without HOME is an error", "darwin", map[string]string{}, "", ErrNoHome.Error()},
|
||||||
{
|
{"windows", "windows", map[string]string{"APPDATA": `C:\Users\u\AppData\Roaming`}, filepath.Join(`C:\Users\u\AppData\Roaming`, "talk"), ""},
|
||||||
name: "linux XDG hat Vorrang",
|
{"windows without APPDATA is an error", "windows", map[string]string{}, "", ErrNoHome.Error()},
|
||||||
goos: "linux",
|
|
||||||
env: map[string]string{"HOME": "/home/u", "XDG_CONFIG_HOME": "/xdg"},
|
|
||||||
want: "/xdg/talk",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "linux relativer XDG wird ignoriert",
|
|
||||||
goos: "linux",
|
|
||||||
env: map[string]string{"HOME": "/home/u", "XDG_CONFIG_HOME": "relativ"},
|
|
||||||
want: "/home/u/.config/talk",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "linux ohne HOME ist Fehler",
|
|
||||||
goos: "linux",
|
|
||||||
env: map[string]string{},
|
|
||||||
errMsg: ErrNoHome.Error(),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "macos",
|
|
||||||
goos: "darwin",
|
|
||||||
env: map[string]string{"HOME": "/Users/u"},
|
|
||||||
want: "/Users/u/Library/Application Support/talk",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "macos ohne HOME ist Fehler",
|
|
||||||
goos: "darwin",
|
|
||||||
env: map[string]string{},
|
|
||||||
errMsg: ErrNoHome.Error(),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "windows",
|
|
||||||
goos: "windows",
|
|
||||||
env: map[string]string{"APPDATA": `C:\Users\u\AppData\Roaming`},
|
|
||||||
want: filepath.Join(`C:\Users\u\AppData\Roaming`, "talk"),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "windows ohne APPDATA ist Fehler",
|
|
||||||
goos: "windows",
|
|
||||||
env: map[string]string{},
|
|
||||||
errMsg: ErrNoHome.Error(),
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
for _, tc := range cases {
|
for _, tc := range cases {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
got, err := dirFor(tc.goos, env(tc.env))
|
got, err := dirFor(tc.goos, env(tc.env))
|
||||||
if tc.errMsg != "" {
|
if tc.errMsg != "" {
|
||||||
if err == nil || err.Error() != tc.errMsg {
|
if err == nil || err.Error() != tc.errMsg {
|
||||||
t.Fatalf("dirFor(%q) Fehler = %v, want %q", tc.goos, err, tc.errMsg)
|
t.Fatalf("dirFor(%q) error = %v, want %q", tc.goos, err, tc.errMsg)
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("dirFor(%q): unerwarteter Fehler %v", tc.goos, err)
|
t.Fatalf("dirFor(%q): unexpected error %v", tc.goos, err)
|
||||||
}
|
}
|
||||||
if got != tc.want {
|
if got != tc.want {
|
||||||
t.Errorf("dirFor(%q) = %q, want %q", tc.goos, got, tc.want)
|
t.Errorf("dirFor(%q) = %q, want %q", tc.goos, got, tc.want)
|
||||||
@@ -90,58 +66,39 @@ func TestDirForPlattformpfade(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestLoadMerge ist tischgesteuert für die Schichtenfolge
|
// TestLoadMerge pins the layering defaults → TOML file → env override.
|
||||||
// Defaults → TOML-Datei → Env-Override.
|
|
||||||
func TestLoadMerge(t *testing.T) {
|
func TestLoadMerge(t *testing.T) {
|
||||||
writeTOML := func(t *testing.T, content string) string {
|
t.Run("defaults only", func(t *testing.T) {
|
||||||
t.Helper()
|
cfg, err := Load(Options{File: missingFile(t), Getenv: env(nil)})
|
||||||
path := filepath.Join(t.TempDir(), "config.toml")
|
|
||||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return path
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Run("nur Defaults", func(t *testing.T) {
|
|
||||||
cfg, err := Load(Options{
|
|
||||||
File: filepath.Join(t.TempDir(), "gibt-es-nicht.toml"),
|
|
||||||
Getenv: env(nil),
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if cfg.Audio.Sink != SinkOto {
|
if cfg.Audio.Sink != SinkOto {
|
||||||
t.Errorf("Audio.Sink = %q, want Default %q", cfg.Audio.Sink, SinkOto)
|
t.Errorf("Audio.Sink = %q, want default %q", cfg.Audio.Sink, SinkOto)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("TOML überschreibt Default", func(t *testing.T) {
|
t.Run("TOML overrides default", func(t *testing.T) {
|
||||||
cfg, err := Load(Options{
|
cfg, err := Load(Options{File: writeTOML(t, "[audio]\nsink = \"null\"\n"), Getenv: env(nil)})
|
||||||
File: writeTOML(t, "[audio]\nsink = \"null\"\n"),
|
|
||||||
Getenv: env(nil),
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if cfg.Audio.Sink != SinkNull {
|
if cfg.Audio.Sink != SinkNull {
|
||||||
t.Errorf("Audio.Sink = %q, want %q aus TOML", cfg.Audio.Sink, SinkNull)
|
t.Errorf("Audio.Sink = %q, want %q from TOML", cfg.Audio.Sink, SinkNull)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("leere TOML-Sektion lässt Default stehen", func(t *testing.T) {
|
t.Run("empty TOML section keeps default", func(t *testing.T) {
|
||||||
cfg, err := Load(Options{
|
cfg, err := Load(Options{File: writeTOML(t, "# just a comment\n[audio]\n"), Getenv: env(nil)})
|
||||||
File: writeTOML(t, "# nur ein Kommentar\n[audio]\n"),
|
|
||||||
Getenv: env(nil),
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if cfg.Audio.Sink != SinkOto {
|
if cfg.Audio.Sink != SinkOto {
|
||||||
t.Errorf("Audio.Sink = %q, want Default %q", cfg.Audio.Sink, SinkOto)
|
t.Errorf("Audio.Sink = %q, want default %q", cfg.Audio.Sink, SinkOto)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Env schlägt Datei", func(t *testing.T) {
|
t.Run("env beats file", func(t *testing.T) {
|
||||||
cfg, err := Load(Options{
|
cfg, err := Load(Options{
|
||||||
File: writeTOML(t, "[audio]\nsink = \"oto\"\n"),
|
File: writeTOML(t, "[audio]\nsink = \"oto\"\n"),
|
||||||
Getenv: env(map[string]string{"TALK_AUDIO_SINK": "null"}),
|
Getenv: env(map[string]string{"TALK_AUDIO_SINK": "null"}),
|
||||||
@@ -150,15 +107,12 @@ func TestLoadMerge(t *testing.T) {
|
|||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if cfg.Audio.Sink != SinkNull {
|
if cfg.Audio.Sink != SinkNull {
|
||||||
t.Errorf("Audio.Sink = %q, want Env-Override %q", cfg.Audio.Sink, SinkNull)
|
t.Errorf("Audio.Sink = %q, want env override %q", cfg.Audio.Sink, SinkNull)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Env allein ohne Datei", func(t *testing.T) {
|
t.Run("env alone without file", func(t *testing.T) {
|
||||||
cfg, err := Load(Options{
|
cfg, err := Load(Options{File: missingFile(t), Getenv: env(map[string]string{"TALK_AUDIO_SINK": "null"})})
|
||||||
File: filepath.Join(t.TempDir(), "gibt-es-nicht.toml"),
|
|
||||||
Getenv: env(map[string]string{"TALK_AUDIO_SINK": "null"}),
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
@@ -167,59 +121,40 @@ func TestLoadMerge(t *testing.T) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("ungültiger Sink-Wert in Datei ist klarer Fehler", func(t *testing.T) {
|
t.Run("invalid sink in file is a clear error", func(t *testing.T) {
|
||||||
_, err := Load(Options{
|
_, err := Load(Options{File: writeTOML(t, "[audio]\nsink = \"mpv\"\n"), Getenv: env(nil)})
|
||||||
File: writeTOML(t, "[audio]\nsink = \"mpv\"\n"),
|
|
||||||
Getenv: env(nil),
|
|
||||||
})
|
|
||||||
if err == nil || !strings.Contains(err.Error(), "audio.sink") {
|
if err == nil || !strings.Contains(err.Error(), "audio.sink") {
|
||||||
t.Fatalf("Load-Fehler = %v, will klaren audio.sink-Fehler", err)
|
t.Fatalf("Load error = %v, want a clear audio.sink error", err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("ungültiger Env-Wert ist klarer Fehler", func(t *testing.T) {
|
t.Run("invalid env value is a clear error", func(t *testing.T) {
|
||||||
_, err := Load(Options{
|
_, err := Load(Options{File: missingFile(t), Getenv: env(map[string]string{"TALK_AUDIO_SINK": "bogus"})})
|
||||||
File: filepath.Join(t.TempDir(), "gibt-es-nicht.toml"),
|
if err == nil || !strings.Contains(err.Error(), "audio.sink") {
|
||||||
Getenv: env(map[string]string{"TALK_AUDIO_SINK": "bogus"}),
|
t.Fatalf("Load error = %v, want a clear audio.sink error", err)
|
||||||
})
|
|
||||||
if err == nil || !strings.Contains(err.Error(), "TALK") && !strings.Contains(err.Error(), "audio.sink") {
|
|
||||||
t.Fatalf("Load-Fehler = %v, will klaren audio.sink-Fehler", err)
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("kaputte TOML-Syntax ist klarer Fehler", func(t *testing.T) {
|
t.Run("broken TOML syntax is a clear error", func(t *testing.T) {
|
||||||
_, err := Load(Options{
|
if _, err := Load(Options{File: writeTOML(t, "[audio\nsink = \n"), Getenv: env(nil)}); err == nil {
|
||||||
File: writeTOML(t, "[audio\nsink = \n"),
|
t.Fatal("Load with broken TOML: no error")
|
||||||
Getenv: env(nil),
|
|
||||||
})
|
|
||||||
if err == nil {
|
|
||||||
t.Fatal("Load bei kaputter TOML: kein Fehler")
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("ohne Home läuft Load mit Defaults weiter", func(t *testing.T) {
|
t.Run("without HOME Load continues with defaults", func(t *testing.T) {
|
||||||
cfg, err := Load(Options{Getenv: env(nil)})
|
cfg, err := Load(Options{Getenv: env(nil)})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load ohne HOME: %v", err)
|
t.Fatalf("Load without HOME: %v", err)
|
||||||
}
|
}
|
||||||
if cfg.Audio.Sink != SinkOto {
|
if cfg.Audio.Sink != SinkOto {
|
||||||
t.Errorf("Audio.Sink = %q, want Default %q", cfg.Audio.Sink, SinkOto)
|
t.Errorf("Audio.Sink = %q, want default %q", cfg.Audio.Sink, SinkOto)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestLoadProviderKette deckt die Task-03-Felder ab: Provider-Pin per
|
// TestLoadProviderChain covers the provider pin (file/env), per-provider
|
||||||
// Datei/Env, Provider-Endpunkte/-Modelle und das Voice-Mapping.
|
// endpoints/models and the voice mapping.
|
||||||
func TestLoadProviderKette(t *testing.T) {
|
func TestLoadProviderChain(t *testing.T) {
|
||||||
writeTOML := func(t *testing.T, content string) string {
|
|
||||||
t.Helper()
|
|
||||||
path := filepath.Join(t.TempDir(), "config.toml")
|
|
||||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return path
|
|
||||||
}
|
|
||||||
|
|
||||||
toml := `provider = "openai"
|
toml := `provider = "openai"
|
||||||
|
|
||||||
[providers.elevenlabs]
|
[providers.elevenlabs]
|
||||||
@@ -233,14 +168,14 @@ model = "gpt-4o-mini-tts"
|
|||||||
endpoint = "wss://edge.example.com/synth"
|
endpoint = "wss://edge.example.com/synth"
|
||||||
|
|
||||||
[voice.elevenlabs]
|
[voice.elevenlabs]
|
||||||
de = "MeineStimme"
|
de = "MyGermanVoice"
|
||||||
en = "MyVoice"
|
en = "MyVoice"
|
||||||
|
|
||||||
[voice.edge]
|
[voice.edge]
|
||||||
de = "de-DE-KatjaNeural"
|
de = "de-DE-KatjaNeural"
|
||||||
`
|
`
|
||||||
|
|
||||||
t.Run("TOML liefert Pin, Endpunkte und Voice-Mapping", func(t *testing.T) {
|
t.Run("TOML yields pin, endpoints and voice mapping", func(t *testing.T) {
|
||||||
cfg, err := Load(Options{File: writeTOML(t, toml), Getenv: env(nil)})
|
cfg, err := Load(Options{File: writeTOML(t, toml), Getenv: env(nil)})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
@@ -257,7 +192,7 @@ de = "de-DE-KatjaNeural"
|
|||||||
if got := cfg.Providers["edge"].Endpoint; got != "wss://edge.example.com/synth" {
|
if got := cfg.Providers["edge"].Endpoint; got != "wss://edge.example.com/synth" {
|
||||||
t.Errorf("Providers[edge].Endpoint = %q", got)
|
t.Errorf("Providers[edge].Endpoint = %q", got)
|
||||||
}
|
}
|
||||||
if got := cfg.Voice["elevenlabs"]["de"]; got != "MeineStimme" {
|
if got := cfg.Voice["elevenlabs"]["de"]; got != "MyGermanVoice" {
|
||||||
t.Errorf("Voice[elevenlabs][de] = %q", got)
|
t.Errorf("Voice[elevenlabs][de] = %q", got)
|
||||||
}
|
}
|
||||||
if got := cfg.Voice["elevenlabs"]["en"]; got != "MyVoice" {
|
if got := cfg.Voice["elevenlabs"]["en"]; got != "MyVoice" {
|
||||||
@@ -265,74 +200,51 @@ de = "de-DE-KatjaNeural"
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("TALK_PROVIDER schlägt Datei-Pin", func(t *testing.T) {
|
t.Run("TALK_PROVIDER beats the file pin", func(t *testing.T) {
|
||||||
cfg, err := Load(Options{
|
cfg, err := Load(Options{File: writeTOML(t, toml), Getenv: env(map[string]string{"TALK_PROVIDER": "edge"})})
|
||||||
File: writeTOML(t, toml),
|
|
||||||
Getenv: env(map[string]string{"TALK_PROVIDER": "edge"}),
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if cfg.Provider != "edge" {
|
if cfg.Provider != "edge" {
|
||||||
t.Errorf("Provider = %q, want Env-Override %q", cfg.Provider, "edge")
|
t.Errorf("Provider = %q, want env override %q", cfg.Provider, "edge")
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("ohne alles: keine Pins, keine Endpunkte", func(t *testing.T) {
|
t.Run("nothing configured: no pin, no endpoints", func(t *testing.T) {
|
||||||
cfg, err := Load(Options{
|
cfg, err := Load(Options{File: missingFile(t), Getenv: env(nil)})
|
||||||
File: filepath.Join(t.TempDir(), "gibt-es-nicht.toml"),
|
|
||||||
Getenv: env(nil),
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if cfg.Provider != "" || cfg.Providers != nil || cfg.Voice != nil {
|
if cfg.Provider != "" || cfg.Providers != nil || cfg.Voice != nil {
|
||||||
t.Errorf("Provider-Konfiguration = %+v, will leer", cfg)
|
t.Errorf("provider configuration = %+v, want empty", cfg)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestLoadServerPort deckt die Task-04-Felder ab: Daemon-Port per Defaults
|
// TestLoadWrapLabel: the `talk wrap` announcement label, defaults → TOML →
|
||||||
// (7800), TOML [server] port, Env-Override TALK_PORT samt Validierung.
|
// env in the usual layering.
|
||||||
// TestLoadWrapLabel: das Ansage-Label von `talk wrap` (Task 07) —
|
|
||||||
// Defaults → TOML → Env nach dem üblichen Schichten-Muster.
|
|
||||||
func TestLoadWrapLabel(t *testing.T) {
|
func TestLoadWrapLabel(t *testing.T) {
|
||||||
writeTOML := func(t *testing.T, content string) string {
|
t.Run("default empty (command base name)", func(t *testing.T) {
|
||||||
t.Helper()
|
cfg, err := Load(Options{File: missingFile(t), Getenv: env(nil)})
|
||||||
path := filepath.Join(t.TempDir(), "config.toml")
|
|
||||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return path
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Run("Default leer (Basisname des Befehls)", func(t *testing.T) {
|
|
||||||
cfg, err := Load(Options{
|
|
||||||
File: filepath.Join(t.TempDir(), "gibt-es-nicht.toml"),
|
|
||||||
Getenv: env(nil),
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if cfg.Wrap.Label != "" {
|
if cfg.Wrap.Label != "" {
|
||||||
t.Errorf("Wrap.Label = %q, want leer (Default)", cfg.Wrap.Label)
|
t.Errorf("Wrap.Label = %q, want empty (default)", cfg.Wrap.Label)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("TOML überschreibt Default", func(t *testing.T) {
|
t.Run("TOML overrides default", func(t *testing.T) {
|
||||||
cfg, err := Load(Options{
|
cfg, err := Load(Options{File: writeTOML(t, "[wrap]\nlabel = \"Deployment\"\n"), Getenv: env(nil)})
|
||||||
File: writeTOML(t, "[wrap]\nlabel = \"Deployment\"\n"),
|
|
||||||
Getenv: env(nil),
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if cfg.Wrap.Label != "Deployment" {
|
if cfg.Wrap.Label != "Deployment" {
|
||||||
t.Errorf("Wrap.Label = %q, want %q aus TOML", cfg.Wrap.Label, "Deployment")
|
t.Errorf("Wrap.Label = %q, want %q from TOML", cfg.Wrap.Label, "Deployment")
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("TALK_WRAP_LABEL schlägt Datei", func(t *testing.T) {
|
t.Run("TALK_WRAP_LABEL beats the file", func(t *testing.T) {
|
||||||
cfg, err := Load(Options{
|
cfg, err := Load(Options{
|
||||||
File: writeTOML(t, "[wrap]\nlabel = \"Deployment\"\n"),
|
File: writeTOML(t, "[wrap]\nlabel = \"Deployment\"\n"),
|
||||||
Getenv: env(map[string]string{"TALK_WRAP_LABEL": "Nightly Build"}),
|
Getenv: env(map[string]string{"TALK_WRAP_LABEL": "Nightly Build"}),
|
||||||
@@ -341,48 +253,35 @@ func TestLoadWrapLabel(t *testing.T) {
|
|||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if cfg.Wrap.Label != "Nightly Build" {
|
if cfg.Wrap.Label != "Nightly Build" {
|
||||||
t.Errorf("Wrap.Label = %q, want Env-Override %q", cfg.Wrap.Label, "Nightly Build")
|
t.Errorf("Wrap.Label = %q, want env override %q", cfg.Wrap.Label, "Nightly Build")
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestLoadServerPort: daemon port by default (7800), TOML [server] port and
|
||||||
|
// env override TALK_PORT including validation.
|
||||||
func TestLoadServerPort(t *testing.T) {
|
func TestLoadServerPort(t *testing.T) {
|
||||||
writeTOML := func(t *testing.T, content string) string {
|
t.Run("default 7800", func(t *testing.T) {
|
||||||
t.Helper()
|
cfg, err := Load(Options{File: missingFile(t), Getenv: env(nil)})
|
||||||
path := filepath.Join(t.TempDir(), "config.toml")
|
|
||||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return path
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Run("Default 7800", func(t *testing.T) {
|
|
||||||
cfg, err := Load(Options{
|
|
||||||
File: filepath.Join(t.TempDir(), "gibt-es-nicht.toml"),
|
|
||||||
Getenv: env(nil),
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if cfg.Server.Port != DefaultServerPort {
|
if cfg.Server.Port != DefaultServerPort {
|
||||||
t.Errorf("Server.Port = %d, want Default %d", cfg.Server.Port, DefaultServerPort)
|
t.Errorf("Server.Port = %d, want default %d", cfg.Server.Port, DefaultServerPort)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("TOML überschreibt Default", func(t *testing.T) {
|
t.Run("TOML overrides default", func(t *testing.T) {
|
||||||
cfg, err := Load(Options{
|
cfg, err := Load(Options{File: writeTOML(t, "[server]\nport = 7999\n"), Getenv: env(nil)})
|
||||||
File: writeTOML(t, "[server]\nport = 7999\n"),
|
|
||||||
Getenv: env(nil),
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if cfg.Server.Port != 7999 {
|
if cfg.Server.Port != 7999 {
|
||||||
t.Errorf("Server.Port = %d, want 7999 aus TOML", cfg.Server.Port)
|
t.Errorf("Server.Port = %d, want 7999 from TOML", cfg.Server.Port)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("TALK_PORT schlägt Datei", func(t *testing.T) {
|
t.Run("TALK_PORT beats the file", func(t *testing.T) {
|
||||||
cfg, err := Load(Options{
|
cfg, err := Load(Options{
|
||||||
File: writeTOML(t, "[server]\nport = 7999\n"),
|
File: writeTOML(t, "[server]\nport = 7999\n"),
|
||||||
Getenv: env(map[string]string{"TALK_PORT": "7912"}),
|
Getenv: env(map[string]string{"TALK_PORT": "7912"}),
|
||||||
@@ -391,92 +290,73 @@ func TestLoadServerPort(t *testing.T) {
|
|||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if cfg.Server.Port != 7912 {
|
if cfg.Server.Port != 7912 {
|
||||||
t.Errorf("Server.Port = %d, want Env-Override 7912", cfg.Server.Port)
|
t.Errorf("Server.Port = %d, want env override 7912", cfg.Server.Port)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("ungültiger TALK_PORT-Wert ist klarer Fehler", func(t *testing.T) {
|
t.Run("invalid TALK_PORT is a clear error", func(t *testing.T) {
|
||||||
for _, bad := range []string{"null", "0", "-1", "70000"} {
|
for _, bad := range []string{"null", "0", "-1", "70000"} {
|
||||||
_, err := Load(Options{
|
_, err := Load(Options{File: missingFile(t), Getenv: env(map[string]string{"TALK_PORT": bad})})
|
||||||
File: filepath.Join(t.TempDir(), "gibt-es-nicht.toml"),
|
|
||||||
Getenv: env(map[string]string{"TALK_PORT": bad}),
|
|
||||||
})
|
|
||||||
if err == nil || !strings.Contains(err.Error(), "TALK_PORT") {
|
if err == nil || !strings.Contains(err.Error(), "TALK_PORT") {
|
||||||
t.Fatalf("TALK_PORT=%q: Fehler = %v, will klaren TALK_PORT-Fehler", bad, err)
|
t.Fatalf("TALK_PORT=%q: error = %v, want a clear TALK_PORT error", bad, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestLoadAllowedOrigins(t *testing.T) {
|
func TestLoadAllowedOrigins(t *testing.T) {
|
||||||
writeTOML := func(t *testing.T, content string) string {
|
t.Run("default: empty list (no CORS)", func(t *testing.T) {
|
||||||
t.Helper()
|
cfg, err := Load(Options{File: missingFile(t), Getenv: env(nil)})
|
||||||
path := filepath.Join(t.TempDir(), "config.toml")
|
|
||||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return path
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Run("Default: leere Liste (kein CORS)", func(t *testing.T) {
|
|
||||||
cfg, err := Load(Options{
|
|
||||||
File: filepath.Join(t.TempDir(), "gibt-es-nicht.toml"),
|
|
||||||
Getenv: env(nil),
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if len(cfg.Server.AllowedOrigins) != 0 {
|
if len(cfg.Server.AllowedOrigins) != 0 {
|
||||||
t.Errorf("AllowedOrigins = %v, want leer (Tür zu)", cfg.Server.AllowedOrigins)
|
t.Errorf("AllowedOrigins = %v, want empty (door shut)", cfg.Server.AllowedOrigins)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("TOML-Liste", func(t *testing.T) {
|
t.Run("TOML list", func(t *testing.T) {
|
||||||
cfg, err := Load(Options{
|
cfg, err := Load(Options{
|
||||||
File: writeTOML(t, "[server]\nallowed_origins = [\"https://chat.az-gruppe.com\"]\n"),
|
File: writeTOML(t, "[server]\nallowed_origins = [\"https://chat.example.com\"]\n"),
|
||||||
Getenv: env(nil),
|
Getenv: env(nil),
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
want := []string{"https://chat.az-gruppe.com"}
|
if strings.Join(cfg.Server.AllowedOrigins, "|") != "https://chat.example.com" {
|
||||||
if strings.Join(cfg.Server.AllowedOrigins, "|") != strings.Join(want, "|") {
|
t.Errorf("AllowedOrigins = %v", cfg.Server.AllowedOrigins)
|
||||||
t.Errorf("AllowedOrigins = %v, want %v", cfg.Server.AllowedOrigins, want)
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("TALK_ALLOWED_ORIGINS schlägt Datei (mehrere, mit Leerzeichen)", func(t *testing.T) {
|
t.Run("TALK_ALLOWED_ORIGINS beats the file (several, with spaces)", func(t *testing.T) {
|
||||||
cfg, err := Load(Options{
|
cfg, err := Load(Options{
|
||||||
File: writeTOML(t, "[server]\nallowed_origins = [\"https://datei.example\"]\n"),
|
File: writeTOML(t, "[server]\nallowed_origins = [\"https://file.example\"]\n"),
|
||||||
Getenv: env(map[string]string{"TALK_ALLOWED_ORIGINS": "https://chat.az-gruppe.com, https://grid.ag"}),
|
Getenv: env(map[string]string{"TALK_ALLOWED_ORIGINS": "https://chat.example.com, https://grid.example"}),
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
want := []string{"https://chat.az-gruppe.com", "https://grid.ag"}
|
want := "https://chat.example.com|https://grid.example"
|
||||||
if strings.Join(cfg.Server.AllowedOrigins, "|") != strings.Join(want, "|") {
|
if strings.Join(cfg.Server.AllowedOrigins, "|") != want {
|
||||||
t.Errorf("AllowedOrigins = %v, want %v", cfg.Server.AllowedOrigins, want)
|
t.Errorf("AllowedOrigins = %v, want %v", cfg.Server.AllowedOrigins, want)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("TALK_ALLOWED_ORIGINS=off leert die Datei-Liste", func(t *testing.T) {
|
t.Run("TALK_ALLOWED_ORIGINS=off clears the file list", func(t *testing.T) {
|
||||||
cfg, err := Load(Options{
|
cfg, err := Load(Options{
|
||||||
File: writeTOML(t, "[server]\nallowed_origins = [\"https://datei.example\"]\n"),
|
File: writeTOML(t, "[server]\nallowed_origins = [\"https://file.example\"]\n"),
|
||||||
Getenv: env(map[string]string{"TALK_ALLOWED_ORIGINS": "off"}),
|
Getenv: env(map[string]string{"TALK_ALLOWED_ORIGINS": "off"}),
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if len(cfg.Server.AllowedOrigins) != 0 {
|
if len(cfg.Server.AllowedOrigins) != 0 {
|
||||||
t.Errorf("AllowedOrigins = %v, want leer (off)", cfg.Server.AllowedOrigins)
|
t.Errorf("AllowedOrigins = %v, want empty (off)", cfg.Server.AllowedOrigins)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Wildcard ist erlaubter Wert", func(t *testing.T) {
|
t.Run("wildcard is an allowed value", func(t *testing.T) {
|
||||||
cfg, err := Load(Options{
|
cfg, err := Load(Options{File: missingFile(t), Getenv: env(map[string]string{"TALK_ALLOWED_ORIGINS": "*"})})
|
||||||
File: filepath.Join(t.TempDir(), "gibt-es-nicht.toml"),
|
|
||||||
Getenv: env(map[string]string{"TALK_ALLOWED_ORIGINS": "*"}),
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
@@ -485,69 +365,53 @@ func TestLoadAllowedOrigins(t *testing.T) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("leere Einträge sind klare Fehler", func(t *testing.T) {
|
t.Run("empty entries are clear errors", func(t *testing.T) {
|
||||||
for _, tc := range []struct {
|
for _, tc := range []struct {
|
||||||
name string
|
name string
|
||||||
file string
|
file string
|
||||||
envv string
|
envv string
|
||||||
}{
|
}{
|
||||||
{"env", "", "https://a.example,,https://b.example"},
|
{"env", "", "https://a.example,,https://b.example"},
|
||||||
{"datei", "[server]\nallowed_origins = [\"https://a.example\", \"\"]\n", ""},
|
{"file", "[server]\nallowed_origins = [\"https://a.example\", \"\"]\n", ""},
|
||||||
} {
|
} {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
file := filepath.Join(t.TempDir(), "gibt-es-nicht.toml")
|
file := missingFile(t)
|
||||||
if tc.file != "" {
|
if tc.file != "" {
|
||||||
file = writeTOML(t, tc.file)
|
file = writeTOML(t, tc.file)
|
||||||
}
|
}
|
||||||
_, err := Load(Options{
|
_, err := Load(Options{File: file, Getenv: env(map[string]string{"TALK_ALLOWED_ORIGINS": tc.envv})})
|
||||||
File: file,
|
|
||||||
Getenv: env(map[string]string{"TALK_ALLOWED_ORIGINS": tc.envv}),
|
|
||||||
})
|
|
||||||
if err == nil || !strings.Contains(err.Error(), "allowed_origins") && !strings.Contains(err.Error(), "ALLOWED_ORIGINS") {
|
if err == nil || !strings.Contains(err.Error(), "allowed_origins") && !strings.Contains(err.Error(), "ALLOWED_ORIGINS") {
|
||||||
t.Fatalf("Fehler = %v, will klaren allowed_origins-Fehler", err)
|
t.Fatalf("error = %v, want a clear allowed_origins error", err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestLoadGesetze deckt die Task-05-Felder ab: Rate-Limit (Default 30 s,
|
// TestLoadLaws covers rate limit (default 30 s, "0s" = unlimited), high
|
||||||
// "0s" = unbegrenzt), High-Burst (Default an), Ruhezeiten (Default aus;
|
// burst (default on) and quiet hours (default off; format validated) with
|
||||||
// Format validiert) samt Env-Overrides und klaren Fehlern.
|
// env overrides and clear errors.
|
||||||
func TestLoadGesetze(t *testing.T) {
|
func TestLoadLaws(t *testing.T) {
|
||||||
writeTOML := func(t *testing.T, content string) string {
|
t.Run("defaults: 30 s, burst on, quiet hours off, mode discard", func(t *testing.T) {
|
||||||
t.Helper()
|
cfg, err := Load(Options{File: missingFile(t), Getenv: env(nil)})
|
||||||
path := filepath.Join(t.TempDir(), "config.toml")
|
|
||||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return path
|
|
||||||
}
|
|
||||||
fehlendeDatei := func(t *testing.T) string {
|
|
||||||
t.Helper()
|
|
||||||
return filepath.Join(t.TempDir(), "gibt-es-nicht.toml")
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Run("Defaults: 30 s, Burst an, Ruhezeit aus, Modus discard", func(t *testing.T) {
|
|
||||||
cfg, err := Load(Options{File: fehlendeDatei(t), Getenv: env(nil)})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if cfg.Queue.RateLimit != DefaultRateLimit {
|
if cfg.Queue.RateLimit != DefaultRateLimit {
|
||||||
t.Errorf("Queue.RateLimit = %v, want Default %v", cfg.Queue.RateLimit, DefaultRateLimit)
|
t.Errorf("Queue.RateLimit = %v, want default %v", cfg.Queue.RateLimit, DefaultRateLimit)
|
||||||
}
|
}
|
||||||
if !cfg.Queue.AllowHighBurst {
|
if !cfg.Queue.AllowHighBurst {
|
||||||
t.Error("Queue.AllowHighBurst = false, want Default true")
|
t.Error("Queue.AllowHighBurst = false, want default true")
|
||||||
}
|
}
|
||||||
if cfg.QuietHours != "" {
|
if cfg.QuietHours != "" {
|
||||||
t.Errorf("QuietHours = %q, want Default leer (aus)", cfg.QuietHours)
|
t.Errorf("QuietHours = %q, want default empty (off)", cfg.QuietHours)
|
||||||
}
|
}
|
||||||
if cfg.QuietMode != queue.QuietModeDiscard {
|
if cfg.QuietMode != queue.QuietModeDiscard {
|
||||||
t.Errorf("QuietMode = %q, want Default %q", cfg.QuietMode, queue.QuietModeDiscard)
|
t.Errorf("QuietMode = %q, want default %q", cfg.QuietMode, queue.QuietModeDiscard)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("TOML setzt alle Gesetz-Felder", func(t *testing.T) {
|
t.Run("TOML sets all law fields", func(t *testing.T) {
|
||||||
cfg, err := Load(Options{
|
cfg, err := Load(Options{
|
||||||
File: writeTOML(t, `
|
File: writeTOML(t, `
|
||||||
quiet_hours = "18:00-08:00"
|
quiet_hours = "18:00-08:00"
|
||||||
@@ -566,36 +430,33 @@ allow_high_burst = false
|
|||||||
t.Errorf("Queue.RateLimit = %v, want 10s", cfg.Queue.RateLimit)
|
t.Errorf("Queue.RateLimit = %v, want 10s", cfg.Queue.RateLimit)
|
||||||
}
|
}
|
||||||
if cfg.Queue.AllowHighBurst {
|
if cfg.Queue.AllowHighBurst {
|
||||||
t.Error("Queue.AllowHighBurst = true, want false aus TOML")
|
t.Error("Queue.AllowHighBurst = true, want false from TOML")
|
||||||
}
|
}
|
||||||
if cfg.QuietHours != "18:00-08:00" {
|
if cfg.QuietHours != "18:00-08:00" {
|
||||||
t.Errorf("QuietHours = %q, want Fenster aus TOML", cfg.QuietHours)
|
t.Errorf("QuietHours = %q, want window from TOML", cfg.QuietHours)
|
||||||
}
|
}
|
||||||
if cfg.QuietMode != queue.QuietModeToast {
|
if cfg.QuietMode != queue.QuietModeToast {
|
||||||
t.Errorf("QuietMode = %q, want toast", cfg.QuietMode)
|
t.Errorf("QuietMode = %q, want toast", cfg.QuietMode)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("partielle [queue]-Tabelle behält Defaults", func(t *testing.T) {
|
t.Run("partial [queue] table keeps defaults", func(t *testing.T) {
|
||||||
cfg, err := Load(Options{
|
cfg, err := Load(Options{File: writeTOML(t, "[queue]\nrate_limit = \"0s\"\n"), Getenv: env(nil)})
|
||||||
File: writeTOML(t, "[queue]\nrate_limit = \"0s\"\n"),
|
|
||||||
Getenv: env(nil),
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if cfg.Queue.RateLimit != 0 {
|
if cfg.Queue.RateLimit != 0 {
|
||||||
t.Errorf("Queue.RateLimit = %v, want 0 (unbegrenzt)", cfg.Queue.RateLimit)
|
t.Errorf("Queue.RateLimit = %v, want 0 (unlimited)", cfg.Queue.RateLimit)
|
||||||
}
|
}
|
||||||
if !cfg.Queue.AllowHighBurst {
|
if !cfg.Queue.AllowHighBurst {
|
||||||
t.Error("Queue.AllowHighBurst = false, want unveränderten Default true")
|
t.Error("Queue.AllowHighBurst = false, want unchanged default true")
|
||||||
}
|
}
|
||||||
if cfg.QuietMode != queue.QuietModeDiscard {
|
if cfg.QuietMode != queue.QuietModeDiscard {
|
||||||
t.Errorf("QuietMode = %q, want unveränderten Default discard", cfg.QuietMode)
|
t.Errorf("QuietMode = %q, want unchanged default discard", cfg.QuietMode)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Env überschreibt Datei (inkl. off)", func(t *testing.T) {
|
t.Run("env overrides file (including off)", func(t *testing.T) {
|
||||||
cfg, err := Load(Options{
|
cfg, err := Load(Options{
|
||||||
File: writeTOML(t, `
|
File: writeTOML(t, `
|
||||||
quiet_hours = "18:00-08:00"
|
quiet_hours = "18:00-08:00"
|
||||||
@@ -616,96 +477,58 @@ allow_high_burst = false
|
|||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if cfg.Queue.RateLimit != time.Second {
|
if cfg.Queue.RateLimit != time.Second {
|
||||||
t.Errorf("Queue.RateLimit = %v, want 1s aus Env", cfg.Queue.RateLimit)
|
t.Errorf("Queue.RateLimit = %v, want 1s from env", cfg.Queue.RateLimit)
|
||||||
}
|
}
|
||||||
if !cfg.Queue.AllowHighBurst {
|
if !cfg.Queue.AllowHighBurst {
|
||||||
t.Error("Queue.AllowHighBurst = false, want true aus Env")
|
t.Error("Queue.AllowHighBurst = false, want true from env")
|
||||||
}
|
}
|
||||||
if cfg.QuietHours != "" {
|
if cfg.QuietHours != "" {
|
||||||
t.Errorf("QuietHours = %q, want leer (off aus Env)", cfg.QuietHours)
|
t.Errorf("QuietHours = %q, want empty (off from env)", cfg.QuietHours)
|
||||||
}
|
}
|
||||||
if cfg.QuietMode != queue.QuietModeToast {
|
if cfg.QuietMode != queue.QuietModeToast {
|
||||||
t.Errorf("QuietMode = %q, want toast aus Env", cfg.QuietMode)
|
t.Errorf("QuietMode = %q, want toast from env", cfg.QuietMode)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("ungültige Gesetz-Werte sind klare Fehler", func(t *testing.T) {
|
t.Run("invalid law values are clear errors", func(t *testing.T) {
|
||||||
cases := []struct {
|
cases := []struct {
|
||||||
name string
|
name string
|
||||||
toml string
|
toml string
|
||||||
envs map[string]string
|
envs map[string]string
|
||||||
want string
|
want string
|
||||||
}{
|
}{
|
||||||
{
|
{"TALK_RATE_LIMIT garbage", "", map[string]string{"TALK_RATE_LIMIT": "fast"}, "TALK_RATE_LIMIT"},
|
||||||
name: "TALK_RATE_LIMIT Müll",
|
{"TALK_RATE_LIMIT negative", "", map[string]string{"TALK_RATE_LIMIT": "-5s"}, "TALK_RATE_LIMIT"},
|
||||||
envs: map[string]string{"TALK_RATE_LIMIT": "schnell"},
|
{"rate_limit garbage in file", "[queue]\nrate_limit = \"garbage\"\n", nil, "rate_limit"},
|
||||||
want: "TALK_RATE_LIMIT",
|
{"TALK_ALLOW_HIGH_BURST garbage", "", map[string]string{"TALK_ALLOW_HIGH_BURST": "maybe"}, "TALK_ALLOW_HIGH_BURST"},
|
||||||
},
|
{"quiet_hours garbage in file", "quiet_hours = \"evenings\"\n", nil, "quiet_hours"},
|
||||||
{
|
{"TALK_QUIET_HOURS garbage", "", map[string]string{"TALK_QUIET_HOURS": "25:00-26:00"}, "TALK_QUIET_HOURS"},
|
||||||
name: "TALK_RATE_LIMIT negativ",
|
{"TALK_QUIET_MODE garbage", "", map[string]string{"TALK_QUIET_MODE": "vibrate"}, "TALK_QUIET_MODE"},
|
||||||
envs: map[string]string{"TALK_RATE_LIMIT": "-5s"},
|
|
||||||
want: "TALK_RATE_LIMIT",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "rate_limit Müll in Datei",
|
|
||||||
toml: "[queue]\nrate_limit = \"müll\"\n",
|
|
||||||
want: "rate_limit",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "TALK_ALLOW_HIGH_BURST Müll",
|
|
||||||
envs: map[string]string{"TALK_ALLOW_HIGH_BURST": "vielleicht"},
|
|
||||||
want: "TALK_ALLOW_HIGH_BURST",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "quiet_hours Müll in Datei",
|
|
||||||
toml: "quiet_hours = \"abends\"\n",
|
|
||||||
want: "quiet_hours",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "TALK_QUIET_HOURS Müll",
|
|
||||||
envs: map[string]string{"TALK_QUIET_HOURS": "25:00-26:00"},
|
|
||||||
want: "TALK_QUIET_HOURS",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "TALK_QUIET_MODE Müll",
|
|
||||||
envs: map[string]string{"TALK_QUIET_MODE": "vibrieren"},
|
|
||||||
want: "TALK_QUIET_MODE",
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
for _, tc := range cases {
|
for _, tc := range cases {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
file := fehlendeDatei(t)
|
file := missingFile(t)
|
||||||
if tc.toml != "" {
|
if tc.toml != "" {
|
||||||
file = writeTOML(t, tc.toml)
|
file = writeTOML(t, tc.toml)
|
||||||
}
|
}
|
||||||
_, err := Load(Options{File: file, Getenv: env(tc.envs)})
|
_, err := Load(Options{File: file, Getenv: env(tc.envs)})
|
||||||
if err == nil || !strings.Contains(err.Error(), tc.want) {
|
if err == nil || !strings.Contains(err.Error(), tc.want) {
|
||||||
t.Fatalf("Fehler = %v, will klaren Fehler mit %q", err, tc.want)
|
t.Fatalf("error = %v, want a clear error mentioning %q", err, tc.want)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestLoadDaemonAutostart deckt [daemon] autostart ab: Default an, TOML
|
// TestLoadDaemonAutostart covers [daemon] autostart: default on, TOML can
|
||||||
// kann es ausschalten, Env TALK_AUTOSTART schlägt die Datei, Unsinn ist ein
|
// switch it off, env TALK_AUTOSTART beats the file, garbage is an error.
|
||||||
// klarer Fehler.
|
|
||||||
func TestLoadDaemonAutostart(t *testing.T) {
|
func TestLoadDaemonAutostart(t *testing.T) {
|
||||||
fehlendeDatei := filepath.Join(t.TempDir(), "gibt-es-nicht.toml")
|
cfg, err := Load(Options{File: missingFile(t), Getenv: env(nil)})
|
||||||
writeTOML := func(t *testing.T, content string) string {
|
|
||||||
path := filepath.Join(t.TempDir(), "config.toml")
|
|
||||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return path
|
|
||||||
}
|
|
||||||
|
|
||||||
cfg, err := Load(Options{File: fehlendeDatei, Getenv: env(nil)})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if !cfg.Daemon.Autostart {
|
if !cfg.Daemon.Autostart {
|
||||||
t.Error("Daemon.Autostart = false, want Default true")
|
t.Error("Daemon.Autostart = false, want default true")
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg, err = Load(Options{File: writeTOML(t, "[daemon]\nautostart = false\n"), Getenv: env(nil)})
|
cfg, err = Load(Options{File: writeTOML(t, "[daemon]\nautostart = false\n"), Getenv: env(nil)})
|
||||||
@@ -713,7 +536,7 @@ func TestLoadDaemonAutostart(t *testing.T) {
|
|||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if cfg.Daemon.Autostart {
|
if cfg.Daemon.Autostart {
|
||||||
t.Error("Daemon.Autostart = true, want false aus TOML")
|
t.Error("Daemon.Autostart = true, want false from TOML")
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg, err = Load(Options{
|
cfg, err = Load(Options{
|
||||||
@@ -724,33 +547,24 @@ func TestLoadDaemonAutostart(t *testing.T) {
|
|||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if !cfg.Daemon.Autostart {
|
if !cfg.Daemon.Autostart {
|
||||||
t.Error("Daemon.Autostart = false, want true aus Env (Env schlägt Datei)")
|
t.Error("Daemon.Autostart = false, want true from env (env beats file)")
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := Load(Options{File: fehlendeDatei, Getenv: env(map[string]string{"TALK_AUTOSTART": "vielleicht"})}); err == nil {
|
if _, err := Load(Options{File: missingFile(t), Getenv: env(map[string]string{"TALK_AUTOSTART": "maybe"})}); err == nil {
|
||||||
t.Error("TALK_AUTOSTART=vielleicht: kein Fehler, want klarer Fehler")
|
t.Error("TALK_AUTOSTART=maybe: no error, want a clear error")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestLoadLimits deckt queue.max_text / queue.max_age ab: Defaults 400 / 2m,
|
// TestLoadLimits covers queue.max_text / queue.max_age: defaults 400 / 2m,
|
||||||
// TOML und Env (Env schlägt Datei), 0 = unbegrenzt, Unsinn und negative
|
// TOML and env (env beats file), 0 = unlimited, garbage and negative values
|
||||||
// Werte sind klare Fehler.
|
// are clear errors.
|
||||||
func TestLoadLimits(t *testing.T) {
|
func TestLoadLimits(t *testing.T) {
|
||||||
fehlendeDatei := filepath.Join(t.TempDir(), "gibt-es-nicht.toml")
|
cfg, err := Load(Options{File: missingFile(t), Getenv: env(nil)})
|
||||||
writeTOML := func(t *testing.T, content string) string {
|
|
||||||
path := filepath.Join(t.TempDir(), "config.toml")
|
|
||||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return path
|
|
||||||
}
|
|
||||||
|
|
||||||
cfg, err := Load(Options{File: fehlendeDatei, Getenv: env(nil)})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if cfg.Queue.MaxText != DefaultMaxText || cfg.Queue.MaxAge != DefaultMaxAge {
|
if cfg.Queue.MaxText != DefaultMaxText || cfg.Queue.MaxAge != DefaultMaxAge {
|
||||||
t.Errorf("Defaults = %d/%v, want %d/%v", cfg.Queue.MaxText, cfg.Queue.MaxAge, DefaultMaxText, DefaultMaxAge)
|
t.Errorf("defaults = %d/%v, want %d/%v", cfg.Queue.MaxText, cfg.Queue.MaxAge, DefaultMaxText, DefaultMaxAge)
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg, err = Load(Options{File: writeTOML(t, "[queue]\nmax_text = 0\nmax_age = \"45s\"\n"), Getenv: env(nil)})
|
cfg, err = Load(Options{File: writeTOML(t, "[queue]\nmax_text = 0\nmax_age = \"45s\"\n"), Getenv: env(nil)})
|
||||||
@@ -769,20 +583,89 @@ func TestLoadLimits(t *testing.T) {
|
|||||||
t.Fatalf("Load: %v", err)
|
t.Fatalf("Load: %v", err)
|
||||||
}
|
}
|
||||||
if cfg.Queue.MaxText != 250 || cfg.Queue.MaxAge != 0 {
|
if cfg.Queue.MaxText != 250 || cfg.Queue.MaxAge != 0 {
|
||||||
t.Errorf("Env = %d/%v, want 250/0 (Env schlägt Datei)", cfg.Queue.MaxText, cfg.Queue.MaxAge)
|
t.Errorf("env = %d/%v, want 250/0 (env beats file)", cfg.Queue.MaxText, cfg.Queue.MaxAge)
|
||||||
}
|
}
|
||||||
|
|
||||||
for name, kv := range map[string]map[string]string{
|
for name, kv := range map[string]map[string]string{
|
||||||
"TALK_MAX_TEXT=abc": {"TALK_MAX_TEXT": "abc"},
|
"TALK_MAX_TEXT=abc": {"TALK_MAX_TEXT": "abc"},
|
||||||
"TALK_MAX_TEXT=-1": {"TALK_MAX_TEXT": "-1"},
|
"TALK_MAX_TEXT=-1": {"TALK_MAX_TEXT": "-1"},
|
||||||
"TALK_MAX_AGE=bald": {"TALK_MAX_AGE": "bald"},
|
"TALK_MAX_AGE=soon": {"TALK_MAX_AGE": "soon"},
|
||||||
"TALK_MAX_AGE=-1s": {"TALK_MAX_AGE": "-1s"},
|
"TALK_MAX_AGE=-1s": {"TALK_MAX_AGE": "-1s"},
|
||||||
} {
|
} {
|
||||||
if _, err := Load(Options{File: fehlendeDatei, Getenv: env(kv)}); err == nil {
|
if _, err := Load(Options{File: missingFile(t), Getenv: env(kv)}); err == nil {
|
||||||
t.Errorf("%s: kein Fehler, want klarer Fehler", name)
|
t.Errorf("%s: no error, want a clear error", name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if _, err := Load(Options{File: writeTOML(t, "[queue]\nmax_text = -5\n"), Getenv: env(nil)}); err == nil {
|
if _, err := Load(Options{File: writeTOML(t, "[queue]\nmax_text = -5\n"), Getenv: env(nil)}); err == nil {
|
||||||
t.Error("max_text = -5 in TOML: kein Fehler, want klarer Fehler")
|
t.Error("max_text = -5 in TOML: no error, want a clear error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLoadLang covers the fallback language: default en, TOML, env
|
||||||
|
// TALK_LANG beats the file, anything but de/en is an error.
|
||||||
|
func TestLoadLang(t *testing.T) {
|
||||||
|
cfg, err := Load(Options{File: missingFile(t), Getenv: env(nil)})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Load: %v", err)
|
||||||
|
}
|
||||||
|
if cfg.Lang != "en" {
|
||||||
|
t.Errorf("Lang = %q, want default en", cfg.Lang)
|
||||||
|
}
|
||||||
|
cfg, err = Load(Options{File: writeTOML(t, "lang = \"de\"\n"), Getenv: env(nil)})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Load: %v", err)
|
||||||
|
}
|
||||||
|
if cfg.Lang != "de" {
|
||||||
|
t.Errorf("Lang = %q, want de from TOML", cfg.Lang)
|
||||||
|
}
|
||||||
|
cfg, err = Load(Options{File: writeTOML(t, "lang = \"de\"\n"), Getenv: env(map[string]string{"TALK_LANG": "en"})})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Load: %v", err)
|
||||||
|
}
|
||||||
|
if cfg.Lang != "en" {
|
||||||
|
t.Errorf("Lang = %q, want en from env", cfg.Lang)
|
||||||
|
}
|
||||||
|
if _, err := Load(Options{File: missingFile(t), Getenv: env(map[string]string{"TALK_LANG": "fr"})}); err == nil || !strings.Contains(err.Error(), "lang") {
|
||||||
|
t.Errorf("TALK_LANG=fr: error = %v, want a clear lang error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLoadNotify covers [notify] on_speak: default on, TOML off, env
|
||||||
|
// TALK_NOTIFY beats the file, garbage is an error.
|
||||||
|
func TestLoadNotify(t *testing.T) {
|
||||||
|
cfg, err := Load(Options{File: missingFile(t), Getenv: env(nil)})
|
||||||
|
if err != nil || !cfg.Notify.OnSpeak {
|
||||||
|
t.Fatalf("default = %+v (%v), want on_speak true", cfg.Notify, err)
|
||||||
|
}
|
||||||
|
cfg, err = Load(Options{File: writeTOML(t, "[notify]\non_speak = false\n"), Getenv: env(nil)})
|
||||||
|
if err != nil || cfg.Notify.OnSpeak {
|
||||||
|
t.Errorf("TOML = %+v (%v), want on_speak false", cfg.Notify, err)
|
||||||
|
}
|
||||||
|
cfg, err = Load(Options{File: writeTOML(t, "[notify]\non_speak = false\n"), Getenv: env(map[string]string{"TALK_NOTIFY": "true"})})
|
||||||
|
if err != nil || !cfg.Notify.OnSpeak {
|
||||||
|
t.Errorf("env = %+v (%v), want on_speak true (env beats file)", cfg.Notify, err)
|
||||||
|
}
|
||||||
|
if _, err := Load(Options{File: missingFile(t), Getenv: env(map[string]string{"TALK_NOTIFY": "maybe"})}); err == nil {
|
||||||
|
t.Error("TALK_NOTIFY=maybe: no error, want a clear error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLoadReportsUnknownKeys: keys talk does not know are collected (not an
|
||||||
|
// error), including the classic trap of a top-level key written below a
|
||||||
|
// [table] header.
|
||||||
|
func TestLoadReportsUnknownKeys(t *testing.T) {
|
||||||
|
cfg, err := Load(Options{File: writeTOML(t, "[voice]\nlang = \"de\"\n[voice.edge]\nde = \"de-DE-KatjaNeural\"\nvolume = \"loud\"\n\n[typo]\nvalue = 1\n"), Getenv: env(nil)})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Load: %v", err)
|
||||||
|
}
|
||||||
|
if strings.Join(cfg.Unknown, ",") != "typo.value,voice.edge.volume,voice.lang" {
|
||||||
|
t.Errorf("Unknown = %v, want [typo.value voice.edge.volume voice.lang]", cfg.Unknown)
|
||||||
|
}
|
||||||
|
if cfg.Lang != "en" {
|
||||||
|
t.Errorf("Lang = %q; the misplaced key must not leak into the top level", cfg.Lang)
|
||||||
|
}
|
||||||
|
cfg, _ = Load(Options{File: writeTOML(t, "lang = \"de\"\n"), Getenv: env(nil)})
|
||||||
|
if len(cfg.Unknown) != 0 {
|
||||||
|
t.Errorf("Unknown = %v for a clean file, want none", cfg.Unknown)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,5 @@
|
|||||||
// Package config implementiert die Config-Auflösung von talk: Defaults +
|
// Package config resolves talk's configuration in layers: built-in defaults,
|
||||||
// optionale config.toml im platform-nativen Verzeichnis (~/.config/talk,
|
// then the optional config.toml in the platform-native config directory,
|
||||||
// ~/Library/Application Support/talk, %APPDATA%\talk) + Env-Overrides
|
// then TALK_* environment variables (which win). It validates the result and
|
||||||
// (TALK_*); Env schlägt Datei. Pfade und Env sind injizierbar (Tests).
|
// reports problems as clear errors instead of silently falling back.
|
||||||
// Voice-Mapping voice.<provider>.<lang> und Provider-Endpunkte folgen mit
|
|
||||||
// Task 03.
|
|
||||||
package config
|
package config
|
||||||
+14
-15
@@ -6,26 +6,25 @@ import (
|
|||||||
"runtime"
|
"runtime"
|
||||||
)
|
)
|
||||||
|
|
||||||
// fileName ist der Name der Config-Datei im Config-Verzeichnis.
|
// fileName is the config file's name inside the config directory.
|
||||||
const fileName = "config.toml"
|
const fileName = "config.toml"
|
||||||
|
|
||||||
// ErrNoHome meldet, dass das Heimatverzeichnis nicht bestimmt werden kann
|
// ErrNoHome reports that the home directory cannot be determined (no HOME or
|
||||||
// (keine HOME- bzw. APPDATA-Umgebungsvariable).
|
// APPDATA environment variable).
|
||||||
var ErrNoHome = errors.New("Config-Verzeichnis nicht bestimmbar (HOME bzw. APPDATA fehlt)")
|
var ErrNoHome = errors.New("config directory unknown (HOME or APPDATA not set)")
|
||||||
|
|
||||||
// Dir liefert das platform-native Config-Verzeichnis von talk auf dem
|
// Dir returns talk's platform-native config directory: ~/.config/talk on
|
||||||
// aktuellen System: Linux ~/.config/talk (respektive $XDG_CONFIG_HOME/talk),
|
// Linux (or $XDG_CONFIG_HOME/talk), ~/Library/Application Support/talk on
|
||||||
// macOS ~/Library/Application Support/talk, Windows %APPDATA%\talk.
|
// macOS, %APPDATA%\talk on Windows.
|
||||||
func Dir(getenv func(string) string) (string, error) {
|
func Dir(getenv func(string) string) (string, error) {
|
||||||
return dirFor(runtime.GOOS, getenv)
|
return dirFor(runtime.GOOS, getenv)
|
||||||
}
|
}
|
||||||
|
|
||||||
// dirFor ist die testbare Plattformlogik hinter Dir: goos wird als
|
// dirFor is the testable platform logic behind Dir: goos is a parameter so
|
||||||
// Parameter übergeben, damit die Pfade für alle Betriebssysteme vom
|
// all platforms can be table-tested from one host.
|
||||||
// Dev-Host aus tischgesteuert geprüft werden können.
|
|
||||||
//
|
//
|
||||||
// XDG_CONFIG_HOME wird nur berücksichtigt, wenn es einen absoluten Pfad
|
// XDG_CONFIG_HOME is honoured only when it holds an absolute path (XDG
|
||||||
// enthält (XDG-Spezifikation); relative Werte werden ignoriert.
|
// spec); relative values are ignored.
|
||||||
func dirFor(goos string, getenv func(string) string) (string, error) {
|
func dirFor(goos string, getenv func(string) string) (string, error) {
|
||||||
if getenv == nil {
|
if getenv == nil {
|
||||||
return "", ErrNoHome
|
return "", ErrNoHome
|
||||||
@@ -43,7 +42,7 @@ func dirFor(goos string, getenv func(string) string) (string, error) {
|
|||||||
return "", ErrNoHome
|
return "", ErrNoHome
|
||||||
}
|
}
|
||||||
return filepath.Join(home, "Library", "Application Support", "talk"), nil
|
return filepath.Join(home, "Library", "Application Support", "talk"), nil
|
||||||
default: // linux und sonstige unixartige Systeme
|
default: // linux and other unix-likes
|
||||||
if xdg := getenv("XDG_CONFIG_HOME"); xdg != "" && filepath.IsAbs(xdg) {
|
if xdg := getenv("XDG_CONFIG_HOME"); xdg != "" && filepath.IsAbs(xdg) {
|
||||||
return filepath.Join(xdg, "talk"), nil
|
return filepath.Join(xdg, "talk"), nil
|
||||||
}
|
}
|
||||||
@@ -55,8 +54,8 @@ func dirFor(goos string, getenv func(string) string) (string, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Path liefert den vollständigen Pfad der config.toml im platform-nativen
|
// Path returns the full path of config.toml in the config directory
|
||||||
// Config-Verzeichnis (Diagnose, Setup-Wizard).
|
// (diagnostics, setup).
|
||||||
func Path(getenv func(string) string) (string, error) {
|
func Path(getenv func(string) string) (string, error) {
|
||||||
dir, err := Dir(getenv)
|
dir, err := Dir(getenv)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
+98
-57
@@ -1,9 +1,9 @@
|
|||||||
// Package daemon ist der Hintergrundprozess von talk: HTTP-API auf
|
// Package daemon is talk's background process: HTTP API on 127.0.0.1, a
|
||||||
// 127.0.0.1, serialisierte Ansage-Queue mit Prioritäten und now-Sprung,
|
// serialized announcement queue with priorities and the now jump,
|
||||||
// persistenter Mute-State, die Anti-Spam-Gesetze (Rate-Limit, Ruhezeiten),
|
// persistent mute state, the anti-spam laws (rate limit, quiet hours), the
|
||||||
// CORS-Tür und MCP-Endpoint. Es gibt genau ein Binary: `talk daemon run`
|
// CORS door and the MCP endpoint. There is exactly one binary: `talk daemon
|
||||||
// betreibt den Daemon im Vordergrund, die CLI startet ihn mit Spawn bei
|
// run` runs the daemon in the foreground, and the CLI starts it in the
|
||||||
// Bedarf selbst im Hintergrund (daemon.autostart).
|
// background itself via Spawn when needed (daemon.autostart).
|
||||||
package daemon
|
package daemon
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -28,37 +28,38 @@ import (
|
|||||||
"code.m3ta.dev/m3tam3re/talk/internal/speak"
|
"code.m3ta.dev/m3tam3re/talk/internal/speak"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Dateien des Daemons im Config-Verzeichnis.
|
// Files of the daemon in the config directory.
|
||||||
const (
|
const (
|
||||||
// LogFileName ist das Protokoll eines im Hintergrund gestarteten
|
// LogFileName is the log of a daemon started in the background (Spawn
|
||||||
// Daemons (Spawn leitet stdout/stderr dorthin; pro Start neu).
|
// redirects stdout/stderr there; fresh per start).
|
||||||
LogFileName = "daemon.log"
|
LogFileName = "daemon.log"
|
||||||
|
|
||||||
// PIDFileName hält die Prozess-ID des laufenden Daemons (für
|
// PIDFileName holds the process ID of the running daemon (for
|
||||||
// Diagnose und als Notbremse, wenn die HTTP-API nicht antwortet).
|
// diagnostics and as an emergency brake when the HTTP API does not
|
||||||
|
// answer).
|
||||||
PIDFileName = "daemon.pid"
|
PIDFileName = "daemon.pid"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Options sind die Abhängigkeiten von Run.
|
// Options are the dependencies of Run.
|
||||||
type Options struct {
|
type Options struct {
|
||||||
// Config ist die geladene Konfiguration (Port, Gesetze, Sink, …).
|
// Config is the loaded configuration (port, laws, sink, ...).
|
||||||
Config config.Config
|
Config config.Config
|
||||||
|
|
||||||
// Getenv liefert Keys und Endpunkt-Overrides (nil = os.Getenv).
|
// Getenv supplies keys and endpoint overrides (nil = os.Getenv).
|
||||||
Getenv func(string) string
|
Getenv func(string) string
|
||||||
|
|
||||||
// Version ist die Daemon-Version für /status und MCP serverInfo.
|
// Version is the daemon version for /status and MCP serverInfo.
|
||||||
Version string
|
Version string
|
||||||
|
|
||||||
// Log empfängt das Protokoll (Vordergrund: stderr; Hintergrund: die
|
// Log receives the log output (foreground: stderr; background: the log
|
||||||
// Log-Datei). nil = os.Stderr.
|
// file). nil = os.Stderr.
|
||||||
Log io.Writer
|
Log io.Writer
|
||||||
}
|
}
|
||||||
|
|
||||||
// Run betreibt den Daemon, bis ctx endet (Signal), POST /shutdown kommt
|
// Run runs the daemon until ctx ends (signal), POST /shutdown arrives or
|
||||||
// oder der HTTP-Server scheitert. Eine laufende Ansage wird beim
|
// the HTTP server fails. A playing announcement is cancelled on shutdown;
|
||||||
// Herunterfahren abgebrochen — der Daemon soll prompt reagieren. Ein
|
// the daemon should react promptly. A port in use is a clear error ("is
|
||||||
// belegter Port ist ein klarer Fehler („läuft bereits ein Daemon?").
|
// another daemon running?").
|
||||||
func Run(ctx context.Context, opts Options) error {
|
func Run(ctx context.Context, opts Options) error {
|
||||||
getenv := opts.Getenv
|
getenv := opts.Getenv
|
||||||
if getenv == nil {
|
if getenv == nil {
|
||||||
@@ -77,13 +78,54 @@ func Run(ctx context.Context, opts Options) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Anti-Spam-Gesetz: config.Load hat quiet_hours validiert — ein Fehler
|
// Anti-spam law: config.Load has validated quiet_hours; an error here
|
||||||
// hier ist praktisch unmöglich, darf aber nie still werden.
|
// is practically impossible but must never be silent.
|
||||||
quiet, err := queue.ParseQuietHours(cfg.QuietHours)
|
quiet, err := queue.ParseQuietHours(cfg.QuietHours)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
q := queue.New(queue.Laws{
|
// Desktop side: the icon next to the config, Windows additionally the
|
||||||
|
// toast identity and the talk: protocol handler for the Cancel button.
|
||||||
|
if dir, err := config.Dir(getenv); err == nil {
|
||||||
|
exe, _ := os.Executable()
|
||||||
|
if err := notify.Setup(dir, exe); err != nil {
|
||||||
|
logger.Printf("warning: %v; notifications fall back to the plain identity or lose the Cancel button", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Desktop notification per announcement (notify.on_speak): shown when the
|
||||||
|
// announcement starts, with a Cancel button where the platform has one,
|
||||||
|
// closed when it ends. Best effort: the first failure is logged, later
|
||||||
|
// ones are silent, speech never waits for a notification problem.
|
||||||
|
var q *queue.Queue
|
||||||
|
var notifyFailed sync.Once
|
||||||
|
announceNotification := func(ctx context.Context, item queue.Item, lang string) func() {
|
||||||
|
if !cfg.Notify.OnSpeak {
|
||||||
|
return func() {}
|
||||||
|
}
|
||||||
|
label := "Cancel"
|
||||||
|
if lang == "de" {
|
||||||
|
label = "Abbrechen"
|
||||||
|
}
|
||||||
|
closeFn, err := notify.Announce(ctx, notify.Announcement{
|
||||||
|
Text: item.Text,
|
||||||
|
CancelLabel: label,
|
||||||
|
CancelURI: fmt.Sprintf("talk:cancel?id=%s&port=%d", item.ID, cfg.Server.Port),
|
||||||
|
Tag: item.ID,
|
||||||
|
}, func() {
|
||||||
|
if q.CancelItem(item.ID) {
|
||||||
|
logger.Printf("announcement %s cancelled from its notification", item.ID)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
notifyFailed.Do(func() {
|
||||||
|
logger.Printf("warning: notifications unavailable (%v); announcements play without one. Set [notify] on_speak = false to silence this", err)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return closeFn
|
||||||
|
}
|
||||||
|
|
||||||
|
q = queue.New(queue.Laws{
|
||||||
RateLimit: cfg.Queue.RateLimit,
|
RateLimit: cfg.Queue.RateLimit,
|
||||||
AllowHighBurst: cfg.Queue.AllowHighBurst,
|
AllowHighBurst: cfg.Queue.AllowHighBurst,
|
||||||
Quiet: quiet,
|
Quiet: quiet,
|
||||||
@@ -91,22 +133,20 @@ func Run(ctx context.Context, opts Options) error {
|
|||||||
MaxText: cfg.Queue.MaxText,
|
MaxText: cfg.Queue.MaxText,
|
||||||
MaxAge: cfg.Queue.MaxAge,
|
MaxAge: cfg.Queue.MaxAge,
|
||||||
}, func(ctx context.Context, item queue.Item) error {
|
}, func(ctx context.Context, item queue.Item) error {
|
||||||
out, err := engine.Speak(ctx, speak.Request{
|
req := speak.Request{Text: item.Text, Lang: item.Lang, Provider: item.Provider, Voice: item.Voice}
|
||||||
Text: item.Text,
|
closeNotification := announceNotification(ctx, item, engine.Lang(req))
|
||||||
Lang: item.Lang,
|
defer closeNotification()
|
||||||
Provider: item.Provider,
|
out, err := engine.Speak(ctx, req)
|
||||||
Voice: item.Voice,
|
|
||||||
})
|
|
||||||
if err == nil && !out.Discarded {
|
if err == nil && !out.Discarded {
|
||||||
logger.Printf("ansage %s über %s (synthese %s, wiedergabe %s)", item.ID, out.Provider,
|
logger.Printf("announcement %s via %s (synthesis %s, playback %s)", item.ID, out.Provider,
|
||||||
out.Synthesis.Round(time.Millisecond), out.Playback.Round(time.Millisecond))
|
out.Synthesis.Round(time.Millisecond), out.Playback.Round(time.Millisecond))
|
||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
}, lw)
|
}, lw)
|
||||||
|
|
||||||
// Ruhezeit-Toast: Desktop-Benachrichtigung statt Audio (quiet_mode =
|
// Quiet-hours toast: desktop notification instead of audio (quiet_mode
|
||||||
// "toast"); best effort, Fehler nur im Protokoll. Läuft asynchron, damit
|
// = "toast"); best effort, errors only in the log. Runs asynchronously
|
||||||
// ein hängender Notification-Daemon nie die Queue blockiert.
|
// so a hanging notification daemon never blocks the queue.
|
||||||
if cfg.QuietMode == queue.QuietModeToast {
|
if cfg.QuietMode == queue.QuietModeToast {
|
||||||
if notify.Available() {
|
if notify.Available() {
|
||||||
q.OnToast(func(item queue.Item) {
|
q.OnToast(func(item queue.Item) {
|
||||||
@@ -117,18 +157,19 @@ func Run(ctx context.Context, opts Options) error {
|
|||||||
}()
|
}()
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
logger.Printf("warnung: quiet_mode = toast, aber %s — Ruhezeit-Ansagen werden nur protokolliert", notify.Describe())
|
logger.Printf("warning: quiet_mode = toast, but %s; quiet-hours announcements are only logged", notify.Describe())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Persistenter Mute-State und PID-Datei im Config-Dir. Ohne Config-Dir
|
// Persistent mute state and PID file in the config dir. Without a
|
||||||
// läuft der Daemon ohne beides weiter (Warnung) statt zu scheitern.
|
// config dir the daemon keeps running without both (warning) instead
|
||||||
|
// of failing.
|
||||||
var mutePath, pidPath string
|
var mutePath, pidPath string
|
||||||
if dir, err := config.Dir(getenv); err == nil {
|
if dir, err := config.Dir(getenv); err == nil {
|
||||||
mutePath = filepath.Join(dir, queue.MuteFileName)
|
mutePath = filepath.Join(dir, queue.MuteFileName)
|
||||||
pidPath = filepath.Join(dir, PIDFileName)
|
pidPath = filepath.Join(dir, PIDFileName)
|
||||||
} else {
|
} else {
|
||||||
logger.Printf("warnung: Config-Dir nicht bestimmbar — Mute-State und PID-Datei deaktiviert (%v)", err)
|
logger.Printf("warning: config directory unknown; mute state and PID file disabled (%v)", err)
|
||||||
}
|
}
|
||||||
mute := queue.MuteStore{Path: mutePath}
|
mute := queue.MuteStore{Path: mutePath}
|
||||||
|
|
||||||
@@ -156,12 +197,12 @@ func Run(ctx context.Context, opts Options) error {
|
|||||||
ln, err := net.Listen("tcp", addr)
|
ln, err := net.Listen("tcp", addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
q.Close()
|
q.Close()
|
||||||
return fmt.Errorf("Port belegen (%s): %w — läuft bereits ein talk daemon?", addr, err)
|
return fmt.Errorf("bind %s: %w; is another talk daemon running?", addr, err)
|
||||||
}
|
}
|
||||||
if pidPath != "" {
|
if pidPath != "" {
|
||||||
writePID(pidPath, logger)
|
writePID(pidPath, logger)
|
||||||
// Die PID-Datei verschwindet als Letztes — `talk daemon stop`
|
// The PID file disappears last: `talk daemon stop` waits for that
|
||||||
// wartet darauf und weiß dann: Prozess ist fertig, nicht nur HTTP.
|
// and then knows the process is done, not just HTTP.
|
||||||
defer os.Remove(pidPath)
|
defer os.Remove(pidPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,12 +210,12 @@ func Run(ctx context.Context, opts Options) error {
|
|||||||
errCh := make(chan error, 1)
|
errCh := make(chan error, 1)
|
||||||
go func() { errCh <- srv.Serve(ln) }()
|
go func() { errCh <- srv.Serve(ln) }()
|
||||||
|
|
||||||
corsLog := "zu (kein CORS)"
|
corsLog := "closed (no CORS)"
|
||||||
if len(cfg.Server.AllowedOrigins) > 0 {
|
if len(cfg.Server.AllowedOrigins) > 0 {
|
||||||
corsLog = fmt.Sprintf("%v", cfg.Server.AllowedOrigins)
|
corsLog = fmt.Sprintf("%v", cfg.Server.AllowedOrigins)
|
||||||
}
|
}
|
||||||
logger.Printf("listening on http://%s (version %s, pid %d, audio sink %s, mute=%v, rate-limit %s, high-burst=%v, max-text %d, max-age %s, ruhezeit=%q modus %s, cors=%s, mcp=/mcp)",
|
logger.Printf("listening on http://%s (version %s, pid %d, audio sink %s, mute=%v, notify=%v, rate-limit %s, high-burst=%v, max-text %d, max-age %s, quiet-hours=%q mode %s, cors=%s, mcp=/mcp)",
|
||||||
addr, opts.Version, os.Getpid(), engine.SinkName(), mute.Muted(),
|
addr, opts.Version, os.Getpid(), engine.SinkName(), mute.Muted(), cfg.Notify.OnSpeak,
|
||||||
cfg.Queue.RateLimit, cfg.Queue.AllowHighBurst, cfg.Queue.MaxText, cfg.Queue.MaxAge, cfg.QuietHours, cfg.QuietMode, corsLog)
|
cfg.Queue.RateLimit, cfg.Queue.AllowHighBurst, cfg.Queue.MaxText, cfg.Queue.MaxAge, cfg.QuietHours, cfg.QuietMode, corsLog)
|
||||||
|
|
||||||
select {
|
select {
|
||||||
@@ -182,14 +223,14 @@ func Run(ctx context.Context, opts Options) error {
|
|||||||
q.Close()
|
q.Close()
|
||||||
return fmt.Errorf("http server: %w", err)
|
return fmt.Errorf("http server: %w", err)
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
logger.Printf("Signal empfangen — fahre herunter (laufende Ansage wird abgebrochen)")
|
logger.Printf("signal received; shutting down (the playing announcement is cancelled)")
|
||||||
case <-shutdown:
|
case <-shutdown:
|
||||||
logger.Printf("Shutdown angefordert (talk daemon stop) — fahre herunter")
|
logger.Printf("shutdown requested (talk daemon stop); shutting down")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reihenfolge: erst HTTP dicht (keine neuen Anfragen), dann die Queue
|
// Order: close HTTP first (no new requests), then close the queue
|
||||||
// schließen (laufende Ansage abbrechen, Worker beenden und darauf
|
// (cancel the playing announcement, stop the worker and wait for it).
|
||||||
// warten). So läuft nie eine Ansage nach dem Daemon-Ende weiter.
|
// That way no announcement ever keeps playing after the daemon ends.
|
||||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||||
@@ -199,19 +240,19 @@ func Run(ctx context.Context, opts Options) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// writePID schreibt die eigene Prozess-ID (best effort; ein Fehler ist nur
|
// writePID writes our own process ID (best effort; an error is only a log
|
||||||
// eine Protokollzeile — der Daemon funktioniert auch ohne PID-Datei).
|
// line, the daemon works without a PID file too).
|
||||||
func writePID(path string, logger *log.Logger) {
|
func writePID(path string, logger *log.Logger) {
|
||||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||||
logger.Printf("warnung: PID-Datei: %v", err)
|
logger.Printf("warning: PID file: %v", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := os.WriteFile(path, []byte(strconv.Itoa(os.Getpid())+"\n"), 0o644); err != nil {
|
if err := os.WriteFile(path, []byte(strconv.Itoa(os.Getpid())+"\n"), 0o644); err != nil {
|
||||||
logger.Printf("warnung: PID-Datei: %v", err)
|
logger.Printf("warning: PID file: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReadPID liest die PID-Datei; 0, wenn keine (lesbare) Datei existiert.
|
// ReadPID reads the PID file; 0 if no (readable) file exists.
|
||||||
func ReadPID(dir string) int {
|
func ReadPID(dir string) int {
|
||||||
b, err := os.ReadFile(filepath.Join(dir, PIDFileName))
|
b, err := os.ReadFile(filepath.Join(dir, PIDFileName))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -224,9 +265,9 @@ func ReadPID(dir string) int {
|
|||||||
return pid
|
return pid
|
||||||
}
|
}
|
||||||
|
|
||||||
// lineWriter reicht Zeilen an den Logger weiter (Zeitstempel + Präfix),
|
// lineWriter forwards lines to the logger (timestamp + prefix) instead of
|
||||||
// statt sie roh zu schreiben: Provider-Kette, Queue und null-Sink schreiben
|
// writing them raw: provider chain, queue and null sink write line by line,
|
||||||
// zeilenweise, so entsteht ein einheitliches Protokoll.
|
// which yields one uniform log.
|
||||||
type lineWriter struct{ l *log.Logger }
|
type lineWriter struct{ l *log.Logger }
|
||||||
|
|
||||||
func (w lineWriter) Write(p []byte) (int, error) {
|
func (w lineWriter) Write(p []byte) (int, error) {
|
||||||
|
|||||||
+30
-19
@@ -6,34 +6,45 @@ import (
|
|||||||
"os/exec"
|
"os/exec"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Spawn startet `exe daemon run` als eigenständigen Hintergrundprozess
|
// Spawn starts `exe daemon run` as an independent background process (own
|
||||||
// (eigene Session bzw. eigene Prozessgruppe, losgelöst vom Terminal), mit
|
// session or own process group, detached from the terminal), with
|
||||||
// stdout/stderr in die Log-Datei logPath (pro Start neu angelegt; leer =
|
// stdout/stderr going to the log file logPath (created fresh per start;
|
||||||
// verwerfen). env ist die Umgebung des Kindes (Keys, TALK_*-Overrides).
|
// empty = discard). env is the child's environment (keys, TALK_*
|
||||||
|
// overrides).
|
||||||
//
|
//
|
||||||
// Rückgabe ist ein Kanal, der genau einmal das Wait-Ergebnis liefert, wenn
|
// The return value is a channel that delivers the Wait result exactly once
|
||||||
// das Kind endet — der Aufrufer erkennt daran einen fehlgeschlagenen Start
|
// when the child exits; the caller uses it to detect a failed start (e.g.
|
||||||
// (z. B. Port belegt), ohne auf einen Timeout warten zu müssen. Endet der
|
// port in use) without waiting for a timeout. If the caller exits first,
|
||||||
// Aufrufer zuerst, läuft der Daemon weiter (das ist der Zweck).
|
// the daemon keeps running (that is the point).
|
||||||
func Spawn(exe, logPath string, env []string) (<-chan error, error) {
|
func Spawn(exe, logPath string, env []string) (<-chan error, error) {
|
||||||
var logFile *os.File
|
|
||||||
if logPath == "" {
|
if logPath == "" {
|
||||||
logPath = os.DevNull
|
logPath = os.DevNull
|
||||||
}
|
}
|
||||||
logFile, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
|
logFile, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("Daemon-Log %s: %w", logPath, err)
|
return nil, fmt.Errorf("daemon log %s: %w", logPath, err)
|
||||||
}
|
}
|
||||||
defer logFile.Close() // das Kind hält sein eigenes Handle
|
defer logFile.Close() // the child holds its own handle
|
||||||
|
|
||||||
cmd := exec.Command(exe, "daemon", "run")
|
// First attempt: fully detached, including a breakaway from the parent's
|
||||||
cmd.Env = env
|
// job object (Windows). Shells such as WinRM, SSH servers or CI runners
|
||||||
cmd.Stdin = nil
|
// put children into a job that is terminated with the session; the
|
||||||
cmd.Stdout = logFile
|
// breakaway lets the daemon outlive it. If the job forbids breakaway,
|
||||||
cmd.Stderr = logFile
|
// CreateProcess fails, and the second attempt starts without it.
|
||||||
detach(cmd)
|
var cmd *exec.Cmd
|
||||||
if err := cmd.Start(); err != nil {
|
for _, breakaway := range []bool{true, false} {
|
||||||
return nil, fmt.Errorf("Daemon starten (%s daemon run): %w", exe, err)
|
cmd = exec.Command(exe, "daemon", "run")
|
||||||
|
cmd.Env = env
|
||||||
|
cmd.Stdin = nil
|
||||||
|
cmd.Stdout = logFile
|
||||||
|
cmd.Stderr = logFile
|
||||||
|
detach(cmd, breakaway)
|
||||||
|
if err = cmd.Start(); err == nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("starting daemon (%s daemon run): %w", exe, err)
|
||||||
}
|
}
|
||||||
exited := make(chan error, 1)
|
exited := make(chan error, 1)
|
||||||
go func() { exited <- cmd.Wait() }()
|
go func() { exited <- cmd.Wait() }()
|
||||||
|
|||||||
@@ -4,5 +4,5 @@ package daemon
|
|||||||
|
|
||||||
import "os/exec"
|
import "os/exec"
|
||||||
|
|
||||||
// detach ist auf dieser Plattform ein No-op (kein Setsid, keine Konsole).
|
// detach is a no-op on this platform (no Setsid, no console).
|
||||||
func detach(*exec.Cmd) {}
|
func detach(*exec.Cmd, bool) {}
|
||||||
@@ -7,8 +7,9 @@ import (
|
|||||||
"syscall"
|
"syscall"
|
||||||
)
|
)
|
||||||
|
|
||||||
// detach löst das Kind vom Terminal: eigene Session (kein SIGHUP beim
|
// detach detaches the child from the terminal (the breakaway flag is a
|
||||||
// Schließen des Terminals, kein Ctrl-C der Shell).
|
// Windows concept and ignored here): own session (no SIGHUP when
|
||||||
func detach(cmd *exec.Cmd) {
|
// the terminal closes, no Ctrl-C from the shell).
|
||||||
|
func detach(cmd *exec.Cmd, _ bool) {
|
||||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
|
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
|
||||||
}
|
}
|
||||||
@@ -7,14 +7,22 @@ import (
|
|||||||
"syscall"
|
"syscall"
|
||||||
)
|
)
|
||||||
|
|
||||||
// detachedProcess ist das Win32-Flag DETACHED_PROCESS: kein Konsolenfenster,
|
// detachedProcess is the Win32 flag DETACHED_PROCESS: no console window, no
|
||||||
// keine Bindung an die Konsole des Aufrufers.
|
// binding to the caller's console.
|
||||||
const detachedProcess = 0x00000008
|
const detachedProcess = 0x00000008
|
||||||
|
|
||||||
// detach löst das Kind von der Konsole: eigene Prozessgruppe (kein Ctrl-C
|
// createBreakawayFromJob is the Win32 flag CREATE_BREAKAWAY_FROM_JOB: the
|
||||||
// der Shell) und keine Konsole (kein aufblitzendes Fenster).
|
// child leaves the parent's job object, so a session-bound job (WinRM, SSH,
|
||||||
func detach(cmd *exec.Cmd) {
|
// CI) does not take the daemon down with it. Only works when the job allows
|
||||||
cmd.SysProcAttr = &syscall.SysProcAttr{
|
// it; Spawn falls back to a start without the flag otherwise.
|
||||||
CreationFlags: syscall.CREATE_NEW_PROCESS_GROUP | detachedProcess,
|
const createBreakawayFromJob = 0x01000000
|
||||||
|
|
||||||
|
// detach detaches the child from the console: own process group (no Ctrl-C
|
||||||
|
// from the shell) and no console (no flashing window).
|
||||||
|
func detach(cmd *exec.Cmd, breakaway bool) {
|
||||||
|
flags := uint32(syscall.CREATE_NEW_PROCESS_GROUP | detachedProcess)
|
||||||
|
if breakaway {
|
||||||
|
flags |= createBreakawayFromJob
|
||||||
}
|
}
|
||||||
|
cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: flags}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// Package icon carries the talk icon for the desktop: the PNG is embedded
|
||||||
|
// in the binary and written next to the config so the OS can show it in
|
||||||
|
// notifications (Windows toast identity, freedesktop app_icon). The source
|
||||||
|
// is assets/icon/talk.svg; `go run assets/icon/gen.go` renders it, the
|
||||||
|
// Windows .ico and the resource objects for talk.exe.
|
||||||
|
package icon
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
_ "embed"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed talk.png
|
||||||
|
var PNG []byte
|
||||||
|
|
||||||
|
// FileName is the icon's name in the config directory.
|
||||||
|
const FileName = "talk.png"
|
||||||
|
|
||||||
|
// Install writes the icon into dir (if missing or outdated) and returns its
|
||||||
|
// path. Idempotent: an unchanged file is not touched.
|
||||||
|
func Install(dir string) (string, error) {
|
||||||
|
if dir == "" {
|
||||||
|
return "", errors.New("icon: no directory")
|
||||||
|
}
|
||||||
|
path := filepath.Join(dir, FileName)
|
||||||
|
if cur, err := os.ReadFile(path); err == nil && bytes.Equal(cur, PNG) {
|
||||||
|
return path, nil
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, PNG, 0o644); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return path, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package icon
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestInstall: the icon lands in the directory, is left alone when current,
|
||||||
|
// and is repaired when the file on disk differs.
|
||||||
|
func TestInstall(t *testing.T) {
|
||||||
|
if len(PNG) < 8 || !bytes.HasPrefix(PNG, []byte("\x89PNG")) {
|
||||||
|
t.Fatalf("embedded icon is not a PNG (%d bytes)", len(PNG))
|
||||||
|
}
|
||||||
|
dir := filepath.Join(t.TempDir(), "talk")
|
||||||
|
path, err := Install(dir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if path != filepath.Join(dir, FileName) {
|
||||||
|
t.Errorf("path = %q", path)
|
||||||
|
}
|
||||||
|
got, err := os.ReadFile(path)
|
||||||
|
if err != nil || !bytes.Equal(got, PNG) {
|
||||||
|
t.Fatalf("installed file differs (err %v)", err)
|
||||||
|
}
|
||||||
|
first, _ := os.Stat(path)
|
||||||
|
if _, err := Install(dir); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
second, _ := os.Stat(path)
|
||||||
|
if !second.ModTime().Equal(first.ModTime()) {
|
||||||
|
t.Error("unchanged icon was rewritten")
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, []byte("stale"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := Install(dir); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got, _ = os.ReadFile(path)
|
||||||
|
if !bytes.Equal(got, PNG) {
|
||||||
|
t.Error("stale icon was not replaced")
|
||||||
|
}
|
||||||
|
if _, err := Install(""); err == nil {
|
||||||
|
t.Error("Install(\"\") succeeded")
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 4.0 KiB |
@@ -1,3 +1,7 @@
|
|||||||
|
// Package langdetect guesses whether an announcement is German or English.
|
||||||
|
// It is a pure function over two small word lists, deliberately without any
|
||||||
|
// ML: announcements are one or two sentences, and the only question is which
|
||||||
|
// voice should read them.
|
||||||
package langdetect
|
package langdetect
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -5,14 +9,12 @@ import (
|
|||||||
"unicode"
|
"unicode"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Detect erkennt die Sprache eines Ansage-Texts und liefert "de" oder "en".
|
// Detect returns "de" or "en" for text. Umlauts and ß count as strong German
|
||||||
// Default (auch bei leerem oder unentscheidbarem Text) ist "de".
|
// signals; otherwise common-word hits decide. English wins only with strictly
|
||||||
//
|
// more English than German hits; ties and undecidable text (empty, numbers,
|
||||||
// Heuristik: Common-Word-Listen deutscher und englischer Wörter plus
|
// punctuation) return fallback, which callers take from the configured
|
||||||
// Umlaute/ß als starke Deutsch-Signale. Englisch gewinnt nur bei strikt
|
// default language.
|
||||||
// mehr englischen Signalen als deutschen; bei Gleichstand entscheidet der
|
func Detect(text, fallback string) string {
|
||||||
// Default "de". Die Funktion ist rein (kein globaler Zustand, keine IO).
|
|
||||||
func Detect(text string) string {
|
|
||||||
var de, en int
|
var de, en int
|
||||||
for _, r := range text {
|
for _, r := range text {
|
||||||
switch r {
|
switch r {
|
||||||
@@ -33,14 +35,18 @@ func Detect(text string) string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if en > de {
|
switch {
|
||||||
|
case en > de:
|
||||||
return "en"
|
return "en"
|
||||||
|
case de > en:
|
||||||
|
return "de"
|
||||||
|
default:
|
||||||
|
return fallback
|
||||||
}
|
}
|
||||||
return "de"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// germanWords sind häufige deutsche Wörter, die im Englischen nicht
|
// germanWords are common German words that do not occur in English
|
||||||
// vorkommen (Mehrdeutigkeiten wie „was" und „in" wurden weggelassen).
|
// (ambiguous ones such as "was" and "in" are left out on purpose).
|
||||||
var germanWords = map[string]struct{}{
|
var germanWords = map[string]struct{}{
|
||||||
"der": {}, "die": {}, "das": {}, "und": {}, "nicht": {}, "ist": {},
|
"der": {}, "die": {}, "das": {}, "und": {}, "nicht": {}, "ist": {},
|
||||||
"ein": {}, "eine": {}, "einen": {}, "einem": {}, "einer": {},
|
"ein": {}, "eine": {}, "einen": {}, "einem": {}, "einer": {},
|
||||||
@@ -58,8 +64,7 @@ var germanWords = map[string]struct{}{
|
|||||||
"wurden": {}, "haben": {}, "geht": {}, "machen": {},
|
"wurden": {}, "haben": {}, "geht": {}, "machen": {},
|
||||||
}
|
}
|
||||||
|
|
||||||
// englishWords sind häufige englische Wörter, die im Deutschen nicht
|
// englishWords are common English words that do not occur in German.
|
||||||
// vorkommen.
|
|
||||||
var englishWords = map[string]struct{}{
|
var englishWords = map[string]struct{}{
|
||||||
"the": {}, "is": {}, "not": {}, "and": {}, "with": {}, "for": {},
|
"the": {}, "is": {}, "not": {}, "and": {}, "with": {}, "for": {},
|
||||||
"on": {}, "of": {}, "to": {}, "from": {}, "by": {}, "at": {},
|
"on": {}, "of": {}, "to": {}, "from": {}, "by": {}, "at": {},
|
||||||
|
|||||||
@@ -2,36 +2,38 @@ package langdetect
|
|||||||
|
|
||||||
import "testing"
|
import "testing"
|
||||||
|
|
||||||
// TestDetect ist tischgesteuert: Eingabetext → erwartete Sprache.
|
// TestDetect is table-driven: input text, expected language. The fallback
|
||||||
// Der Default "de" gilt für leeren, unentscheidbaren und gemischten
|
// applies to empty, undecidable and tied text; it is passed explicitly so
|
||||||
// Text ohne englische Mehrheit.
|
// the test pins both directions.
|
||||||
func TestDetect(t *testing.T) {
|
func TestDetect(t *testing.T) {
|
||||||
cases := []struct {
|
cases := []struct {
|
||||||
name string
|
name string
|
||||||
text string
|
text string
|
||||||
want string
|
fallback string
|
||||||
|
want string
|
||||||
}{
|
}{
|
||||||
{"leer", "", "de"},
|
{"empty → fallback de", "", "de", "de"},
|
||||||
{"nur whitespace", " \n\t ", "de"},
|
{"empty → fallback en", "", "en", "en"},
|
||||||
{"nur interpunktion", "!!! ??? ...", "de"},
|
{"whitespace only", " \n\t ", "en", "en"},
|
||||||
{"deutsch satz", "Der Build wurde erfolgreich abgeschlossen und das Deployment ist fertig.", "de"},
|
{"punctuation only", "!!! ??? ...", "de", "de"},
|
||||||
{"deutsch frage mit was", "Was macht er?", "de"},
|
{"german sentence", "Der Build wurde erfolgreich abgeschlossen und das Deployment ist fertig.", "en", "de"},
|
||||||
{"deutsch umlaute", "Größe früh Ärzteübung — schön daß es klappt", "de"},
|
{"undecidable german question → fallback", "Was macht er?", "en", "en"},
|
||||||
{"ß alleine", "weiß", "de"},
|
{"german umlauts", "Größe früh Ärzteübung — schön daß es klappt", "en", "de"},
|
||||||
{"englisch satz", "The build has finished and the deployment is done.", "en"},
|
{"ß alone", "weiß", "en", "de"},
|
||||||
{"englisch imperativ", "Please wait until the tests are green.", "en"},
|
{"english sentence", "The build has finished and the deployment is done.", "de", "en"},
|
||||||
{"englisch kurz", "done", "en"},
|
{"english imperative", "Please wait until the tests are green.", "de", "en"},
|
||||||
{"gemischt englisch dominiert", "the build is done and ready for you", "en"},
|
{"english single word", "done", "de", "en"},
|
||||||
{"gemischt deutsch dominiert", "Der build ist done und fertig für dich", "de"},
|
{"mixed, english dominates", "the build is done and ready for you", "de", "en"},
|
||||||
{"gemischt gleichstand", "der the", "de"},
|
{"mixed, german dominates", "Der build ist done und fertig für dich", "en", "de"},
|
||||||
{"unklare sprache", "Build 2026-10-18 14:22 UTC", "de"},
|
{"tie → fallback", "der the", "en", "en"},
|
||||||
{"agenten-typisch en", "Task completed. Please review the changes and approve.", "en"},
|
{"undecidable → fallback", "Build 2026-10-18 14:22 UTC", "de", "de"},
|
||||||
{"agenten-typisch de", "Aufgabe abgeschlossen. Bitte prüfen und freigeben.", "de"},
|
{"agent-style en", "Task completed. Please review the changes and approve.", "de", "en"},
|
||||||
|
{"agent-style de", "Aufgabe abgeschlossen. Bitte prüfen und freigeben.", "en", "de"},
|
||||||
}
|
}
|
||||||
for _, tc := range cases {
|
for _, tc := range cases {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
if got := Detect(tc.text); got != tc.want {
|
if got := Detect(tc.text, tc.fallback); got != tc.want {
|
||||||
t.Errorf("Detect(%q) = %q, want %q", tc.text, got, tc.want)
|
t.Errorf("Detect(%q, %q) = %q, want %q", tc.text, tc.fallback, got, tc.want)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +0,0 @@
|
|||||||
// Package langdetect erkennt die Sprache eines Ansage-Texts als reine
|
|
||||||
// Funktion Detect(text) → "de" | "en" (Default "de"; Heuristik über
|
|
||||||
// Common-Word-Listen und Umlaute/ß).
|
|
||||||
package langdetect
|
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
//go:build linux
|
||||||
|
|
||||||
|
package notify
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"slices"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/godbus/dbus/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The freedesktop Notifications service on the session bus. One connection
|
||||||
|
// per process, made lazily on first use and kept: the daemon notifies on
|
||||||
|
// every announcement and must see the ActionInvoked signals for the Cancel
|
||||||
|
// button, which only works on a connection that stays open.
|
||||||
|
const (
|
||||||
|
notifDest = "org.freedesktop.Notifications"
|
||||||
|
notifPath = "/org/freedesktop/Notifications"
|
||||||
|
notifIface = "org.freedesktop.Notifications"
|
||||||
|
|
||||||
|
// dbusCallTimeout bounds every call: a hanging notification service
|
||||||
|
// must never hold up an announcement.
|
||||||
|
dbusCallTimeout = 2 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
var bus struct {
|
||||||
|
once sync.Once
|
||||||
|
conn *dbus.Conn
|
||||||
|
err error
|
||||||
|
caps []string
|
||||||
|
server string
|
||||||
|
mu sync.Mutex
|
||||||
|
handlers map[uint32]func(action string) // by notification id
|
||||||
|
}
|
||||||
|
|
||||||
|
// connect opens the session bus once, subscribes to the service's signals
|
||||||
|
// and starts the dispatcher. A missing bus (DBUS_SESSION_BUS_ADDRESS unset:
|
||||||
|
// servers, SSH, WinRM-style sessions) is a normal, remembered failure.
|
||||||
|
func connect() (*dbus.Conn, error) {
|
||||||
|
bus.once.Do(func() {
|
||||||
|
conn, err := dbus.SessionBus()
|
||||||
|
if err != nil {
|
||||||
|
bus.err = fmt.Errorf("session bus: %w", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), dbusCallTimeout)
|
||||||
|
defer cancel()
|
||||||
|
obj := conn.Object(notifDest, notifPath)
|
||||||
|
var name, vendor, version, spec string
|
||||||
|
if err := obj.CallWithContext(ctx, notifIface+".GetServerInformation", 0).Store(&name, &vendor, &version, &spec); err != nil {
|
||||||
|
bus.err = fmt.Errorf("no notification service on the session bus: %w", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
bus.server = name
|
||||||
|
if version != "" {
|
||||||
|
bus.server += " " + version
|
||||||
|
}
|
||||||
|
if err := obj.CallWithContext(ctx, notifIface+".GetCapabilities", 0).Store(&bus.caps); err != nil {
|
||||||
|
bus.caps = nil
|
||||||
|
}
|
||||||
|
if err := conn.AddMatchSignal(dbus.WithMatchObjectPath(notifPath), dbus.WithMatchInterface(notifIface)); err != nil {
|
||||||
|
bus.err = fmt.Errorf("subscribing to notification signals: %w", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
bus.handlers = map[uint32]func(string){}
|
||||||
|
ch := make(chan *dbus.Signal, 32)
|
||||||
|
conn.Signal(ch)
|
||||||
|
go dispatch(ch)
|
||||||
|
bus.conn = conn
|
||||||
|
})
|
||||||
|
return bus.conn, bus.err
|
||||||
|
}
|
||||||
|
|
||||||
|
// dispatch routes ActionInvoked to the notification's handler and drops the
|
||||||
|
// handler on NotificationClosed.
|
||||||
|
func dispatch(ch <-chan *dbus.Signal) {
|
||||||
|
for sig := range ch {
|
||||||
|
if len(sig.Body) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
id, ok := sig.Body[0].(uint32)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
switch sig.Name {
|
||||||
|
case notifIface + ".ActionInvoked":
|
||||||
|
action, _ := sig.Body[1].(string)
|
||||||
|
bus.mu.Lock()
|
||||||
|
h := bus.handlers[id]
|
||||||
|
bus.mu.Unlock()
|
||||||
|
if h != nil {
|
||||||
|
h(action)
|
||||||
|
}
|
||||||
|
case notifIface + ".NotificationClosed":
|
||||||
|
bus.mu.Lock()
|
||||||
|
delete(bus.handlers, id)
|
||||||
|
bus.mu.Unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// dbusAvailable reports whether a notification service answers on the bus.
|
||||||
|
func dbusAvailable() bool {
|
||||||
|
_, err := connect()
|
||||||
|
return err == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// dbusSupportsActions reports the "actions" capability of the service.
|
||||||
|
func dbusSupportsActions() bool {
|
||||||
|
if _, err := connect(); err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return slices.Contains(bus.caps, "actions")
|
||||||
|
}
|
||||||
|
|
||||||
|
// dbusDescribe names the service for `talk doctor`.
|
||||||
|
func dbusDescribe() (string, bool) {
|
||||||
|
if _, err := connect(); err != nil {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
s := "notification service " + bus.server + " via D-Bus"
|
||||||
|
if slices.Contains(bus.caps, "actions") {
|
||||||
|
return s + " (cancel button supported)", true
|
||||||
|
}
|
||||||
|
return s + " (no actions: no cancel button)", true
|
||||||
|
}
|
||||||
|
|
||||||
|
// dbusNotify shows a notification and returns its id. actions is the flat
|
||||||
|
// freedesktop list [key, label, …]; onAction receives the key when the user
|
||||||
|
// clicks. expire_timeout 0 keeps the notification until talk closes it, so
|
||||||
|
// the Cancel button stays for the whole announcement.
|
||||||
|
func dbusNotify(ctx context.Context, text string, actions []string, onAction func(action string)) (uint32, error) {
|
||||||
|
conn, err := connect()
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if actions == nil {
|
||||||
|
actions = []string{}
|
||||||
|
}
|
||||||
|
expire := int32(-1) // server default for plain toasts
|
||||||
|
if len(actions) > 0 {
|
||||||
|
expire = 0
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, dbusCallTimeout)
|
||||||
|
defer cancel()
|
||||||
|
hints := map[string]dbus.Variant{
|
||||||
|
"urgency": dbus.MakeVariant(byte(1)),
|
||||||
|
"desktop-entry": dbus.MakeVariant(Title),
|
||||||
|
}
|
||||||
|
var id uint32
|
||||||
|
err = conn.Object(notifDest, notifPath).CallWithContext(ctx, notifIface+".Notify", 0,
|
||||||
|
Title, uint32(0), appIcon(), Title, text, actions, hints, expire).Store(&id)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("notify: %w", err)
|
||||||
|
}
|
||||||
|
if onAction != nil {
|
||||||
|
bus.mu.Lock()
|
||||||
|
bus.handlers[id] = onAction
|
||||||
|
bus.mu.Unlock()
|
||||||
|
}
|
||||||
|
return id, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// dbusClose dismisses a notification (best effort).
|
||||||
|
func dbusClose(id uint32) {
|
||||||
|
conn, err := connect()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
bus.mu.Lock()
|
||||||
|
delete(bus.handlers, id)
|
||||||
|
bus.mu.Unlock()
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), dbusCallTimeout)
|
||||||
|
defer cancel()
|
||||||
|
_ = conn.Object(notifDest, notifPath).CallWithContext(ctx, notifIface+".CloseNotification", 0, id).Err
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
//go:build !linux
|
||||||
|
|
||||||
|
package notify
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Without the freedesktop Notifications service there is no bus path; the
|
||||||
|
// OS tool does the job (no actions).
|
||||||
|
|
||||||
|
var errNoDBus = errors.New("notify: no D-Bus notification service on this platform")
|
||||||
|
|
||||||
|
func dbusAvailable() bool { return false }
|
||||||
|
func dbusSupportsActions() bool { return false }
|
||||||
|
func dbusDescribe() (string, bool) { return "", false }
|
||||||
|
func dbusClose(uint32) {}
|
||||||
|
func dbusNotify(context.Context, string, []string, func(string)) (uint32, error) {
|
||||||
|
return 0, errNoDBus
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
//go:build !windows
|
||||||
|
|
||||||
|
package notify
|
||||||
|
|
||||||
|
// UseIcon remembers the icon file for notifications (Linux: app_icon of the
|
||||||
|
// freedesktop notification). macOS has no way to pass one to osascript.
|
||||||
|
func UseIcon(iconPath string) error {
|
||||||
|
setIconPath(iconPath)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ownIdentity is a Windows concept (toast AppUserModelID).
|
||||||
|
func ownIdentity() bool { return false }
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package notify
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows/registry"
|
||||||
|
)
|
||||||
|
|
||||||
|
// appIDKey is where Windows looks up the identity (name, icon) of an
|
||||||
|
// unpackaged program that shows toasts: HKCU, so no admin rights.
|
||||||
|
const appIDKey = `Software\Classes\AppUserModelId\` + AppID
|
||||||
|
|
||||||
|
var (
|
||||||
|
identityMu sync.Mutex
|
||||||
|
identityKnown bool
|
||||||
|
identityOK bool
|
||||||
|
)
|
||||||
|
|
||||||
|
// UseIcon registers talk's own toast identity for the current user: the
|
||||||
|
// AppUserModelID AppID with display name "talk" and the icon at iconPath.
|
||||||
|
// Toasts then appear as coming from talk instead of Windows PowerShell.
|
||||||
|
// Idempotent; rewritten on every call so it follows the icon's location.
|
||||||
|
func UseIcon(iconPath string) error {
|
||||||
|
setIconPath(iconPath)
|
||||||
|
k, _, err := registry.CreateKey(registry.CURRENT_USER, appIDKey, registry.SET_VALUE)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("registering toast identity: %w", err)
|
||||||
|
}
|
||||||
|
defer k.Close()
|
||||||
|
if err := k.SetStringValue("DisplayName", Title); err != nil {
|
||||||
|
return fmt.Errorf("registering toast identity: %w", err)
|
||||||
|
}
|
||||||
|
if err := k.SetStringValue("IconUri", iconPath); err != nil {
|
||||||
|
return fmt.Errorf("registering toast identity: %w", err)
|
||||||
|
}
|
||||||
|
identityMu.Lock()
|
||||||
|
identityKnown, identityOK = true, true
|
||||||
|
identityMu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ownIdentity reports whether AppID is registered for this user (by this
|
||||||
|
// process or an earlier daemon start); checked once per process.
|
||||||
|
func ownIdentity() bool {
|
||||||
|
identityMu.Lock()
|
||||||
|
defer identityMu.Unlock()
|
||||||
|
if !identityKnown {
|
||||||
|
identityKnown = true
|
||||||
|
identityOK = false
|
||||||
|
if k, err := registry.OpenKey(registry.CURRENT_USER, appIDKey, registry.QUERY_VALUE); err == nil {
|
||||||
|
_, _, err := k.GetStringValue("IconUri")
|
||||||
|
identityOK = err == nil
|
||||||
|
k.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return identityOK
|
||||||
|
}
|
||||||
+165
-32
@@ -1,13 +1,17 @@
|
|||||||
// Package notify zeigt Desktop-Benachrichtigungen — best effort, über die
|
// Package notify shows desktop notifications: best effort, never a reason to
|
||||||
// Bordmittel des Betriebssystems, ohne Bibliotheks-Abhängigkeit und ohne
|
// abort an announcement.
|
||||||
// CGO (dieselbe Linie wie provider/osbuiltin):
|
|
||||||
//
|
//
|
||||||
// Linux: notify-send (libnotify; braucht einen Notification-Daemon)
|
// Linux: the freedesktop Notifications D-Bus service (org.freedesktop.
|
||||||
// macOS: osascript `display notification`
|
// Notifications, pure Go via godbus): notifications with a Cancel
|
||||||
// Windows: PowerShell Toast (Windows.UI.Notifications)
|
// action, closed again when the announcement ends. Fallback when
|
||||||
|
// no session bus is reachable: notify-send (no action).
|
||||||
|
// macOS: osascript `display notification` (no action).
|
||||||
|
// Windows: PowerShell toast (Windows.UI.Notifications) with a Cancel
|
||||||
|
// button that opens a talk: link; the talk: protocol handler
|
||||||
|
// (registered in HKCU, `talk uri`) relays the click to the daemon.
|
||||||
//
|
//
|
||||||
// Fehlende Werkzeuge sind ein klarer Fehler für den Aufrufer (Protokoll),
|
// Missing tools are a clear error for the caller (log), never an abort: a
|
||||||
// nie ein Abbruch: Eine Benachrichtigung ist Zusatz, kein Vertrag.
|
// notification is an extra, not a contract.
|
||||||
package notify
|
package notify
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -15,43 +19,116 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
"unicode/utf16"
|
"unicode/utf16"
|
||||||
|
|
||||||
|
"code.m3ta.dev/m3tam3re/talk/internal/icon"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Title ist der Titel aller talk-Benachrichtigungen.
|
// Title is the title of all talk notifications.
|
||||||
const Title = "talk"
|
const Title = "talk"
|
||||||
|
|
||||||
// timeout begrenzt den Aufruf des OS-Werkzeugs.
|
// AppID is talk's AppUserModelID on Windows: the identity (name, icon) its
|
||||||
|
// toasts are shown under once UseIcon has registered it.
|
||||||
|
const AppID = "m3ta.talk"
|
||||||
|
|
||||||
|
var (
|
||||||
|
iconMu sync.Mutex
|
||||||
|
iconFile string
|
||||||
|
)
|
||||||
|
|
||||||
|
func setIconPath(p string) {
|
||||||
|
iconMu.Lock()
|
||||||
|
iconFile = p
|
||||||
|
iconMu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// appIcon is the icon a freedesktop notification carries: the installed
|
||||||
|
// talk icon, or a theme icon while none is installed.
|
||||||
|
func appIcon() string {
|
||||||
|
iconMu.Lock()
|
||||||
|
defer iconMu.Unlock()
|
||||||
|
if iconFile != "" {
|
||||||
|
return iconFile
|
||||||
|
}
|
||||||
|
return "audio-speakers"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Setup prepares the desktop side once per process (daemon start, talk
|
||||||
|
// test --toast): installs the icon into dir and registers it (Windows: the
|
||||||
|
// toast identity and, with exe, the talk: protocol handler the Cancel
|
||||||
|
// button needs). Best effort: the error is for the log, notifications still
|
||||||
|
// work under the fallback identity.
|
||||||
|
func Setup(dir, exe string) error {
|
||||||
|
path, err := icon.Install(dir)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var errs []error
|
||||||
|
if err := UseIcon(path); err != nil {
|
||||||
|
errs = append(errs, err)
|
||||||
|
}
|
||||||
|
if exe != "" {
|
||||||
|
if err := RegisterProtocol(exe); err != nil {
|
||||||
|
errs = append(errs, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return errors.Join(errs...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// timeout bounds the call of the OS tool.
|
||||||
const timeout = 10 * time.Second
|
const timeout = 10 * time.Second
|
||||||
|
|
||||||
// Available meldet, ob auf diesem System ein Benachrichtigungs-Weg
|
// Available reports whether a notification path exists on this system: a
|
||||||
// existiert (Binary vorhanden; ob ein Daemon lauscht, zeigt erst Show).
|
// reachable notification service on the session bus, or the OS tool.
|
||||||
func Available() bool {
|
func Available() bool {
|
||||||
|
if dbusAvailable() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
_, err := exec.LookPath(tool())
|
_, err := exec.LookPath(tool())
|
||||||
return err == nil
|
return err == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Describe nennt den Weg für `talk doctor`.
|
// Describe names the path for `talk doctor`: the notification service with
|
||||||
|
// name and version and whether it supports a Cancel action, or the OS tool.
|
||||||
func Describe() string {
|
func Describe() string {
|
||||||
|
if info, ok := dbusDescribe(); ok {
|
||||||
|
return info
|
||||||
|
}
|
||||||
t := tool()
|
t := tool()
|
||||||
if _, err := exec.LookPath(t); err != nil {
|
if _, err := exec.LookPath(t); err != nil {
|
||||||
return t + " nicht gefunden"
|
if runtime.GOOS == "linux" {
|
||||||
|
return "no notification service on the session bus and " + t + " not found"
|
||||||
|
}
|
||||||
|
return t + " not found"
|
||||||
}
|
}
|
||||||
switch runtime.GOOS {
|
switch runtime.GOOS {
|
||||||
case "darwin":
|
case "darwin":
|
||||||
return "osascript (Notification Center)"
|
return "osascript (Notification Center; no cancel button)"
|
||||||
case "windows":
|
case "windows":
|
||||||
return "powershell (Windows Toast)"
|
if ownIdentity() {
|
||||||
|
return "powershell (Windows toast as talk, cancel button via the talk: link)"
|
||||||
|
}
|
||||||
|
return "powershell (Windows toast under the Windows PowerShell identity until the daemon has run once; cancel button via the talk: link)"
|
||||||
default:
|
default:
|
||||||
return "notify-send (libnotify)"
|
return "notify-send (libnotify; no session bus, so no cancel button)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SupportsCancel reports whether notifications on this system can carry a
|
||||||
|
// Cancel button that reaches talk: Linux with a notification service that
|
||||||
|
// has the "actions" capability, or Windows (toast button via the talk:
|
||||||
|
// protocol handler).
|
||||||
|
func SupportsCancel() bool {
|
||||||
|
return dbusSupportsActions() || runtime.GOOS == "windows"
|
||||||
|
}
|
||||||
|
|
||||||
func tool() string {
|
func tool() string {
|
||||||
switch runtime.GOOS {
|
switch runtime.GOOS {
|
||||||
case "darwin":
|
case "darwin":
|
||||||
@@ -63,9 +140,66 @@ func tool() string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Show zeigt eine Benachrichtigung mit Title und text und wartet auf das
|
// Show shows a plain notification with Title and text (no action) and waits
|
||||||
// Ende des OS-Aufrufs (nicht auf das Schließen der Benachrichtigung).
|
// for the handover to finish, not for the notification to be closed. Used
|
||||||
|
// for the quiet-hours toast.
|
||||||
func Show(ctx context.Context, text string) error {
|
func Show(ctx context.Context, text string) error {
|
||||||
|
if dbusAvailable() {
|
||||||
|
id, err := dbusNotify(ctx, text, nil, nil)
|
||||||
|
if err == nil {
|
||||||
|
_ = id
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return showWithTool(ctx, text)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Announcement is what Announce shows for a playing announcement.
|
||||||
|
type Announcement struct {
|
||||||
|
// Text is the announcement text (the notification body).
|
||||||
|
Text string
|
||||||
|
|
||||||
|
// CancelLabel is the button label ("Cancel", "Abbrechen").
|
||||||
|
CancelLabel string
|
||||||
|
|
||||||
|
// CancelURI is the talk: link the button opens where the click cannot
|
||||||
|
// reach the daemon directly (Windows toast): talk:cancel?id=…&port=….
|
||||||
|
// The talk: protocol handler (talk uri) turns it into POST /cancel-item.
|
||||||
|
CancelURI string
|
||||||
|
|
||||||
|
// Tag identifies the notification for closing it again where the
|
||||||
|
// platform needs a tag (Windows); typically the announcement id.
|
||||||
|
Tag string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Announce shows the notification for an announcement that is playing: the
|
||||||
|
// text plus a Cancel button where the platform supports it. onCancel runs
|
||||||
|
// when the user clicks it on platforms that report the click back (Linux
|
||||||
|
// D-Bus); on Windows the click opens CancelURI instead. The returned close
|
||||||
|
// function dismisses the notification (call it when the announcement
|
||||||
|
// ends); it is never nil. Platforms without actions show a plain
|
||||||
|
// notification and the close function does nothing.
|
||||||
|
func Announce(ctx context.Context, a Announcement, onCancel func()) (close func(), err error) {
|
||||||
|
noop := func() {}
|
||||||
|
if dbusAvailable() {
|
||||||
|
id, err := dbusNotify(ctx, a.Text, []string{"cancel", a.CancelLabel}, func(action string) {
|
||||||
|
if action == "cancel" && onCancel != nil {
|
||||||
|
onCancel()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
return func() { dbusClose(id) }, nil
|
||||||
|
}
|
||||||
|
// fall through to the tool on a bus error
|
||||||
|
}
|
||||||
|
if runtime.GOOS == "windows" && a.CancelURI != "" {
|
||||||
|
return announceWindows(ctx, a)
|
||||||
|
}
|
||||||
|
return noop, showWithTool(ctx, a.Text)
|
||||||
|
}
|
||||||
|
|
||||||
|
// showWithTool shows a notification through the OS tool (no action).
|
||||||
|
func showWithTool(ctx context.Context, text string) error {
|
||||||
ctx, cancel := context.WithTimeout(ctx, timeout)
|
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
var cmd *exec.Cmd
|
var cmd *exec.Cmd
|
||||||
@@ -74,36 +208,35 @@ func Show(ctx context.Context, text string) error {
|
|||||||
script := fmt.Sprintf("display notification %s with title %s", appleString(text), appleString(Title))
|
script := fmt.Sprintf("display notification %s with title %s", appleString(text), appleString(Title))
|
||||||
cmd = exec.CommandContext(ctx, "osascript", "-e", script)
|
cmd = exec.CommandContext(ctx, "osascript", "-e", script)
|
||||||
case "windows":
|
case "windows":
|
||||||
cmd = exec.CommandContext(ctx, "powershell", "-NoProfile", "-NonInteractive", "-EncodedCommand", psEncode(toastScript(text)))
|
cmd = exec.CommandContext(ctx, "powershell", "-NoProfile", "-NonInteractive", "-EncodedCommand", psEncode(toastScript(text, toastAppID())))
|
||||||
default:
|
default:
|
||||||
cmd = exec.CommandContext(ctx, "notify-send", "--app-name="+Title, "--urgency=normal", Title, text)
|
cmd = exec.CommandContext(ctx, "notify-send", "--app-name="+Title, "--urgency=normal", Title, text)
|
||||||
}
|
}
|
||||||
if out, err := cmd.CombinedOutput(); err != nil {
|
if out, err := cmd.CombinedOutput(); err != nil {
|
||||||
return fmt.Errorf("notify: %s fehlgeschlagen: %w: %s", tool(), err, bytes.TrimSpace(out))
|
return fmt.Errorf("notify: %s failed: %w: %s", tool(), err, bytes.TrimSpace(out))
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// appleString macht aus s ein AppleScript-Stringliteral.
|
// appleString turns s into an AppleScript string literal.
|
||||||
func appleString(s string) string {
|
func appleString(s string) string {
|
||||||
return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(s) + `"`
|
return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(s) + `"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// toastScript ist der PowerShell-Toast (Windows 10/11); der Text wird
|
// toastScript is the PowerShell for a plain toast (Windows 10/11) under
|
||||||
// base64 übergeben, damit es kein Quoting-Problem gibt.
|
// appID; the text is passed base64-encoded so there is no quoting problem.
|
||||||
func toastScript(text string) string {
|
func toastScript(text, appID string) string {
|
||||||
return fmt.Sprintf(`$ErrorActionPreference = 'Stop'
|
return fmt.Sprintf(`$ErrorActionPreference = 'Stop'
|
||||||
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
|
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
|
||||||
$msg = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('%s'))
|
[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null
|
||||||
$xml = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)
|
$msg = [System.Security.SecurityElement]::Escape([System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('%s')))
|
||||||
$nodes = $xml.GetElementsByTagName('text')
|
$xml = New-Object Windows.Data.Xml.Dom.XmlDocument
|
||||||
$nodes.Item(0).AppendChild($xml.CreateTextNode('%s')) | Out-Null
|
$xml.LoadXml("<toast><visual><binding template='ToastGeneric'>%s<text>$msg</text></binding></visual></toast>")
|
||||||
$nodes.Item(1).AppendChild($xml.CreateTextNode($msg)) | Out-Null
|
|
||||||
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('%s').Show([Windows.UI.Notifications.ToastNotification]::new($xml))
|
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('%s').Show([Windows.UI.Notifications.ToastNotification]::new($xml))
|
||||||
`, base64.StdEncoding.EncodeToString([]byte(text)), Title, Title)
|
`, base64.StdEncoding.EncodeToString([]byte(text)), titleLine(appID), appID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// psEncode kodiert ein Skript für -EncodedCommand (UTF-16LE + Base64).
|
// psEncode encodes a script for -EncodedCommand (UTF-16LE + base64).
|
||||||
func psEncode(script string) string {
|
func psEncode(script string) string {
|
||||||
runes := utf16.Encode([]rune(script))
|
runes := utf16.Encode([]rune(script))
|
||||||
buf := make([]byte, len(runes)*2)
|
buf := make([]byte, len(runes)*2)
|
||||||
|
|||||||
@@ -9,12 +9,19 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestShowRuftNotifySend: Auf Linux geht Show über notify-send — hier ein
|
// TestMain cuts the tests off from the developer's real session bus so they
|
||||||
// Fake im PATH, der seine Argumente protokolliert (echter Prozess, kein
|
// observe the notify-send fallback instead of popping real notifications.
|
||||||
// Mock-Framework). Titel und Text kommen unverändert an.
|
func TestMain(m *testing.M) {
|
||||||
func TestShowRuftNotifySend(t *testing.T) {
|
os.Setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path=/nonexistent/talk-test-bus")
|
||||||
|
os.Exit(m.Run())
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestShowCallsNotifySend: on Linux, Show goes through notify-send; here a
|
||||||
|
// fake in PATH that records its arguments (a real process, no mock
|
||||||
|
// framework). Title and text arrive unchanged.
|
||||||
|
func TestShowCallsNotifySend(t *testing.T) {
|
||||||
if runtime.GOOS != "linux" {
|
if runtime.GOOS != "linux" {
|
||||||
t.Skip("notify-send-Weg gibt es nur auf Linux")
|
t.Skip("the notify-send path exists only on Linux")
|
||||||
}
|
}
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
seen := filepath.Join(dir, "seen.txt")
|
seen := filepath.Join(dir, "seen.txt")
|
||||||
@@ -25,9 +32,9 @@ func TestShowRuftNotifySend(t *testing.T) {
|
|||||||
t.Setenv("PATH", dir)
|
t.Setenv("PATH", dir)
|
||||||
|
|
||||||
if !Available() {
|
if !Available() {
|
||||||
t.Fatal("Available = false mit Fake im PATH")
|
t.Fatal("Available = false with fake in PATH")
|
||||||
}
|
}
|
||||||
if err := Show(context.Background(), "Ruhezeit: Build fertig"); err != nil {
|
if err := Show(context.Background(), "quiet hours: build done"); err != nil {
|
||||||
t.Fatalf("Show: %v", err)
|
t.Fatalf("Show: %v", err)
|
||||||
}
|
}
|
||||||
b, err := os.ReadFile(seen)
|
b, err := os.ReadFile(seen)
|
||||||
@@ -35,27 +42,91 @@ func TestShowRuftNotifySend(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
args := strings.Split(strings.TrimSpace(string(b)), "\n")
|
args := strings.Split(strings.TrimSpace(string(b)), "\n")
|
||||||
if args[len(args)-1] != "Ruhezeit: Build fertig" || args[len(args)-2] != Title {
|
if args[len(args)-1] != "quiet hours: build done" || args[len(args)-2] != Title {
|
||||||
t.Errorf("notify-send-Argumente = %q, want … %q %q", args, Title, "Ruhezeit: Build fertig")
|
t.Errorf("notify-send arguments = %q, want ... %q %q", args, Title, "quiet hours: build done")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestShowOhneWerkzeug: fehlt das Werkzeug, ist das ein klarer Fehler.
|
// TestShowWithoutTool: a missing tool is a clear error.
|
||||||
func TestShowOhneWerkzeug(t *testing.T) {
|
func TestShowWithoutTool(t *testing.T) {
|
||||||
t.Setenv("PATH", t.TempDir())
|
t.Setenv("PATH", t.TempDir())
|
||||||
if Available() {
|
if Available() {
|
||||||
t.Fatal("Available = true ohne Werkzeug")
|
t.Fatal("Available = true without tool")
|
||||||
}
|
}
|
||||||
if err := Show(context.Background(), "x"); err == nil {
|
if err := Show(context.Background(), "x"); err == nil {
|
||||||
t.Error("Show ohne Werkzeug: kein Fehler")
|
t.Error("Show without tool: no error")
|
||||||
}
|
}
|
||||||
if !strings.Contains(Describe(), "nicht gefunden") {
|
if !strings.Contains(Describe(), "not found") {
|
||||||
t.Errorf("Describe = %q", Describe())
|
t.Errorf("Describe = %q", Describe())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAppleString(t *testing.T) {
|
func TestAppleString(t *testing.T) {
|
||||||
if got := appleString(`sag "hallo" \ tschüss`); got != `"sag \"hallo\" \\ tschüss"` {
|
if got := appleString(`say "hello" \ bye`); got != `"say \"hello\" \\ bye"` {
|
||||||
t.Errorf("appleString = %s", got)
|
t.Errorf("appleString = %s", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestToastIdentity: under talk's own AppUserModelID the toast header names
|
||||||
|
// talk already, so the scripts carry only the body; under the PowerShell
|
||||||
|
// fallback identity a first line names talk.
|
||||||
|
func TestToastIdentity(t *testing.T) {
|
||||||
|
a := Announcement{Text: "build done", CancelLabel: "Cancel", CancelURI: "talk:cancel?id=1", Tag: "1"}
|
||||||
|
own := cancelToastScript(a, "talk-1", AppID)
|
||||||
|
if !strings.Contains(own, "CreateToastNotifier('"+AppID+"')") || strings.Contains(own, "<text>"+Title+"</text>") {
|
||||||
|
t.Errorf("own identity script wrong:\n%s", own)
|
||||||
|
}
|
||||||
|
fallback := cancelToastScript(a, "talk-1", powerShellAppID)
|
||||||
|
if !strings.Contains(fallback, "CreateToastNotifier('"+powerShellAppID+"')") || !strings.Contains(fallback, "<text>"+Title+"</text>") {
|
||||||
|
t.Errorf("fallback script wrong:\n%s", fallback)
|
||||||
|
}
|
||||||
|
plain := toastScript("quiet", AppID)
|
||||||
|
if strings.Contains(plain, "<text>"+Title+"</text>") || !strings.Contains(plain, "<text>$msg</text>") {
|
||||||
|
t.Errorf("plain own-identity script wrong:\n%s", plain)
|
||||||
|
}
|
||||||
|
if !strings.Contains(toastScript("quiet", powerShellAppID), "<text>"+Title+"</text>") {
|
||||||
|
t.Error("plain fallback script lacks the talk line")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestUseIconOutsideWindows: UseIcon remembers the file and the freedesktop
|
||||||
|
// notification carries it as app_icon; without one a theme icon is used.
|
||||||
|
func TestUseIconOutsideWindows(t *testing.T) {
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
t.Skip("registry path on Windows")
|
||||||
|
}
|
||||||
|
setIconPath("")
|
||||||
|
if appIcon() != "audio-speakers" {
|
||||||
|
t.Errorf("appIcon without file = %q", appIcon())
|
||||||
|
}
|
||||||
|
if err := UseIcon("/x/talk.png"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { setIconPath("") })
|
||||||
|
if appIcon() != "/x/talk.png" {
|
||||||
|
t.Errorf("appIcon = %q", appIcon())
|
||||||
|
}
|
||||||
|
if ownIdentity() {
|
||||||
|
t.Error("ownIdentity true outside Windows")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSetup: the icon lands in dir and is used; with no exe the protocol
|
||||||
|
// step is skipped (outside Windows it is a no-op anyway).
|
||||||
|
func TestSetup(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
if err := Setup(dir, ""); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { setIconPath("") })
|
||||||
|
want := filepath.Join(dir, "talk.png")
|
||||||
|
if _, err := os.Stat(want); err != nil {
|
||||||
|
t.Fatalf("icon not installed: %v", err)
|
||||||
|
}
|
||||||
|
if runtime.GOOS != "windows" && appIcon() != want {
|
||||||
|
t.Errorf("appIcon = %q, want %q", appIcon(), want)
|
||||||
|
}
|
||||||
|
if err := Setup("", ""); err == nil {
|
||||||
|
t.Error("Setup without dir succeeded")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
//go:build !windows
|
||||||
|
|
||||||
|
package notify
|
||||||
|
|
||||||
|
// RegisterProtocol is a no-op outside Windows: Linux reports clicks over
|
||||||
|
// D-Bus, macOS has no button.
|
||||||
|
func RegisterProtocol(string) error { return nil }
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package notify
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows/registry"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RegisterProtocol registers the talk: URL protocol for the current user
|
||||||
|
// (HKCU\Software\Classes\talk, no admin rights needed) so that a toast
|
||||||
|
// button with a talk: link starts `<exe> uri <link>`. Idempotent; the
|
||||||
|
// command is rewritten on every call so it follows the binary's location.
|
||||||
|
func RegisterProtocol(exe string) error {
|
||||||
|
root, _, err := registry.CreateKey(registry.CURRENT_USER, `Software\Classes\talk`, registry.SET_VALUE)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("registering talk: protocol: %w", err)
|
||||||
|
}
|
||||||
|
defer root.Close()
|
||||||
|
if err := root.SetStringValue("", "URL:talk protocol"); err != nil {
|
||||||
|
return fmt.Errorf("registering talk: protocol: %w", err)
|
||||||
|
}
|
||||||
|
if err := root.SetStringValue("URL Protocol", ""); err != nil {
|
||||||
|
return fmt.Errorf("registering talk: protocol: %w", err)
|
||||||
|
}
|
||||||
|
cmdKey, _, err := registry.CreateKey(registry.CURRENT_USER, `Software\Classes\talk\shell\open\command`, registry.SET_VALUE)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("registering talk: protocol: %w", err)
|
||||||
|
}
|
||||||
|
defer cmdKey.Close()
|
||||||
|
if err := cmdKey.SetStringValue("", fmt.Sprintf(`"%s" uri "%%1"`, exe)); err != nil {
|
||||||
|
return fmt.Errorf("registering talk: protocol: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
package notify
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
|
"os/exec"
|
||||||
|
)
|
||||||
|
|
||||||
|
// powerShellAppID is the fallback toast identity while talk's own (AppID)
|
||||||
|
// is not registered yet: PowerShell's AppUserModelID exists on every
|
||||||
|
// Windows, the toast then appears as coming from Windows PowerShell.
|
||||||
|
const powerShellAppID = `{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\WindowsPowerShell\v1.0\powershell.exe`
|
||||||
|
|
||||||
|
// toastGroup groups all talk toasts so they can be removed by tag.
|
||||||
|
const toastGroup = "talk"
|
||||||
|
|
||||||
|
// toastAppID is the AppUserModelID toasts are shown under: talk's own once
|
||||||
|
// UseIcon has registered it, PowerShell's before that.
|
||||||
|
func toastAppID() string {
|
||||||
|
if ownIdentity() {
|
||||||
|
return AppID
|
||||||
|
}
|
||||||
|
return powerShellAppID
|
||||||
|
}
|
||||||
|
|
||||||
|
// announceWindows shows a toast with the text and a Cancel button that opens
|
||||||
|
// a.CancelURI (protocol activation; Windows then starts `talk uri <link>`,
|
||||||
|
// which tells the daemon to cancel). The returned close removes the toast by
|
||||||
|
// its tag when the announcement ends.
|
||||||
|
func announceWindows(ctx context.Context, a Announcement) (func(), error) {
|
||||||
|
tag := "talk-" + a.Tag
|
||||||
|
appID := toastAppID()
|
||||||
|
if err := runPowerShell(ctx, cancelToastScript(a, tag, appID)); err != nil {
|
||||||
|
return func() {}, err
|
||||||
|
}
|
||||||
|
return func() {
|
||||||
|
remove := fmt.Sprintf(`[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
|
||||||
|
[Windows.UI.Notifications.ToastNotificationManager]::History.Remove('%s', '%s', '%s')
|
||||||
|
`, tag, toastGroup, appID)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||||
|
defer cancel()
|
||||||
|
_ = runPowerShell(ctx, remove)
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// cancelToastScript builds the PowerShell for a toast with a Cancel button
|
||||||
|
// shown under appID. Under talk's own identity the header already says
|
||||||
|
// "talk" with the icon, so the body is the text alone; under the PowerShell
|
||||||
|
// identity a first line names talk.
|
||||||
|
func cancelToastScript(a Announcement, tag, appID string) string {
|
||||||
|
return fmt.Sprintf(`$ErrorActionPreference = 'Stop'
|
||||||
|
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
|
||||||
|
[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null
|
||||||
|
$dec = { param($b) [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($b)) }
|
||||||
|
$esc = { param($s) [System.Security.SecurityElement]::Escape($s) }
|
||||||
|
$body = & $esc (& $dec '%s')
|
||||||
|
$label = & $esc (& $dec '%s')
|
||||||
|
$uri = & $esc (& $dec '%s')
|
||||||
|
$xmlText = "<toast><visual><binding template='ToastGeneric'>%s<text>$body</text></binding></visual><actions><action content='$label' arguments='$uri' activationType='protocol'/></actions></toast>"
|
||||||
|
$xml = New-Object Windows.Data.Xml.Dom.XmlDocument
|
||||||
|
$xml.LoadXml($xmlText)
|
||||||
|
$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
|
||||||
|
$toast.Tag = '%s'
|
||||||
|
$toast.Group = '%s'
|
||||||
|
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('%s').Show($toast)
|
||||||
|
`, b64(a.Text), b64(a.CancelLabel), b64(a.CancelURI), titleLine(appID), tag, toastGroup, appID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// titleLine is the extra "talk" line a toast needs under a foreign identity.
|
||||||
|
func titleLine(appID string) string {
|
||||||
|
if appID == AppID {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return "<text>" + Title + "</text>"
|
||||||
|
}
|
||||||
|
|
||||||
|
// runPowerShell runs a script via -EncodedCommand.
|
||||||
|
func runPowerShell(ctx context.Context, script string) error {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||||
|
defer cancel()
|
||||||
|
cmd := exec.CommandContext(ctx, "powershell", "-NoProfile", "-NonInteractive", "-EncodedCommand", psEncode(script))
|
||||||
|
if out, err := cmd.CombinedOutput(); err != nil {
|
||||||
|
return fmt.Errorf("notify: powershell failed: %w: %s", err, string(out))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func b64(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) }
|
||||||
@@ -2,10 +2,10 @@ package provider
|
|||||||
|
|
||||||
import "sort"
|
import "sort"
|
||||||
|
|
||||||
// Voice ist ein Eintrag des Stimmen-Katalogs: eine bekannte Stimme eines
|
// Voice is an entry of the voice catalog: a known voice of a provider for a
|
||||||
// Providers für eine Sprache, mit lesbarem Namen. Der Katalog ist kuratiert
|
// language, with a readable name. The catalog is curated (the common
|
||||||
// (die gängigen Standardstimmen), nicht vollständig — jede Voice-ID des
|
// standard voices), not complete; any voice ID of the provider also works
|
||||||
// Providers funktioniert auch ohne Katalog-Eintrag (--voice, config).
|
// without a catalog entry (--voice, config).
|
||||||
type Voice struct {
|
type Voice struct {
|
||||||
Provider string
|
Provider string
|
||||||
Lang string // de | en
|
Lang string // de | en
|
||||||
@@ -13,10 +13,10 @@ type Voice struct {
|
|||||||
Name string
|
Name string
|
||||||
}
|
}
|
||||||
|
|
||||||
// catalog sind die bekannten Stimmen je Provider. ElevenLabs: öffentliche
|
// catalog lists the known voices per provider. ElevenLabs: public premade
|
||||||
// Premade-Stimmen (multilingual, daher für de UND en gelistet). OpenAI: die
|
// voices (multilingual, hence listed for both de AND en). OpenAI: the voices
|
||||||
// Stimmen der TTS-API (sprachunabhängig). Edge: Neural-Stimmen der
|
// of the TTS API (language independent). Edge: neural voices of the
|
||||||
// jeweiligen Locale. osbuiltin kennt keine IDs (das OS wählt).
|
// respective locale. osbuiltin has no IDs (the OS chooses).
|
||||||
var catalog = []Voice{
|
var catalog = []Voice{
|
||||||
{"elevenlabs", "de", "21m00Tcm4TlvDq8ikWAM", "Rachel"},
|
{"elevenlabs", "de", "21m00Tcm4TlvDq8ikWAM", "Rachel"},
|
||||||
{"elevenlabs", "de", "pNInz6obpgDQGcFmaJgB", "Adam"},
|
{"elevenlabs", "de", "pNInz6obpgDQGcFmaJgB", "Adam"},
|
||||||
@@ -54,8 +54,8 @@ var catalog = []Voice{
|
|||||||
{"edge", "en", "en-GB-RyanNeural", "Ryan (GB)"},
|
{"edge", "en", "en-GB-RyanNeural", "Ryan (GB)"},
|
||||||
}
|
}
|
||||||
|
|
||||||
// Catalog liefert den Stimmen-Katalog in stabiler Reihenfolge
|
// Catalog returns the voice catalog in stable order (chain order of the
|
||||||
// (Ketten-Reihenfolge der Provider, dann de vor en, dann Katalog-Reihe).
|
// providers, then de before en, then catalog order).
|
||||||
func Catalog() []Voice {
|
func Catalog() []Voice {
|
||||||
out := make([]Voice, len(catalog))
|
out := make([]Voice, len(catalog))
|
||||||
copy(out, catalog)
|
copy(out, catalog)
|
||||||
@@ -72,7 +72,7 @@ func Catalog() []Voice {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
// VoiceName liefert den Katalog-Namen einer Voice-ID; leer, wenn unbekannt.
|
// VoiceName returns the catalog name of a voice ID; empty if unknown.
|
||||||
func VoiceName(provider, id string) string {
|
func VoiceName(provider, id string) string {
|
||||||
for _, v := range catalog {
|
for _, v := range catalog {
|
||||||
if v.Provider == provider && v.ID == id {
|
if v.Provider == provider && v.ID == id {
|
||||||
@@ -82,9 +82,9 @@ func VoiceName(provider, id string) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// DefaultVoice liefert die effektive Default-Stimme eines Providers für
|
// DefaultVoice returns the effective default voice of a provider for a
|
||||||
// eine Sprache: config-Mapping voice.<provider>.<lang> vor dem Repo-Default
|
// language: config mapping voice.<provider>.<lang> before the repo default
|
||||||
// (ohne --voice-Pin). Leer bei osbuiltin (das OS wählt).
|
// (without a --voice pin). Empty for osbuiltin (the OS chooses).
|
||||||
func DefaultVoice(provider, lang string, cfgVoices map[string]map[string]string) string {
|
func DefaultVoice(provider, lang string, cfgVoices map[string]map[string]string) string {
|
||||||
return resolveVoice(provider, lang, "", cfgVoices[provider])
|
return resolveVoice(provider, lang, "", cfgVoices[provider])
|
||||||
}
|
}
|
||||||
+105
-108
@@ -9,69 +9,68 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DefaultOrder ist die bindende Default-Fallback-Reihenfolge der Kette
|
// DefaultOrder is the binding default fallback order of the chain
|
||||||
// (Spec: ElevenLabs → OpenAI TTS → Edge-TTS → OS built-in).
|
// (spec: ElevenLabs → OpenAI TTS → Edge TTS → OS built-in).
|
||||||
var DefaultOrder = []string{"elevenlabs", "openai", "edge", "osbuiltin"}
|
var DefaultOrder = []string{"elevenlabs", "openai", "edge", "osbuiltin"}
|
||||||
|
|
||||||
// NullPlayerName ist der dokumentierte Name des verwerfenden Sinks
|
// NullPlayerName is the documented name of the discarding sink
|
||||||
// (Spec: audio.sink = "oto" | "null"). Die Kette braucht ihn für die
|
// (spec: audio.sink = "oto" | "null"). The chain needs it to decide
|
||||||
// Entscheidung, ob eine Direktansage (DirectSpeaker) verworfen werden
|
// whether a direct announcement (DirectSpeaker) must be discarded; the
|
||||||
// muss — der null-Sink darf niemals Ton erzeugen.
|
// null sink must never produce sound.
|
||||||
const NullPlayerName = "null"
|
const NullPlayerName = "null"
|
||||||
|
|
||||||
// Player spielt Audio-Bytes ab, die die Kette geliefert hat. Der Vertrag
|
// Player plays audio bytes the chain has produced. The contract is
|
||||||
// ist absichtlich strukturell identisch zu audio.Sink (Play + Name): CLI
|
// deliberately structurally identical to audio.Sink (Play + Name): CLI and
|
||||||
// und Daemon (Task 04) übergeben das Ergebnis von audio.NewSink(name, log)
|
// daemon pass the result of audio.NewSink(name, log) unchanged, which keeps
|
||||||
// unverändert — dadurch bleibt die Kette ohne Import des audio-Pakets
|
// the chain testable and reusable without importing the audio package.
|
||||||
// testbar und wiederverwendbar.
|
|
||||||
type Player interface {
|
type Player interface {
|
||||||
Play(ctx context.Context, data []byte) error
|
Play(ctx context.Context, data []byte) error
|
||||||
Name() string
|
Name() string
|
||||||
}
|
}
|
||||||
|
|
||||||
// ChainConfig ist alles, was die Kette zum Bau braucht. CLI (Task 03) und
|
// ChainConfig is everything the chain needs for construction. CLI and
|
||||||
// Daemon (Task 04) füllen sie aus Config + Flags; die Kette selbst liest
|
// daemon fill it from config + flags; the chain itself reads no files and
|
||||||
// keine Dateien und keine Prozess-Env — Getenv ist die injizierbare Seam
|
// no process environment. Getenv is the injectable seam (tests and daemon
|
||||||
// (Tests und Daemon kommen so ohne echte Keys aus).
|
// thus work without real keys).
|
||||||
type ChainConfig struct {
|
type ChainConfig struct {
|
||||||
// Pin reduziert die Kette auf genau einen Provider (CLI-Flag --provider
|
// Pin reduces the chain to exactly one provider (CLI flag --provider
|
||||||
// schlägt config `provider = "…"`). Leer = DefaultOrder.
|
// beats config `provider = "…"`). Empty = DefaultOrder.
|
||||||
Pin string
|
Pin string
|
||||||
|
|
||||||
// Voice ist eine explizite Voice-ID (CLI-Flag --voice); sie wird über
|
// Voice is an explicit voice ID (CLI flag --voice); it is pinned on all
|
||||||
// VoicePinner an alle Stufen gepinnt und schlägt Mapping + Defaults.
|
// tiers via VoicePinner and beats mapping + defaults.
|
||||||
Voice string
|
Voice string
|
||||||
|
|
||||||
// Voices ist das voice.<provider>.<lang>-Mapping aus der config.toml.
|
// Voices is the voice.<provider>.<lang> mapping from config.toml.
|
||||||
Voices map[string]map[string]string
|
Voices map[string]map[string]string
|
||||||
|
|
||||||
// Endpoints sind die Datei-Endpunkte [providers.<name>].endpoint;
|
// Endpoints are the file endpoints [providers.<name>].endpoint;
|
||||||
// TALK_<NAME>_ENDPOINT (via Getenv) schlägt sie, sie schlägt die
|
// TALK_<NAME>_ENDPOINT (via Getenv) beats them, they beat the built-in
|
||||||
// eingebauten Defaults (siehe endpointFrom).
|
// defaults (see endpointFrom).
|
||||||
Endpoints map[string]string
|
Endpoints map[string]string
|
||||||
|
|
||||||
// Model ist [providers.openai].model (leer = "tts-1").
|
// Model is [providers.openai].model (empty = "tts-1").
|
||||||
Model string
|
Model string
|
||||||
|
|
||||||
// Getenv liefert Umgebungsvariablen (Keys, Endpunkt-Overrides). Nil
|
// Getenv returns environment variables (keys, endpoint overrides). Nil
|
||||||
// wird beim Bau durch eine Funktion ersetzt, die immer "" liefert.
|
// is replaced at construction by a function that always returns "".
|
||||||
Getenv func(string) string
|
Getenv func(string) string
|
||||||
|
|
||||||
// Player gibt erfolgreiche Synthesen aus; nil = die Kette liefert nur
|
// Player plays successful syntheses; nil = the chain only returns bytes
|
||||||
// Bytes (Synthesize) und Speak meldet einen klaren Fehler.
|
// (Synthesize) and Speak reports a clear error.
|
||||||
Player Player
|
Player Player
|
||||||
|
|
||||||
// Log empfängt die Fallback-Protokoll-Zeilen (CLI: stderr). Fallbacks
|
// Log receives the fallback log lines (CLI: stderr). Fallbacks are never
|
||||||
// sind nie still: Jede übersprungene oder fehlgeschlagene Stufe wird
|
// silent: every skipped or failed tier is reported here, even when a
|
||||||
// hier gemeldet — auch wenn am Ende noch eine Stufe Erfolg hat.
|
// later tier succeeds.
|
||||||
Log io.Writer
|
Log io.Writer
|
||||||
}
|
}
|
||||||
|
|
||||||
// endpointFrom löst einen Provider-Endpunkt auf:
|
// endpointFrom resolves a provider endpoint:
|
||||||
// TALK_<NAME>_ENDPOINT (Env) > [providers.<name>].endpoint (Datei) >
|
// TALK_<NAME>_ENDPOINT (env) > [providers.<name>].endpoint (file) >
|
||||||
// eingebauter Default. Env-Overrides in der Provider-Schicht zu lesen hält
|
// built-in default. Reading env overrides in the provider layer keeps the
|
||||||
// das config-Paket frei von Provider-Namen und erlaubt Prozessgrenzen-
|
// config package free of provider names and allows process-boundary tests
|
||||||
// Tests ohne Config-Datei.
|
// without a config file.
|
||||||
func endpointFrom(cfg ChainConfig, name, envName, def string) string {
|
func endpointFrom(cfg ChainConfig, name, envName, def string) string {
|
||||||
if cfg.Getenv != nil {
|
if cfg.Getenv != nil {
|
||||||
if v := cfg.Getenv(envName); v != "" {
|
if v := cfg.Getenv(envName); v != "" {
|
||||||
@@ -84,25 +83,25 @@ func endpointFrom(cfg ChainConfig, name, envName, def string) string {
|
|||||||
return def
|
return def
|
||||||
}
|
}
|
||||||
|
|
||||||
// Chain ist die geordnete Fallback-Kette über Provider. Sie implementiert
|
// Chain is the ordered fallback chain over providers. It implements
|
||||||
// selbst Provider (Synthesize liefert die Bytes der ersten erfolgreichen
|
// Provider itself (Synthesize returns the bytes of the first successful
|
||||||
// Stufe) UND DirectSpeaker (letzter Stufen-Ausweg für Plattformen ohne
|
// tier) AND DirectSpeaker (last-resort tier for platforms without
|
||||||
// Byte-fähiges TTS) — damit ist sie für CLI und Daemon (Task 04)
|
// byte-capable TTS), so CLI and daemon can swap it for any single provider.
|
||||||
// austauschbar gegen jeden einzelnen Provider.
|
|
||||||
//
|
//
|
||||||
// Speak ist die komplette Ansage-Orchestrierung: Bytes-Synthese mit
|
// Speak is the complete announcement orchestration: byte synthesis with
|
||||||
// Fallback, Wiedergabe über den Player, und als letzte Stufe die
|
// fallback, playback via the Player, and as the last tier the direct
|
||||||
// Direktansage (osbuiltin über spd-say). Bei einem null-Player wird die
|
// announcement (osbuiltin via spd-say). With a null player the direct
|
||||||
// Direktansage tonlos verworfen (CI/Server) statt Ton zu erzeugen.
|
// announcement is discarded silently (CI/server) instead of producing
|
||||||
|
// sound.
|
||||||
type Chain struct {
|
type Chain struct {
|
||||||
cfg ChainConfig
|
cfg ChainConfig
|
||||||
tiers []Provider
|
tiers []Provider
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewChain baut die Kette: gepinnt (Pin) oder in DefaultOrder. Unbekannte
|
// NewChain builds the chain: pinned (Pin) or in DefaultOrder. Unknown names
|
||||||
// Namen sind ein klarer Fehler, der die verfügbaren Namen nennt. Das
|
// are a clear error that lists the available names. The --voice pin is
|
||||||
// --voice-Pin wird auf alle Stufen angewandt, die VoicePinner implementieren
|
// applied to all tiers implementing VoicePinner (tiers without a notion of
|
||||||
// (Stufen ohne Voice-Begriff bekommen einen protokollierten Hinweis).
|
// voice get a logged note).
|
||||||
func NewChain(cfg ChainConfig) (*Chain, error) {
|
func NewChain(cfg ChainConfig) (*Chain, error) {
|
||||||
if cfg.Getenv == nil {
|
if cfg.Getenv == nil {
|
||||||
cfg.Getenv = func(string) string { return "" }
|
cfg.Getenv = func(string) string { return "" }
|
||||||
@@ -121,7 +120,7 @@ func NewChain(cfg ChainConfig) (*Chain, error) {
|
|||||||
if vp, ok := p.(VoicePinner); ok {
|
if vp, ok := p.(VoicePinner); ok {
|
||||||
vp.PinVoice(cfg.Voice)
|
vp.PinVoice(cfg.Voice)
|
||||||
} else {
|
} else {
|
||||||
chainLogf(cfg, "kette: --voice für Stufe %s ignoriert (kennt keine Voice-IDs)\n", name)
|
chainLogf(cfg, "chain: --voice ignored for tier %s (it has no voice IDs)\n", name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
tiers = append(tiers, p)
|
tiers = append(tiers, p)
|
||||||
@@ -129,13 +128,13 @@ func NewChain(cfg ChainConfig) (*Chain, error) {
|
|||||||
return &Chain{cfg: cfg, tiers: tiers}, nil
|
return &Chain{cfg: cfg, tiers: tiers}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name implementiert Provider.
|
// Name implements Provider.
|
||||||
func (*Chain) Name() string { return "chain" }
|
func (*Chain) Name() string { return "chain" }
|
||||||
|
|
||||||
// Tiers liefert die Stufen in Ketten-Reihenfolge (Diagnose/doctor).
|
// Tiers returns the tiers in chain order (diagnosis/doctor).
|
||||||
func (c *Chain) Tiers() []Provider { return c.tiers }
|
func (c *Chain) Tiers() []Provider { return c.tiers }
|
||||||
|
|
||||||
// Available implementiert Provider: true, sobald eine Stunde verfügbar ist.
|
// Available implements Provider: true as soon as one tier is available.
|
||||||
func (c *Chain) Available(ctx context.Context) bool {
|
func (c *Chain) Available(ctx context.Context) bool {
|
||||||
for _, p := range c.tiers {
|
for _, p := range c.tiers {
|
||||||
if p.Available(ctx) {
|
if p.Available(ctx) {
|
||||||
@@ -145,55 +144,54 @@ func (c *Chain) Available(ctx context.Context) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// walkResult ist das interne Ergebnis des Ketten-Durchlaufs.
|
// walkResult is the internal result of a chain walk.
|
||||||
type walkResult struct {
|
type walkResult struct {
|
||||||
data []byte // Bytes der ersten erfolgreichen Stufe (nil = keine)
|
data []byte // bytes of the first successful tier (nil = none)
|
||||||
used Provider // die erfolgreiche Stufe
|
used Provider // the successful tier
|
||||||
direct DirectSpeaker // erste Stufe, die nur direkt sprechen kann
|
direct DirectSpeaker // first tier that can only speak directly
|
||||||
directName string
|
directName string
|
||||||
failed []string // "name: fehler" je fehlgeschlagener Stufe
|
failed []string // "name: error" per failed tier
|
||||||
skipped []string // Namen nicht verfügbarer Stufen
|
skipped []string // names of unavailable tiers
|
||||||
}
|
}
|
||||||
|
|
||||||
// walk läuft die Kette in Ordnung ab: nicht verfügbare Stufen werden
|
// walk runs the chain in order: unavailable tiers are skipped (logged),
|
||||||
// übersprungen (protokolliert), fehlgeschlagene protokolliert und
|
// failed ones are logged and passed over. A tier returning ErrNoByteOutput
|
||||||
// überwunden. Eine Stufe mit ErrNoByteOutput, die DirectSpeaker
|
// that implements DirectSpeaker is remembered as the last resort (the walk
|
||||||
// implementiert, wird als letzter Ausweg gemerkt (der Durchlauf geht
|
// continues; a later tier might still deliver bytes).
|
||||||
// weiter — eine spätere Stufe könnte noch Bytes liefern).
|
|
||||||
func (c *Chain) walk(ctx context.Context, text, lang string) walkResult {
|
func (c *Chain) walk(ctx context.Context, text, lang string) walkResult {
|
||||||
var r walkResult
|
var r walkResult
|
||||||
for _, p := range c.tiers {
|
for _, p := range c.tiers {
|
||||||
if !p.Available(ctx) {
|
if !p.Available(ctx) {
|
||||||
r.skipped = append(r.skipped, p.Name())
|
r.skipped = append(r.skipped, p.Name())
|
||||||
chainLogf(c.cfg, "kette: Stufe %s übersprungen (nicht verfügbar)\n", p.Name())
|
chainLogf(c.cfg, "chain: tier %s skipped (not available)\n", p.Name())
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
data, err := p.Synthesize(ctx, text, lang)
|
data, err := p.Synthesize(ctx, text, lang)
|
||||||
switch {
|
switch {
|
||||||
case err == nil:
|
case err == nil:
|
||||||
r.data, r.used = data, p
|
r.data, r.used = data, p
|
||||||
chainLogf(c.cfg, "kette: Ansage über %s\n", p.Name())
|
chainLogf(c.cfg, "chain: spoken via %s\n", p.Name())
|
||||||
return r
|
return r
|
||||||
case errors.Is(err, ErrNoByteOutput) && r.direct == nil:
|
case errors.Is(err, ErrNoByteOutput) && r.direct == nil:
|
||||||
if ds, ok := p.(DirectSpeaker); ok {
|
if ds, ok := p.(DirectSpeaker); ok {
|
||||||
r.direct, r.directName = ds, p.Name()
|
r.direct, r.directName = ds, p.Name()
|
||||||
chainLogf(c.cfg, "kette: Stufe %s liefert keine Bytes, kann aber direkt sprechen (als letzte Stufe gemerkt)\n", p.Name())
|
chainLogf(c.cfg, "chain: tier %s yields no bytes but can speak directly (kept as last resort)\n", p.Name())
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
r.failed = append(r.failed, p.Name()+": "+err.Error())
|
r.failed = append(r.failed, p.Name()+": "+err.Error())
|
||||||
chainLogf(c.cfg, "kette: Stufe %s fehlgeschlagen: %v — Fallback auf nächste Stufe\n", p.Name(), err)
|
chainLogf(c.cfg, "chain: tier %s failed: %v; falling back to the next tier\n", p.Name(), err)
|
||||||
default:
|
default:
|
||||||
r.failed = append(r.failed, p.Name()+": "+err.Error())
|
r.failed = append(r.failed, p.Name()+": "+err.Error())
|
||||||
chainLogf(c.cfg, "kette: Stufe %s fehlgeschlagen: %v — Fallback auf nächste Stufe\n", p.Name(), err)
|
chainLogf(c.cfg, "chain: tier %s failed: %v; falling back to the next tier\n", p.Name(), err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
// Synthesize implementiert Provider: Bytes der ersten erfolgreichen Stufe.
|
// Synthesize implements Provider: bytes of the first successful tier. If
|
||||||
// Kann nur eine Direkt-Stufe sprechen, ist der Fehler ErrNoByteOutput (die
|
// only a direct tier can speak, the error is ErrNoByteOutput (the chain thus
|
||||||
// Kette erfüllt damit den DirectSpeaker-Vertrag am Aufrufer). Scheitert
|
// honours the DirectSpeaker contract towards the caller). If everything
|
||||||
// alles, nennt der Fehler die letzte Stufen-Fehler — nie still.
|
// fails, the error names the tier errors; never silent.
|
||||||
func (c *Chain) Synthesize(ctx context.Context, text, lang string) ([]byte, error) {
|
func (c *Chain) Synthesize(ctx context.Context, text, lang string) ([]byte, error) {
|
||||||
r := c.walk(ctx, text, lang)
|
r := c.walk(ctx, text, lang)
|
||||||
if r.data != nil {
|
if r.data != nil {
|
||||||
@@ -201,50 +199,49 @@ func (c *Chain) Synthesize(ctx context.Context, text, lang string) ([]byte, erro
|
|||||||
}
|
}
|
||||||
if r.direct != nil {
|
if r.direct != nil {
|
||||||
if len(r.failed) > 0 {
|
if len(r.failed) > 0 {
|
||||||
return nil, fmt.Errorf("%w (Stufe %s spricht nur direkt; daneben fehlgeschlagen: %s)",
|
return nil, fmt.Errorf("%w (tier %s speaks directly only; also failed: %s)",
|
||||||
ErrNoByteOutput, r.directName, strings.Join(r.failed, "; "))
|
ErrNoByteOutput, r.directName, strings.Join(r.failed, "; "))
|
||||||
}
|
}
|
||||||
return nil, fmt.Errorf("%w (Stufe %s spricht nur direkt)", ErrNoByteOutput, r.directName)
|
return nil, fmt.Errorf("%w (tier %s speaks directly only)", ErrNoByteOutput, r.directName)
|
||||||
}
|
}
|
||||||
return nil, r.noTierErr()
|
return nil, r.noTierErr()
|
||||||
}
|
}
|
||||||
|
|
||||||
// SpeakDirect implementiert DirectSpeaker: Direktansage über die Stufe,
|
// SpeakDirect implements DirectSpeaker: direct announcement via the tier
|
||||||
// die nur direkt sprechen kann (typischerweise osbuiltin/spd-say auf Linux
|
// that can only speak directly (typically osbuiltin/spd-say on Linux
|
||||||
// ohne espeak). Gibt es eine Byte-fähige Stufe, ist SpeakDirect ein klarer
|
// without espeak). If a byte-capable tier exists, SpeakDirect is a clear
|
||||||
// Fehler (der Aufrufer soll Synthesize + Player nutzen).
|
// error (the caller should use Synthesize + Player).
|
||||||
func (c *Chain) SpeakDirect(ctx context.Context, text, lang string) error {
|
func (c *Chain) SpeakDirect(ctx context.Context, text, lang string) error {
|
||||||
r := c.walk(ctx, text, lang)
|
r := c.walk(ctx, text, lang)
|
||||||
if r.direct != nil {
|
if r.direct != nil {
|
||||||
return r.direct.SpeakDirect(ctx, text, lang)
|
return r.direct.SpeakDirect(ctx, text, lang)
|
||||||
}
|
}
|
||||||
if r.data != nil {
|
if r.data != nil {
|
||||||
return fmt.Errorf("kette: Stufe %s liefert Bytes — über Synthesize und den Player abspielen, nicht direkt", r.used.Name())
|
return fmt.Errorf("chain: tier %s yields bytes; play them via Synthesize and the player, not directly", r.used.Name())
|
||||||
}
|
}
|
||||||
return fmt.Errorf("kette: keine Stufe kann direkt sprechen (nicht verfügbar: %s; fehlgeschlagen: %s)",
|
return fmt.Errorf("chain: no tier can speak directly (not available: %s; failed: %s)",
|
||||||
joinOr(r.skipped, "keine"), joinOr(r.failed, "keine"))
|
joinOr(r.skipped, "none"), joinOr(r.failed, "none"))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Speak ist die komplette Ansage in EINEM Ketten-Durchlauf: Synthese mit
|
// Speak is the complete announcement in ONE chain walk: synthesis with
|
||||||
// Fallback → Wiedergabe über den Player; fällt die Kette auf die Direkt-
|
// fallback → playback via the Player; if the chain falls back to the direct
|
||||||
// Stufe zurück, entscheidet der Player-Name über Ton (alles außer „null")
|
// tier, the player name decides between sound (anything but "null") and
|
||||||
// oder tonloses Verwerfen (null: CI/Server bleiben fehler- und tonfrei,
|
// silent discarding (null: CI/server stay error- and sound-free, the
|
||||||
// der Verwurf wird protokolliert). Der Durchlauf findet bewusst genau
|
// discard is logged). The walk deliberately happens exactly once: failed
|
||||||
// einmal statt: fehlgeschlagene Cloud-Stufen werden nicht ein zweites Mal
|
// cloud tiers are not requested a second time (no duplicate POSTs to paid
|
||||||
// angefragt (keine doppelten POSTs auf bezahlten APIs, keine doppelten
|
// APIs, no duplicate log lines), and bytes from this walk are played
|
||||||
// Protokoll-Zeilen), und Bytes aus diesem Durchlauf werden abgespielt,
|
// instead of being thrown away and re-run. Only a failure of all tiers or a
|
||||||
// statt sie wegzuwerfen und neu zu laufen. Nur ein Fehler aller Stufen
|
// failed playback are errors.
|
||||||
// oder eine fehlgeschlagene Wiedergabe sind Fehler.
|
|
||||||
func (c *Chain) Speak(ctx context.Context, text, lang string) error {
|
func (c *Chain) Speak(ctx context.Context, text, lang string) error {
|
||||||
_, err := c.SpeakOutcome(ctx, text, lang)
|
_, err := c.SpeakOutcome(ctx, text, lang)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Outcome beschreibt eine gelungene Ansage: welche Stufe gesprochen hat,
|
// Outcome describes a successful announcement: which tier spoke, how long
|
||||||
// wie lange Synthese (Ketten-Durchlauf bis zu den Bytes) und Wiedergabe
|
// synthesis (chain walk up to the bytes) and playback took, and whether it
|
||||||
// gedauert haben, und ob es eine Direktansage war (keine Bytes, Provider
|
// was a direct announcement (no bytes, the provider plays itself; then
|
||||||
// spielt selbst — dann ist Synthesis die Gesamtzeit und Playback 0).
|
// Synthesis is the total time and Playback is 0). Discarded reports the
|
||||||
// Discarded meldet die tonlose Verwerfung einer Direktansage am null-Sink.
|
// silent discarding of a direct announcement on the null sink.
|
||||||
type Outcome struct {
|
type Outcome struct {
|
||||||
Provider string
|
Provider string
|
||||||
Direct bool
|
Direct bool
|
||||||
@@ -254,7 +251,7 @@ type Outcome struct {
|
|||||||
Playback time.Duration
|
Playback time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
// SpeakOutcome ist Speak mit Bericht (Diagnose: `talk test`, Daemon-Log).
|
// SpeakOutcome is Speak with a report (diagnosis: `talk test`, daemon log).
|
||||||
func (c *Chain) SpeakOutcome(ctx context.Context, text, lang string) (Outcome, error) {
|
func (c *Chain) SpeakOutcome(ctx context.Context, text, lang string) (Outcome, error) {
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
r := c.walk(ctx, text, lang)
|
r := c.walk(ctx, text, lang)
|
||||||
@@ -262,16 +259,16 @@ func (c *Chain) SpeakOutcome(ctx context.Context, text, lang string) (Outcome, e
|
|||||||
switch {
|
switch {
|
||||||
case r.data != nil:
|
case r.data != nil:
|
||||||
if c.cfg.Player == nil {
|
if c.cfg.Player == nil {
|
||||||
return Outcome{}, fmt.Errorf("kette: kein Player konfiguriert — Bytes können nicht abgespielt werden")
|
return Outcome{}, fmt.Errorf("chain: no player configured; bytes cannot be played")
|
||||||
}
|
}
|
||||||
playStart := time.Now()
|
playStart := time.Now()
|
||||||
if err := c.cfg.Player.Play(ctx, r.data); err != nil {
|
if err := c.cfg.Player.Play(ctx, r.data); err != nil {
|
||||||
return Outcome{}, fmt.Errorf("kette: Wiedergabe über %s fehlgeschlagen: %w", c.cfg.Player.Name(), err)
|
return Outcome{}, fmt.Errorf("chain: playback via %s failed: %w", c.cfg.Player.Name(), err)
|
||||||
}
|
}
|
||||||
return Outcome{Provider: r.used.Name(), Bytes: len(r.data), Synthesis: synth, Playback: time.Since(playStart)}, nil
|
return Outcome{Provider: r.used.Name(), Bytes: len(r.data), Synthesis: synth, Playback: time.Since(playStart)}, nil
|
||||||
case r.direct != nil:
|
case r.direct != nil:
|
||||||
if c.cfg.Player != nil && c.cfg.Player.Name() == NullPlayerName {
|
if c.cfg.Player != nil && c.cfg.Player.Name() == NullPlayerName {
|
||||||
chainLogf(c.cfg, "kette: Direktansage verworfen (audio.sink=null)\n")
|
chainLogf(c.cfg, "chain: direct speech discarded (audio.sink=null)\n")
|
||||||
return Outcome{Provider: r.directName, Direct: true, Discarded: true, Synthesis: synth}, nil
|
return Outcome{Provider: r.directName, Direct: true, Discarded: true, Synthesis: synth}, nil
|
||||||
}
|
}
|
||||||
if err := r.direct.SpeakDirect(ctx, text, lang); err != nil {
|
if err := r.direct.SpeakDirect(ctx, text, lang); err != nil {
|
||||||
@@ -283,22 +280,22 @@ func (c *Chain) SpeakOutcome(ctx context.Context, text, lang string) (Outcome, e
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// noTierErr bündelt den Ende-ohne-Ergebnis-Fehler eines Durchlaufs: keine
|
// noTierErr bundles the no-result error of a walk: no tier delivered bytes
|
||||||
// Stufe lieferte Bytes oder Direktansage — übersprungene (nicht verfügbar)
|
// or a direct announcement; skipped (unavailable) and failed tiers are
|
||||||
// und fehlgeschlagene Stufen werden genannt, nie still.
|
// named, never silent.
|
||||||
func (r walkResult) noTierErr() error {
|
func (r walkResult) noTierErr() error {
|
||||||
return fmt.Errorf("kette: keine Stufe konnte sprechen (nicht verfügbar: %s; fehlgeschlagen: %s)",
|
return fmt.Errorf("chain: no tier could speak (not available: %s; failed: %s)",
|
||||||
joinOr(r.skipped, "keine"), joinOr(r.failed, "keine"))
|
joinOr(r.skipped, "none"), joinOr(r.failed, "none"))
|
||||||
}
|
}
|
||||||
|
|
||||||
// chainLogf schreibt eine Protokoll-Zeile, wenn ein Log gesetzt ist.
|
// chainLogf writes a log line if a log is set.
|
||||||
func chainLogf(cfg ChainConfig, format string, args ...any) {
|
func chainLogf(cfg ChainConfig, format string, args ...any) {
|
||||||
if cfg.Log != nil {
|
if cfg.Log != nil {
|
||||||
fmt.Fprintf(cfg.Log, format, args...)
|
fmt.Fprintf(cfg.Log, format, args...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// joinOr verbindet Einträge mit sep; ist die Liste leer, kommt fallback.
|
// joinOr joins items with "; "; if the list is empty, fallback is returned.
|
||||||
func joinOr(items []string, fallback string) string {
|
func joinOr(items []string, fallback string) string {
|
||||||
if len(items) == 0 {
|
if len(items) == 0 {
|
||||||
return fallback
|
return fallback
|
||||||
|
|||||||
+104
-105
@@ -13,8 +13,8 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
// fakePlayer zeichnet Play-Aufrufe auf (Name steuert die null-Entscheidung
|
// fakePlayer records Play calls (the name drives the chain's null
|
||||||
// der Kette).
|
// decision).
|
||||||
type fakePlayer struct {
|
type fakePlayer struct {
|
||||||
name string
|
name string
|
||||||
played [][]byte
|
played [][]byte
|
||||||
@@ -26,8 +26,8 @@ func (f *fakePlayer) Play(_ context.Context, data []byte) error {
|
|||||||
}
|
}
|
||||||
func (f *fakePlayer) Name() string { return f.name }
|
func (f *fakePlayer) Name() string { return f.name }
|
||||||
|
|
||||||
// countingTTSServer antwortet mit status + body und zählt die Requests
|
// countingTTSServer responds with status + body and counts the requests
|
||||||
// (atomic, der Server kann mehrere Stufen-Requests sehen).
|
// (atomic; the server may see requests from several tiers).
|
||||||
func countingTTSServer(t *testing.T, status int, body []byte) (url string, hits *atomic.Int32) {
|
func countingTTSServer(t *testing.T, status int, body []byte) (url string, hits *atomic.Int32) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
var n atomic.Int32
|
var n atomic.Int32
|
||||||
@@ -40,13 +40,13 @@ func countingTTSServer(t *testing.T, status int, body []byte) (url string, hits
|
|||||||
return ts.URL, &n
|
return ts.URL, &n
|
||||||
}
|
}
|
||||||
|
|
||||||
// chainEnv baut die Getenv-Seam für Tests mit gefakten Cloud-Endpunkten.
|
// chainEnv builds the Getenv seam for tests with faked cloud endpoints.
|
||||||
func chainEnv(kv map[string]string) func(string) string {
|
func chainEnv(kv map[string]string) func(string) string {
|
||||||
return func(k string) string { return kv[k] }
|
return func(k string) string { return kv[k] }
|
||||||
}
|
}
|
||||||
|
|
||||||
// fakeProcBin schreibt ein ausführbares Shell-Skript (gleicher Mechanismus
|
// fakeProcBin writes an executable shell script (same mechanism as in
|
||||||
// wie in osbuiltin_test.go — echter Prozess, PATH-Manipulation).
|
// osbuiltin_test.go: real process, PATH manipulation).
|
||||||
func fakeProcBin(t *testing.T, dir, name, body string) {
|
func fakeProcBin(t *testing.T, dir, name, body string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
script := "#!/bin/sh\n" + body + "\n"
|
script := "#!/bin/sh\n" + body + "\n"
|
||||||
@@ -55,9 +55,9 @@ func fakeProcBin(t *testing.T, dir, name, body string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// cloudEnv liefert die Env-Map für eine Kette, deren elevenlabs-Stufe auf
|
// cloudEnv returns the env map for a chain whose elevenlabs tier points at
|
||||||
// elevenURL und deren openai-Stufe auf openaiURL zeigt (edge tot, damit
|
// elevenURL and whose openai tier points at openaiURL (edge is dead so that
|
||||||
// kein Test den echten Microsoft-Endpunkt anfasst).
|
// no test touches the real Microsoft endpoint).
|
||||||
func cloudEnv(elevenURL, openaiURL string, extra map[string]string) map[string]string {
|
func cloudEnv(elevenURL, openaiURL string, extra map[string]string) map[string]string {
|
||||||
kv := map[string]string{
|
kv := map[string]string{
|
||||||
EnvElevenLabsKey: "k",
|
EnvElevenLabsKey: "k",
|
||||||
@@ -72,11 +72,10 @@ func cloudEnv(elevenURL, openaiURL string, extra map[string]string) map[string]s
|
|||||||
return kv
|
return kv
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestChainFallbackErster500ZweiterTreffer (Abnahmekriterium aus dem
|
// TestChainFallbackFirst500SecondHit (acceptance criterion): tier 1
|
||||||
// Task-Brief): Stufe 1 (elevenlabs) antwortet 500 → die Kette fällt auf
|
// (elevenlabs) answers 500 → the chain falls through to tier 2 (openai),
|
||||||
// Stufe 2 (openai) durch, deren Bytes kommen zurück; der Fallback ist im
|
// whose bytes come back; the fallback is visible in the log, never silent.
|
||||||
// Log sichtbar, nie still.
|
func TestChainFallbackFirst500SecondHit(t *testing.T) {
|
||||||
func TestChainFallbackErster500ZweiterTreffer(t *testing.T) {
|
|
||||||
eleven, elHits := countingTTSServer(t, 500, []byte("boom"))
|
eleven, elHits := countingTTSServer(t, 500, []byte("boom"))
|
||||||
openai, oaHits := countingTTSServer(t, 200, fakeMP3)
|
openai, oaHits := countingTTSServer(t, 200, fakeMP3)
|
||||||
|
|
||||||
@@ -89,30 +88,30 @@ func TestChainFallbackErster500ZweiterTreffer(t *testing.T) {
|
|||||||
t.Fatalf("NewChain: %v", err)
|
t.Fatalf("NewChain: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
data, err := ch.Synthesize(context.Background(), "Hallo Welt", "de")
|
data, err := ch.Synthesize(context.Background(), "Hello world", "de")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Synthesize: %v", err)
|
t.Fatalf("Synthesize: %v", err)
|
||||||
}
|
}
|
||||||
if string(data) != string(fakeMP3) {
|
if string(data) != string(fakeMP3) {
|
||||||
t.Errorf("Synthesize = %q, want Bytes der openai-Stufe", data)
|
t.Errorf("Synthesize = %q, want bytes of the openai tier", data)
|
||||||
}
|
}
|
||||||
if elHits.Load() != 1 || oaHits.Load() != 1 {
|
if elHits.Load() != 1 || oaHits.Load() != 1 {
|
||||||
t.Errorf("Hits: elevenlabs = %d, openai = %d — want je 1 (500 → Fallback)", elHits.Load(), oaHits.Load())
|
t.Errorf("hits: elevenlabs = %d, openai = %d; want 1 each (500 → fallback)", elHits.Load(), oaHits.Load())
|
||||||
}
|
}
|
||||||
for _, want := range []string{"elevenlabs", "500", "Fallback", "Ansage über openai"} {
|
for _, want := range []string{"elevenlabs", "500", "falling back", "spoken via openai"} {
|
||||||
if !strings.Contains(log.String(), want) {
|
if !strings.Contains(log.String(), want) {
|
||||||
t.Errorf("Log = %q, will %q", log.String(), want)
|
t.Errorf("log = %q, want %q", log.String(), want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestChainAllesFehlt: beide Cloud-Stufen 500, edge tot, osbuiltin nicht
|
// TestChainEverythingFails: both cloud tiers 500, edge dead, osbuiltin not
|
||||||
// verfügbar → Fehler nennt die fehlgeschlagenen Stufen; Log zeigt jeden.
|
// available → the error names the failed tiers; the log shows each one.
|
||||||
func TestChainAllesFehlt(t *testing.T) {
|
func TestChainEverythingFails(t *testing.T) {
|
||||||
eleven, _ := countingTTSServer(t, 500, []byte("el-boom"))
|
eleven, _ := countingTTSServer(t, 500, []byte("el-boom"))
|
||||||
openai, _ := countingTTSServer(t, 500, []byte("oa-boom"))
|
openai, _ := countingTTSServer(t, 500, []byte("oa-boom"))
|
||||||
|
|
||||||
// PATH leer: osbuiltin nicht verfügbar.
|
// Empty PATH: osbuiltin not available.
|
||||||
t.Setenv("PATH", t.TempDir())
|
t.Setenv("PATH", t.TempDir())
|
||||||
|
|
||||||
var log bytes.Buffer
|
var log bytes.Buffer
|
||||||
@@ -124,21 +123,21 @@ func TestChainAllesFehlt(t *testing.T) {
|
|||||||
t.Fatalf("NewChain: %v", err)
|
t.Fatalf("NewChain: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = ch.Synthesize(context.Background(), "Hallo", "de")
|
_, err = ch.Synthesize(context.Background(), "Hello", "de")
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Fatal("Synthesize mit allen Stufen kaputt: kein Fehler")
|
t.Fatal("Synthesize with all tiers broken: no error")
|
||||||
}
|
}
|
||||||
for _, want := range []string{"elevenlabs", "openai", "osbuiltin", "500"} {
|
for _, want := range []string{"elevenlabs", "openai", "osbuiltin", "500"} {
|
||||||
if !strings.Contains(err.Error(), want) && !strings.Contains(log.String(), want) {
|
if !strings.Contains(err.Error(), want) && !strings.Contains(log.String(), want) {
|
||||||
t.Errorf("Weder Fehler (%v) noch Log nennen %q", err, want)
|
t.Errorf("neither error (%v) nor log mention %q", err, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestChainOhneKeysEdgeOsbuiltin (Abnahmekriterium): ohne jeden Key und
|
// TestChainWithoutKeysEdgeOsbuiltin (acceptance criterion): without any
|
||||||
// mit totem edge wählt die Kette osbuiltin — mit gefaktem espeak kommen
|
// key and with a dead edge, the chain picks osbuiltin; with a faked espeak
|
||||||
// dessen Bytes zurück.
|
// its bytes come back.
|
||||||
func TestChainOhneKeysEdgeOsbuiltin(t *testing.T) {
|
func TestChainWithoutKeysEdgeOsbuiltin(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
fakeProcBin(t, dir, "espeak", `printf 'RIFFxxxxWAVEfmt '`)
|
fakeProcBin(t, dir, "espeak", `printf 'RIFFxxxxWAVEfmt '`)
|
||||||
t.Setenv("PATH", dir)
|
t.Setenv("PATH", dir)
|
||||||
@@ -151,20 +150,20 @@ func TestChainOhneKeysEdgeOsbuiltin(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("NewChain: %v", err)
|
t.Fatalf("NewChain: %v", err)
|
||||||
}
|
}
|
||||||
data, err := ch.Synthesize(context.Background(), "Hallo", "de")
|
data, err := ch.Synthesize(context.Background(), "Hello", "de")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Synthesize: %v", err)
|
t.Fatalf("Synthesize: %v", err)
|
||||||
}
|
}
|
||||||
if !bytes.HasPrefix(data, []byte("RIFF")) {
|
if !bytes.HasPrefix(data, []byte("RIFF")) {
|
||||||
t.Errorf("Synthesize = %q, want WAV-Bytes des fake espeak", data)
|
t.Errorf("Synthesize = %q, want WAV bytes of the fake espeak", data)
|
||||||
}
|
}
|
||||||
if !strings.Contains(log.String(), "übersprungen (nicht verfügbar)") {
|
if !strings.Contains(log.String(), "skipped (not available)") {
|
||||||
t.Errorf("Log = %q, will Skip-Hinweise für die Key-Stufen", log.String())
|
t.Errorf("log = %q, want skip notes for the key tiers", log.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestChainPin: --provider/config pinnen die Kette auf genau eine Stufe —
|
// TestChainPin: --provider/config pin the chain to exactly one tier; other
|
||||||
// andere Stufen werden nicht einmal angefragt.
|
// tiers are not even requested.
|
||||||
func TestChainPin(t *testing.T) {
|
func TestChainPin(t *testing.T) {
|
||||||
eleven, elHits := countingTTSServer(t, 200, fakeMP3)
|
eleven, elHits := countingTTSServer(t, 200, fakeMP3)
|
||||||
openai, oaHits := countingTTSServer(t, 500, []byte("boom"))
|
openai, oaHits := countingTTSServer(t, 500, []byte("boom"))
|
||||||
@@ -176,24 +175,24 @@ func TestChainPin(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("NewChain: %v", err)
|
t.Fatalf("NewChain: %v", err)
|
||||||
}
|
}
|
||||||
if _, err := ch.Synthesize(context.Background(), "Hallo", "de"); err == nil {
|
if _, err := ch.Synthesize(context.Background(), "Hello", "de"); err == nil {
|
||||||
t.Fatal("Gepinnte kaputte Stufe soll fehlschlagen (kein Fallback bei Pin)")
|
t.Fatal("pinned broken tier should fail (no fallback when pinned)")
|
||||||
}
|
}
|
||||||
if elHits.Load() != 0 || oaHits.Load() != 1 {
|
if elHits.Load() != 0 || oaHits.Load() != 1 {
|
||||||
t.Errorf("Hits: elevenlabs = %d (want 0), openai = %d (want 1)", elHits.Load(), oaHits.Load())
|
t.Errorf("hits: elevenlabs = %d (want 0), openai = %d (want 1)", elHits.Load(), oaHits.Load())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestChainUnbekannterPin ist ein klarer Fehler mit Namensliste.
|
// TestChainUnknownPin is a clear error listing the names.
|
||||||
func TestChainUnbekannterPin(t *testing.T) {
|
func TestChainUnknownPin(t *testing.T) {
|
||||||
if _, err := NewChain(ChainConfig{Pin: "gibtsnicht"}); err == nil || !strings.Contains(err.Error(), "elevenlabs") {
|
if _, err := NewChain(ChainConfig{Pin: "doesnotexist"}); err == nil || !strings.Contains(err.Error(), "elevenlabs") {
|
||||||
t.Errorf("NewChain-Fehler = %v, will verfügbare Namen nennen", err)
|
t.Errorf("NewChain error = %v, want the available names", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestChainSpeakBytesUeberPlayer: erfolgreiche Synthese wird über den
|
// TestChainSpeakBytesViaPlayer: a successful synthesis is played via the
|
||||||
// Player abgespielt.
|
// Player.
|
||||||
func TestChainSpeakBytesUeberPlayer(t *testing.T) {
|
func TestChainSpeakBytesViaPlayer(t *testing.T) {
|
||||||
eleven, _ := countingTTSServer(t, 200, fakeMP3)
|
eleven, _ := countingTTSServer(t, 200, fakeMP3)
|
||||||
player := &fakePlayer{name: "oto"}
|
player := &fakePlayer{name: "oto"}
|
||||||
ch, err := NewChain(ChainConfig{
|
ch, err := NewChain(ChainConfig{
|
||||||
@@ -203,22 +202,22 @@ func TestChainSpeakBytesUeberPlayer(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("NewChain: %v", err)
|
t.Fatalf("NewChain: %v", err)
|
||||||
}
|
}
|
||||||
if err := ch.Speak(context.Background(), "Hallo", "de"); err != nil {
|
if err := ch.Speak(context.Background(), "Hello", "de"); err != nil {
|
||||||
t.Fatalf("Speak: %v", err)
|
t.Fatalf("Speak: %v", err)
|
||||||
}
|
}
|
||||||
if len(player.played) != 1 || string(player.played[0]) != string(fakeMP3) {
|
if len(player.played) != 1 || string(player.played[0]) != string(fakeMP3) {
|
||||||
t.Errorf("Player.Play = %x, want die Synthese-Bytes", player.played)
|
t.Errorf("Player.Play = %x, want the synthesis bytes", player.played)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestChainDirektMitNullPlayer: fällt die Kette auf die Direkt-Stufe
|
// TestChainDirectWithNullPlayer: when the chain falls back to the direct
|
||||||
// (osbuiltin ohne espeak), verwirft ein null-Player die Ansage tonlos und
|
// tier (osbuiltin without espeak), a null player discards the announcement
|
||||||
// SUCCESS — spd-say wird nicht gerufen.
|
// silently and SUCCEEDS; spd-say is not called.
|
||||||
func TestChainDirektMitNullPlayer(t *testing.T) {
|
func TestChainDirectWithNullPlayer(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
seen := filepath.Join(dir, "seen.txt")
|
seen := filepath.Join(dir, "seen.txt")
|
||||||
fakeProcBin(t, dir, "spd-say", `printf '%s\n' "$*" > "`+seen+`"`)
|
fakeProcBin(t, dir, "spd-say", `printf '%s\n' "$*" > "`+seen+`"`)
|
||||||
t.Setenv("PATH", dir) // kein espeak → keine Bytes, aber spd-say da
|
t.Setenv("PATH", dir) // no espeak → no bytes, but spd-say present
|
||||||
|
|
||||||
var log bytes.Buffer
|
var log bytes.Buffer
|
||||||
ch, err := NewChain(ChainConfig{
|
ch, err := NewChain(ChainConfig{
|
||||||
@@ -230,20 +229,21 @@ func TestChainDirektMitNullPlayer(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("NewChain: %v", err)
|
t.Fatalf("NewChain: %v", err)
|
||||||
}
|
}
|
||||||
if err := ch.Speak(context.Background(), "Hallo Welt", "de"); err != nil {
|
if err := ch.Speak(context.Background(), "Hello world", "de"); err != nil {
|
||||||
t.Fatalf("Speak (null-Player): %v", err)
|
t.Fatalf("Speak (null player): %v", err)
|
||||||
}
|
}
|
||||||
if _, err := os.Stat(seen); err == nil {
|
if _, err := os.Stat(seen); err == nil {
|
||||||
t.Error("spd-say wurde gerufen — null-Player hätte verwerfen müssen")
|
t.Error("spd-say was called; the null player should have discarded")
|
||||||
}
|
}
|
||||||
if !strings.Contains(log.String(), "verworfen") {
|
if !strings.Contains(log.String(), "discarded") {
|
||||||
t.Errorf("Log = %q, will Verwurf-Zeile", log.String())
|
t.Errorf("log = %q, want discard line", log.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestChainDirektMitTonPlayer: mit echtem Player (Name ≠ null) läuft die
|
// TestChainDirectWithSoundPlayer: with a real player (name != null) the
|
||||||
// Direktansage über SpeakDirect — blockierend (-w) mit Sprache und Text.
|
// direct announcement runs via SpeakDirect, blocking (-w) with language and
|
||||||
func TestChainDirektMitTonPlayer(t *testing.T) {
|
// text.
|
||||||
|
func TestChainDirectWithSoundPlayer(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
seen := filepath.Join(dir, "seen.txt")
|
seen := filepath.Join(dir, "seen.txt")
|
||||||
fakeProcBin(t, dir, "spd-say", `printf '%s\n' "$*" > "`+seen+`"`)
|
fakeProcBin(t, dir, "spd-say", `printf '%s\n' "$*" > "`+seen+`"`)
|
||||||
@@ -258,24 +258,24 @@ func TestChainDirektMitTonPlayer(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("NewChain: %v", err)
|
t.Fatalf("NewChain: %v", err)
|
||||||
}
|
}
|
||||||
if err := ch.Speak(context.Background(), "Hallo Welt", "de"); err != nil {
|
if err := ch.Speak(context.Background(), "Hello world", "de"); err != nil {
|
||||||
t.Fatalf("Speak (Direkt): %v", err)
|
t.Fatalf("Speak (direct): %v", err)
|
||||||
}
|
}
|
||||||
args, err := os.ReadFile(seen)
|
args, err := os.ReadFile(seen)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("fake spd-say nicht gerufen: %v", err)
|
t.Fatalf("fake spd-say not called: %v", err)
|
||||||
}
|
}
|
||||||
if got := strings.TrimSpace(string(args)); got != "-w -l de Hallo Welt" {
|
if got := strings.TrimSpace(string(args)); got != "-w -l de Hello world" {
|
||||||
t.Errorf("spd-say ARGS = %q, want %q", got, "-w -l de Hallo Welt")
|
t.Errorf("spd-say ARGS = %q, want %q", got, "-w -l de Hello world")
|
||||||
}
|
}
|
||||||
if len(player.played) != 0 {
|
if len(player.played) != 0 {
|
||||||
t.Errorf("Player.Play wurde gerufen (%x) — Direktansage geht am Player vorbei", player.played)
|
t.Errorf("Player.Play was called (%x); a direct announcement bypasses the player", player.played)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestChainSynthesizeErrNoByteOutput: Die Kette als Provider meldet
|
// TestChainSynthesizeErrNoByteOutput: the chain as a Provider reports
|
||||||
// ErrNoByteOutput, wenn nur eine Direkt-Stufe übrig bleibt — der
|
// ErrNoByteOutput when only a direct tier remains; the DirectSpeaker
|
||||||
// DirectSpeaker-Vertrag bleibt am Aufrufer erhalten.
|
// contract is preserved towards the caller.
|
||||||
func TestChainSynthesizeErrNoByteOutput(t *testing.T) {
|
func TestChainSynthesizeErrNoByteOutput(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
fakeProcBin(t, dir, "spd-say", "true")
|
fakeProcBin(t, dir, "spd-say", "true")
|
||||||
@@ -285,27 +285,27 @@ func TestChainSynthesizeErrNoByteOutput(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("NewChain: %v", err)
|
t.Fatalf("NewChain: %v", err)
|
||||||
}
|
}
|
||||||
_, err = ch.Synthesize(context.Background(), "Hallo", "de")
|
_, err = ch.Synthesize(context.Background(), "Hello", "de")
|
||||||
if !errors.Is(err, ErrNoByteOutput) {
|
if !errors.Is(err, ErrNoByteOutput) {
|
||||||
t.Fatalf("Synthesize-Fehler = %v, want ErrNoByteOutput", err)
|
t.Fatalf("Synthesize error = %v, want ErrNoByteOutput", err)
|
||||||
}
|
}
|
||||||
// Chain selbst ist DirectSpeaker.
|
// Chain itself is a DirectSpeaker.
|
||||||
if _, ok := any(ch).(DirectSpeaker); !ok {
|
if _, ok := any(ch).(DirectSpeaker); !ok {
|
||||||
t.Error("Chain implementiert DirectSpeaker nicht")
|
t.Error("Chain does not implement DirectSpeaker")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestChainAvailableUndNamen: Available true sobald eine Stufe verfügbar;
|
// TestChainAvailableAndNames: Available is true as soon as one tier is
|
||||||
// Default-Reihenfolge ist die bindende aus der Spec.
|
// available; the default order is the binding one from the spec.
|
||||||
func TestChainAvailableUndNamen(t *testing.T) {
|
func TestChainAvailableAndNames(t *testing.T) {
|
||||||
ch, err := NewChain(ChainConfig{Getenv: chainEnv(map[string]string{
|
ch, err := NewChain(ChainConfig{Getenv: chainEnv(map[string]string{
|
||||||
EnvEdgeEndpoint: "wss://edge.example.com", // edge: immer verfügbar mit Endpunkt
|
EnvEdgeEndpoint: "wss://edge.example.com", // edge: always available with an endpoint
|
||||||
})})
|
})})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("NewChain: %v", err)
|
t.Fatalf("NewChain: %v", err)
|
||||||
}
|
}
|
||||||
if !ch.Available(context.Background()) {
|
if !ch.Available(context.Background()) {
|
||||||
t.Error("Available = false trotz verfügbarer edge-Stufe")
|
t.Error("Available = false despite an available edge tier")
|
||||||
}
|
}
|
||||||
want := []string{"elevenlabs", "openai", "edge", "osbuiltin"}
|
want := []string{"elevenlabs", "openai", "edge", "osbuiltin"}
|
||||||
if len(ch.Tiers()) != len(want) {
|
if len(ch.Tiers()) != len(want) {
|
||||||
@@ -318,9 +318,9 @@ func TestChainAvailableUndNamen(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestChainVoicePinDurchgereicht: ChainConfig.Voice wird via VoicePinner an
|
// TestChainVoicePinForwarded: ChainConfig.Voice is pinned on the tiers via
|
||||||
// die Stufen gepinnt — beobachtbar am Request-Pfad des ElevenLabs-Fakes.
|
// VoicePinner; observable in the request path of the ElevenLabs fake.
|
||||||
func TestChainVoicePinDurchgereicht(t *testing.T) {
|
func TestChainVoicePinForwarded(t *testing.T) {
|
||||||
ts, rec := fakeTTSServer(t, 200, fakeMP3)
|
ts, rec := fakeTTSServer(t, 200, fakeMP3)
|
||||||
ch, err := NewChain(ChainConfig{
|
ch, err := NewChain(ChainConfig{
|
||||||
Pin: "elevenlabs",
|
Pin: "elevenlabs",
|
||||||
@@ -333,24 +333,23 @@ func TestChainVoicePinDurchgereicht(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("NewChain: %v", err)
|
t.Fatalf("NewChain: %v", err)
|
||||||
}
|
}
|
||||||
if _, err := ch.Synthesize(context.Background(), "Hallo", "de"); err != nil {
|
if _, err := ch.Synthesize(context.Background(), "Hello", "de"); err != nil {
|
||||||
t.Fatalf("Synthesize: %v", err)
|
t.Fatalf("Synthesize: %v", err)
|
||||||
}
|
}
|
||||||
if want := "/v1/text-to-speech/ChainVoice"; rec.path != want {
|
if want := "/v1/text-to-speech/ChainVoice"; rec.path != want {
|
||||||
t.Errorf("Pfad = %q, want %q", rec.path, want)
|
t.Errorf("path = %q, want %q", rec.path, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestChainDirektEndgameEinDurchlauf (Review-Fix): Im DirectSpeaker-
|
// TestChainDirectEndgameSingleWalk (review fix): in the DirectSpeaker
|
||||||
// Endgame läuft die Kette genau EINMAL — die fehlgeschlagene Cloud-Stufe
|
// endgame the chain walks exactly ONCE; the failed cloud tier is requested
|
||||||
// wird nur einmal angefragt (keine doppelten POSTs auf bezahlten APIs,
|
// only once (no duplicate POSTs to paid APIs, no doubled latency), every
|
||||||
// keine verdoppelte Latenz), jede Stufe protokolliert ihren Fehlschlag
|
// tier logs its failure exactly once, and the direct announcement happens.
|
||||||
// genau einmal, und die Direktansage kommt zustande.
|
func TestChainDirectEndgameSingleWalk(t *testing.T) {
|
||||||
func TestChainDirektEndgameEinDurchlauf(t *testing.T) {
|
|
||||||
eleven, elHits := countingTTSServer(t, 500, []byte("boom"))
|
eleven, elHits := countingTTSServer(t, 500, []byte("boom"))
|
||||||
// elevenlabs: Key + Fake (500). openai: Endpunkt, aber KEIN Key →
|
// elevenlabs: key + fake (500). openai: endpoint but NO key → skipped.
|
||||||
// übersprungen. edge: toter Loopback-Port. osbuiltin: PATH nur mit
|
// edge: dead loopback port. osbuiltin: PATH with only a fake spd-say (no
|
||||||
// fake spd-say (kein espeak) → keine Bytes, Direktansage.
|
// espeak) → no bytes, direct announcement.
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
seen := filepath.Join(dir, "seen.txt")
|
seen := filepath.Join(dir, "seen.txt")
|
||||||
fakeProcBin(t, dir, "spd-say", `printf '%s\n' "$*" > "`+seen+`"`)
|
fakeProcBin(t, dir, "spd-say", `printf '%s\n' "$*" > "`+seen+`"`)
|
||||||
@@ -361,7 +360,7 @@ func TestChainDirektEndgameEinDurchlauf(t *testing.T) {
|
|||||||
Getenv: chainEnv(map[string]string{
|
Getenv: chainEnv(map[string]string{
|
||||||
EnvElevenLabsKey: "k",
|
EnvElevenLabsKey: "k",
|
||||||
EnvElevenLabsEndpoint: eleven,
|
EnvElevenLabsEndpoint: eleven,
|
||||||
EnvOpenAIEndpoint: eleven, // ohne Key ohnehin übersprungen
|
EnvOpenAIEndpoint: eleven, // skipped anyway without a key
|
||||||
EnvEdgeEndpoint: "ws://127.0.0.1:1/",
|
EnvEdgeEndpoint: "ws://127.0.0.1:1/",
|
||||||
}),
|
}),
|
||||||
Player: &fakePlayer{name: "oto"},
|
Player: &fakePlayer{name: "oto"},
|
||||||
@@ -371,25 +370,25 @@ func TestChainDirektEndgameEinDurchlauf(t *testing.T) {
|
|||||||
t.Fatalf("NewChain: %v", err)
|
t.Fatalf("NewChain: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := ch.Speak(context.Background(), "Hallo Welt", "de"); err != nil {
|
if err := ch.Speak(context.Background(), "Hello world", "de"); err != nil {
|
||||||
t.Fatalf("Speak (Direkt-Endgame): %v", err)
|
t.Fatalf("Speak (direct endgame): %v", err)
|
||||||
}
|
}
|
||||||
if got := elHits.Load(); got != 1 {
|
if got := elHits.Load(); got != 1 {
|
||||||
t.Errorf("elevenlabs wurde %d× angefragt, want genau 1 (kein zweiter Durchlauf)", got)
|
t.Errorf("elevenlabs was requested %d times, want exactly 1 (no second walk)", got)
|
||||||
}
|
}
|
||||||
for _, tier := range []string{"elevenlabs", "edge"} {
|
for _, tier := range []string{"elevenlabs", "edge"} {
|
||||||
if got := strings.Count(log.String(), "Stufe "+tier+" fehlgeschlagen"); got != 1 {
|
if got := strings.Count(log.String(), "tier "+tier+" failed"); got != 1 {
|
||||||
t.Errorf("„Stufe %s fehlgeschlagen“ steht %d× im Log, want genau 1:\n%s", tier, got, log.String())
|
t.Errorf("\"tier %s failed\" appears %d times in the log, want exactly 1:\n%s", tier, got, log.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if got := strings.Count(log.String(), "Stufe openai übersprungen"); got != 1 {
|
if got := strings.Count(log.String(), "tier openai skipped"); got != 1 {
|
||||||
t.Errorf("openai-Skip steht %d× im Log, want genau 1", got)
|
t.Errorf("openai skip appears %d times in the log, want exactly 1", got)
|
||||||
}
|
}
|
||||||
args, err := os.ReadFile(seen)
|
args, err := os.ReadFile(seen)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("fake spd-say nicht gerufen: %v", err)
|
t.Fatalf("fake spd-say not called: %v", err)
|
||||||
}
|
}
|
||||||
if got := strings.TrimSpace(string(args)); got != "-w -l de Hallo Welt" {
|
if got := strings.TrimSpace(string(args)); got != "-w -l de Hello world" {
|
||||||
t.Errorf("spd-say ARGS = %q, want %q", got, "-w -l de Hallo Welt")
|
t.Errorf("spd-say ARGS = %q, want %q", got, "-w -l de Hello world")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+10
-11
@@ -1,12 +1,11 @@
|
|||||||
// Package provider implementiert die TTS-Provider von talk und ihre
|
// Package provider implements talk's TTS providers and their fallback
|
||||||
// Fallback-Kette. Der Vertrag (Name/Available/Synthesize) trägt die
|
// chain. The contract (Name/Available/Synthesize) carries the four-tier
|
||||||
// Vier-Stufen-Kette aus Task 03: ElevenLabs → OpenAI TTS → Edge-TTS →
|
// chain: ElevenLabs → OpenAI TTS → Edge TTS → OS built-in (overridable via
|
||||||
// OS built-in (überschreibbar per --provider/config provider). Die
|
// --provider/config provider). The cloud providers return MP3 (keys come
|
||||||
// Cloud-Provider liefern MP3 (Keys ausschließlich über TALK_ELEVENLABS_KEY
|
// exclusively from TALK_ELEVENLABS_KEY and TALK_OPENAI_KEY, endpoints are
|
||||||
// bzw. TALK_OPENAI_KEY, Endpunkte konfigurierbar und damit fake-bar);
|
// configurable and therefore fakeable); osbuiltin returns RIFF/WAVE PCM.
|
||||||
// osbuiltin liefert RIFF/WAVE-PCM. Die dokumentierte optionale Erweiterung
|
// The documented optional extension DirectSpeaker covers platforms whose
|
||||||
// DirectSpeaker deckt Plattformen ab, deren OS-TTS keine Audio-Bytes
|
// OS TTS cannot provide audio bytes (Linux speech-dispatcher); Chain.Speak
|
||||||
// liefern kann (Linux speech-dispatcher) — Chain.Speak behandelt diesen
|
// handles that case, including silent discarding on the null sink, so that
|
||||||
// Fall inklusive tonlosem Verwerfen am null-Sink, damit CLI (Task 03) und
|
// the CLI and the daemon use the same chain unchanged.
|
||||||
// Daemon (Task 04) dieselbe Kette unverändert nutzen.
|
|
||||||
package provider
|
package provider
|
||||||
+77
-78
@@ -16,20 +16,19 @@ import (
|
|||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Edge-TTS-Konstanten. Das Protokoll ist das bekannte, von edge-tts
|
// Edge TTS constants. The protocol is the well-known "Read Aloud" protocol
|
||||||
// reverse-engineerte „Read Aloud"-Protokoll von Microsoft Edge — Stand der
|
// of Microsoft Edge, reverse-engineered by edge-tts. State of the
|
||||||
// Implementierung (2026): DRM-Token Sec-MS-GEC v2 (CS64 + verschleierte
|
// implementation (2026): DRM token Sec-MS-GEC v2 (CS64 + obfuscated SHA-256
|
||||||
// SHA-256-Variante, siehe edgedrm.go) + MUID-Cookie, im Übrigen das
|
// variant, see edgedrm.go) + MUID cookie; otherwise the known WebSocket
|
||||||
// bekannte WebSocket-Nachrichtenformat (speech.config + SSML, Binär-Rahmen
|
// message format (speech.config + SSML, binary frames with a 2-byte header
|
||||||
// mit 2-Byte-Header-Länge, turn.end). Ändert Microsoft es, liefern die
|
// length, turn.end). If Microsoft changes it, the synthesis paths return
|
||||||
// Synthese-Pfade klare Fehler mit Hinweis auf Protokoll-Änderung statt
|
// clear errors hinting at a protocol change instead of failing silently.
|
||||||
// stiller Fehlfunktion.
|
|
||||||
const (
|
const (
|
||||||
// DefaultEndpointEdge ist der produktive WebSocket-Endpunkt (Pfad ohne
|
// DefaultEndpointEdge is the production WebSocket endpoint (path without
|
||||||
// Query — Token/ConnectionId/Sec-MS-GEC werden in requestURL ergänzt).
|
// query; token/ConnectionId/Sec-MS-GEC are added in requestURL).
|
||||||
DefaultEndpointEdge = "wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1"
|
DefaultEndpointEdge = "wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1"
|
||||||
|
|
||||||
// EnvEdgeEndpoint überschreibt den Endpunkt (Tests/Firmenserver).
|
// EnvEdgeEndpoint overrides the endpoint (tests/corporate servers).
|
||||||
EnvEdgeEndpoint = "TALK_EDGE_ENDPOINT"
|
EnvEdgeEndpoint = "TALK_EDGE_ENDPOINT"
|
||||||
|
|
||||||
edgeTrustedClientToken = "6A5AA1D4EAFF4E9FB37E23D68491D6F4"
|
edgeTrustedClientToken = "6A5AA1D4EAFF4E9FB37E23D68491D6F4"
|
||||||
@@ -39,36 +38,36 @@ const (
|
|||||||
edgeOutputFormat = "audio-24khz-48kbitrate-mono-mp3" // mp3!
|
edgeOutputFormat = "audio-24khz-48kbitrate-mono-mp3" // mp3!
|
||||||
)
|
)
|
||||||
|
|
||||||
// edgeIOTimeout begrenzt einzelne Lese-/Schreiboperationen sowie (wenn der
|
// edgeIOTimeout bounds individual read/write operations and (if the caller
|
||||||
// Aufrufer keine Deadline mitgibt) die gesamte Synthese.
|
// provides no deadline) the whole synthesis.
|
||||||
const edgeIOTimeout = 20 * time.Second
|
const edgeIOTimeout = 20 * time.Second
|
||||||
|
|
||||||
// edgeClockSkew korrigiert lokale Uhrenabweichung: Bei 403 liest die Kette
|
// edgeClockSkew corrects local clock drift: on 403 the provider reads the
|
||||||
// das Date-Header-Feld der Antwort und justiert die Tick-Berechnung (ein
|
// Date header of the response and adjusts the tick calculation (one retry,
|
||||||
// Wiederholungsversuch, wie die edge-tts-Referenz).
|
// like the edge-tts reference).
|
||||||
var edgeClockSkew atomic.Int64
|
var edgeClockSkew atomic.Int64
|
||||||
|
|
||||||
// Edge ist die kostenlose dritte Stufe der Kette: Microsofts „Read Aloud"-
|
// Edge is the free third tier of the chain: Microsoft's "Read Aloud"
|
||||||
// Endpoint, kein Key nötig. Synthesize öffnet eine WebSocket-Verbindung,
|
// endpoint, no key needed. Synthesize opens a WebSocket connection, sends
|
||||||
// sendet speech.config + SSML-Anfrage und sammelt die Binär-Audio-Frames
|
// speech.config + the SSML request and collects the binary audio frames
|
||||||
// bis turn.end. Rückgabeformat: MP3 (24 kHz mono — der audio-Sink
|
// until turn.end. Return format: MP3 (24 kHz mono; the audio sink decodes
|
||||||
// dekodiert das Format).
|
// the format).
|
||||||
type Edge struct {
|
type Edge struct {
|
||||||
// Endpoint ist die WebSocket-URL (ws:// oder wss://), leer = Default.
|
// Endpoint is the WebSocket URL (ws:// or wss://), empty = default.
|
||||||
Endpoint string
|
Endpoint string
|
||||||
|
|
||||||
// Voices ist das config-Mapping voice.edge.<lang> = id; leer = neutrale
|
// Voices is the config mapping voice.edge.<lang> = id; empty = neutral
|
||||||
// Repo-Defaults (de-DE-KatjaNeural / en-US-AriaNeural).
|
// repo defaults (de-DE-KatjaNeural / en-US-AriaNeural).
|
||||||
Voices map[string]string
|
Voices map[string]string
|
||||||
|
|
||||||
// Dialer ist der WebSocket-Dialer; nil = websocket.DefaultDialer.
|
// Dialer is the WebSocket dialer; nil = websocket.DefaultDialer.
|
||||||
Dialer *websocket.Dialer
|
Dialer *websocket.Dialer
|
||||||
|
|
||||||
pinned string // --voice-Pin (VoicePinner)
|
pinned string // --voice pin (VoicePinner)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewEdge baut den Provider aus der Ketten-Konfiguration: Endpunkt aus
|
// NewEdge builds the provider from the chain configuration: endpoint from
|
||||||
// TALK_EDGE_ENDPOINT > [providers.edge].endpoint > Default.
|
// TALK_EDGE_ENDPOINT > [providers.edge].endpoint > default.
|
||||||
func NewEdge(cfg ChainConfig) *Edge {
|
func NewEdge(cfg ChainConfig) *Edge {
|
||||||
return &Edge{
|
return &Edge{
|
||||||
Endpoint: endpointFrom(cfg, "edge", EnvEdgeEndpoint, DefaultEndpointEdge),
|
Endpoint: endpointFrom(cfg, "edge", EnvEdgeEndpoint, DefaultEndpointEdge),
|
||||||
@@ -76,25 +75,25 @@ func NewEdge(cfg ChainConfig) *Edge {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name implementiert Provider.
|
// Name implements Provider.
|
||||||
func (*Edge) Name() string { return "edge" }
|
func (*Edge) Name() string { return "edge" }
|
||||||
|
|
||||||
// PinVoice implementiert VoicePinner (CLI-Flag --voice).
|
// PinVoice implements VoicePinner (CLI flag --voice).
|
||||||
func (p *Edge) PinVoice(id string) { p.pinned = id }
|
func (p *Edge) PinVoice(id string) { p.pinned = id }
|
||||||
|
|
||||||
// Available implementiert Provider: Edge braucht nur einen Endpunkt —
|
// Available implements Provider: Edge only needs an endpoint, deliberately
|
||||||
// bewusst ohne Netz-Call (Erreichbarkeit stellt Synthesize fest, an deren
|
// without a network call (reachability is determined by Synthesize, on
|
||||||
// Fehler fällt die Kette weiter).
|
// whose error the chain falls back).
|
||||||
func (p *Edge) Available(ctx context.Context) bool { return p.Endpoint != "" }
|
func (p *Edge) Available(ctx context.Context) bool { return p.Endpoint != "" }
|
||||||
|
|
||||||
// Synthesize implementiert Provider. Rückgabeformat: MP3.
|
// Synthesize implements Provider. Return format: MP3.
|
||||||
func (p *Edge) Synthesize(ctx context.Context, text, lang string) ([]byte, error) {
|
func (p *Edge) Synthesize(ctx context.Context, text, lang string) ([]byte, error) {
|
||||||
if text == "" {
|
if text == "" {
|
||||||
return nil, fmt.Errorf("edge: leerer Text")
|
return nil, fmt.Errorf("edge: empty text")
|
||||||
}
|
}
|
||||||
voice := resolveVoice("edge", lang, p.pinned, p.Voices)
|
voice := resolveVoice("edge", lang, p.pinned, p.Voices)
|
||||||
if voice == "" {
|
if voice == "" {
|
||||||
return nil, fmt.Errorf("edge: keine Stimme für Sprache %q konfiguriert", lang)
|
return nil, fmt.Errorf("edge: no voice configured for language %q", lang)
|
||||||
}
|
}
|
||||||
if _, hasDeadline := ctx.Deadline(); !hasDeadline {
|
if _, hasDeadline := ctx.Deadline(); !hasDeadline {
|
||||||
var cancel context.CancelFunc
|
var cancel context.CancelFunc
|
||||||
@@ -135,7 +134,7 @@ func (p *Edge) Synthesize(ctx context.Context, text, lang string) ([]byte, error
|
|||||||
case websocket.TextMessage:
|
case websocket.TextMessage:
|
||||||
if strings.Contains(string(msg), "Path:turn.end") {
|
if strings.Contains(string(msg), "Path:turn.end") {
|
||||||
if audio.Len() == 0 {
|
if audio.Len() == 0 {
|
||||||
return nil, fmt.Errorf("edge: Server meldete turn.end ohne Audio-Frames — Protokoll geändert? (%s)", redactURL(wsURL))
|
return nil, fmt.Errorf("edge: server sent turn.end without audio frames; protocol changed? (%s)", redactURL(wsURL))
|
||||||
}
|
}
|
||||||
return audio.Bytes(), nil
|
return audio.Bytes(), nil
|
||||||
}
|
}
|
||||||
@@ -148,8 +147,8 @@ func (p *Edge) Synthesize(ctx context.Context, text, lang string) ([]byte, error
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// dialWithSkewRetry baut die Verbindung; bei 403 (Uhrabweichung) wird der
|
// dialWithSkewRetry establishes the connection; on 403 (clock drift) the
|
||||||
// Server-Zeitstempel übernommen und EINMAL wiederholt.
|
// server timestamp is adopted and the dial is retried ONCE.
|
||||||
func (p *Edge) dialWithSkewRetry(ctx context.Context) (*websocket.Conn, string, error) {
|
func (p *Edge) dialWithSkewRetry(ctx context.Context) (*websocket.Conn, string, error) {
|
||||||
conn, wsURL, resp, err := p.dial(ctx)
|
conn, wsURL, resp, err := p.dial(ctx)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -167,16 +166,16 @@ func (p *Edge) dialWithSkewRetry(ctx context.Context) (*websocket.Conn, string,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if resp != nil {
|
if resp != nil {
|
||||||
return nil, wsURL, fmt.Errorf("edge: WebSocket-Verbindung zu %s fehlgeschlagen (HTTP %d; Netz/Timeout oder Protokoll geändert?): %w",
|
return nil, wsURL, fmt.Errorf("edge: WebSocket connection to %s failed (HTTP %d; network/timeout, or the Edge TTS protocol changed?): %w",
|
||||||
redactURL(wsURL), resp.StatusCode, err)
|
redactURL(wsURL), resp.StatusCode, err)
|
||||||
}
|
}
|
||||||
return nil, wsURL, fmt.Errorf("edge: WebSocket-Verbindung zu %s fehlgeschlagen — Netz/Timeout oder das Edge-TTS-Protokoll hat sich geändert: %w",
|
return nil, wsURL, fmt.Errorf("edge: WebSocket connection to %s failed; network/timeout, or the Edge TTS protocol changed: %w",
|
||||||
redactURL(wsURL), err)
|
redactURL(wsURL), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// dial öffnet die Verbindung gemäß Protokoll: Query mit Token,
|
// dial opens the connection according to the protocol: query with token,
|
||||||
// ConnectionId, Sec-MS-GEC (v2) und Version; Header mit Origin,
|
// ConnectionId, Sec-MS-GEC (v2) and version; headers with Origin, Edge
|
||||||
// Edge-User-Agent und MUID-Cookie.
|
// user agent and MUID cookie.
|
||||||
func (p *Edge) dial(ctx context.Context) (*websocket.Conn, string, *http.Response, error) {
|
func (p *Edge) dial(ctx context.Context) (*websocket.Conn, string, *http.Response, error) {
|
||||||
wsURL, err := p.requestURL(time.Now())
|
wsURL, err := p.requestURL(time.Now())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -200,18 +199,18 @@ func (p *Edge) dial(ctx context.Context) (*websocket.Conn, string, *http.Respons
|
|||||||
return conn, wsURL, nil, nil
|
return conn, wsURL, nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// requestURL ergänzt die Protokoll-Query-Parameter und validiert das
|
// requestURL adds the protocol query parameters and validates the scheme
|
||||||
// Schema (ws/wss).
|
// (ws/wss).
|
||||||
func (p *Edge) requestURL(now time.Time) (string, error) {
|
func (p *Edge) requestURL(now time.Time) (string, error) {
|
||||||
if p.Endpoint == "" {
|
if p.Endpoint == "" {
|
||||||
return "", fmt.Errorf("edge: kein Endpunkt konfiguriert")
|
return "", fmt.Errorf("edge: no endpoint configured")
|
||||||
}
|
}
|
||||||
u, err := url.Parse(p.Endpoint)
|
u, err := url.Parse(p.Endpoint)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("edge: Endpunkt %q unlesbar: %w", p.Endpoint, err)
|
return "", fmt.Errorf("edge: endpoint %q unreadable: %w", p.Endpoint, err)
|
||||||
}
|
}
|
||||||
if u.Scheme != "ws" && u.Scheme != "wss" {
|
if u.Scheme != "ws" && u.Scheme != "wss" {
|
||||||
return "", fmt.Errorf("edge: Endpunkt %q muss ws:// oder wss:// sein (ist %q)", p.Endpoint, u.Scheme)
|
return "", fmt.Errorf("edge: endpoint %q must be ws:// or wss:// (is %q)", p.Endpoint, u.Scheme)
|
||||||
}
|
}
|
||||||
q := u.Query()
|
q := u.Query()
|
||||||
q.Set("TrustedClientToken", edgeTrustedClientToken)
|
q.Set("TrustedClientToken", edgeTrustedClientToken)
|
||||||
@@ -222,12 +221,12 @@ func (p *Edge) requestURL(now time.Time) (string, error) {
|
|||||||
return u.String(), nil
|
return u.String(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// edgeSecMSGEC erzeugt den DRM-Token Sec-MS-GEC v2: Windows-Filetime-Ticks
|
// edgeSecMSGEC produces the DRM token Sec-MS-GEC v2: Windows filetime ticks
|
||||||
// (100 ns, 5-Minuten-Raster, Uhrenkorrektur) + Trusted-Client-Token →
|
// (100 ns, 5-minute grid, clock correction) + trusted client token →
|
||||||
// „<CS64>-<SHA256-Variante>" (beides großes Hex, siehe edgedrm.go).
|
// "<CS64>-<SHA256 variant>" (both upper-case hex, see edgedrm.go).
|
||||||
func edgeSecMSGEC(now time.Time) string {
|
func edgeSecMSGEC(now time.Time) string {
|
||||||
secs := now.Unix() + edgeClockSkew.Load() + drmWinEpoch
|
secs := now.Unix() + edgeClockSkew.Load() + drmWinEpoch
|
||||||
secs -= secs % 300 // 5-Minuten-Raster
|
secs -= secs % 300 // 5-minute grid
|
||||||
ticks := uint64(secs) * 10_000_000
|
ticks := uint64(secs) * 10_000_000
|
||||||
strToHash := fmt.Appendf(nil, "%d%s", ticks, edgeTrustedClientToken)
|
strToHash := fmt.Appendf(nil, "%d%s", ticks, edgeTrustedClientToken)
|
||||||
digest := drmSHA256Digest(strToHash)
|
digest := drmSHA256Digest(strToHash)
|
||||||
@@ -253,16 +252,16 @@ func edgeSecMSGEC(now time.Time) string {
|
|||||||
return strings.ToUpper(hex.EncodeToString(cs64Buf[:])) + "-" + strings.ToUpper(hex.EncodeToString(shaBuf[:]))
|
return strings.ToUpper(hex.EncodeToString(cs64Buf[:])) + "-" + strings.ToUpper(hex.EncodeToString(shaBuf[:]))
|
||||||
}
|
}
|
||||||
|
|
||||||
// protocolErr überführt Lese-/Schreib-/Verbindungsabbrüche in klare
|
// protocolErr turns read/write/connection aborts into clear "protocol
|
||||||
// „Protokoll geändert?"-Fehler — Edge ist ein undokumentierter Endpoint,
|
// changed?" errors; Edge is an undocumented endpoint and changes should be
|
||||||
// Änderungen sollen sofort diagnostizierbar sein.
|
// diagnosable immediately.
|
||||||
func protocolErr(err error) error {
|
func protocolErr(err error) error {
|
||||||
return fmt.Errorf("edge: Kommunikation fehlgeschlagen — Netz/Timeout oder das Edge-TTS-Protokoll hat sich geändert: %w", err)
|
return fmt.Errorf("edge: communication failed; network/timeout, or the Edge TTS protocol changed: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// splitEdgeBinary zerlegt eine binäre Server-Nachricht: Die ersten 2 Bytes
|
// splitEdgeBinary splits a binary server message: the first 2 bytes
|
||||||
// (big-endian) geben die Länge des Header-Blocks an (CRLF-Zeilen wie
|
// (big-endian) give the length of the header block (CRLF lines such as
|
||||||
// „Path:audio"), danach kommt die Audio-Payload.
|
// "Path:audio"), followed by the audio payload.
|
||||||
func splitEdgeBinary(msg []byte) (header string, payload []byte, ok bool) {
|
func splitEdgeBinary(msg []byte) (header string, payload []byte, ok bool) {
|
||||||
if len(msg) < 2 {
|
if len(msg) < 2 {
|
||||||
return "", nil, false
|
return "", nil, false
|
||||||
@@ -274,9 +273,9 @@ func splitEdgeBinary(msg []byte) (header string, payload []byte, ok bool) {
|
|||||||
return string(msg[2 : 2+headerLen]), msg[2+headerLen:], true
|
return string(msg[2 : 2+headerLen]), msg[2+headerLen:], true
|
||||||
}
|
}
|
||||||
|
|
||||||
// edgeSpeechConfigMsg ist die erste Client-Nachricht: Header-Block +
|
// edgeSpeechConfigMsg is the first client message: header block + JSON body
|
||||||
// JSON-Body mit Ausgabeformat und Metadaten-Optionen (Satzgrenzen an,
|
// with output format and metadata options (sentence boundaries on, word
|
||||||
// Wortgrenzen aus — Referenz-Default).
|
// boundaries off; reference default).
|
||||||
func edgeSpeechConfigMsg(now time.Time) string {
|
func edgeSpeechConfigMsg(now time.Time) string {
|
||||||
return fmt.Sprintf(
|
return fmt.Sprintf(
|
||||||
"X-Timestamp:%s\r\nContent-Type:application/json; charset=utf-8\r\nPath:speech.config\r\n\r\n"+
|
"X-Timestamp:%s\r\nContent-Type:application/json; charset=utf-8\r\nPath:speech.config\r\n\r\n"+
|
||||||
@@ -284,17 +283,17 @@ func edgeSpeechConfigMsg(now time.Time) string {
|
|||||||
edgeTimestamp(now), edgeOutputFormat)
|
edgeTimestamp(now), edgeOutputFormat)
|
||||||
}
|
}
|
||||||
|
|
||||||
// edgeSynthesisHeaders ist der Header-Block der SSML-Anfrage. Der
|
// edgeSynthesisHeaders is the header block of the SSML request. The
|
||||||
// nachgestellte Z beim Timestamp ist Referenz-Verhalten („Microsoft Edge
|
// trailing Z on the timestamp is reference behaviour ("Microsoft Edge
|
||||||
// bug"), bewusst mitgeschleppt.
|
// bug"), deliberately carried along.
|
||||||
func edgeSynthesisHeaders(now time.Time, requestID string) string {
|
func edgeSynthesisHeaders(now time.Time, requestID string) string {
|
||||||
return fmt.Sprintf(
|
return fmt.Sprintf(
|
||||||
"X-RequestId:%s\r\nContent-Type:application/ssml+xml\r\nX-Timestamp:%sZ\r\nPath:ssml\r\n\r\n",
|
"X-RequestId:%s\r\nContent-Type:application/ssml+xml\r\nX-Timestamp:%sZ\r\nPath:ssml\r\n\r\n",
|
||||||
requestID, edgeTimestamp(now))
|
requestID, edgeTimestamp(now))
|
||||||
}
|
}
|
||||||
|
|
||||||
// edgeSSML baut die Sprach-Anfrage (xml:lang wie die Referenz fest
|
// edgeSSML builds the speech request (xml:lang fixed to "en-US" like the
|
||||||
// „en-US"; der Text wird von Steuerzeichen befreit und XML-escapt).
|
// reference; the text is stripped of control characters and XML-escaped).
|
||||||
func edgeSSML(voice, text string) string {
|
func edgeSSML(voice, text string) string {
|
||||||
return fmt.Sprintf(
|
return fmt.Sprintf(
|
||||||
"<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'>"+
|
"<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'>"+
|
||||||
@@ -304,8 +303,8 @@ func edgeSSML(voice, text string) string {
|
|||||||
voice, edgeEscape(text))
|
voice, edgeEscape(text))
|
||||||
}
|
}
|
||||||
|
|
||||||
// edgeEscape entfernt nicht unterstützte Steuerzeichen (Referenz:
|
// edgeEscape removes unsupported control characters (reference:
|
||||||
// remove_incompatible_characters) und escapt danach & < >.
|
// remove_incompatible_characters) and then escapes & < >.
|
||||||
func edgeEscape(s string) string {
|
func edgeEscape(s string) string {
|
||||||
clean := make([]byte, 0, len(s))
|
clean := make([]byte, 0, len(s))
|
||||||
for i := 0; i < len(s); i++ {
|
for i := 0; i < len(s); i++ {
|
||||||
@@ -331,27 +330,27 @@ func edgeEscape(s string) string {
|
|||||||
return string(esc)
|
return string(esc)
|
||||||
}
|
}
|
||||||
|
|
||||||
// edgeTimestamp formatiert den Zeitstempel im edge-tts-Format.
|
// edgeTimestamp formats the timestamp in the edge-tts format.
|
||||||
func edgeTimestamp(now time.Time) string {
|
func edgeTimestamp(now time.Time) string {
|
||||||
return now.Format("Mon Jan 02 2006 15:04:05 GMT+0000 (Coordinated Universal Time)")
|
return now.Format("Mon Jan 02 2006 15:04:05 GMT+0000 (Coordinated Universal Time)")
|
||||||
}
|
}
|
||||||
|
|
||||||
// edgeRequestID erzeugt eine 32-stellige Hex-ID (UUID v4 ohne Striche).
|
// edgeRequestID produces a 32-character hex ID (UUID v4 without dashes).
|
||||||
func edgeRequestID() string {
|
func edgeRequestID() string {
|
||||||
var b [16]byte
|
var b [16]byte
|
||||||
if _, err := rand.Read(b[:]); err != nil {
|
if _, err := rand.Read(b[:]); err != nil {
|
||||||
// Fallback: zeitbasiert — die ID muss nur eindeutig pro Anfrage sein.
|
// Fallback: time based; the ID only has to be unique per request.
|
||||||
now := time.Now().UnixNano()
|
now := time.Now().UnixNano()
|
||||||
for i := 0; i < 16; i++ {
|
for i := 0; i < 16; i++ {
|
||||||
b[i] = byte(now >> (uint(i%8) * 8))
|
b[i] = byte(now >> (uint(i%8) * 8))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
b[6] = (b[6] & 0x0f) | 0x40 // UUID-Version
|
b[6] = (b[6] & 0x0f) | 0x40 // UUID version
|
||||||
b[8] = (b[8] & 0x3f) | 0x80 // Variante
|
b[8] = (b[8] & 0x3f) | 0x80 // variant
|
||||||
return hex.EncodeToString(b[:])
|
return hex.EncodeToString(b[:])
|
||||||
}
|
}
|
||||||
|
|
||||||
// edgeMUID erzeugt die zufällige MUID für das Cookie (32 Hex, groß).
|
// edgeMUID produces the random MUID for the cookie (32 hex, upper case).
|
||||||
func edgeMUID() string {
|
func edgeMUID() string {
|
||||||
var b [16]byte
|
var b [16]byte
|
||||||
if _, err := rand.Read(b[:]); err != nil {
|
if _, err := rand.Read(b[:]); err != nil {
|
||||||
@@ -360,8 +359,8 @@ func edgeMUID() string {
|
|||||||
return strings.ToUpper(hex.EncodeToString(b[:]))
|
return strings.ToUpper(hex.EncodeToString(b[:]))
|
||||||
}
|
}
|
||||||
|
|
||||||
// redactURL maskiert die Query-Parameter (enthalten DRM-Token und IDs) in
|
// redactURL masks the query parameters (they contain the DRM token and
|
||||||
// Fehlermeldungen — die URL selbst genügt zur Diagnose.
|
// IDs) in error messages; the URL itself is enough for diagnosis.
|
||||||
func redactURL(raw string) string {
|
func redactURL(raw string) string {
|
||||||
u, err := url.Parse(raw)
|
u, err := url.Parse(raw)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -14,72 +14,72 @@ import (
|
|||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestEdgeAvailable: Edge braucht nur einen Endpunkt, keinen Key — der
|
// TestEdgeAvailable: Edge needs only an endpoint, no key. The constructor
|
||||||
// Konstruktor bäkt den Default-Endpunkt ein, daher ist ein über NewEdge
|
// bakes in the default endpoint, so an Edge built via NewEdge is always
|
||||||
// gebauter Edge immer verfügbar; nur der Nullwert (direkt gebaut, ohne
|
// available; only the zero value (built directly, without an endpoint) is
|
||||||
// Endpunkt) ist es nicht.
|
// not.
|
||||||
func TestEdgeAvailable(t *testing.T) {
|
func TestEdgeAvailable(t *testing.T) {
|
||||||
if (&Edge{}).Available(context.Background()) {
|
if (&Edge{}).Available(context.Background()) {
|
||||||
t.Error("Available ohne Endpunkt (Nullwert) = true, want false")
|
t.Error("Available without endpoint (zero value) = true, want false")
|
||||||
}
|
}
|
||||||
p := NewEdge(ChainConfig{Getenv: envMap(map[string]string{
|
p := NewEdge(ChainConfig{Getenv: envMap(map[string]string{
|
||||||
EnvEdgeEndpoint: "wss://edge.example.com",
|
EnvEdgeEndpoint: "wss://edge.example.com",
|
||||||
})})
|
})})
|
||||||
if !p.Available(context.Background()) {
|
if !p.Available(context.Background()) {
|
||||||
t.Error("Available mit Endpunkt = false, want true")
|
t.Error("Available with endpoint = false, want true")
|
||||||
}
|
}
|
||||||
if !NewEdge(ChainConfig{Getenv: envMap(nil)}).Available(context.Background()) {
|
if !NewEdge(ChainConfig{Getenv: envMap(nil)}).Available(context.Background()) {
|
||||||
t.Error("Available mit Default-Endpunkt = false, want true (edge ist der Key-freie Fallback)")
|
t.Error("Available with default endpoint = false, want true (edge is the key-free fallback)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestEdgeVerbindungFehlschlaegt (Fehlerpfad-Mock): ein garantiert toter
|
// TestEdgeConnectionFails (error-path mock): a guaranteed dead loopback
|
||||||
// Loopback-Port liefert einen klaren Fehler — sofort, ohne Netz.
|
// port yields a clear error, immediately and without network.
|
||||||
func TestEdgeVerbindungFehlschlaegt(t *testing.T) {
|
func TestEdgeConnectionFails(t *testing.T) {
|
||||||
p := NewEdge(ChainConfig{Getenv: envMap(map[string]string{
|
p := NewEdge(ChainConfig{Getenv: envMap(map[string]string{
|
||||||
EnvEdgeEndpoint: "ws://127.0.0.1:1/",
|
EnvEdgeEndpoint: "ws://127.0.0.1:1/",
|
||||||
})})
|
})})
|
||||||
_, err := p.Synthesize(context.Background(), "Hallo", "de")
|
_, err := p.Synthesize(context.Background(), "Hello", "de")
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Fatal("Synthesize gegen toten Port: kein Fehler")
|
t.Fatal("Synthesize against dead port: no error")
|
||||||
}
|
}
|
||||||
if !strings.Contains(err.Error(), "edge") || !strings.Contains(err.Error(), "WebSocket") {
|
if !strings.Contains(err.Error(), "edge") || !strings.Contains(err.Error(), "WebSocket") {
|
||||||
t.Errorf("Fehler = %v, will klaren edge/WebSocket-Fehler", err)
|
t.Errorf("error = %v, want a clear edge/WebSocket error", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestEdgeUngueltigesSchema: ein Nicht-w(s)-Endpunkt ist ein klarer Fehler.
|
// TestEdgeInvalidScheme: a non-ws(s) endpoint is a clear error.
|
||||||
func TestEdgeUngueltigesSchema(t *testing.T) {
|
func TestEdgeInvalidScheme(t *testing.T) {
|
||||||
p := NewEdge(ChainConfig{Getenv: envMap(map[string]string{
|
p := NewEdge(ChainConfig{Getenv: envMap(map[string]string{
|
||||||
EnvEdgeEndpoint: "http://127.0.0.1:1234/",
|
EnvEdgeEndpoint: "http://127.0.0.1:1234/",
|
||||||
})})
|
})})
|
||||||
_, err := p.Synthesize(context.Background(), "Hallo", "de")
|
_, err := p.Synthesize(context.Background(), "Hello", "de")
|
||||||
if err == nil || !strings.Contains(err.Error(), "ws://") {
|
if err == nil || !strings.Contains(err.Error(), "ws://") {
|
||||||
t.Errorf("Fehler = %v, will Schema-Hinweis ws://", err)
|
t.Errorf("error = %v, want scheme hint ws://", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestEdgeSSML: die SSML-Anfrage enthält Stimme und den von Steuerzeichen
|
// TestEdgeSSML: the SSML request contains the voice and the text stripped
|
||||||
// befreiten, XML-escapten Text; xml:lang ist wie in der Referenz fest
|
// of control characters and XML-escaped; xml:lang is fixed to "en-US" as in
|
||||||
// „en-US".
|
// the reference.
|
||||||
func TestEdgeSSML(t *testing.T) {
|
func TestEdgeSSML(t *testing.T) {
|
||||||
got := edgeSSML("de-DE-KatjaNeural", "AT&T <Kunde> „fertig“")
|
got := edgeSSML("de-DE-KatjaNeural", "AT&T <customer> „done“")
|
||||||
for _, want := range []string{
|
for _, want := range []string{
|
||||||
"voice name='de-DE-KatjaNeural'",
|
"voice name='de-DE-KatjaNeural'",
|
||||||
"xml:lang='en-US'",
|
"xml:lang='en-US'",
|
||||||
"AT&T <Kunde>",
|
"AT&T <customer>",
|
||||||
} {
|
} {
|
||||||
if !strings.Contains(got, want) {
|
if !strings.Contains(got, want) {
|
||||||
t.Errorf("SSML = %q, will %q", got, want)
|
t.Errorf("SSML = %q, want %q", got, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if strings.Contains(got, "AT&T") {
|
if strings.Contains(got, "AT&T") {
|
||||||
t.Errorf("SSML enthält unescaptes &: %q", got)
|
t.Errorf("SSML contains unescaped &: %q", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestEdgeEscape: Steuerzeichen (u. a. Vertical Tab aus OCR-Texten) werden
|
// TestEdgeEscape: control characters (e.g. vertical tab from OCR texts) are
|
||||||
// durch Leerzeichen ersetzt, & < > escapt.
|
// replaced by spaces, & < > are escaped.
|
||||||
func TestEdgeEscape(t *testing.T) {
|
func TestEdgeEscape(t *testing.T) {
|
||||||
in := "a\x0bb&c<d>\x08e"
|
in := "a\x0bb&c<d>\x08e"
|
||||||
if want := "a b&c<d> e"; edgeEscape(in) != want {
|
if want := "a b&c<d> e"; edgeEscape(in) != want {
|
||||||
@@ -87,19 +87,19 @@ func TestEdgeEscape(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestEdgeSpeechConfigMsg: Output-Format (mono-mp3) und Pfad stimmen.
|
// TestEdgeSpeechConfigMsg: output format (mono mp3) and path are correct.
|
||||||
func TestEdgeSpeechConfigMsg(t *testing.T) {
|
func TestEdgeSpeechConfigMsg(t *testing.T) {
|
||||||
msg := edgeSpeechConfigMsg(time.Unix(0, 0).UTC())
|
msg := edgeSpeechConfigMsg(time.Unix(0, 0).UTC())
|
||||||
if !strings.Contains(msg, "Path:speech.config") {
|
if !strings.Contains(msg, "Path:speech.config") {
|
||||||
t.Errorf("speech.config-Nachricht ohne Path: %q", msg)
|
t.Errorf("speech.config message without Path: %q", msg)
|
||||||
}
|
}
|
||||||
if !strings.Contains(msg, edgeOutputFormat) {
|
if !strings.Contains(msg, edgeOutputFormat) {
|
||||||
t.Errorf("speech.config-Nachricht ohne Ausgabeformat %q: %q", edgeOutputFormat, msg)
|
t.Errorf("speech.config message without output format %q: %q", edgeOutputFormat, msg)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestEdgeRequestURL: Query-Parameter (Token, Sec-MS-GEC, Version) werden
|
// TestEdgeRequestURL: query parameters (token, Sec-MS-GEC, version) are
|
||||||
// ergänzt; der Token landet nicht in der URL-Debug-Ausgabe.
|
// added; the token does not end up in the redacted URL output.
|
||||||
func TestEdgeRequestURL(t *testing.T) {
|
func TestEdgeRequestURL(t *testing.T) {
|
||||||
p := &Edge{Endpoint: "wss://edge.example.com/path"}
|
p := &Edge{Endpoint: "wss://edge.example.com/path"}
|
||||||
raw, err := p.requestURL(time.Unix(1700000000, 0).UTC())
|
raw, err := p.requestURL(time.Unix(1700000000, 0).UTC())
|
||||||
@@ -112,20 +112,20 @@ func TestEdgeRequestURL(t *testing.T) {
|
|||||||
"Sec-MS-GEC-Version=" + edgeSecMSGECVersion,
|
"Sec-MS-GEC-Version=" + edgeSecMSGECVersion,
|
||||||
} {
|
} {
|
||||||
if !strings.Contains(raw, want) {
|
if !strings.Contains(raw, want) {
|
||||||
t.Errorf("requestURL = %q, will %q", raw, want)
|
t.Errorf("requestURL = %q, want %q", raw, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if got := redactURL(raw); strings.Contains(got, edgeTrustedClientToken) {
|
if got := redactURL(raw); strings.Contains(got, edgeTrustedClientToken) {
|
||||||
t.Errorf("redactURL leakt den Token: %q", got)
|
t.Errorf("redactURL leaks the token: %q", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestEdgeSecMSGEC: Format „<16 Hex>-<64 Hex>" (groß), 5-Minuten-Raster
|
// TestEdgeSecMSGEC: format "<16 hex>-<64 hex>" (upper case), 5-minute grid
|
||||||
// (innerhalb des Fensters stabil, über die Grenze anders) und exakte
|
// (stable within the window, different across the boundary) and exact
|
||||||
// Referenzvektoren der edge-tts-DRM-Implementierung (v2).
|
// reference vectors of the edge-tts DRM implementation (v2).
|
||||||
func TestEdgeSecMSGEC(t *testing.T) {
|
func TestEdgeSecMSGEC(t *testing.T) {
|
||||||
// Referenzvektoren: (Unix-Sekunden, erwarteter Token) — erzeugt mit der
|
// Reference vectors: (unix seconds, expected token), generated with the
|
||||||
// Python-Referenz (edge-tts src/edge_tts/drm.py, Stand 2026-10).
|
// Python reference (edge-tts src/edge_tts/drm.py, as of 2026-10).
|
||||||
vectors := []struct {
|
vectors := []struct {
|
||||||
ts int64
|
ts int64
|
||||||
want string
|
want string
|
||||||
@@ -141,36 +141,36 @@ func TestEdgeSecMSGEC(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fenster-Stabilität (Basis am Fensterbeginn, mod 300 == 0).
|
// Window stability (base at window start, mod 300 == 0).
|
||||||
base := time.Unix(1700000400, 0).UTC()
|
base := time.Unix(1700000400, 0).UTC()
|
||||||
token := edgeSecMSGEC(base)
|
token := edgeSecMSGEC(base)
|
||||||
if edgeSecMSGEC(base.Add(4*time.Minute)) != token {
|
if edgeSecMSGEC(base.Add(4*time.Minute)) != token {
|
||||||
t.Error("Sec-MS-GEC weicht innerhalb des 5-Minuten-Fensters ab")
|
t.Error("Sec-MS-GEC differs within the 5-minute window")
|
||||||
}
|
}
|
||||||
if edgeSecMSGEC(base.Add(6*time.Minute)) == token {
|
if edgeSecMSGEC(base.Add(6*time.Minute)) == token {
|
||||||
t.Error("Sec-MS-GEC ändert sich über die Fenster-Grenze nicht")
|
t.Error("Sec-MS-GEC does not change across the window boundary")
|
||||||
}
|
}
|
||||||
if len(token) != 16+1+64 || !strings.Contains(token, "-") {
|
if len(token) != 16+1+64 || !strings.Contains(token, "-") {
|
||||||
t.Errorf("Token-Format = %q, want <16 Hex>-<64 Hex>", token)
|
t.Errorf("token format = %q, want <16 hex>-<64 hex>", token)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestEdgeRequestID: 32 Hex-Zeichen, eindeutig.
|
// TestEdgeRequestID: 32 hex characters, unique.
|
||||||
func TestEdgeRequestID(t *testing.T) {
|
func TestEdgeRequestID(t *testing.T) {
|
||||||
a, b := edgeRequestID(), edgeRequestID()
|
a, b := edgeRequestID(), edgeRequestID()
|
||||||
if len(a) != 32 {
|
if len(a) != 32 {
|
||||||
t.Errorf("RequestID-Länge = %d, want 32", len(a))
|
t.Errorf("request ID length = %d, want 32", len(a))
|
||||||
}
|
}
|
||||||
if _, err := hex.DecodeString(a); err != nil {
|
if _, err := hex.DecodeString(a); err != nil {
|
||||||
t.Errorf("RequestID ist kein Hex: %v", err)
|
t.Errorf("request ID is not hex: %v", err)
|
||||||
}
|
}
|
||||||
if a == b {
|
if a == b {
|
||||||
t.Error("RequestID nicht eindeutig")
|
t.Error("request ID not unique")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestEdgeSplitBinary: Binär-Rahmen: 2 Bytes big-endian Header-Länge, dann
|
// TestEdgeSplitBinary: binary frame: 2 bytes big-endian header length, then
|
||||||
// Header (Path:audio), dann Payload.
|
// header (Path:audio), then payload.
|
||||||
func TestEdgeSplitBinary(t *testing.T) {
|
func TestEdgeSplitBinary(t *testing.T) {
|
||||||
msg := []byte{0, 12, 'P', 'a', 't', 'h', ':', 'a', 'u', 'd', 'i', 'o', '\r', '\n', 1, 2, 3}
|
msg := []byte{0, 12, 'P', 'a', 't', 'h', ':', 'a', 'u', 'd', 'i', 'o', '\r', '\n', 1, 2, 3}
|
||||||
header, payload, ok := splitEdgeBinary(msg)
|
header, payload, ok := splitEdgeBinary(msg)
|
||||||
@@ -178,15 +178,15 @@ func TestEdgeSplitBinary(t *testing.T) {
|
|||||||
t.Errorf("splitEdgeBinary = %q, %x, %v", header, payload, ok)
|
t.Errorf("splitEdgeBinary = %q, %x, %v", header, payload, ok)
|
||||||
}
|
}
|
||||||
if _, _, ok := splitEdgeBinary([]byte{0, 99, 'x'}); ok {
|
if _, _, ok := splitEdgeBinary([]byte{0, 99, 'x'}); ok {
|
||||||
t.Error("übergroßer Header-Längenangabe soll abgelehnt werden")
|
t.Error("oversized header length should be rejected")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// fakeEdgeServer ist ein Loopback-Fake des Edge-WSS-Protokolls (kein
|
// fakeEdgeServer is a loopback fake of the Edge WSS protocol (no real
|
||||||
// echter Netz-Call — alles bleibt auf 127.0.0.1). Er prüft die beiden
|
// network call; everything stays on 127.0.0.1). It checks the two client
|
||||||
// Client-Nachrichten und antwortet nach Protokoll: Audio-Binär-Rahmen mit
|
// messages and answers per protocol: a binary audio frame with Path:audio,
|
||||||
// Path:audio, danach turn.end. audio ist die zu liefernde Payload;
|
// then turn.end. audio is the payload to deliver; closing closes the
|
||||||
// closing schließt die Verbindung vor turn.end (Fehlerpfad).
|
// connection before turn.end (error path).
|
||||||
func fakeEdgeServer(t *testing.T, audio []byte, closing bool) (*httptest.Server, *fakeEdgeSeen) {
|
func fakeEdgeServer(t *testing.T, audio []byte, closing bool) (*httptest.Server, *fakeEdgeSeen) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
seen := &fakeEdgeSeen{}
|
seen := &fakeEdgeSeen{}
|
||||||
@@ -208,21 +208,21 @@ func fakeEdgeServer(t *testing.T, audio []byte, closing bool) (*httptest.Server,
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if _, cfg, err := conn.ReadMessage(); err != nil {
|
if _, cfg, err := conn.ReadMessage(); err != nil {
|
||||||
t.Errorf("speech.config lesen: %v", err)
|
t.Errorf("reading speech.config: %v", err)
|
||||||
} else {
|
} else {
|
||||||
seen.mu.Lock()
|
seen.mu.Lock()
|
||||||
seen.config = string(cfg)
|
seen.config = string(cfg)
|
||||||
seen.mu.Unlock()
|
seen.mu.Unlock()
|
||||||
}
|
}
|
||||||
if _, req, err := conn.ReadMessage(); err != nil {
|
if _, req, err := conn.ReadMessage(); err != nil {
|
||||||
t.Errorf("ssml lesen: %v", err)
|
t.Errorf("reading ssml: %v", err)
|
||||||
} else {
|
} else {
|
||||||
seen.mu.Lock()
|
seen.mu.Lock()
|
||||||
seen.ssml = string(req)
|
seen.ssml = string(req)
|
||||||
seen.mu.Unlock()
|
seen.mu.Unlock()
|
||||||
}
|
}
|
||||||
if closing {
|
if closing {
|
||||||
return // Verbindung dichtmachen, ohne zu antworten
|
return // close the connection without answering
|
||||||
}
|
}
|
||||||
header := "X-RequestId:dummy\r\nPath:audio\r\n"
|
header := "X-RequestId:dummy\r\nPath:audio\r\n"
|
||||||
frame := make([]byte, 0, 2+len(header)+len(audio))
|
frame := make([]byte, 0, 2+len(header)+len(audio))
|
||||||
@@ -252,10 +252,9 @@ func (s *fakeEdgeSeen) snapshot() (configMsg, ssml string) {
|
|||||||
return s.config, s.ssml
|
return s.config, s.ssml
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestEdgeLoopbackFakeServer: kompletter Protokoll-Durchlauf gegen den
|
// TestEdgeLoopbackFakeServer: complete protocol run against the loopback
|
||||||
// Loopback-Fake (fake-bar getestet: Handshake-Parameter, beide
|
// fake (tested fakeably: handshake parameters, both client messages,
|
||||||
// Client-Nachrichten, Binär-Rahmen-Parsing, turn.end-Ende) — siehe
|
// binary frame parsing, turn.end termination).
|
||||||
// Task-03-Report für die Abgrenzung zum echten Endpoint.
|
|
||||||
func TestEdgeLoopbackFakeServer(t *testing.T) {
|
func TestEdgeLoopbackFakeServer(t *testing.T) {
|
||||||
wantAudio := []byte("\xff\xfb\x90\x00" + "edge-audio")
|
wantAudio := []byte("\xff\xfb\x90\x00" + "edge-audio")
|
||||||
ts, seen := fakeEdgeServer(t, wantAudio, false)
|
ts, seen := fakeEdgeServer(t, wantAudio, false)
|
||||||
@@ -263,9 +262,9 @@ func TestEdgeLoopbackFakeServer(t *testing.T) {
|
|||||||
p := NewEdge(ChainConfig{Getenv: envMap(map[string]string{
|
p := NewEdge(ChainConfig{Getenv: envMap(map[string]string{
|
||||||
EnvEdgeEndpoint: "ws://" + ts.Listener.Addr().String(),
|
EnvEdgeEndpoint: "ws://" + ts.Listener.Addr().String(),
|
||||||
})})
|
})})
|
||||||
data, err := p.Synthesize(context.Background(), "Hallo & fertig", "de")
|
data, err := p.Synthesize(context.Background(), "Hello & done", "de")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Synthesize gegen Loopback-Fake: %v", err)
|
t.Fatalf("Synthesize against loopback fake: %v", err)
|
||||||
}
|
}
|
||||||
if string(data) != string(wantAudio) {
|
if string(data) != string(wantAudio) {
|
||||||
t.Errorf("Synthesize = %x, want %x", data, wantAudio)
|
t.Errorf("Synthesize = %x, want %x", data, wantAudio)
|
||||||
@@ -275,47 +274,47 @@ func TestEdgeLoopbackFakeServer(t *testing.T) {
|
|||||||
t.Errorf("speech.config = %q", configMsg)
|
t.Errorf("speech.config = %q", configMsg)
|
||||||
}
|
}
|
||||||
if !strings.Contains(ssml, "Path:ssml") {
|
if !strings.Contains(ssml, "Path:ssml") {
|
||||||
t.Errorf("ssml-Anfrage ohne Path:ssml: %q", ssml)
|
t.Errorf("ssml request without Path:ssml: %q", ssml)
|
||||||
}
|
}
|
||||||
if !strings.Contains(ssml, "voice name='de-DE-KatjaNeural'") {
|
if !strings.Contains(ssml, "voice name='de-DE-KatjaNeural'") {
|
||||||
t.Errorf("ssml ohne Default-Stimme de: %q", ssml)
|
t.Errorf("ssml without default voice de: %q", ssml)
|
||||||
}
|
}
|
||||||
if !strings.Contains(ssml, "Hallo & fertig") {
|
if !strings.Contains(ssml, "Hello & done") {
|
||||||
t.Errorf("ssml ohne escapten Text: %q", ssml)
|
t.Errorf("ssml without escaped text: %q", ssml)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestEdgeLoopbackVerbindungsAbbruch: Server schließt nach den Anfragen
|
// TestEdgeLoopbackConnectionAbort: the server closes after the requests
|
||||||
// ohne Audio → klarer „Protokoll geändert?"-Fehler.
|
// without audio → clear "protocol changed?" error.
|
||||||
func TestEdgeLoopbackVerbindungsAbbruch(t *testing.T) {
|
func TestEdgeLoopbackConnectionAbort(t *testing.T) {
|
||||||
ts, _ := fakeEdgeServer(t, nil, true)
|
ts, _ := fakeEdgeServer(t, nil, true)
|
||||||
p := NewEdge(ChainConfig{Getenv: envMap(map[string]string{
|
p := NewEdge(ChainConfig{Getenv: envMap(map[string]string{
|
||||||
EnvEdgeEndpoint: "ws://" + ts.Listener.Addr().String(),
|
EnvEdgeEndpoint: "ws://" + ts.Listener.Addr().String(),
|
||||||
})})
|
})})
|
||||||
_, err := p.Synthesize(context.Background(), "Hallo", "de")
|
_, err := p.Synthesize(context.Background(), "Hello", "de")
|
||||||
if err == nil || !strings.Contains(err.Error(), "Protokoll") {
|
if err == nil || !strings.Contains(err.Error(), "protocol") {
|
||||||
t.Errorf("Fehler = %v, will Protokoll-Änderungs-Hinweis", err)
|
t.Errorf("error = %v, want protocol-change hint", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestEdgeIntegrationEcht ist die als testing.Short überspringbare
|
// TestEdgeIntegrationReal is the integration marker against the REAL
|
||||||
// Integrations-Markierung gegen den ECHTEN Microsoft-Endpunkt (kostenlos,
|
// Microsoft endpoint, skippable via testing.Short (free, but real network;
|
||||||
// aber echtes Netz — Standard-Testläufe und -short überspringen; einmalige
|
// standard test runs and -short skip it; one-off manual acceptance with
|
||||||
// manuelle Abnahme mit TALK_TEST_REAL_EDGE=1).
|
// TALK_TEST_REAL_EDGE=1).
|
||||||
func TestEdgeIntegrationEcht(t *testing.T) {
|
func TestEdgeIntegrationReal(t *testing.T) {
|
||||||
if testing.Short() {
|
if testing.Short() {
|
||||||
t.Skip("Übersprungen (-short)")
|
t.Skip("skipped (-short)")
|
||||||
}
|
}
|
||||||
if os.Getenv("TALK_TEST_REAL_EDGE") != "1" {
|
if os.Getenv("TALK_TEST_REAL_EDGE") != "1" {
|
||||||
t.Skip("Übersprungen (echtes Netz) — mit TALK_TEST_REAL_EDGE=1 ausführen")
|
t.Skip("skipped (real network); run with TALK_TEST_REAL_EDGE=1")
|
||||||
}
|
}
|
||||||
p := NewEdge(ChainConfig{})
|
p := NewEdge(ChainConfig{})
|
||||||
data, err := p.Synthesize(context.Background(), "Kurzer Sprachtest über Edge.", "de")
|
data, err := p.Synthesize(context.Background(), "Short speech test via Edge.", "de")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Synthesize gegen echten Endpunkt: %v", err)
|
t.Fatalf("Synthesize against real endpoint: %v", err)
|
||||||
}
|
}
|
||||||
if len(data) == 0 {
|
if len(data) == 0 {
|
||||||
t.Fatal("Synthesize gegen echten Endpunkt: 0 Bytes")
|
t.Fatal("Synthesize against real endpoint: 0 bytes")
|
||||||
}
|
}
|
||||||
t.Logf("Edge-Integration: %d Bytes Audio", len(data))
|
t.Logf("Edge integration: %d bytes of audio", len(data))
|
||||||
}
|
}
|
||||||
@@ -4,35 +4,35 @@ import (
|
|||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Edge-DRM: Sec-MS-GEC v2. Microsoft verlangt seit der Protokoll-Änderung
|
// Edge DRM: Sec-MS-GEC v2. Since the protocol change (edge-tts reference,
|
||||||
// (edge-tts-Referenz, Stand 2026) einen Token der Form
|
// as of 2026) Microsoft requires a token of the form
|
||||||
// „<16 Hex CS64>-<64 Hex SHA256-Variante>" über den 5-Minuten-gerundeten
|
// "<16 hex CS64>-<64 hex SHA256 variant>" over the 5-minute-rounded
|
||||||
// Windows-Filetime-Ticks + Trusted-Client-Token. Beide Digests sind
|
// Windows filetime ticks + trusted client token. Both digests are
|
||||||
// absichtlich verschleierte Varianten bekannter Algorithmen — die
|
// deliberately obfuscated variants of well-known algorithms; the constants
|
||||||
// Konstanten und der Kontrollfluss unten sind eine wörtliche Portierung
|
// and the control flow below are a literal port of the reference (edge-tts
|
||||||
// der Referenz (edge-tts src/edge_tts/drm.py, MIT) und gegen deren
|
// src/edge_tts/drm.py, MIT) and are table-checked against its outputs
|
||||||
// Ausgaben tabellengeprüft (TestEdgeDRMReferenzvektoren). Ändert Microsoft
|
// (TestEdgeSecMSGEC). If Microsoft changes the scheme again, the Edge
|
||||||
// das Schema erneut, liefert der Edge-Provider klare Fehler („Protokoll
|
// provider returns clear errors ("protocol changed?") instead of failing
|
||||||
// geändert?"), statt still zu versagen.
|
// silently.
|
||||||
|
|
||||||
const (
|
const (
|
||||||
drmWinEpoch = 11644473600 // Sekunden zwischen 1601-01-01 und 1970-01-01
|
drmWinEpoch = 11644473600 // seconds between 1601-01-01 and 1970-01-01
|
||||||
)
|
)
|
||||||
|
|
||||||
// drmIV ist der Standard-SHA-256-Initialvektor.
|
// drmIV is the standard SHA-256 initial vector.
|
||||||
var drmIV = [8]uint32{
|
var drmIV = [8]uint32{
|
||||||
0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A,
|
0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A,
|
||||||
0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19,
|
0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19,
|
||||||
}
|
}
|
||||||
|
|
||||||
// drmMidState ist der Arbeitsregister-Stand der Referenz für den
|
// drmMidState is the reference's working-register state for the mid-block
|
||||||
// Mid-Block-Einstieg (Runde 14 des ersten Blocks).
|
// entry (round 14 of the first block).
|
||||||
var drmMidState = [8]uint32{
|
var drmMidState = [8]uint32{
|
||||||
0xFD9FBEA2, 0x91243CE7, 0xBE499094, 0xCD2E1E0A,
|
0xFD9FBEA2, 0x91243CE7, 0xBE499094, 0xCD2E1E0A,
|
||||||
0x6C006F49, 0x04BD35AB, 0xFEB0A7E4, 0x03EFFBD2,
|
0x6C006F49, 0x04BD35AB, 0xFEB0A7E4, 0x03EFFBD2,
|
||||||
}
|
}
|
||||||
|
|
||||||
// drmSchedule sind vorberechnete Schedule-Anteile des ersten Blocks.
|
// drmSchedule holds precomputed schedule parts of the first block.
|
||||||
var drmSchedule = [14]uint32{
|
var drmSchedule = [14]uint32{
|
||||||
0xEB24BF9E, 0x1558691F, 0xA0C09EE2, 0x0CFA32BA,
|
0xEB24BF9E, 0x1558691F, 0xA0C09EE2, 0x0CFA32BA,
|
||||||
0xA622EE8C, 0xD1DD9491, 0xC0DD25A0, 0xF9E70AB6,
|
0xA622EE8C, 0xD1DD9491, 0xC0DD25A0, 0xF9E70AB6,
|
||||||
@@ -40,7 +40,7 @@ var drmSchedule = [14]uint32{
|
|||||||
0xD258B060, 0x72766564,
|
0xD258B060, 0x72766564,
|
||||||
}
|
}
|
||||||
|
|
||||||
// drmAdjustment ersetzt die Rundungskonstante K[14] im Mid-Block-Pfad.
|
// drmAdjustment replaces the round constant K[14] on the mid-block path.
|
||||||
const (
|
const (
|
||||||
drmAdjustment uint32 = 0xC9DC06A7
|
drmAdjustment uint32 = 0xC9DC06A7
|
||||||
drmSigma0Adj uint32 = 0x059C0B80
|
drmSigma0Adj uint32 = 0x059C0B80
|
||||||
@@ -50,7 +50,7 @@ const (
|
|||||||
drmCS64Adj1 uint32 = 0x0B1A0000
|
drmCS64Adj1 uint32 = 0x0B1A0000
|
||||||
)
|
)
|
||||||
|
|
||||||
// drmK sind die Standard-SHA-256-Rundungskonstanten.
|
// drmK are the standard SHA-256 round constants.
|
||||||
var drmK = [64]uint32{
|
var drmK = [64]uint32{
|
||||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||||
@@ -62,7 +62,7 @@ var drmK = [64]uint32{
|
|||||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
||||||
}
|
}
|
||||||
|
|
||||||
// drmCS64Coefficients: (Term-, Offset-Koeffizient) je Zeile.
|
// drmCS64Coefficients: (term coefficient, offset coefficient) per row.
|
||||||
var drmCS64Coefficients = [14][2]uint32{
|
var drmCS64Coefficients = [14][2]uint32{
|
||||||
{0xE82E91B1, 0xB32700D0}, {0x44DE24C6, 0x88DFF51D},
|
{0xE82E91B1, 0xB32700D0}, {0x44DE24C6, 0x88DFF51D},
|
||||||
{0x3BEB65BC, 0x29514038}, {0xC89C5933, 0xB328CBDF},
|
{0x3BEB65BC, 0x29514038}, {0xC89C5933, 0xB328CBDF},
|
||||||
@@ -73,23 +73,23 @@ var drmCS64Coefficients = [14][2]uint32{
|
|||||||
{0x35FA38C6, 0xBB04A2C1}, {0xCB49E3C6, 0xC5626167},
|
{0x35FA38C6, 0xBB04A2C1}, {0xCB49E3C6, 0xC5626167},
|
||||||
}
|
}
|
||||||
|
|
||||||
// drmSigma0 ist die (verschleiert notierte) SHA-256-σ0-Mischfunktion.
|
// drmSigma0 is the (obfuscated-notation) SHA-256 σ0 mixing function.
|
||||||
func drmSigma0(v uint32) uint32 {
|
func drmSigma0(v uint32) uint32 {
|
||||||
return v>>7 ^ v<<25 ^ v>>18 ^ v<<14 ^ v>>3
|
return v>>7 ^ v<<25 ^ v>>18 ^ v<<14 ^ v>>3
|
||||||
}
|
}
|
||||||
|
|
||||||
// drmSigma1 ist die SHA-256-σ1-Mischfunktion.
|
// drmSigma1 is the SHA-256 σ1 mixing function.
|
||||||
func drmSigma1(v uint32) uint32 {
|
func drmSigma1(v uint32) uint32 {
|
||||||
return v>>17 ^ v<<15 ^ v>>19 ^ v<<13 ^ v>>10
|
return v>>17 ^ v<<15 ^ v>>19 ^ v<<13 ^ v>>10
|
||||||
}
|
}
|
||||||
|
|
||||||
// drmRol16 rotiert 32 Bit um 16.
|
// drmRol16 rotates 32 bits by 16.
|
||||||
func drmRol16(v uint32) uint32 { return v<<16 | v>>16 }
|
func drmRol16(v uint32) uint32 { return v<<16 | v>>16 }
|
||||||
|
|
||||||
// drmRotR rotiert 32 Bit rechts um n.
|
// drmRotR rotates 32 bits right by n.
|
||||||
func drmRotR(v uint32, n uint) uint32 { return v>>n | v<<(32-n) }
|
func drmRotR(v uint32, n uint) uint32 { return v>>n | v<<(32-n) }
|
||||||
|
|
||||||
// drmExpand erweitert die Message-Schedule ab from auf 64 Wörter.
|
// drmExpand extends the message schedule from index from to 64 words.
|
||||||
func drmExpand(words []uint32, from int) []uint32 {
|
func drmExpand(words []uint32, from int) []uint32 {
|
||||||
for i := from; i < 64; i++ {
|
for i := from; i < 64; i++ {
|
||||||
x, y := words[i-2], words[i-15]
|
x, y := words[i-2], words[i-15]
|
||||||
@@ -98,9 +98,9 @@ func drmExpand(words []uint32, from int) []uint32 {
|
|||||||
return words
|
return words
|
||||||
}
|
}
|
||||||
|
|
||||||
// drmRounds führt die SHA-256-Runden aus — wörtlich nach Referenz,
|
// drmRounds executes the SHA-256 rounds, literally following the
|
||||||
// inklusive des Mid-Block-Einstiegs (firstRound 14 mit ersetzter
|
// reference, including the mid-block entry (firstRound 14 with the replaced
|
||||||
// Rundungskonstante) und der 8er-Rollen-Rotation der Register.
|
// round constant) and the 8-way role rotation of the registers.
|
||||||
func drmRounds(state [8]uint32, words []uint32, firstRound int) [8]uint32 {
|
func drmRounds(state [8]uint32, words []uint32, firstRound int) [8]uint32 {
|
||||||
a, b, c, d, e, f, g, h := state[0], state[1], state[2], state[3], state[4], state[5], state[6], state[7]
|
a, b, c, d, e, f, g, h := state[0], state[1], state[2], state[3], state[4], state[5], state[6], state[7]
|
||||||
midBlock := firstRound == 14
|
midBlock := firstRound == 14
|
||||||
@@ -120,35 +120,35 @@ func drmRounds(state [8]uint32, words []uint32, firstRound int) [8]uint32 {
|
|||||||
a, b, c, d, e, f, g, h = t1+t2, a, b, c, d+t1, e, f, g
|
a, b, c, d, e, f, g, h = t1+t2, a, b, c, d+t1, e, f, g
|
||||||
}
|
}
|
||||||
for i := aligned; i < 64; i += 8 {
|
for i := aligned; i < 64; i += 8 {
|
||||||
// Runde i
|
// round i
|
||||||
t1 := h + (drmRotR(e, 6) ^ drmRotR(e, 11) ^ drmRotR(e, 25)) + (g ^ (e & (f ^ g))) + k(i) + words[i]
|
t1 := h + (drmRotR(e, 6) ^ drmRotR(e, 11) ^ drmRotR(e, 25)) + (g ^ (e & (f ^ g))) + k(i) + words[i]
|
||||||
d += t1
|
d += t1
|
||||||
h = t1 + (drmRotR(a, 2) ^ drmRotR(a, 13) ^ drmRotR(a, 22)) + ((a & b) | (c & (a | b)))
|
h = t1 + (drmRotR(a, 2) ^ drmRotR(a, 13) ^ drmRotR(a, 22)) + ((a & b) | (c & (a | b)))
|
||||||
// Runde i+1 (Rollen rotiert)
|
// round i+1 (roles rotated)
|
||||||
t1 = g + (drmRotR(d, 6) ^ drmRotR(d, 11) ^ drmRotR(d, 25)) + (f ^ (d & (e ^ f))) + k(i+1) + words[i+1]
|
t1 = g + (drmRotR(d, 6) ^ drmRotR(d, 11) ^ drmRotR(d, 25)) + (f ^ (d & (e ^ f))) + k(i+1) + words[i+1]
|
||||||
c += t1
|
c += t1
|
||||||
g = t1 + (drmRotR(h, 2) ^ drmRotR(h, 13) ^ drmRotR(h, 22)) + ((h & a) | (b & (h | a)))
|
g = t1 + (drmRotR(h, 2) ^ drmRotR(h, 13) ^ drmRotR(h, 22)) + ((h & a) | (b & (h | a)))
|
||||||
// Runde i+2
|
// round i+2
|
||||||
t1 = f + (drmRotR(c, 6) ^ drmRotR(c, 11) ^ drmRotR(c, 25)) + (e ^ (c & (d ^ e))) + k(i+2) + words[i+2]
|
t1 = f + (drmRotR(c, 6) ^ drmRotR(c, 11) ^ drmRotR(c, 25)) + (e ^ (c & (d ^ e))) + k(i+2) + words[i+2]
|
||||||
b += t1
|
b += t1
|
||||||
f = t1 + (drmRotR(g, 2) ^ drmRotR(g, 13) ^ drmRotR(g, 22)) + ((g & h) | (a & (g | h)))
|
f = t1 + (drmRotR(g, 2) ^ drmRotR(g, 13) ^ drmRotR(g, 22)) + ((g & h) | (a & (g | h)))
|
||||||
// Runde i+3
|
// round i+3
|
||||||
t1 = e + (drmRotR(b, 6) ^ drmRotR(b, 11) ^ drmRotR(b, 25)) + (d ^ (b & (c ^ d))) + k(i+3) + words[i+3]
|
t1 = e + (drmRotR(b, 6) ^ drmRotR(b, 11) ^ drmRotR(b, 25)) + (d ^ (b & (c ^ d))) + k(i+3) + words[i+3]
|
||||||
a += t1
|
a += t1
|
||||||
e = t1 + (drmRotR(f, 2) ^ drmRotR(f, 13) ^ drmRotR(f, 22)) + ((f & g) | (h & (f | g)))
|
e = t1 + (drmRotR(f, 2) ^ drmRotR(f, 13) ^ drmRotR(f, 22)) + ((f & g) | (h & (f | g)))
|
||||||
// Runde i+4
|
// round i+4
|
||||||
t1 = d + (drmRotR(a, 6) ^ drmRotR(a, 11) ^ drmRotR(a, 25)) + (c ^ (a & (b ^ c))) + k(i+4) + words[i+4]
|
t1 = d + (drmRotR(a, 6) ^ drmRotR(a, 11) ^ drmRotR(a, 25)) + (c ^ (a & (b ^ c))) + k(i+4) + words[i+4]
|
||||||
h += t1
|
h += t1
|
||||||
d = t1 + (drmRotR(e, 2) ^ drmRotR(e, 13) ^ drmRotR(e, 22)) + ((e & f) | (g & (e | f)))
|
d = t1 + (drmRotR(e, 2) ^ drmRotR(e, 13) ^ drmRotR(e, 22)) + ((e & f) | (g & (e | f)))
|
||||||
// Runde i+5
|
// round i+5
|
||||||
t1 = c + (drmRotR(h, 6) ^ drmRotR(h, 11) ^ drmRotR(h, 25)) + (b ^ (h & (a ^ b))) + k(i+5) + words[i+5]
|
t1 = c + (drmRotR(h, 6) ^ drmRotR(h, 11) ^ drmRotR(h, 25)) + (b ^ (h & (a ^ b))) + k(i+5) + words[i+5]
|
||||||
g += t1
|
g += t1
|
||||||
c = t1 + (drmRotR(d, 2) ^ drmRotR(d, 13) ^ drmRotR(d, 22)) + ((d & e) | (f & (d | e)))
|
c = t1 + (drmRotR(d, 2) ^ drmRotR(d, 13) ^ drmRotR(d, 22)) + ((d & e) | (f & (d | e)))
|
||||||
// Runde i+6
|
// round i+6
|
||||||
t1 = b + (drmRotR(g, 6) ^ drmRotR(g, 11) ^ drmRotR(g, 25)) + (a ^ (g & (h ^ a))) + k(i+6) + words[i+6]
|
t1 = b + (drmRotR(g, 6) ^ drmRotR(g, 11) ^ drmRotR(g, 25)) + (a ^ (g & (h ^ a))) + k(i+6) + words[i+6]
|
||||||
f += t1
|
f += t1
|
||||||
b = t1 + (drmRotR(c, 2) ^ drmRotR(c, 13) ^ drmRotR(c, 22)) + ((c & d) | (e & (c | d)))
|
b = t1 + (drmRotR(c, 2) ^ drmRotR(c, 13) ^ drmRotR(c, 22)) + ((c & d) | (e & (c | d)))
|
||||||
// Runde i+7
|
// round i+7
|
||||||
t1 = a + (drmRotR(f, 6) ^ drmRotR(f, 11) ^ drmRotR(f, 25)) + (h ^ (f & (g ^ h))) + k(i+7) + words[i+7]
|
t1 = a + (drmRotR(f, 6) ^ drmRotR(f, 11) ^ drmRotR(f, 25)) + (h ^ (f & (g ^ h))) + k(i+7) + words[i+7]
|
||||||
e += t1
|
e += t1
|
||||||
a = t1 + (drmRotR(b, 2) ^ drmRotR(b, 13) ^ drmRotR(b, 22)) + ((b & c) | (d & (b | c)))
|
a = t1 + (drmRotR(b, 2) ^ drmRotR(b, 13) ^ drmRotR(b, 22)) + ((b & c) | (d & (b | c)))
|
||||||
@@ -156,16 +156,16 @@ func drmRounds(state [8]uint32, words []uint32, firstRound int) [8]uint32 {
|
|||||||
return [8]uint32{a, b, c, d, e, f, g, h}
|
return [8]uint32{a, b, c, d, e, f, g, h}
|
||||||
}
|
}
|
||||||
|
|
||||||
// drmSHA256Init berechnet den Zustand nach dem (verschleiert notierten)
|
// drmSHA256Init computes the state after the (obfuscated-notation) first
|
||||||
// ersten Block: 14 Nullwörter + die ersten 7 Bytes von data als
|
// block: 14 zero words + the first 7 bytes of data as 24-bit/32-bit
|
||||||
// 24-Bit-/32-Bit-Big-Endian-Wörter, Schedule mit Korrekturen, Runden ab 14.
|
// big-endian words, schedule with corrections, rounds from 14 onwards.
|
||||||
func drmSHA256Init(data []byte) [8]uint32 {
|
func drmSHA256Init(data []byte) [8]uint32 {
|
||||||
words := make([]uint32, 30, 64)
|
words := make([]uint32, 30, 64)
|
||||||
words[14] = uint32(data[0])<<16 | uint32(data[1])<<8 | uint32(data[2])
|
words[14] = uint32(data[0])<<16 | uint32(data[1])<<8 | uint32(data[2])
|
||||||
words[15] = binary.BigEndian.Uint32(data[3:7])
|
words[15] = binary.BigEndian.Uint32(data[3:7])
|
||||||
for i := 16; i < 30; i++ {
|
for i := 16; i < 30; i++ {
|
||||||
v := drmSchedule[i-16]
|
v := drmSchedule[i-16]
|
||||||
// σ1-Anteil von W[i-2] (Index 16 liest W[14], dazu die Korrektur).
|
// σ1 part of W[i-2] (index 16 reads W[14], plus the correction).
|
||||||
s1 := drmSigma1(words[i-2])
|
s1 := drmSigma1(words[i-2])
|
||||||
if i == 16 {
|
if i == 16 {
|
||||||
s1 ^= drmSigma1Adj
|
s1 ^= drmSigma1Adj
|
||||||
@@ -174,7 +174,7 @@ func drmSHA256Init(data []byte) [8]uint32 {
|
|||||||
if i-7 >= 14 {
|
if i-7 >= 14 {
|
||||||
v += words[i-7]
|
v += words[i-7]
|
||||||
}
|
}
|
||||||
if i-15 >= 14 { // nur i == 29, liest W[14], dazu die Korrektur
|
if i-15 >= 14 { // only i == 29, reads W[14], plus the correction
|
||||||
s0 := drmSigma0(words[i-15])
|
s0 := drmSigma0(words[i-15])
|
||||||
if i == 29 {
|
if i == 29 {
|
||||||
s0 ^= drmSigma0Adj
|
s0 ^= drmSigma0Adj
|
||||||
@@ -193,9 +193,9 @@ func drmSHA256Init(data []byte) [8]uint32 {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
// drmSHA256Digest ist die verschleierte SHA-256-Variante der Referenz:
|
// drmSHA256Digest is the reference's obfuscated SHA-256 variant: block 1
|
||||||
// Block 1 steckt in drmSHA256Init (erste 7 Bytes), danach data[7:] mit
|
// lives in drmSHA256Init (first 7 bytes), followed by data[7:] with the
|
||||||
// Referenz-Längenfeld (57+len(data)) und Standard-Runden.
|
// reference length field (57+len(data)) and standard rounds.
|
||||||
func drmSHA256Digest(data []byte) [8]uint32 {
|
func drmSHA256Digest(data []byte) [8]uint32 {
|
||||||
length := 57 + len(data)
|
length := 57 + len(data)
|
||||||
padded := append([]byte(nil), data[7:]...)
|
padded := append([]byte(nil), data[7:]...)
|
||||||
@@ -224,8 +224,8 @@ func drmSHA256Digest(data []byte) [8]uint32 {
|
|||||||
return state
|
return state
|
||||||
}
|
}
|
||||||
|
|
||||||
// drmWordsLE4Even zerlegt data in little-endian u32-Wörter (auf 4 Bytes
|
// drmWordsLE4Even splits data into little-endian u32 words (zero-padded to
|
||||||
// null-aufgefüllt, Wortzahl gerade).
|
// 4 bytes, even word count).
|
||||||
func drmWordsLE4Even(data []byte) []uint32 {
|
func drmWordsLE4Even(data []byte) []uint32 {
|
||||||
padded := make([]byte, len(data))
|
padded := make([]byte, len(data))
|
||||||
copy(padded, data)
|
copy(padded, data)
|
||||||
@@ -242,8 +242,8 @@ func drmWordsLE4Even(data []byte) []uint32 {
|
|||||||
return words
|
return words
|
||||||
}
|
}
|
||||||
|
|
||||||
// drmCS64 berechnet die beiden CS64-Prüfsummen-Wörter (wörtliche
|
// drmCS64 computes the two CS64 checksum words (literal port; keys from
|
||||||
// Portierung; Schlüssel aus den ersten 8 Digest-Bytes little-endian).
|
// the first 8 digest bytes, little-endian).
|
||||||
func drmCS64(data []byte, digest [8]uint32) (a, b uint32) {
|
func drmCS64(data []byte, digest [8]uint32) (a, b uint32) {
|
||||||
var digestBytes [32]byte
|
var digestBytes [32]byte
|
||||||
for i, w := range digest {
|
for i, w := range digest {
|
||||||
|
|||||||
@@ -8,51 +8,50 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ElevenLabs-Konstanten (öffentlicher Vertrag: Env-Namen sind Teil der
|
// ElevenLabs constants (public contract: the env names are part of the
|
||||||
// Fleet-Doku, Endpunkt-Default Teil der Konfigurierbarkeit).
|
// fleet documentation, the endpoint default part of the configurability).
|
||||||
const (
|
const (
|
||||||
// DefaultEndpointElevenLabs ist der produktive API-Endpunkt.
|
// DefaultEndpointElevenLabs is the production API endpoint.
|
||||||
DefaultEndpointElevenLabs = "https://api.elevenlabs.io"
|
DefaultEndpointElevenLabs = "https://api.elevenlabs.io"
|
||||||
|
|
||||||
// EnvElevenLabsKey liefert den API-Key (Spec: Keys ausschließlich Env,
|
// EnvElevenLabsKey provides the API key (spec: keys come exclusively
|
||||||
// nie config.toml).
|
// from the environment, never from config.toml).
|
||||||
EnvElevenLabsKey = "TALK_ELEVENLABS_KEY"
|
EnvElevenLabsKey = "TALK_ELEVENLABS_KEY"
|
||||||
|
|
||||||
// EnvElevenLabsEndpoint überschreibt den Endpunkt (Tests/Firmenserver;
|
// EnvElevenLabsEndpoint overrides the endpoint (tests/corporate
|
||||||
// schlägt die config.toml, siehe voices.go/chain.go-Doku).
|
// servers; beats config.toml, see the voices.go/chain.go docs).
|
||||||
EnvElevenLabsEndpoint = "TALK_ELEVENLABS_ENDPOINT"
|
EnvElevenLabsEndpoint = "TALK_ELEVENLABS_ENDPOINT"
|
||||||
|
|
||||||
elevenLabsModel = "eleven_multilingual_v2" // multilingual v2, Task-Brief
|
elevenLabsModel = "eleven_multilingual_v2" // multilingual v2
|
||||||
)
|
)
|
||||||
|
|
||||||
// ElevenLabs ist die Premium-Stufe der Kette. Synthesize führt POST
|
// ElevenLabs is the premium tier of the chain. Synthesize performs POST
|
||||||
// <endpoint>/v1/text-to-speech/<voiceID> aus — Header `xi-api-key`, Body
|
// <endpoint>/v1/text-to-speech/<voiceID> with header `xi-api-key` and body
|
||||||
// {text, model_id: "eleven_multilingual_v2", voice_settings:
|
// {text, model_id: "eleven_multilingual_v2", voice_settings:
|
||||||
// {stability: 0.5, similarity_boost: 0.75}} — und liefert die Antwort-Bytes
|
// {stability: 0.5, similarity_boost: 0.75}} and returns the response bytes
|
||||||
// unverändert zurück. Rückgabeformat: MP3 (dokumentierter Vertrag des
|
// unchanged. Return format: MP3 (documented contract of the audio package).
|
||||||
// audio-Pakets).
|
|
||||||
type ElevenLabs struct {
|
type ElevenLabs struct {
|
||||||
// Endpoint ist die Basis-URL (ohne Pfad); leer wird beim Bau durch den
|
// Endpoint is the base URL (without path); empty is replaced by the
|
||||||
// Default ersetzt.
|
// default at construction.
|
||||||
Endpoint string
|
Endpoint string
|
||||||
|
|
||||||
// APIKey ist der ElevenLabs-Key (aus TALK_ELEVENLABS_KEY).
|
// APIKey is the ElevenLabs key (from TALK_ELEVENLABS_KEY).
|
||||||
APIKey string
|
APIKey string
|
||||||
|
|
||||||
// Voices ist das config-Mapping voice.elevenlabs.<lang> = id; leer =
|
// Voices is the config mapping voice.elevenlabs.<lang> = id; empty =
|
||||||
// neutrale Repo-Defaults (siehe voices.go).
|
// neutral repo defaults (see voices.go).
|
||||||
Voices map[string]string
|
Voices map[string]string
|
||||||
|
|
||||||
// Client ist der HTTP-Client; nil = geteilter Client mit Timeout
|
// Client is the HTTP client; nil = shared client with timeout
|
||||||
// (cloudTimeout).
|
// (cloudTimeout).
|
||||||
Client *http.Client
|
Client *http.Client
|
||||||
|
|
||||||
pinned string // --voice-Pin (VoicePinner)
|
pinned string // --voice pin (VoicePinner)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewElevenLabs baut den Provider aus der Ketten-Konfiguration: Endpunkt
|
// NewElevenLabs builds the provider from the chain configuration: endpoint
|
||||||
// aus TALK_ELEVENLABS_ENDPOINT > [providers.elevenlabs].endpoint > Default;
|
// from TALK_ELEVENLABS_ENDPOINT > [providers.elevenlabs].endpoint > default;
|
||||||
// Key ausschließlich aus TALK_ELEVENLABS_KEY.
|
// key exclusively from TALK_ELEVENLABS_KEY.
|
||||||
func NewElevenLabs(cfg ChainConfig) *ElevenLabs {
|
func NewElevenLabs(cfg ChainConfig) *ElevenLabs {
|
||||||
return &ElevenLabs{
|
return &ElevenLabs{
|
||||||
Endpoint: endpointFrom(cfg, "elevenlabs", EnvElevenLabsEndpoint, DefaultEndpointElevenLabs),
|
Endpoint: endpointFrom(cfg, "elevenlabs", EnvElevenLabsEndpoint, DefaultEndpointElevenLabs),
|
||||||
@@ -61,20 +60,21 @@ func NewElevenLabs(cfg ChainConfig) *ElevenLabs {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name implementiert Provider.
|
// Name implements Provider.
|
||||||
func (*ElevenLabs) Name() string { return "elevenlabs" }
|
func (*ElevenLabs) Name() string { return "elevenlabs" }
|
||||||
|
|
||||||
// PinVoice implementiert VoicePinner (CLI-Flag --voice).
|
// PinVoice implements VoicePinner (CLI flag --voice).
|
||||||
func (p *ElevenLabs) PinVoice(id string) { p.pinned = id }
|
func (p *ElevenLabs) PinVoice(id string) { p.pinned = id }
|
||||||
|
|
||||||
// Available implementiert Provider: Key und Endpunkt müssen gesetzt sein
|
// Available implements Provider: key and endpoint must be set (deliberately
|
||||||
// (bewusst ohne Netz-Call — Available muss billig bleiben; ob der Key
|
// without a network call; Available must stay cheap. Whether the key is
|
||||||
// gültig ist, stellt Synthesize fest und die Kette fällt weiter).
|
// valid is determined by Synthesize, and the chain falls back).
|
||||||
func (p *ElevenLabs) Available(ctx context.Context) bool {
|
func (p *ElevenLabs) Available(ctx context.Context) bool {
|
||||||
return p.APIKey != "" && p.Endpoint != ""
|
return p.APIKey != "" && p.Endpoint != ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// elevenLabsRequest ist der Antwort-Body (Task-Brief, wörtliche Werte).
|
// elevenLabsRequest is the request body (literal values from the API
|
||||||
|
// contract).
|
||||||
type elevenLabsRequest struct {
|
type elevenLabsRequest struct {
|
||||||
Text string `json:"text"`
|
Text string `json:"text"`
|
||||||
ModelID string `json:"model_id"`
|
ModelID string `json:"model_id"`
|
||||||
@@ -86,14 +86,14 @@ type elevenLabsVoiceSettings struct {
|
|||||||
SimilarityBoost float64 `json:"similarity_boost"`
|
SimilarityBoost float64 `json:"similarity_boost"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Synthesize implementiert Provider. Rückgabeformat: MP3.
|
// Synthesize implements Provider. Return format: MP3.
|
||||||
func (p *ElevenLabs) Synthesize(ctx context.Context, text, lang string) ([]byte, error) {
|
func (p *ElevenLabs) Synthesize(ctx context.Context, text, lang string) ([]byte, error) {
|
||||||
if text == "" {
|
if text == "" {
|
||||||
return nil, fmt.Errorf("elevenlabs: leerer Text")
|
return nil, fmt.Errorf("elevenlabs: empty text")
|
||||||
}
|
}
|
||||||
voice := resolveVoice("elevenlabs", lang, p.pinned, p.Voices)
|
voice := resolveVoice("elevenlabs", lang, p.pinned, p.Voices)
|
||||||
if voice == "" {
|
if voice == "" {
|
||||||
return nil, fmt.Errorf("elevenlabs: keine Stimme für Sprache %q konfiguriert", lang)
|
return nil, fmt.Errorf("elevenlabs: no voice configured for language %q", lang)
|
||||||
}
|
}
|
||||||
body, err := json.Marshal(elevenLabsRequest{
|
body, err := json.Marshal(elevenLabsRequest{
|
||||||
Text: text,
|
Text: text,
|
||||||
@@ -101,7 +101,7 @@ func (p *ElevenLabs) Synthesize(ctx context.Context, text, lang string) ([]byte,
|
|||||||
VoiceSettings: elevenLabsVoiceSettings{Stability: 0.5, SimilarityBoost: 0.75},
|
VoiceSettings: elevenLabsVoiceSettings{Stability: 0.5, SimilarityBoost: 0.75},
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("elevenlabs: Anfrage-Body bauen: %w", err)
|
return nil, fmt.Errorf("elevenlabs: building request body: %w", err)
|
||||||
}
|
}
|
||||||
url := strings.TrimRight(p.Endpoint, "/") + "/v1/text-to-speech/" + voice
|
url := strings.TrimRight(p.Endpoint, "/") + "/v1/text-to-speech/" + voice
|
||||||
return postForBytes(ctx, p.Client, "elevenlabs", url,
|
return postForBytes(ctx, p.Client, "elevenlabs", url,
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
// fakeTTServation zeichnet einen Request am Fake-Server auf.
|
// recordedRequest records a request seen by the fake server.
|
||||||
type recordedRequest struct {
|
type recordedRequest struct {
|
||||||
method string
|
method string
|
||||||
path string
|
path string
|
||||||
@@ -19,8 +19,8 @@ type recordedRequest struct {
|
|||||||
body []byte
|
body []byte
|
||||||
}
|
}
|
||||||
|
|
||||||
// fakeTTSServer ist der httptest-Fake eines Cloud-Providers: antwortet mit
|
// fakeTTSServer is the httptest fake of a cloud provider: responds with
|
||||||
// status + body und zeichnet den (einzigen) gesehenen Request auf.
|
// status + body and records the (single) request it saw.
|
||||||
func fakeTTSServer(t *testing.T, status int, body []byte) (*httptest.Server, *recordedRequest) {
|
func fakeTTSServer(t *testing.T, status int, body []byte) (*httptest.Server, *recordedRequest) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
rec := &recordedRequest{}
|
rec := &recordedRequest{}
|
||||||
@@ -28,7 +28,7 @@ func fakeTTSServer(t *testing.T, status int, body []byte) (*httptest.Server, *re
|
|||||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
body2, err := io.ReadAll(r.Body)
|
body2, err := io.ReadAll(r.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("Fake-Server: Body lesen: %v", err)
|
t.Errorf("fake server: reading body: %v", err)
|
||||||
}
|
}
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
rec.method, rec.path, rec.header, rec.body = r.Method, r.URL.Path, r.Header.Clone(), body2
|
rec.method, rec.path, rec.header, rec.body = r.Method, r.URL.Path, r.Header.Clone(), body2
|
||||||
@@ -44,14 +44,14 @@ func envMap(kv map[string]string) func(string) string {
|
|||||||
return func(k string) string { return kv[k] }
|
return func(k string) string { return kv[k] }
|
||||||
}
|
}
|
||||||
|
|
||||||
// fakeMP3 ist eine beliebige Byte-Folge — die Provider geben Antwort-Bytes
|
// fakeMP3 is an arbitrary byte sequence; the providers return response
|
||||||
// unverändert zurück, der audio-Sink dekodiert (eigene Tests).
|
// bytes unchanged, the audio sink decodes (its own tests).
|
||||||
var fakeMP3 = []byte("\xff\xfb\x90\x00" + "audio-bytes-von-elf")
|
var fakeMP3 = []byte("\xff\xfb\x90\x00" + "audio-bytes-from-eleven")
|
||||||
|
|
||||||
// TestElevenLabsSynthese200: 200 mit Bytes → Bytes kommen unverändert
|
// TestElevenLabsSynthesize200: 200 with bytes → bytes come back unchanged;
|
||||||
// zurück; Methode, Pfad (inkl. Voice-ID), Header (xi-api-key) und der
|
// method, path (incl. voice ID), header (xi-api-key) and the JSON body
|
||||||
// JSON-Body (model_id, voice_settings) entsprechen dem Task-Brief.
|
// (model_id, voice_settings) match the API contract.
|
||||||
func TestElevenLabsSynthese200(t *testing.T) {
|
func TestElevenLabsSynthesize200(t *testing.T) {
|
||||||
ts, rec := fakeTTSServer(t, 200, fakeMP3)
|
ts, rec := fakeTTSServer(t, 200, fakeMP3)
|
||||||
p := NewElevenLabs(ChainConfig{
|
p := NewElevenLabs(ChainConfig{
|
||||||
Getenv: envMap(map[string]string{
|
Getenv: envMap(map[string]string{
|
||||||
@@ -60,18 +60,18 @@ func TestElevenLabsSynthese200(t *testing.T) {
|
|||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
|
|
||||||
data, err := p.Synthesize(context.Background(), "Hallo Welt", "de")
|
data, err := p.Synthesize(context.Background(), "Hello world", "de")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Synthesize: %v", err)
|
t.Fatalf("Synthesize: %v", err)
|
||||||
}
|
}
|
||||||
if string(data) != string(fakeMP3) {
|
if string(data) != string(fakeMP3) {
|
||||||
t.Errorf("Synthesize = %q, want Fake-Bytes %q", data, fakeMP3)
|
t.Errorf("Synthesize = %q, want fake bytes %q", data, fakeMP3)
|
||||||
}
|
}
|
||||||
if rec.method != http.MethodPost {
|
if rec.method != http.MethodPost {
|
||||||
t.Errorf("Methode = %s, want POST", rec.method)
|
t.Errorf("method = %s, want POST", rec.method)
|
||||||
}
|
}
|
||||||
if want := "/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM"; rec.path != want {
|
if want := "/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM"; rec.path != want {
|
||||||
t.Errorf("Pfad = %q, want %q (neutrales Repo-Default „Rachel“)", rec.path, want)
|
t.Errorf("path = %q, want %q (neutral repo default \"Rachel\")", rec.path, want)
|
||||||
}
|
}
|
||||||
if got := rec.header.Get("xi-api-key"); got != "testkey" {
|
if got := rec.header.Get("xi-api-key"); got != "testkey" {
|
||||||
t.Errorf("xi-api-key = %q, want %q", got, "testkey")
|
t.Errorf("xi-api-key = %q, want %q", got, "testkey")
|
||||||
@@ -86,9 +86,9 @@ func TestElevenLabsSynthese200(t *testing.T) {
|
|||||||
} `json:"voice_settings"`
|
} `json:"voice_settings"`
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal(rec.body, &body); err != nil {
|
if err := json.Unmarshal(rec.body, &body); err != nil {
|
||||||
t.Fatalf("Antwort-Body ist kein JSON: %v (%s)", err, rec.body)
|
t.Fatalf("request body is not JSON: %v (%s)", err, rec.body)
|
||||||
}
|
}
|
||||||
if body.Text != "Hallo Welt" {
|
if body.Text != "Hello world" {
|
||||||
t.Errorf("text = %q", body.Text)
|
t.Errorf("text = %q", body.Text)
|
||||||
}
|
}
|
||||||
if body.ModelID != "eleven_multilingual_v2" {
|
if body.ModelID != "eleven_multilingual_v2" {
|
||||||
@@ -99,9 +99,9 @@ func TestElevenLabsSynthese200(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestElevenLabsHTTPFehler: 500 und 401 sind klare Fehler, die Status und
|
// TestElevenLabsHTTPError: 500 and 401 are clear errors naming the status
|
||||||
// einen Body-Ausschnitt nennen (die Kette fällt daran weiter).
|
// and a body snippet (the chain falls back on them).
|
||||||
func TestElevenLabsHTTPFehler(t *testing.T) {
|
func TestElevenLabsHTTPError(t *testing.T) {
|
||||||
cases := []struct {
|
cases := []struct {
|
||||||
status int
|
status int
|
||||||
body string
|
body string
|
||||||
@@ -117,32 +117,32 @@ func TestElevenLabsHTTPFehler(t *testing.T) {
|
|||||||
EnvElevenLabsKey: "testkey",
|
EnvElevenLabsKey: "testkey",
|
||||||
EnvElevenLabsEndpoint: ts.URL,
|
EnvElevenLabsEndpoint: ts.URL,
|
||||||
})})
|
})})
|
||||||
_, err := p.Synthesize(context.Background(), "Hallo", "de")
|
_, err := p.Synthesize(context.Background(), "Hello", "de")
|
||||||
if err == nil || !strings.Contains(err.Error(), tc.want) {
|
if err == nil || !strings.Contains(err.Error(), tc.want) {
|
||||||
t.Fatalf("Synthesize-Fehler = %v, will HTTP %s", err, tc.want)
|
t.Fatalf("Synthesize error = %v, want HTTP %s", err, tc.want)
|
||||||
}
|
}
|
||||||
if !strings.Contains(err.Error(), "elevenlabs") {
|
if !strings.Contains(err.Error(), "elevenlabs") {
|
||||||
t.Errorf("Fehler soll den Provider nennen: %v", err)
|
t.Errorf("error should name the provider: %v", err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestElevenLabsAvailable: ohne Key nicht verfügbar, mit Key verfügbar —
|
// TestElevenLabsAvailable: not available without a key, available with
|
||||||
// ohne jeden Netz-Call.
|
// one; without any network call.
|
||||||
func TestElevenLabsAvailable(t *testing.T) {
|
func TestElevenLabsAvailable(t *testing.T) {
|
||||||
if NewElevenLabs(ChainConfig{Getenv: envMap(nil)}).Available(context.Background()) {
|
if NewElevenLabs(ChainConfig{Getenv: envMap(nil)}).Available(context.Background()) {
|
||||||
t.Error("Available ohne Key = true, want false")
|
t.Error("Available without key = true, want false")
|
||||||
}
|
}
|
||||||
p := NewElevenLabs(ChainConfig{Getenv: envMap(map[string]string{EnvElevenLabsKey: "k"})})
|
p := NewElevenLabs(ChainConfig{Getenv: envMap(map[string]string{EnvElevenLabsKey: "k"})})
|
||||||
if !p.Available(context.Background()) {
|
if !p.Available(context.Background()) {
|
||||||
t.Error("Available mit Key = false, want true")
|
t.Error("Available with key = false, want true")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestElevenLabsVoiceRangfolge: --voice-Pin schlägt config-Mapping, Mapping
|
// TestElevenLabsVoicePrecedence: the --voice pin beats the config mapping,
|
||||||
// schlägt Repo-Default (beobachtbar am Request-Pfad).
|
// the mapping beats the repo default (observable in the request path).
|
||||||
func TestElevenLabsVoiceRangfolge(t *testing.T) {
|
func TestElevenLabsVoicePrecedence(t *testing.T) {
|
||||||
mk := func(t *testing.T, voices map[string]string, pin string) (*ElevenLabs, *recordedRequest) {
|
mk := func(t *testing.T, voices map[string]string, pin string) (*ElevenLabs, *recordedRequest) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
ts, rec := fakeTTSServer(t, 200, fakeMP3)
|
ts, rec := fakeTTSServer(t, 200, fakeMP3)
|
||||||
@@ -159,46 +159,46 @@ func TestElevenLabsVoiceRangfolge(t *testing.T) {
|
|||||||
return p, rec
|
return p, rec
|
||||||
}
|
}
|
||||||
|
|
||||||
t.Run("config-Mapping schlägt Default", func(t *testing.T) {
|
t.Run("config mapping beats default", func(t *testing.T) {
|
||||||
p, rec := mk(t, map[string]string{"de": "AusConfig"}, "")
|
p, rec := mk(t, map[string]string{"de": "FromConfig"}, "")
|
||||||
if _, err := p.Synthesize(context.Background(), "Hallo", "de"); err != nil {
|
if _, err := p.Synthesize(context.Background(), "Hello", "de"); err != nil {
|
||||||
t.Fatalf("Synthesize: %v", err)
|
t.Fatalf("Synthesize: %v", err)
|
||||||
}
|
}
|
||||||
if want := "/v1/text-to-speech/AusConfig"; rec.path != want {
|
if want := "/v1/text-to-speech/FromConfig"; rec.path != want {
|
||||||
t.Errorf("Pfad = %q, want %q", rec.path, want)
|
t.Errorf("path = %q, want %q", rec.path, want)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
t.Run("Pin (--voice) schlägt config-Mapping", func(t *testing.T) {
|
t.Run("pin (--voice) beats config mapping", func(t *testing.T) {
|
||||||
p, rec := mk(t, map[string]string{"de": "AusConfig"}, "Gepinnt")
|
p, rec := mk(t, map[string]string{"de": "FromConfig"}, "Pinned")
|
||||||
if _, err := p.Synthesize(context.Background(), "Hallo", "de"); err != nil {
|
if _, err := p.Synthesize(context.Background(), "Hello", "de"); err != nil {
|
||||||
t.Fatalf("Synthesize: %v", err)
|
t.Fatalf("Synthesize: %v", err)
|
||||||
}
|
}
|
||||||
if want := "/v1/text-to-speech/Gepinnt"; rec.path != want {
|
if want := "/v1/text-to-speech/Pinned"; rec.path != want {
|
||||||
t.Errorf("Pfad = %q, want %q", rec.path, want)
|
t.Errorf("path = %q, want %q", rec.path, want)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
t.Run("unbekannte Sprache fällt auf en-Default", func(t *testing.T) {
|
t.Run("unknown language falls back to en default", func(t *testing.T) {
|
||||||
p, rec := mk(t, nil, "")
|
p, rec := mk(t, nil, "")
|
||||||
if _, err := p.Synthesize(context.Background(), "Hallo", "fr"); err != nil {
|
if _, err := p.Synthesize(context.Background(), "Hello", "fr"); err != nil {
|
||||||
t.Fatalf("Synthesize: %v", err)
|
t.Fatalf("Synthesize: %v", err)
|
||||||
}
|
}
|
||||||
if want := "/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM"; rec.path != want {
|
if want := "/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM"; rec.path != want {
|
||||||
t.Errorf("Pfad = %q, want en-Default %q", rec.path, want)
|
t.Errorf("path = %q, want en default %q", rec.path, want)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestElevenLabsLeererText ist ein klarer Fehler ohne Request.
|
// TestElevenLabsEmptyText is a clear error without a request.
|
||||||
func TestElevenLabsLeererText(t *testing.T) {
|
func TestElevenLabsEmptyText(t *testing.T) {
|
||||||
ts, rec := fakeTTSServer(t, 200, fakeMP3)
|
ts, rec := fakeTTSServer(t, 200, fakeMP3)
|
||||||
p := NewElevenLabs(ChainConfig{Getenv: envMap(map[string]string{
|
p := NewElevenLabs(ChainConfig{Getenv: envMap(map[string]string{
|
||||||
EnvElevenLabsKey: "k",
|
EnvElevenLabsKey: "k",
|
||||||
EnvElevenLabsEndpoint: ts.URL,
|
EnvElevenLabsEndpoint: ts.URL,
|
||||||
})})
|
})})
|
||||||
if _, err := p.Synthesize(context.Background(), "", "de"); err == nil {
|
if _, err := p.Synthesize(context.Background(), "", "de"); err == nil {
|
||||||
t.Error("Synthesize(\"\") soll fehlschlagen")
|
t.Error("Synthesize(\"\") should fail")
|
||||||
}
|
}
|
||||||
if rec.method != "" {
|
if rec.method != "" {
|
||||||
t.Error("Bei leerem Text darf kein Request gehen")
|
t.Error("no request must be sent for empty text")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -9,30 +9,30 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// cloudTimeout ist das Budget für einen einzigen Synthese-Call eines
|
// cloudTimeout is the budget for a single synthesis call of a cloud
|
||||||
// Cloud-Providers (Aufbau + Anfrage + vollständige Antwort). Ansagen sind
|
// provider (connect + request + complete response). Announcements are
|
||||||
// kurz; nach Ablauf greift der Fallback auf die nächste Ketten-Stufe.
|
// short; once it expires the chain falls back to the next tier.
|
||||||
const cloudTimeout = 45 * time.Second
|
const cloudTimeout = 45 * time.Second
|
||||||
|
|
||||||
// cloudClient ist der geteilte HTTP-Client der REST-Provider (mit Timeout,
|
// cloudClient is the shared HTTP client of the REST providers (with a
|
||||||
// im Gegensatz zu http.DefaultClient). Bei Ausbleiben einer Antwort greift
|
// timeout, unlike http.DefaultClient). If a response never arrives, the
|
||||||
// so der Ketten-Fallback statt einer Endlos-Blockade.
|
// chain falls back instead of blocking forever.
|
||||||
var cloudClient = &http.Client{Timeout: cloudTimeout}
|
var cloudClient = &http.Client{Timeout: cloudTimeout}
|
||||||
|
|
||||||
// maxErrBody begrenzt, wie viel einer Fehler-Antwort in die Fehlermeldung
|
// maxErrBody limits how much of an error response is copied into the error
|
||||||
// übernommen wird (Diagnose ja, Spam nein).
|
// message (diagnosis yes, spam no).
|
||||||
const maxErrBody = 200
|
const maxErrBody = 200
|
||||||
|
|
||||||
// postForBytes macht den gemeinsamen Kern der REST-Provider: POST von JSON
|
// postForBytes is the shared core of the REST providers: POST JSON to url
|
||||||
// an url mit Headern, erwartet 2xx und liefert die rohen Antwort-Bytes
|
// with headers, expect 2xx and return the raw response bytes (audio).
|
||||||
// (Audio). Alles andere — non-2xx, Netz-Fehler, Timeouts, leere Antworten —
|
// Everything else (non-2xx, network errors, timeouts, empty responses) is a
|
||||||
// ist ein klarer Fehler, an dem die Kette in die nächste Stufe fällt.
|
// clear error on which the chain falls back to the next tier.
|
||||||
func postForBytes(ctx context.Context, client *http.Client, providerName, url string, headers map[string]string, body []byte) ([]byte, error) {
|
func postForBytes(ctx context.Context, client *http.Client, providerName, url string, headers map[string]string, body []byte) ([]byte, error) {
|
||||||
if client == nil {
|
if client == nil {
|
||||||
client = cloudClient
|
client = cloudClient
|
||||||
}
|
}
|
||||||
// Eigenes Zeit-Budget setzen, falls der Aufrufer keins mitgibt — die
|
// Apply our own time budget if the caller does not bring one; the chain
|
||||||
// Kette soll auch ohne fremden Deadline-Kontext weiterfallen können.
|
// must be able to fall through even without an external deadline.
|
||||||
if _, hasDeadline := ctx.Deadline(); !hasDeadline {
|
if _, hasDeadline := ctx.Deadline(); !hasDeadline {
|
||||||
var cancel context.CancelFunc
|
var cancel context.CancelFunc
|
||||||
ctx, cancel = context.WithTimeout(ctx, cloudTimeout)
|
ctx, cancel = context.WithTimeout(ctx, cloudTimeout)
|
||||||
@@ -41,7 +41,7 @@ func postForBytes(ctx context.Context, client *http.Client, providerName, url st
|
|||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s: Anfrage an %s bauen: %w", providerName, url, err)
|
return nil, fmt.Errorf("%s: building request to %s: %w", providerName, url, err)
|
||||||
}
|
}
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
for k, v := range headers {
|
for k, v := range headers {
|
||||||
@@ -50,21 +50,21 @@ func postForBytes(ctx context.Context, client *http.Client, providerName, url st
|
|||||||
|
|
||||||
resp, err := client.Do(req)
|
resp, err := client.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s: Anfrage an %s fehlgeschlagen (Netz/Timeout?): %w", providerName, url, err)
|
return nil, fmt.Errorf("%s: request to %s failed (network/timeout?): %w", providerName, url, err)
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
||||||
snippet, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrBody))
|
snippet, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrBody))
|
||||||
return nil, fmt.Errorf("%s: HTTP %d von %s: %s", providerName, resp.StatusCode, url, bytes.TrimSpace(snippet))
|
return nil, fmt.Errorf("%s: HTTP %d from %s: %s", providerName, resp.StatusCode, url, bytes.TrimSpace(snippet))
|
||||||
}
|
}
|
||||||
|
|
||||||
data, err := io.ReadAll(resp.Body)
|
data, err := io.ReadAll(resp.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s: Antwort von %s lesen: %w", providerName, url, err)
|
return nil, fmt.Errorf("%s: reading response from %s: %w", providerName, url, err)
|
||||||
}
|
}
|
||||||
if len(data) == 0 {
|
if len(data) == 0 {
|
||||||
return nil, fmt.Errorf("%s: leere Antwort von %s (0 Bytes Audio)", providerName, url)
|
return nil, fmt.Errorf("%s: empty response from %s (0 bytes of audio)", providerName, url)
|
||||||
}
|
}
|
||||||
return data, nil
|
return data, nil
|
||||||
}
|
}
|
||||||
+29
-28
@@ -8,47 +8,48 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// OpenAI-TTS-Konstanten (öffentlicher Vertrag wie bei ElevenLabs).
|
// OpenAI TTS constants (public contract as with ElevenLabs).
|
||||||
const (
|
const (
|
||||||
// DefaultEndpointOpenAI ist der produktive API-Endpunkt.
|
// DefaultEndpointOpenAI is the production API endpoint.
|
||||||
DefaultEndpointOpenAI = "https://api.openai.com"
|
DefaultEndpointOpenAI = "https://api.openai.com"
|
||||||
|
|
||||||
// DefaultModelOpenAI: Entscheidungsnotiz aus dem Task-Brief — der
|
// DefaultModelOpenAI: decision note. The model string is configurable
|
||||||
// Modell-String ist konfigurierbar ([providers.openai] model), Default
|
// ([providers.openai] model), default "tts-1"; "gpt-4o-mini-tts" is a
|
||||||
// "tts-1"; "gpt-4o-mini-tts" ist ein gültiger Alternativwert.
|
// valid alternative.
|
||||||
DefaultModelOpenAI = "tts-1"
|
DefaultModelOpenAI = "tts-1"
|
||||||
|
|
||||||
EnvOpenAIKey = "TALK_OPENAI_KEY"
|
EnvOpenAIKey = "TALK_OPENAI_KEY"
|
||||||
EnvOpenAIEndpoint = "TALK_OPENAI_ENDPOINT"
|
EnvOpenAIEndpoint = "TALK_OPENAI_ENDPOINT"
|
||||||
)
|
)
|
||||||
|
|
||||||
// OpenAI ist die zweite Stufe der Kette (für Nutzer mit vorhandenem
|
// OpenAI is the second tier of the chain (for users with an existing OpenAI
|
||||||
// OpenAI-Key). Synthesize führt POST <endpoint>/v1/audio/speech aus —
|
// key). Synthesize performs POST <endpoint>/v1/audio/speech with a bearer
|
||||||
// Bearer-Key, Body {model, voice, input, response_format: "mp3"} — und
|
// key and body {model, voice, input, response_format: "mp3"} and returns
|
||||||
// liefert die Antwort-Bytes unverändert zurück. Rückgabeformat: MP3.
|
// the response bytes unchanged. Return format: MP3.
|
||||||
type OpenAI struct {
|
type OpenAI struct {
|
||||||
// Endpoint ist die Basis-URL (ohne Pfad); leer = Default beim Bau.
|
// Endpoint is the base URL (without path); empty = default at
|
||||||
|
// construction.
|
||||||
Endpoint string
|
Endpoint string
|
||||||
|
|
||||||
// APIKey ist der OpenAI-Key (aus TALK_OPENAI_KEY).
|
// APIKey is the OpenAI key (from TALK_OPENAI_KEY).
|
||||||
APIKey string
|
APIKey string
|
||||||
|
|
||||||
// Model ist der TTS-Modell-String; leer = DefaultModelOpenAI.
|
// Model is the TTS model string; empty = DefaultModelOpenAI.
|
||||||
Model string
|
Model string
|
||||||
|
|
||||||
// Voices ist das config-Mapping voice.openai.<lang> = id; leer =
|
// Voices is the config mapping voice.openai.<lang> = id; empty =
|
||||||
// neutrale Repo-Defaults (alloy, siehe voices.go).
|
// neutral repo defaults (alloy, see voices.go).
|
||||||
Voices map[string]string
|
Voices map[string]string
|
||||||
|
|
||||||
// Client ist der HTTP-Client; nil = geteilter Client mit Timeout.
|
// Client is the HTTP client; nil = shared client with timeout.
|
||||||
Client *http.Client
|
Client *http.Client
|
||||||
|
|
||||||
pinned string // --voice-Pin (VoicePinner)
|
pinned string // --voice pin (VoicePinner)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewOpenAI baut den Provider aus der Ketten-Konfiguration: Endpunkt aus
|
// NewOpenAI builds the provider from the chain configuration: endpoint from
|
||||||
// TALK_OPENAI_ENDPOINT > [providers.openai].endpoint > Default; Modell aus
|
// TALK_OPENAI_ENDPOINT > [providers.openai].endpoint > default; model from
|
||||||
// [providers.openai].model; Key ausschließlich aus TALK_OPENAI_KEY.
|
// [providers.openai].model; key exclusively from TALK_OPENAI_KEY.
|
||||||
func NewOpenAI(cfg ChainConfig) *OpenAI {
|
func NewOpenAI(cfg ChainConfig) *OpenAI {
|
||||||
return &OpenAI{
|
return &OpenAI{
|
||||||
Endpoint: endpointFrom(cfg, "openai", EnvOpenAIEndpoint, DefaultEndpointOpenAI),
|
Endpoint: endpointFrom(cfg, "openai", EnvOpenAIEndpoint, DefaultEndpointOpenAI),
|
||||||
@@ -58,19 +59,19 @@ func NewOpenAI(cfg ChainConfig) *OpenAI {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name implementiert Provider.
|
// Name implements Provider.
|
||||||
func (*OpenAI) Name() string { return "openai" }
|
func (*OpenAI) Name() string { return "openai" }
|
||||||
|
|
||||||
// PinVoice implementiert VoicePinner (CLI-Flag --voice).
|
// PinVoice implements VoicePinner (CLI flag --voice).
|
||||||
func (p *OpenAI) PinVoice(id string) { p.pinned = id }
|
func (p *OpenAI) PinVoice(id string) { p.pinned = id }
|
||||||
|
|
||||||
// Available implementiert Provider: Key und Endpunkt müssen gesetzt sein
|
// Available implements Provider: key and endpoint must be set (without a
|
||||||
// (ohne Netz-Call, siehe ElevenLabs.Available).
|
// network call, see ElevenLabs.Available).
|
||||||
func (p *OpenAI) Available(ctx context.Context) bool {
|
func (p *OpenAI) Available(ctx context.Context) bool {
|
||||||
return p.APIKey != "" && p.Endpoint != ""
|
return p.APIKey != "" && p.Endpoint != ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// openAIRequest ist der Anfrage-Body.
|
// openAIRequest is the request body.
|
||||||
type openAIRequest struct {
|
type openAIRequest struct {
|
||||||
Model string `json:"model"`
|
Model string `json:"model"`
|
||||||
Voice string `json:"voice"`
|
Voice string `json:"voice"`
|
||||||
@@ -78,14 +79,14 @@ type openAIRequest struct {
|
|||||||
ResponseFormat string `json:"response_format"`
|
ResponseFormat string `json:"response_format"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Synthesize implementiert Provider. Rückgabeformat: MP3.
|
// Synthesize implements Provider. Return format: MP3.
|
||||||
func (p *OpenAI) Synthesize(ctx context.Context, text, lang string) ([]byte, error) {
|
func (p *OpenAI) Synthesize(ctx context.Context, text, lang string) ([]byte, error) {
|
||||||
if text == "" {
|
if text == "" {
|
||||||
return nil, fmt.Errorf("openai: leerer Text")
|
return nil, fmt.Errorf("openai: empty text")
|
||||||
}
|
}
|
||||||
voice := resolveVoice("openai", lang, p.pinned, p.Voices)
|
voice := resolveVoice("openai", lang, p.pinned, p.Voices)
|
||||||
if voice == "" {
|
if voice == "" {
|
||||||
return nil, fmt.Errorf("openai: keine Stimme für Sprache %q konfiguriert", lang)
|
return nil, fmt.Errorf("openai: no voice configured for language %q", lang)
|
||||||
}
|
}
|
||||||
model := p.Model
|
model := p.Model
|
||||||
if model == "" {
|
if model == "" {
|
||||||
@@ -98,7 +99,7 @@ func (p *OpenAI) Synthesize(ctx context.Context, text, lang string) ([]byte, err
|
|||||||
ResponseFormat: "mp3",
|
ResponseFormat: "mp3",
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("openai: Anfrage-Body bauen: %w", err)
|
return nil, fmt.Errorf("openai: building request body: %w", err)
|
||||||
}
|
}
|
||||||
url := strings.TrimRight(p.Endpoint, "/") + "/v1/audio/speech"
|
url := strings.TrimRight(p.Endpoint, "/") + "/v1/audio/speech"
|
||||||
return postForBytes(ctx, p.Client, "openai", url,
|
return postForBytes(ctx, p.Client, "openai", url,
|
||||||
|
|||||||
@@ -9,10 +9,10 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestOpenAISynthese200: 200 mit Bytes → Bytes unverändert; POST
|
// TestOpenAISynthesize200: 200 with bytes → bytes unchanged; POST
|
||||||
// /v1/audio/speech, Bearer-Key, Body mit model/voice/input/response_format
|
// /v1/audio/speech, bearer key, body with model/voice/input/response_format
|
||||||
// laut Task-Brief (Default-Modell tts-1, Default-Stimme alloy).
|
// per the API contract (default model tts-1, default voice alloy).
|
||||||
func TestOpenAISynthese200(t *testing.T) {
|
func TestOpenAISynthesize200(t *testing.T) {
|
||||||
ts, rec := fakeTTSServer(t, 200, fakeMP3)
|
ts, rec := fakeTTSServer(t, 200, fakeMP3)
|
||||||
p := NewOpenAI(ChainConfig{
|
p := NewOpenAI(ChainConfig{
|
||||||
Getenv: envMap(map[string]string{
|
Getenv: envMap(map[string]string{
|
||||||
@@ -21,18 +21,18 @@ func TestOpenAISynthese200(t *testing.T) {
|
|||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
|
|
||||||
data, err := p.Synthesize(context.Background(), "Build fertig", "en")
|
data, err := p.Synthesize(context.Background(), "Build finished", "en")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Synthesize: %v", err)
|
t.Fatalf("Synthesize: %v", err)
|
||||||
}
|
}
|
||||||
if string(data) != string(fakeMP3) {
|
if string(data) != string(fakeMP3) {
|
||||||
t.Errorf("Synthesize = %q, want Fake-Bytes", data)
|
t.Errorf("Synthesize = %q, want fake bytes", data)
|
||||||
}
|
}
|
||||||
if rec.method != http.MethodPost {
|
if rec.method != http.MethodPost {
|
||||||
t.Errorf("Methode = %s, want POST", rec.method)
|
t.Errorf("method = %s, want POST", rec.method)
|
||||||
}
|
}
|
||||||
if want := "/v1/audio/speech"; rec.path != want {
|
if want := "/v1/audio/speech"; rec.path != want {
|
||||||
t.Errorf("Pfad = %q, want %q", rec.path, want)
|
t.Errorf("path = %q, want %q", rec.path, want)
|
||||||
}
|
}
|
||||||
if got := rec.header.Get("Authorization"); got != "Bearer sk-test" {
|
if got := rec.header.Get("Authorization"); got != "Bearer sk-test" {
|
||||||
t.Errorf("Authorization = %q, want Bearer sk-test", got)
|
t.Errorf("Authorization = %q, want Bearer sk-test", got)
|
||||||
@@ -45,15 +45,15 @@ func TestOpenAISynthese200(t *testing.T) {
|
|||||||
ResponseFormat string `json:"response_format"`
|
ResponseFormat string `json:"response_format"`
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal(rec.body, &body); err != nil {
|
if err := json.Unmarshal(rec.body, &body); err != nil {
|
||||||
t.Fatalf("Body ist kein JSON: %v (%s)", err, rec.body)
|
t.Fatalf("body is not JSON: %v (%s)", err, rec.body)
|
||||||
}
|
}
|
||||||
if body.Model != "tts-1" {
|
if body.Model != "tts-1" {
|
||||||
t.Errorf("model = %q, want Default tts-1", body.Model)
|
t.Errorf("model = %q, want default tts-1", body.Model)
|
||||||
}
|
}
|
||||||
if body.Voice != "alloy" {
|
if body.Voice != "alloy" {
|
||||||
t.Errorf("voice = %q, want Default alloy", body.Voice)
|
t.Errorf("voice = %q, want default alloy", body.Voice)
|
||||||
}
|
}
|
||||||
if body.Input != "Build fertig" {
|
if body.Input != "Build finished" {
|
||||||
t.Errorf("input = %q", body.Input)
|
t.Errorf("input = %q", body.Input)
|
||||||
}
|
}
|
||||||
if body.ResponseFormat != "mp3" {
|
if body.ResponseFormat != "mp3" {
|
||||||
@@ -61,8 +61,8 @@ func TestOpenAISynthese200(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestOpenAIHTTPFehler: 500 und 401 sind klare Fehler mit Status.
|
// TestOpenAIHTTPError: 500 and 401 are clear errors with the status.
|
||||||
func TestOpenAIHTTPFehler(t *testing.T) {
|
func TestOpenAIHTTPError(t *testing.T) {
|
||||||
for _, status := range []int{500, 401} {
|
for _, status := range []int{500, 401} {
|
||||||
t.Run(http.StatusText(status), func(t *testing.T) {
|
t.Run(http.StatusText(status), func(t *testing.T) {
|
||||||
ts, _ := fakeTTSServer(t, status, []byte("boom"))
|
ts, _ := fakeTTSServer(t, status, []byte("boom"))
|
||||||
@@ -70,21 +70,21 @@ func TestOpenAIHTTPFehler(t *testing.T) {
|
|||||||
EnvOpenAIKey: "sk-test",
|
EnvOpenAIKey: "sk-test",
|
||||||
EnvOpenAIEndpoint: ts.URL,
|
EnvOpenAIEndpoint: ts.URL,
|
||||||
})})
|
})})
|
||||||
_, err := p.Synthesize(context.Background(), "Hallo", "de")
|
_, err := p.Synthesize(context.Background(), "Hello", "de")
|
||||||
if err == nil || !strings.Contains(err.Error(), fmt.Sprintf("%d", status)) {
|
if err == nil || !strings.Contains(err.Error(), fmt.Sprintf("%d", status)) {
|
||||||
t.Fatalf("Synthesize-Fehler = %v, will HTTP %d", err, status)
|
t.Fatalf("Synthesize error = %v, want HTTP %d", err, status)
|
||||||
}
|
}
|
||||||
if !strings.Contains(err.Error(), "openai") {
|
if !strings.Contains(err.Error(), "openai") {
|
||||||
t.Errorf("Fehler soll den Provider nennen: %v", err)
|
t.Errorf("error should name the provider: %v", err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestOpenAIModelKonfigurierbar: [providers.openai].model ändert den
|
// TestOpenAIModelConfigurable: [providers.openai].model changes the model
|
||||||
// Modell-String im Body (Entscheidungsnotiz: Default tts-1, Alternativen
|
// string in the body (decision note: default tts-1, alternatives such as
|
||||||
// wie gpt-4o-mini-tts erlaubt).
|
// gpt-4o-mini-tts allowed).
|
||||||
func TestOpenAIModelKonfigurierbar(t *testing.T) {
|
func TestOpenAIModelConfigurable(t *testing.T) {
|
||||||
ts, rec := fakeTTSServer(t, 200, fakeMP3)
|
ts, rec := fakeTTSServer(t, 200, fakeMP3)
|
||||||
p := NewOpenAI(ChainConfig{
|
p := NewOpenAI(ChainConfig{
|
||||||
Getenv: envMap(map[string]string{
|
Getenv: envMap(map[string]string{
|
||||||
@@ -93,7 +93,7 @@ func TestOpenAIModelKonfigurierbar(t *testing.T) {
|
|||||||
}),
|
}),
|
||||||
Model: "gpt-4o-mini-tts",
|
Model: "gpt-4o-mini-tts",
|
||||||
})
|
})
|
||||||
if _, err := p.Synthesize(context.Background(), "Hallo", "de"); err != nil {
|
if _, err := p.Synthesize(context.Background(), "Hello", "de"); err != nil {
|
||||||
t.Fatalf("Synthesize: %v", err)
|
t.Fatalf("Synthesize: %v", err)
|
||||||
}
|
}
|
||||||
var body struct {
|
var body struct {
|
||||||
@@ -107,20 +107,20 @@ func TestOpenAIModelKonfigurierbar(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestOpenAIAvailable: Key entscheidet — ohne Netz-Call.
|
// TestOpenAIAvailable: the key decides; without a network call.
|
||||||
func TestOpenAIAvailable(t *testing.T) {
|
func TestOpenAIAvailable(t *testing.T) {
|
||||||
if NewOpenAI(ChainConfig{Getenv: envMap(nil)}).Available(context.Background()) {
|
if NewOpenAI(ChainConfig{Getenv: envMap(nil)}).Available(context.Background()) {
|
||||||
t.Error("Available ohne Key = true, want false")
|
t.Error("Available without key = true, want false")
|
||||||
}
|
}
|
||||||
p := NewOpenAI(ChainConfig{Getenv: envMap(map[string]string{EnvOpenAIKey: "sk"})})
|
p := NewOpenAI(ChainConfig{Getenv: envMap(map[string]string{EnvOpenAIKey: "sk"})})
|
||||||
if !p.Available(context.Background()) {
|
if !p.Available(context.Background()) {
|
||||||
t.Error("Available mit Key = false, want true")
|
t.Error("Available with key = false, want true")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestOpenAIVoiceRangfolge: Pin schlägt Mapping schlägt Default.
|
// TestOpenAIVoicePrecedence: pin beats mapping beats default.
|
||||||
func TestOpenAIVoiceRangfolge(t *testing.T) {
|
func TestOpenAIVoicePrecedence(t *testing.T) {
|
||||||
t.Run("Mapping schlägt Default", func(t *testing.T) {
|
t.Run("mapping beats default", func(t *testing.T) {
|
||||||
ts, rec := fakeTTSServer(t, 200, fakeMP3)
|
ts, rec := fakeTTSServer(t, 200, fakeMP3)
|
||||||
p := NewOpenAI(ChainConfig{
|
p := NewOpenAI(ChainConfig{
|
||||||
Getenv: envMap(map[string]string{
|
Getenv: envMap(map[string]string{
|
||||||
@@ -140,7 +140,7 @@ func TestOpenAIVoiceRangfolge(t *testing.T) {
|
|||||||
t.Errorf("voice = %q, want nova (config)", body.Voice)
|
t.Errorf("voice = %q, want nova (config)", body.Voice)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
t.Run("Pin schlägt Mapping", func(t *testing.T) {
|
t.Run("pin beats mapping", func(t *testing.T) {
|
||||||
ts, rec := fakeTTSServer(t, 200, fakeMP3)
|
ts, rec := fakeTTSServer(t, 200, fakeMP3)
|
||||||
p := NewOpenAI(ChainConfig{
|
p := NewOpenAI(ChainConfig{
|
||||||
Getenv: envMap(map[string]string{
|
Getenv: envMap(map[string]string{
|
||||||
|
|||||||
@@ -13,35 +13,36 @@ import (
|
|||||||
"unicode/utf16"
|
"unicode/utf16"
|
||||||
)
|
)
|
||||||
|
|
||||||
// OSBuiltin spricht über die im Betriebssystem eingebaute TTS-Runtime.
|
// OSBuiltin speaks through the TTS runtime built into the operating system.
|
||||||
// Es ist der Notnagel-Provider der Kette: überall vorhanden, ohne Key und
|
// It is the chain's provider of last resort: present everywhere, without a
|
||||||
// ohne Netz — aber die einfachste Stimme.
|
// key and without network, but with the plainest voice.
|
||||||
//
|
//
|
||||||
// Plattform-Mechanismen (Auswahl zur Laufzeit über runtime.GOOS, damit eine
|
// Platform mechanisms (selected at runtime via runtime.GOOS so that one
|
||||||
// Binärversion alle Ziele kompiliert; jede Route ist reines exec ohne Shell):
|
// binary compiles for all targets; every route is pure exec without a
|
||||||
|
// shell):
|
||||||
//
|
//
|
||||||
// Linux: Synthesize über espeak/espeak-ng (--stdout → WAV-Bytes).
|
// Linux: Synthesize via espeak/espeak-ng (--stdout → WAV bytes).
|
||||||
// Fehlt beides, liefert Synthesize ErrNoByteOutput und
|
// If both are missing, Synthesize returns ErrNoByteOutput and
|
||||||
// SpeakDirect spielt über spd-say (speech-dispatcher) ab —
|
// SpeakDirect plays via spd-say (speech-dispatcher); according
|
||||||
// spd-say kann Audio nach eigener --help-Ausgabe nur selbst über
|
// to its own --help output spd-say can only emit audio itself
|
||||||
// den Daemon ausgeben, nicht in eine Datei/in einen Prozess
|
// through the daemon, not write it to a file or a process
|
||||||
// schreiben (verifiziert am Dev-Host 2026-10-18).
|
// (verified on the dev host 2026-10-18).
|
||||||
// macOS: Synthesize über say (-o temporäre WAV-Datei,
|
// macOS: Synthesize via say (-o temporary WAV file,
|
||||||
// --data-format=LEI16@22050); Stimmen de→Anna, en→Samantha
|
// --data-format=LEI16@22050); voices de→Anna, en→Samantha
|
||||||
// (vorinstalliert; ersetzt durch das Voice-Mapping in Task 03).
|
// (preinstalled).
|
||||||
// Windows: Synthesize über PowerShell System.Speech in temporäre WAV-
|
// Windows: Synthesize via PowerShell System.Speech into a temporary WAV
|
||||||
// Datei (SetOutputToWaveFile); Sprache via SelectVoiceByHints
|
// file (SetOutputToWaveFile); language via SelectVoiceByHints
|
||||||
// mit Fallback auf die Systemstimme.
|
// with fallback to the system voice.
|
||||||
//
|
//
|
||||||
// Fehlende Binaries/Runtimes führen zu Available()==false bzw. klaren
|
// Missing binaries/runtimes lead to Available()==false or clear errors,
|
||||||
// Fehlern — nie zu Panics.
|
// never to panics.
|
||||||
type OSBuiltin struct{}
|
type OSBuiltin struct{}
|
||||||
|
|
||||||
// Name implementiert Provider.
|
// Name implements Provider.
|
||||||
func (OSBuiltin) Name() string { return "osbuiltin" }
|
func (OSBuiltin) Name() string { return "osbuiltin" }
|
||||||
|
|
||||||
// Available implementiert Provider: true, wenn mindestens ein
|
// Available implements Provider: true if at least one platform mechanism is
|
||||||
// Plattform-Mechanismus vorhanden ist.
|
// present.
|
||||||
func (OSBuiltin) Available(ctx context.Context) bool {
|
func (OSBuiltin) Available(ctx context.Context) bool {
|
||||||
switch runtime.GOOS {
|
switch runtime.GOOS {
|
||||||
case "darwin":
|
case "darwin":
|
||||||
@@ -50,7 +51,7 @@ func (OSBuiltin) Available(ctx context.Context) bool {
|
|||||||
case "windows":
|
case "windows":
|
||||||
_, err := exec.LookPath("powershell")
|
_, err := exec.LookPath("powershell")
|
||||||
return err == nil
|
return err == nil
|
||||||
default: // linux und sonstige unixartige Systeme
|
default: // linux and other unix-like systems
|
||||||
for _, bin := range []string{"espeak", "espeak-ng", "spd-say"} {
|
for _, bin := range []string{"espeak", "espeak-ng", "spd-say"} {
|
||||||
if _, err := exec.LookPath(bin); err == nil {
|
if _, err := exec.LookPath(bin); err == nil {
|
||||||
return true
|
return true
|
||||||
@@ -60,40 +61,40 @@ func (OSBuiltin) Available(ctx context.Context) bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Describe nennt den gefundenen Plattform-Mechanismus für die Diagnose
|
// Describe names the platform mechanism found, for diagnosis
|
||||||
// (`talk doctor`): z. B. „espeak-ng (Audio-Bytes)", „spd-say (nur
|
// (`talk doctor`): e.g. "espeak-ng (audio bytes)", "spd-say (direct speech
|
||||||
// Direktansage; espeak-ng für Audio-Bytes fehlt)", „say", „powershell
|
// only; install espeak-ng for audio bytes)", "say", "powershell (SAPI)",
|
||||||
// (SAPI)" — oder, was fehlt.
|
// or what is missing.
|
||||||
func (OSBuiltin) Describe() string {
|
func (OSBuiltin) Describe() string {
|
||||||
switch runtime.GOOS {
|
switch runtime.GOOS {
|
||||||
case "darwin":
|
case "darwin":
|
||||||
if _, err := exec.LookPath("say"); err == nil {
|
if _, err := exec.LookPath("say"); err == nil {
|
||||||
return "say (macOS)"
|
return "say (macOS)"
|
||||||
}
|
}
|
||||||
return "say nicht gefunden"
|
return "say not found"
|
||||||
case "windows":
|
case "windows":
|
||||||
if _, err := exec.LookPath("powershell"); err == nil {
|
if _, err := exec.LookPath("powershell"); err == nil {
|
||||||
return "powershell (SAPI System.Speech)"
|
return "powershell (SAPI System.Speech)"
|
||||||
}
|
}
|
||||||
return "powershell nicht gefunden"
|
return "powershell not found"
|
||||||
default:
|
default:
|
||||||
for _, bin := range []string{"espeak-ng", "espeak"} {
|
for _, bin := range []string{"espeak-ng", "espeak"} {
|
||||||
if _, err := exec.LookPath(bin); err == nil {
|
if _, err := exec.LookPath(bin); err == nil {
|
||||||
return bin + " (Audio-Bytes)"
|
return bin + " (audio bytes)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if _, err := exec.LookPath("spd-say"); err == nil {
|
if _, err := exec.LookPath("spd-say"); err == nil {
|
||||||
return "spd-say (nur Direktansage; espeak-ng für Audio-Bytes fehlt)"
|
return "spd-say (direct speech only; install espeak-ng for audio bytes)"
|
||||||
}
|
}
|
||||||
return "weder espeak-ng/espeak noch spd-say gefunden (espeak-ng installieren)"
|
return "neither espeak-ng/espeak nor spd-say found (install espeak-ng)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Synthesize implementiert Provider. Rückgabeformat: RIFF/WAVE (PCM) —
|
// Synthesize implements Provider. Return format: RIFF/WAVE (PCM), playable
|
||||||
// abspielbar über jeden Sink des audio-Pakets.
|
// through every sink of the audio package.
|
||||||
func (p OSBuiltin) Synthesize(ctx context.Context, text, lang string) ([]byte, error) {
|
func (p OSBuiltin) Synthesize(ctx context.Context, text, lang string) ([]byte, error) {
|
||||||
if text == "" {
|
if text == "" {
|
||||||
return nil, fmt.Errorf("osbuiltin: leerer Text")
|
return nil, fmt.Errorf("osbuiltin: empty text")
|
||||||
}
|
}
|
||||||
switch runtime.GOOS {
|
switch runtime.GOOS {
|
||||||
case "darwin":
|
case "darwin":
|
||||||
@@ -105,31 +106,36 @@ func (p OSBuiltin) Synthesize(ctx context.Context, text, lang string) ([]byte, e
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// SpeakDirect implementiert DirectSpeaker: direkte, blockierende Ausgabe
|
// SpeakDirect implements DirectSpeaker: direct, blocking output through the
|
||||||
// über das OS-TTS mit eigener Wiedergabe. Notwendig auf Linux ohne espeak;
|
// OS TTS with its own playback. Required on Linux without espeak; not
|
||||||
// auf macOS/Windows nicht erforderlich (Synthesize liefert WAV) und ist
|
// needed on macOS/Windows (Synthesize returns WAV) and a clear error there.
|
||||||
// dort ein klarer Fehler.
|
|
||||||
func (p OSBuiltin) SpeakDirect(ctx context.Context, text, lang string) error {
|
func (p OSBuiltin) SpeakDirect(ctx context.Context, text, lang string) error {
|
||||||
if text == "" {
|
if text == "" {
|
||||||
return fmt.Errorf("osbuiltin: leerer Text")
|
return fmt.Errorf("osbuiltin: empty text")
|
||||||
}
|
}
|
||||||
switch runtime.GOOS {
|
switch runtime.GOOS {
|
||||||
case "darwin", "windows":
|
case "darwin", "windows":
|
||||||
return fmt.Errorf("osbuiltin: SpeakDirect auf %s nicht nötig — Synthesize liefert WAV; über einen Sink abspielen", runtime.GOOS)
|
return fmt.Errorf("osbuiltin: SpeakDirect not needed on %s; Synthesize returns WAV, play it through a sink", runtime.GOOS)
|
||||||
default:
|
default:
|
||||||
if _, err := exec.LookPath("spd-say"); err != nil {
|
if _, err := exec.LookPath("spd-say"); err != nil {
|
||||||
return fmt.Errorf("osbuiltin: spd-say nicht gefunden (speech-dispatcher installieren oder espeak für Audio-Bytes): %w", err)
|
return fmt.Errorf("osbuiltin: spd-say not found (install speech-dispatcher, or espeak for audio bytes): %w", err)
|
||||||
}
|
}
|
||||||
cmd := exec.CommandContext(ctx, "spd-say", "-w", "-l", lang, text)
|
cmd := exec.CommandContext(ctx, "spd-say", "-w", "-l", lang, text)
|
||||||
if out, err := cmd.CombinedOutput(); err != nil {
|
if out, err := cmd.CombinedOutput(); err != nil {
|
||||||
return fmt.Errorf("osbuiltin: spd-say fehlgeschlagen: %w: %s", err, bytes.TrimSpace(out))
|
if ctx.Err() != nil {
|
||||||
|
// Cancelled: killing the waiting client does not stop
|
||||||
|
// speech-dispatcher's output; tell it to stop explicitly.
|
||||||
|
_ = exec.Command("spd-say", "-S").Run()
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
return fmt.Errorf("osbuiltin: spd-say failed: %w: %s", err, bytes.TrimSpace(out))
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// synthEspeak versucht espeak, dann espeak-ng. Beide schreiben WAV
|
// synthEspeak tries espeak, then espeak-ng. Both write WAV (RIFF/PCM) to
|
||||||
// (RIFF/PCM) auf stdout.
|
// stdout.
|
||||||
func (OSBuiltin) synthEspeak(ctx context.Context, text, lang string) ([]byte, error) {
|
func (OSBuiltin) synthEspeak(ctx context.Context, text, lang string) ([]byte, error) {
|
||||||
for _, bin := range []string{"espeak", "espeak-ng"} {
|
for _, bin := range []string{"espeak", "espeak-ng"} {
|
||||||
if _, err := exec.LookPath(bin); err != nil {
|
if _, err := exec.LookPath(bin); err != nil {
|
||||||
@@ -138,26 +144,26 @@ func (OSBuiltin) synthEspeak(ctx context.Context, text, lang string) ([]byte, er
|
|||||||
cmd := exec.CommandContext(ctx, bin, "-v", lang, "--stdout", text)
|
cmd := exec.CommandContext(ctx, bin, "-v", lang, "--stdout", text)
|
||||||
out, err := cmd.Output()
|
out, err := cmd.Output()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("osbuiltin: %s fehlgeschlagen: %w", bin, withStderr(err))
|
return nil, fmt.Errorf("osbuiltin: %s failed: %w", bin, withStderr(err))
|
||||||
}
|
}
|
||||||
if len(out) == 0 {
|
if len(out) == 0 {
|
||||||
return nil, fmt.Errorf("osbuiltin: %s lieferte keine Audiodaten", bin)
|
return nil, fmt.Errorf("osbuiltin: %s returned no audio data", bin)
|
||||||
}
|
}
|
||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
return nil, fmt.Errorf("osbuiltin: unter %s kein espeak/espeak-ng für Audio-Bytes gefunden: %w", runtime.GOOS, ErrNoByteOutput)
|
return nil, fmt.Errorf("osbuiltin: no espeak/espeak-ng for audio bytes found on %s: %w", runtime.GOOS, ErrNoByteOutput)
|
||||||
}
|
}
|
||||||
|
|
||||||
// synthSay erzeugt WAV über das macOS-say-Kommando in einer temporären
|
// synthSay produces WAV via the macOS say command into a temporary file.
|
||||||
// Datei. --data-format=LEI16@22050 erzwingt 16-Bit-PCM; die Endung .wav
|
// --data-format=LEI16@22050 forces 16-bit PCM; the .wav extension forces
|
||||||
// den WAVE-Container.
|
// the WAVE container.
|
||||||
func (OSBuiltin) synthSay(ctx context.Context, text, lang string) ([]byte, error) {
|
func (OSBuiltin) synthSay(ctx context.Context, text, lang string) ([]byte, error) {
|
||||||
if _, err := exec.LookPath("say"); err != nil {
|
if _, err := exec.LookPath("say"); err != nil {
|
||||||
return nil, fmt.Errorf("osbuiltin: say nicht gefunden: %w", err)
|
return nil, fmt.Errorf("osbuiltin: say not found: %w", err)
|
||||||
}
|
}
|
||||||
tmp, err := os.CreateTemp("", "talk-say-*.wav")
|
tmp, err := os.CreateTemp("", "talk-say-*.wav")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("osbuiltin: temporäre Datei: %w", err)
|
return nil, fmt.Errorf("osbuiltin: temporary file: %w", err)
|
||||||
}
|
}
|
||||||
name := tmp.Name()
|
name := tmp.Name()
|
||||||
tmp.Close()
|
tmp.Close()
|
||||||
@@ -166,16 +172,16 @@ func (OSBuiltin) synthSay(ctx context.Context, text, lang string) ([]byte, error
|
|||||||
cmd := exec.CommandContext(ctx, "say", "-v", sayVoice(lang),
|
cmd := exec.CommandContext(ctx, "say", "-v", sayVoice(lang),
|
||||||
"--data-format=LEI16@22050", "-o", name, text)
|
"--data-format=LEI16@22050", "-o", name, text)
|
||||||
if out, err := cmd.CombinedOutput(); err != nil {
|
if out, err := cmd.CombinedOutput(); err != nil {
|
||||||
return nil, fmt.Errorf("osbuiltin: say fehlgeschlagen: %w: %s", err, bytes.TrimSpace(out))
|
return nil, fmt.Errorf("osbuiltin: say failed: %w: %s", err, bytes.TrimSpace(out))
|
||||||
}
|
}
|
||||||
data, err := os.ReadFile(name)
|
data, err := os.ReadFile(name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("osbuiltin: say-Ausgabe lesen: %w", err)
|
return nil, fmt.Errorf("osbuiltin: reading say output: %w", err)
|
||||||
}
|
}
|
||||||
return data, nil
|
return data, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// sayVoice mappt Sprachen auf vorinstallierte macOS-Stimmen.
|
// sayVoice maps languages to preinstalled macOS voices.
|
||||||
func sayVoice(lang string) string {
|
func sayVoice(lang string) string {
|
||||||
if lang == "en" {
|
if lang == "en" {
|
||||||
return "Samantha" // en-US
|
return "Samantha" // en-US
|
||||||
@@ -183,18 +189,18 @@ func sayVoice(lang string) string {
|
|||||||
return "Anna" // de-DE
|
return "Anna" // de-DE
|
||||||
}
|
}
|
||||||
|
|
||||||
// synthSAPI erzeugt WAV über die Windows-SAPI (System.Speech) per
|
// synthSAPI produces WAV via the Windows SAPI (System.Speech) through
|
||||||
// PowerShell. Das Skript wird als -EncodedCommand (Base64/UTF-16LE)
|
// PowerShell. The script is passed as -EncodedCommand (Base64/UTF-16LE) and
|
||||||
// übergeben und der Text darin base64-dekodiert übergeben — dadurch gibt
|
// the text inside it is passed base64-decoded, so there is no quoting
|
||||||
// es kein Quoting-Problem mit Sonderzeichen. Ist die Wunschsprache nicht
|
// problem with special characters. If the requested language is not
|
||||||
// installiert, fällt SAPI auf die Systemstimme zurück (try/catch).
|
// installed, SAPI falls back to the system voice (try/catch).
|
||||||
func (OSBuiltin) synthSAPI(ctx context.Context, text, lang string) ([]byte, error) {
|
func (OSBuiltin) synthSAPI(ctx context.Context, text, lang string) ([]byte, error) {
|
||||||
if _, err := exec.LookPath("powershell"); err != nil {
|
if _, err := exec.LookPath("powershell"); err != nil {
|
||||||
return nil, fmt.Errorf("osbuiltin: powershell nicht gefunden: %w", err)
|
return nil, fmt.Errorf("osbuiltin: powershell not found: %w", err)
|
||||||
}
|
}
|
||||||
tmp, err := os.CreateTemp("", "talk-sapi-*.wav")
|
tmp, err := os.CreateTemp("", "talk-sapi-*.wav")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("osbuiltin: temporäre Datei: %w", err)
|
return nil, fmt.Errorf("osbuiltin: temporary file: %w", err)
|
||||||
}
|
}
|
||||||
name := tmp.Name()
|
name := tmp.Name()
|
||||||
tmp.Close()
|
tmp.Close()
|
||||||
@@ -214,16 +220,16 @@ $s.Dispose()
|
|||||||
|
|
||||||
cmd := exec.CommandContext(ctx, "powershell", "-NoProfile", "-STA", "-EncodedCommand", psEncode(script))
|
cmd := exec.CommandContext(ctx, "powershell", "-NoProfile", "-STA", "-EncodedCommand", psEncode(script))
|
||||||
if out, err := cmd.CombinedOutput(); err != nil {
|
if out, err := cmd.CombinedOutput(); err != nil {
|
||||||
return nil, fmt.Errorf("osbuiltin: SAPI fehlgeschlagen: %w: %s", err, bytes.TrimSpace(out))
|
return nil, fmt.Errorf("osbuiltin: SAPI failed: %w: %s", err, bytes.TrimSpace(out))
|
||||||
}
|
}
|
||||||
data, err := os.ReadFile(name)
|
data, err := os.ReadFile(name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("osbuiltin: SAPI-Ausgabe lesen: %w", err)
|
return nil, fmt.Errorf("osbuiltin: reading SAPI output: %w", err)
|
||||||
}
|
}
|
||||||
return data, nil
|
return data, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// sapiCulture mappt Sprachen auf SAPI-Kulturbezeichner.
|
// sapiCulture maps languages to SAPI culture identifiers.
|
||||||
func sapiCulture(lang string) string {
|
func sapiCulture(lang string) string {
|
||||||
if lang == "en" {
|
if lang == "en" {
|
||||||
return "en-US"
|
return "en-US"
|
||||||
@@ -231,7 +237,7 @@ func sapiCulture(lang string) string {
|
|||||||
return "de-DE"
|
return "de-DE"
|
||||||
}
|
}
|
||||||
|
|
||||||
// psEncode kodiert ein PowerShell-Skript für -EncodedCommand
|
// psEncode encodes a PowerShell script for -EncodedCommand
|
||||||
// (UTF-16LE + Base64).
|
// (UTF-16LE + Base64).
|
||||||
func psEncode(script string) string {
|
func psEncode(script string) string {
|
||||||
runes := utf16.Encode([]rune(script))
|
runes := utf16.Encode([]rune(script))
|
||||||
@@ -242,8 +248,8 @@ func psEncode(script string) string {
|
|||||||
return base64.StdEncoding.EncodeToString(buf)
|
return base64.StdEncoding.EncodeToString(buf)
|
||||||
}
|
}
|
||||||
|
|
||||||
// withStderr reichert einen exec-Fehler um die gesammelte stderr-Ausgabe
|
// withStderr enriches an exec error with the process's collected stderr
|
||||||
// des Prozesses an, wenn vorhanden.
|
// output, if any.
|
||||||
func withStderr(err error) error {
|
func withStderr(err error) error {
|
||||||
var exitErr *exec.ExitError
|
var exitErr *exec.ExitError
|
||||||
if errors.As(err, &exitErr) && len(exitErr.Stderr) > 0 {
|
if errors.As(err, &exitErr) && len(exitErr.Stderr) > 0 {
|
||||||
|
|||||||
@@ -10,9 +10,9 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
// fakeBin schreibt ein ausführbares Shell-Skript namens name in dir, das
|
// fakeBin writes an executable shell script called name into dir that runs
|
||||||
// body ausführt. Damit werden die externen Prozesse des Providers an der
|
// body. This fakes the provider's external processes at the real process
|
||||||
// echten Prozessgrenze gefaked (PATH-Manipulation, kein Mock-Framework).
|
// boundary (PATH manipulation, no mock framework).
|
||||||
func fakeBin(t *testing.T, dir, name, body string) {
|
func fakeBin(t *testing.T, dir, name, body string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
script := "#!/bin/sh\n" + body + "\n"
|
script := "#!/bin/sh\n" + body + "\n"
|
||||||
@@ -22,8 +22,8 @@ func fakeBin(t *testing.T, dir, name, body string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// emptyPATH setzt PATH auf ein Verzeichnis ohne einzige Binärdatei —
|
// emptyPATH sets PATH to a directory without a single binary: no espeak,
|
||||||
// kein espeak, kein spd-say.
|
// no spd-say.
|
||||||
func emptyPATH(t *testing.T) string {
|
func emptyPATH(t *testing.T) string {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
@@ -31,15 +31,15 @@ func emptyPATH(t *testing.T) string {
|
|||||||
return dir
|
return dir
|
||||||
}
|
}
|
||||||
|
|
||||||
// prependPATH stellt dir vor den bestehenden PATH: Binaries darin
|
// prependPATH puts dir in front of the existing PATH: binaries in it shadow
|
||||||
// überschatten System-Binaries gleichen Namens (fake espeak vor einem
|
// system binaries of the same name (fake espeak before a real one) while
|
||||||
// echten), während Hilfsprogramme wie cat weiterhin erreichbar bleiben.
|
// helpers such as cat stay reachable.
|
||||||
func prependPATH(t *testing.T, dir string) {
|
func prependPATH(t *testing.T, dir string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestOSBuiltinName und TestNewRegistry pinnen die Registry-Sicht.
|
// TestOSBuiltinName and TestNewRegistry pin the registry view.
|
||||||
func TestOSBuiltinName(t *testing.T) {
|
func TestOSBuiltinName(t *testing.T) {
|
||||||
if got := (OSBuiltin{}).Name(); got != "osbuiltin" {
|
if got := (OSBuiltin{}).Name(); got != "osbuiltin" {
|
||||||
t.Errorf("Name() = %q, want %q", got, "osbuiltin")
|
t.Errorf("Name() = %q, want %q", got, "osbuiltin")
|
||||||
@@ -56,7 +56,7 @@ func TestNewRegistry(t *testing.T) {
|
|||||||
t.Errorf("New(%q).Name() = %q", name, p.Name())
|
t.Errorf("New(%q).Name() = %q", name, p.Name())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Task 03: die Cloud-Provider stehen in der Registry.
|
// The cloud providers are in the registry.
|
||||||
for _, name := range []string{"elevenlabs", "openai", "edge"} {
|
for _, name := range []string{"elevenlabs", "openai", "edge"} {
|
||||||
p, err := New(name, ChainConfig{})
|
p, err := New(name, ChainConfig{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -66,38 +66,38 @@ func TestNewRegistry(t *testing.T) {
|
|||||||
t.Errorf("New(%q).Name() = %q", name, p.Name())
|
t.Errorf("New(%q).Name() = %q", name, p.Name())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if _, err := New("gibtsnicht", ChainConfig{}); err == nil {
|
if _, err := New("doesnotexist", ChainConfig{}); err == nil {
|
||||||
t.Error("New(\"gibtsnicht\") soll fehlschlagen")
|
t.Error("New(\"doesnotexist\") should fail")
|
||||||
} else if !strings.Contains(err.Error(), "osbuiltin") || !strings.Contains(err.Error(), "elevenlabs") {
|
} else if !strings.Contains(err.Error(), "osbuiltin") || !strings.Contains(err.Error(), "elevenlabs") {
|
||||||
t.Errorf("New-Fehler soll verfügbare Provider nennen: %v", err)
|
t.Errorf("New error should name the available providers: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestAvailableOhneTTS: leere PATH-Umgebung → Available false.
|
// TestAvailableWithoutTTS: empty PATH environment → Available false.
|
||||||
func TestAvailableOhneTTS(t *testing.T) {
|
func TestAvailableWithoutTTS(t *testing.T) {
|
||||||
emptyPATH(t)
|
emptyPATH(t)
|
||||||
if (OSBuiltin{}).Available(context.Background()) {
|
if (OSBuiltin{}).Available(context.Background()) {
|
||||||
t.Error("Available() = true ohne jedes TTS-Binary, want false")
|
t.Error("Available() = true without any TTS binary, want false")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSynthesizeOhneTTS: fehlt byte-fähiges TTS, muss der Fehler
|
// TestSynthesizeWithoutTTS: if byte-capable TTS is missing, the error must
|
||||||
// ErrNoByteOutput sein (kein Panik, kein anderer Fehlertyp).
|
// be ErrNoByteOutput (no panic, no other error type).
|
||||||
func TestSynthesizeOhneTTS(t *testing.T) {
|
func TestSynthesizeWithoutTTS(t *testing.T) {
|
||||||
emptyPATH(t)
|
emptyPATH(t)
|
||||||
_, err := (OSBuiltin{}).Synthesize(context.Background(), "Hallo", "de")
|
_, err := (OSBuiltin{}).Synthesize(context.Background(), "Hello", "de")
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Fatal("Synthesize ohne TTS: kein Fehler")
|
t.Fatal("Synthesize without TTS: no error")
|
||||||
}
|
}
|
||||||
if !errors.Is(err, ErrNoByteOutput) {
|
if !errors.Is(err, ErrNoByteOutput) {
|
||||||
t.Fatalf("Synthesize-Fehler = %v, want ErrNoByteOutput", err)
|
t.Fatalf("Synthesize error = %v, want ErrNoByteOutput", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSynthesizeMitFakeEspeak: ein gefaktes espeak liefert WAV-Bytes auf
|
// TestSynthesizeWithFakeEspeak: a faked espeak returns WAV bytes on stdout;
|
||||||
// stdout; Synthesize muss genau diese Bytes durchreichen und die Stimme
|
// Synthesize must pass exactly these bytes through and must have received
|
||||||
// (-v <lang>) sowie den Text übergeben bekommen haben.
|
// the voice (-v <lang>) and the text.
|
||||||
func TestSynthesizeMitFakeEspeak(t *testing.T) {
|
func TestSynthesizeWithFakeEspeak(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
wav := filepath.Join(dir, "probe.wav")
|
wav := filepath.Join(dir, "probe.wav")
|
||||||
if err := os.WriteFile(wav, minimalWAV, 0o644); err != nil {
|
if err := os.WriteFile(wav, minimalWAV, 0o644); err != nil {
|
||||||
@@ -108,95 +108,95 @@ func TestSynthesizeMitFakeEspeak(t *testing.T) {
|
|||||||
cat "`+wav+`"`)
|
cat "`+wav+`"`)
|
||||||
prependPATH(t, dir)
|
prependPATH(t, dir)
|
||||||
|
|
||||||
data, err := (OSBuiltin{}).Synthesize(context.Background(), "Hallo Welt", "de")
|
data, err := (OSBuiltin{}).Synthesize(context.Background(), "Hello world", "de")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Synthesize: %v", err)
|
t.Fatalf("Synthesize: %v", err)
|
||||||
}
|
}
|
||||||
if string(data) != string(minimalWAV) {
|
if string(data) != string(minimalWAV) {
|
||||||
t.Errorf("Synthesize lieferte %d Bytes, want die WAV-Bytes des Fake-espeak (%d)", len(data), len(minimalWAV))
|
t.Errorf("Synthesize returned %d bytes, want the WAV bytes of the fake espeak (%d)", len(data), len(minimalWAV))
|
||||||
}
|
}
|
||||||
args, err := os.ReadFile(seen)
|
args, err := os.ReadFile(seen)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Fake-espeak wurde nicht aufgerufen: %v", err)
|
t.Fatalf("fake espeak was not called: %v", err)
|
||||||
}
|
}
|
||||||
if got := string(args); got != "-v de --stdout Hallo Welt\n" {
|
if got := string(args); got != "-v de --stdout Hello world\n" {
|
||||||
t.Errorf("Fake-espeak ARGS = %q, want %q", got, "-v de --stdout Hallo Welt\n")
|
t.Errorf("fake espeak ARGS = %q, want %q", got, "-v de --stdout Hello world\n")
|
||||||
}
|
}
|
||||||
if !(OSBuiltin{}).Available(context.Background()) {
|
if !(OSBuiltin{}).Available(context.Background()) {
|
||||||
t.Error("Available() = false trotz espeak im PATH")
|
t.Error("Available() = false despite espeak in PATH")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSynthesizeLeererText ist ein klarer Fehler.
|
// TestSynthesizeEmptyText is a clear error.
|
||||||
func TestSynthesizeLeererText(t *testing.T) {
|
func TestSynthesizeEmptyText(t *testing.T) {
|
||||||
if _, err := (OSBuiltin{}).Synthesize(context.Background(), "", "de"); err == nil {
|
if _, err := (OSBuiltin{}).Synthesize(context.Background(), "", "de"); err == nil {
|
||||||
t.Error("Synthesize(\"\") soll fehlschlagen")
|
t.Error("Synthesize(\"\") should fail")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSynthesizeFehlgeschlagenesEspeak: espeak crasht (exit 1) → klarer
|
// TestSynthesizeFailingEspeak: espeak crashes (exit 1) → clear error, not
|
||||||
// Fehler, kein ErrNoByteOutput.
|
// ErrNoByteOutput.
|
||||||
func TestSynthesizeFehlgeschlagenesEspeak(t *testing.T) {
|
func TestSynthesizeFailingEspeak(t *testing.T) {
|
||||||
dir := emptyPATH(t)
|
dir := emptyPATH(t)
|
||||||
fakeBin(t, dir, "espeak", `echo "boom" >&2; exit 1`)
|
fakeBin(t, dir, "espeak", `echo "boom" >&2; exit 1`)
|
||||||
_, err := (OSBuiltin{}).Synthesize(context.Background(), "Hallo", "de")
|
_, err := (OSBuiltin{}).Synthesize(context.Background(), "Hello", "de")
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Fatal("Synthesize mit crashendem espeak: kein Fehler")
|
t.Fatal("Synthesize with crashing espeak: no error")
|
||||||
}
|
}
|
||||||
if errors.Is(err, ErrNoByteOutput) {
|
if errors.Is(err, ErrNoByteOutput) {
|
||||||
t.Errorf("Crashender espeak soll kein ErrNoByteOutput sein: %v", err)
|
t.Errorf("crashing espeak must not be ErrNoByteOutput: %v", err)
|
||||||
}
|
}
|
||||||
if !strings.Contains(err.Error(), "boom") {
|
if !strings.Contains(err.Error(), "boom") {
|
||||||
t.Errorf("Fehler soll stderr des Prozesses enthalten: %v", err)
|
t.Errorf("error should contain the process stderr: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSpeakDirectMitFakeSpdSay: SpeakDirect ruft spd-say blockierend
|
// TestSpeakDirectWithFakeSpdSay: SpeakDirect calls spd-say blocking (-w)
|
||||||
// (-w) mit Sprache (-l <lang>) und Text auf.
|
// with language (-l <lang>) and text.
|
||||||
func TestSpeakDirectMitFakeSpdSay(t *testing.T) {
|
func TestSpeakDirectWithFakeSpdSay(t *testing.T) {
|
||||||
dir := emptyPATH(t)
|
dir := emptyPATH(t)
|
||||||
seen := filepath.Join(dir, "seen.txt")
|
seen := filepath.Join(dir, "seen.txt")
|
||||||
fakeBin(t, dir, "spd-say", `printf '%s\n' "$*" > "`+seen+`"`)
|
fakeBin(t, dir, "spd-say", `printf '%s\n' "$*" > "`+seen+`"`)
|
||||||
prependPATH(t, dir)
|
prependPATH(t, dir)
|
||||||
|
|
||||||
if err := (OSBuiltin{}).SpeakDirect(context.Background(), "Hallo Welt", "de"); err != nil {
|
if err := (OSBuiltin{}).SpeakDirect(context.Background(), "Hello world", "de"); err != nil {
|
||||||
t.Fatalf("SpeakDirect: %v", err)
|
t.Fatalf("SpeakDirect: %v", err)
|
||||||
}
|
}
|
||||||
args, err := os.ReadFile(seen)
|
args, err := os.ReadFile(seen)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Fake-spd-say wurde nicht aufgerufen: %v", err)
|
t.Fatalf("fake spd-say was not called: %v", err)
|
||||||
}
|
}
|
||||||
if got := string(args); got != "-w -l de Hallo Welt\n" {
|
if got := string(args); got != "-w -l de Hello world\n" {
|
||||||
t.Errorf("Fake-spd-say ARGS = %q, want %q", got, "-w -l de Hallo Welt\n")
|
t.Errorf("fake spd-say ARGS = %q, want %q", got, "-w -l de Hello world\n")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSpeakDirectOhneSpdSay ist ein klarer Fehler.
|
// TestSpeakDirectWithoutSpdSay is a clear error.
|
||||||
func TestSpeakDirectOhneSpdSay(t *testing.T) {
|
func TestSpeakDirectWithoutSpdSay(t *testing.T) {
|
||||||
emptyPATH(t)
|
emptyPATH(t)
|
||||||
if err := (OSBuiltin{}).SpeakDirect(context.Background(), "Hallo", "de"); err == nil {
|
if err := (OSBuiltin{}).SpeakDirect(context.Background(), "Hello", "de"); err == nil {
|
||||||
t.Error("SpeakDirect ohne spd-say soll fehlschlagen")
|
t.Error("SpeakDirect without spd-say should fail")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSpeakDirectEchtesSpdSay läuft nur, wenn TALK_TEST_REAL_SPD=1 gesetzt
|
// TestSpeakDirectRealSpdSay runs only when TALK_TEST_REAL_SPD=1 is set (it
|
||||||
// ist (erzeugt echte, hörbare Ausgabe über speech-dispatcher — einmalige
|
// produces real, audible output through speech-dispatcher; one-off manual
|
||||||
// manuelle Abnahme; Standard-Testläufe bleiben stumm).
|
// acceptance, standard test runs stay silent).
|
||||||
func TestSpeakDirectEchtesSpdSay(t *testing.T) {
|
func TestSpeakDirectRealSpdSay(t *testing.T) {
|
||||||
if os.Getenv("TALK_TEST_REAL_SPD") != "1" {
|
if os.Getenv("TALK_TEST_REAL_SPD") != "1" {
|
||||||
t.Skip("Übersprungen (hörbar) — mit TALK_TEST_REAL_SPD=1 ausführen")
|
t.Skip("skipped (audible); run with TALK_TEST_REAL_SPD=1")
|
||||||
}
|
}
|
||||||
if _, err := exec.LookPath("spd-say"); err != nil {
|
if _, err := exec.LookPath("spd-say"); err != nil {
|
||||||
t.Skip("spd-say nicht installiert")
|
t.Skip("spd-say not installed")
|
||||||
}
|
}
|
||||||
if err := (OSBuiltin{}).SpeakDirect(context.Background(), "Sprachtest über speech dispatcher", "de"); err != nil {
|
if err := (OSBuiltin{}).SpeakDirect(context.Background(), "Speech test via speech dispatcher", "de"); err != nil {
|
||||||
t.Fatalf("SpeakDirect gegen echtes spd-say: %v", err)
|
t.Fatalf("SpeakDirect against real spd-say: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// minimalWAV ist eine minimal gültige RIFF/WAVE-Datei (PCM 16 Bit, mono,
|
// minimalWAV is a minimal valid RIFF/WAVE file (PCM 16 bit, mono, 8000 Hz)
|
||||||
// 8000 Hz) mit vier Samples — handgebaut nach der RIFF-Spezifikation,
|
// with four samples, hand-built per the RIFF specification, independent of
|
||||||
// unabhängig vom Parser im audio-Paket.
|
// the parser in the audio package.
|
||||||
var minimalWAV = []byte{
|
var minimalWAV = []byte{
|
||||||
'R', 'I', 'F', 'F', 44, 0, 0, 0, // ChunkSize = 4 + (8+16) + (8+8)
|
'R', 'I', 'F', 'F', 44, 0, 0, 0, // ChunkSize = 4 + (8+16) + (8+8)
|
||||||
'W', 'A', 'V', 'E',
|
'W', 'A', 'V', 'E',
|
||||||
@@ -208,5 +208,5 @@ var minimalWAV = []byte{
|
|||||||
2, 0, // BlockAlign
|
2, 0, // BlockAlign
|
||||||
16, 0, // Bits
|
16, 0, // Bits
|
||||||
'd', 'a', 't', 'a', 8, 0, 0, 0,
|
'd', 'a', 't', 'a', 8, 0, 0, 0,
|
||||||
0, 0, 0x10, 0x7F, 0xF0, 0x80, 0x00, 0x40, // 4 Samples
|
0, 0, 0x10, 0x7F, 0xF0, 0x80, 0x00, 0x40, // 4 samples
|
||||||
}
|
}
|
||||||
@@ -8,69 +8,68 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DefaultName ist der Provider, den New("") liefert (Einzelkonstruktion,
|
// DefaultName is the provider New("") returns (single construction, e.g.
|
||||||
// z. B. für doctor). Die Default-Ansage-Kette ab Task 03 steht in
|
// for doctor). The default announcement chain lives in DefaultOrder
|
||||||
// DefaultOrder (chain.go): elevenlabs → openai → edge → osbuiltin.
|
// (chain.go): elevenlabs → openai → edge → osbuiltin.
|
||||||
const DefaultName = "osbuiltin"
|
const DefaultName = "osbuiltin"
|
||||||
|
|
||||||
// ErrNoByteOutput meldet, dass die Plattform keine über Synthesize
|
// ErrNoByteOutput reports that the platform cannot provide audio bytes via
|
||||||
// beziehbaren Audio-Bytes liefern kann — konkret Linux mit speech-dispatcher
|
// Synthesize; concretely Linux with speech-dispatcher (spd-say) but without
|
||||||
// (spd-say) ohne espeak: spd-say kann Audio nur selbst über den Daemon
|
// espeak: spd-say can only play audio itself through the daemon, it cannot
|
||||||
// abspielen, nicht in einen Prozess schreiben. Aufrufer sollen auf
|
// write it to a process. Callers should fall back to DirectSpeaker (see
|
||||||
// DirectSpeaker ausweichen (siehe dort).
|
// there).
|
||||||
var ErrNoByteOutput = errors.New(
|
var ErrNoByteOutput = errors.New(
|
||||||
"diese Plattform kann keine Audio-Bytes liefern (Linux ohne espeak; spd-say spielt nur direkt)")
|
"this platform cannot provide audio bytes (Linux without espeak; spd-say only speaks directly)")
|
||||||
|
|
||||||
// Provider ist der Vertrag aller TTS-Backends von talk.
|
// Provider is the contract of all talk TTS backends.
|
||||||
//
|
//
|
||||||
// Synthesize liefert dekodierbare Audio-Bytes; das Format ist von der
|
// Synthesize returns decodable audio bytes; the format is documented by the
|
||||||
// Implementierung dokumentiert: osbuiltin liefert RIFF/WAVE (PCM), die
|
// implementation: osbuiltin returns RIFF/WAVE (PCM), the cloud providers
|
||||||
// Cloud-Provider elevenlabs, openai und edge liefern MP3 — beides wird vom
|
// elevenlabs, openai and edge return MP3. Both are understood by the audio
|
||||||
// audio-Paket (oto-Sink) verstanden.
|
// package (oto sink).
|
||||||
type Provider interface {
|
type Provider interface {
|
||||||
// Name liefert den eindeutigen Providernamen (CLI --provider, Config).
|
// Name returns the unique provider name (CLI --provider, config).
|
||||||
Name() string
|
Name() string
|
||||||
|
|
||||||
// Available meldet, ob der Provider auf diesem System überhaupt nutzbar
|
// Available reports whether the provider is usable on this system at all
|
||||||
// ist (z. B. Binary oder Key vorhanden). Muss billig und ohne Neben-
|
// (e.g. binary or key present). Must be cheap and side-effect free;
|
||||||
// wirkungen sein; false heißt: Kette soll überspringen werden.
|
// false means: the chain should skip this tier.
|
||||||
Available(ctx context.Context) bool
|
Available(ctx context.Context) bool
|
||||||
|
|
||||||
// Synthesize erzeugt Audio-Bytes für text in der Sprache lang.
|
// Synthesize produces audio bytes for text in language lang.
|
||||||
Synthesize(ctx context.Context, text, lang string) ([]byte, error)
|
Synthesize(ctx context.Context, text, lang string) ([]byte, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// DirectSpeaker ist eine dokumentierte optionale Erweiterung über das
|
// DirectSpeaker is a documented optional extension beyond the Provider
|
||||||
// Provider-Interface hinaus (kein Bestandteil des Basisvertrags): Provider,
|
// interface (not part of the base contract): providers that can make text
|
||||||
// die Text ohne Umweg über Synthesize-Bytes selbst hörbar ausgeben können.
|
// audible themselves without going through Synthesize bytes. Required on
|
||||||
// Notwendig auf Linux-Systemen, deren OS-TTS (speech-dispatcher) keine
|
// Linux systems whose OS TTS (speech-dispatcher) cannot hand audio bytes to
|
||||||
// Audio-Bytes an Prozesse liefern kann — dort spielt osbuiltin.SpeakDirect
|
// processes; there osbuiltin.SpeakDirect plays via spd-say itself (blocking
|
||||||
// über spd-say selbst ab (blockierend bis zum Ende der Ansage).
|
// until the announcement has finished).
|
||||||
//
|
//
|
||||||
// In der Kette (chain.go) ist SpeakDirect die letzte Stufe, wenn kein
|
// In the chain (chain.go) SpeakDirect is the last tier when no provider can
|
||||||
// Provider Bytes liefern kann; Chain implementiert DirectSpeaker selbst und
|
// deliver bytes; Chain implements DirectSpeaker itself and forwards to the
|
||||||
// reicht an den Stufen-Provider durch.
|
// tier provider.
|
||||||
type DirectSpeaker interface {
|
type DirectSpeaker interface {
|
||||||
// SpeakDirect gibt text in der Sprache lang direkt über das OS-TTS aus
|
// SpeakDirect speaks text in language lang directly through the OS TTS
|
||||||
// und blockiert bis zum Ende der Wiedergabe (oder bis ctx abgebrochen
|
// and blocks until playback has finished (or ctx is cancelled).
|
||||||
// wird).
|
|
||||||
SpeakDirect(ctx context.Context, text, lang string) error
|
SpeakDirect(ctx context.Context, text, lang string) error
|
||||||
}
|
}
|
||||||
|
|
||||||
// VoicePinner ist eine dokumentierte optionale Erweiterung über das
|
// VoicePinner is a documented optional extension beyond the Provider
|
||||||
// Provider-Interface hinaus: Provider, die eine explizite Voice-ID pinnen
|
// interface: providers that can pin an explicit voice ID (the CLI flag
|
||||||
// können (das CLI-Flag --voice). Die gepinnte Stimme schlägt das
|
// --voice). The pinned voice beats the voice.<provider>.<lang> mapping of
|
||||||
// voice.<provider>.<lang>-Mapping der config.toml und die eingebauten
|
// config.toml and the built-in neutral defaults. The chain calls PinVoice
|
||||||
// neutralen Defaults. Die Kette ruft PinVoice beim Bau auf alle Stufen auf,
|
// at construction on all tiers that implement the extension (tiers without
|
||||||
// die die Erweiterung implementieren (Stufen ohne Voice-Begriff, z. B.
|
// a notion of voice, e.g. osbuiltin, log a note instead of silently
|
||||||
// osbuiltin, loggen einen Hinweis statt still zu ignorieren).
|
// ignoring it).
|
||||||
type VoicePinner interface {
|
type VoicePinner interface {
|
||||||
PinVoice(id string)
|
PinVoice(id string)
|
||||||
}
|
}
|
||||||
|
|
||||||
// registry bildet Providernamen auf Konstruktoren; NewChain und New bauen
|
// registry maps provider names to constructors; NewChain and New build
|
||||||
// darüber. Die Konstruktoren erhalten die ChainConfig (Endpunkte, Voices,
|
// through it. The constructors receive the ChainConfig (endpoints, voices,
|
||||||
// Keys via Getenv), damit Kette und Daemon (Task 04) dieselbe Quelle haben.
|
// keys via Getenv) so that the chain and the daemon share one source.
|
||||||
var registry = map[string]func(ChainConfig) Provider{
|
var registry = map[string]func(ChainConfig) Provider{
|
||||||
"elevenlabs": func(cfg ChainConfig) Provider { return NewElevenLabs(cfg) },
|
"elevenlabs": func(cfg ChainConfig) Provider { return NewElevenLabs(cfg) },
|
||||||
"openai": func(cfg ChainConfig) Provider { return NewOpenAI(cfg) },
|
"openai": func(cfg ChainConfig) Provider { return NewOpenAI(cfg) },
|
||||||
@@ -78,7 +77,7 @@ var registry = map[string]func(ChainConfig) Provider{
|
|||||||
"osbuiltin": func(ChainConfig) Provider { return OSBuiltin{} },
|
"osbuiltin": func(ChainConfig) Provider { return OSBuiltin{} },
|
||||||
}
|
}
|
||||||
|
|
||||||
// Names liefert die registrierten Providernamen (sortiert).
|
// Names returns the registered provider names (sorted).
|
||||||
func Names() []string {
|
func Names() []string {
|
||||||
names := make([]string, 0, len(registry))
|
names := make([]string, 0, len(registry))
|
||||||
for name := range registry {
|
for name := range registry {
|
||||||
@@ -88,16 +87,16 @@ func Names() []string {
|
|||||||
return names
|
return names
|
||||||
}
|
}
|
||||||
|
|
||||||
// New liefert den Provider mit dem angegebenen Namen (Einzelkonstruktion);
|
// New returns the provider with the given name (single construction); ""
|
||||||
// "" wählt DefaultName. Für die Ansage-Kette (Fallback) NewChain verwenden.
|
// selects DefaultName. For the announcement chain (fallback) use NewChain.
|
||||||
// Unbekannte Namen sind ein klarer Fehler.
|
// Unknown names are a clear error.
|
||||||
func New(name string, cfg ChainConfig) (Provider, error) {
|
func New(name string, cfg ChainConfig) (Provider, error) {
|
||||||
if name == "" {
|
if name == "" {
|
||||||
name = DefaultName
|
name = DefaultName
|
||||||
}
|
}
|
||||||
ctor, ok := registry[name]
|
ctor, ok := registry[name]
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, fmt.Errorf("unbekannter oder noch nicht implementierter Provider %q (verfügbar: %s)",
|
return nil, fmt.Errorf("unknown provider %q (available: %s)",
|
||||||
name, strings.Join(Names(), ", "))
|
name, strings.Join(Names(), ", "))
|
||||||
}
|
}
|
||||||
if cfg.Getenv == nil {
|
if cfg.Getenv == nil {
|
||||||
|
|||||||
+21
-22
@@ -2,28 +2,27 @@ package provider
|
|||||||
|
|
||||||
import "sort"
|
import "sort"
|
||||||
|
|
||||||
// voiceDefaults sind die neutralen Repo-Defaults je Provider und Sprache
|
// voiceDefaults are the neutral repo defaults per provider and language
|
||||||
// (Teil des öffentlichen Vertrags: `talk voices` aus Task 08 listet sie,
|
// (part of the public contract: `talk voices` lists them; they are
|
||||||
// überschrieben werden sie durch voice.<provider>.<lang> in der config.toml
|
// overridden by voice.<provider>.<lang> in config.toml or the CLI flag
|
||||||
// oder das CLI-Flag --voice).
|
// --voice).
|
||||||
//
|
//
|
||||||
// Entscheidungsnotiz ElevenLabs-Stimme: Spec und Plan führen die persönliche
|
// Decision note on the ElevenLabs voice: spec and plan explicitly treat the
|
||||||
// Stimme KXxZd16DiBqt82nbarJx ausdrücklich als PRIVATEN Default des Nutzers
|
// personal voice KXxZd16DiBqt82nbarJx as the user's PRIVATE default ("not a
|
||||||
// („nicht Repo-Default", Spec Further Notes); der Repo-Default ist deshalb
|
// repo default", spec Further Notes); the repo default is therefore the
|
||||||
// die neutrale, mehrsprachige Standardstimme „Rachel" (21m00Tcm4TlvDq8ikWAM
|
// neutral, multilingual standard voice "Rachel" (21m00Tcm4TlvDq8ikWAM from
|
||||||
// aus dem öffentlichen ElevenLabs-Katalog). Die persönliche Stimme gehört in
|
// the public ElevenLabs catalog). The personal voice belongs in one's own
|
||||||
// die eigene config.toml:
|
// config.toml:
|
||||||
//
|
//
|
||||||
// [voice.elevenlabs]
|
// [voice.elevenlabs]
|
||||||
// de = "KXxZd16DiBqt82nbarJx"
|
// de = "KXxZd16DiBqt82nbarJx"
|
||||||
// en = "KXxZd16DiBqt82nbarJx"
|
// en = "KXxZd16DiBqt82nbarJx"
|
||||||
//
|
//
|
||||||
// OpenAI „alloy" und die Edge-Neural-Stimmen (de-DE-KatjaNeural,
|
// OpenAI "alloy" and the Edge neural voices (de-DE-KatjaNeural,
|
||||||
// en-US-AriaNeural) sind die jeweils neutralen Standardstimmen der APIs
|
// en-US-AriaNeural) are the respective neutral standard voices of the APIs.
|
||||||
// (Edge-Stimmen sind im Task-Brief vorgegeben).
|
|
||||||
var voiceDefaults = map[string]map[string]string{
|
var voiceDefaults = map[string]map[string]string{
|
||||||
"elevenlabs": {
|
"elevenlabs": {
|
||||||
"de": "21m00Tcm4TlvDq8ikWAM", // „Rachel", multilingual
|
"de": "21m00Tcm4TlvDq8ikWAM", // "Rachel", multilingual
|
||||||
"en": "21m00Tcm4TlvDq8ikWAM",
|
"en": "21m00Tcm4TlvDq8ikWAM",
|
||||||
},
|
},
|
||||||
"openai": {
|
"openai": {
|
||||||
@@ -35,19 +34,19 @@ var voiceDefaults = map[string]map[string]string{
|
|||||||
"en": "en-US-AriaNeural",
|
"en": "en-US-AriaNeural",
|
||||||
},
|
},
|
||||||
"osbuiltin": {
|
"osbuiltin": {
|
||||||
// osbuiltin mappt intern selbst (macOS Anna/Samantha, SAPI-Kultur,
|
// osbuiltin maps internally on its own (macOS Anna/Samantha, SAPI
|
||||||
// espeak -v <lang>) und kennt keine Voice-IDs — hier nur der
|
// culture, espeak -v <lang>) and has no voice IDs; documented here
|
||||||
// Vollständigkeit wegen dokumentiert.
|
// only for completeness.
|
||||||
"de": "",
|
"de": "",
|
||||||
"en": "",
|
"en": "",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
// resolveVoice liefert die Voice-ID für einen Provider und eine Sprache.
|
// resolveVoice returns the voice ID for a provider and a language.
|
||||||
// Rangfolge: override (CLI-Flag --voice bzw. PinVoice) > Mapping aus der
|
// Precedence: override (CLI flag --voice or PinVoice) > mapping from
|
||||||
// config.toml > neutrales Repo-Default > en-Default > alphabetisch erstes
|
// config.toml > neutral repo default > en default > alphabetically first
|
||||||
// Default. Ein leerer Rückgabewert heißt: der Provider kennt für diese
|
// default. An empty result means: the provider has no voice for this
|
||||||
// Sprache keine Stimme (osbuiltin) und entscheidet selbst.
|
// language (osbuiltin) and decides on its own.
|
||||||
func resolveVoice(name, lang, override string, cfgVoices map[string]string) string {
|
func resolveVoice(name, lang, override string, cfgVoices map[string]string) string {
|
||||||
if override != "" {
|
if override != "" {
|
||||||
return override
|
return override
|
||||||
|
|||||||
@@ -2,9 +2,9 @@ package provider
|
|||||||
|
|
||||||
import "testing"
|
import "testing"
|
||||||
|
|
||||||
// TestResolveVoiceRangfolge pinnt die dokumentierte Rangfolge
|
// TestResolveVoicePrecedence pins the documented precedence
|
||||||
// --voice-Pin > config-Mapping > Repo-Default > en-Default.
|
// --voice pin > config mapping > repo default > en default.
|
||||||
func TestResolveVoiceRangfolge(t *testing.T) {
|
func TestResolveVoicePrecedence(t *testing.T) {
|
||||||
cases := []struct {
|
cases := []struct {
|
||||||
name string
|
name string
|
||||||
provider string
|
provider string
|
||||||
@@ -13,14 +13,14 @@ func TestResolveVoiceRangfolge(t *testing.T) {
|
|||||||
cfg map[string]string
|
cfg map[string]string
|
||||||
want string
|
want string
|
||||||
}{
|
}{
|
||||||
{"Default edge de", "edge", "de", "", nil, "de-DE-KatjaNeural"},
|
{"default edge de", "edge", "de", "", nil, "de-DE-KatjaNeural"},
|
||||||
{"Default edge en", "edge", "en", "", nil, "en-US-AriaNeural"},
|
{"default edge en", "edge", "en", "", nil, "en-US-AriaNeural"},
|
||||||
{"Default elevenlabs de (neutral, nicht privat)", "elevenlabs", "de", "", nil, "21m00Tcm4TlvDq8ikWAM"},
|
{"default elevenlabs de (neutral, not private)", "elevenlabs", "de", "", nil, "21m00Tcm4TlvDq8ikWAM"},
|
||||||
{"Default openai en", "openai", "en", "", nil, "alloy"},
|
{"default openai en", "openai", "en", "", nil, "alloy"},
|
||||||
{"Mapping schlägt Default", "edge", "de", "", map[string]string{"de": "de-DE-ConradNeural"}, "de-DE-ConradNeural"},
|
{"mapping beats default", "edge", "de", "", map[string]string{"de": "de-DE-ConradNeural"}, "de-DE-ConradNeural"},
|
||||||
{"Pin schlägt Mapping", "edge", "de", "Gepinnt", map[string]string{"de": "de-DE-ConradNeural"}, "Gepinnt"},
|
{"pin beats mapping", "edge", "de", "Pinned", map[string]string{"de": "de-DE-ConradNeural"}, "Pinned"},
|
||||||
{"unbekannte Sprache → en-Default", "edge", "fr", "", nil, "en-US-AriaNeural"},
|
{"unknown language falls back to en default", "edge", "fr", "", nil, "en-US-AriaNeural"},
|
||||||
{"osbuiltin kennt keine Voice-IDs", "osbuiltin", "de", "", nil, ""},
|
{"osbuiltin has no voice IDs", "osbuiltin", "de", "", nil, ""},
|
||||||
}
|
}
|
||||||
for _, tc := range cases {
|
for _, tc := range cases {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
// Package queue implementiert die Ansage-Queue des Daemons: serialisierte
|
// Package queue is the daemon's announcement queue: serialized playback (one
|
||||||
// Abarbeitung (eine Ansage gleichzeitig), Prioritäten (high > normal > low,
|
// announcement at a time), priorities (high > normal > low, FIFO per level),
|
||||||
// FIFO je Level), now-Items springen vor, dazu den persistenten Mute-State
|
// now items that jump ahead, plus the persistent mute state (file "mute" in
|
||||||
// (Datei mute im Config-Dir). Seit Task 05 unter dem Anti-Spam-Gesetz
|
// the config directory). The anti-spam laws (rate.go, quiet.go) sit on top:
|
||||||
// (rate.go/quiet.go): Rate-Limit — jede gestartete Ansage bucht das Fenster;
|
// a rate limit where every started announcement books the window (low over
|
||||||
// low über dem Budget verfällt, normal parkt bis zum Slot, high darf mit
|
// budget is discarded, normal parks until the slot, high may break it with
|
||||||
// Burst-Recht verstoßen — und Ruhezeiten, die still verwerfen oder durch
|
// burst rights), quiet hours that discard silently or toast instead, a text
|
||||||
// einen Toast ersetzen. now:true bricht bewusst aus beiden aus.
|
// length cap and a maximum queue age. now:true deliberately breaks out of
|
||||||
|
// all of them.
|
||||||
package queue
|
package queue
|
||||||
+50
-50
@@ -6,9 +6,9 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestTruncateText: Kürzung auf max Runen an einer Wortgrenze (nicht in der
|
// TestTruncateText: cut to max runes at a word boundary (not in the first
|
||||||
// ersten Hälfte), ohne hängende Satzzeichen; kurze Texte und max 0 bleiben
|
// half), without dangling punctuation; short texts and max 0 stay untouched;
|
||||||
// unangetastet; Runen zählen, nicht Bytes.
|
// runes count, not bytes.
|
||||||
func TestTruncateText(t *testing.T) {
|
func TestTruncateText(t *testing.T) {
|
||||||
cases := []struct {
|
cases := []struct {
|
||||||
name string
|
name string
|
||||||
@@ -17,13 +17,13 @@ func TestTruncateText(t *testing.T) {
|
|||||||
want string
|
want string
|
||||||
truncated bool
|
truncated bool
|
||||||
}{
|
}{
|
||||||
{"kurz bleibt", "Build fertig", 400, "Build fertig", false},
|
{"short stays", "Build done", 400, "Build done", false},
|
||||||
{"genau max bleibt", "abcde", 5, "abcde", false},
|
{"exactly max stays", "abcde", 5, "abcde", false},
|
||||||
{"unbegrenzt", strings.Repeat("x", 1000), 0, strings.Repeat("x", 1000), false},
|
{"unlimited", strings.Repeat("x", 1000), 0, strings.Repeat("x", 1000), false},
|
||||||
{"wortgrenze", "Der Build ist fertig und bereit", 14, "Der Build ist", true},
|
{"word boundary", "The build is done and ready", 14, "The build is", true},
|
||||||
{"satzzeichen weg", "Fertig, aber dann kam noch mehr", 8, "Fertig", true},
|
{"punctuation dropped", "Done, but then there was more", 6, "Done", true},
|
||||||
{"keine wortgrenze in zweiter hälfte → hart", "abcdefghijklmnop qrs", 10, "abcdefghij", true},
|
{"no boundary in second half → hard cut", "abcdefghijklmnop qrs", 10, "abcdefghij", true},
|
||||||
{"umlaute als eine rune", "Übergröße ärgert", 9, "Übergröße", true},
|
{"umlauts count as one rune", "Übergröße ärgert", 9, "Übergröße", true},
|
||||||
}
|
}
|
||||||
for _, c := range cases {
|
for _, c := range cases {
|
||||||
t.Run(c.name, func(t *testing.T) {
|
t.Run(c.name, func(t *testing.T) {
|
||||||
@@ -32,83 +32,83 @@ func TestTruncateText(t *testing.T) {
|
|||||||
t.Errorf("truncateText(%q, %d) = %q/%v, want %q/%v", c.in, c.max, got, tr, c.want, c.truncated)
|
t.Errorf("truncateText(%q, %d) = %q/%v, want %q/%v", c.in, c.max, got, tr, c.want, c.truncated)
|
||||||
}
|
}
|
||||||
if c.max > 0 && len([]rune(got)) > c.max {
|
if c.max > 0 && len([]rune(got)) > c.max {
|
||||||
t.Errorf("Ergebnis %q länger als %d Runen", got, c.max)
|
t.Errorf("result %q longer than %d runes", got, c.max)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestEnqueueKuerztText: Das Gesetz MaxText greift beim Eintritt — die
|
// TestEnqueueTruncatesText: the MaxText law applies on admission; the
|
||||||
// gekürzte Fassung wird gesprochen, Admission meldet Truncated.
|
// shortened version is spoken and Admission reports Truncated.
|
||||||
func TestEnqueueKuerztText(t *testing.T) {
|
func TestEnqueueTruncatesText(t *testing.T) {
|
||||||
g := neueSpielerin()
|
g := newSpeaker()
|
||||||
q := New(Laws{MaxText: 20}, g.speak, nil)
|
q := New(Laws{MaxText: 20}, g.speak, nil)
|
||||||
defer q.Close()
|
defer q.Close()
|
||||||
|
|
||||||
adm, err := q.Enqueue(Item{Text: "Dieser Text ist deutlich länger als zwanzig Zeichen"})
|
adm, err := q.Enqueue(Item{Text: "This text is clearly longer than twenty characters"})
|
||||||
if err != nil || adm.ID == "" || !adm.Truncated {
|
if err != nil || adm.ID == "" || !adm.Truncated {
|
||||||
t.Fatalf("Enqueue = %+v, %v; want aufgenommen + Truncated", adm, err)
|
t.Fatalf("Enqueue = %+v, %v; want admitted + Truncated", adm, err)
|
||||||
}
|
}
|
||||||
items := g.warteBis(t, 1)
|
items := g.waitUntil(t, 1)
|
||||||
if items[0].Text != "Dieser Text ist" {
|
if items[0].Text != "This text is clearly" {
|
||||||
t.Errorf("gesprochen = %q, want gekürzte Fassung", items[0].Text)
|
t.Errorf("spoken = %q, want the shortened version", items[0].Text)
|
||||||
}
|
}
|
||||||
g.step <- struct{}{}
|
g.step <- struct{}{}
|
||||||
|
|
||||||
adm, _ = q.Enqueue(Item{Text: "kurz"})
|
adm, _ = q.Enqueue(Item{Text: "short"})
|
||||||
if adm.Truncated {
|
if adm.Truncated {
|
||||||
t.Error("kurzer Text als gekürzt gemeldet")
|
t.Error("short text reported as truncated")
|
||||||
}
|
}
|
||||||
g.warteBis(t, 2)
|
g.waitUntil(t, 2)
|
||||||
g.step <- struct{}{}
|
g.step <- struct{}{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestDecideExpired: Ein Item, das länger als MaxAge gewartet hat, wird
|
// TestDecideExpired: an item that waited longer than MaxAge is discarded,
|
||||||
// verworfen — vor Ruhezeit und Rate-Limit, aber nach now (now bricht aus).
|
// before quiet hours and rate limit but after now (now breaks out).
|
||||||
func TestDecideExpired(t *testing.T) {
|
func TestDecideExpired(t *testing.T) {
|
||||||
laws := Laws{MaxAge: time.Minute, RateLimit: time.Hour}
|
laws := Laws{MaxAge: time.Minute, RateLimit: time.Hour}
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
alt := Item{Text: "alt", Priority: PriorityNormal, enqueued: now.Add(-2 * time.Minute)}
|
old := Item{Text: "old", Priority: PriorityNormal, enqueued: now.Add(-2 * time.Minute)}
|
||||||
frisch := Item{Text: "frisch", Priority: PriorityNormal, enqueued: now.Add(-10 * time.Second)}
|
fresh := Item{Text: "fresh", Priority: PriorityNormal, enqueued: now.Add(-10 * time.Second)}
|
||||||
|
|
||||||
if v := laws.decide(alt, now, true); v != verdictDiscardExpired {
|
if v := laws.decide(old, now, true); v != verdictDiscardExpired {
|
||||||
t.Errorf("altes Item bei freiem Slot = %v, want verdictDiscardExpired", v)
|
t.Errorf("old item with open slot = %v, want verdictDiscardExpired", v)
|
||||||
}
|
}
|
||||||
if v := laws.decide(frisch, now, true); v != verdictPlay {
|
if v := laws.decide(fresh, now, true); v != verdictPlay {
|
||||||
t.Errorf("frisches Item bei freiem Slot = %v, want verdictPlay", v)
|
t.Errorf("fresh item with open slot = %v, want verdictPlay", v)
|
||||||
}
|
}
|
||||||
if v := laws.decide(frisch, now, false); v != verdictWait {
|
if v := laws.decide(fresh, now, false); v != verdictWait {
|
||||||
t.Errorf("frisches Item ohne Slot = %v, want verdictWait", v)
|
t.Errorf("fresh item without slot = %v, want verdictWait", v)
|
||||||
}
|
}
|
||||||
altNow := alt
|
oldNow := old
|
||||||
altNow.Now = true
|
oldNow.Now = true
|
||||||
if v := laws.decide(altNow, now, false); v != verdictPlay {
|
if v := laws.decide(oldNow, now, false); v != verdictPlay {
|
||||||
t.Errorf("altes now-Item = %v, want verdictPlay (now bricht aus)", v)
|
t.Errorf("old now item = %v, want verdictPlay (now breaks out)", v)
|
||||||
}
|
}
|
||||||
if v := (Laws{}).decide(alt, now, true); v != verdictPlay {
|
if v := (Laws{}).decide(old, now, true); v != verdictPlay {
|
||||||
t.Errorf("MaxAge 0 (unbegrenzt) verwirft altes Item: %v", v)
|
t.Errorf("MaxAge 0 (unlimited) discards old item: %v", v)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestGeparktesItemVerfaellt: Ein normal-Item parkt auf den Rate-Limit-Slot;
|
// TestParkedItemExpires: a normal item parks for the rate-limit slot; if it
|
||||||
// ist es beim Fälligwerden älter als MaxAge, wird es verworfen (Protokoll
|
// is older than MaxAge when it comes due, it is discarded (log names
|
||||||
// nennt max_age) und nicht mehr gesprochen.
|
// max_age) and never spoken.
|
||||||
func TestGeparktesItemVerfaellt(t *testing.T) {
|
func TestParkedItemExpires(t *testing.T) {
|
||||||
logb := &syncLog{}
|
logb := &syncLog{}
|
||||||
g := neueSpielerin()
|
g := newSpeaker()
|
||||||
q := New(Laws{RateLimit: 300 * time.Millisecond, MaxAge: 150 * time.Millisecond}, g.speak, logb)
|
q := New(Laws{RateLimit: 300 * time.Millisecond, MaxAge: 150 * time.Millisecond}, g.speak, logb)
|
||||||
defer q.Close()
|
defer q.Close()
|
||||||
|
|
||||||
q.Enqueue(Item{Text: "erste"}) // bucht das Fenster
|
q.Enqueue(Item{Text: "first"}) // books the window
|
||||||
g.warteBis(t, 1)
|
g.waitUntil(t, 1)
|
||||||
g.step <- struct{}{}
|
g.step <- struct{}{}
|
||||||
adm, _ := q.Enqueue(Item{Text: "parkt zu lange"}) // parkt ~300 ms > MaxAge
|
adm, _ := q.Enqueue(Item{Text: "parks too long"}) // parks ~300 ms > MaxAge
|
||||||
if adm.ID == "" || adm.Discarded != "" {
|
if adm.ID == "" || adm.Discarded != "" {
|
||||||
t.Fatalf("beim Eintritt darf nichts verfallen: %+v", adm)
|
t.Fatalf("nothing may expire on admission: %+v", adm)
|
||||||
}
|
}
|
||||||
waitFor(t, func() bool { return strings.Contains(logb.String(), "max_age") })
|
waitFor(t, func() bool { return strings.Contains(logb.String(), "max_age") })
|
||||||
g.keineWeitere(t)
|
g.noFurther(t)
|
||||||
if !strings.Contains(logb.String(), adm.ID) {
|
if !strings.Contains(logb.String(), adm.ID) {
|
||||||
t.Errorf("Protokoll nennt die verfallene Ansage nicht:\n%s", logb.String())
|
t.Errorf("log does not name the expired announcement:\n%s", logb.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+16
-20
@@ -7,31 +7,27 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// MuteFileName ist der Name der Mute-Datei im Config-Verzeichnis (bindender
|
// MuteFileName is the mute file's name inside the config directory.
|
||||||
// Vertrag: „persistenten Mute-State toggeln (Datei mute im Config-Dir)").
|
|
||||||
const MuteFileName = "mute"
|
const MuteFileName = "mute"
|
||||||
|
|
||||||
// ErrNoMutePath meldet einen Set-Versuch ohne konfigurierten Datei-Pfad
|
// ErrNoMutePath reports a Set attempt without a configured file path (config
|
||||||
// (Config-Dir nicht bestimmbar — der Daemon deaktiviert dann Mute mit einer
|
// directory unknown; the daemon then runs without mute and warns at start).
|
||||||
// Start-Warnung statt zu scheitern).
|
var ErrNoMutePath = errors.New("mute: no file path configured (config directory unknown)")
|
||||||
var ErrNoMutePath = errors.New("mute: kein Datei-Pfad konfiguriert (Config-Dir nicht bestimmbar)")
|
|
||||||
|
|
||||||
// MuteStore verwaltet den persistenten Mute-State als Datei im
|
// MuteStore manages the persistent mute state as a file in the config
|
||||||
// Config-Verzeichnis: Inhalt „true" = stumm, alles andere (oder keine Datei)
|
// directory: content "true" = muted, anything else (or no file) = not muted.
|
||||||
// = nicht stumm.
|
|
||||||
//
|
//
|
||||||
// Der Daemon liest die Datei bei jeder /speak-Anfrage neu — dadurch wirkt
|
// The daemon re-reads the file on every /speak request, so a state written
|
||||||
// auch ein im Degraded Mode (Daemon tot) von der CLI direkt geschriebener
|
// by the CLI while no daemon runs takes effect immediately, and the state
|
||||||
// State sofort, und der Zustand überlebt Daemon-Restarts.
|
// survives daemon restarts.
|
||||||
type MuteStore struct {
|
type MuteStore struct {
|
||||||
// Path ist der vollständige Pfad der Mute-Datei. Leer (kein Config-Dir
|
// Path is the mute file's full path. Empty (no config directory): Muted
|
||||||
// bestimmbar): Muted() ist immer false, Set ein Fehler.
|
// is always false and Set an error.
|
||||||
Path string
|
Path string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Muted meldet den persistenten Mute-State. Eine fehlende oder unlesbare
|
// Muted reports the persistent mute state. A missing or unreadable file
|
||||||
// Datei heißt: nicht stumm (Fehlstart ohne Config-Dir wird nie „stumm aus
|
// means not muted: a broken setup must never be "accidentally silent".
|
||||||
// Versehen").
|
|
||||||
func (s MuteStore) Muted() bool {
|
func (s MuteStore) Muted() bool {
|
||||||
if s.Path == "" {
|
if s.Path == "" {
|
||||||
return false
|
return false
|
||||||
@@ -43,9 +39,9 @@ func (s MuteStore) Muted() bool {
|
|||||||
return strings.TrimSpace(string(b)) == "true"
|
return strings.TrimSpace(string(b)) == "true"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set schreibt den Mute-State atomar (temporäre Datei + Rename, damit
|
// Set writes the mute state atomically (temp file + rename, so daemon and
|
||||||
// Daemon und CLI nie eine halb geschriebene Datei lesen) und legt das
|
// CLI never read a half-written file) and creates the config directory if
|
||||||
// Config-Verzeichnis bei Bedarf an.
|
// needed.
|
||||||
func (s MuteStore) Set(muted bool) error {
|
func (s MuteStore) Set(muted bool) error {
|
||||||
if s.Path == "" {
|
if s.Path == "" {
|
||||||
return ErrNoMutePath
|
return ErrNoMutePath
|
||||||
|
|||||||
+135
-128
@@ -12,18 +12,18 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Priority eines Queue-Items — öffentlicher Vertrag der HTTP-API
|
// Priority of a queue item; public contract of the HTTP API
|
||||||
// (low | normal | high; leer wird als normal behandelt).
|
// (low | normal | high; empty is treated as normal).
|
||||||
type Priority string
|
type Priority string
|
||||||
|
|
||||||
// Erlaubte Prioritäts-Werte (Spec: high > normal > low, FIFO je Level).
|
// Allowed priority values (high > normal > low, FIFO per level).
|
||||||
const (
|
const (
|
||||||
PriorityLow Priority = "low"
|
PriorityLow Priority = "low"
|
||||||
PriorityNormal Priority = "normal"
|
PriorityNormal Priority = "normal"
|
||||||
PriorityHigh Priority = "high"
|
PriorityHigh Priority = "high"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Valid meldet, ob p ein erlaubter Prioritäts-Wert ist.
|
// Valid reports whether p is an allowed priority value.
|
||||||
func (p Priority) Valid() bool {
|
func (p Priority) Valid() bool {
|
||||||
switch p {
|
switch p {
|
||||||
case PriorityLow, PriorityNormal, PriorityHigh:
|
case PriorityLow, PriorityNormal, PriorityHigh:
|
||||||
@@ -33,43 +33,42 @@ func (p Priority) Valid() bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ErrClosed meldet einen Enqueue-Versuch nach Close (Daemon fährt herunter).
|
// ErrClosed reports an Enqueue attempt after Close (daemon shutting down).
|
||||||
var ErrClosed = errors.New("queue: bereits geschlossen")
|
var ErrClosed = errors.New("queue: already closed")
|
||||||
|
|
||||||
// Item ist eine Ansage in der Warteschlange. Alle Felder kommen aus der
|
// Item is an announcement in the queue. All fields come from the HTTP API
|
||||||
// HTTP-API (POST /speak); ID und Ablauf-Verwaltung liegen bei der Queue.
|
// (POST /speak); ID and lifecycle belong to the queue.
|
||||||
type Item struct {
|
type Item struct {
|
||||||
// ID ist die kurze Ansage-Kennung (Antwort von POST /speak; Grundlage
|
// ID is the short announcement identifier (returned by POST /speak; the
|
||||||
// des --wait-Pollings der CLI). Wird von Enqueue vergeben, wenn leer.
|
// CLI polls it for --wait). Assigned by Enqueue when empty.
|
||||||
ID string
|
ID string
|
||||||
|
|
||||||
// Text ist der Ansage-Text.
|
// Text is the announcement text.
|
||||||
Text string
|
Text string
|
||||||
|
|
||||||
// Lang ist die Sprach-Pin (de | en); leer = automatische Erkennung
|
// Lang pins the language (de | en); empty = detected by the daemon.
|
||||||
// durch den Daemon (langdetect).
|
|
||||||
Lang string
|
Lang string
|
||||||
|
|
||||||
// Provider pinnt die Provider-Kette auf eine Stufe (--provider); leer
|
// Provider pins the chain to one tier (--provider); empty = the
|
||||||
// = konfigurierte Default-Kette.
|
// configured default chain.
|
||||||
Provider string
|
Provider string
|
||||||
|
|
||||||
// Voice pinnt eine Voice-ID (--voice); leer = Voice-Mapping/Defaults.
|
// Voice pins a voice ID (--voice); empty = voice mapping/defaults.
|
||||||
Voice string
|
Voice string
|
||||||
|
|
||||||
// Priority steuert die Abarbeitungs-Reihenfolge (high > normal > low,
|
// Priority controls processing order (high > normal > low, FIFO per
|
||||||
// FIFO je Level).
|
// level).
|
||||||
Priority Priority
|
Priority Priority
|
||||||
|
|
||||||
// Now lässt die Ansage vor alle wartenden Items springen (auch vor
|
// Now lets the announcement jump ahead of every waiting item (including
|
||||||
// high) — sie unterbricht aber nie die laufende Ansage.
|
// high); it never interrupts the announcement that is playing.
|
||||||
Now bool
|
Now bool
|
||||||
|
|
||||||
seq uint64 // Enqueue-Reihenfolge: FIFO-Tiebrecher innerhalb eines Levels
|
seq uint64 // enqueue order: FIFO tiebreaker within a level
|
||||||
enqueued time.Time // Eintrittszeit (Basis für Laws.MaxAge)
|
enqueued time.Time // admission time (basis for Laws.MaxAge)
|
||||||
}
|
}
|
||||||
|
|
||||||
// rank liefert die Abarbeitungs-Klasse: now über high über normal über low.
|
// rank returns the processing class: now over high over normal over low.
|
||||||
func (it Item) rank() int {
|
func (it Item) rank() int {
|
||||||
if it.Now {
|
if it.Now {
|
||||||
return 3
|
return 3
|
||||||
@@ -84,56 +83,53 @@ func (it Item) rank() int {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Speaker spielt ein Item ab. Im Daemon: Provider-Kette bauen und Speak
|
// Speaker plays an item. In the daemon: build the provider chain and call
|
||||||
// aufrufen (Synthese mit Fallback + Wiedergabe über den Audio-Sink — die
|
// Speak (synthesis with fallback plus playback through the audio sink). ctx
|
||||||
// Kette aus internal/provider wird unverändert wiederverwendet). ctx wird
|
// is cancelled when the announcement is cancelled (POST /cancel) or the
|
||||||
// abgebrochen, wenn die Ansage abgebrochen (POST /cancel) oder der Daemon
|
// daemon shuts down; the chain then aborts its network and process work.
|
||||||
// heruntergefahren wird; die Kette bricht ihre Netz- und Prozess-Arbeit
|
// The returned error is logged, never passed to the API.
|
||||||
// dann ab. Der Rückgabe-Fehler wird protokolliert, nie an die API gereicht.
|
|
||||||
type Speaker func(ctx context.Context, item Item) error
|
type Speaker func(ctx context.Context, item Item) error
|
||||||
|
|
||||||
// Queue ist die serialisierte Ansage-Queue des Daemons: genau eine Ansage
|
// Queue is the daemon's serialized announcement queue: exactly one
|
||||||
// gleichzeitig, Reihenfolge now > high > normal > low (FIFO je Level) —
|
// announcement at a time, order now > high > normal > low (FIFO per level),
|
||||||
// seit Task 05 unter dem Anti-Spam-Gesetz (Laws): normal parkt bis zum
|
// under the anti-spam laws: normal parks until the rate-limit slot, low
|
||||||
// Rate-Limit-Slot, low wird über dem Budget verworfen, high darf mit
|
// over budget is discarded, high may break the limit with burst rights, now
|
||||||
// Burst-Recht verstoßen, now bricht bewusst aus, und Ruhezeiten verwerfen
|
// deliberately breaks out, quiet hours discard or toast instead of audio,
|
||||||
// bzw. toasten statt Audio.
|
// stale items expire.
|
||||||
//
|
//
|
||||||
// Die Synchronisation ist bewusst simpel und offensichtlich korrekt statt
|
// Synchronization is deliberately simple and obviously correct rather than
|
||||||
// clever: EIN Mutex + EIN Cond schützen alles (Items, aktuelles Item,
|
// clever: ONE mutex and ONE cond protect everything (items, current item,
|
||||||
// Closed-Flag, cancelCur, Slot-Wecker). Der Worker ist der einzige, der
|
// closed flag, cancelCur, slot timer). The worker is the only one taking
|
||||||
// Items entnimmt; take und das Setzen von current/cancelCur geschehen unter
|
// items; take and setting current/cancelCur happen under the same lock, so
|
||||||
// demselben Lock, damit ein Item nie zwischen „wartet" und „läuft" der
|
// an item can never slip past cancellation between "waiting" and "playing".
|
||||||
// Cancelierung entwischen kann. Cancel/Close rufen cancelCur unter dem Lock
|
// Cancel/Close call cancelCur under the lock; the worker notices via ctx in
|
||||||
// ab — der Worker bemerkt die Abbrechung in seiner speak-Funktion über ctx.
|
// its speak function. Parked items stay in the queue; a slot timer
|
||||||
// Geparkte Items bleiben in der Warteschlange liegen; ein Slot-Wecker
|
// (armWakeLocked) broadcasts when the window elapses so the worker wakes
|
||||||
// (armWakeLocked) broadcastet zum Fenster-Ablauf, damit der Worker auch ohne
|
// without a new Enqueue. The wait condition re-evaluates the laws every
|
||||||
// neuen Enqueue aufwacht — die Wait-Bedingung prüft jedes Mal die Gesetze
|
// time, so lost signals are harmless.
|
||||||
// neu, verlorene Signale sind dadurch harmlos.
|
|
||||||
type Queue struct {
|
type Queue struct {
|
||||||
laws Laws
|
laws Laws
|
||||||
limit *RateLimiter
|
limit *RateLimiter
|
||||||
speak Speaker
|
speak Speaker
|
||||||
log io.Writer
|
log io.Writer
|
||||||
toast func(Item) // Ruhezeit-Toast (optional; gesetzt vor dem ersten Enqueue)
|
toast func(Item) // quiet-hours toast (optional; set before the first Enqueue)
|
||||||
|
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
notEmpty *sync.Cond // Signal: neues Item; Broadcast: Close/Slot frei
|
notEmpty *sync.Cond // Signal: new item; Broadcast: Close / slot open
|
||||||
items []Item
|
items []Item
|
||||||
current *Item
|
current *Item
|
||||||
cancelCur context.CancelFunc
|
cancelCur context.CancelFunc
|
||||||
seq uint64
|
seq uint64
|
||||||
closed bool
|
closed bool
|
||||||
wake *time.Timer // weckt den geparkten Worker zum Slot-Termin
|
wake *time.Timer // wakes the parked worker at the slot time
|
||||||
wakeAt time.Time // Termin des laufenden Weckers
|
wakeAt time.Time // time of the armed timer
|
||||||
done chan struct{} // geschlossen, wenn der Worker-Loop endet
|
done chan struct{} // closed when the worker loop ends
|
||||||
}
|
}
|
||||||
|
|
||||||
// New startet die Queue mit ihrem Worker-Loop (eine Ansage gleichzeitig).
|
// New starts the queue with its worker loop (one announcement at a time).
|
||||||
// laws trägt die Anti-Spam-Gesetze (Nullwert = alles erlaubt; der Daemon
|
// laws carries the anti-spam laws (zero value = everything allowed; the
|
||||||
// liefert die Config-Gesetze). log ist optional (nil = still) und empfängt
|
// daemon supplies the configured laws). log is optional (nil = silent) and
|
||||||
// die Lebenslauf-Zeilen der Items. Close beendet den Loop und wartet auf
|
// receives the items' lifecycle lines. Close ends the loop and waits for it.
|
||||||
// sein Ende.
|
|
||||||
func New(laws Laws, speak Speaker, log io.Writer) *Queue {
|
func New(laws Laws, speak Speaker, log io.Writer) *Queue {
|
||||||
q := &Queue{
|
q := &Queue{
|
||||||
laws: laws,
|
laws: laws,
|
||||||
@@ -147,24 +143,24 @@ func New(laws Laws, speak Speaker, log io.Writer) *Queue {
|
|||||||
return q
|
return q
|
||||||
}
|
}
|
||||||
|
|
||||||
// OnToast setzt die Benachrichtigung, die in der Ruhezeit mit quiet_mode =
|
// OnToast sets the notification fired during quiet hours with quiet_mode =
|
||||||
// "toast" statt Audio ausgelöst wird (Daemon: Desktop-Notification). Ohne
|
// "toast" instead of audio (daemon: desktop notification). Unset, only the
|
||||||
// Setzen bleibt es bei der Protokollzeile. Vor dem ersten Enqueue setzen.
|
// log line remains. Set it before the first Enqueue.
|
||||||
func (q *Queue) OnToast(fn func(Item)) { q.toast = fn }
|
func (q *Queue) OnToast(fn func(Item)) { q.toast = fn }
|
||||||
|
|
||||||
// fireToast ruft die Toast-Benachrichtigung auf (nie unter dem Mutex).
|
// fireToast calls the toast hook (never under the mutex).
|
||||||
func (q *Queue) fireToast(item Item) {
|
func (q *Queue) fireToast(item Item) {
|
||||||
if q.toast != nil {
|
if q.toast != nil {
|
||||||
q.toast(item)
|
q.toast(item)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Enqueue stellt item in die Warteschlange und liefert die Aufnahme-
|
// Enqueue puts item into the queue and returns the admission decision:
|
||||||
// Entscheidung: Aufgenommene tragen ihre ID (bei leerer ID neu vergeben:
|
// admitted items carry their ID (assigned when empty: short and random).
|
||||||
// kurz und zufällig). Ruhezeit-Verwurf/Toast und low über dem Fenster-Budget
|
// Quiet-hours discard/toast and low over the window budget are decided on
|
||||||
// werden schon beim Eintritt entschieden (die 202-Antwort von POST /speak
|
// admission (the 202 response of POST /speak names the reason); everything
|
||||||
// nennt den Grund); alles andere entscheidet der Worker, wenn das Item
|
// else is decided by the worker when the item comes due. After Close,
|
||||||
// fällig ist. Nach Close ist Enqueue ein Fehler.
|
// Enqueue is an error.
|
||||||
func (q *Queue) Enqueue(item Item) (Admission, error) {
|
func (q *Queue) Enqueue(item Item) (Admission, error) {
|
||||||
q.mu.Lock()
|
q.mu.Lock()
|
||||||
if q.closed {
|
if q.closed {
|
||||||
@@ -176,24 +172,24 @@ func (q *Queue) Enqueue(item Item) (Admission, error) {
|
|||||||
}
|
}
|
||||||
var truncated bool
|
var truncated bool
|
||||||
if item.Text, truncated = truncateText(item.Text, q.laws.MaxText); truncated {
|
if item.Text, truncated = truncateText(item.Text, q.laws.MaxText); truncated {
|
||||||
defer q.logf("queue: ansage (%q …) auf %d Zeichen gekürzt (max_text)", firstRunes(item.Text, 40), q.laws.MaxText)
|
defer q.logf("queue: announcement (%q …) truncated to %d characters (max_text)", firstRunes(item.Text, 40), q.laws.MaxText)
|
||||||
}
|
}
|
||||||
item.enqueued = time.Now()
|
item.enqueued = time.Now()
|
||||||
switch q.laws.decide(item, item.enqueued, q.limit.Allow()) {
|
switch q.laws.decide(item, item.enqueued, q.limit.Allow()) {
|
||||||
case verdictDiscardQuiet:
|
case verdictDiscardQuiet:
|
||||||
q.mu.Unlock()
|
q.mu.Unlock()
|
||||||
q.logf("queue: ansage (%q, priorität %s) verworfen — ruhezeit %s aktiv (modus discard)",
|
q.logf("queue: announcement (%q, priority %s) discarded: quiet hours %s active (mode discard)",
|
||||||
item.Text, item.Priority, q.laws.Quiet)
|
item.Text, item.Priority, q.laws.Quiet)
|
||||||
return Admission{Discarded: DiscardQuietHours}, nil
|
return Admission{Discarded: DiscardQuietHours}, nil
|
||||||
case verdictToast:
|
case verdictToast:
|
||||||
q.mu.Unlock()
|
q.mu.Unlock()
|
||||||
q.logf("queue: ansage (%q, priorität %s) durch toast ersetzt — ruhezeit %s aktiv (modus toast)",
|
q.logf("queue: announcement (%q, priority %s) replaced by toast: quiet hours %s active (mode toast)",
|
||||||
item.Text, item.Priority, q.laws.Quiet)
|
item.Text, item.Priority, q.laws.Quiet)
|
||||||
q.fireToast(item)
|
q.fireToast(item)
|
||||||
return Admission{Discarded: DiscardQuietHours, Toast: true}, nil
|
return Admission{Discarded: DiscardQuietHours, Toast: true}, nil
|
||||||
case verdictDiscardRate:
|
case verdictDiscardRate:
|
||||||
q.mu.Unlock()
|
q.mu.Unlock()
|
||||||
q.logf("queue: ansage (%q, priorität low) verworfen — rate-limit %s",
|
q.logf("queue: announcement (%q, priority low) discarded: rate limit %s",
|
||||||
item.Text, q.laws.RateLimit)
|
item.Text, q.laws.RateLimit)
|
||||||
return Admission{Discarded: DiscardRateLimit}, nil
|
return Admission{Discarded: DiscardRateLimit}, nil
|
||||||
}
|
}
|
||||||
@@ -208,7 +204,7 @@ func (q *Queue) Enqueue(item Item) (Admission, error) {
|
|||||||
return Admission{ID: item.ID, Truncated: truncated}, nil
|
return Admission{ID: item.ID, Truncated: truncated}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// firstRunes liefert die ersten n Runen von s (Protokoll-Vorschau).
|
// firstRunes returns the first n runes of s (log preview).
|
||||||
func firstRunes(s string, n int) string {
|
func firstRunes(s string, n int) string {
|
||||||
r := []rune(s)
|
r := []rune(s)
|
||||||
if len(r) <= n {
|
if len(r) <= n {
|
||||||
@@ -217,8 +213,8 @@ func firstRunes(s string, n int) string {
|
|||||||
return string(r[:n])
|
return string(r[:n])
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pending liefert eine Momentaufnahme der wartenden Items in
|
// Pending returns a snapshot of the waiting items in processing order (best
|
||||||
// Abarbeitungs-Reihenfolge (bestes Item zuerst) — Basis für GET /status.
|
// item first); basis for GET /status.
|
||||||
func (q *Queue) Pending() []Item {
|
func (q *Queue) Pending() []Item {
|
||||||
q.mu.Lock()
|
q.mu.Lock()
|
||||||
defer q.mu.Unlock()
|
defer q.mu.Unlock()
|
||||||
@@ -228,8 +224,8 @@ func (q *Queue) Pending() []Item {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
// itemBefore meldet, ob a vor b abgearbeitet wird: höhere Klasse zuerst,
|
// itemBefore reports whether a is processed before b: higher class first,
|
||||||
// innerhalb derselben Klasse die frühere Enqueue-Reihenfolge.
|
// earlier enqueue order within the same class.
|
||||||
func itemBefore(a, b Item) bool {
|
func itemBefore(a, b Item) bool {
|
||||||
if a.rank() != b.rank() {
|
if a.rank() != b.rank() {
|
||||||
return a.rank() > b.rank()
|
return a.rank() > b.rank()
|
||||||
@@ -237,7 +233,7 @@ func itemBefore(a, b Item) bool {
|
|||||||
return a.seq < b.seq
|
return a.seq < b.seq
|
||||||
}
|
}
|
||||||
|
|
||||||
// Current liefert das gerade laufende Item (false: Queue ist idle).
|
// Current returns the item that is playing (false: queue is idle).
|
||||||
func (q *Queue) Current() (Item, bool) {
|
func (q *Queue) Current() (Item, bool) {
|
||||||
q.mu.Lock()
|
q.mu.Lock()
|
||||||
defer q.mu.Unlock()
|
defer q.mu.Unlock()
|
||||||
@@ -247,8 +243,8 @@ func (q *Queue) Current() (Item, bool) {
|
|||||||
return *q.current, true
|
return *q.current, true
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cancel bricht die laufende Ansage ab und leert die Queue. Rückgabe ist
|
// Cancel aborts the playing announcement and empties the queue. It returns
|
||||||
// die Zahl der abgebrochenen Ansagen (laufende + wartende).
|
// the number of cancelled announcements (playing + waiting).
|
||||||
func (q *Queue) Cancel() int {
|
func (q *Queue) Cancel() int {
|
||||||
q.mu.Lock()
|
q.mu.Lock()
|
||||||
defer q.mu.Unlock()
|
defer q.mu.Unlock()
|
||||||
@@ -263,9 +259,22 @@ func (q *Queue) Cancel() int {
|
|||||||
return n
|
return n
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close fährt die Queue herunter: wartende Items werden verworfen, die
|
// CancelItem aborts the announcement with the given id if it is the one
|
||||||
// laufende Ansage abgebrochen, der Worker-Loop beendet. Close wartet, bis
|
// playing right now (the Cancel button of its notification). Waiting items
|
||||||
// der Loop sicher beendet ist (idempotent).
|
// and the rest of the queue are untouched. Reports whether it hit.
|
||||||
|
func (q *Queue) CancelItem(id string) bool {
|
||||||
|
q.mu.Lock()
|
||||||
|
defer q.mu.Unlock()
|
||||||
|
if q.current == nil || q.current.ID != id || q.cancelCur == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
q.cancelCur()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close shuts the queue down: waiting items are dropped, the playing
|
||||||
|
// announcement is aborted, the worker loop ends. Close waits until the loop
|
||||||
|
// has ended (idempotent).
|
||||||
func (q *Queue) Close() {
|
func (q *Queue) Close() {
|
||||||
q.mu.Lock()
|
q.mu.Lock()
|
||||||
if q.closed {
|
if q.closed {
|
||||||
@@ -287,10 +296,9 @@ func (q *Queue) Close() {
|
|||||||
<-q.done
|
<-q.done
|
||||||
}
|
}
|
||||||
|
|
||||||
// LawState liefert die /status-Sicht auf die Anti-Spam-Gesetze: das
|
// LawState returns the /status view of the laws: the configured rate limit
|
||||||
// konfigurierte Rate-Limit mit dem nächsten freien Slot (Nullzeit = frei
|
// with the next open slot (zero = open or unlimited), the quiet window with
|
||||||
// oder unbegrenzt) und das Ruhezeit-Fenster mit seinem Ende, wenn es
|
// its end if active, and the length and age limits.
|
||||||
// gerade aktiv ist.
|
|
||||||
func (q *Queue) LawState() LawState {
|
func (q *Queue) LawState() LawState {
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
return LawState{
|
return LawState{
|
||||||
@@ -306,19 +314,19 @@ func (q *Queue) LawState() LawState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// loop ist der Worker: wartet auf fällige Items und spielt sie einzeln ab.
|
// loop is the worker: it waits for due items and plays them one by one.
|
||||||
// „Fällig" heißt seit Task 05 auch gesetzkonform: Geparkte schlafen bis zum
|
// "Due" includes the laws: parked items sleep until the rate-limit slot
|
||||||
// Rate-Limit-Slot (armWakeLocked weckt), low- und Ruhezeit-Verwürfe laufen
|
// (armWakeLocked wakes them), discards pass through the worker without
|
||||||
// ohne Audio durchs Protokoll, now und high-burst spielen sofort.
|
// audio but with a log line, now and high burst play immediately. After
|
||||||
// Nach Close (oder wenn Close während einer Ansage zuschlägt) beendet er
|
// Close (also when Close hits during an announcement) it exits as soon as
|
||||||
// sich, sobald die laufende Ansage zurückgekehrt ist.
|
// the playing announcement has returned.
|
||||||
func (q *Queue) loop() {
|
func (q *Queue) loop() {
|
||||||
defer close(q.done)
|
defer close(q.done)
|
||||||
for {
|
for {
|
||||||
q.mu.Lock()
|
q.mu.Lock()
|
||||||
for !q.closed && !q.readyLocked() {
|
for !q.closed && !q.readyLocked() {
|
||||||
if len(q.items) > 0 {
|
if len(q.items) > 0 {
|
||||||
// Bestes Item parkt auf den Slot: Wecker zum Termin armieren.
|
// The best item parks for its slot: arm the timer.
|
||||||
q.armWakeLocked(q.limit.Next())
|
q.armWakeLocked(q.limit.Next())
|
||||||
}
|
}
|
||||||
q.notEmpty.Wait()
|
q.notEmpty.Wait()
|
||||||
@@ -329,27 +337,28 @@ func (q *Queue) loop() {
|
|||||||
}
|
}
|
||||||
item, v := q.takeLocked()
|
item, v := q.takeLocked()
|
||||||
if v == verdictWait {
|
if v == verdictWait {
|
||||||
// Kurz ohne Fortschritt geweckt (z. B. verlorenes Signal):
|
// Woken without progress (for example a lost signal): go back to
|
||||||
// wieder schlafen legen. Kann nach readyLocked eigentlich nie
|
// sleep. Cannot really happen after readyLocked; parked rather
|
||||||
// eintreten — sicherheitshalber geparkt statt gedreht.
|
// than spun, just in case.
|
||||||
q.mu.Unlock()
|
q.mu.Unlock()
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if v == verdictPlay {
|
if v == verdictPlay {
|
||||||
// Fenster buchen, BEVOR gesprochen wird: Sobald das Item als
|
// Book the window BEFORE speaking: as soon as the item counts as
|
||||||
// laufend gilt, steht der nächste Slot-Termin fest.
|
// playing, the next slot time is fixed.
|
||||||
q.limit.Reserve()
|
q.limit.Reserve()
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
q.current = &item
|
q.current = &item
|
||||||
q.cancelCur = cancel
|
q.cancelCur = cancel
|
||||||
q.mu.Unlock()
|
q.mu.Unlock()
|
||||||
|
|
||||||
q.logf("queue: ansage %s (%q, Priorität %s, now=%v) startet", item.ID, item.Text, item.Priority, item.Now)
|
q.logf("queue: announcement %s (%q, priority %s, now=%v) starting", item.ID, item.Text, item.Priority, item.Now)
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
err := q.speak(ctx, item)
|
err := q.speak(ctx, item)
|
||||||
dur := time.Since(start)
|
dur := time.Since(start)
|
||||||
// Abbruch VOR dem eigenen cancel() ablesen — danach wäre ctx.Err()
|
// Read the cancellation BEFORE our own cancel(): afterwards
|
||||||
// immer gesetzt und jede fertige Ansage hieße „abgebrochen".
|
// ctx.Err() is always set and every finished announcement would
|
||||||
|
// read as cancelled.
|
||||||
cancelled := ctx.Err() != nil
|
cancelled := ctx.Err() != nil
|
||||||
cancel()
|
cancel()
|
||||||
|
|
||||||
@@ -360,37 +369,37 @@ func (q *Queue) loop() {
|
|||||||
|
|
||||||
switch {
|
switch {
|
||||||
case cancelled:
|
case cancelled:
|
||||||
q.logf("queue: ansage %s abgebrochen", item.ID)
|
q.logf("queue: announcement %s cancelled", item.ID)
|
||||||
case err != nil:
|
case err != nil:
|
||||||
q.logf("queue: ansage %s fehlgeschlagen nach %s: %v", item.ID, dur.Round(time.Millisecond), err)
|
q.logf("queue: announcement %s failed after %s: %v", item.ID, dur.Round(time.Millisecond), err)
|
||||||
default:
|
default:
|
||||||
q.logf("queue: ansage %s fertig nach %s", item.ID, dur.Round(time.Millisecond))
|
q.logf("queue: announcement %s finished after %s", item.ID, dur.Round(time.Millisecond))
|
||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
q.mu.Unlock()
|
q.mu.Unlock()
|
||||||
switch v {
|
switch v {
|
||||||
case verdictDiscardRate:
|
case verdictDiscardRate:
|
||||||
q.logf("queue: ansage %s (%q, priorität low) verworfen — rate-limit %s",
|
q.logf("queue: announcement %s (%q, priority low) discarded: rate limit %s",
|
||||||
item.ID, item.Text, q.laws.RateLimit)
|
item.ID, item.Text, q.laws.RateLimit)
|
||||||
case verdictDiscardQuiet:
|
case verdictDiscardQuiet:
|
||||||
q.logf("queue: ansage %s (%q) verworfen — ruhezeit %s aktiv (modus discard)",
|
q.logf("queue: announcement %s (%q) discarded: quiet hours %s active (mode discard)",
|
||||||
item.ID, item.Text, q.laws.Quiet)
|
item.ID, item.Text, q.laws.Quiet)
|
||||||
case verdictToast:
|
case verdictToast:
|
||||||
q.logf("queue: ansage %s (%q) durch toast ersetzt — ruhezeit %s aktiv (modus toast)",
|
q.logf("queue: announcement %s (%q) replaced by toast: quiet hours %s active (mode toast)",
|
||||||
item.ID, item.Text, q.laws.Quiet)
|
item.ID, item.Text, q.laws.Quiet)
|
||||||
q.fireToast(item)
|
q.fireToast(item)
|
||||||
case verdictDiscardExpired:
|
case verdictDiscardExpired:
|
||||||
q.logf("queue: ansage %s (%q) verworfen — %s gewartet, älter als max_age %s",
|
q.logf("queue: announcement %s (%q) discarded: waited %s, older than max_age %s",
|
||||||
item.ID, item.Text, time.Since(item.enqueued).Round(time.Second), q.laws.MaxAge)
|
item.ID, item.Text, time.Since(item.enqueued).Round(time.Second), q.laws.MaxAge)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// readyLocked meldet, ob der Worker arbeiten kann (mu muss gehalten
|
// readyLocked reports whether the worker has work (mu must be held): always
|
||||||
// werden): geschlossen immer; sonst nur, wenn das beste Item nicht bloß
|
// when closed; otherwise only when the best item is not merely parked for
|
||||||
// auf seinen Rate-Limit-Slot parkt. Verwürfe zählen als Arbeit — sie
|
// its rate-limit slot. Discards count as work: they pass through the worker
|
||||||
// laufen ohne Audio, aber mit Protokoll durch den Worker.
|
// without audio but with a log line.
|
||||||
func (q *Queue) readyLocked() bool {
|
func (q *Queue) readyLocked() bool {
|
||||||
if q.closed || len(q.items) == 0 {
|
if q.closed || len(q.items) == 0 {
|
||||||
return q.closed
|
return q.closed
|
||||||
@@ -398,10 +407,9 @@ func (q *Queue) readyLocked() bool {
|
|||||||
return q.verdictLocked(q.items[q.bestIndexLocked()]) != verdictWait
|
return q.verdictLocked(q.items[q.bestIndexLocked()]) != verdictWait
|
||||||
}
|
}
|
||||||
|
|
||||||
// takeLocked entnimmt das als nächstes fällige Item, wenn es spielbar oder
|
// takeLocked removes the next due item when it is playable or decidable
|
||||||
// entscheidbar ist (mu muss gehalten werden). Bei verdictWait wird NICHT
|
// (mu must be held). On verdictWait it is NOT removed: the item stays
|
||||||
// entnommen — das Item bleibt geparkt, bis der Slot frei ist (oder ein
|
// parked until the slot opens (or a better item overtakes it).
|
||||||
// besseres Item vorgezogen wird).
|
|
||||||
func (q *Queue) takeLocked() (Item, verdict) {
|
func (q *Queue) takeLocked() (Item, verdict) {
|
||||||
best := q.bestIndexLocked()
|
best := q.bestIndexLocked()
|
||||||
item := q.items[best]
|
item := q.items[best]
|
||||||
@@ -412,8 +420,7 @@ func (q *Queue) takeLocked() (Item, verdict) {
|
|||||||
return item, v
|
return item, v
|
||||||
}
|
}
|
||||||
|
|
||||||
// bestIndexLocked liefert den Index des als nächstes fälligen Items
|
// bestIndexLocked returns the index of the next due item (mu must be held).
|
||||||
// (mu muss gehalten werden).
|
|
||||||
func (q *Queue) bestIndexLocked() int {
|
func (q *Queue) bestIndexLocked() int {
|
||||||
best := 0
|
best := 0
|
||||||
for i := 1; i < len(q.items); i++ {
|
for i := 1; i < len(q.items); i++ {
|
||||||
@@ -424,16 +431,16 @@ func (q *Queue) bestIndexLocked() int {
|
|||||||
return best
|
return best
|
||||||
}
|
}
|
||||||
|
|
||||||
// verdictLocked wendet die Gesetze auf ein Item an (mu muss gehalten
|
// verdictLocked applies the laws to an item (mu must be held; the lock order
|
||||||
// werden — die Lock-Ordnung Queue → RateLimiter bleibt gewahrt).
|
// queue → RateLimiter is preserved).
|
||||||
func (q *Queue) verdictLocked(item Item) verdict {
|
func (q *Queue) verdictLocked(item Item) verdict {
|
||||||
return q.laws.decide(item, time.Now(), q.limit.Allow())
|
return q.laws.decide(item, time.Now(), q.limit.Allow())
|
||||||
}
|
}
|
||||||
|
|
||||||
// armWakeLocked armiert den Slot-Wecker auf until (mu muss gehalten
|
// armWakeLocked arms the slot timer for until (mu must be held): it
|
||||||
// werden): Er broadcastet die Cond zum Termin, damit der geparkte Worker
|
// broadcasts the cond at that time so the parked worker wakes without a new
|
||||||
// auch ohne neuen Enqueue aufwacht. Ein bereits laufender Wecker mit
|
// Enqueue. A running timer with an earlier (or equal) time suffices;
|
||||||
// früherem (oder gleichem) Termin reicht; sonst wird er ersetzt.
|
// otherwise it is replaced.
|
||||||
func (q *Queue) armWakeLocked(until time.Time) {
|
func (q *Queue) armWakeLocked(until time.Time) {
|
||||||
if q.wake != nil && !q.wakeAt.After(until) {
|
if q.wake != nil && !q.wakeAt.After(until) {
|
||||||
return
|
return
|
||||||
@@ -454,9 +461,9 @@ func (q *Queue) armWakeLocked(until time.Time) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// newID liefert eine kurze, kollisionsarme ID (6 Hex-Zeichen). IDs müssen
|
// newID returns a short, collision-resistant ID (6 hex characters). IDs only
|
||||||
// nur pro Daemon-Lauf eindeutig sein (--wait-Polling); der Fallback ist
|
// need to be unique per daemon run (--wait polling); the fallback is
|
||||||
// praktisch unerreichbar, aber deterministisch sicher.
|
// practically unreachable but deterministic.
|
||||||
func newID() string {
|
func newID() string {
|
||||||
var b [3]byte
|
var b [3]byte
|
||||||
if _, err := rand.Read(b[:]); err == nil {
|
if _, err := rand.Read(b[:]); err == nil {
|
||||||
@@ -465,8 +472,8 @@ func newID() string {
|
|||||||
return fmt.Sprintf("id%d", time.Now().UnixNano())
|
return fmt.Sprintf("id%d", time.Now().UnixNano())
|
||||||
}
|
}
|
||||||
|
|
||||||
// logf schreibt eine Protokoll-Zeile, wenn ein Log gesetzt ist. Wird nie
|
// logf writes a log line when a log is set. Never called under the mutex
|
||||||
// unter dem Mutex gerufen (Aufrufer achten darauf).
|
// (callers take care of that).
|
||||||
func (q *Queue) logf(format string, args ...any) {
|
func (q *Queue) logf(format string, args ...any) {
|
||||||
if q.log != nil {
|
if q.log != nil {
|
||||||
fmt.Fprintf(q.log, format+"\n", args...)
|
fmt.Fprintf(q.log, format+"\n", args...)
|
||||||
|
|||||||
+267
-233
@@ -11,23 +11,22 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// gesteuerteSpielerin ist ein testbarer Speaker: Jede Ansage meldet ihren
|
// controlledSpeaker is a testable Speaker: every announcement reports its
|
||||||
// Start auf started (Kanal-Puffer: der Worker blockiert nie) und wartet
|
// start on started (buffered channel: the worker never blocks) and then
|
||||||
// dann, bis der Test sie per step freigibt — so ist die Abarbeitung
|
// waits until the test releases it via step, so processing is fully
|
||||||
// vollständig deterministisch steuerbar. Ein abgebrochener ctx beendet das
|
// deterministic. A cancelled ctx ends the wait (Cancel/Close paths). All
|
||||||
// Warten (Cancel-/Close-Pfade). Alle Felder werden nur vom Test gelesen;
|
// fields are read only by the test; started order == start order.
|
||||||
// started-Reihenfolge == Start-Reihenfolge.
|
type controlledSpeaker struct {
|
||||||
type gesteuerteSpielerin struct {
|
|
||||||
started chan Item
|
started chan Item
|
||||||
step chan struct{}
|
step chan struct{}
|
||||||
consumed int // von warteBis konsumierte Starts (nur Test-Goroutine)
|
consumed int // starts consumed by waitUntil (test goroutine only)
|
||||||
}
|
}
|
||||||
|
|
||||||
func neueSpielerin() *gesteuerteSpielerin {
|
func newSpeaker() *controlledSpeaker {
|
||||||
return &gesteuerteSpielerin{started: make(chan Item, 16), step: make(chan struct{})}
|
return &controlledSpeaker{started: make(chan Item, 16), step: make(chan struct{})}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (g *gesteuerteSpielerin) speak(ctx context.Context, item Item) error {
|
func (g *controlledSpeaker) speak(ctx context.Context, item Item) error {
|
||||||
g.started <- item
|
g.started <- item
|
||||||
select {
|
select {
|
||||||
case <-g.step:
|
case <-g.step:
|
||||||
@@ -37,9 +36,9 @@ func (g *gesteuerteSpielerin) speak(ctx context.Context, item Item) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// warteBis wartet, bis insgesamt n Ansagen gestartet sind, und liefert die
|
// waitUntil waits until n announcements have started in total and returns
|
||||||
// seit dem letzten warteBis-Aufruf neu gestarteten.
|
// the ones started since the previous waitUntil call.
|
||||||
func (g *gesteuerteSpielerin) warteBis(t *testing.T, n int) []Item {
|
func (g *controlledSpeaker) waitUntil(t *testing.T, n int) []Item {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
var items []Item
|
var items []Item
|
||||||
deadline := time.After(2 * time.Second)
|
deadline := time.After(2 * time.Second)
|
||||||
@@ -49,29 +48,29 @@ func (g *gesteuerteSpielerin) warteBis(t *testing.T, n int) []Item {
|
|||||||
g.consumed++
|
g.consumed++
|
||||||
items = append(items, it)
|
items = append(items, it)
|
||||||
case <-deadline:
|
case <-deadline:
|
||||||
t.Fatalf("nur %d von %d Ansagen gestartet", g.consumed, n)
|
t.Fatalf("only %d of %d announcements started", g.consumed, n)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return items
|
return items
|
||||||
}
|
}
|
||||||
|
|
||||||
// keineWeitere prüft, dass keine weitere Ansage startet (Poll-Fenster).
|
// noFurther checks that no further announcement starts (poll window).
|
||||||
func (g *gesteuerteSpielerin) keineWeitere(t *testing.T) {
|
func (g *controlledSpeaker) noFurther(t *testing.T) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
select {
|
select {
|
||||||
case it := <-g.started:
|
case it := <-g.started:
|
||||||
g.consumed++
|
g.consumed++
|
||||||
t.Fatalf("unerwartete Ansage %q gestartet", it.Text)
|
t.Fatalf("unexpected announcement %q started", it.Text)
|
||||||
case <-time.After(150 * time.Millisecond):
|
case <-time.After(150 * time.Millisecond):
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestAbarbeitungsReihenfolge: now vor high vor normal vor low, FIFO je
|
// TestProcessingOrder: now before high before normal before low, FIFO per
|
||||||
// Level. Der erste Blocker besetzt den Worker; danach werden alle Level
|
// level. The first blocker occupies the worker; then all levels are
|
||||||
// gleichzeitig eingereiht — die Abarbeitung muss der Klasse folgen.
|
// enqueued at once and processing must follow the class.
|
||||||
// (Ohne Gesetze: Null-Laws = unbegrenzt, keine Ruhezeit.)
|
// (No laws: zero Laws = unlimited, no quiet hours.)
|
||||||
func TestAbarbeitungsReihenfolge(t *testing.T) {
|
func TestProcessingOrder(t *testing.T) {
|
||||||
g := neueSpielerin()
|
g := newSpeaker()
|
||||||
q := New(Laws{}, g.speak, nil)
|
q := New(Laws{}, g.speak, nil)
|
||||||
defer q.Close()
|
defer q.Close()
|
||||||
|
|
||||||
@@ -80,131 +79,130 @@ func TestAbarbeitungsReihenfolge(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if adm.ID == "" || adm.Discarded != "" {
|
if adm.ID == "" || adm.Discarded != "" {
|
||||||
t.Fatalf("Enqueue = %+v, want Aufnahme mit ID", adm)
|
t.Fatalf("Enqueue = %+v, want admission with ID", adm)
|
||||||
}
|
}
|
||||||
g.warteBis(t, 1) // Blocker läuft, Worker gebunden.
|
g.waitUntil(t, 1) // blocker is playing, worker is busy
|
||||||
|
|
||||||
for _, it := range []Item{
|
for _, it := range []Item{
|
||||||
{Text: "niedrig", Priority: PriorityLow},
|
{Text: "low", Priority: PriorityLow},
|
||||||
{Text: "zweit-niedrig", Priority: PriorityLow},
|
{Text: "second-low", Priority: PriorityLow},
|
||||||
{Text: "mittel", Priority: PriorityNormal},
|
{Text: "normal", Priority: PriorityNormal},
|
||||||
{Text: "dringend", Priority: PriorityHigh},
|
{Text: "urgent", Priority: PriorityHigh},
|
||||||
{Text: "sofort", Now: true},
|
{Text: "right-now", Now: true},
|
||||||
} {
|
} {
|
||||||
if _, err := q.Enqueue(it); err != nil {
|
if _, err := q.Enqueue(it); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
g.keineWeitere(t) // Serialisierung: Worker spielt noch den Blocker.
|
g.noFurther(t) // serialization: the worker is still on the blocker
|
||||||
|
|
||||||
// Freigeben: alles Übrige läuft in Klassen-Reihenfolge durch.
|
// Release: everything else runs through in class order.
|
||||||
close(g.step)
|
close(g.step)
|
||||||
rest := g.warteBis(t, 6)
|
rest := g.waitUntil(t, 6)
|
||||||
|
|
||||||
var texts []string
|
var texts []string
|
||||||
for _, it := range rest {
|
for _, it := range rest {
|
||||||
texts = append(texts, it.Text)
|
texts = append(texts, it.Text)
|
||||||
}
|
}
|
||||||
want := []string{"sofort", "dringend", "mittel", "niedrig", "zweit-niedrig"}
|
want := []string{"right-now", "urgent", "normal", "low", "second-low"}
|
||||||
if !slices.Equal(texts, want) {
|
if !slices.Equal(texts, want) {
|
||||||
t.Errorf("Abarbeitung nach dem Blocker = %v, want %v", texts, want)
|
t.Errorf("processing after the blocker = %v, want %v", texts, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestCurrentUndPending: Status-Sicht auf laufendes Item + Warteschlange.
|
// TestCurrentAndPending: status view of the playing item and the queue.
|
||||||
func TestCurrentUndPending(t *testing.T) {
|
func TestCurrentAndPending(t *testing.T) {
|
||||||
g := neueSpielerin()
|
g := newSpeaker()
|
||||||
q := New(Laws{}, g.speak, nil)
|
q := New(Laws{}, g.speak, nil)
|
||||||
defer q.Close()
|
defer q.Close()
|
||||||
|
|
||||||
if _, ok := q.Current(); ok {
|
if _, ok := q.Current(); ok {
|
||||||
t.Fatal("Current vor erster Ansage: want idle")
|
t.Fatal("Current before the first announcement: want idle")
|
||||||
}
|
}
|
||||||
|
|
||||||
q.Enqueue(Item{Text: "blocker"})
|
q.Enqueue(Item{Text: "blocker"})
|
||||||
g.warteBis(t, 1)
|
g.waitUntil(t, 1)
|
||||||
|
|
||||||
q.Enqueue(Item{Text: "hoch", Priority: PriorityHigh})
|
q.Enqueue(Item{Text: "high", Priority: PriorityHigh})
|
||||||
q.Enqueue(Item{Text: "niedrig", Priority: PriorityLow})
|
q.Enqueue(Item{Text: "low", Priority: PriorityLow})
|
||||||
|
|
||||||
if cur, ok := q.Current(); !ok || cur.Text != "blocker" {
|
if cur, ok := q.Current(); !ok || cur.Text != "blocker" {
|
||||||
t.Errorf("Current = %+v (ok=%v), will Blocker", cur, ok)
|
t.Errorf("Current = %+v (ok=%v), want the blocker", cur, ok)
|
||||||
}
|
}
|
||||||
var pendingTexts []string
|
var pendingTexts []string
|
||||||
for _, it := range q.Pending() {
|
for _, it := range q.Pending() {
|
||||||
pendingTexts = append(pendingTexts, it.Text)
|
pendingTexts = append(pendingTexts, it.Text)
|
||||||
}
|
}
|
||||||
if !slices.Equal(pendingTexts, []string{"hoch", "niedrig"}) {
|
if !slices.Equal(pendingTexts, []string{"high", "low"}) {
|
||||||
t.Errorf("Pending = %v, want [hoch niedrig]", pendingTexts)
|
t.Errorf("Pending = %v, want [high low]", pendingTexts)
|
||||||
}
|
}
|
||||||
|
|
||||||
close(g.step)
|
close(g.step)
|
||||||
g.warteBis(t, 3)
|
g.waitUntil(t, 3)
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestCancel: laufende Ansage wird über ctx abgebrochen, Queue geleert,
|
// TestCancel: the playing announcement is aborted via ctx, the queue
|
||||||
// Gesamtzahl zurückgemeldet; danach ist die Queue wieder aufnahme- und
|
// emptied, the total reported; afterwards the queue admits and plays again.
|
||||||
// spielbereit.
|
|
||||||
func TestCancel(t *testing.T) {
|
func TestCancel(t *testing.T) {
|
||||||
g := neueSpielerin()
|
g := newSpeaker()
|
||||||
q := New(Laws{}, g.speak, nil)
|
q := New(Laws{}, g.speak, nil)
|
||||||
defer q.Close()
|
defer q.Close()
|
||||||
|
|
||||||
q.Enqueue(Item{Text: "blocker"})
|
q.Enqueue(Item{Text: "blocker"})
|
||||||
g.warteBis(t, 1)
|
g.waitUntil(t, 1)
|
||||||
|
|
||||||
q.Enqueue(Item{Text: "wartet-eins"})
|
q.Enqueue(Item{Text: "waiting-one"})
|
||||||
q.Enqueue(Item{Text: "wartet-zwei"})
|
q.Enqueue(Item{Text: "waiting-two"})
|
||||||
|
|
||||||
if n := q.Cancel(); n != 3 {
|
if n := q.Cancel(); n != 3 {
|
||||||
t.Errorf("Cancel = %d, want 3 (laufende + 2 wartende)", n)
|
t.Errorf("Cancel = %d, want 3 (playing + 2 waiting)", n)
|
||||||
}
|
}
|
||||||
|
|
||||||
g.keineWeitere(t) // Blocker durch ctx beendet, wartende Items sind weg.
|
g.noFurther(t) // blocker ended via ctx, waiting items are gone
|
||||||
waitIdle(t, q)
|
waitIdle(t, q)
|
||||||
|
|
||||||
if n := q.Cancel(); n != 0 {
|
if n := q.Cancel(); n != 0 {
|
||||||
t.Errorf("Cancel auf leerer Queue = %d, want 0", n)
|
t.Errorf("Cancel on empty queue = %d, want 0", n)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Queue nimmt wieder an und spielt:
|
// The queue admits and plays again:
|
||||||
adm, err := q.Enqueue(Item{Text: "danach"})
|
adm, err := q.Enqueue(Item{Text: "afterwards"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
g.step <- struct{}{} // gibt die wartende Ansage im Speaker frei
|
g.step <- struct{}{} // releases the waiting announcement in the speaker
|
||||||
gestartet := g.warteBis(t, 2)
|
started := g.waitUntil(t, 2)
|
||||||
if len(gestartet) != 1 || gestartet[0].ID != adm.ID {
|
if len(started) != 1 || started[0].ID != adm.ID {
|
||||||
t.Errorf("neue Ansage nicht gestartet: %+v", gestartet)
|
t.Errorf("new announcement not started: %+v", started)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestClose: wartende Items werden verworfen, die laufende Ansage über den
|
// TestClose: waiting items are dropped, the playing announcement ends via
|
||||||
// abgebrochenen ctx beendet, Close wartet auf den Worker-Exit, danach ist
|
// the cancelled ctx, Close waits for the worker to exit, afterwards Enqueue
|
||||||
// Enqueue ein Fehler (und Close idempotent).
|
// is an error (and Close idempotent).
|
||||||
func TestClose(t *testing.T) {
|
func TestClose(t *testing.T) {
|
||||||
g := neueSpielerin()
|
g := newSpeaker()
|
||||||
q := New(Laws{}, g.speak, nil)
|
q := New(Laws{}, g.speak, nil)
|
||||||
|
|
||||||
q.Enqueue(Item{Text: "blocker"})
|
q.Enqueue(Item{Text: "blocker"})
|
||||||
g.warteBis(t, 1)
|
g.waitUntil(t, 1)
|
||||||
q.Enqueue(Item{Text: "wartet"})
|
q.Enqueue(Item{Text: "waiting"})
|
||||||
|
|
||||||
q.Close()
|
q.Close()
|
||||||
|
|
||||||
g.keineWeitere(t)
|
g.noFurther(t)
|
||||||
if _, ok := q.Current(); ok {
|
if _, ok := q.Current(); ok {
|
||||||
t.Error("Current nach Close: want idle")
|
t.Error("Current after Close: want idle")
|
||||||
}
|
}
|
||||||
if _, err := q.Enqueue(Item{Text: "zu spät"}); err == nil {
|
if _, err := q.Enqueue(Item{Text: "too late"}); err == nil {
|
||||||
t.Error("Enqueue nach Close: want Fehler")
|
t.Error("Enqueue after Close: want error")
|
||||||
}
|
}
|
||||||
q.Close() // idempotent
|
q.Close() // idempotent
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestEnqueueVergibtIDs: IDs sind kurz und eindeutig.
|
// TestEnqueueAssignsIDs: IDs are short and unique.
|
||||||
func TestEnqueueVergibtIDs(t *testing.T) {
|
func TestEnqueueAssignsIDs(t *testing.T) {
|
||||||
g := neueSpielerin()
|
g := newSpeaker()
|
||||||
q := New(Laws{}, g.speak, nil)
|
q := New(Laws{}, g.speak, nil)
|
||||||
defer q.Close()
|
defer q.Close()
|
||||||
|
|
||||||
@@ -215,15 +213,15 @@ func TestEnqueueVergibtIDs(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if len(adm.ID) < 4 || seen[adm.ID] {
|
if len(adm.ID) < 4 || seen[adm.ID] {
|
||||||
t.Errorf("ID %q zu kurz oder doppelt", adm.ID)
|
t.Errorf("ID %q too short or duplicate", adm.ID)
|
||||||
}
|
}
|
||||||
seen[adm.ID] = true
|
seen[adm.ID] = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// waitIdle pollt, bis kein Item mehr läuft (Cancel-/Close-Pfade geben das
|
// waitIdle polls until no item is playing (Cancel/Close release that
|
||||||
// nach dem Worker-Exit synchron frei; das Pollen deckt die Übergangsphase
|
// synchronously after the worker exits; polling covers the transition
|
||||||
// ab, ohne auf Timing zu trauen).
|
// without trusting timing).
|
||||||
func waitIdle(t *testing.T, q *Queue) {
|
func waitIdle(t *testing.T, q *Queue) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
deadline := time.Now().Add(time.Second)
|
deadline := time.Now().Add(time.Second)
|
||||||
@@ -232,314 +230,323 @@ func waitIdle(t *testing.T, q *Queue) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if time.Now().After(deadline) {
|
if time.Now().After(deadline) {
|
||||||
t.Fatal("Queue wird nicht idle")
|
t.Fatal("queue does not become idle")
|
||||||
}
|
}
|
||||||
time.Sleep(5 * time.Millisecond)
|
time.Sleep(5 * time.Millisecond)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestMuteStore: Datei-Roundtrip, Fehlend-Heißt-Nicht-Stumm, atomares Set.
|
// TestMuteStore: file round trip, missing means not muted, atomic Set.
|
||||||
func TestMuteStore(t *testing.T) {
|
func TestMuteStore(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
path := filepath.Join(dir, MuteFileName)
|
path := filepath.Join(dir, MuteFileName)
|
||||||
|
|
||||||
var s MuteStore
|
var s MuteStore
|
||||||
if s.Muted() {
|
if s.Muted() {
|
||||||
t.Error("MuteStore ohne Pfad: Muted() = true, want false")
|
t.Error("MuteStore without path: Muted() = true, want false")
|
||||||
}
|
}
|
||||||
if err := s.Set(true); err == nil {
|
if err := s.Set(true); err == nil {
|
||||||
t.Error("Set ohne Pfad: want Fehler")
|
t.Error("Set without path: want error")
|
||||||
}
|
}
|
||||||
|
|
||||||
s = MuteStore{Path: path}
|
s = MuteStore{Path: path}
|
||||||
if s.Muted() {
|
if s.Muted() {
|
||||||
t.Error("ohne Datei: Muted() = true, want false (nie still aus Versehen)")
|
t.Error("without file: Muted() = true, want false (never silent by accident)")
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := s.Set(true); err != nil {
|
if err := s.Set(true); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if !s.Muted() {
|
if !s.Muted() {
|
||||||
t.Error("nach Set(true): Muted() = false")
|
t.Error("after Set(true): Muted() = false")
|
||||||
}
|
}
|
||||||
if b, _ := os.ReadFile(path); string(b) != "true\n" {
|
if b, _ := os.ReadFile(path); string(b) != "true\n" {
|
||||||
t.Errorf("Datei-Inhalt = %q, want %q", b, "true\n")
|
t.Errorf("file content = %q, want %q", b, "true\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := s.Set(false); err != nil {
|
if err := s.Set(false); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if s.Muted() {
|
if s.Muted() {
|
||||||
t.Error("nach Set(false): Muted() = true")
|
t.Error("after Set(false): Muted() = true")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Müll in der Datei heißt: nicht stumm (nur „true" ist stumm).
|
// Garbage in the file means not muted (only "true" is muted).
|
||||||
if err := os.WriteFile(path, []byte("vielleicht\n"), 0o644); err != nil {
|
if err := os.WriteFile(path, []byte("maybe\n"), 0o644); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if s.Muted() {
|
if s.Muted() {
|
||||||
t.Error("Datei-Inhalt „vielleicht“: Muted() = true, want false")
|
t.Error("file content \"maybe\": Muted() = true, want false")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestRateLimiter: Struktur-Semantik (seit Task 05 in den Loop verwired).
|
// TestRateLimiter: the limiter's own semantics.
|
||||||
func TestRateLimiter(t *testing.T) {
|
func TestRateLimiter(t *testing.T) {
|
||||||
// Unbegrenzt (Task-04-Default): Interval 0 erlaubt immer.
|
// Unlimited: interval 0 always allows.
|
||||||
unlimited := &RateLimiter{}
|
unlimited := &RateLimiter{}
|
||||||
for i := 0; i < 3; i++ {
|
for i := 0; i < 3; i++ {
|
||||||
if !unlimited.Allow() {
|
if !unlimited.Allow() {
|
||||||
t.Fatal("Interval 0: Allow = false, want true (unbegrenzt)")
|
t.Fatal("interval 0: Allow = false, want true (unlimited)")
|
||||||
}
|
}
|
||||||
unlimited.Reserve()
|
unlimited.Reserve()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Begrenzt: nach Reserve ist erst nach Interval wieder Allow.
|
// Limited: after Reserve, Allow only after the interval.
|
||||||
l := &RateLimiter{Interval: 30 * time.Millisecond}
|
l := &RateLimiter{Interval: 30 * time.Millisecond}
|
||||||
if !l.Allow() {
|
if !l.Allow() {
|
||||||
t.Fatal("frisches Limit: Allow = false")
|
t.Fatal("fresh limiter: Allow = false")
|
||||||
}
|
}
|
||||||
l.Reserve()
|
l.Reserve()
|
||||||
if l.Allow() {
|
if l.Allow() {
|
||||||
t.Fatal("sofort nach Reserve: Allow = true, want false")
|
t.Fatal("right after Reserve: Allow = true, want false")
|
||||||
}
|
}
|
||||||
if next := l.Next(); time.Now().After(next) {
|
if next := l.Next(); time.Now().After(next) {
|
||||||
t.Errorf("Next() = %v liegt in der Vergangenheit", next)
|
t.Errorf("Next() = %v lies in the past", next)
|
||||||
}
|
}
|
||||||
time.Sleep(40 * time.Millisecond)
|
time.Sleep(40 * time.Millisecond)
|
||||||
if !l.Allow() {
|
if !l.Allow() {
|
||||||
t.Fatal("nach Interval: Allow = false, want true")
|
t.Fatal("after the interval: Allow = false, want true")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// fensterUm baut ein "HH:MM-HH:MM"-Ruhefenster, das t sicher einschließt
|
// windowAround builds an "HH:MM-HH:MM" quiet window that safely contains t
|
||||||
// (eine Minute davor bis eine Minute danach; Minute-Auflösung reicht).
|
// (three minutes before to four minutes after; minute resolution).
|
||||||
func fensterUm(t time.Time) string {
|
func windowAround(t time.Time) string {
|
||||||
return t.Add(-time.Minute).Format("15:04") + "-" + t.Add(time.Minute).Format("15:04")
|
return t.Add(-3*time.Minute).Format("15:04") + "-" + t.Add(4*time.Minute).Format("15:04")
|
||||||
}
|
}
|
||||||
|
|
||||||
// warteAuf verifies mit Pollen eine Bedingung (Zeit-Gesetze sind real, der
|
// waitForCond polls a condition (time laws are real; the controlled speaker
|
||||||
// gesteuerte Speaker allein sieht sie nicht).
|
// alone cannot see them).
|
||||||
func warteAuf(t *testing.T, timeout time.Duration, cond func() bool, was string) {
|
func waitForCond(t *testing.T, timeout time.Duration, cond func() bool, what string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
deadline := time.Now().Add(timeout)
|
deadline := time.Now().Add(timeout)
|
||||||
for !cond() {
|
for !cond() {
|
||||||
if time.Now().After(deadline) {
|
if time.Now().After(deadline) {
|
||||||
t.Fatalf("%s innerhalb %s nicht eingetreten", was, timeout)
|
t.Fatalf("%s did not happen within %s", what, timeout)
|
||||||
}
|
}
|
||||||
time.Sleep(5 * time.Millisecond)
|
time.Sleep(5 * time.Millisecond)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestRateLimitLowVerworfenNormalParkt: mit kurzem Fenster spielt die
|
// TestRateLimitLowDiscardedNormalParks: with a short window the first
|
||||||
// erste Ansage sofort; low über dem Budget wird schon beim Eintritt
|
// announcement plays at once; low over budget is discarded on admission
|
||||||
// verworfen (Admission nennt den Grund), normal parkt und spielt nach
|
// (Admission names the reason), normal parks and plays after the window.
|
||||||
// Fenster-Ablauf.
|
func TestRateLimitLowDiscardedNormalParks(t *testing.T) {
|
||||||
func TestRateLimitLowVerworfenNormalParkt(t *testing.T) {
|
g := newSpeaker()
|
||||||
g := neueSpielerin()
|
|
||||||
q := New(Laws{RateLimit: 400 * time.Millisecond}, g.speak, nil)
|
q := New(Laws{RateLimit: 400 * time.Millisecond}, g.speak, nil)
|
||||||
defer q.Close()
|
defer q.Close()
|
||||||
|
|
||||||
if adm, err := q.Enqueue(Item{Text: "erste"}); err != nil || adm.ID == "" || adm.Discarded != "" {
|
if adm, err := q.Enqueue(Item{Text: "first"}); err != nil || adm.ID == "" || adm.Discarded != "" {
|
||||||
t.Fatalf("erste Enqueue = %+v (%v), want Aufnahme", adm, err)
|
t.Fatalf("first Enqueue = %+v (%v), want admission", adm, err)
|
||||||
}
|
}
|
||||||
g.warteBis(t, 1) // erste läuft — Fenster ist gebucht.
|
g.waitUntil(t, 1) // first is playing, the window is booked
|
||||||
|
|
||||||
adm, err := q.Enqueue(Item{Text: "low-eins", Priority: PriorityLow})
|
adm, err := q.Enqueue(Item{Text: "low-one", Priority: PriorityLow})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if adm.ID != "" || adm.Discarded != DiscardRateLimit || adm.Toast {
|
if adm.ID != "" || adm.Discarded != DiscardRateLimit || adm.Toast {
|
||||||
t.Errorf("low über Budget = %+v, want Verwurf %q", adm, DiscardRateLimit)
|
t.Errorf("low over budget = %+v, want discard %q", adm, DiscardRateLimit)
|
||||||
}
|
}
|
||||||
if adm, err = q.Enqueue(Item{Text: "low-zwei", Priority: PriorityLow}); err != nil || adm.Discarded != DiscardRateLimit {
|
if adm, err = q.Enqueue(Item{Text: "low-two", Priority: PriorityLow}); err != nil || adm.Discarded != DiscardRateLimit {
|
||||||
t.Errorf("zweiter low-Verwurf = %+v (%v)", adm, err)
|
t.Errorf("second low discard = %+v (%v)", adm, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
adm, err = q.Enqueue(Item{Text: "zweite"})
|
adm, err = q.Enqueue(Item{Text: "second"})
|
||||||
if err != nil || adm.ID == "" || adm.Discarded != "" {
|
if err != nil || adm.ID == "" || adm.Discarded != "" {
|
||||||
t.Fatalf("normal = %+v (%v), want Aufnahme (parkt bis zum Slot)", adm, err)
|
t.Fatalf("normal = %+v (%v), want admission (parks until the slot)", adm, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Status-Sicht während der erste läuft: zweite wartet (normal, geparkt).
|
// Status view while the first plays: second waits (normal, parked).
|
||||||
warteAuf(t, time.Second, func() bool {
|
waitForCond(t, time.Second, func() bool {
|
||||||
for _, it := range q.Pending() {
|
for _, it := range q.Pending() {
|
||||||
if it.Text == "zweite" {
|
if it.Text == "second" {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}, "geparkte normale Ansage in Pending")
|
}, "parked normal announcement in Pending")
|
||||||
|
|
||||||
close(g.step) // erste beenden — zweite muss weiter parken …
|
close(g.step) // end the first; second must keep parking …
|
||||||
g.keineWeitere(t)
|
g.noFurther(t)
|
||||||
// … und nach Fenster-Ablauf starten (Deadline deckt Jitter locker).
|
// … and start after the window elapses (deadline covers jitter easily).
|
||||||
gestartet := g.warteBis(t, 2)
|
started := g.waitUntil(t, 2)
|
||||||
if len(gestartet) != 1 || gestartet[0].Text != "zweite" {
|
if len(started) != 1 || started[0].Text != "second" {
|
||||||
t.Errorf("nach Fenster-Ablauf = %+v, will zweite", gestartet)
|
t.Errorf("after the window = %+v, want second", started)
|
||||||
}
|
}
|
||||||
// low-eins/low-zwei spielen nie: genau 2 Starts insgesamt.
|
// low-one/low-two never play: exactly 2 starts in total.
|
||||||
g.keineWeitere(t)
|
g.noFurther(t)
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestHighBurstEinUndAus: mit Burst-Recht startet high sofort nach der
|
// TestHighBurstOnAndOff: with burst rights high starts right after the
|
||||||
// laufenden Ansage, obwohl das Fenster voll ist; ohne Recht parkt high
|
// playing announcement although the window is full; without rights high
|
||||||
// wie normal (kein Verstoß).
|
// parks like normal (no violation).
|
||||||
func TestHighBurstEinUndAus(t *testing.T) {
|
func TestHighBurstOnAndOff(t *testing.T) {
|
||||||
g := neueSpielerin()
|
g := newSpeaker()
|
||||||
q := New(Laws{RateLimit: 10 * time.Second, AllowHighBurst: true}, g.speak, nil)
|
q := New(Laws{RateLimit: 10 * time.Second, AllowHighBurst: true}, g.speak, nil)
|
||||||
|
|
||||||
q.Enqueue(Item{Text: "erste"})
|
q.Enqueue(Item{Text: "first"})
|
||||||
g.warteBis(t, 1)
|
g.waitUntil(t, 1)
|
||||||
if adm, err := q.Enqueue(Item{Text: "dringend", Priority: PriorityHigh}); err != nil || adm.ID == "" {
|
if adm, err := q.Enqueue(Item{Text: "urgent", Priority: PriorityHigh}); err != nil || adm.ID == "" {
|
||||||
t.Fatalf("high mit Burst-Recht = %+v (%v), want Aufnahme", adm, err)
|
t.Fatalf("high with burst rights = %+v (%v), want admission", adm, err)
|
||||||
}
|
}
|
||||||
g.step <- struct{}{} // erste beenden
|
g.step <- struct{}{} // end the first
|
||||||
gestartet := g.warteBis(t, 2) // high startet trotz vollem Fenster
|
started := g.waitUntil(t, 2) // high starts despite the full window
|
||||||
if len(gestartet) != 1 || gestartet[0].Text != "dringend" {
|
if len(started) != 1 || started[0].Text != "urgent" {
|
||||||
t.Errorf("burst = %+v, will dringend sofort", gestartet)
|
t.Errorf("burst = %+v, want urgent right away", started)
|
||||||
}
|
}
|
||||||
q.Close()
|
q.Close()
|
||||||
|
|
||||||
g2 := neueSpielerin()
|
g2 := newSpeaker()
|
||||||
q2 := New(Laws{RateLimit: 10 * time.Second, AllowHighBurst: false}, g2.speak, nil)
|
q2 := New(Laws{RateLimit: 10 * time.Second, AllowHighBurst: false}, g2.speak, nil)
|
||||||
defer q2.Close()
|
defer q2.Close()
|
||||||
|
|
||||||
q2.Enqueue(Item{Text: "erste"})
|
q2.Enqueue(Item{Text: "first"})
|
||||||
g2.warteBis(t, 1) // erste läuft — Fenster gebucht
|
g2.waitUntil(t, 1) // first is playing, window booked
|
||||||
if adm, err := q2.Enqueue(Item{Text: "dringend", Priority: PriorityHigh}); err != nil || adm.ID == "" {
|
if adm, err := q2.Enqueue(Item{Text: "urgent", Priority: PriorityHigh}); err != nil || adm.ID == "" {
|
||||||
t.Fatalf("high ohne Burst-Recht = %+v (%v), want Aufnahme (parkt)", adm, err)
|
t.Fatalf("high without burst rights = %+v (%v), want admission (parks)", adm, err)
|
||||||
}
|
}
|
||||||
g2.step <- struct{}{} // erste beenden
|
g2.step <- struct{}{} // end the first
|
||||||
g2.keineWeitere(t) // high wartet den Slot ab — kein Verstoß ohne Recht
|
g2.noFurther(t) // high waits for the slot: no violation without rights
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestNowBypassesRateLimit: now startet trotz vollem Fensters sofort —
|
// TestNowBypassesRateLimit: now starts at once despite a full window, the
|
||||||
// der dokumentierte Ausbruch (er startet trotzdem ein neues Fenster).
|
// documented escape (it still books a new window).
|
||||||
func TestNowBypassesRateLimit(t *testing.T) {
|
func TestNowBypassesRateLimit(t *testing.T) {
|
||||||
g := neueSpielerin()
|
g := newSpeaker()
|
||||||
q := New(Laws{RateLimit: 10 * time.Second}, g.speak, nil)
|
q := New(Laws{RateLimit: 10 * time.Second}, g.speak, nil)
|
||||||
defer q.Close()
|
defer q.Close()
|
||||||
|
|
||||||
q.Enqueue(Item{Text: "erste"})
|
q.Enqueue(Item{Text: "first"})
|
||||||
g.warteBis(t, 1) // Fenster gebucht (10 s)
|
g.waitUntil(t, 1) // window booked (10 s)
|
||||||
|
|
||||||
if adm, err := q.Enqueue(Item{Text: "sofort", Now: true}); err != nil || adm.ID == "" || adm.Discarded != "" {
|
if adm, err := q.Enqueue(Item{Text: "right-now", Now: true}); err != nil || adm.ID == "" || adm.Discarded != "" {
|
||||||
t.Fatalf("now über vollem Fenster = %+v (%v), want Aufnahme", adm, err)
|
t.Fatalf("now over a full window = %+v (%v), want admission", adm, err)
|
||||||
}
|
}
|
||||||
g.step <- struct{}{}
|
g.step <- struct{}{}
|
||||||
gestartet := g.warteBis(t, 2) // lange vor Fenster-Ablauf (10 s) — sonst Timeout
|
started := g.waitUntil(t, 2) // long before the window elapses (10 s), else timeout
|
||||||
if len(gestartet) != 1 || gestartet[0].Text != "sofort" {
|
if len(started) != 1 || started[0].Text != "right-now" {
|
||||||
t.Errorf("now = %+v, will sofort", gestartet)
|
t.Errorf("now = %+v, want right-now", started)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Der now-Bruch hat ein neues Fenster gebucht: normal parkt jetzt.
|
// The now break-out booked a new window: normal parks now.
|
||||||
if adm, err := q.Enqueue(Item{Text: "danach"}); err != nil || adm.ID == "" {
|
if adm, err := q.Enqueue(Item{Text: "afterwards"}); err != nil || adm.ID == "" {
|
||||||
t.Fatalf("normal nach now = %+v (%v)", adm, err)
|
t.Fatalf("normal after now = %+v (%v)", adm, err)
|
||||||
}
|
}
|
||||||
close(g.step)
|
close(g.step)
|
||||||
g.keineWeitere(t) // parkt bis zum Slot — nicht sofort
|
g.noFurther(t) // parks until the slot, not immediately
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestRuhezeitDiscardUndToast: aktives Fenster verwirft normal und high
|
// TestQuietHoursDiscardAndToast: an active window discards normal and high
|
||||||
// (Burst ist ein Rate-Recht, kein Ruhe-Recht) — toast ersetzt stattdessen;
|
// (burst is a rate right, not a quiet right); toast replaces instead; now
|
||||||
// now bricht bewusst aus.
|
// deliberately breaks out.
|
||||||
func TestRuhezeitDiscardUndToast(t *testing.T) {
|
func TestQuietHoursDiscardAndToast(t *testing.T) {
|
||||||
fenster := fensterUm(time.Now())
|
window := windowAround(time.Now())
|
||||||
|
|
||||||
g := neueSpielerin()
|
g := newSpeaker()
|
||||||
q := New(Laws{Quiet: mustQuiet(t, fenster), QuietMode: QuietModeDiscard}, g.speak, nil)
|
q := New(Laws{Quiet: mustQuiet(t, window), QuietMode: QuietModeDiscard}, g.speak, nil)
|
||||||
defer q.Close()
|
defer q.Close()
|
||||||
|
|
||||||
adm, err := q.Enqueue(Item{Text: "normal"})
|
adm, err := q.Enqueue(Item{Text: "normal"})
|
||||||
if err != nil || adm.ID != "" || adm.Discarded != DiscardQuietHours || adm.Toast {
|
if err != nil || adm.ID != "" || adm.Discarded != DiscardQuietHours || adm.Toast {
|
||||||
t.Errorf("normal in Ruhezeit = %+v (%v), want stiller Verwurf", adm, err)
|
t.Errorf("normal in quiet hours = %+v (%v), want silent discard", adm, err)
|
||||||
}
|
}
|
||||||
if adm, err = q.Enqueue(Item{Text: "dringend", Priority: PriorityHigh}); err != nil || adm.Discarded != DiscardQuietHours {
|
if adm, err = q.Enqueue(Item{Text: "urgent", Priority: PriorityHigh}); err != nil || adm.Discarded != DiscardQuietHours {
|
||||||
t.Errorf("high in Ruhezeit = %+v (%v), want auch Verwurf", adm, err)
|
t.Errorf("high in quiet hours = %+v (%v), want discard too", adm, err)
|
||||||
}
|
}
|
||||||
adm, err = q.Enqueue(Item{Text: "sofort", Now: true})
|
adm, err = q.Enqueue(Item{Text: "right-now", Now: true})
|
||||||
if err != nil || adm.ID == "" || adm.Discarded != "" {
|
if err != nil || adm.ID == "" || adm.Discarded != "" {
|
||||||
t.Fatalf("now in Ruhezeit = %+v (%v), want Ausbruch", adm, err)
|
t.Fatalf("now in quiet hours = %+v (%v), want break-out", adm, err)
|
||||||
}
|
}
|
||||||
gestartet := g.warteBis(t, 1)
|
started := g.waitUntil(t, 1)
|
||||||
if len(gestartet) != 1 || gestartet[0].Text != "sofort" {
|
if len(started) != 1 || started[0].Text != "right-now" {
|
||||||
t.Errorf("in Ruhezeit = %+v, will nur sofort", gestartet)
|
t.Errorf("in quiet hours = %+v, want only right-now", started)
|
||||||
}
|
}
|
||||||
g.keineWeitere(t)
|
g.noFurther(t)
|
||||||
|
|
||||||
g2 := neueSpielerin()
|
g2 := newSpeaker()
|
||||||
q2 := New(Laws{Quiet: mustQuiet(t, fenster), QuietMode: QuietModeToast}, g2.speak, nil)
|
q2 := New(Laws{Quiet: mustQuiet(t, window), QuietMode: QuietModeToast}, g2.speak, nil)
|
||||||
defer q2.Close()
|
defer q2.Close()
|
||||||
|
|
||||||
|
toasted := make(chan Item, 1)
|
||||||
|
q2.OnToast(func(it Item) { toasted <- it })
|
||||||
adm, err = q2.Enqueue(Item{Text: "normal"})
|
adm, err = q2.Enqueue(Item{Text: "normal"})
|
||||||
if err != nil || adm.Discarded != DiscardQuietHours || !adm.Toast {
|
if err != nil || adm.Discarded != DiscardQuietHours || !adm.Toast {
|
||||||
t.Errorf("normal in Ruhezeit (toast) = %+v (%v), want Toast-Ersetzung", adm, err)
|
t.Errorf("normal in quiet hours (toast) = %+v (%v), want toast replacement", adm, err)
|
||||||
}
|
}
|
||||||
g2.keineWeitere(t)
|
select {
|
||||||
|
case it := <-toasted:
|
||||||
|
if it.Text != "normal" {
|
||||||
|
t.Errorf("toast hook got %q", it.Text)
|
||||||
|
}
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Error("toast hook not fired")
|
||||||
|
}
|
||||||
|
g2.noFurther(t)
|
||||||
}
|
}
|
||||||
|
|
||||||
// mustQuiet parst ein Ruhefenster oder bricht den Test ab.
|
// mustQuiet parses a quiet window or fails the test.
|
||||||
func mustQuiet(t *testing.T, fenster string) QuietHours {
|
func mustQuiet(t *testing.T, window string) QuietHours {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
q, err := ParseQuietHours(fenster)
|
q, err := ParseQuietHours(window)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
return q
|
return q
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestLawState: unbegrenzt liefert freien Slot; nach gebuchtem Fenster
|
// TestLawState: unlimited yields an open slot; after a booked window the
|
||||||
// liegt der nächste Slot in der Zukunft; Ruhezeit-Fenster ist sichtbar.
|
// next slot lies in the future; the quiet window and limits are visible.
|
||||||
func TestLawState(t *testing.T) {
|
func TestLawState(t *testing.T) {
|
||||||
g := neueSpielerin()
|
g := newSpeaker()
|
||||||
q := New(Laws{}, g.speak, nil)
|
q := New(Laws{}, g.speak, nil)
|
||||||
st := q.LawState()
|
st := q.LawState()
|
||||||
if !st.NextSlot.IsZero() || st.RateLimit != 0 {
|
if !st.NextSlot.IsZero() || st.RateLimit != 0 {
|
||||||
t.Errorf("unbegrenzt = %+v, want Nullzeit-Slot", st)
|
t.Errorf("unlimited = %+v, want zero-time slot", st)
|
||||||
}
|
}
|
||||||
q.Close()
|
q.Close()
|
||||||
|
|
||||||
// Das Ruhezeit-Fenster muss JETZT inaktiv sein, sonst würde die Ansage
|
// The quiet window must be inactive NOW, otherwise the announcement
|
||||||
// unten getoastet statt gesprochen — ein festes Fenster wäre eine
|
// below would be toasted instead of spoken. A fixed window would be a
|
||||||
// Zeitbombe (rot zu bestimmten Tageszeiten). Deshalb dynamisch: eine
|
// time bomb (red at certain hours), hence dynamic: one hour starting two
|
||||||
// Stunde, die zwei Stunden in der Zukunft beginnt.
|
// hours from now.
|
||||||
window := inactiveQuietWindow(time.Now())
|
window := inactiveQuietWindow(time.Now())
|
||||||
fenster := mustQuiet(t, window)
|
quiet := mustQuiet(t, window)
|
||||||
if fenster.Active(time.Now()) {
|
if quiet.Active(time.Now()) {
|
||||||
t.Fatalf("Testfenster %s ist aktiv — darf nicht sein", window)
|
t.Fatalf("test window %s is active, must not be", window)
|
||||||
}
|
}
|
||||||
q2 := New(Laws{RateLimit: time.Hour, AllowHighBurst: true, Quiet: fenster, QuietMode: QuietModeToast}, g.speak, nil)
|
q2 := New(Laws{RateLimit: time.Hour, AllowHighBurst: true, Quiet: quiet, QuietMode: QuietModeToast, MaxText: 400, MaxAge: 2 * time.Minute}, g.speak, nil)
|
||||||
defer q2.Close()
|
defer q2.Close()
|
||||||
st2 := q2.LawState()
|
st2 := q2.LawState()
|
||||||
if st2.RateLimit != time.Hour || !st2.AllowHighBurst {
|
if st2.RateLimit != time.Hour || !st2.AllowHighBurst || st2.MaxText != 400 || st2.MaxAge != 2*time.Minute {
|
||||||
t.Errorf("LawState = %+v, want 1h-Fenster mit Burst-Recht", st2)
|
t.Errorf("LawState = %+v, want 1h window with burst rights and limits 400/2m", st2)
|
||||||
}
|
}
|
||||||
if st2.Quiet.String() != window || st2.QuietMode != QuietModeToast {
|
if st2.Quiet.String() != window || st2.QuietMode != QuietModeToast {
|
||||||
t.Errorf("Ruhezeit in LawState = %q/%q, want %q/toast", st2.Quiet, st2.QuietMode, window)
|
t.Errorf("quiet hours in LawState = %q/%q, want %q/toast", st2.Quiet, st2.QuietMode, window)
|
||||||
}
|
}
|
||||||
if st2.QuietActive || !st2.QuietUntil.IsZero() {
|
if st2.QuietActive || !st2.QuietUntil.IsZero() {
|
||||||
t.Errorf("Ruhezeit inaktiv erwartet, LawState meldet active=%v until=%v", st2.QuietActive, st2.QuietUntil)
|
t.Errorf("quiet hours expected inactive, LawState reports active=%v until=%v", st2.QuietActive, st2.QuietUntil)
|
||||||
}
|
}
|
||||||
|
|
||||||
q2.Enqueue(Item{Text: "erste"})
|
q2.Enqueue(Item{Text: "first"})
|
||||||
g.warteBis(t, 1)
|
g.waitUntil(t, 1)
|
||||||
if next := q2.LawState().NextSlot; !next.After(time.Now()) {
|
if next := q2.LawState().NextSlot; !next.After(time.Now()) {
|
||||||
t.Errorf("nach Start = %v, want Slot in der Zukunft", next)
|
t.Errorf("after start = %v, want slot in the future", next)
|
||||||
}
|
}
|
||||||
g.step <- struct{}{}
|
g.step <- struct{}{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// inactiveQuietWindow liefert ein "HH:MM-HH:MM"-Fenster von einer Stunde,
|
// inactiveQuietWindow returns a one-hour "HH:MM-HH:MM" window starting two
|
||||||
// das zwei Stunden nach now beginnt — es enthält now garantiert nicht, egal
|
// hours after now; it never contains now, whatever the time of day (also
|
||||||
// zu welcher Tageszeit der Test läuft (auch über Mitternacht hinweg).
|
// across midnight).
|
||||||
func inactiveQuietWindow(now time.Time) string {
|
func inactiveQuietWindow(now time.Time) string {
|
||||||
start := now.Add(2 * time.Hour)
|
start := now.Add(2 * time.Hour)
|
||||||
end := now.Add(3 * time.Hour)
|
end := now.Add(3 * time.Hour)
|
||||||
return start.Format("15:04") + "-" + end.Format("15:04")
|
return start.Format("15:04") + "-" + end.Format("15:04")
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestInactiveQuietWindow: Das Test-Hilfsfenster darf zu KEINER Tageszeit
|
// TestInactiveQuietWindow: the helper window must not be active at ANY time
|
||||||
// aktiv sein — sonst wäre TestLawState wieder eine Zeitbombe.
|
// of day, otherwise TestLawState would be a time bomb again.
|
||||||
func TestInactiveQuietWindow(t *testing.T) {
|
func TestInactiveQuietWindow(t *testing.T) {
|
||||||
base := time.Date(2026, 10, 24, 0, 0, 0, 0, time.Local)
|
base := time.Date(2026, 10, 24, 0, 0, 0, 0, time.Local)
|
||||||
for m := 0; m < 24*60; m += 7 {
|
for m := 0; m < 24*60; m += 7 {
|
||||||
@@ -550,12 +557,12 @@ func TestInactiveQuietWindow(t *testing.T) {
|
|||||||
t.Fatalf("%s: %v", now.Format("15:04"), err)
|
t.Fatalf("%s: %v", now.Format("15:04"), err)
|
||||||
}
|
}
|
||||||
if q.Active(now) {
|
if q.Active(now) {
|
||||||
t.Errorf("um %s ist Fenster %s aktiv", now.Format("15:04"), w)
|
t.Errorf("at %s the window %s is active", now.Format("15:04"), w)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// syncLog ist ein nebenläufigkeitssicherer Log-Puffer für Worker-Zeilen.
|
// syncLog is a concurrency-safe log buffer for worker lines.
|
||||||
type syncLog struct {
|
type syncLog struct {
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
b strings.Builder
|
b strings.Builder
|
||||||
@@ -573,38 +580,65 @@ func (l *syncLog) String() string {
|
|||||||
return l.b.String()
|
return l.b.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestProtokollFertigNichtAbgebrochen: Eine normal beendete Ansage wird als
|
// TestLogFinishedNotCancelled: a normally finished announcement is logged as
|
||||||
// „fertig" protokolliert, nicht als „abgebrochen" — der Worker darf seinen
|
// "finished", not "cancelled"; the worker must not read its own cancel() as
|
||||||
// eigenen cancel() nicht als Abbruch deuten. Ein echter Cancel heißt
|
// a cancellation. A real Cancel does log "cancelled".
|
||||||
// dagegen „abgebrochen".
|
func TestLogFinishedNotCancelled(t *testing.T) {
|
||||||
func TestProtokollFertigNichtAbgebrochen(t *testing.T) {
|
|
||||||
logb := &syncLog{}
|
logb := &syncLog{}
|
||||||
g := neueSpielerin()
|
g := newSpeaker()
|
||||||
q := New(Laws{}, g.speak, logb)
|
q := New(Laws{}, g.speak, logb)
|
||||||
defer q.Close()
|
defer q.Close()
|
||||||
|
|
||||||
q.Enqueue(Item{Text: "normal zu ende"})
|
q.Enqueue(Item{Text: "runs to the end"})
|
||||||
g.warteBis(t, 1)
|
g.waitUntil(t, 1)
|
||||||
g.step <- struct{}{}
|
g.step <- struct{}{}
|
||||||
waitFor(t, func() bool { return strings.Contains(logb.String(), "fertig nach") })
|
waitFor(t, func() bool { return strings.Contains(logb.String(), "finished after") })
|
||||||
if strings.Contains(logb.String(), "abgebrochen") {
|
if strings.Contains(logb.String(), "cancelled") {
|
||||||
t.Errorf("fertige Ansage als abgebrochen protokolliert:\n%s", logb.String())
|
t.Errorf("finished announcement logged as cancelled:\n%s", logb.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
q.Enqueue(Item{Text: "wird abgebrochen"})
|
q.Enqueue(Item{Text: "gets cancelled"})
|
||||||
g.warteBis(t, 2)
|
g.waitUntil(t, 2)
|
||||||
q.Cancel()
|
q.Cancel()
|
||||||
waitFor(t, func() bool { return strings.Contains(logb.String(), "abgebrochen") })
|
waitFor(t, func() bool { return strings.Contains(logb.String(), "cancelled") })
|
||||||
}
|
}
|
||||||
|
|
||||||
// waitFor pollt cond bis zu zwei Sekunden.
|
// waitFor polls cond for up to two seconds.
|
||||||
func waitFor(t *testing.T, cond func() bool) {
|
func waitFor(t *testing.T, cond func() bool) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
deadline := time.Now().Add(2 * time.Second)
|
deadline := time.Now().Add(2 * time.Second)
|
||||||
for !cond() {
|
for !cond() {
|
||||||
if time.Now().After(deadline) {
|
if time.Now().After(deadline) {
|
||||||
t.Fatal("Bedingung nicht binnen 2 s erfüllt")
|
t.Fatal("condition not met within 2 s")
|
||||||
}
|
}
|
||||||
time.Sleep(5 * time.Millisecond)
|
time.Sleep(5 * time.Millisecond)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestCancelItem: cancels only the playing item with that id; a stale id or
|
||||||
|
// a waiting item is a no-op, the queue goes on with the next item.
|
||||||
|
func TestCancelItem(t *testing.T) {
|
||||||
|
g := newSpeaker()
|
||||||
|
q := New(Laws{}, g.speak, nil)
|
||||||
|
defer q.Close()
|
||||||
|
|
||||||
|
first, _ := q.Enqueue(Item{Text: "playing"})
|
||||||
|
g.waitUntil(t, 1)
|
||||||
|
second, _ := q.Enqueue(Item{Text: "waiting"})
|
||||||
|
|
||||||
|
if q.CancelItem(second.ID) {
|
||||||
|
t.Error("CancelItem on a waiting item reported a hit")
|
||||||
|
}
|
||||||
|
if q.CancelItem("nosuch") {
|
||||||
|
t.Error("CancelItem with an unknown id reported a hit")
|
||||||
|
}
|
||||||
|
if !q.CancelItem(first.ID) {
|
||||||
|
t.Fatal("CancelItem on the playing item reported no hit")
|
||||||
|
}
|
||||||
|
// The playing item ended via ctx; the waiting one starts next.
|
||||||
|
started := g.waitUntil(t, 2)
|
||||||
|
if len(started) != 1 || started[0].ID != second.ID {
|
||||||
|
t.Errorf("after CancelItem started = %+v, want the waiting item", started)
|
||||||
|
}
|
||||||
|
g.step <- struct{}{}
|
||||||
|
}
|
||||||
+24
-24
@@ -7,29 +7,29 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Erlaubte Werte für quiet_mode (öffentlicher Config-Wert).
|
// Allowed values for quiet_mode (public config value).
|
||||||
const (
|
const (
|
||||||
QuietModeDiscard = "discard"
|
QuietModeDiscard = "discard"
|
||||||
QuietModeToast = "toast"
|
QuietModeToast = "toast"
|
||||||
)
|
)
|
||||||
|
|
||||||
// clockTime ist eine Tageszeit in Minuten-Auflösung (lokale Zeit, 24 h).
|
// clockTime is a time of day at minute resolution (local time, 24 h).
|
||||||
type clockTime struct{ hour, minute int }
|
type clockTime struct{ hour, minute int }
|
||||||
|
|
||||||
// minutes liefert Minuten seit Mitternacht.
|
// minutes returns minutes since midnight.
|
||||||
func (c clockTime) minutes() int { return c.hour*60 + c.minute }
|
func (c clockTime) minutes() int { return c.hour*60 + c.minute }
|
||||||
|
|
||||||
// String rendert die Uhrzeit als "HH:MM".
|
// String renders the time as "HH:MM".
|
||||||
func (c clockTime) String() string { return fmt.Sprintf("%02d:%02d", c.hour, c.minute) }
|
func (c clockTime) String() string { return fmt.Sprintf("%02d:%02d", c.hour, c.minute) }
|
||||||
|
|
||||||
// QuietHours ist ein Ruhezeit-Fenster in lokaler Zeit, z. B. "18:00-08:00"
|
// QuietHours is a quiet window in local time, for example "18:00-08:00"
|
||||||
// (überspannt Mitternacht). Der Nullwert (Start == End) ist deaktiviert —
|
// (spanning midnight). The zero value (Start == End) is disabled; silence
|
||||||
// rund-um-die-Uhr-Stumm ist mute, nicht quiet_hours.
|
// around the clock is mute, not quiet hours.
|
||||||
type QuietHours struct {
|
type QuietHours struct {
|
||||||
Start, End clockTime
|
Start, End clockTime
|
||||||
}
|
}
|
||||||
|
|
||||||
// String rendert das Fenster als "HH:MM-HH:MM" (Nullwert: "").
|
// String renders the window as "HH:MM-HH:MM" (zero value: "").
|
||||||
func (q QuietHours) String() string {
|
func (q QuietHours) String() string {
|
||||||
if q.Start == q.End {
|
if q.Start == q.End {
|
||||||
return ""
|
return ""
|
||||||
@@ -37,17 +37,17 @@ func (q QuietHours) String() string {
|
|||||||
return q.Start.String() + "-" + q.End.String()
|
return q.Start.String() + "-" + q.End.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseQuietHours parst ein Ruhezeit-Fenster "HH:MM-HH:MM" (lokale Zeit,
|
// ParseQuietHours parses a quiet window "HH:MM-HH:MM" (local time, 24 h;
|
||||||
// 24 h; Stunden ein- oder zweistellig). Fenster über Mitternacht
|
// hours with one or two digits). Windows across midnight (Start > End) are
|
||||||
// (Start > End) sind erlaubt; Start == End deaktiviert das Fenster. Der
|
// allowed; Start == End disables the window. The empty string is the
|
||||||
// Leerstring ist das deaktivierte Fenster (kein Fehler).
|
// disabled window (no error).
|
||||||
func ParseQuietHours(s string) (QuietHours, error) {
|
func ParseQuietHours(s string) (QuietHours, error) {
|
||||||
if s == "" {
|
if s == "" {
|
||||||
return QuietHours{}, nil
|
return QuietHours{}, nil
|
||||||
}
|
}
|
||||||
startS, endS, ok := strings.Cut(s, "-")
|
startS, endS, ok := strings.Cut(s, "-")
|
||||||
if !ok {
|
if !ok {
|
||||||
return QuietHours{}, fmt.Errorf("quiet_hours: %q ist nicht HH:MM-HH:MM", s)
|
return QuietHours{}, fmt.Errorf("quiet_hours: %q is not HH:MM-HH:MM", s)
|
||||||
}
|
}
|
||||||
start, err := parseClock(startS)
|
start, err := parseClock(startS)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -60,29 +60,29 @@ func ParseQuietHours(s string) (QuietHours, error) {
|
|||||||
return QuietHours{Start: start, End: end}, nil
|
return QuietHours{Start: start, End: end}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// parseClock parst "H[H]:MM" in Uhrzeit-Bestandteile.
|
// parseClock parses "H[H]:MM" into its parts.
|
||||||
func parseClock(s string) (clockTime, error) {
|
func parseClock(s string) (clockTime, error) {
|
||||||
hourS, minuteS, ok := strings.Cut(s, ":")
|
hourS, minuteS, ok := strings.Cut(s, ":")
|
||||||
if !ok || len(hourS) < 1 || len(hourS) > 2 || len(minuteS) != 2 {
|
if !ok || len(hourS) < 1 || len(hourS) > 2 || len(minuteS) != 2 {
|
||||||
return clockTime{}, fmt.Errorf("%q ist nicht HH:MM", s)
|
return clockTime{}, fmt.Errorf("%q is not HH:MM", s)
|
||||||
}
|
}
|
||||||
hour, err := strconv.Atoi(hourS)
|
hour, err := strconv.Atoi(hourS)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return clockTime{}, fmt.Errorf("%q ist nicht HH:MM", s)
|
return clockTime{}, fmt.Errorf("%q is not HH:MM", s)
|
||||||
}
|
}
|
||||||
minute, err := strconv.Atoi(minuteS)
|
minute, err := strconv.Atoi(minuteS)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return clockTime{}, fmt.Errorf("%q ist nicht HH:MM", s)
|
return clockTime{}, fmt.Errorf("%q is not HH:MM", s)
|
||||||
}
|
}
|
||||||
if hour < 0 || hour > 23 || minute < 0 || minute > 59 {
|
if hour < 0 || hour > 23 || minute < 0 || minute > 59 {
|
||||||
return clockTime{}, fmt.Errorf("%q ist keine gültige Uhrzeit (24 h)", s)
|
return clockTime{}, fmt.Errorf("%q is not a valid time of day (24 h)", s)
|
||||||
}
|
}
|
||||||
return clockTime{hour: hour, minute: minute}, nil
|
return clockTime{hour: hour, minute: minute}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Active meldet, ob der lokale Zeitpunkt t im Ruhefenster liegt.
|
// Active reports whether the local time t lies inside the window. Day
|
||||||
// Tagfenster (Start < End) gelten ab Start bis ausschließlich End;
|
// windows (Start < End) run from Start up to but excluding End; night
|
||||||
// Nachtfenster (Start > End) überspannen Mitternacht.
|
// windows (Start > End) span midnight.
|
||||||
func (q QuietHours) Active(t time.Time) bool {
|
func (q QuietHours) Active(t time.Time) bool {
|
||||||
if q.Start == q.End {
|
if q.Start == q.End {
|
||||||
return false
|
return false
|
||||||
@@ -95,15 +95,15 @@ func (q QuietHours) Active(t time.Time) bool {
|
|||||||
return m >= s || m < e
|
return m >= s || m < e
|
||||||
}
|
}
|
||||||
|
|
||||||
// Until liefert das lokale Ende des gerade aktiven Fensters — Nullzeit,
|
// Until returns the local end of the currently active window; the zero time
|
||||||
// wenn gerade kein Ruhefenster aktiv ist. Basis für GET /status.
|
// when no window is active. Basis for GET /status.
|
||||||
func (q QuietHours) Until(t time.Time) time.Time {
|
func (q QuietHours) Until(t time.Time) time.Time {
|
||||||
if !q.Active(t) {
|
if !q.Active(t) {
|
||||||
return time.Time{}
|
return time.Time{}
|
||||||
}
|
}
|
||||||
end := time.Date(t.Year(), t.Month(), t.Day(), q.End.hour, q.End.minute, 0, 0, t.Location())
|
end := time.Date(t.Year(), t.Month(), t.Day(), q.End.hour, q.End.minute, 0, 0, t.Location())
|
||||||
if q.Start.minutes() > q.End.minutes() && t.Hour()*60+t.Minute() >= q.Start.minutes() {
|
if q.Start.minutes() > q.End.minutes() && t.Hour()*60+t.Minute() >= q.Start.minutes() {
|
||||||
end = end.AddDate(0, 0, 1) // Nachtfenster: das Ende ist am Folgetag
|
end = end.AddDate(0, 0, 1) // night window: the end is tomorrow
|
||||||
}
|
}
|
||||||
return end
|
return end
|
||||||
}
|
}
|
||||||
@@ -5,14 +5,14 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// lokal baut eine lokale Test-Zeit (Stunde/Minute reichen — Ruhefenster
|
// local builds a local test time (hour and minute suffice; quiet windows
|
||||||
// arbeiten auf Minuten-Auflösung).
|
// work at minute resolution).
|
||||||
func lokal(hour, minute int) time.Time {
|
func local(hour, minute int) time.Time {
|
||||||
return time.Date(2026, 10, 18, hour, minute, 0, 0, time.Local)
|
return time.Date(2026, 10, 18, hour, minute, 0, 0, time.Local)
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestParseQuietHours: Format HH:MM-HH:MM (überspannt Mitternacht),
|
// TestParseQuietHours: format HH:MM-HH:MM (may span midnight), clear errors
|
||||||
// klare Fehler für Müll.
|
// for garbage.
|
||||||
func TestParseQuietHours(t *testing.T) {
|
func TestParseQuietHours(t *testing.T) {
|
||||||
cases := []struct {
|
cases := []struct {
|
||||||
in string
|
in string
|
||||||
@@ -23,8 +23,8 @@ func TestParseQuietHours(t *testing.T) {
|
|||||||
{in: "18:00-08:00", start: clockTime{18, 0}, end: clockTime{8, 0}},
|
{in: "18:00-08:00", start: clockTime{18, 0}, end: clockTime{8, 0}},
|
||||||
{in: "9:30-17:45", start: clockTime{9, 30}, end: clockTime{17, 45}},
|
{in: "9:30-17:45", start: clockTime{9, 30}, end: clockTime{17, 45}},
|
||||||
{in: "22:00-06:00", start: clockTime{22, 0}, end: clockTime{6, 0}},
|
{in: "22:00-06:00", start: clockTime{22, 0}, end: clockTime{6, 0}},
|
||||||
{in: "08:00-08:00", start: clockTime{8, 0}, end: clockTime{8, 0}}, // deaktiviert, aber gültig
|
{in: "08:00-08:00", start: clockTime{8, 0}, end: clockTime{8, 0}}, // disabled but valid
|
||||||
{in: ""}, // Leerstring = deaktiviert, kein Fehler
|
{in: ""}, // empty = disabled, no error
|
||||||
{in: "18:00", bad: true},
|
{in: "18:00", bad: true},
|
||||||
{in: "18:00-", bad: true},
|
{in: "18:00-", bad: true},
|
||||||
{in: "-08:00", bad: true},
|
{in: "-08:00", bad: true},
|
||||||
@@ -37,12 +37,12 @@ func TestParseQuietHours(t *testing.T) {
|
|||||||
q, err := ParseQuietHours(tc.in)
|
q, err := ParseQuietHours(tc.in)
|
||||||
if tc.bad {
|
if tc.bad {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Errorf("ParseQuietHours(%q) = %+v, want Fehler", tc.in, q)
|
t.Errorf("ParseQuietHours(%q) = %+v, want error", tc.in, q)
|
||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("ParseQuietHours(%q): unerwarteter Fehler %v", tc.in, err)
|
t.Errorf("ParseQuietHours(%q): unexpected error %v", tc.in, err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if q.Start != tc.start || q.End != tc.end {
|
if q.Start != tc.start || q.End != tc.end {
|
||||||
@@ -51,69 +51,70 @@ func TestParseQuietHours(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestQuietHoursActive: Tagfenster, Nachtfenster über Mitternacht und der
|
// TestQuietHoursActive: day window, night window across midnight and the
|
||||||
// deaktivierte Nullwert über alle Grenzen (Start inklusiv, End exklusiv).
|
// disabled zero value across all boundaries (start inclusive, end
|
||||||
|
// exclusive).
|
||||||
func TestQuietHoursActive(t *testing.T) {
|
func TestQuietHoursActive(t *testing.T) {
|
||||||
cases := []struct {
|
cases := []struct {
|
||||||
fenster string
|
window string
|
||||||
hour, minute int
|
hour, minute int
|
||||||
want bool
|
want bool
|
||||||
}{
|
}{
|
||||||
// Tagfenster 09:00-17:00
|
// day window 09:00-17:00
|
||||||
{"09:00-17:00", 8, 59, false},
|
{"09:00-17:00", 8, 59, false},
|
||||||
{"09:00-17:00", 9, 0, true}, // Start inklusiv
|
{"09:00-17:00", 9, 0, true}, // start inclusive
|
||||||
{"09:00-17:00", 12, 30, true},
|
{"09:00-17:00", 12, 30, true},
|
||||||
{"09:00-17:00", 16, 59, true},
|
{"09:00-17:00", 16, 59, true},
|
||||||
{"09:00-17:00", 17, 0, false}, // End exklusiv
|
{"09:00-17:00", 17, 0, false}, // end exclusive
|
||||||
{"09:00-17:00", 23, 0, false},
|
{"09:00-17:00", 23, 0, false},
|
||||||
// Nachtfenster 18:00-08:00 (überspannt Mitternacht)
|
// night window 18:00-08:00 (spans midnight)
|
||||||
{"18:00-08:00", 17, 59, false},
|
{"18:00-08:00", 17, 59, false},
|
||||||
{"18:00-08:00", 18, 0, true},
|
{"18:00-08:00", 18, 0, true},
|
||||||
{"18:00-08:00", 23, 59, true},
|
{"18:00-08:00", 23, 59, true},
|
||||||
{"18:00-08:00", 0, 0, true}, // über Mitternacht
|
{"18:00-08:00", 0, 0, true}, // past midnight
|
||||||
{"18:00-08:00", 7, 59, true},
|
{"18:00-08:00", 7, 59, true},
|
||||||
{"18:00-08:00", 8, 0, false}, // End exklusiv
|
{"18:00-08:00", 8, 0, false}, // end exclusive
|
||||||
{"18:00-08:00", 12, 0, false},
|
{"18:00-08:00", 12, 0, false},
|
||||||
// Zweites Nachtfenster
|
// another night window
|
||||||
{"22:00-06:00", 3, 0, true},
|
{"22:00-06:00", 3, 0, true},
|
||||||
{"22:00-06:00", 21, 59, false},
|
{"22:00-06:00", 21, 59, false},
|
||||||
// Start == End: deaktiviert
|
// start == end: disabled
|
||||||
{"08:00-08:00", 8, 0, false},
|
{"08:00-08:00", 8, 0, false},
|
||||||
{"08:00-08:00", 20, 0, false},
|
{"08:00-08:00", 20, 0, false},
|
||||||
}
|
}
|
||||||
for _, tc := range cases {
|
for _, tc := range cases {
|
||||||
q := mustQuiet(t, tc.fenster)
|
q := mustQuiet(t, tc.window)
|
||||||
if got := q.Active(lokal(tc.hour, tc.minute)); got != tc.want {
|
if got := q.Active(local(tc.hour, tc.minute)); got != tc.want {
|
||||||
t.Errorf("%s um %02d:%02d: Active = %v, want %v", tc.fenster, tc.hour, tc.minute, got, tc.want)
|
t.Errorf("%s at %02d:%02d: Active = %v, want %v", tc.window, tc.hour, tc.minute, got, tc.want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestQuietHoursUntil: Fenster-Ende (heute bzw. morgen bei Nachtfenstern),
|
// TestQuietHoursUntil: window end (today, or tomorrow for night windows),
|
||||||
// Nullzeit wenn inaktiv.
|
// zero time when inactive.
|
||||||
func TestQuietHoursUntil(t *testing.T) {
|
func TestQuietHoursUntil(t *testing.T) {
|
||||||
// Tagfenster: Ende heute.
|
// Day window: ends today.
|
||||||
q := mustQuiet(t, "09:00-17:00")
|
q := mustQuiet(t, "09:00-17:00")
|
||||||
if want := lokal(17, 0); !q.Until(lokal(12, 0)).Equal(want) {
|
if want := local(17, 0); !q.Until(local(12, 0)).Equal(want) {
|
||||||
t.Errorf("Until(12:00) = %v, want %v (heute 17:00)", q.Until(lokal(12, 0)), want)
|
t.Errorf("Until(12:00) = %v, want %v (today 17:00)", q.Until(local(12, 0)), want)
|
||||||
}
|
}
|
||||||
if !q.Until(lokal(3, 0)).IsZero() {
|
if !q.Until(local(3, 0)).IsZero() {
|
||||||
t.Error("Until außerhalb des Fensters: want Nullzeit")
|
t.Error("Until outside the window: want zero time")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Nachtfenster: ab 18:00 ist das Ende morgen früh.
|
// Night window: from 18:00 the end is tomorrow morning.
|
||||||
n := mustQuiet(t, "18:00-08:00")
|
n := mustQuiet(t, "18:00-08:00")
|
||||||
if want := lokal(0, 0).Add(32 * time.Hour); !n.Until(lokal(20, 0)).Equal(want) {
|
if want := local(0, 0).Add(32 * time.Hour); !n.Until(local(20, 0)).Equal(want) {
|
||||||
t.Errorf("Until(20:00) = %v, want %v (morgen 08:00)", n.Until(lokal(20, 0)), want)
|
t.Errorf("Until(20:00) = %v, want %v (tomorrow 08:00)", n.Until(local(20, 0)), want)
|
||||||
}
|
}
|
||||||
// Nach Mitternacht (00:30) ist das Ende heute 08:00.
|
// Past midnight (00:30) the end is today 08:00.
|
||||||
if want := lokal(8, 0); !n.Until(lokal(0, 30)).Equal(want) {
|
if want := local(8, 0); !n.Until(local(0, 30)).Equal(want) {
|
||||||
t.Errorf("Until(00:30) = %v, want %v (heute 08:00)", n.Until(lokal(0, 30)), want)
|
t.Errorf("Until(00:30) = %v, want %v (today 08:00)", n.Until(local(0, 30)), want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestQuietHoursStringRoundtrip: String liefert die konfigurierte Form
|
// TestQuietHoursStringRoundtrip: String returns the configured form and
|
||||||
// zurück und parst identisch; der Nullwert rendert leer.
|
// parses back identically; the zero value renders empty.
|
||||||
func TestQuietHoursStringRoundtrip(t *testing.T) {
|
func TestQuietHoursStringRoundtrip(t *testing.T) {
|
||||||
for _, s := range []string{"18:00-08:00", "09:00-17:00", "22:00-06:00"} {
|
for _, s := range []string{"18:00-08:00", "09:00-17:00", "22:00-06:00"} {
|
||||||
q := mustQuiet(t, s)
|
q := mustQuiet(t, s)
|
||||||
@@ -122,10 +123,10 @@ func TestQuietHoursStringRoundtrip(t *testing.T) {
|
|||||||
}
|
}
|
||||||
q2 := mustQuiet(t, q.String())
|
q2 := mustQuiet(t, q.String())
|
||||||
if q2 != q {
|
if q2 != q {
|
||||||
t.Errorf("Roundtrip von %q: %+v ≠ %+v", s, q2, q)
|
t.Errorf("round trip of %q: %+v != %+v", s, q2, q)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (QuietHours{}).String() != "" {
|
if (QuietHours{}).String() != "" {
|
||||||
t.Error("Nullwert-String nicht leer")
|
t.Error("zero value String is not empty")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+79
-82
@@ -7,32 +7,32 @@ import (
|
|||||||
"unicode"
|
"unicode"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Verwurfs-Gründe im HTTP-Vertrag von POST /speak
|
// Discard reasons in the HTTP contract of POST /speak
|
||||||
// (202 {"id":"","discarded":"…"}).
|
// (202 {"id":"","discarded":"…"}).
|
||||||
const (
|
const (
|
||||||
DiscardRateLimit = "rate_limit" // priority=low über dem Fenster-Budget
|
DiscardRateLimit = "rate_limit" // priority=low over the window budget
|
||||||
DiscardQuietHours = "quiet_hours" // Ruhezeit aktiv (discard oder toast)
|
DiscardQuietHours = "quiet_hours" // quiet hours active (discard or toast)
|
||||||
DiscardExpired = "expired" // länger gewartet als queue.max_age (Ansage wäre veraltet)
|
DiscardExpired = "expired" // waited longer than queue.max_age (stale)
|
||||||
)
|
)
|
||||||
|
|
||||||
// RateLimiter ist das Zeitfenster des Daemon-Gesetzes gegen Ansage-Spam:
|
// RateLimiter is the time window of the daemon's anti-spam law: default
|
||||||
// Spec-Default ca. 1 Ansage / 30 s (queue.rate_limit), 0 = unbegrenzt.
|
// about one announcement per 30 s (queue.rate_limit), 0 = unlimited. Every
|
||||||
// Jede gestartete Ansage bucht das Fenster neu (Reserve) — auch eine per
|
// started announcement books the window anew (Reserve), including ones that
|
||||||
// now oder high-burst ausgebrochene: Das Fenster zählt Abspiel-Starts,
|
// broke out via now or high burst: the window counts playback starts, not
|
||||||
// nicht deren Legitimität.
|
// their legitimacy.
|
||||||
//
|
//
|
||||||
// Lock-Ordnung: RateLimiter.mu ist immer die innere Sperre — Aufrufer
|
// Lock order: RateLimiter.mu is always the inner lock; callers hold the
|
||||||
// halten beim Allow/Reserve/Next die Queue-sperre (niemals umgekehrt).
|
// queue lock during Allow/Reserve/Next, never the other way round.
|
||||||
type RateLimiter struct {
|
type RateLimiter struct {
|
||||||
// Interval ist der Mindestabstand zwischen zwei Ansage-Starten.
|
// Interval is the minimum gap between two announcement starts. 0 or
|
||||||
// 0 oder negativ = unbegrenzt.
|
// negative = unlimited.
|
||||||
Interval time.Duration
|
Interval time.Duration
|
||||||
|
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
last time.Time // Start der zuletzt per Reserve gebuchten Ansage
|
last time.Time // start of the announcement last booked via Reserve
|
||||||
}
|
}
|
||||||
|
|
||||||
// Allow meldet, ob sofort eine Ansage starten dürfte.
|
// Allow reports whether an announcement could start right now.
|
||||||
func (l *RateLimiter) Allow() bool {
|
func (l *RateLimiter) Allow() bool {
|
||||||
if l == nil || l.Interval <= 0 {
|
if l == nil || l.Interval <= 0 {
|
||||||
return true
|
return true
|
||||||
@@ -42,10 +42,9 @@ func (l *RateLimiter) Allow() bool {
|
|||||||
return time.Since(l.last) >= l.Interval
|
return time.Since(l.last) >= l.Interval
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reserve bucht einen Ansage-Slot (direkt nach der Play-Entscheidung
|
// Reserve books a slot. Call it right after the play decision, before actual
|
||||||
// aufrufen, vor dem eigentlichen Abspielen — auch fehlgeschlagene Ansagen
|
// playback: failed announcements consume the window too, so a broken
|
||||||
// verbrauchen das Fenster: Ein kaputter Provider darf nicht zum Maschinengewehr
|
// provider cannot turn into a machine gun.
|
||||||
// werden).
|
|
||||||
func (l *RateLimiter) Reserve() {
|
func (l *RateLimiter) Reserve() {
|
||||||
if l == nil || l.Interval <= 0 {
|
if l == nil || l.Interval <= 0 {
|
||||||
return
|
return
|
||||||
@@ -55,9 +54,9 @@ func (l *RateLimiter) Reserve() {
|
|||||||
l.last = time.Now()
|
l.last = time.Now()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Next liefert, wann der nächste Ansage-Slot frei wird — Nullzeit, wenn
|
// Next returns when the next slot opens; the zero time when Allow would
|
||||||
// Allow sofort true liefern würde (unbegrenzt oder Fenster abgelaufen).
|
// return true right away (unlimited or window elapsed). Basis for parking
|
||||||
// Basis für das Parken wartender Items und den Status-Endpoint.
|
// waiting items and for the status endpoint.
|
||||||
func (l *RateLimiter) Next() time.Time {
|
func (l *RateLimiter) Next() time.Time {
|
||||||
if l == nil || l.Interval <= 0 {
|
if l == nil || l.Interval <= 0 {
|
||||||
return time.Time{}
|
return time.Time{}
|
||||||
@@ -70,68 +69,65 @@ func (l *RateLimiter) Next() time.Time {
|
|||||||
return l.last.Add(l.Interval)
|
return l.last.Add(l.Interval)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Laws sind die Anti-Spam-Gesetze des Daemons (Task 05): Rate-Limit mit
|
// Laws are the daemon's anti-spam laws: rate limit with configurable burst
|
||||||
// verkonfigurierbarem Verstoß-Recht für high, plus Ruhezeiten. Der Nullwert
|
// rights for high, quiet hours, text length cap and maximum queue age. The
|
||||||
// erlaubt alles (unbegrenzt, kein Ruhefenster) — der Daemon liefert die
|
// zero value allows everything; the daemon supplies the laws from the
|
||||||
// Gesetze aus der Config; Default siehe internal/config.Defaults.
|
// config (defaults in internal/config.Defaults).
|
||||||
type Laws struct {
|
type Laws struct {
|
||||||
// RateLimit ist der Mindestabstand zwischen zwei Ansage-Starten
|
// RateLimit is the minimum gap between two announcement starts
|
||||||
// (0 = unbegrenzt).
|
// (0 = unlimited).
|
||||||
RateLimit time.Duration
|
RateLimit time.Duration
|
||||||
|
|
||||||
// AllowHighBurst erlaubt priority=high, das Rate-Limit bewusst zu
|
// AllowHighBurst lets priority=high deliberately break the rate limit
|
||||||
// verstoßen (Default true). Ohne Burst-Recht wartet high wie normal.
|
// (default true). Without burst rights, high waits like normal. Quiet
|
||||||
// Die Ruhezeit gilt davon unberührt auch für high.
|
// hours apply to high regardless.
|
||||||
AllowHighBurst bool
|
AllowHighBurst bool
|
||||||
|
|
||||||
// Quiet ist das Ruhezeit-Fenster (lokale Zeit; Nullwert = deaktiviert).
|
// Quiet is the quiet window (local time; zero value = disabled).
|
||||||
Quiet QuietHours
|
Quiet QuietHours
|
||||||
|
|
||||||
// QuietMode bestimmt das Verhalten in der Ruhezeit: "discard" verwirft
|
// QuietMode is the behaviour during quiet hours: "discard" drops
|
||||||
// still, "toast" ersetzt Audio durch eine Benachrichtigung — aktuell
|
// silently, "toast" replaces audio with a desktop notification (the
|
||||||
// eine Protokoll-Zeile über den Notification-Pfad des Loggers; der
|
// queue fires the OnToast hook; the daemon wires the notification).
|
||||||
// echte OS-Toast folgt mit der Notification-Anbindung (dokumentierte
|
|
||||||
// Einschränkung, siehe Task-05-Report).
|
|
||||||
QuietMode string
|
QuietMode string
|
||||||
|
|
||||||
// MaxText ist die Obergrenze der Ansage-Länge in Zeichen (Runen).
|
// MaxText caps announcement length in characters (runes). Longer texts
|
||||||
// Längere Texte werden beim Eintritt an einer Wortgrenze gekürzt und
|
// are cut at a word boundary on admission and reported as truncated: an
|
||||||
// als gekürzt gemeldet — ein Agent, der die Langantwort vorliest,
|
// agent reading out its long answer costs neither minutes nor API
|
||||||
// kostet so weder Minuten noch API-Budget; der Nutzer hört den Anfang.
|
// budget, and the user still hears the beginning. 0 = unlimited.
|
||||||
// 0 = unbegrenzt.
|
|
||||||
MaxText int
|
MaxText int
|
||||||
|
|
||||||
// MaxAge ist die längste Wartezeit einer Ansage in der Queue. Was
|
// MaxAge is the longest an announcement may wait in the queue. Whatever
|
||||||
// länger parkt (Rate-Limit, Stau), ist veraltet und wird beim
|
// parks longer (rate limit, backlog) is stale and gets discarded when it
|
||||||
// Fälligwerden verworfen (DiscardExpired) statt gesprochen. 0 =
|
// comes due (DiscardExpired) instead of spoken. 0 = unlimited. now:true
|
||||||
// unbegrenzt. now:true wartet nie lange und ist davon ausgenommen.
|
// never waits long and is exempt.
|
||||||
MaxAge time.Duration
|
MaxAge time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
// verdict ist die Gesetzes-Entscheidung über ein fälliges Item.
|
// verdict is the laws' decision about a due item.
|
||||||
type verdict int
|
type verdict int
|
||||||
|
|
||||||
const (
|
const (
|
||||||
verdictPlay verdict = iota // abspielen
|
verdictPlay verdict = iota // play
|
||||||
verdictWait // parken bis zum freien Slot
|
verdictWait // park until the slot opens
|
||||||
verdictDiscardRate // verwerfen: low über dem Budget
|
verdictDiscardRate // discard: low over budget
|
||||||
verdictDiscardQuiet // verwerfen: Ruhezeit (discard)
|
verdictDiscardQuiet // discard: quiet hours (discard)
|
||||||
verdictToast // Toast statt Audio (Ruhezeit)
|
verdictToast // toast instead of audio (quiet hours)
|
||||||
verdictDiscardExpired // verwerfen: länger gewartet als MaxAge
|
verdictDiscardExpired // discard: waited longer than MaxAge
|
||||||
)
|
)
|
||||||
|
|
||||||
// decide wendet die Gesetze auf ein fälliges Item an (rein, ohne Zustand):
|
// decide applies the laws to a due item (pure, no state): slotFree says
|
||||||
// slotFree sagt, ob der Rate-Limit-Slot gerade frei ist. Rangordnung:
|
// whether the rate-limit slot is open right now. Precedence:
|
||||||
//
|
//
|
||||||
// 1. now:true bricht bewusst aus — überspringt Rate-Limit UND Ruhezeit
|
// 1. now:true deliberately breaks out: it skips rate limit AND quiet hours
|
||||||
// (dokumentierter Ausbruch für Dringendes; startet trotzdem ein neues
|
// (the documented escape for urgent matters; it still books a new rate
|
||||||
// Rate-Fenster).
|
// window).
|
||||||
// 2. Veraltet: Hat das Item länger als MaxAge gewartet, wird es verworfen
|
// 2. Stale: an item that waited longer than MaxAge is discarded; an
|
||||||
// — eine Ansage von vor fünf Minuten ist keine Nachricht mehr.
|
// announcement from five minutes ago is no longer news.
|
||||||
// 3. Ruhezeit: discard verwirft, toast ersetzt — gilt auch für high,
|
// 3. Quiet hours: discard drops, toast replaces; this applies to high too,
|
||||||
// denn Burst ist ein Rate-Recht, kein Ruhe-Recht.
|
// because burst is a rate right, not a quiet right.
|
||||||
// 4. Rate-Limit: freier Slot spielt; high spielt mit Burst-Recht; low
|
// 4. Rate limit: an open slot plays; high plays with burst rights; low is
|
||||||
// wird verworfen; normal (und high ohne Recht) parken bis zum Slot.
|
// discarded; normal (and high without rights) park until the slot.
|
||||||
func (l Laws) decide(item Item, now time.Time, slotFree bool) verdict {
|
func (l Laws) decide(item Item, now time.Time, slotFree bool) verdict {
|
||||||
if item.Now {
|
if item.Now {
|
||||||
return verdictPlay
|
return verdictPlay
|
||||||
@@ -157,42 +153,43 @@ func (l Laws) decide(item Item, now time.Time, slotFree bool) verdict {
|
|||||||
return verdictWait
|
return verdictWait
|
||||||
}
|
}
|
||||||
|
|
||||||
// Admission ist das Ergebnis von Enqueue: Aufgenommene tragen ihre ID,
|
// Admission is the result of Enqueue: admitted items carry their ID,
|
||||||
// verworfene nennen den Grund (die 202-Antwort von POST /speak führt ihn).
|
// discarded ones name the reason (the 202 response of POST /speak carries
|
||||||
|
// it).
|
||||||
type Admission struct {
|
type Admission struct {
|
||||||
// ID der aufgenommenen Ansage (leer, wenn verworfen).
|
// ID of the admitted announcement (empty when discarded).
|
||||||
ID string
|
ID string
|
||||||
|
|
||||||
// Discarded ist der Verwurfs-Grund (DiscardRateLimit bzw.
|
// Discarded is the discard reason (DiscardRateLimit or
|
||||||
// DiscardQuietHours); leer, wenn die Ansage aufgenommen wurde.
|
// DiscardQuietHours); empty when the announcement was admitted.
|
||||||
Discarded string
|
Discarded string
|
||||||
|
|
||||||
// Toast meldet, dass die Ansage in der Ruhezeit durch eine
|
// Toast reports that the announcement was replaced by a notification
|
||||||
// Benachrichtigung ersetzt wurde (quiet_mode = "toast").
|
// during quiet hours (quiet_mode = "toast").
|
||||||
Toast bool
|
Toast bool
|
||||||
|
|
||||||
// Truncated meldet, dass der Text auf MaxText gekürzt wurde (die
|
// Truncated reports that the text was cut to MaxText (the shortened
|
||||||
// gekürzte Fassung ist aufgenommen).
|
// version was admitted).
|
||||||
Truncated bool
|
Truncated bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// LawState ist die /status-Sicht auf die Anti-Spam-Gesetze: konfiguriertes
|
// LawState is the /status view of the laws: the configured rate limit with
|
||||||
// Rate-Limit mit dem nächsten freien Slot sowie das Ruhezeit-Fenster.
|
// the next open slot, the quiet window, and the length and age limits.
|
||||||
type LawState struct {
|
type LawState struct {
|
||||||
RateLimit time.Duration
|
RateLimit time.Duration
|
||||||
AllowHighBurst bool
|
AllowHighBurst bool
|
||||||
NextSlot time.Time // Nullzeit = Slot frei (oder unbegrenzt)
|
NextSlot time.Time // zero = slot open (or unlimited)
|
||||||
Quiet QuietHours
|
Quiet QuietHours
|
||||||
QuietActive bool
|
QuietActive bool
|
||||||
QuietMode string
|
QuietMode string
|
||||||
QuietUntil time.Time // Nullzeit = Ruhezeit inaktiv
|
QuietUntil time.Time // zero = quiet hours inactive
|
||||||
MaxText int // 0 = unbegrenzt
|
MaxText int // 0 = unlimited
|
||||||
MaxAge time.Duration // 0 = unbegrenzt
|
MaxAge time.Duration // 0 = unlimited
|
||||||
}
|
}
|
||||||
|
|
||||||
// truncateText kürzt s auf höchstens max Runen, bevorzugt an einer
|
// truncateText cuts s to at most max runes, preferably at a word boundary
|
||||||
// Wortgrenze (sofern die nicht in der ersten Hälfte liegt), und meldet, ob
|
// (unless that lies in the first half), and reports whether it cut.
|
||||||
// gekürzt wurde. max <= 0 = unbegrenzt.
|
// max <= 0 = unlimited.
|
||||||
func truncateText(s string, max int) (string, bool) {
|
func truncateText(s string, max int) (string, bool) {
|
||||||
if max <= 0 {
|
if max <= 0 {
|
||||||
return s, false
|
return s, false
|
||||||
|
|||||||
+47
-38
@@ -1,8 +1,8 @@
|
|||||||
// Package speak ist der eine Sprech-Kern von talk: Er setzt Config, Audio-
|
// Package speak is talk's single speech core: it assembles config, audio
|
||||||
// Sink und Provider-Kette zu einer Ansage zusammen. Der Daemon ruft ihn aus
|
// sink and provider chain into an announcement. The daemon calls it from
|
||||||
// dem Queue-Worker, die CLI nur im Notfall ohne Daemon (direkt, ohne
|
// the queue worker, the CLI only in the emergency path without a daemon
|
||||||
// Warteschlange) — beide über genau diesen Weg, damit es keine zweite
|
// (directly, without a queue); both go through exactly this path so there
|
||||||
// Zusammensetzung der Kette gibt, die auseinanderlaufen könnte.
|
// is no second assembly of the chain that could drift apart.
|
||||||
package speak
|
package speak
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -16,37 +16,37 @@ import (
|
|||||||
"code.m3ta.dev/m3tam3re/talk/internal/provider"
|
"code.m3ta.dev/m3tam3re/talk/internal/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
// NoProvider ist der Provider-Name, den ActiveProvider meldet, wenn keine
|
// NoProvider is the provider name ActiveProvider reports when no tier of
|
||||||
// Stufe der Kette verfügbar ist (Status-Anzeige).
|
// the chain is available (status display).
|
||||||
const NoProvider = "keine"
|
const NoProvider = "none"
|
||||||
|
|
||||||
// Request ist eine Ansage: Text plus optionale Pins. Leere Pins heißen
|
// Request is an announcement: text plus optional pins. Empty pins mean
|
||||||
// „Default": Sprache wird erkannt, die Kette läuft in Config-Reihenfolge,
|
// "default": the language is detected, the chain runs in config order, the
|
||||||
// die Stimme kommt aus dem Voice-Mapping.
|
// voice comes from the voice mapping.
|
||||||
type Request struct {
|
type Request struct {
|
||||||
Text string
|
Text string
|
||||||
Lang string // de | en; leer = langdetect
|
Lang string // de | en; empty = langdetect
|
||||||
Provider string // Provider-Pin; leer = Config-Pin bzw. Default-Kette
|
Provider string // provider pin; empty = config pin or default chain
|
||||||
Voice string // Voice-ID-Pin; leer = Mapping/Defaults
|
Voice string // voice ID pin; empty = mapping/defaults
|
||||||
}
|
}
|
||||||
|
|
||||||
// Engine hält Sink und Konfiguration und baut pro Ansage die Kette (Pin und
|
// Engine holds sink and configuration and builds the chain per announcement
|
||||||
// Stimme sind Eigenschaften der einzelnen Anfrage). Sie ist nebenläufig
|
// (pin and voice are properties of the individual request). It is safe for
|
||||||
// nutzbar; der Daemon spricht ohnehin seriell.
|
// concurrent use; the daemon speaks serially anyway.
|
||||||
type Engine struct {
|
type Engine struct {
|
||||||
cfg config.Config
|
cfg config.Config
|
||||||
sink audio.Sink
|
sink audio.Sink
|
||||||
getenv func(string) string
|
getenv func(string) string
|
||||||
log io.Writer
|
log io.Writer
|
||||||
base *provider.Chain // ungepinnte Kette: Verfügbarkeits-Auflösung für Status
|
base *provider.Chain // unpinned chain: availability resolution for status
|
||||||
|
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
last string // zuletzt verwendeter Provider (Status im Leerlauf)
|
last string // most recently used provider (status when idle)
|
||||||
}
|
}
|
||||||
|
|
||||||
// New baut den Sprech-Kern: Sink nach cfg.Audio.Sink, Basiskette nach
|
// New builds the speech core: sink per cfg.Audio.Sink, base chain per
|
||||||
// Config. getenv liefert Keys und Endpunkt-Overrides (nil = leer), log
|
// config. getenv supplies keys and endpoint overrides (nil = empty), log
|
||||||
// empfängt Ketten- und Sink-Protokoll (nil = still).
|
// receives chain and sink output (nil = silent).
|
||||||
func New(cfg config.Config, getenv func(string) string, log io.Writer) (*Engine, error) {
|
func New(cfg config.Config, getenv func(string) string, log io.Writer) (*Engine, error) {
|
||||||
if getenv == nil {
|
if getenv == nil {
|
||||||
getenv = func(string) string { return "" }
|
getenv = func(string) string { return "" }
|
||||||
@@ -62,14 +62,14 @@ func New(cfg config.Config, getenv func(string) string, log io.Writer) (*Engine,
|
|||||||
return &Engine{cfg: cfg, sink: sink, getenv: getenv, log: log, base: base}, nil
|
return &Engine{cfg: cfg, sink: sink, getenv: getenv, log: log, base: base}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Speak spricht eine Anfrage: Sprache erkennen (falls nicht gepinnt), Kette
|
// Speak speaks a request: detect the language (unless pinned), build the
|
||||||
// bauen, synthetisieren mit Fallback, über den Sink abspielen. Blockiert
|
// chain, synthesize with fallback, play through the sink. Blocks until
|
||||||
// bis zum Ende der Wiedergabe oder bis ctx abgebrochen wird. Das Outcome
|
// playback ends or ctx is cancelled. The outcome names the tier that
|
||||||
// nennt die Stufe, die wirklich gesprochen hat, und die Zeiten.
|
// actually spoke and the timings.
|
||||||
func (e *Engine) Speak(ctx context.Context, req Request) (provider.Outcome, error) {
|
func (e *Engine) Speak(ctx context.Context, req Request) (provider.Outcome, error) {
|
||||||
lang := req.Lang
|
lang := req.Lang
|
||||||
if lang == "" {
|
if lang == "" {
|
||||||
lang = langdetect.Detect(req.Text)
|
lang = langdetect.Detect(req.Text, e.cfg.Lang)
|
||||||
}
|
}
|
||||||
chain, err := provider.NewChain(chainConfig(e.cfg, req.Provider, req.Voice, e.getenv, e.sink, e.log))
|
chain, err := provider.NewChain(chainConfig(e.cfg, req.Provider, req.Voice, e.getenv, e.sink, e.log))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -82,13 +82,22 @@ func (e *Engine) Speak(ctx context.Context, req Request) (provider.Outcome, erro
|
|||||||
return out, err
|
return out, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Chain liefert die ungepinnte Basiskette (Diagnose: Stufen und ihre
|
// Lang resolves the language of a request: the pin, or detection with the
|
||||||
// Verfügbarkeit).
|
// configured fallback.
|
||||||
|
func (e *Engine) Lang(req Request) string {
|
||||||
|
if req.Lang != "" {
|
||||||
|
return req.Lang
|
||||||
|
}
|
||||||
|
return langdetect.Detect(req.Text, e.cfg.Lang)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Chain returns the unpinned base chain (diagnostics: tiers and their
|
||||||
|
// availability).
|
||||||
func (e *Engine) Chain() *provider.Chain { return e.base }
|
func (e *Engine) Chain() *provider.Chain { return e.base }
|
||||||
|
|
||||||
// ActiveProvider löst den „aktiven Provider" für eine Anfrage auf: der Pin,
|
// ActiveProvider resolves the "active provider" for a request: the pin,
|
||||||
// sonst die erste verfügbare Stufe der Basiskette (Available ist billig —
|
// otherwise the first available tier of the base chain (Available is cheap:
|
||||||
// Key-/Binary-Prüfung ohne Netz), sonst NoProvider.
|
// key/binary check without network), otherwise NoProvider.
|
||||||
func (e *Engine) ActiveProvider(pin string) string {
|
func (e *Engine) ActiveProvider(pin string) string {
|
||||||
if pin != "" {
|
if pin != "" {
|
||||||
return pin
|
return pin
|
||||||
@@ -101,15 +110,15 @@ func (e *Engine) ActiveProvider(pin string) string {
|
|||||||
return NoProvider
|
return NoProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
// LastProvider liefert den Provider der zuletzt gestarteten Ansage; leer,
|
// LastProvider returns the provider of the most recently started
|
||||||
// wenn noch nichts gesprochen wurde.
|
// announcement; empty if nothing has been spoken yet.
|
||||||
func (e *Engine) LastProvider() string {
|
func (e *Engine) LastProvider() string {
|
||||||
e.mu.Lock()
|
e.mu.Lock()
|
||||||
defer e.mu.Unlock()
|
defer e.mu.Unlock()
|
||||||
return e.last
|
return e.last
|
||||||
}
|
}
|
||||||
|
|
||||||
// SinkName liefert den Namen des Audio-Sinks (oto | null).
|
// SinkName returns the name of the audio sink (oto | null).
|
||||||
func (e *Engine) SinkName() string { return e.sink.Name() }
|
func (e *Engine) SinkName() string { return e.sink.Name() }
|
||||||
|
|
||||||
func (e *Engine) setLast(name string) {
|
func (e *Engine) setLast(name string) {
|
||||||
@@ -118,9 +127,9 @@ func (e *Engine) setLast(name string) {
|
|||||||
e.mu.Unlock()
|
e.mu.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
// chainConfig überführt Config + Anfrage-Pins in die ChainConfig: Anfrage-
|
// chainConfig turns config plus request pins into the ChainConfig: the
|
||||||
// Pin schlägt den Config-Pin `provider = "…"`; Endpunkte und das OpenAI-
|
// request pin beats the config pin `provider = "..."`; endpoints and the
|
||||||
// Modell kommen aus [providers.<name>].
|
// OpenAI model come from [providers.<name>].
|
||||||
func chainConfig(cfg config.Config, pin, voice string, getenv func(string) string, player provider.Player, log io.Writer) provider.ChainConfig {
|
func chainConfig(cfg config.Config, pin, voice string, getenv func(string) string, player provider.Player, log io.Writer) provider.ChainConfig {
|
||||||
if pin == "" {
|
if pin == "" {
|
||||||
pin = cfg.Provider
|
pin = cfg.Provider
|
||||||
|
|||||||
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user