17 Commits
Author SHA1 Message Date
hauke 35e560020c chore #14740: release 0.2.2 2026-11-09 12:06:27 +01:00
haukeandClaude Opus 5.5 3a16c76257 feat #14740: track uploads per backend server
Schema v4 adds calls.crm_base_url; existing uploads are tagged with the
test backend. A call counts as uploaded (list/detail fields, the
"Hochgeladen am" line, the upload-once guard) only if it was uploaded to
this build's backend. Uploading to the other server replaces the single
upload record; nothing is deleted.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 10:52:16 +01:00
haukeandClaude Opus 5.5 d0ece263a2 feat #14740: release builds use the production backend
Release builds talk to https://backend.euvinopro.eu, debug builds keep
https://test.euvinopro.eu. A key bound to the test backend is discarded
in a release build (fresh login).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 10:51:09 +01:00
haukeandClaude Opus 5.5 a0f89454f9 fix #14740: linux update check and upload safety
- Linux: ask the feed for the windows-x86_64 entry only to learn the
  version; report it (the settings show the .deb hint) without storing a
  pending update or announcing it. install_update refuses off Windows.
- Background checks re-check is_due once the running lock is held.
- Check errors read "Update-Prüfung fehlgeschlagen: …".
- Settings: a failed follow-up getUpdate() never hides a found update; an
  unknown canSelfUpdate() shows it without an install button.
- An upload the CRM accepted but that could not be saved locally names
  the CRM id and is refused for re-upload until the app restarts.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 10:50:12 +01:00
hauke 083edf32a2 chore #14740: update feed 0.2.1 2026-11-06 15:48:53 +01:00
hauke 687d4bccfe chore #14740: release 0.2.1 2026-11-06 15:48:45 +01:00
haukeandClaude Sonnet 5 fa55dcb7bc fix #14740: upload a transcript only once
A call once uploaded can no longer be sent again: claim_upload refuses a
call that already carries a CRM transcript id ("Bereits hochgeladen"),
checked under the same lock that already serializes uploads per call, so a
concurrent second upload can never slip through between the check and the
one upload it allows. upload_transcript runs this check before any HTTP
request, so a rejected re-upload never reaches the backend.

The call detail view drops "Erneut hochladen" and its confirmation dialog:
once a call has uploaded_at/crm_transcript_id, only "Hochgeladen am …" is
shown, no button.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-06 15:40:31 +01:00
haukeandClaude Sonnet 5 dad98b4558 fix #14740: guard the backend url and the backend key
BACKEND_URL must never end with "/" (a stored key's base_url is compared
against it byte-for-byte): a unit test now asserts both RELEASE_BACKEND_URL
and DEV_BACKEND_URL have no trailing slash and start with "https://", and
AppState trims it defensively where it is stored (an earlier commit already
carries that trim).

set_api_key/has_api_key now refuse Service::Backend ("Dieser Schlüssel wird
über die Backend-Anmeldung verwaltet"): its key is only ever set by the
backend login, which holds backend_key_lock and binds it to this build's
backend.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-06 15:40:15 +01:00
haukeandClaude Sonnet 5 96eec22971 feat #14740: check for updates from the settings
Adds a "Nach Updates suchen" button to the settings' new Updates section,
next to the app's own version. It runs check_for_update_now, the very same
feed check the background loop uses (one implementation, shared via
UpdateSchedule), so a manual check counts as an attempt for the same
scheduler: success resets the 6 h interval and the failure count, a failure
advances the backoff by one step, and a manual and a background check never
run at the same time (serialized).

An available update leaves the same state the background check does, so the
main window's banner still shows it; the settings also show it inline with
the existing "Installieren & neu starten" button and busy guard/hint. "None"
and "error" results are shown inline (unlike the background check, which
never surfaces its errors). On Linux (can_self_update) the button still asks
the feed but offers no install, since Debian builds never self-update.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-06 15:38:35 +01:00
hauke 1735f431dd chore #14740: update feed 0.2.0 2026-11-06 15:20:29 +01:00
hauke 782b24a6de chore #14740: release 0.2.0 2026-11-06 15:20:20 +01:00
haukeandClaude Opus 5.5 3358de7888 fix #14740: fixed backend url per build, key bound to its server
- the backend URL is no longer a setting: one constant per build
  (release/dev) in src-tauri/src/backend.rs; Settings shows the server
  read-only; an old backend_url in settings.json is ignored
- the stored key records the backend it was created for; a key of
  another backend is discarded before any use and never stored
- a refused key is discarded only if it still is the stored one
- the keyring is never called while the settings are locked
- one upload per call at a time, also visible after a view switch
- opener plugin without its link-click script (it also ran in the
  remote login page); a login error says to reload the login page

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-06 15:18:05 +01:00
haukeandClaude Opus 5.5 f045424e97 feat #14740: link to the euvino admin backend
- Settings section "Backend": backend URL, login status checked live
  (logged in as / until, not logged in, backend unreachable), Anmelden /
  Neu anmelden, Abmelden and the link to the key management page
- login window "backend-login": the backend's own login page in an
  incognito webview without any Tauri capability; after a page load
  behind the login, its cookies create a key (one request, never stored
  or logged), the key goes to the keyring, the window closes; closing it
  cancels; one login at a time, later requests wait for the same result
- call detail: "Transkript hochladen" / "Erneut hochladen" (with a
  confirmation), "wird hochgeladen…", "Hochgeladen am … (ID …)" and
  inline errors; logs in first when there is no usable key
- saving a different backend URL discards the key of the old backend

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-06 14:54:38 +01:00
haukeandClaude Opus 5.5 58e96a2954 feat #14740: admin backend client and transcript upload text
recorder-core side of linking the app to the euvino admin backend:
- backend: BackendClient (create a key with the admin's session cookie,
  check a key, upload a transcript; redirects never followed), German
  error messages, the login-window decision (LoginStep) and the upload
  flow with login, one retry after a refused key and no loop
- call_view: the upload text (header + merged, renamed lines) and the
  upload fields on the call
- store: schema v3 with crm_transcript_id and uploaded_at
- settings: backend_url (validated https), the app-managed login fields,
  kept on edit and cleared when the backend URL changes
- secrets: Service::Backend; http: per-request follow_redirects;
  FakeTransport can script transport errors

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-06 14:52:50 +01:00
haukeandClaude Opus 5.5 54a81e5ba0 chore #14740: remove claude config and customer selection
Summaries are not coming to the desktop app, and the customer is chosen
in the web UI after the upload:
- drop the Anthropic key (Service::Anthropic, Settings field) and delete
  a leftover keyring entry best-effort at startup
- drop the Summary model, the store's summary accessors and the
  "Zusammenfassung" tab; the transcript is the detail's only content
- drop the mocked customer accounts, list_accounts/set_account and the
  "Kunde" dropdown; calls.account_id and summaries stay in the schema

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-06 14:35:41 +01:00
haukeandClaude Sonnet 5 eff07d2f59 chore #14740: drop appimage and the unsupported feed url
Verified on Gitea 1.27.3: releases/latest/download/<file> does not
redirect to a release's assets (404), so that update-feed endpoint is
dead. Only raw/branch/master/latest.json works; keep that one in
release.env and tauri.conf.json and document it as the mandatory feed
in RELEASING.md.

Also drop the AppImage (user: it is huge and we don't need it): bundle
targets become nsis+deb, build-release.sh only builds the .deb on
Linux, and make-latest-json.sh no longer writes a Linux platform entry
at all (Debian builds don't self-update).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-06 12:29:53 +01:00
hauke 572c685396 chore #14740: update feed 0.1.1 2026-11-06 12:15:15 +01:00
33 changed files with 3630 additions and 587 deletions
Generated
+56 -1
View File
@@ -445,8 +445,9 @@ dependencies = [
[[package]] [[package]]
name = "call-recorder" name = "call-recorder"
version = "0.1.1" version = "0.2.2"
dependencies = [ dependencies = [
"async-trait",
"chrono", "chrono",
"log", "log",
"recorder-audio", "recorder-audio",
@@ -458,9 +459,11 @@ dependencies = [
"tauri-plugin-autostart", "tauri-plugin-autostart",
"tauri-plugin-log", "tauri-plugin-log",
"tauri-plugin-notification", "tauri-plugin-notification",
"tauri-plugin-opener",
"tauri-plugin-single-instance", "tauri-plugin-single-instance",
"tauri-plugin-updater", "tauri-plugin-updater",
"tempfile", "tempfile",
"tokio",
] ]
[[package]] [[package]]
@@ -2059,6 +2062,25 @@ version = "2.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
[[package]]
name = "is-docker"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3"
dependencies = [
"once_cell",
]
[[package]]
name = "is-wsl"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5"
dependencies = [
"is-docker",
"once_cell",
]
[[package]] [[package]]
name = "itoa" name = "itoa"
version = "1.0.18" version = "1.0.18"
@@ -2981,6 +3003,17 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "open"
version = "5.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d8c8b8e725ad26404d6896eb2f064294a0a7b4f1d9120210d85544684c4ca95"
dependencies = [
"dunce",
"is-wsl",
"libc",
]
[[package]] [[package]]
name = "openssl-probe" name = "openssl-probe"
version = "0.2.2" version = "0.2.2"
@@ -4712,6 +4745,28 @@ dependencies = [
"zbus 5.19.0", "zbus 5.19.0",
] ]
[[package]]
name = "tauri-plugin-opener"
version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53810be1b4fed22bb6ac3f4cab5a2b80d9391d1af436bda145607532bc0bb219"
dependencies = [
"dunce",
"glob",
"objc2-app-kit",
"objc2-foundation",
"open",
"schemars 0.8.22",
"serde",
"serde_json",
"tauri",
"tauri-plugin",
"thiserror 2.0.21",
"url",
"windows",
"zbus 5.19.0",
]
[[package]] [[package]]
name = "tauri-plugin-single-instance" name = "tauri-plugin-single-instance"
version = "2.5.5" version = "2.5.5"
+2 -2
View File
@@ -1,12 +1,12 @@
# Gesprächsrekorder # Gesprächsrekorder
A Tauri 2 desktop app that records calls (Teams, MicroSIP, browser-based A Tauri 2 desktop app that records calls (Teams, MicroSIP, browser-based
softphones, …), then transcribes and summarizes them. softphones, …) and transcribes them.
## Workspace layout ## Workspace layout
- `crates/core` (`recorder-core`) — core domain logic: call detection, - `crates/core` (`recorder-core`) — core domain logic: call detection,
recording orchestration, transcription and summarization. Independent of recording orchestration and transcription. Independent of
the Tauri app shell and the audio backend so it can be unit-tested without the Tauri app shell and the audio backend so it can be unit-tested without
a GUI, a sound device or network access. a GUI, a sound device or network access.
- `crates/audio` (`recorder-audio`) — audio capture and WAV/FLAC encoding. - `crates/audio` (`recorder-audio`) — audio capture and WAV/FLAC encoding.
+35 -52
View File
@@ -3,7 +3,7 @@
A release consists of: A release consists of:
- the Windows NSIS installer (per-user, no admin rights), cross-built on Debian, - the Windows NSIS installer (per-user, no admin rights), cross-built on Debian,
- the Debian `.deb` and `.AppImage`, - the Debian `.deb`,
- an updater signature (`.sig`) for each of them, - an updater signature (`.sig`) for each of them,
- `latest.json`, the update feed the installed Windows apps read. - `latest.json`, the update feed the installed Windows apps read.
@@ -46,8 +46,7 @@ restarts the app. Debian builds do not update themselves.
`https://gitea.euvino.eu/public/call-recorder`. The download URLs in `latest.json` `https://gitea.euvino.eu/public/call-recorder`. The download URLs in `latest.json`
point to `${RELEASE_BASE_URL}/releases/download/v<version>/<file>`. point to `${RELEASE_BASE_URL}/releases/download/v<version>/<file>`.
- `UPDATE_JSON_URLS`: where the app looks for `latest.json`. `build-release.sh` - `UPDATE_JSON_URLS`: where the app looks for `latest.json`. `build-release.sh`
writes them, in this order, into `plugins.updater.endpoints` in writes them into `plugins.updater.endpoints` in `src-tauri/tauri.conf.json`.
`src-tauri/tauri.conf.json`.
Do not edit the endpoints in `tauri.conf.json` by hand. Change `release.env`; the Do not edit the endpoints in `tauri.conf.json` by hand. Change `release.env`; the
next release build writes them into `tauri.conf.json`. next release build writes them into `tauri.conf.json`.
@@ -55,43 +54,25 @@ next release build writes them into `tauri.conf.json`.
The repository and its releases must be readable without logging in: the app The repository and its releases must be readable without logging in: the app
downloads anonymously. downloads anonymously.
### The two feed URLs ### The feed URL
The app tries the endpoints in order and uses the first one that returns a release. Verified on Gitea 1.27.3: `releases/latest/download/<file>` does **not** redirect
A `404` or a network error on one moves on to the next one: to a release's assets, even for the newest non-draft, non-prerelease release —
requesting it returns `404`. So the feed lives only at
1. `https://gitea.euvino.eu/public/call-recorder/releases/latest/download/latest.json`: ```
`latest.json` as an asset of the newest release (not a draft, not a pre-release). https://gitea.euvino.eu/public/call-recorder/raw/branch/master/latest.json
This works only if Gitea redirects `releases/latest/download/<file>` to the newest
release.
2. `https://gitea.euvino.eu/public/call-recorder/raw/branch/master/latest.json`:
`latest.json` committed to the root of `master`.
Each release serves both:
- uploading the release assets covers URL 1 (step 7 below);
- committing `latest.json` to the root of `master` covers URL 2 (step 8 below).
The endpoints are compiled into the app. Installed versions keep asking the URLs
they were built with, which is why both are configured from the start.
After the first release, check which URL works:
```sh
curl -sIL https://gitea.euvino.eu/public/call-recorder/releases/latest/download/latest.json
curl -sIL https://gitea.euvino.eu/public/call-recorder/raw/branch/master/latest.json
``` ```
The final status of a working URL is `200`. Then: `latest.json` committed to the root of `master`. This makes committing
`latest.json` after every release **mandatory**, not optional (step 8 below) —
there is no redirect to fall back on.
- **URL 1 works:** a later version may drop URL 2 from `UPDATE_JSON_URLS`. Every Versions 0.1.0 and 0.1.1 were built with both URLs compiled in (the endpoints
installed version also asks URL 1, so step 8 is no longer needed. are fixed at build time; installed apps keep asking the URLs they were built
- **Only URL 2 works:** a later version may drop URL 1. Step 8 (committing with). They still try `releases/latest/download/latest.json` first on every
`latest.json`) stays part of every release. check; that is harmless — it 404s and the app falls through to the
`raw/branch/master` URL, which answers normally.
Caveat: if URL 1 answered `200` with something that is not JSON (e.g. an HTML page),
the updater would stop there instead of trying URL 2. Gitea answers a missing file
with `404`, which falls through as intended.
## Releasing a version ## Releasing a version
@@ -120,8 +101,8 @@ e.g. for the first release `0.1.0`.
- sets the version in `src-tauri/tauri.conf.json`, `src-tauri/Cargo.toml` and - sets the version in `src-tauri/tauri.conf.json`, `src-tauri/Cargo.toml` and
`ui/package.json` (the build updates `Cargo.lock` too), and writes the endpoints `ui/package.json` (the build updates `Cargo.lock` too), and writes the endpoints
from `release.env` into `tauri.conf.json`, from `release.env` into `tauri.conf.json`,
- builds the Windows installer (`scripts/build-windows.sh`), the `.deb` and the - builds the Windows installer (`scripts/build-windows.sh`) and the `.deb`, each
`.AppImage`, each with its `.sig`, with its `.sig`,
- copies them to `dist-release/0.1.1/` under ASCII names (`Gespraechsrekorder_…`) - copies them to `dist-release/0.1.1/` under ASCII names (`Gespraechsrekorder_…`)
and writes `latest.json` with `scripts/make-latest-json.sh`. and writes `latest.json` with `scripts/make-latest-json.sh`.
@@ -130,12 +111,11 @@ e.g. for the first release `0.1.0`.
3. Check `dist-release/0.1.1/`. It should contain: 3. Check `dist-release/0.1.1/`. It should contain:
| File | Purpose | | File | Purpose |
|------------------------------------------------------|--------------------------------------| |------------------------------------------------------|--------------------------------------|
| `Gespraechsrekorder_0.1.1_x64-setup.exe` (+ `.sig`) | Windows installer and update package | | `Gespraechsrekorder_0.1.1_x64-setup.exe` (+ `.sig`) | Windows installer and update package |
| `Gespraechsrekorder_0.1.1_amd64.deb` (+ `.sig`) | Debian package | | `Gespraechsrekorder_0.1.1_amd64.deb` (+ `.sig`) | Debian package |
| `Gespraechsrekorder_0.1.1_amd64.AppImage` (+ `.sig`) | Debian AppImage | | `latest.json` | Update feed |
| `latest.json` | Update feed |
4. Commit the version bump the script left in the working tree: 4. Commit the version bump the script left in the working tree:
@@ -155,12 +135,14 @@ e.g. for the first release `0.1.0`.
<https://gitea.euvino.eu/public/call-recorder/releases/new>. Do not mark it as a <https://gitea.euvino.eu/public/call-recorder/releases/new>. Do not mark it as a
draft or a pre-release, otherwise it is not the "latest" release. draft or a pre-release, otherwise it is not the "latest" release.
7. Upload every file from `dist-release/0.1.1/` as a release asset, keeping the file 7. Upload the installer, the `.deb` and their `.sig` files from
names (`latest.json` points to them). Upload the installers, packages and `.sig` `dist-release/0.1.1/` as release assets, keeping the file names (`latest.json`
files first and **`latest.json` last**. As soon as `latest.json` is visible, points to them). `latest.json` itself does not need to be uploaded as a release
installed apps may try to download the files it lists. asset: the feed is served from the committed file (step 8), not from
`releases/latest/download/latest.json` (see "The feed URL" above).
8. Only after all assets are uploaded, publish the feed for URL 2 as well: 8. Only after all assets from step 7 are uploaded and downloadable (their URLs are
what the feed will point to), commit the feed:
```sh ```sh
cp dist-release/0.1.1/latest.json latest.json cp dist-release/0.1.1/latest.json latest.json
@@ -169,15 +151,16 @@ e.g. for the first release `0.1.0`.
git push origin master git push origin master
``` ```
Committing `latest.json` is mandatory for every release — it is the only
place the feed lives.
9. Check the feed: 9. Check the feed:
```sh ```sh
curl -sL https://gitea.euvino.eu/public/call-recorder/releases/latest/download/latest.json | jq .
curl -sL https://gitea.euvino.eu/public/call-recorder/raw/branch/master/latest.json | jq . curl -sL https://gitea.euvino.eu/public/call-recorder/raw/branch/master/latest.json | jq .
``` ```
The URL(s) that work must show the new version, and the `url` entries must It must show the new version, and the `url` entry must download.
download.
## Checking an update on Windows 11 ## Checking an update on Windows 11
@@ -211,5 +194,5 @@ and 30 minutes, then every 6 hours. The log
- `RELEASE_ALLOW_KEY_MISMATCH=1` lets `build-release.sh` build with a key that does - `RELEASE_ALLOW_KEY_MISMATCH=1` lets `build-release.sh` build with a key that does
not match `plugins.updater.pubkey`. Use it only to test the pipeline with a throwaway not match `plugins.updater.pubkey`. Use it only to test the pipeline with a throwaway
key. Installed apps reject such a release, so never publish it. key. Installed apps reject such a release, so never publish it.
- `latest.json` also lists the AppImage (`linux-x86_64`). The Debian builds do not - `latest.json` only lists `windows-x86_64`. Debian installs from the `.deb` and
check for updates yet. does not self-update, so Linux has no entry in the feed.
-82
View File
@@ -1,82 +0,0 @@
//! Customer accounts a call can be assigned to (the "Kunde" dropdown).
//!
//! A static mock for now: the names are clearly fictional placeholders
//! until the account system is connected.
use serde::Serialize;
/// A customer account. `id` is what a call stores as its `account_id`.
#[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq)]
pub struct Account {
pub id: &'static str,
pub name: &'static str,
}
const MOCK_ACCOUNTS: [Account; 5] = [
Account {
id: "mock-1",
name: "Weingut Beispiel GmbH",
},
Account {
id: "mock-2",
name: "Weinhandel Muster KG",
},
Account {
id: "mock-3",
name: "Vinothek Probe",
},
Account {
id: "mock-4",
name: "Kellerei Test eG",
},
Account {
id: "mock-5",
name: "Restaurant Platzhalter",
},
];
/// All accounts, in display order.
pub fn list() -> Vec<Account> {
MOCK_ACCOUNTS.to_vec()
}
/// Whether `id` names one of the accounts.
pub fn exists(id: &str) -> bool {
MOCK_ACCOUNTS.iter().any(|account| account.id == id)
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
use super::*;
#[test]
fn mock_accounts_are_stable_and_unique() {
let accounts = list();
let names: Vec<_> = accounts.iter().map(|a| a.name).collect();
assert_eq!(
names,
[
"Weingut Beispiel GmbH",
"Weinhandel Muster KG",
"Vinothek Probe",
"Kellerei Test eG",
"Restaurant Platzhalter",
]
);
let ids: HashSet<_> = accounts.iter().map(|a| a.id).collect();
assert_eq!(ids.len(), 5);
// Stored with the calls, so they must never change.
assert_eq!(accounts[0].id, "mock-1");
assert_eq!(accounts[4].id, "mock-5");
assert_eq!(list(), accounts);
}
#[test]
fn only_listed_accounts_exist() {
assert!(exists("mock-3"));
assert!(!exists("mock-6"));
assert!(!exists(""));
}
}
+963
View File
@@ -0,0 +1,963 @@
//! The euvino admin backend: an admin's API key, minted with their browser
//! session, and the upload of call transcripts to the CRM with that key.
//!
//! The key goes only into the `X-Admin-Api-Key` header of `/admin/api/…`
//! requests, the session cookie only into the one request that creates the
//! key. Neither is ever logged or part of an error message.
use std::fmt;
use std::sync::Arc;
use async_trait::async_trait;
use chrono::{DateTime, Duration, Local};
use reqwest::Url;
use serde::Deserialize;
use serde_json::{json, Value};
use crate::http::{HttpBody, HttpRequest, HttpResponse, HttpTransport, Method};
/// The admin login page, relative to the backend URL.
const LOGIN_PATH: &str = "/euvadm";
const KEY_HEADER: &str = "X-Admin-Api-Key";
/// Longest key label the backend accepts, in characters.
const MAX_LABEL_CHARS: usize = 100;
/// The label of a key this app creates: "Gesprächsrekorder (<hostname>)",
/// at most 100 characters.
pub fn key_label(hostname: Option<&str>) -> String {
let app = "Gesprächsrekorder";
let label = match hostname.map(str::trim).filter(|host| !host.is_empty()) {
Some(host) => format!("{app} ({host})"),
None => app.to_string(),
};
label.chars().take(MAX_LABEL_CHARS).collect()
}
/// A key the backend just created. The key is shown only in this response.
#[derive(Clone, PartialEq)]
pub struct NewKey {
pub key: String,
pub expires_at: DateTime<Local>,
}
impl fmt::Debug for NewKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NewKey")
.field("key", &"<redacted>")
.field("expires_at", &self.expires_at)
.finish()
}
}
/// What the backend knows about a key (`GET /admin/api/key`).
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct KeyInfo {
pub label: String,
/// The key's last characters, safe to show.
pub hint: String,
pub username: String,
pub created_at: DateTime<Local>,
pub expires_at: DateTime<Local>,
}
/// Why a backend request failed.
#[derive(Debug, Clone, PartialEq)]
pub enum BackendError {
/// Creating a key: the session is not (yet) logged in (redirect to the
/// login page, or 401).
NotLoggedIn,
/// Creating a key: the session cannot create one (not an admin, or an
/// impersonation).
Forbidden,
/// The key is unknown, expired or deleted, or its admin was disabled.
InvalidKey,
/// The backend cannot check the key right now (503).
Unavailable,
/// The backend refused the transcript (400/422), with its reason.
Rejected(String),
/// Any other status, with the backend's `error` message if it sent one.
Http(u16, String),
/// The backend could not be reached.
Transport(String),
}
impl BackendError {
/// The German message shown to the user.
pub fn user_message(&self) -> String {
match self {
BackendError::NotLoggedIn => "Nicht beim Backend angemeldet".to_string(),
BackendError::Forbidden => "Diese Anmeldung kann keinen Schlüssel erzeugen (z. B. bei \
Impersonation) – bitte als Admin selbst anmelden."
.to_string(),
BackendError::InvalidKey => {
"Backend-Schlüssel ungültig oder abgelaufen – bitte neu anmelden.".to_string()
}
BackendError::Unavailable => "Backend kann die Anmeldung gerade nicht prüfen – bitte \
später erneut versuchen."
.to_string(),
BackendError::Rejected(reason) => {
format!("Backend hat das Transkript abgelehnt: {reason}")
}
BackendError::Http(status, msg) if msg.is_empty() => {
format!("Backend-Fehler (HTTP {status})")
}
BackendError::Http(status, msg) => format!("Backend-Fehler (HTTP {status}): {msg}"),
BackendError::Transport(msg) => format!("Backend nicht erreichbar: {msg}"),
}
}
}
/// Client of the admin backend at one base URL.
#[derive(Clone)]
pub struct BackendClient {
transport: Arc<dyn HttpTransport>,
base_url: String,
}
impl BackendClient {
/// `base_url` is the backend's https origin (plus path prefix, if
/// any); a trailing slash is ignored.
pub fn new(transport: Arc<dyn HttpTransport>, base_url: &str) -> Self {
Self {
transport,
base_url: base_url.trim_end_matches('/').to_string(),
}
}
/// The backend this client talks to, without trailing slash. A key it
/// creates belongs to this backend only.
pub fn base_url(&self) -> &str {
&self.base_url
}
/// The admin login page the login window opens.
pub fn login_url(&self) -> String {
format!("{}{LOGIN_PATH}", self.base_url)
}
/// Where admins see and delete their keys (in the browser).
pub fn keys_page_url(&self) -> String {
format!("{}/admin/api-keys", self.base_url)
}
/// Whether `url`, a page the login window loaded, shows that the admin
/// is logged in: a page of the backend other than the login page.
pub fn is_logged_in_page(&self, url: &str) -> bool {
let (Ok(page), Ok(base)) = (Url::parse(url), Url::parse(&self.base_url)) else {
return false;
};
if page.origin() != base.origin() {
return false;
}
let login = format!("{}{LOGIN_PATH}", base.path().trim_end_matches('/'));
page.path() != login && !page.path().starts_with(&format!("{login}/"))
}
/// Creates a key with the admin's browser session (`cookie_header`, the
/// session's cookies as a `Cookie` header value). Redirects are not
/// followed: one to the login page means not logged in.
pub async fn create_key(
&self,
cookie_header: &str,
label: &str,
) -> Result<NewKey, BackendError> {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Created {
key: String,
expires_at: DateTime<Local>,
}
let resp = self
.send(
Method::Post,
self.keys_page_url(),
("Cookie", cookie_header),
json!({ "label": label }),
)
.await?;
match resp.status {
200..=299 => match resp.json::<Created>() {
Ok(created) if !created.key.is_empty() => Ok(NewKey {
key: created.key,
expires_at: created.expires_at,
}),
_ => Err(unexpected(&resp)),
},
300..=399 | 401 => Err(BackendError::NotLoggedIn),
403 => Err(BackendError::Forbidden),
_ => Err(http_error(&resp)),
}
}
/// Checks `key` and returns what the backend knows about it.
pub async fn key_info(&self, key: &str) -> Result<KeyInfo, BackendError> {
let url = format!("{}/admin/api/key", self.base_url);
let resp = self
.send(Method::Get, url, (KEY_HEADER, key), Value::Null)
.await?;
match resp.status {
200..=299 => resp.json().map_err(|_| unexpected(&resp)),
_ => Err(api_error(&resp)),
}
}
/// Uploads a transcript; returns the id the CRM gave it.
pub async fn upload_transcript(&self, key: &str, text: &str) -> Result<String, BackendError> {
let url = format!("{}/admin/api/phone-transcripts", self.base_url);
let resp = self
.send(
Method::Post,
url,
(KEY_HEADER, key),
json!({ "text": text }),
)
.await?;
match resp.status {
200..=299 => match resp.json::<Value>().ok().and_then(|v| v.get("id").cloned()) {
Some(Value::Number(id)) => Ok(id.to_string()),
Some(Value::String(id)) if !id.is_empty() => Ok(id),
_ => Err(unexpected(&resp)),
},
400 | 422 => Err(BackendError::Rejected(rejection_reason(&resp))),
_ => Err(api_error(&resp)),
}
}
/// Sends a request with one credential header (`auth`) and a JSON body
/// (none for `Value::Null`). Redirects are never followed, so neither
/// the key nor the cookie can be forwarded to another host.
async fn send(
&self,
method: Method,
url: String,
auth: (&str, &str),
body: Value,
) -> Result<HttpResponse, BackendError> {
let req = HttpRequest {
method,
url,
headers: vec![
(auth.0.to_string(), auth.1.to_string()),
("Accept".to_string(), "application/json".to_string()),
],
body: match body {
Value::Null => HttpBody::Empty,
body => HttpBody::Json(body),
},
follow_redirects: false,
};
self.transport
.send(req)
.await
.map_err(|e| BackendError::Transport(e.to_string()))
}
}
/// What a page load in the login window leads to, given the result of
/// trying to create a key there.
#[derive(Debug, Clone, PartialEq)]
pub enum LoginStep {
/// The key: store it, close the window.
Done(NewKey),
/// Not logged in yet: keep waiting for the admin.
Wait,
/// The session can never create a key: close the window and fail with
/// this message.
Fail(String),
/// Something else went wrong: show this message and keep the window
/// open, so the admin can try again.
Retry(String),
}
impl LoginStep {
pub fn of(result: Result<NewKey, BackendError>) -> Self {
match result {
Ok(key) => LoginStep::Done(key),
Err(BackendError::NotLoggedIn) => LoginStep::Wait,
Err(e @ BackendError::Forbidden) => LoginStep::Fail(e.user_message()),
Err(e) => LoginStep::Retry(e.user_message()),
}
}
}
/// How a stored key fared when checked with the backend.
#[derive(Debug, Clone, PartialEq)]
pub enum KeyCheck {
Valid(KeyInfo),
/// Refused by the backend: forget it.
Invalid,
/// Not checkable right now (unreachable, 503, other error).
Unknown(BackendError),
}
impl BackendClient {
/// Checks a stored key ([`BackendClient::key_info`]).
pub async fn check_key(&self, key: &str) -> KeyCheck {
match self.key_info(key).await {
Ok(info) => KeyCheck::Valid(info),
Err(BackendError::InvalidKey) => KeyCheck::Invalid,
Err(e) => KeyCheck::Unknown(e),
}
}
}
/// A key from the keyring and the expiry stored with it.
#[derive(Clone, PartialEq)]
pub struct StoredKey {
pub key: String,
pub expires_at: Option<DateTime<Local>>,
}
impl fmt::Debug for StoredKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StoredKey")
.field("key", &"<redacted>")
.field("expires_at", &self.expires_at)
.finish()
}
}
/// Whether `stored` is missing or expires within a minute of `now`, so a
/// login has to come first.
pub fn needs_login(stored: Option<&StoredKey>, now: DateTime<Local>) -> bool {
match stored {
None => true,
Some(stored) => stored
.expires_at
.is_some_and(|expires_at| expires_at <= now + Duration::minutes(1)),
}
}
/// The app's side of a login, for [`upload_with_login`].
#[async_trait]
pub trait Login: Send + Sync {
/// Runs the login flow; returns the new (already stored) key, or the
/// message why there is none.
async fn login(&self) -> Result<String, String>;
/// Forgets the stored key if it still is `refused`, the key the backend
/// just refused (a login meanwhile may have stored a new one).
async fn discard_key(&self, refused: &str);
}
/// Uploads `text` with the stored key, logging in first when there is no
/// usable key. A key the backend refuses is discarded, and after a new
/// login the upload is tried once more. Returns the CRM's id, or the
/// message to show.
pub async fn upload_with_login(
client: &BackendClient,
login: &dyn Login,
stored: Option<StoredKey>,
now: DateTime<Local>,
text: &str,
) -> Result<String, String> {
let key = match stored.filter(|stored| !needs_login(Some(stored), now)) {
Some(stored) => stored.key,
None => login.login().await?,
};
match client.upload_transcript(&key, text).await {
Err(BackendError::InvalidKey) => {
login.discard_key(&key).await;
let key = login.login().await?;
let result = client.upload_transcript(&key, text).await;
if result == Err(BackendError::InvalidKey) {
login.discard_key(&key).await;
}
result.map_err(|e| e.user_message())
}
result => result.map_err(|e| e.user_message()),
}
}
/// A 2xx answer whose body is not what the contract says.
fn unexpected(resp: &HttpResponse) -> BackendError {
BackendError::Http(resp.status, "unerwartete Antwort".to_string())
}
/// The error of an `/admin/api/…` request: refused key, backend unable to
/// check it, or any other status.
fn api_error(resp: &HttpResponse) -> BackendError {
match resp.status {
401 => BackendError::InvalidKey,
503 => BackendError::Unavailable,
_ => http_error(resp),
}
}
/// An unexpected status with the backend's `error` message, if any. Other
/// bodies (e.g. an HTML error page) are not passed on.
fn http_error(resp: &HttpResponse) -> BackendError {
let message = resp
.json::<Value>()
.ok()
.and_then(|body| body.get("error")?.as_str().map(str::to_string))
.unwrap_or_default();
BackendError::Http(resp.status, message)
}
/// Why the backend refused a transcript: its `errors`, else its `error`.
fn rejection_reason(resp: &HttpResponse) -> String {
let Ok(body) = resp.json::<Value>() else {
return String::new();
};
let errors: Vec<String> = body
.get("errors")
.and_then(Value::as_array)
.into_iter()
.flatten()
.map(|error| match error {
Value::String(text) => text.clone(),
other => other.to_string(),
})
.collect();
if errors.is_empty() {
body.get("error")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string()
} else {
errors.join("; ")
}
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use chrono::TimeZone;
use super::*;
use crate::http::TransportError;
use crate::testing::FakeTransport;
const BASE: &str = "https://backend.example";
const KEYS: &str = "https://backend.example/admin/api-keys";
const KEY_INFO: &str = "https://backend.example/admin/api/key";
const UPLOAD: &str = "https://backend.example/admin/api/phone-transcripts";
fn client() -> (Arc<FakeTransport>, BackendClient) {
let transport = Arc::new(FakeTransport::new());
let client = BackendClient::new(transport.clone(), BASE);
(transport, client)
}
fn at(y: i32, mo: u32, d: u32, h: u32, mi: u32) -> DateTime<Local> {
Local.with_ymd_and_hms(y, mo, d, h, mi, 0).unwrap()
}
fn json_body(req: &HttpRequest) -> Value {
match &req.body {
HttpBody::Json(value) => value.clone(),
other => panic!("expected a JSON body, got {other:?}"),
}
}
#[test]
fn the_key_label_names_the_computer_within_100_chars() {
assert_eq!(
key_label(Some("PC-VERTRIEB-3")),
"Gesprächsrekorder (PC-VERTRIEB-3)"
);
assert_eq!(key_label(Some(" ")), "Gesprächsrekorder");
assert_eq!(key_label(None), "Gesprächsrekorder");
let long = key_label(Some(&"x".repeat(200)));
assert_eq!(long.chars().count(), 100);
assert!(long.starts_with("Gesprächsrekorder (xxx"));
}
#[test]
fn login_and_keys_pages_are_under_the_base_url() {
let (_, client) = client();
assert_eq!(client.login_url(), "https://backend.example/euvadm");
assert_eq!(client.keys_page_url(), KEYS);
assert_eq!(client.base_url(), BASE);
let slash = BackendClient::new(Arc::new(FakeTransport::new()), "https://backend.example/");
assert_eq!(slash.login_url(), "https://backend.example/euvadm");
assert_eq!(slash.base_url(), BASE);
}
#[test]
fn a_backend_page_other_than_the_login_page_means_logged_in() {
let (_, client) = client();
assert!(client.is_logged_in_page("https://backend.example/admin"));
assert!(client.is_logged_in_page("https://backend.example/admin/dashboard?x=1"));
assert!(client.is_logged_in_page("https://backend.example/"));
assert!(!client.is_logged_in_page("https://backend.example/euvadm"));
assert!(!client.is_logged_in_page("https://backend.example/euvadm/login_check"));
assert!(!client.is_logged_in_page("https://other.example/admin"));
assert!(!client.is_logged_in_page("http://backend.example/admin"));
assert!(!client.is_logged_in_page("https://backend.example:8443/admin"));
assert!(!client.is_logged_in_page("about:blank"));
assert!(!client.is_logged_in_page("not a url"));
}
#[tokio::test]
async fn create_key_sends_the_session_cookie_and_label_without_following_redirects() {
let (transport, client) = client();
transport.expect(
Method::Post,
KEYS,
201,
r#"{"key":"euv_secret","expiresAt":"2027-11-06T10:00:00+01:00","label":"Gesprächsrekorder (PC)"}"#,
);
let key = client
.create_key("PHPSESSID=abc; other=1", "Gesprächsrekorder (PC)")
.await
.unwrap();
assert_eq!(key.key, "euv_secret");
assert_eq!(
key.expires_at,
DateTime::parse_from_rfc3339("2027-11-06T10:00:00+01:00").unwrap()
);
let req = &transport.requests()[0];
assert_eq!(req.header("Cookie"), Some("PHPSESSID=abc; other=1"));
assert_eq!(req.header(KEY_HEADER), None);
assert!(!req.follow_redirects);
assert_eq!(json_body(req), json!({"label": "Gesprächsrekorder (PC)"}));
assert!(!format!("{key:?}").contains("euv_secret"));
transport.assert_done();
}
#[tokio::test]
async fn create_key_maps_redirects_and_refusals() {
for (status, body, expected) in [
(302, "", BackendError::NotLoggedIn),
(401, "", BackendError::NotLoggedIn),
(
403,
r#"{"error":"admin session required"}"#,
BackendError::Forbidden,
),
(
500,
"<html>boom</html>",
BackendError::Http(500, String::new()),
),
(
400,
r#"{"error":"label too long"}"#,
BackendError::Http(400, "label too long".into()),
),
(
201,
r#"{"key":"euv_x"}"#,
BackendError::Http(201, "unerwartete Antwort".into()),
),
] {
let (transport, client) = client();
transport.expect(Method::Post, KEYS, status, body);
assert_eq!(
client.create_key("s=1", "l").await,
Err(expected),
"{status}"
);
}
}
#[tokio::test]
async fn key_info_sends_the_key_and_parses_the_answer() {
let (transport, client) = client();
transport.expect(
Method::Get,
KEY_INFO,
200,
r#"{"label":"Gesprächsrekorder (PC)","hint":"…x9f2","username":"hinrichs","createdAt":"2026-11-06T10:00:00+01:00","expiresAt":"2027-11-06T10:00:00+01:00"}"#,
);
let info = client.key_info("euv_secret").await.unwrap();
assert_eq!(info.username, "hinrichs");
assert_eq!(info.hint, "…x9f2");
assert_eq!(info.expires_at, at(2027, 11, 6, 10, 0));
let req = &transport.requests()[0];
assert_eq!(req.header(KEY_HEADER), Some("euv_secret"));
assert_eq!(req.header("Cookie"), None);
assert!(!req.follow_redirects);
transport.assert_done();
}
#[tokio::test]
async fn key_info_maps_refused_and_unavailable() {
for (status, body, expected) in [
(
401,
r#"{"error":"invalid api key"}"#,
BackendError::InvalidKey,
),
(
401,
r#"{"error":"api key required"}"#,
BackendError::InvalidKey,
),
(
503,
r#"{"error":"admin status unavailable"}"#,
BackendError::Unavailable,
),
] {
let (transport, client) = client();
transport.expect(Method::Get, KEY_INFO, status, body);
assert_eq!(client.key_info("euv_k").await, Err(expected), "{status}");
}
let (transport, client) = client();
transport.fail(Method::Get, KEY_INFO, TransportError::Timeout);
assert_eq!(
client.key_info("euv_k").await,
Err(BackendError::Transport("Zeitüberschreitung".into()))
);
}
#[tokio::test]
async fn upload_posts_the_text_with_the_key_and_returns_the_id() {
for (body, id) in [
(r#"{"id":4711}"#, "4711"),
(r#"{"id":"crm-0815"}"#, "crm-0815"),
] {
let (transport, client) = client();
transport.expect(Method::Post, UPLOAD, 201, body);
assert_eq!(
client.upload_transcript("euv_k", "Titel: Test").await,
Ok(id.into())
);
let req = &transport.requests()[0];
assert_eq!(req.header(KEY_HEADER), Some("euv_k"));
assert_eq!(req.header("Cookie"), None);
assert!(!req.follow_redirects);
assert_eq!(json_body(req), json!({"text": "Titel: Test"}));
}
}
#[tokio::test]
async fn upload_maps_rejections_and_auth_errors() {
for (status, body, expected) in [
(
400,
r#"{"error":"text required"}"#,
BackendError::Rejected("text required".into()),
),
(
422,
r#"{"error":"transcript rejected","errors":["Text zu lang","Kein Admin"]}"#,
BackendError::Rejected("Text zu lang; Kein Admin".into()),
),
(
422,
r#"{"error":"transcript rejected","errors":[]}"#,
BackendError::Rejected("transcript rejected".into()),
),
(
422,
r#"{"error":"transcript rejected","errors":[{"field":"text"}]}"#,
BackendError::Rejected(r#"{"field":"text"}"#.into()),
),
(
401,
r#"{"error":"invalid api key"}"#,
BackendError::InvalidKey,
),
(
503,
r#"{"error":"admin status unavailable"}"#,
BackendError::Unavailable,
),
(
201,
r#"{"id":null}"#,
BackendError::Http(201, "unerwartete Antwort".into()),
),
] {
let (transport, client) = client();
transport.expect(Method::Post, UPLOAD, status, body);
assert_eq!(
client.upload_transcript("euv_k", "x").await,
Err(expected),
"{body}"
);
}
}
#[test]
fn errors_have_german_messages_without_secrets() {
assert_eq!(
BackendError::Forbidden.user_message(),
"Diese Anmeldung kann keinen Schlüssel erzeugen (z. B. bei Impersonation) – bitte als Admin selbst anmelden."
);
assert_eq!(
BackendError::Unavailable.user_message(),
"Backend kann die Anmeldung gerade nicht prüfen – bitte später erneut versuchen."
);
assert_eq!(
BackendError::Rejected("text required".into()).user_message(),
"Backend hat das Transkript abgelehnt: text required"
);
assert_eq!(
BackendError::Transport("Zeitüberschreitung".into()).user_message(),
"Backend nicht erreichbar: Zeitüberschreitung"
);
assert_eq!(
BackendError::Http(500, String::new()).user_message(),
"Backend-Fehler (HTTP 500)"
);
assert_eq!(
BackendError::Http(400, "label too long".into()).user_message(),
"Backend-Fehler (HTTP 400): label too long"
);
assert_eq!(
BackendError::InvalidKey.user_message(),
"Backend-Schlüssel ungültig oder abgelaufen – bitte neu anmelden."
);
assert_eq!(
BackendError::NotLoggedIn.user_message(),
"Nicht beim Backend angemeldet"
);
}
#[test]
fn a_login_step_follows_from_the_create_key_result() {
let key = NewKey {
key: "euv_k".into(),
expires_at: at(2027, 1, 1, 0, 0),
};
assert_eq!(LoginStep::of(Ok(key.clone())), LoginStep::Done(key));
assert_eq!(
LoginStep::of(Err(BackendError::NotLoggedIn)),
LoginStep::Wait
);
assert_eq!(
LoginStep::of(Err(BackendError::Forbidden)),
LoginStep::Fail(BackendError::Forbidden.user_message())
);
for err in [
BackendError::Http(500, String::new()),
BackendError::Transport("weg".into()),
] {
assert_eq!(
LoginStep::of(Err(err.clone())),
LoginStep::Retry(err.user_message())
);
}
}
#[tokio::test]
async fn a_checked_key_is_valid_invalid_or_unknown() {
let (transport, client) = client();
transport.expect(
Method::Get,
KEY_INFO,
200,
r#"{"label":"l","hint":"h","username":"u","createdAt":"2026-11-06T10:00:00+01:00","expiresAt":"2027-11-06T10:00:00+01:00"}"#,
);
transport.expect(Method::Get, KEY_INFO, 401, r#"{"error":"invalid api key"}"#);
transport.expect(Method::Get, KEY_INFO, 503, "");
transport.fail(Method::Get, KEY_INFO, TransportError::Network("dns".into()));
assert!(
matches!(client.check_key("k").await, KeyCheck::Valid(info) if info.username == "u")
);
assert_eq!(client.check_key("k").await, KeyCheck::Invalid);
assert_eq!(
client.check_key("k").await,
KeyCheck::Unknown(BackendError::Unavailable)
);
assert_eq!(
client.check_key("k").await,
KeyCheck::Unknown(BackendError::Transport("Netzwerkfehler: dns".into()))
);
}
fn stored(key: &str, expires_at: Option<DateTime<Local>>) -> StoredKey {
StoredKey {
key: key.into(),
expires_at,
}
}
#[test]
fn a_missing_or_expiring_key_needs_a_login() {
let now = at(2026, 11, 6, 12, 0);
assert!(needs_login(None, now));
assert!(needs_login(Some(&stored("k", Some(now))), now));
assert!(needs_login(
Some(&stored("k", Some(now + chrono::Duration::seconds(60)))),
now
));
assert!(!needs_login(
Some(&stored("k", Some(now + chrono::Duration::seconds(61)))),
now
));
assert!(!needs_login(Some(&stored("k", None)), now));
assert!(!format!("{:?}", stored("euv_secret", None)).contains("euv_secret"));
}
/// Scripted [`Login`]: hands out the given results in order and
/// records the discarded keys.
struct FakeLogin {
results: Mutex<Vec<Result<String, String>>>,
logins: Mutex<usize>,
discarded: Mutex<Vec<String>>,
}
impl FakeLogin {
fn new(results: Vec<Result<String, String>>) -> Self {
Self {
results: Mutex::new(results),
logins: Mutex::new(0),
discarded: Mutex::new(Vec::new()),
}
}
fn counts(&self) -> (usize, usize) {
(
*self.logins.lock().unwrap(),
self.discarded.lock().unwrap().len(),
)
}
fn discarded(&self) -> Vec<String> {
self.discarded.lock().unwrap().clone()
}
}
#[async_trait]
impl Login for FakeLogin {
async fn login(&self) -> Result<String, String> {
*self.logins.lock().unwrap() += 1;
self.results.lock().unwrap().remove(0)
}
async fn discard_key(&self, refused: &str) {
self.discarded.lock().unwrap().push(refused.to_string());
}
}
fn now() -> DateTime<Local> {
at(2026, 11, 6, 12, 0)
}
fn valid(key: &str) -> Option<StoredKey> {
Some(stored(key, Some(at(2027, 11, 6, 12, 0))))
}
#[tokio::test]
async fn without_a_key_the_upload_logs_in_first() {
let (transport, client) = client();
transport.expect(Method::Post, UPLOAD, 201, r#"{"id":1}"#);
let login = FakeLogin::new(vec![Ok("euv_new".into())]);
let id = upload_with_login(&client, &login, None, now(), "t").await;
assert_eq!(id, Ok("1".into()));
assert_eq!(login.counts(), (1, 0));
assert_eq!(transport.requests()[0].header(KEY_HEADER), Some("euv_new"));
}
#[tokio::test]
async fn an_expired_key_is_replaced_before_the_upload() {
let (transport, client) = client();
transport.expect(Method::Post, UPLOAD, 201, r#"{"id":2}"#);
let login = FakeLogin::new(vec![Ok("euv_new".into())]);
let expired = Some(stored("euv_old", Some(now() - chrono::Duration::days(1))));
let id = upload_with_login(&client, &login, expired, now(), "t").await;
assert_eq!(id, Ok("2".into()));
assert_eq!(login.counts(), (1, 0));
assert_eq!(transport.requests()[0].header(KEY_HEADER), Some("euv_new"));
}
#[tokio::test]
async fn a_valid_key_uploads_without_a_login() {
let (transport, client) = client();
transport.expect(Method::Post, UPLOAD, 201, r#"{"id":3}"#);
let login = FakeLogin::new(vec![]);
let id = upload_with_login(&client, &login, valid("euv_k"), now(), "t").await;
assert_eq!(id, Ok("3".into()));
assert_eq!(login.counts(), (0, 0));
}
#[tokio::test]
async fn a_refused_key_is_discarded_and_the_upload_retried_once_after_a_login() {
let (transport, client) = client();
transport.expect(Method::Post, UPLOAD, 401, r#"{"error":"invalid api key"}"#);
transport.expect(Method::Post, UPLOAD, 201, r#"{"id":"crm-9"}"#);
let login = FakeLogin::new(vec![Ok("euv_new".into())]);
let id = upload_with_login(&client, &login, valid("euv_old"), now(), "t").await;
assert_eq!(id, Ok("crm-9".into()));
assert_eq!(login.counts(), (1, 1));
assert_eq!(login.discarded(), ["euv_old"]);
let keys: Vec<_> = transport
.requests()
.iter()
.map(|r| r.header(KEY_HEADER).unwrap().to_string())
.collect();
assert_eq!(keys, ["euv_old", "euv_new"]);
transport.assert_done();
}
#[tokio::test]
async fn a_key_refused_twice_ends_in_an_error_without_looping() {
let (transport, client) = client();
transport.expect(Method::Post, UPLOAD, 401, r#"{"error":"invalid api key"}"#);
transport.expect(Method::Post, UPLOAD, 401, r#"{"error":"invalid api key"}"#);
let login = FakeLogin::new(vec![Ok("euv_new".into())]);
let result = upload_with_login(&client, &login, valid("euv_old"), now(), "t").await;
assert_eq!(result, Err(BackendError::InvalidKey.user_message()));
assert_eq!(login.counts(), (1, 2));
assert_eq!(login.discarded(), ["euv_old", "euv_new"]);
transport.assert_done();
}
#[tokio::test]
async fn an_unavailable_backend_fails_without_a_login() {
let (transport, client) = client();
transport.expect(
Method::Post,
UPLOAD,
503,
r#"{"error":"admin status unavailable"}"#,
);
let login = FakeLogin::new(vec![]);
let result = upload_with_login(&client, &login, valid("euv_k"), now(), "t").await;
assert_eq!(result, Err(BackendError::Unavailable.user_message()));
assert_eq!(login.counts(), (0, 0));
}
#[tokio::test]
async fn a_failed_login_stops_the_upload() {
let (transport, client) = client();
let login = FakeLogin::new(vec![Err("Anmeldung abgebrochen".into())]);
let result = upload_with_login(&client, &login, None, now(), "t").await;
assert_eq!(result, Err("Anmeldung abgebrochen".into()));
assert!(transport.requests().is_empty());
}
#[tokio::test]
async fn an_unreachable_backend_is_reported() {
let (transport, client) = client();
transport.fail(Method::Post, UPLOAD, TransportError::Network("dns".into()));
let login = FakeLogin::new(vec![]);
let result = upload_with_login(&client, &login, valid("euv_k"), now(), "t").await;
assert_eq!(
result,
Err("Backend nicht erreichbar: Netzwerkfehler: dns".into())
);
assert_eq!(login.counts(), (0, 0));
}
}
+242 -13
View File
@@ -21,10 +21,20 @@ pub struct CallListItem {
pub interrupted: bool, pub interrupted: bool,
/// The name the user gave the call, if any. /// The name the user gave the call, if any.
pub title: Option<String>, pub title: Option<String>,
/// The id the CRM gave the transcript at its last upload.
pub crm_transcript_id: Option<String>,
/// When the transcript was last uploaded.
pub uploaded_at: Option<DateTime<Local>>,
} }
impl CallListItem { impl CallListItem {
pub fn of(call: &Call) -> Self { /// `backend_url` is this build's backend (`crate::backend::BACKEND_URL`
/// in the app): an upload recorded for a different one is shown as not
/// uploaded at all ([`uploaded_here`]) — e.g. a transcript sent to the
/// test backend must not look done to a release build reading the same
/// row. Nothing is deleted; the fields are just not shown as set.
pub fn of(call: &Call, backend_url: &str) -> Self {
let uploaded = uploaded_here(call, backend_url);
Self { Self {
id: call.id, id: call.id,
app: call.app.clone(), app: call.app.clone(),
@@ -33,6 +43,12 @@ impl CallListItem {
status: call.status, status: call.status,
interrupted: call.interrupted, interrupted: call.interrupted,
title: call.title.clone(), title: call.title.clone(),
crm_transcript_id: if uploaded {
call.crm_transcript_id.clone()
} else {
None
},
uploaded_at: if uploaded { call.uploaded_at } else { None },
} }
} }
} }
@@ -44,14 +60,25 @@ pub fn duration_secs(call: &Call) -> i64 {
.map_or(0, |end| (end - call.started_at).num_seconds().max(0)) .map_or(0, |end| (end - call.started_at).num_seconds().max(0))
} }
/// Whether `call`'s upload belongs to `backend_url`: its
/// `crm_transcript_id` is set *and* `crm_base_url` is exactly this
/// backend. An upload recorded for a different one (e.g. the test backend,
/// read by a release build) counts as not uploaded: the CRM this
/// `backend_url` talks to has never seen the transcript, so the UI offers
/// the normal upload control again instead of claiming it is done.
pub fn uploaded_here(call: &Call, backend_url: &str) -> bool {
call.crm_transcript_id.is_some() && call.crm_base_url.as_deref() == Some(backend_url)
}
/// The selected call's header data: its list row plus the error of a /// The selected call's header data: its list row plus the error of a
/// failed run and the assigned account. /// failed run and when it was transcribed (only a transcribed call can be
/// uploaded).
#[derive(Serialize, Clone, Debug, PartialEq)] #[derive(Serialize, Clone, Debug, PartialEq)]
pub struct CallHeader { pub struct CallHeader {
#[serde(flatten)] #[serde(flatten)]
pub item: CallListItem, pub item: CallListItem,
pub error: Option<String>, pub error: Option<String>,
pub account_id: Option<String>, pub transcribed_at: Option<DateTime<Local>>,
} }
/// A transcript line with the speaker's display label. /// A transcript line with the speaker's display label.
@@ -90,16 +117,21 @@ pub struct CallDetail {
pub speaker_names: BTreeMap<String, String>, pub speaker_names: BTreeMap<String, String>,
/// The call's speaker merges, by source speaker number. /// The call's speaker merges, by source speaker number.
pub merges: Vec<MergeView>, pub merges: Vec<MergeView>,
/// Whether the transcript is being uploaded right now. Set by the app,
/// which tracks its uploads; `false` from [`CallDetail::of`].
pub uploading: bool,
} }
impl CallDetail { impl CallDetail {
/// `segments` are the stored ones; `merges` the stored speaker merges /// `segments` are the stored ones; `merges` the stored speaker merges
/// (source key → target key). /// (source key → target key); `backend_url` is this build's backend
/// (see [`CallListItem::of`]).
pub fn of( pub fn of(
call: &Call, call: &Call,
segments: &[Segment], segments: &[Segment],
speaker_names: BTreeMap<String, String>, speaker_names: BTreeMap<String, String>,
merges: &BTreeMap<String, String>, merges: &BTreeMap<String, String>,
backend_url: &str,
) -> Self { ) -> Self {
let segments = merge::apply_merges(segments, merges) let segments = merge::apply_merges(segments, merges)
.iter() .iter()
@@ -113,17 +145,82 @@ impl CallDetail {
.collect(); .collect();
Self { Self {
call: CallHeader { call: CallHeader {
item: CallListItem::of(call), item: CallListItem::of(call, backend_url),
error: call.error.clone(), error: call.error.clone(),
account_id: call.account_id.clone(), transcribed_at: call.transcribed_at,
}, },
segments, segments,
merges: merge_views(merges, &speaker_names), merges: merge_views(merges, &speaker_names),
uploading: false,
speaker_names, speaker_names,
} }
} }
} }
impl CallDetail {
/// The transcript as plain text for the CRM, as the user sees it
/// (speaker merges and renames applied): a header with title, date,
/// call app and duration, a blank line, then one `[mm:ss] Name: text`
/// line per segment (`h:mm:ss` from one hour on). Blank segments are
/// left out; with none left, the error is [`NO_TRANSCRIPT`].
pub fn upload_text(&self) -> Result<String, String> {
let lines: Vec<String> = self
.segments
.iter()
.filter(|segment| !segment.text.trim().is_empty())
.map(|segment| {
format!(
"[{}] {}: {}",
offset(segment.start),
segment.label,
segment.text.trim()
)
})
.collect();
if lines.is_empty() {
return Err(NO_TRANSCRIPT.to_string());
}
let item = &self.call.item;
let date = item.started_at.format("%d.%m.%Y %H:%M").to_string();
let title = match &item.title {
Some(title) => title.clone(),
None => format!("{} · {date}", item.app),
};
let minutes = ((item.duration_secs as f64 / 60.0).round() as i64).max(1);
let header = [
format!("Titel: {title}"),
format!("Datum: {date}"),
format!("Kanal: {}", item.app),
format!("Dauer: {minutes} min"),
String::new(),
];
Ok(header
.into_iter()
.chain(lines)
.collect::<Vec<_>>()
.join("\n"))
}
}
/// Why [`CallDetail::upload_text`] has nothing to upload.
pub const NO_TRANSCRIPT: &str = "Kein Transkript zum Hochladen";
/// Position in the recording: "04:07", or "1:02:07" from one hour on (like
/// the transcript view).
fn offset(secs: f64) -> String {
let total = if secs.is_finite() && secs > 0.0 {
secs as u64
} else {
0
};
let (h, m, s) = (total / 3600, total % 3600 / 60, total % 60);
if h > 0 {
format!("{h}:{m:02}:{s:02}")
} else {
format!("{m:02}:{s:02}")
}
}
fn merge_views( fn merge_views(
merges: &BTreeMap<String, String>, merges: &BTreeMap<String, String>,
speaker_names: &BTreeMap<String, String>, speaker_names: &BTreeMap<String, String>,
@@ -159,6 +256,11 @@ mod tests {
use super::*; use super::*;
use crate::model::Speaker; use crate::model::Speaker;
/// This build's backend, for `CallListItem::of`/`CallDetail::of`.
const BACKEND: &str = "https://backend.example";
/// A different backend, for the "uploaded elsewhere" cases.
const OTHER_BACKEND: &str = "https://other.example";
fn at(h: u32, m: u32, s: u32) -> DateTime<Local> { fn at(h: u32, m: u32, s: u32) -> DateTime<Local> {
Local.with_ymd_and_hms(2026, 11, 5, h, m, s).unwrap() Local.with_ymd_and_hms(2026, 11, 5, h, m, s).unwrap()
} }
@@ -176,8 +278,10 @@ mod tests {
out_path: PathBuf::from("7-out.wav"), out_path: PathBuf::from("7-out.wav"),
transcribed_at: None, transcribed_at: None,
audio_deleted: false, audio_deleted: false,
account_id: None,
title: None, title: None,
crm_transcript_id: None,
crm_base_url: None,
uploaded_at: None,
} }
} }
@@ -207,7 +311,7 @@ mod tests {
c.status = CallStatus::AwaitingDecision; c.status = CallStatus::AwaitingDecision;
c.interrupted = true; c.interrupted = true;
assert_eq!( assert_eq!(
CallListItem::of(&c), CallListItem::of(&c, BACKEND),
CallListItem { CallListItem {
id: 7, id: 7,
app: "Microsoft Teams".into(), app: "Microsoft Teams".into(),
@@ -216,11 +320,56 @@ mod tests {
status: CallStatus::AwaitingDecision, status: CallStatus::AwaitingDecision,
interrupted: true, interrupted: true,
title: None, title: None,
crm_transcript_id: None,
uploaded_at: None,
} }
); );
c.title = Some("Angebot Rioja".into()); c.title = Some("Angebot Rioja".into());
assert_eq!(CallListItem::of(&c).title.as_deref(), Some("Angebot Rioja")); c.crm_transcript_id = Some("4711".into());
c.crm_base_url = Some(BACKEND.into());
c.uploaded_at = Some(at(11, 0, 0));
let item = CallListItem::of(&c, BACKEND);
assert_eq!(item.title.as_deref(), Some("Angebot Rioja"));
assert_eq!(item.crm_transcript_id.as_deref(), Some("4711"));
assert_eq!(item.uploaded_at, Some(at(11, 0, 0)));
}
#[test]
fn uploaded_here_needs_a_transcript_id_and_a_matching_backend() {
let mut c = call(Some(at(10, 15, 0)));
assert!(!uploaded_here(&c, BACKEND), "never uploaded");
c.crm_transcript_id = Some("4711".into());
c.crm_base_url = Some(OTHER_BACKEND.into());
assert!(
!uploaded_here(&c, BACKEND),
"uploaded, but to a different backend"
);
c.crm_base_url = Some(BACKEND.into());
assert!(uploaded_here(&c, BACKEND));
}
#[test]
fn an_upload_to_another_backend_is_hidden_from_the_list_item() {
// Uploaded to OTHER_BACKEND; this build's backend is BACKEND: the
// row still has crm_transcript_id/uploaded_at, but the view must
// not show them, so the UI offers the normal upload control again.
let mut c = call(Some(at(10, 15, 0)));
c.crm_transcript_id = Some("4711".into());
c.crm_base_url = Some(OTHER_BACKEND.into());
c.uploaded_at = Some(at(11, 0, 0));
let item = CallListItem::of(&c, BACKEND);
assert_eq!(item.crm_transcript_id, None);
assert_eq!(item.uploaded_at, None);
// The same row, read by a build whose backend actually matches:
// shown normally.
let item = CallListItem::of(&c, OTHER_BACKEND);
assert_eq!(item.crm_transcript_id.as_deref(), Some("4711"));
assert_eq!(item.uploaded_at, Some(at(11, 0, 0)));
} }
#[test] #[test]
@@ -239,6 +388,7 @@ mod tests {
&segments, &segments,
names.clone(), names.clone(),
&BTreeMap::new(), &BTreeMap::new(),
BACKEND,
); );
let lines: Vec<_> = detail let lines: Vec<_> = detail
@@ -283,7 +433,13 @@ mod tests {
("remote:10", "remote:4"), ("remote:10", "remote:4"),
]); ]);
let detail = CallDetail::of(&call(Some(at(10, 15, 0))), &segments, names, &merges); let detail = CallDetail::of(
&call(Some(at(10, 15, 0))),
&segments,
names,
&merges,
BACKEND,
);
let lines: Vec<_> = detail let lines: Vec<_> = detail
.segments .segments
@@ -330,12 +486,13 @@ mod tests {
let mut c = call(Some(at(10, 15, 0))); let mut c = call(Some(at(10, 15, 0)));
c.status = CallStatus::Failed; c.status = CallStatus::Failed;
c.error = Some("Netzwerkfehler".into()); c.error = Some("Netzwerkfehler".into());
c.account_id = Some("mock-2".into());
c.title = Some("Reklamation".into()); c.title = Some("Reklamation".into());
c.transcribed_at = Some(at(10, 20, 0));
let merges = keys(&[("remote:2", "remote:1")]); let merges = keys(&[("remote:2", "remote:1")]);
let value = let value =
serde_json::to_value(CallDetail::of(&c, &[], BTreeMap::new(), &merges)).unwrap(); serde_json::to_value(CallDetail::of(&c, &[], BTreeMap::new(), &merges, BACKEND))
.unwrap();
assert_eq!( assert_eq!(
value, value,
@@ -348,8 +505,10 @@ mod tests {
"status": "failed", "status": "failed",
"interrupted": false, "interrupted": false,
"title": "Reklamation", "title": "Reklamation",
"crm_transcript_id": null,
"uploaded_at": null,
"error": "Netzwerkfehler", "error": "Netzwerkfehler",
"account_id": "mock-2", "transcribed_at": serde_json::to_value(at(10, 20, 0)).unwrap(),
}, },
"segments": [], "segments": [],
"speaker_names": {}, "speaker_names": {},
@@ -359,7 +518,77 @@ mod tests {
"into_key": "remote:1", "into_key": "remote:1",
"into_label": "Sprecher 1", "into_label": "Sprecher 1",
}], }],
"uploading": false,
}) })
); );
} }
fn detail_with(c: &Call, segments: &[Segment], names: &[(&str, &str)]) -> CallDetail {
CallDetail::of(
c,
segments,
keys(names),
&keys(&[("remote:2", "remote:1")]),
BACKEND,
)
}
#[test]
fn the_upload_text_has_a_header_and_the_lines_the_user_sees() {
let segments = [
segment(Speaker::Remote(1), 0.0, "Guten Tag,"),
segment(Speaker::Remote(2), 2.5, "hier Weingut Beispiel."),
segment(Speaker::Me, 65.9, "Hallo."),
segment(Speaker::Remote(3), 600.0, " "),
segment(Speaker::Remote(1), 3725.0, "Zur Lieferung."),
];
let c = call(Some(at(10, 46, 0)));
let text = detail_with(&c, &segments, &[("remote:1", "Frau Beispiel")]).upload_text();
assert_eq!(
text.as_deref(),
Ok("Titel: Microsoft Teams · 05.11.2026 10:14\n\
Datum: 05.11.2026 10:14\n\
Kanal: Microsoft Teams\n\
Dauer: 32 min\n\
\n\
[00:00] Frau Beispiel: Guten Tag, hier Weingut Beispiel.\n\
[01:05] Ich: Hallo.\n\
[1:02:05] Frau Beispiel: Zur Lieferung.")
);
}
#[test]
fn the_upload_text_uses_the_title_and_at_least_one_minute() {
let mut c = call(Some(at(10, 14, 10)));
c.title = Some("Angebot Rioja".into());
let text = detail_with(&c, &[segment(Speaker::Me, 0.0, "Hallo.")], &[])
.upload_text()
.unwrap();
let header: Vec<_> = text.lines().take(4).collect();
assert_eq!(
header,
[
"Titel: Angebot Rioja",
"Datum: 05.11.2026 10:14",
"Kanal: Microsoft Teams",
"Dauer: 1 min",
]
);
}
#[test]
fn an_empty_transcript_is_not_uploaded() {
let c = call(Some(at(10, 46, 0)));
for segments in [vec![], vec![segment(Speaker::Me, 0.0, " ")]] {
assert_eq!(
detail_with(&c, &segments, &[]).upload_text(),
Err(NO_TRANSCRIPT.to_string())
);
}
assert_eq!(NO_TRANSCRIPT, "Kein Transkript zum Hochladen");
}
} }
+35 -17
View File
@@ -1,7 +1,6 @@
//! The HTTP transport seam: every outgoing request the DeepScript and Claude //! The HTTP transport seam: every outgoing request the API clients make goes
//! clients (Tasks 12/13) make goes through [`HttpTransport`], so unit tests //! through [`HttpTransport`], so unit tests can swap in
//! can swap in [`crate::testing::FakeTransport`] and run with the network //! [`crate::testing::FakeTransport`] and run with the network unplugged. [`ReqwestTransport`] is the real implementation, exercised only
//! unplugged. [`ReqwestTransport`] is the real implementation, exercised only
//! by the live integration suite (`crates/core/tests/live_api.rs`). //! by the live integration suite (`crates/core/tests/live_api.rs`).
use std::path::PathBuf; use std::path::PathBuf;
@@ -51,6 +50,9 @@ pub struct HttpRequest {
pub url: String, pub url: String,
pub headers: Vec<(String, String)>, pub headers: Vec<(String, String)>,
pub body: HttpBody, pub body: HttpBody,
/// `false` returns a redirect (3xx) as the response instead of
/// following it.
pub follow_redirects: bool,
} }
impl HttpRequest { impl HttpRequest {
@@ -99,22 +101,30 @@ pub trait HttpTransport: Send + Sync {
async fn send(&self, req: HttpRequest) -> Result<HttpResponse, TransportError>; async fn send(&self, req: HttpRequest) -> Result<HttpResponse, TransportError>;
} }
/// Live `HttpTransport` backed by `reqwest` (rustls). Shares one /// Live `HttpTransport` backed by `reqwest` (rustls). Shares its
/// `reqwest::Client` (connection pooling) with a 10 minute request timeout /// `reqwest::Client`s (connection pooling) with a 10 minute request timeout
/// and a 30 second connect timeout, matching the Claude/DeepScript clients' /// and a 30 second connect timeout, matching the DeepScript client's
/// worst-case wait. /// worst-case wait. reqwest sets the redirect policy per client, so there
/// is one that follows redirects and one that does not.
pub struct ReqwestTransport { pub struct ReqwestTransport {
client: reqwest::Client, client: reqwest::Client,
no_redirect_client: reqwest::Client,
} }
impl ReqwestTransport { impl ReqwestTransport {
pub fn new() -> Self { pub fn new() -> Self {
let client = reqwest::Client::builder() let build = |redirects| {
.timeout(Duration::from_secs(10 * 60)) reqwest::Client::builder()
.connect_timeout(Duration::from_secs(30)) .timeout(Duration::from_secs(10 * 60))
.build() .connect_timeout(Duration::from_secs(30))
.expect("failed to build reqwest client"); .redirect(redirects)
ReqwestTransport { client } .build()
.expect("failed to build reqwest client")
};
ReqwestTransport {
client: build(reqwest::redirect::Policy::default()),
no_redirect_client: build(reqwest::redirect::Policy::none()),
}
} }
} }
@@ -127,10 +137,15 @@ impl Default for ReqwestTransport {
#[async_trait] #[async_trait]
impl HttpTransport for ReqwestTransport { impl HttpTransport for ReqwestTransport {
async fn send(&self, req: HttpRequest) -> Result<HttpResponse, TransportError> { async fn send(&self, req: HttpRequest) -> Result<HttpResponse, TransportError> {
let client = if req.follow_redirects {
&self.client
} else {
&self.no_redirect_client
};
let mut builder = match req.method { let mut builder = match req.method {
Method::Get => self.client.get(&req.url), Method::Get => client.get(&req.url),
Method::Post => self.client.post(&req.url), Method::Post => client.post(&req.url),
Method::Delete => self.client.delete(&req.url), Method::Delete => client.delete(&req.url),
}; };
for (name, value) in &req.headers { for (name, value) in &req.headers {
builder = builder.header(name, value); builder = builder.header(name, value);
@@ -203,6 +218,7 @@ mod tests {
url: url.to_string(), url: url.to_string(),
headers: vec![], headers: vec![],
body: HttpBody::Empty, body: HttpBody::Empty,
follow_redirects: true,
} }
} }
@@ -225,6 +241,7 @@ mod tests {
url: "https://api.example.com/b?x=1".to_string(), url: "https://api.example.com/b?x=1".to_string(),
headers: vec![("x-test".to_string(), "1".to_string())], headers: vec![("x-test".to_string(), "1".to_string())],
body: HttpBody::Empty, body: HttpBody::Empty,
follow_redirects: true,
}) })
.await .await
.unwrap(); .unwrap();
@@ -265,6 +282,7 @@ mod tests {
url: "https://api.example.com".to_string(), url: "https://api.example.com".to_string(),
headers: vec![("Authorization".to_string(), "Bearer xyz".to_string())], headers: vec![("Authorization".to_string(), "Bearer xyz".to_string())],
body: HttpBody::Empty, body: HttpBody::Empty,
follow_redirects: true,
}; };
assert_eq!(req.header("authorization"), Some("Bearer xyz")); assert_eq!(req.header("authorization"), Some("Bearer xyz"));
assert_eq!(req.header("missing"), None); assert_eq!(req.header("missing"), None);
+4 -4
View File
@@ -1,11 +1,11 @@
//! Core domain logic for the Gesprächsrekorder call recorder. //! Core domain logic for the Gesprächsrekorder call recorder.
//! //!
//! This crate will grow to hold call detection, recording orchestration, //! Call detection, recording orchestration and transcription, kept
//! transcription and summarization logic, kept independent of the Tauri //! independent of the Tauri application shell so it can be unit-tested
//! application shell so it can be unit-tested without a GUI or network. //! without a GUI or network.
pub mod accounts;
pub mod audio; pub mod audio;
pub mod backend;
pub mod call_view; pub mod call_view;
pub mod capture; pub mod capture;
pub mod detect; pub mod detect;
+10 -37
View File
@@ -3,7 +3,7 @@
use std::path::PathBuf; use std::path::PathBuf;
use chrono::{DateTime, Local, NaiveDate}; use chrono::{DateTime, Local};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
/// Primary key of a `calls` row (SQLite `rowid`). /// Primary key of a `calls` row (SQLite `rowid`).
@@ -37,9 +37,17 @@ pub struct Call {
pub out_path: PathBuf, pub out_path: PathBuf,
pub transcribed_at: Option<DateTime<Local>>, pub transcribed_at: Option<DateTime<Local>>,
pub audio_deleted: bool, pub audio_deleted: bool,
pub account_id: Option<String>,
/// The name the user gave the call, if any. /// The name the user gave the call, if any.
pub title: Option<String>, pub title: Option<String>,
/// The id the CRM gave the transcript at its last upload.
pub crm_transcript_id: Option<String>,
/// The backend ([`crate::backend`]'s base URL) `crm_transcript_id` was
/// uploaded to; `None` if never uploaded. A build whose own backend
/// differs (e.g. release reading a row a test build uploaded) does not
/// count this as uploaded — see `call_view::uploaded_here`.
pub crm_base_url: Option<String>,
/// When the transcript was last uploaded.
pub uploaded_at: Option<DateTime<Local>>,
} }
/// A single transcribed word with its timing and speaker attribution. /// A single transcribed word with its timing and speaker attribution.
@@ -97,38 +105,3 @@ pub struct Segment {
pub end: f64, pub end: f64,
pub text: String, pub text: String,
} }
/// Who owns a to-do coming out of the call summary.
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Owner {
Ich,
Kunde,
Sonstige,
}
/// A single action item extracted from the call summary.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Todo {
pub text: String,
pub owner: Owner,
pub faellig: Option<NaiveDate>,
#[serde(default)]
pub erledigt: bool,
}
/// The next agreed point of contact, if any.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
pub struct NaechsterKontakt {
pub datum: Option<NaiveDate>,
pub notiz: Option<String>,
}
/// Structured summary produced by Claude for a finished call.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Summary {
pub kernpunkte: Vec<String>,
pub vereinbarungen: Vec<String>,
pub todos: Vec<Todo>,
pub naechster_kontakt: NaechsterKontakt,
}
-1
View File
@@ -108,7 +108,6 @@ async fn run(
// Jobs whose delete failed in an earlier run. // Jobs whose delete failed in an earlier run.
delete_remote_jobs(store, tr, id).await; delete_remote_jobs(store, tr, id).await;
} }
// SUMMARY SEAM (Task 14b): summarize here.
store.set_status(id, CallStatus::Done, None)?; store.set_status(id, CallStatus::Done, None)?;
log::info!("call {id}: done"); log::info!("call {id}: done");
Ok(()) Ok(())
+4 -2
View File
@@ -10,7 +10,7 @@ use crate::model::{Call, CallId, CallStatus};
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RetentionAction { pub enum RetentionAction {
/// Delete the call's audio file(s) on disk; the row stays (it has a /// Delete the call's audio file(s) on disk; the row stays (it has a
/// summary/transcript worth keeping). /// transcript worth keeping).
DeleteAudio(CallId), DeleteAudio(CallId),
/// Delete the whole call row (and everything derived from it). /// Delete the whole call row (and everything derived from it).
DeleteCall(CallId), DeleteCall(CallId),
@@ -88,8 +88,10 @@ mod tests {
out_path: PathBuf::from("/tmp/out.wav"), out_path: PathBuf::from("/tmp/out.wav"),
transcribed_at: None, transcribed_at: None,
audio_deleted: false, audio_deleted: false,
account_id: None,
title: None, title: None,
crm_transcript_id: None,
crm_base_url: None,
uploaded_at: None,
} }
} }
+35 -5
View File
@@ -1,5 +1,7 @@
//! API keys, stored only in the OS keyring (Windows Credential Manager, //! API keys, stored only in the OS keyring (Windows Credential Manager,
//! Linux Secret Service) under the service `eu.euvino.callrecorder`. //! Linux Secret Service) under the service `eu.euvino.callrecorder`: the
//! DeepScript key the user enters and the euvino admin backend key the
//! login creates.
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::Mutex; use std::sync::Mutex;
@@ -15,7 +17,7 @@ pub const KEYRING_SERVICE: &str = "eu.euvino.callrecorder";
#[serde(rename_all = "lowercase")] #[serde(rename_all = "lowercase")]
pub enum Service { pub enum Service {
DeepScript, DeepScript,
Anthropic, Backend,
} }
impl Service { impl Service {
@@ -23,7 +25,7 @@ impl Service {
pub fn user(self) -> &'static str { pub fn user(self) -> &'static str {
match self { match self {
Service::DeepScript => "deepscript", Service::DeepScript => "deepscript",
Service::Anthropic => "anthropic", Service::Backend => "backend",
} }
} }
} }
@@ -45,6 +47,10 @@ pub trait SecretStore: Send + Sync {
fn delete(&self, s: Service) -> Result<()>; fn delete(&self, s: Service) -> Result<()>;
} }
/// Keyring users of keys that earlier versions stored and this one no
/// longer uses: the Anthropic key of the dropped Claude summary.
const UNUSED_USERS: [&str; 1] = ["anthropic"];
/// The OS keyring. /// The OS keyring.
pub struct KeyringSecrets; pub struct KeyringSecrets;
@@ -53,6 +59,21 @@ impl KeyringSecrets {
keyring::Entry::new(KEYRING_SERVICE, s.user()) keyring::Entry::new(KEYRING_SERVICE, s.user())
.map_err(|e| SecretError::Keyring(e.to_string())) .map_err(|e| SecretError::Keyring(e.to_string()))
} }
/// Best-effort deletes the keys earlier versions stored and this one no
/// longer uses, so no stale secret lingers in the keyring. Missing
/// entries and failures are only logged (never the key).
pub fn remove_unused_keys() {
for user in UNUSED_USERS {
let result =
keyring::Entry::new(KEYRING_SERVICE, user).and_then(|e| e.delete_credential());
match result {
Ok(()) => log::info!("removed the unused keyring entry {user:?}"),
Err(keyring::Error::NoEntry) => {}
Err(e) => log::info!("could not remove the unused keyring entry {user:?}: {e}"),
}
}
}
} }
impl SecretStore for KeyringSecrets { impl SecretStore for KeyringSecrets {
@@ -100,6 +121,8 @@ impl SecretStore for MemorySecrets {
mod tests { mod tests {
use super::*; use super::*;
const SERVICES: &[Service] = &[Service::DeepScript, Service::Backend];
#[test] #[test]
fn memory_secrets_roundtrip() { fn memory_secrets_roundtrip() {
let secrets = MemorySecrets::default(); let secrets = MemorySecrets::default();
@@ -107,16 +130,23 @@ mod tests {
secrets.set(Service::DeepScript, "ds-key").unwrap(); secrets.set(Service::DeepScript, "ds-key").unwrap();
assert_eq!(secrets.get(Service::DeepScript).as_deref(), Some("ds-key")); assert_eq!(secrets.get(Service::DeepScript).as_deref(), Some("ds-key"));
assert_eq!(secrets.get(Service::Anthropic), None); assert_eq!(secrets.get(Service::Backend), None);
secrets.delete(Service::DeepScript).unwrap(); secrets.delete(Service::DeepScript).unwrap();
assert_eq!(secrets.get(Service::DeepScript), None); assert_eq!(secrets.get(Service::DeepScript), None);
secrets.delete(Service::DeepScript).unwrap(); secrets.delete(Service::DeepScript).unwrap();
} }
#[test]
fn unused_keys_never_include_a_key_in_use() {
for &s in SERVICES {
assert!(!UNUSED_USERS.contains(&s.user()), "{s:?}");
}
}
#[test] #[test]
fn service_serializes_as_keyring_user() { fn service_serializes_as_keyring_user() {
for s in [Service::DeepScript, Service::Anthropic] { for &s in SERVICES {
let json = serde_json::to_string(&s).unwrap(); let json = serde_json::to_string(&s).unwrap();
assert_eq!(json, format!("\"{}\"", s.user())); assert_eq!(json, format!("\"{}\"", s.user()));
assert_eq!(serde_json::from_str::<Service>(&json).unwrap(), s); assert_eq!(serde_json::from_str::<Service>(&json).unwrap(), s);
+88
View File
@@ -8,6 +8,7 @@ use std::io;
use std::ops::RangeInclusive; use std::ops::RangeInclusive;
use std::path::Path; use std::path::Path;
use chrono::{DateTime, Local};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
/// Executables whose mic use counts as a call (matched case-insensitively). /// Executables whose mic use counts as a call (matched case-insensitively).
@@ -38,6 +39,14 @@ pub struct Settings {
pub autostart: bool, pub autostart: bool,
pub start_after_secs: u64, pub start_after_secs: u64,
pub end_after_secs: u64, pub end_after_secs: u64,
/// Whose backend key is stored (the key itself is in the keyring). Set
/// by the app at login, not by the user.
pub backend_username: Option<String>,
/// When the stored backend key expires. Set by the app at login.
pub backend_key_expires_at: Option<DateTime<Local>>,
/// The backend the stored key was created for: it is sent to that one
/// only. Set by the app at login.
pub backend_key_base_url: Option<String>,
} }
impl Default for Settings { impl Default for Settings {
@@ -52,6 +61,9 @@ impl Default for Settings {
autostart: true, autostart: true,
start_after_secs: 3, start_after_secs: 3,
end_after_secs: 10, end_after_secs: 10,
backend_username: None,
backend_key_expires_at: None,
backend_key_base_url: None,
} }
} }
} }
@@ -76,6 +88,17 @@ impl Settings {
Ok(()) Ok(())
} }
/// The settings after the user saved `edited` over these: checked, with
/// the backend login (which only the app changes) kept, so a settings
/// page loaded before a login cannot undo it.
pub fn edited(&self, mut edited: Settings) -> Result<Settings, String> {
edited.validate()?;
edited.backend_username = self.backend_username.clone();
edited.backend_key_expires_at = self.backend_key_expires_at;
edited.backend_key_base_url = self.backend_key_base_url.clone();
Ok(edited)
}
/// Reads the settings file. A missing or unreadable file yields the /// Reads the settings file. A missing or unreadable file yields the
/// defaults; fields missing from the file take their default value. /// defaults; fields missing from the file take their default value.
pub fn load(path: &Path) -> Settings { pub fn load(path: &Path) -> Settings {
@@ -124,6 +147,71 @@ mod tests {
assert!(s.autostart); assert!(s.autostart);
assert_eq!(s.start_after_secs, 3); assert_eq!(s.start_after_secs, 3);
assert_eq!(s.end_after_secs, 10); assert_eq!(s.end_after_secs, 10);
assert_eq!(s.backend_username, None);
assert_eq!(s.backend_key_expires_at, None);
assert_eq!(s.backend_key_base_url, None);
}
#[test]
fn a_backend_url_in_an_older_file_is_ignored() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("settings.json");
fs::write(
&path,
r#"{"retention_days": 9, "backend_url": "https://other.example"}"#,
)
.unwrap();
assert_eq!(
Settings::load(&path),
Settings {
retention_days: 9,
..Settings::default()
}
);
}
fn logged_in() -> Settings {
Settings {
backend_username: Some("hinrichs".into()),
backend_key_expires_at: Some(
chrono::DateTime::parse_from_rfc3339("2027-11-06T10:00:00+01:00")
.unwrap()
.into(),
),
backend_key_base_url: Some("https://test.euvinopro.eu".into()),
..Settings::default()
}
}
#[test]
fn an_edit_keeps_the_backend_login_which_only_the_app_changes() {
let current = logged_in();
let edited = Settings {
retention_days: 30,
backend_username: None,
backend_key_expires_at: None,
backend_key_base_url: Some("https://elsewhere.example".into()),
..Settings::default()
};
let saved = current.edited(edited).unwrap();
assert_eq!(
saved,
Settings {
retention_days: 30,
..logged_in()
}
);
}
#[test]
fn an_invalid_edit_is_refused() {
let edited = Settings {
start_after_secs: 0,
..Settings::default()
};
assert!(logged_in().edited(edited).is_err());
} }
#[test] #[test]
+238 -108
View File
@@ -1,5 +1,5 @@
//! SQLite-backed persistence for calls, their transcripts, summaries, //! SQLite-backed persistence for calls, their transcripts, speaker renames
//! speaker renames and outstanding remote transcription/summary jobs. //! and merges, and outstanding remote transcription jobs.
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@@ -10,7 +10,7 @@ use rusqlite::{params, Connection, Row, TransactionBehavior};
use thiserror::Error; use thiserror::Error;
use crate::merge::{self, MergeError}; use crate::merge::{self, MergeError};
use crate::model::{Call, CallId, CallStatus, Segment, Speaker, Summary}; use crate::model::{Call, CallId, CallStatus, Segment, Speaker};
/// Longest call title, in characters. /// Longest call title, in characters.
const MAX_TITLE_CHARS: usize = 120; const MAX_TITLE_CHARS: usize = 120;
@@ -22,8 +22,8 @@ pub enum StoreError {
Sqlite(#[from] rusqlite::Error), Sqlite(#[from] rusqlite::Error),
/// A value read back from SQLite could not be interpreted, e.g. an /// A value read back from SQLite could not be interpreted, e.g. an
/// unknown `status` string, invalid RFC 3339 timestamp, unparsable /// unknown `status` string, invalid RFC 3339 timestamp or unparsable
/// speaker key or malformed summary JSON. /// speaker key.
#[error("corrupt stored value: {0}")] #[error("corrupt stored value: {0}")]
Corrupt(String), Corrupt(String),
@@ -51,7 +51,9 @@ pub struct RecoveryReport {
pub failed: Vec<CallId>, pub failed: Vec<CallId>,
} }
/// Version 1: the first release. /// Version 1: the first release. `calls.account_id` (the customer mock) and
/// `summaries` are no longer used; they stay so no migration has to drop
/// them.
const SCHEMA_V1_SQL: &str = " const SCHEMA_V1_SQL: &str = "
CREATE TABLE IF NOT EXISTS calls ( CREATE TABLE IF NOT EXISTS calls (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -112,9 +114,25 @@ CREATE TABLE speaker_merges (
); );
"; ";
/// Version 3: the last upload of the transcript to the CRM.
const SCHEMA_V3_SQL: &str = "
ALTER TABLE calls ADD COLUMN crm_transcript_id TEXT;
ALTER TABLE calls ADD COLUMN uploaded_at TEXT;
";
/// Version 4: which backend an upload belongs to, so a build whose own
/// backend differs (see `crate::backend`) does not show someone else's
/// upload as done (`call_view::uploaded_here`). Every upload before this
/// version only ever went to the test backend (production never had the
/// API yet): backfilled here, so existing rows keep meaning what they did.
const SCHEMA_V4_SQL: &str = "
ALTER TABLE calls ADD COLUMN crm_base_url TEXT;
UPDATE calls SET crm_base_url = 'https://test.euvinopro.eu' WHERE crm_transcript_id IS NOT NULL;
";
/// Schema steps by `PRAGMA user_version`: entry `i` takes a database from /// Schema steps by `PRAGMA user_version`: entry `i` takes a database from
/// version `i` to `i + 1`. A new database runs all of them. /// version `i` to `i + 1`. A new database runs all of them.
const MIGRATIONS: &[&str] = &[SCHEMA_V1_SQL, SCHEMA_V2_SQL]; const MIGRATIONS: &[&str] = &[SCHEMA_V1_SQL, SCHEMA_V2_SQL, SCHEMA_V3_SQL, SCHEMA_V4_SQL];
/// SQLite-backed store for calls and everything derived from them. /// SQLite-backed store for calls and everything derived from them.
pub struct Store { pub struct Store {
@@ -152,8 +170,8 @@ impl Store {
let conn = self.conn.lock().unwrap(); let conn = self.conn.lock().unwrap();
conn.execute( conn.execute(
"INSERT INTO calls \ "INSERT INTO calls \
(app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, account_id) \ (app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted) \
VALUES (?1, ?2, NULL, ?3, 0, NULL, ?4, ?5, NULL, 0, NULL)", VALUES (?1, ?2, NULL, ?3, 0, NULL, ?4, ?5, NULL, 0)",
params![ params![
app, app,
dt_to_str(started_at), dt_to_str(started_at),
@@ -271,33 +289,6 @@ impl Store {
Ok(segments) Ok(segments)
} }
pub fn save_summary(&self, id: CallId, summary: &Summary, edited: bool) -> Result<()> {
let conn = self.conn.lock().unwrap();
let json = serde_json::to_string(summary)
.map_err(|e| StoreError::Corrupt(format!("failed to serialize summary: {e}")))?;
conn.execute(
"INSERT INTO summaries (call_id, json, edited) VALUES (?1, ?2, ?3) \
ON CONFLICT(call_id) DO UPDATE SET json = excluded.json, edited = excluded.edited",
params![id, json, edited],
)?;
Ok(())
}
pub fn summary(&self, id: CallId) -> Result<Option<Summary>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare("SELECT json FROM summaries WHERE call_id = ?1")?;
let mut rows = stmt.query(params![id])?;
match rows.next()? {
Some(row) => {
let json: String = row.get(0)?;
let summary = serde_json::from_str(&json)
.map_err(|e| StoreError::Corrupt(format!("invalid summary json: {e}")))?;
Ok(Some(summary))
}
None => Ok(None),
}
}
pub fn set_speaker_name(&self, id: CallId, speaker_key: &str, name: &str) -> Result<()> { pub fn set_speaker_name(&self, id: CallId, speaker_key: &str, name: &str) -> Result<()> {
let conn = self.conn.lock().unwrap(); let conn = self.conn.lock().unwrap();
conn.execute( conn.execute(
@@ -380,6 +371,25 @@ impl Store {
Ok(()) Ok(())
} }
/// Records that the transcript was uploaded to `crm_base_url` at `at`,
/// which gave it `crm_transcript_id`; replaces an earlier upload's
/// record (even one of another backend — one upload slot per call, see
/// `call_view::uploaded_here`).
pub fn set_uploaded(
&self,
id: CallId,
crm_transcript_id: &str,
crm_base_url: &str,
at: DateTime<Local>,
) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"UPDATE calls SET crm_transcript_id = ?1, crm_base_url = ?2, uploaded_at = ?3 WHERE id = ?4",
params![crm_transcript_id, crm_base_url, dt_to_str(at), id],
)?;
Ok(())
}
pub fn mark_transcribed(&self, id: CallId, at: DateTime<Local>) -> Result<()> { pub fn mark_transcribed(&self, id: CallId, at: DateTime<Local>) -> Result<()> {
let conn = self.conn.lock().unwrap(); let conn = self.conn.lock().unwrap();
conn.execute( conn.execute(
@@ -398,8 +408,9 @@ impl Store {
Ok(()) Ok(())
} }
/// Deletes a call and every row derived from it (segments, summary, /// Deletes a call and every row derived from it (segments, speaker
/// speaker names and merges, remote jobs). /// names and merges, remote jobs; also the `summaries` table of schema
/// v1, which nothing writes).
pub fn delete_call(&self, id: CallId) -> Result<()> { pub fn delete_call(&self, id: CallId) -> Result<()> {
let mut conn = self.conn.lock().unwrap(); let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?; let tx = conn.transaction()?;
@@ -413,15 +424,6 @@ impl Store {
Ok(()) Ok(())
} }
pub fn set_account(&self, id: CallId, account_id: Option<&str>) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"UPDATE calls SET account_id = ?1 WHERE id = ?2",
params![account_id, id],
)?;
Ok(())
}
pub fn record_remote_job(&self, id: CallId, track: &str, remote_id: &str) -> Result<()> { pub fn record_remote_job(&self, id: CallId, track: &str, remote_id: &str) -> Result<()> {
let conn = self.conn.lock().unwrap(); let conn = self.conn.lock().unwrap();
conn.execute( conn.execute(
@@ -470,7 +472,7 @@ impl Store {
/// `AwaitingDecision`, with `interrupted` set and `ended_at` set to now /// `AwaitingDecision`, with `interrupted` set and `ended_at` set to now
/// if it was not already set (a later pass corrects it from the WAV /// if it was not already set (a later pass corrects it from the WAV
/// length). /// length).
/// - `Processing` calls were mid-transcription/summarization: they move /// - `Processing` calls were mid-transcription: they move
/// to `Failed` with a fixed error message. /// to `Failed` with a fixed error message.
/// ///
/// Both updates run in a single transaction. /// Both updates run in a single transaction.
@@ -547,9 +549,9 @@ fn ids_with_status(conn: &rusqlite::Connection, status: CallStatus) -> Result<Ve
Ok(ids) Ok(ids)
} }
const SELECT_ALL_CALLS_SQL: &str = "SELECT id, app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, account_id, title FROM calls"; const SELECT_ALL_CALLS_SQL: &str = "SELECT id, app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, title, crm_transcript_id, uploaded_at, crm_base_url FROM calls";
const SELECT_CALL_COLUMNS_SQL: &str = "SELECT id, app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, account_id, title FROM calls WHERE id = ?1"; const SELECT_CALL_COLUMNS_SQL: &str = "SELECT id, app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, title, crm_transcript_id, uploaded_at, crm_base_url FROM calls WHERE id = ?1";
fn row_to_call(row: &Row) -> Result<Call> { fn row_to_call(row: &Row) -> Result<Call> {
let id: CallId = row.get(0)?; let id: CallId = row.get(0)?;
@@ -563,8 +565,10 @@ fn row_to_call(row: &Row) -> Result<Call> {
let out_path: String = row.get(8)?; let out_path: String = row.get(8)?;
let transcribed_at: Option<String> = row.get(9)?; let transcribed_at: Option<String> = row.get(9)?;
let audio_deleted: bool = row.get(10)?; let audio_deleted: bool = row.get(10)?;
let account_id: Option<String> = row.get(11)?; let title: Option<String> = row.get(11)?;
let title: Option<String> = row.get(12)?; let crm_transcript_id: Option<String> = row.get(12)?;
let uploaded_at: Option<String> = row.get(13)?;
let crm_base_url: Option<String> = row.get(14)?;
Ok(Call { Ok(Call {
id, id,
@@ -578,8 +582,10 @@ fn row_to_call(row: &Row) -> Result<Call> {
out_path: PathBuf::from(out_path), out_path: PathBuf::from(out_path),
transcribed_at: opt_dt_from_str(transcribed_at)?, transcribed_at: opt_dt_from_str(transcribed_at)?,
audio_deleted, audio_deleted,
account_id,
title, title,
crm_transcript_id,
crm_base_url,
uploaded_at: opt_dt_from_str(uploaded_at)?,
}) })
} }
@@ -637,9 +643,7 @@ mod tests {
use chrono::Local; use chrono::Local;
use crate::model::{ use crate::model::{CallId, CallStatus, Segment, Speaker};
CallId, CallStatus, NaechsterKontakt, Owner, Segment, Speaker, Summary, Todo,
};
use crate::store::Store; use crate::store::Store;
/// The schema of user_version 1, exactly as the first release created /// The schema of user_version 1, exactly as the first release created
@@ -690,6 +694,27 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
remote_id TEXT NOT NULL, remote_id TEXT NOT NULL,
PRIMARY KEY (call_id, track, remote_id) PRIMARY KEY (call_id, track, remote_id)
); );
";
/// The schema of user_version 2, exactly as release 0.1.1 created it:
/// version 1 plus these statements.
const RELEASED_V2_STEP_SQL: &str = "
ALTER TABLE calls ADD COLUMN title TEXT;
CREATE TABLE speaker_merges (
call_id INTEGER NOT NULL REFERENCES calls(id) ON DELETE CASCADE,
from_key TEXT NOT NULL,
into_key TEXT NOT NULL,
PRIMARY KEY (call_id, from_key)
);
";
/// The schema of user_version 3, exactly as release 0.2.0 created it
/// (copied from `SCHEMA_V3_SQL` at `HEAD`): version 2 plus these
/// statements.
const RELEASED_V3_STEP_SQL: &str = "
ALTER TABLE calls ADD COLUMN crm_transcript_id TEXT;
ALTER TABLE calls ADD COLUMN uploaded_at TEXT;
"; ";
fn user_version(path: &Path) -> i64 { fn user_version(path: &Path) -> i64 {
@@ -713,16 +738,19 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
} }
#[test] #[test]
fn a_new_database_starts_at_version_2() { fn a_new_database_starts_at_version_4() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("calls.sqlite"); let path = dir.path().join("calls.sqlite");
let store = Store::open(&path).unwrap(); let store = Store::open(&path).unwrap();
let id = new_call(&store); let id = new_call(&store);
store.set_title(id, Some("Angebot")).unwrap(); store.set_title(id, Some("Angebot")).unwrap();
store.set_speaker_merge(id, "remote:2", "remote:1").unwrap(); store.set_speaker_merge(id, "remote:2", "remote:1").unwrap();
store
.set_uploaded(id, "4711", "https://backend.example", Local::now())
.unwrap();
drop(store); drop(store);
assert_eq!(user_version(&path), 2); assert_eq!(user_version(&path), 4);
} }
#[test] #[test]
@@ -754,7 +782,6 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
let call = store.get_call(1).unwrap().expect("call kept"); let call = store.get_call(1).unwrap().expect("call kept");
assert_eq!(call.app, "Microsoft Teams"); assert_eq!(call.app, "Microsoft Teams");
assert_eq!(call.status, CallStatus::Done); assert_eq!(call.status, CallStatus::Done);
assert_eq!(call.account_id.as_deref(), Some("mock-2"));
assert_eq!(call.mic_path, PathBuf::from("/rec/1-mic.wav")); assert_eq!(call.mic_path, PathBuf::from("/rec/1-mic.wav"));
assert_eq!(call.title, None); assert_eq!(call.title, None);
let texts: Vec<_> = store let texts: Vec<_> = store
@@ -780,7 +807,7 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
store.set_title(1, Some("Lieferung März")).unwrap(); store.set_title(1, Some("Lieferung März")).unwrap();
store.set_speaker_merge(1, "remote:2", "remote:1").unwrap(); store.set_speaker_merge(1, "remote:2", "remote:1").unwrap();
drop(store); drop(store);
assert_eq!(user_version(&path), 2); assert_eq!(user_version(&path), 4);
let store = Store::open(&path).unwrap(); let store = Store::open(&path).unwrap();
let call = store.get_call(1).unwrap().unwrap(); let call = store.get_call(1).unwrap().unwrap();
assert_eq!(call.title.as_deref(), Some("Lieferung März")); assert_eq!(call.title.as_deref(), Some("Lieferung März"));
@@ -791,6 +818,157 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
assert_eq!(store.list_calls().unwrap().len(), 1); assert_eq!(store.list_calls().unwrap().len(), 1);
} }
#[test]
fn a_version_2_database_is_upgraded_keeping_its_data() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("calls.sqlite");
let started = "2026-11-05T10:14:00+01:00";
{
let conn = rusqlite::Connection::open(&path).unwrap();
conn.execute_batch(RELEASED_V1_SCHEMA_SQL).unwrap();
conn.execute_batch(RELEASED_V2_STEP_SQL).unwrap();
conn.execute_batch("PRAGMA user_version = 2;").unwrap();
conn.execute(
"INSERT INTO calls (app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, account_id, title) \
VALUES ('Microsoft Teams', ?1, ?1, 'done', 0, NULL, '/rec/1-mic.wav', '/rec/1-out.wav', ?1, 1, NULL, 'Angebot')",
rusqlite::params![started],
)
.unwrap();
conn.execute_batch(
"INSERT INTO segments (call_id, seq, speaker, start_ts, end_ts, text) VALUES \
(1, 0, 'remote:2', 0.0, 1.5, 'Hallo.'); \
INSERT INTO speaker_merges (call_id, from_key, into_key) VALUES (1, 'remote:2', 'remote:1');",
)
.unwrap();
}
let store = Store::open(&path).unwrap();
let call = store.get_call(1).unwrap().expect("call kept");
assert_eq!(call.title.as_deref(), Some("Angebot"));
assert!(call.audio_deleted);
assert_eq!(call.crm_transcript_id, None);
assert_eq!(call.uploaded_at, None);
assert_eq!(store.segments(1).unwrap().len(), 1);
assert_eq!(
store.speaker_merges(1).unwrap(),
merge_map(&[("remote:2", "remote:1")])
);
// The new columns work, and opening again changes nothing.
let uploaded = Local::now();
store
.set_uploaded(1, "crm-1", "https://backend.example", uploaded)
.unwrap();
drop(store);
assert_eq!(user_version(&path), 4);
let store = Store::open(&path).unwrap();
let call = store.get_call(1).unwrap().unwrap();
assert_eq!(call.crm_transcript_id.as_deref(), Some("crm-1"));
assert_eq!(
call.crm_base_url.as_deref(),
Some("https://backend.example")
);
assert_eq!(call.uploaded_at, Some(uploaded));
}
#[test]
fn a_version_3_database_is_upgraded_backfilling_the_test_backend_for_uploads() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("calls.sqlite");
let started = "2026-11-05T10:14:00+01:00";
{
let conn = rusqlite::Connection::open(&path).unwrap();
conn.execute_batch(RELEASED_V1_SCHEMA_SQL).unwrap();
conn.execute_batch(RELEASED_V2_STEP_SQL).unwrap();
conn.execute_batch(RELEASED_V3_STEP_SQL).unwrap();
conn.execute_batch("PRAGMA user_version = 3;").unwrap();
// An already-uploaded call (every pre-v4 upload went to the
// test backend; production never had the API).
conn.execute(
"INSERT INTO calls \
(app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, account_id, title, crm_transcript_id, uploaded_at) \
VALUES ('Microsoft Teams', ?1, ?1, 'done', 0, NULL, '/rec/1-mic.wav', '/rec/1-out.wav', ?1, 0, NULL, NULL, 'crm-1', ?1)",
rusqlite::params![started],
)
.unwrap();
// A call that was never uploaded.
conn.execute(
"INSERT INTO calls \
(app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, account_id, title, crm_transcript_id, uploaded_at) \
VALUES ('MicroSIP', ?1, NULL, 'awaiting_decision', 0, NULL, '/rec/2-mic.wav', '/rec/2-out.wav', NULL, 0, NULL, NULL, NULL, NULL)",
rusqlite::params![started],
)
.unwrap();
}
let store = Store::open(&path).unwrap();
let uploaded = store.get_call(1).unwrap().expect("call kept");
assert_eq!(uploaded.crm_transcript_id.as_deref(), Some("crm-1"));
assert_eq!(
uploaded.crm_base_url.as_deref(),
Some("https://test.euvinopro.eu")
);
let not_uploaded = store.get_call(2).unwrap().expect("call kept");
assert_eq!(not_uploaded.crm_transcript_id, None);
assert_eq!(not_uploaded.crm_base_url, None);
assert_eq!(user_version(&path), 4);
}
#[test]
fn an_upload_is_recorded_and_replaced_by_the_next_even_for_another_backend() {
let store = Store::open_in_memory().unwrap();
let id = new_call(&store);
let other = new_call(&store);
let first = Local::now();
let second = first + chrono::Duration::minutes(5);
store
.set_uploaded(id, "4711", "https://test.euvinopro.eu", first)
.unwrap();
let call = store.get_call(id).unwrap().unwrap();
assert_eq!(
(
call.crm_transcript_id.as_deref(),
call.crm_base_url.as_deref(),
call.uploaded_at
),
(Some("4711"), Some("https://test.euvinopro.eu"), Some(first))
);
// One upload slot per call: a later upload, even to a different
// backend, replaces it rather than keeping both.
store
.set_uploaded(id, "4712", "https://backend.euvinopro.eu", second)
.unwrap();
let listed = store.list_calls().unwrap();
let call = listed.iter().find(|c| c.id == id).unwrap();
assert_eq!(
(
call.crm_transcript_id.as_deref(),
call.crm_base_url.as_deref(),
call.uploaded_at
),
(
Some("4712"),
Some("https://backend.euvinopro.eu"),
Some(second)
)
);
let untouched = store.get_call(other).unwrap().unwrap();
assert_eq!(
(
untouched.crm_transcript_id,
untouched.crm_base_url,
untouched.uploaded_at
),
(None, None, None)
);
}
#[test] #[test]
fn speaker_merges_are_set_replaced_and_removed() { fn speaker_merges_are_set_replaced_and_removed() {
let store = Store::open_in_memory().unwrap(); let store = Store::open_in_memory().unwrap();
@@ -939,38 +1117,6 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
assert_eq!(store.segments(id).unwrap(), second); assert_eq!(store.segments(id).unwrap(), second);
} }
#[test]
fn summary_roundtrip_with_null_dates() {
let store = Store::open_in_memory().unwrap();
let id = store
.create_call(
"teams.exe",
Local::now(),
Path::new("/tmp/mic.wav"),
Path::new("/tmp/out.wav"),
)
.unwrap();
assert_eq!(store.summary(id).unwrap(), None);
let summary = Summary {
kernpunkte: vec!["Punkt 1".to_string()],
vereinbarungen: vec!["Angebot folgt".to_string()],
todos: vec![Todo {
text: "Angebot schicken".to_string(),
owner: Owner::Ich,
faellig: None,
erledigt: false,
}],
naechster_kontakt: NaechsterKontakt {
datum: None,
notiz: None,
},
};
store.save_summary(id, &summary, false).unwrap();
assert_eq!(store.summary(id).unwrap(), Some(summary));
}
#[test] #[test]
fn speaker_names_upsert() { fn speaker_names_upsert() {
let store = Store::open_in_memory().unwrap(); let store = Store::open_in_memory().unwrap();
@@ -1167,21 +1313,6 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
}], }],
) )
.unwrap(); .unwrap();
store
.save_summary(
id,
&Summary {
kernpunkte: vec![],
vereinbarungen: vec![],
todos: vec![],
naechster_kontakt: NaechsterKontakt {
datum: None,
notiz: None,
},
},
false,
)
.unwrap();
store.set_speaker_name(id, "me", "Ich").unwrap(); store.set_speaker_name(id, "me", "Ich").unwrap();
store.set_speaker_merge(id, "remote:2", "remote:1").unwrap(); store.set_speaker_merge(id, "remote:2", "remote:1").unwrap();
store store
@@ -1192,7 +1323,6 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
assert_eq!(store.get_call(id).unwrap(), None); assert_eq!(store.get_call(id).unwrap(), None);
assert_eq!(store.segments(id).unwrap(), Vec::new()); assert_eq!(store.segments(id).unwrap(), Vec::new());
assert_eq!(store.summary(id).unwrap(), None);
assert_eq!(store.speaker_names(id).unwrap(), BTreeMap::new()); assert_eq!(store.speaker_names(id).unwrap(), BTreeMap::new());
assert_eq!(store.remote_jobs(id).unwrap(), Vec::new()); assert_eq!(store.remote_jobs(id).unwrap(), Vec::new());
assert_eq!(store.speaker_merges(id).unwrap(), BTreeMap::new()); assert_eq!(store.speaker_merges(id).unwrap(), BTreeMap::new());
+17 -8
View File
@@ -10,8 +10,7 @@ use crate::http::{HttpRequest, HttpResponse, HttpTransport, Method, TransportErr
struct Expectation { struct Expectation {
method: Method, method: Method,
url: String, url: String,
status: u16, response: Result<HttpResponse, TransportError>,
body: Vec<u8>,
} }
/// Scripted [`HttpTransport`]: queue expected requests in order with /// Scripted [`HttpTransport`]: queue expected requests in order with
@@ -36,11 +35,24 @@ impl FakeTransport {
/// Queues the next expected request and the response to return for it. /// Queues the next expected request and the response to return for it.
pub fn expect(&self, method: Method, url: &str, status: u16, body: impl Into<Vec<u8>>) { pub fn expect(&self, method: Method, url: &str, status: u16, body: impl Into<Vec<u8>>) {
let response = HttpResponse {
status,
body: body.into(),
};
self.push(method, url, Ok(response));
}
/// Queues the next expected request and the transport error it fails
/// with (e.g. the server is unreachable).
pub fn fail(&self, method: Method, url: &str, error: TransportError) {
self.push(method, url, Err(error));
}
fn push(&self, method: Method, url: &str, response: Result<HttpResponse, TransportError>) {
self.expectations.lock().unwrap().push(Expectation { self.expectations.lock().unwrap().push(Expectation {
method, method,
url: url.to_string(), url: url.to_string(),
status, response,
body: body.into(),
}); });
} }
@@ -92,9 +104,6 @@ impl HttpTransport for FakeTransport {
); );
} }
self.requests.lock().unwrap().push(req); self.requests.lock().unwrap().push(req);
Ok(HttpResponse { expectation.response
status: expectation.status,
body: expectation.body,
})
} }
} }
+4
View File
@@ -86,6 +86,7 @@ impl DeepScript {
url: format!("{}/transcriptions/{remote_id}/status", self.base_url), url: format!("{}/transcriptions/{remote_id}/status", self.base_url),
headers: vec![self.auth_header()], headers: vec![self.auth_header()],
body: HttpBody::Empty, body: HttpBody::Empty,
follow_redirects: true,
}; };
let resp = match self.transport.send(req).await { let resp = match self.transport.send(req).await {
Ok(resp) => resp, Ok(resp) => resp,
@@ -115,6 +116,7 @@ impl DeepScript {
url: format!("{}/transcriptions/{remote_id}", self.base_url), url: format!("{}/transcriptions/{remote_id}", self.base_url),
headers: vec![self.auth_header()], headers: vec![self.auth_header()],
body: HttpBody::Empty, body: HttpBody::Empty,
follow_redirects: true,
}; };
let resp = self.send(req).await?; let resp = self.send(req).await?;
match resp.status { match resp.status {
@@ -205,6 +207,7 @@ impl Transcriber for DeepScript {
url: format!("{}/transcriptions", self.base_url), url: format!("{}/transcriptions", self.base_url),
headers: vec![self.auth_header()], headers: vec![self.auth_header()],
body: HttpBody::Multipart(parts), body: HttpBody::Multipart(parts),
follow_redirects: true,
}; };
let resp = self.send(req).await?; let resp = self.send(req).await?;
@@ -265,6 +268,7 @@ impl Transcriber for DeepScript {
url: format!("{}/transcriptions/{remote_id}", self.base_url), url: format!("{}/transcriptions/{remote_id}", self.base_url),
headers: vec![self.auth_header()], headers: vec![self.auth_header()],
body: HttpBody::Empty, body: HttpBody::Empty,
follow_redirects: true,
}; };
let resp = self.send(req).await?; let resp = self.send(req).await?;
match resp.status { match resp.status {
+10
View File
@@ -0,0 +1,10 @@
{
"version": "0.2.1",
"pub_date": "2026-11-06T14:48:27Z",
"platforms": {
"windows-x86_64": {
"signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVUdGpRa1ZvalU2SU9ZeUN6RUpYcjNFQ0VFTTZrZFpEa255SkRib0JtMVE4aEdVOG9ack5valRJdVAwZy9wcHZ2a1JFUHREZmJGT21Yd2hNOTh2TmMwSTVYRlRhQ1NqREFZPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzOTc2NDgwCWZpbGU6R2VzcHLDpGNoc3Jla29yZGVyXzAuMi4xX3g2NC1zZXR1cC5leGUJdmVyc2lvbjowLjIuMQplYUZLR25PZVk0dm4xZUczMElNYlpYeEZ5Um9VbTgwbEJKUmQwU2l1QkZPUE9Bdy9sd1FIUHAyb0MyeEZlemkxaktwM0VBd05PZDBRV3NYWTVOSmlBQT09Cg==",
"url": "https://gitea.euvino.eu/public/call-recorder/releases/download/v0.2.1/Gespraechsrekorder_0.2.1_x64-setup.exe"
}
}
}
+2 -3
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Builds a signed release of Gesprächsrekorder into dist-release/<version>/: # Builds a signed release of Gesprächsrekorder into dist-release/<version>/:
# the Windows NSIS installer (cross-built via build-windows.sh), the Linux # the Windows NSIS installer (cross-built via build-windows.sh), the Linux
# deb and AppImage, their updater signatures (.sig) and latest.json. # deb, their updater signatures (.sig) and latest.json.
# Sets <version> in tauri.conf.json, src-tauri/Cargo.toml and # Sets <version> in tauri.conf.json, src-tauri/Cargo.toml and
# ui/package.json and leaves those changes for you to commit. Never tags or # ui/package.json and leaves those changes for you to commit. Never tags or
# publishes anything; see RELEASING.md. # publishes anything; see RELEASING.md.
@@ -157,7 +157,7 @@ grep -qx "version = \"${VERSION}\"" "${CARGO_TOML}" || die "could not set the ve
# --- Build ------------------------------------------------------------------ # --- Build ------------------------------------------------------------------
"${SCRIPT_DIR}/build-windows.sh" "${SCRIPT_DIR}/build-windows.sh"
(cd "${REPO_ROOT}" && cargo tauri build --bundles deb appimage) (cd "${REPO_ROOT}" && cargo tauri build --bundles deb)
# --- Collect ---------------------------------------------------------------- # --- Collect ----------------------------------------------------------------
OUT="${REPO_ROOT}/dist-release/${VERSION}" OUT="${REPO_ROOT}/dist-release/${VERSION}"
@@ -183,7 +183,6 @@ collect() {
} }
collect "${WINDOWS_BUNDLE}" "*_${VERSION}_x64-setup.exe" collect "${WINDOWS_BUNDLE}" "*_${VERSION}_x64-setup.exe"
collect "${LINUX_BUNDLE}/deb" "*_${VERSION}_amd64.deb" collect "${LINUX_BUNDLE}/deb" "*_${VERSION}_amd64.deb"
collect "${LINUX_BUNDLE}/appimage" "*_${VERSION}_amd64.AppImage"
"${SCRIPT_DIR}/make-latest-json.sh" "${VERSION}" "${OUT}" "${SCRIPT_DIR}/make-latest-json.sh" "${VERSION}" "${OUT}"
jq -e . "${OUT}/latest.json" >/dev/null || die "latest.json is not valid JSON" jq -e . "${OUT}/latest.json" >/dev/null || die "latest.json is not valid JSON"
+2 -8
View File
@@ -2,7 +2,8 @@
# Writes <dir>/latest.json, the update feed the app reads, from the signed # Writes <dir>/latest.json, the update feed the app reads, from the signed
# release artifacts in <dir>: # release artifacts in <dir>:
# windows-x86_64 -> *_<version>_x64-setup.exe (+ .sig) # windows-x86_64 -> *_<version>_x64-setup.exe (+ .sig)
# linux-x86_64 -> *_<version>_amd64.AppImage (+ .sig) # Debian builds do not self-update, so the .deb is not listed here (it is
# still a release asset, just not part of the feed).
# The download URLs point at ${RELEASE_BASE_URL}/releases/download/v<version>/ # The download URLs point at ${RELEASE_BASE_URL}/releases/download/v<version>/
# (scripts/release.env). # (scripts/release.env).
# #
@@ -38,7 +39,6 @@ signed_file() {
} }
WINDOWS="$(signed_file "*_${VERSION}_x64-setup.exe")" WINDOWS="$(signed_file "*_${VERSION}_x64-setup.exe")"
LINUX="$(signed_file "*_${VERSION}_amd64.AppImage")"
jq -n \ jq -n \
--arg version "${VERSION}" \ --arg version "${VERSION}" \
@@ -46,8 +46,6 @@ jq -n \
--arg base "${RELEASE_BASE_URL}/releases/download/v${VERSION}" \ --arg base "${RELEASE_BASE_URL}/releases/download/v${VERSION}" \
--arg windows_file "$(basename "${WINDOWS}")" \ --arg windows_file "$(basename "${WINDOWS}")" \
--rawfile windows_sig "${WINDOWS}.sig" \ --rawfile windows_sig "${WINDOWS}.sig" \
--arg linux_file "$(basename "${LINUX}")" \
--rawfile linux_sig "${LINUX}.sig" \
'{ '{
version: $version, version: $version,
pub_date: $pub_date, pub_date: $pub_date,
@@ -55,10 +53,6 @@ jq -n \
"windows-x86_64": { "windows-x86_64": {
signature: ($windows_sig | gsub("\\s"; "")), signature: ($windows_sig | gsub("\\s"; "")),
url: "\($base)/\($windows_file | @uri)" url: "\($base)/\($windows_file | @uri)"
},
"linux-x86_64": {
signature: ($linux_sig | gsub("\\s"; "")),
url: "\($base)/\($linux_file | @uri)"
} }
} }
}' >"${DIR}/latest.json" }' >"${DIR}/latest.json"
+3 -7
View File
@@ -6,13 +6,9 @@
RELEASE_BASE_URL="https://gitea.euvino.eu/public/call-recorder" RELEASE_BASE_URL="https://gitea.euvino.eu/public/call-recorder"
# Where the app looks for latest.json, tried in this order until one answers # Where the app looks for latest.json: committed to the root of master.
# with a release: # Gitea 1.27.3 does not redirect releases/latest/download/<file> to a
# 1. latest.json as an asset of the newest release, # release's assets, so that URL is not offered here. See RELEASING.md.
# 2. latest.json committed to the root of master.
# Once it is clear which one Gitea serves, the other can be dropped here (it
# then disappears from the next version built).
UPDATE_JSON_URLS=( UPDATE_JSON_URLS=(
"${RELEASE_BASE_URL}/releases/latest/download/latest.json"
"${RELEASE_BASE_URL}/raw/branch/master/latest.json" "${RELEASE_BASE_URL}/raw/branch/master/latest.json"
) )
+4 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "call-recorder" name = "call-recorder"
version = "0.1.1" version = "0.2.2"
description = "Gesprächsrekorder desktop app" description = "Gesprächsrekorder desktop app"
edition = "2021" edition = "2021"
@@ -27,3 +27,6 @@ tempfile = "3"
recorder-core = { path = "../crates/core" } recorder-core = { path = "../crates/core" }
recorder-audio = { path = "../crates/audio" } recorder-audio = { path = "../crates/audio" }
tauri-plugin-updater = "2" tauri-plugin-updater = "2"
tauri-plugin-opener = "2"
tokio = { version = "1", features = ["sync"] }
async-trait = "0.1"
+521
View File
@@ -0,0 +1,521 @@
//! Link to the euvino admin backend: the login window that turns the
//! admin's browser session into an API key, the login status for the
//! settings, and the upload of a call's transcript.
//!
//! The login window shows the backend's own login page, a remote origin: it
//! has no Tauri capability (see `capabilities/default.json`), so the page
//! cannot invoke any command. It runs in incognito mode, so the session
//! never outlives the window. After each page load on the backend the app
//! reads the window's cookies for the backend and uses them for the one
//! request that creates a key. Neither the cookies nor the key are ever
//! logged; the key is stored only in the keyring.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
use async_trait::async_trait;
use chrono::{DateTime, Local};
use recorder_core::backend::{self, BackendClient, KeyCheck, Login, LoginStep, NewKey};
use recorder_core::model::CallId;
use serde::Serialize;
use tauri::webview::PageLoadEvent;
use tauri::{
AppHandle, Emitter, Manager, State, Url, WebviewUrl, WebviewWindow, WebviewWindowBuilder,
WindowEvent,
};
use tauri_plugin_opener::OpenerExt;
use tokio::sync::oneshot;
use crate::processing;
use crate::state::AppState;
// The backend this build talks to: the one place to change it. It is not a
// setting; a key created on one backend is never sent to another.
/// Release builds: the production euvino admin backend.
pub(crate) const RELEASE_BACKEND_URL: &str = "https://backend.euvinopro.eu";
/// Debug builds (`cargo tauri dev`) always use the test backend, never the
/// production one. `pub(crate)`: `state.rs` tests the exact test-backend →
/// release-backend transition against this value (a key bound to one must
/// never work for the other).
pub(crate) const DEV_BACKEND_URL: &str = "https://test.euvinopro.eu";
/// The backend of this build (no trailing slash).
pub const BACKEND_URL: &str = if cfg!(debug_assertions) {
DEV_BACKEND_URL
} else {
RELEASE_BACKEND_URL
};
/// Label of the login window.
pub const LOGIN_WINDOW: &str = "backend-login";
const CANCELLED: &str = "Anmeldung abgebrochen";
type CmdResult<T> = Result<T, String>;
/// A login's outcome: the new key, or the message why there is none.
type LoginResult = Result<String, String>;
/// Everyone waiting for the login that runs in the login window. Only one
/// login runs at a time; later requests wait for the same result.
#[derive(Default)]
pub struct LoginWaiters {
waiters: Mutex<Vec<oneshot::Sender<LoginResult>>>,
/// Set while a key is being created, so page loads in quick succession
/// do not create several.
creating: AtomicBool,
}
impl LoginWaiters {
/// Waits for the login. `true` if no login was running yet, so the
/// caller has to start one.
fn join(&self) -> (oneshot::Receiver<LoginResult>, bool) {
let (tx, rx) = oneshot::channel();
let mut waiters = lock(&self.waiters);
let first = waiters.is_empty();
waiters.push(tx);
(rx, first)
}
/// Whether anyone waits for a login.
fn waiting(&self) -> bool {
!lock(&self.waiters).is_empty()
}
/// Ends the login with `result` for everyone waiting.
fn finish(&self, result: LoginResult) {
for waiter in lock(&self.waiters).drain(..) {
let _ = waiter.send(result.clone());
}
}
/// Claims the right to create a key; `None` while another page load
/// is already creating one.
fn claim_creating(&self) -> Option<CreatingClaim<'_>> {
(!self.creating.swap(true, Ordering::SeqCst)).then_some(CreatingClaim(&self.creating))
}
}
/// Releases [`LoginWaiters::creating`] when dropped.
struct CreatingClaim<'a>(&'a AtomicBool);
impl Drop for CreatingClaim<'_> {
fn drop(&mut self) {
self.0.store(false, Ordering::SeqCst);
}
}
/// Answer of `backend_server`: the backend of this build.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct BackendServer {
pub base_url: String,
/// Where the admin manages their keys.
pub keys_url: String,
}
/// Answer of `backend_status`.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct BackendStatus {
pub logged_in: bool,
pub username: Option<String>,
pub expires_at: Option<DateTime<Local>>,
/// `false` if the stored key could not be checked; username and expiry
/// are then the stored ones.
pub reachable: bool,
}
/// Payload of `backend-login-error`: creating the key failed, the login
/// window stays open for another try.
#[derive(Serialize, Clone)]
struct LoginError {
message: String,
}
/// The backend this build talks to, for the settings (no network).
#[tauri::command]
pub fn backend_server(state: State<'_, AppState>) -> BackendServer {
BackendServer {
base_url: state.backend_url().to_string(),
keys_url: state.backend_client().keys_page_url(),
}
}
/// Whether a backend key is stored, and whose it is: checked with the
/// backend. A key the backend refuses, or one of another backend, is
/// discarded.
#[tauri::command]
pub async fn backend_status(app: AppHandle) -> CmdResult<BackendStatus> {
let state = app.state::<AppState>();
let client = state.backend_client();
let stored = blocking(&app, |state| Ok(state.backend_key())).await?;
let mut status = BackendStatus {
logged_in: false,
username: None,
expires_at: None,
reachable: true,
};
let Some(stored) = stored else {
return Ok(status);
};
match client.check_key(&stored.key).await {
KeyCheck::Valid(info) => {
state.refresh_backend_login(&info)?;
status.logged_in = true;
status.username = Some(info.username);
status.expires_at = Some(info.expires_at);
}
KeyCheck::Invalid => {
log::info!("backend: the stored key was refused, discarding it");
let refused = stored.key;
blocking(&app, move |state| {
state.discard_refused_backend_key(&refused)
})
.await?;
}
KeyCheck::Unknown(e) => {
log::info!(
"backend: could not check the stored key: {}",
e.user_message()
);
let settings = state.settings();
status.logged_in = true;
status.username = settings.backend_username;
status.expires_at = settings.backend_key_expires_at;
status.reachable = false;
}
}
Ok(status)
}
/// "Anmelden": runs the login in the login window (a new key replaces the
/// stored one).
#[tauri::command]
pub async fn backend_login(app: AppHandle) -> CmdResult<()> {
login(&app).await.map(|_key| ())
}
/// "Abmelden": forgets the key locally (it stays valid on the server until
/// the admin deletes it there or it expires).
#[tauri::command]
pub async fn backend_logout(app: AppHandle) -> CmdResult<()> {
blocking(&app, |state| state.discard_backend_key()).await?;
emit_changed(&app);
Ok(())
}
/// Opens the backend's key management page in the system browser.
#[tauri::command]
pub fn open_backend_keys_page(app: AppHandle) -> CmdResult<()> {
let url = app.state::<AppState>().backend_client().keys_page_url();
app.opener()
.open_url(url, None::<&str>)
.map_err(|e| format!("Browser konnte nicht geöffnet werden: {e}"))
}
/// "Transkript hochladen": uploads the call's transcript as the user sees
/// it, logging in first if needed, and records the CRM's id on the call.
/// One upload per call at a time; `call-updated` tells the views when it
/// starts and ends.
#[tauri::command]
pub async fn upload_transcript(app: AppHandle, id: CallId) -> CmdResult<()> {
let state = app.state::<AppState>();
let claim = state.claim_upload(id)?;
processing::emit_updated(&app, id);
let result = upload(&app, &state, id).await;
drop(claim);
processing::emit_updated(&app, id);
result
}
async fn upload(app: &AppHandle, state: &AppState, id: CallId) -> CmdResult<()> {
let detail = state.call_detail(id)?;
if detail.call.transcribed_at.is_none() {
return Err("Das Gespräch ist noch nicht transkribiert".to_string());
}
let text = detail.upload_text()?;
let client = state.backend_client();
let stored = blocking(app, |state| Ok(state.backend_key())).await?;
let login = AppLogin { app: app.clone() };
let crm_id = backend::upload_with_login(&client, &login, stored, Local::now(), &text)
.await
.inspect_err(|e| log::warn!("call {id}: upload failed: {e}"))?;
log::info!("call {id}: transcript uploaded (CRM id {crm_id})");
if let Err(e) = state.mark_uploaded(id, &crm_id) {
// The CRM already has it: a retry must never send it again, even
// though the row itself still shows no crm_transcript_id.
state.note_upload_confirmed_but_unsaved(id);
log::error!("call {id}: uploaded (CRM id {crm_id}) but could not save locally: {e}");
return Err(unsaved_upload_message(&crm_id, &e));
}
Ok(())
}
/// Message for an upload that reached the CRM (`crm_id`) but whose local
/// record (`mark_uploaded`) failed with `e`: names the CRM id so the user
/// can find it there, and says plainly not to upload the call again (the
/// app also refuses on its own, see `AppState::note_upload_confirmed_but_unsaved`).
fn unsaved_upload_message(crm_id: &str, e: &str) -> String {
format!("Hochgeladen (ID {crm_id}), aber lokal nicht gespeichert: {e} – nicht erneut hochladen")
}
/// [`Login`] through the login window, for the upload.
struct AppLogin {
app: AppHandle,
}
#[async_trait]
impl Login for AppLogin {
async fn login(&self) -> Result<String, String> {
login(&self.app).await
}
async fn discard_key(&self, refused: &str) {
let refused = refused.to_string();
match blocking(&self.app, move |state| {
state.discard_refused_backend_key(&refused)
})
.await
{
Ok(true) => {
log::info!("backend: the key was refused, discarded it");
emit_changed(&self.app);
}
Ok(false) => log::info!("backend: the refused key was already replaced"),
Err(e) => log::error!("backend: {e}"),
}
}
}
/// Runs the login in the login window, or waits for the one already
/// running (and brings its window to the front). Returns the new key,
/// already stored.
pub async fn login(app: &AppHandle) -> LoginResult {
let waiters = app.state::<LoginWaiters>();
let (result, first) = waiters.join();
match app.get_webview_window(LOGIN_WINDOW) {
Some(window) => {
let _ = window.unminimize();
let _ = window.set_focus();
}
None if first => {
if let Err(e) = open_login_window(app) {
log::error!("backend: could not open the login window: {e}");
waiters.finish(Err(format!(
"Anmeldefenster konnte nicht geöffnet werden: {e}"
)));
}
}
None => {}
}
result.await.unwrap_or_else(|_| Err(CANCELLED.to_string()))
}
fn open_login_window(app: &AppHandle) -> tauri::Result<()> {
let client = app.state::<AppState>().backend_client();
let url = Url::parse(&client.login_url()).map_err(tauri::Error::InvalidUrl)?;
let window = WebviewWindowBuilder::new(app, LOGIN_WINDOW, WebviewUrl::External(url))
.title("Anmeldung euvino Admin")
.inner_size(1000.0, 760.0)
.incognito(true)
.on_page_load(move |window, payload| {
if payload.event() == PageLoadEvent::Finished
&& client.is_logged_in_page(payload.url().as_str())
{
create_key(window, client.clone());
}
})
.build()?;
let app = app.clone();
window.on_window_event(move |event| {
if let WindowEvent::Destroyed = event {
// Closed by the user: the login is cancelled. After a
// finished login nobody waits any more.
app.state::<LoginWaiters>()
.finish(Err(CANCELLED.to_string()));
}
});
Ok(())
}
/// The login window shows a backend page behind the login: creates a key
/// with the window's session, in the background. `client` is the backend
/// the window was opened for.
fn create_key(window: WebviewWindow, client: BackendClient) {
tauri::async_runtime::spawn(async move {
let app = window.app_handle().clone();
let waiters = app.state::<LoginWaiters>();
if !waiters.waiting() {
return;
}
let Some(_claim) = waiters.claim_creating() else {
return;
};
match try_create_key(&client, &window).await {
LoginStep::Done(key) => {
let result = store_key(&app, &client, &key).await.map(|()| key.key);
waiters.finish(result);
emit_changed(&app);
let _ = window.destroy();
}
LoginStep::Wait => {}
LoginStep::Fail(message) => {
log::warn!("backend: the login cannot create a key: {message}");
waiters.finish(Err(message));
let _ = window.destroy();
}
LoginStep::Retry(message) => {
log::warn!("backend: creating the key failed: {message}");
let message = format!("{message} – bitte die Seite im Anmeldefenster neu laden");
let _ = app.emit_to("main", "backend-login-error", LoginError { message });
}
}
});
}
/// Creates a key with the cookies the login window holds for the backend.
/// The cookies are used for this one request and dropped.
async fn try_create_key(client: &BackendClient, window: &WebviewWindow) -> LoginStep {
let Ok(url) = Url::parse(&client.keys_page_url()) else {
return LoginStep::Wait;
};
// Off the async runtime: on Windows reading cookies blocks until the
// main thread answers.
let reader = window.clone();
let cookies = tauri::async_runtime::spawn_blocking(move || reader.cookies_for_url(url)).await;
let cookies = match cookies {
Ok(Ok(cookies)) => cookies,
Ok(Err(e)) => return LoginStep::Retry(format!("Anmeldedaten nicht lesbar: {e}")),
Err(e) => return LoginStep::Retry(format!("Anmeldedaten nicht lesbar: {e}")),
};
if cookies.is_empty() {
return LoginStep::Wait;
}
let cookie_header = cookies
.iter()
.map(|cookie| format!("{}={}", cookie.name(), cookie.value()))
.collect::<Vec<_>>()
.join("; ");
let label = backend::key_label(hostname().as_deref());
LoginStep::of(client.create_key(&cookie_header, &label).await)
}
/// Stores a new key with whose it is (asked from the backend; left empty if
/// that fails) and its expiry.
async fn store_key(app: &AppHandle, client: &BackendClient, key: &NewKey) -> Result<(), String> {
let username = match client.key_info(&key.key).await {
Ok(info) => Some(info.username),
Err(e) => {
log::warn!(
"backend: could not ask whose the new key is: {}",
e.user_message()
);
None
}
};
let (key, base_url) = (key.clone(), client.base_url().to_string());
blocking(app, move |state| {
state.store_backend_key(&key, &base_url, username)
})
.await?;
log::info!("backend: logged in, key stored");
Ok(())
}
/// The computer's name, for the key's label.
fn hostname() -> Option<String> {
std::env::var("COMPUTERNAME")
.ok()
.or_else(|| std::fs::read_to_string("/etc/hostname").ok())
.or_else(|| std::env::var("HOSTNAME").ok())
.map(|name| name.trim().to_string())
.filter(|name| !name.is_empty())
}
/// Tells the settings that the login changed (`backend-changed`).
fn emit_changed(app: &AppHandle) {
if let Err(e) = app.emit_to("main", "backend-changed", ()) {
log::error!("could not emit backend-changed: {e}");
}
}
/// Runs `f` with the app state on the blocking pool (keyring access).
async fn blocking<T, F>(app: &AppHandle, f: F) -> CmdResult<T>
where
T: Send + 'static,
F: FnOnce(&AppState) -> CmdResult<T> + Send + 'static,
{
let app = app.clone();
tauri::async_runtime::spawn_blocking(move || f(&app.state::<AppState>()))
.await
.map_err(|e| e.to_string())?
}
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
mutex
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn backend_urls_have_no_trailing_slash_and_use_https() {
for url in [RELEASE_BACKEND_URL, DEV_BACKEND_URL] {
assert!(!url.ends_with('/'), "{url}");
assert!(url.starts_with("https://"), "{url}");
}
// Release and dev talk to different backends: a key from one must
// never be usable on the other (see AppState::backend_key).
assert_ne!(RELEASE_BACKEND_URL, DEV_BACKEND_URL);
}
#[test]
fn the_unsaved_upload_message_names_the_crm_id_and_warns_against_retrying() {
assert_eq!(
unsaved_upload_message("4711", "disk full"),
"Hochgeladen (ID 4711), aber lokal nicht gespeichert: disk full – nicht erneut hochladen"
);
}
#[test]
fn everyone_waiting_gets_the_one_login_result() {
let waiters = LoginWaiters::default();
assert!(!waiters.waiting());
let (first, starts) = waiters.join();
let (second, starts_again) = waiters.join();
assert!(starts);
assert!(!starts_again);
assert!(waiters.waiting());
waiters.finish(Ok("euv_k".into()));
assert_eq!(first.blocking_recv().unwrap(), Ok("euv_k".to_string()));
assert_eq!(second.blocking_recv().unwrap(), Ok("euv_k".to_string()));
assert!(!waiters.waiting());
}
#[test]
fn a_finished_login_leaves_the_next_one_to_start_anew() {
let waiters = LoginWaiters::default();
let (first, _) = waiters.join();
waiters.finish(Err(CANCELLED.into()));
// A late "window destroyed" reaches nobody.
waiters.finish(Err("ignored".into()));
assert_eq!(first.blocking_recv().unwrap(), Err(CANCELLED.to_string()));
let (next, starts) = waiters.join();
assert!(starts);
waiters.finish(Ok("euv_new".into()));
assert_eq!(next.blocking_recv().unwrap(), Ok("euv_new".to_string()));
}
#[test]
fn only_one_key_is_created_at_a_time() {
let waiters = LoginWaiters::default();
let claim = waiters.claim_creating();
assert!(claim.is_some());
assert!(waiters.claim_creating().is_none());
drop(claim);
assert!(waiters.claim_creating().is_some());
}
}
+39 -18
View File
@@ -8,7 +8,6 @@
use std::thread; use std::thread;
use std::time::Duration; use std::time::Duration;
use recorder_core::accounts::{self, Account};
use recorder_core::call_view::{CallDetail, CallListItem}; use recorder_core::call_view::{CallDetail, CallListItem};
use recorder_core::capture::Devices; use recorder_core::capture::Devices;
use recorder_core::model::CallId; use recorder_core::model::CallId;
@@ -24,6 +23,10 @@ use crate::state::{
}; };
const LEVELS_INTERVAL: Duration = Duration::from_millis(100); const LEVELS_INTERVAL: Duration = Duration::from_millis(100);
/// `set_api_key`/`has_api_key` refuse this service: its key is managed only
/// by the backend login (`backend::login`), which holds `backend_key_lock`
/// and binds the key to this build's backend.
const BACKEND_KEY_MANAGED: &str = "Dieser Schlüssel wird über die Backend-Anmeldung verwaltet";
type CmdResult<T> = Result<T, String>; type CmdResult<T> = Result<T, String>;
@@ -33,6 +36,12 @@ struct CallEnded {
id: CallId, id: CallId,
} }
/// This build's own version, for the settings' "Updates" section.
#[tauri::command]
pub fn get_app_version(app: AppHandle) -> String {
app.package_info().version.to_string()
}
#[tauri::command] #[tauri::command]
pub fn get_settings(state: State<'_, AppState>) -> Settings { pub fn get_settings(state: State<'_, AppState>) -> Settings {
state.settings() state.settings()
@@ -50,9 +59,11 @@ pub fn save_settings(
Ok(()) Ok(())
} }
/// Stores `key` in the keyring; an empty key deletes the entry. /// Stores `key` in the keyring; an empty key deletes the entry. Refuses
/// `Service::Backend` (see [`BACKEND_KEY_MANAGED`]).
#[tauri::command] #[tauri::command]
pub async fn set_api_key(app: AppHandle, service: Service, key: String) -> CmdResult<()> { pub async fn set_api_key(app: AppHandle, service: Service, key: String) -> CmdResult<()> {
reject_backend_service(service)?;
blocking(app, move |app| { blocking(app, move |app| {
let secrets = &app.state::<AppState>().secrets; let secrets = &app.state::<AppState>().secrets;
let key = key.trim(); let key = key.trim();
@@ -66,9 +77,11 @@ pub async fn set_api_key(app: AppHandle, service: Service, key: String) -> CmdRe
.await .await
} }
/// Whether a key is stored. Never returns the key itself. /// Whether a key is stored. Never returns the key itself. Refuses
/// `Service::Backend` (see [`BACKEND_KEY_MANAGED`]).
#[tauri::command] #[tauri::command]
pub async fn has_api_key(app: AppHandle, service: Service) -> CmdResult<bool> { pub async fn has_api_key(app: AppHandle, service: Service) -> CmdResult<bool> {
reject_backend_service(service)?;
blocking(app, move |app| { blocking(app, move |app| {
let key = app.state::<AppState>().secrets.get(service); let key = app.state::<AppState>().secrets.get(service);
Ok(key.is_some_and(|key| !key.is_empty())) Ok(key.is_some_and(|key| !key.is_empty()))
@@ -76,6 +89,15 @@ pub async fn has_api_key(app: AppHandle, service: Service) -> CmdResult<bool> {
.await .await
} }
/// Refuses direct keyring access to `Service::Backend`: its key is only
/// ever set by the backend login flow.
fn reject_backend_service(service: Service) -> CmdResult<()> {
if service == Service::Backend {
return Err(BACKEND_KEY_MANAGED.to_string());
}
Ok(())
}
#[tauri::command] #[tauri::command]
pub async fn list_devices() -> CmdResult<Devices> { pub async fn list_devices() -> CmdResult<Devices> {
tauri::async_runtime::spawn_blocking(recorder_audio::list_devices) tauri::async_runtime::spawn_blocking(recorder_audio::list_devices)
@@ -186,21 +208,6 @@ pub fn rename_call(
Ok(()) Ok(())
} }
#[tauri::command]
pub fn list_accounts() -> Vec<Account> {
accounts::list()
}
/// Assigns a call to a customer account, or to none.
#[tauri::command]
pub fn set_account(
state: State<'_, AppState>,
id: CallId,
account_id: Option<String>,
) -> CmdResult<()> {
state.set_account(id, account_id.as_deref())
}
/// Deletes a finished call's audio and row. Closes the prompt if no call /// Deletes a finished call's audio and row. Closes the prompt if no call
/// waits for it any more; otherwise the prompt reloads and shows the next. /// waits for it any more; otherwise the prompt reloads and shows the next.
/// While its DeepScript jobs are still on record, nothing is deleted and a /// While its DeepScript jobs are still on record, nothing is deleted and a
@@ -428,3 +435,17 @@ where
.await .await
.map_err(|e| e.to_string())? .map_err(|e| e.to_string())?
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_backend_key_is_managed_only_by_the_login() {
assert_eq!(
reject_backend_service(Service::Backend),
Err(BACKEND_KEY_MANAGED.to_string())
);
assert_eq!(reject_backend_service(Service::DeepScript), Ok(()));
}
}
+29 -6
View File
@@ -1,3 +1,4 @@
mod backend;
mod commands; mod commands;
mod detection; mod detection;
mod processing; mod processing;
@@ -13,7 +14,7 @@ use tauri_plugin_autostart::MacosLauncher;
use tauri_plugin_log::{RotationStrategy, Target, TargetKind, TimezoneStrategy}; use tauri_plugin_log::{RotationStrategy, Target, TargetKind, TimezoneStrategy};
use crate::state::AppState; use crate::state::AppState;
use crate::updater::PendingUpdate; use crate::updater::{PendingUpdate, UpdateSchedule};
/// Command-line flag the login item starts the app with; the main window /// Command-line flag the login item starts the app with; the main window
/// then stays hidden in the tray. /// then stays hidden in the tray.
@@ -34,6 +35,14 @@ pub fn run() {
)) ))
.plugin(tauri_plugin_notification::init()) .plugin(tauri_plugin_notification::init())
.plugin(tauri_plugin_updater::Builder::new().build()) .plugin(tauri_plugin_updater::Builder::new().build())
// Only for `open_backend_keys_page`: no capability grants the UI
// the plugin's commands, and no link-click script is injected (it
// would also run in the remote login page).
.plugin(
tauri_plugin_opener::Builder::new()
.open_js_links_on_click(false)
.build(),
)
.setup(|app| { .setup(|app| {
// Release builds log to a file in the app log directory (on // Release builds log to a file in the app log directory (on
// Windows %LOCALAPPDATA%\eu.euvino.callrecorder\logs), debug // Windows %LOCALAPPDATA%\eu.euvino.callrecorder\logs), debug
@@ -83,10 +92,14 @@ pub fn run() {
&config_dir.join("last-version"), &config_dir.join("last-version"),
&app.package_info().version.to_string(), &app.package_info().version.to_string(),
); );
// Off the main thread: the keyring can be slow to answer.
std::thread::spawn(KeyringSecrets::remove_unused_keys);
// Before anything can start a run. // Before anything can start a run.
processing::clear_upload_dir(app.handle()); processing::clear_upload_dir(app.handle());
app.manage(state); app.manage(state);
app.manage(PendingUpdate::default()); app.manage(PendingUpdate::default());
app.manage(UpdateSchedule::default());
app.manage(backend::LoginWaiters::default());
// Windows are created here (`create: false` in tauri.conf.json) // Windows are created here (`create: false` in tauri.conf.json)
// instead of by Tauri before `setup` runs: their webviews load // instead of by Tauri before `setup` runs: their webviews load
// immediately and invoke commands (list_calls, get_recording_state, // immediately and invoke commands (list_calls, get_recording_state,
@@ -108,13 +121,17 @@ pub fn run() {
}) })
.on_window_event(|window, event| { .on_window_event(|window, event| {
// Closing a window only hides it; the app keeps running in the // Closing a window only hides it; the app keeps running in the
// tray (for call detection) until "Beenden". // tray (for call detection) until "Beenden". The login window
// really closes: that cancels the login.
if let WindowEvent::CloseRequested { api, .. } = event { if let WindowEvent::CloseRequested { api, .. } = event {
api.prevent_close(); if window.label() != backend::LOGIN_WINDOW {
let _ = window.hide(); api.prevent_close();
let _ = window.hide();
}
} }
}) })
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![
commands::get_app_version,
commands::get_settings, commands::get_settings,
commands::save_settings, commands::save_settings,
commands::set_api_key, commands::set_api_key,
@@ -137,10 +154,16 @@ pub fn run() {
commands::merge_speakers, commands::merge_speakers,
commands::unmerge_speaker, commands::unmerge_speaker,
commands::rename_call, commands::rename_call,
commands::list_accounts, backend::backend_server,
commands::set_account, backend::backend_status,
backend::backend_login,
backend::backend_logout,
backend::open_backend_keys_page,
backend::upload_transcript,
updater::get_update, updater::get_update,
updater::install_update, updater::install_update,
updater::check_for_update_now,
updater::can_self_update,
]) ])
.run(tauri::generate_context!()) .run(tauri::generate_context!())
.expect("error while building tauri application"); .expect("error while building tauri application");
+539 -46
View File
@@ -17,14 +17,14 @@ use std::time::{Duration, Instant};
use chrono::{DateTime, Local}; use chrono::{DateTime, Local};
use recorder_audio::RenderSession; use recorder_audio::RenderSession;
use recorder_core::accounts; use recorder_core::backend::{BackendClient, KeyInfo, NewKey, StoredKey};
use recorder_core::call_view::{self, CallDetail, CallListItem}; use recorder_core::call_view::{self, CallDetail, CallListItem};
use recorder_core::capture::{CaptureSource, OutputTarget}; use recorder_core::capture::{CaptureSource, OutputTarget};
use recorder_core::detect::{CallDetector, DetectorEvent, MicSession}; use recorder_core::detect::{CallDetector, DetectorEvent, MicSession};
use recorder_core::http::{HttpTransport, ReqwestTransport}; use recorder_core::http::{HttpTransport, ReqwestTransport};
use recorder_core::model::{Call, CallId, CallStatus, Speaker}; use recorder_core::model::{Call, CallId, CallStatus, Speaker};
use recorder_core::recorder::Recorder; use recorder_core::recorder::Recorder;
use recorder_core::secrets::SecretStore; use recorder_core::secrets::{SecretStore, Service};
use recorder_core::settings::Settings; use recorder_core::settings::Settings;
use recorder_core::store::Store; use recorder_core::store::Store;
use serde::Serialize; use serde::Serialize;
@@ -157,6 +157,32 @@ pub struct AppState {
/// Set while a recording starts or the devices are tested, so neither /// Set while a recording starts or the devices are tested, so neither
/// runs twice and `current` is never locked for longer than a moment. /// runs twice and `current` is never locked for longer than a moment.
devices_busy: AtomicBool, devices_busy: AtomicBool,
/// The backend this build talks to ([`crate::backend::BACKEND_URL`]).
backend_url: String,
/// Held while the stored backend key and its login change, so a
/// compare-and-delete never removes a key stored meanwhile.
backend_key_lock: Mutex<()>,
/// Calls whose transcript is being uploaded; one upload per call.
uploading: Mutex<HashSet<CallId>>,
/// Calls whose transcript reached the CRM but could not be recorded
/// locally (`mark_uploaded` failed after a successful upload):
/// `claim_upload` refuses these for the rest of this run, so a retry
/// never creates a second copy at the CRM. In-memory only; a restart
/// forgets it (the row's `crm_transcript_id` is still empty then).
upload_confirmed_unsaved: Mutex<HashSet<CallId>>,
}
/// An upload reserved with [`AppState::claim_upload`]; released when
/// dropped, also if the upload fails or panics.
pub struct UploadClaim<'a> {
state: &'a AppState,
id: CallId,
}
impl Drop for UploadClaim<'_> {
fn drop(&mut self) {
lock(&self.state.uploading).remove(&self.id);
}
} }
/// Releases [`AppState::devices_busy`] when dropped. /// Releases [`AppState::devices_busy`] when dropped.
@@ -189,6 +215,15 @@ impl AppState {
pending_prompts: Mutex::new(VecDeque::new()), pending_prompts: Mutex::new(VecDeque::new()),
processing: Mutex::new(HashSet::new()), processing: Mutex::new(HashSet::new()),
devices_busy: AtomicBool::new(false), devices_busy: AtomicBool::new(false),
// Defensive: BACKEND_URL itself must never have a trailing
// slash (see backend::tests::backend_urls_have_no_trailing…),
// but a stored key's base_url is compared against this field.
backend_url: crate::backend::BACKEND_URL
.trim_end_matches('/')
.to_string(),
backend_key_lock: Mutex::new(()),
uploading: Mutex::new(HashSet::new()),
upload_confirmed_unsaved: Mutex::new(HashSet::new()),
} }
} }
@@ -196,15 +231,175 @@ impl AppState {
lock(&self.settings).clone() lock(&self.settings).clone()
} }
/// Validates, saves and applies the settings; the detector picks up the /// Validates, saves and applies the settings the user edited; the
/// new allowlist and delays immediately. /// detector picks up the new allowlist and delays immediately. The
pub fn save_settings(&self, settings: Settings) -> Result<(), String> { /// backend login (managed by the app) is kept.
settings.validate()?; pub fn save_settings(&self, edited: Settings) -> Result<(), String> {
settings let mut current = lock(&self.settings);
.save(&self.settings_path) let settings = current.edited(edited)?;
.map_err(|e| format!("Einstellungen konnten nicht gespeichert werden: {e}"))?; save(&settings, &self.settings_path)?;
lock(&self.detector).set_config(detector_config(&settings)); lock(&self.detector).set_config(detector_config(&settings));
*lock(&self.settings) = settings; *current = settings;
Ok(())
}
/// The backend this build talks to.
pub fn backend_url(&self) -> &str {
&self.backend_url
}
/// Client of this build's backend.
pub fn backend_client(&self) -> BackendClient {
BackendClient::new(self.transport.clone(), &self.backend_url)
}
/// The stored backend key with its expiry, if it was created for this
/// build's backend. A key of another backend is discarded instead (as
/// if expired), so it is never sent anywhere else. Reads the keyring,
/// so call it off the UI thread.
pub fn backend_key(&self) -> Option<StoredKey> {
let _key_lock = lock(&self.backend_key_lock);
let key = self
.secrets
.get(Service::Backend)
.filter(|key| !key.trim().is_empty())?;
let settings = self.settings();
if settings.backend_key_base_url.as_deref() != Some(self.backend_url.as_str()) {
log::info!(
"backend: the stored key belongs to {:?}, not {:?}: discarding it",
settings.backend_key_base_url,
self.backend_url
);
if let Err(e) = self.forget_backend_key() {
log::error!("backend: {e}");
}
return None;
}
Some(StoredKey {
key,
expires_at: settings.backend_key_expires_at,
})
}
/// Stores a key the login created for the backend at `base_url` (in
/// the keyring) with whose it is, when it expires and its backend (in
/// the settings). A key of another backend than this build's is
/// refused and nothing stored.
pub fn store_backend_key(
&self,
key: &NewKey,
base_url: &str,
username: Option<String>,
) -> Result<(), String> {
let base_url = base_url.trim_end_matches('/');
if base_url != self.backend_url {
return Err(format!(
"Der Schlüssel gehört zu einem anderen Server ({base_url}) und wurde nicht gespeichert."
));
}
let _key_lock = lock(&self.backend_key_lock);
self.secrets
.set(Service::Backend, &key.key)
.map_err(|e| format!("Backend-Schlüssel konnte nicht gespeichert werden: {e}"))?;
self.update_settings(|s| {
s.backend_username = username;
s.backend_key_expires_at = Some(key.expires_at);
s.backend_key_base_url = Some(base_url.to_string());
})
}
/// Takes over whose the stored key is and when it expires, as the
/// backend reports it.
pub fn refresh_backend_login(&self, info: &KeyInfo) -> Result<(), String> {
self.update_settings(|s| {
s.backend_username = Some(info.username.clone());
s.backend_key_expires_at = Some(info.expires_at);
})
}
/// "Abmelden": forgets the backend key (keyring) and its login
/// (settings).
pub fn discard_backend_key(&self) -> Result<(), String> {
let _key_lock = lock(&self.backend_key_lock);
self.forget_backend_key()
}
/// Forgets the stored backend key only if it still is `refused`, the
/// key the backend just refused; a key stored meanwhile (by a login)
/// stays. Returns whether it was forgotten.
pub fn discard_refused_backend_key(&self, refused: &str) -> Result<bool, String> {
let _key_lock = lock(&self.backend_key_lock);
if self.secrets.get(Service::Backend).as_deref() != Some(refused) {
return Ok(false);
}
self.forget_backend_key().map(|()| true)
}
/// Deletes the key and its login; the caller holds `backend_key_lock`.
/// The keyring is never called while the settings are locked.
fn forget_backend_key(&self) -> Result<(), String> {
self.secrets
.delete(Service::Backend)
.map_err(|e| format!("Backend-Schlüssel konnte nicht entfernt werden: {e}"))?;
self.update_settings(|s| {
s.backend_username = None;
s.backend_key_expires_at = None;
s.backend_key_base_url = None;
})
}
/// Reserves call `id` for one upload; released when the claim is
/// dropped. A second upload of the same call is refused meanwhile, and
/// so is a call already uploaded to *this build's* backend
/// ([`call_view::uploaded_here`]) — or one the CRM confirmed but whose
/// id could not be saved locally, see
/// [`AppState::note_upload_confirmed_but_unsaved`]: the CRM this build
/// talks to must never get a duplicate. An upload recorded for another
/// backend (e.g. the test backend, read by a release build) is not
/// "uploaded" here and is claimed like any other call. All three checks
/// happen while `uploading` is locked, so a second upload can never
/// slip in between this check and the one upload it allows.
pub fn claim_upload(&self, id: CallId) -> Result<UploadClaim<'_>, String> {
let mut uploading = lock(&self.uploading);
if uploading.contains(&id) {
return Err("Wird bereits hochgeladen".to_string());
}
if lock(&self.upload_confirmed_unsaved).contains(&id) {
return Err("Bereits hochgeladen".to_string());
}
// An upload recorded for another backend (e.g. the test backend,
// read by a release build) does not count: the CRM this build
// talks to has never seen this transcript.
if call_view::uploaded_here(&self.find_call(id)?, &self.backend_url) {
return Err("Bereits hochgeladen".to_string());
}
uploading.insert(id);
Ok(UploadClaim { state: self, id })
}
/// Whether call `id`'s transcript is being uploaded.
pub fn is_uploading(&self, id: CallId) -> bool {
lock(&self.uploading).contains(&id)
}
/// Records that call `id`'s transcript reached the CRM, but saving that
/// locally (`mark_uploaded`) failed: [`AppState::claim_upload`] refuses
/// this call for the rest of the run, so a retry can never send the CRM
/// a second copy. In-memory only; see the field's doc comment.
pub fn note_upload_confirmed_but_unsaved(&self, id: CallId) {
lock(&self.upload_confirmed_unsaved).insert(id);
}
/// Changes and saves settings the app manages itself; saves only if
/// something changed.
fn update_settings(&self, change: impl FnOnce(&mut Settings)) -> Result<(), String> {
let mut current = lock(&self.settings);
let mut settings = current.clone();
change(&mut settings);
if settings != *current {
save(&settings, &self.settings_path)?;
*current = settings;
}
Ok(()) Ok(())
} }
@@ -438,17 +633,22 @@ impl AppState {
/// All calls for the main window's list, newest first. /// All calls for the main window's list, newest first.
pub fn call_list(&self) -> Result<Vec<CallListItem>, String> { pub fn call_list(&self) -> Result<Vec<CallListItem>, String> {
let calls = self.store.list_calls().map_err(|e| e.to_string())?; let calls = self.store.list_calls().map_err(|e| e.to_string())?;
Ok(calls.iter().map(CallListItem::of).collect()) Ok(calls
.iter()
.map(|call| CallListItem::of(call, &self.backend_url))
.collect())
} }
/// The selected call with its transcript (speaker merges applied) and /// The selected call with its transcript (speaker merges applied),
/// speaker names. /// speaker names and whether it is being uploaded.
pub fn call_detail(&self, id: CallId) -> Result<CallDetail, String> { pub fn call_detail(&self, id: CallId) -> Result<CallDetail, String> {
let call = self.find_call(id)?; let call = self.find_call(id)?;
let segments = self.store.segments(id).map_err(|e| e.to_string())?; let segments = self.store.segments(id).map_err(|e| e.to_string())?;
let names = self.store.speaker_names(id).map_err(|e| e.to_string())?; let names = self.store.speaker_names(id).map_err(|e| e.to_string())?;
let merges = self.store.speaker_merges(id).map_err(|e| e.to_string())?; let merges = self.store.speaker_merges(id).map_err(|e| e.to_string())?;
Ok(CallDetail::of(&call, &segments, names, &merges)) let mut detail = CallDetail::of(&call, &segments, names, &merges, &self.backend_url);
detail.uploading = self.is_uploading(id);
Ok(detail)
} }
/// Renames a speaker of call `id`; a blank `name` restores the default /// Renames a speaker of call `id`; a blank `name` restores the default
@@ -496,15 +696,13 @@ impl AppState {
self.store.set_title(id, title).map_err(|e| e.to_string()) self.store.set_title(id, title).map_err(|e| e.to_string())
} }
/// Assigns call `id` to one of the [`accounts`], or to none. /// Records that call `id`'s transcript was just uploaded and the CRM
pub fn set_account(&self, id: CallId, account_id: Option<&str>) -> Result<(), String> { /// gave it `crm_transcript_id`.
if account_id.is_some_and(|account| !accounts::exists(account)) { pub fn mark_uploaded(&self, id: CallId, crm_transcript_id: &str) -> Result<(), String> {
return Err("Unbekannter Kunde".to_string());
}
self.find_call(id)?; self.find_call(id)?;
self.store self.store
.set_account(id, account_id) .set_uploaded(id, crm_transcript_id, &self.backend_url, Local::now())
.map_err(|e| format!("Kunde konnte nicht gespeichert werden: {e}")) .map_err(|e| format!("Upload konnte nicht vermerkt werden: {e}"))
} }
fn find_call(&self, id: CallId) -> Result<Call, String> { fn find_call(&self, id: CallId) -> Result<Call, String> {
@@ -708,6 +906,12 @@ fn detected_output_target(
} }
} }
fn save(settings: &Settings, path: &Path) -> Result<(), String> {
settings
.save(path)
.map_err(|e| format!("Einstellungen konnten nicht gespeichert werden: {e}"))
}
fn output_target(settings: &Settings) -> OutputTarget { fn output_target(settings: &Settings) -> OutputTarget {
match &settings.output_device { match &settings.output_device {
Some(id) => OutputTarget::Device(id.clone()), Some(id) => OutputTarget::Device(id.clone()),
@@ -725,8 +929,9 @@ fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use chrono::TimeZone; use chrono::TimeZone;
use recorder_core::backend::{KeyInfo, NewKey, StoredKey};
use recorder_core::model::{Segment, Speaker}; use recorder_core::model::{Segment, Speaker};
use recorder_core::secrets::MemorySecrets; use recorder_core::secrets::{MemorySecrets, Service};
use super::*; use super::*;
@@ -1244,30 +1449,6 @@ mod tests {
); );
} }
#[test]
fn the_account_is_set_and_cleared() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
let account = |f: &Fixture| f.state.store.get_call(id).unwrap().unwrap().account_id;
f.state.set_account(id, Some("mock-2")).unwrap();
assert_eq!(account(&f).as_deref(), Some("mock-2"));
f.state.set_account(id, None).unwrap();
assert_eq!(account(&f), None);
}
#[test]
fn only_known_accounts_and_calls_are_assigned() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
assert!(f.state.set_account(id, Some("mock-99")).is_err());
assert!(f.state.set_account(id + 1, Some("mock-1")).is_err());
assert_eq!(
f.state.store.get_call(id).unwrap().unwrap().account_id,
None
);
}
#[test] #[test]
fn invalid_detection_delays_are_not_saved() { fn invalid_detection_delays_are_not_saved() {
let f = fixture(); let f = fixture();
@@ -1290,6 +1471,318 @@ mod tests {
assert_eq!(f.state.settings(), valid); assert_eq!(f.state.settings(), valid);
} }
fn new_key(key: &str) -> NewKey {
NewKey {
key: key.into(),
expires_at: Local.with_ymd_and_hms(2027, 11, 6, 10, 0, 0).unwrap(),
}
}
const BASE: &str = crate::backend::BACKEND_URL;
#[test]
fn a_stored_backend_key_comes_with_its_login_and_server() {
let f = fixture();
assert_eq!(f.state.backend_key(), None);
f.state
.store_backend_key(
&new_key("euv_k"),
&format!("{BASE}/"),
Some("hinrichs".into()),
)
.unwrap();
let expires_at = Local.with_ymd_and_hms(2027, 11, 6, 10, 0, 0).unwrap();
assert_eq!(
f.state.backend_key(),
Some(StoredKey {
key: "euv_k".into(),
expires_at: Some(expires_at),
})
);
let saved = Settings::load(&f.dir.path().join("settings.json"));
assert_eq!(saved.backend_username.as_deref(), Some("hinrichs"));
assert_eq!(saved.backend_key_expires_at, Some(expires_at));
assert_eq!(saved.backend_key_base_url.as_deref(), Some(BASE));
assert!(!fs::read_to_string(f.dir.path().join("settings.json"))
.unwrap()
.contains("euv_k"));
assert_eq!(f.state.settings(), saved);
}
#[test]
fn a_key_of_another_server_is_not_stored() {
let f = fixture();
let err = f
.state
.store_backend_key(&new_key("euv_k"), "https://other.example", None)
.unwrap_err();
assert!(err.contains("anderen Server"), "{err}");
assert_eq!(f.state.secrets.get(Service::Backend), None);
assert_eq!(f.state.settings(), Settings::default());
}
#[test]
fn a_stored_key_of_another_server_is_discarded_before_use() {
for recorded in [Some("https://other.example"), None] {
let f = fixture();
f.state
.store_backend_key(&new_key("euv_k"), BASE, Some("hinrichs".into()))
.unwrap();
// As if stored by a build for another backend.
f.state
.update_settings(|s| s.backend_key_base_url = recorded.map(str::to_string))
.unwrap();
assert_eq!(f.state.backend_key(), None, "{recorded:?}");
assert_eq!(f.state.secrets.get(Service::Backend), None);
let settings = f.state.settings();
assert_eq!(settings.backend_username, None);
assert_eq!(settings.backend_key_expires_at, None);
assert_eq!(settings.backend_key_base_url, None);
}
}
/// The real transition the review asked to lock in: a key created while
/// this install talked to the test backend must not work once the same
/// install is a release build talking to the production backend — it is
/// discarded and a fresh login is required, exactly like any other
/// backend mismatch above, but with the two real build-time constants
/// instead of a placeholder domain.
#[test]
fn a_key_from_the_test_backend_does_not_work_for_a_release_build() {
let mut f = fixture();
// A build on the test backend (what `cargo tauri dev` is), whatever
// profile this test itself runs in.
f.state.backend_url = crate::backend::DEV_BACKEND_URL.to_string();
f.state
.store_backend_key(
&new_key("euv_test"),
crate::backend::DEV_BACKEND_URL,
Some("hinrichs".into()),
)
.unwrap();
assert!(f.state.backend_key().is_some());
// Same keyring entry and settings file; now read as a release build
// would (a different `backend_url`, nothing else changed).
f.state.backend_url = crate::backend::RELEASE_BACKEND_URL.to_string();
assert_eq!(
f.state.backend_key(),
None,
"a test-backend key must not work for the release backend"
);
assert_eq!(f.state.secrets.get(Service::Backend), None);
let settings = f.state.settings();
assert_eq!(settings.backend_username, None);
assert_eq!(settings.backend_key_base_url, None);
}
#[test]
fn the_backend_login_is_refreshed_from_the_key_info() {
let f = fixture();
f.state
.store_backend_key(&new_key("euv_k"), BASE, None)
.unwrap();
let later = Local.with_ymd_and_hms(2028, 1, 1, 0, 0, 0).unwrap();
f.state
.refresh_backend_login(&KeyInfo {
label: "l".into(),
hint: "h".into(),
username: "hinrichs".into(),
created_at: later,
expires_at: later,
})
.unwrap();
let settings = f.state.settings();
assert_eq!(settings.backend_username.as_deref(), Some("hinrichs"));
assert_eq!(settings.backend_key_expires_at, Some(later));
assert_eq!(settings.backend_key_base_url.as_deref(), Some(BASE));
}
#[test]
fn a_discarded_backend_key_is_gone_with_its_login() {
let f = fixture();
f.state
.store_backend_key(&new_key("euv_k"), BASE, Some("hinrichs".into()))
.unwrap();
f.state.discard_backend_key().unwrap();
assert_eq!(f.state.backend_key(), None);
assert_eq!(f.state.secrets.get(Service::Backend), None);
let settings = f.state.settings();
assert_eq!(settings.backend_username, None);
assert_eq!(settings.backend_key_expires_at, None);
assert_eq!(settings.backend_key_base_url, None);
}
#[test]
fn only_the_refused_key_is_discarded() {
let f = fixture();
f.state
.store_backend_key(&new_key("euv_new"), BASE, None)
.unwrap();
// A login stored a new key after the old one was refused.
assert_eq!(f.state.discard_refused_backend_key("euv_old"), Ok(false));
assert_eq!(
f.state.backend_key().map(|k| k.key).as_deref(),
Some("euv_new")
);
assert_eq!(f.state.discard_refused_backend_key("euv_new"), Ok(true));
assert_eq!(f.state.backend_key(), None);
assert_eq!(f.state.settings().backend_key_base_url, None);
}
#[test]
fn saving_settings_keeps_the_backend_login() {
let f = fixture();
f.state
.store_backend_key(&new_key("euv_k"), BASE, Some("hinrichs".into()))
.unwrap();
// The settings page sends what it loaded, maybe before the login.
let edited = Settings {
retention_days: 14,
..Settings::default()
};
assert_eq!(f.state.save_settings(edited), Ok(()));
assert!(f.state.backend_key().is_some());
let settings = f.state.settings();
assert_eq!(settings.backend_username.as_deref(), Some("hinrichs"));
assert_eq!(settings.backend_key_base_url.as_deref(), Some(BASE));
assert_eq!(settings.retention_days, 14);
}
#[test]
fn the_backend_is_fixed_per_build() {
let f = fixture();
// Debug builds (`cargo tauri dev`, `cargo test`) use the test
// backend, release builds the production one.
let expected = if cfg!(debug_assertions) {
"https://test.euvinopro.eu"
} else {
"https://backend.euvinopro.eu"
};
assert_eq!(f.state.backend_url(), expected);
assert_eq!(
f.state.backend_client().login_url(),
format!("{expected}/euvadm")
);
}
#[test]
fn a_call_is_uploaded_once_at_a_time() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
let (other, _, _) = finished_call(&f, "b");
assert!(!f.state.call_detail(id).unwrap().uploading);
let claim = f.state.claim_upload(id).unwrap();
assert!(f.state.is_uploading(id));
assert!(f.state.call_detail(id).unwrap().uploading);
assert_eq!(
f.state.claim_upload(id).err(),
Some("Wird bereits hochgeladen".to_string())
);
assert!(f.state.claim_upload(other).is_ok(), "other calls are free");
drop(claim);
assert!(!f.state.is_uploading(id));
assert!(f.state.claim_upload(id).is_ok());
}
#[test]
fn a_call_already_uploaded_is_not_claimed_again() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
f.state.mark_uploaded(id, "4711").unwrap();
assert_eq!(
f.state.claim_upload(id).err(),
Some("Bereits hochgeladen".to_string())
);
assert!(!f.state.is_uploading(id));
}
/// The real case the review asked to lock in: a call uploaded to the
/// test backend is refused for upload by a build whose own backend is
/// the test backend (the normal case, above), but uploadable again by a
/// build whose backend is the production one — the CRM at that backend
/// has never seen this transcript.
#[test]
fn an_upload_to_another_backend_is_not_counted_as_uploaded_here() {
let mut f = fixture();
let (id, _, _) = finished_call(&f, "a");
// A build on the test backend (what `cargo tauri dev` is), whatever
// profile this test itself runs in: mark_uploaded records it.
f.state.backend_url = crate::backend::DEV_BACKEND_URL.to_string();
f.state.mark_uploaded(id, "4711").unwrap();
assert_eq!(
f.state.find_call(id).unwrap().crm_base_url.as_deref(),
Some(crate::backend::DEV_BACKEND_URL)
);
assert_eq!(
f.state.claim_upload(id).err(),
Some("Bereits hochgeladen".to_string())
);
// The same row, now read as a release build would be: a different
// backend, nothing else changed.
f.state.backend_url = crate::backend::RELEASE_BACKEND_URL.to_string();
assert!(f.state.claim_upload(id).is_ok());
}
#[test]
fn an_upload_confirmed_but_unsaved_is_never_retried() {
// The CRM has the transcript, but mark_uploaded failed: the row
// itself still shows no crm_transcript_id.
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
f.state.note_upload_confirmed_but_unsaved(id);
assert!(f
.state
.call_detail(id)
.unwrap()
.call
.item
.crm_transcript_id
.is_none());
assert_eq!(
f.state.claim_upload(id).err(),
Some("Bereits hochgeladen".to_string())
);
assert!(!f.state.is_uploading(id));
}
#[test]
fn an_upload_is_recorded_on_the_call() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
f.state.mark_uploaded(id, "4711").unwrap();
let call = f.state.store.get_call(id).unwrap().unwrap();
assert_eq!(call.crm_transcript_id.as_deref(), Some("4711"));
assert_eq!(call.crm_base_url.as_deref(), Some(BASE));
assert!(call.uploaded_at.is_some());
assert_eq!(
f.state.mark_uploaded(id + 1, "1"),
Err("Gespräch nicht gefunden".to_string())
);
}
fn render_session(exe: &str, root_pid: u32, device: &str) -> RenderSession { fn render_session(exe: &str, root_pid: u32, device: &str) -> RenderSession {
RenderSession { RenderSession {
exe: exe.to_string(), exe: exe.to_string(),
+306 -31
View File
@@ -2,12 +2,18 @@
//! in `tauri.conf.json`) at startup and every 6 h (sooner after a failed //! in `tauri.conf.json`) at startup and every 6 h (sooner after a failed
//! check), tells the main window about a newer version and installs it when //! check), tells the main window about a newer version and installs it when
//! the user asks, but never while a recording runs or a call is being //! the user asks, but never while a recording runs or a call is being
//! processed. //! processed. The settings' "Nach Updates suchen" button
//! ([`check_for_update_now`]) runs the very same check immediately, counts
//! as an attempt for the same scheduler ([`UpdateSchedule`]) and never runs
//! at the same time as the background loop.
//! //!
//! On Windows the NSIS installer runs in passive mode for the current user //! On Windows the NSIS installer runs in passive mode for the current user
//! (no admin rights) and restarts the app; installing ends this process. //! (no admin rights) and restarts the app; installing ends this process.
//! Debian builds never self-update; a manual check still asks the feed
//! there (see [`can_self_update`]).
use std::fs; use std::fs;
use std::future::Future;
use std::path::Path; use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex; use std::sync::Mutex;
@@ -42,6 +48,17 @@ const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(15 * 60);
const MIB: u64 = 1024 * 1024; const MIB: u64 = 1024 * 1024;
/// Why the banner cannot install yet; the banner shows the same hint. /// Why the banner cannot install yet; the banner shows the same hint.
const BUSY: &str = "Nach der laufenden Aufnahme/Verarbeitung möglich"; const BUSY: &str = "Nach der laufenden Aufnahme/Verarbeitung möglich";
/// The feed's key for the one installable release this app ever builds for
/// itself (see `UpdaterBuilder::target`). Asked explicitly on platforms
/// that cannot self-update, since the feed has no entry of their own and
/// the updater's automatic target lookup would otherwise fail with
/// `TargetsNotFound` even when a newer version exists.
const WINDOWS_TARGET: &str = "windows-x86_64";
/// Why installing is refused outright on this platform (`install_update`'s
/// own guard, in case a future feed ever gets a non-Windows entry and
/// `check` started finding updates there too).
const LINUX_CANNOT_INSTALL: &str =
"Updates werden unter Linux nicht automatisch installiert – bitte das .deb neu installieren.";
/// The newest update found, and whether one is being installed. /// The newest update found, and whether one is being installed.
#[derive(Default)] #[derive(Default)]
@@ -58,6 +75,99 @@ pub struct UpdateInfo {
pub can_install: bool, pub can_install: bool,
} }
/// Answer of `check_for_update_now`: what a check (background or manual)
/// found. On Windows, `Available` also leaves the same state `get_update`
/// reads and fires the same `update-available` event as the background
/// loop, so the main window's banner shows it too; elsewhere it only
/// reports the version (see `check_outcome`).
#[derive(Serialize, Clone, Debug, PartialEq)]
#[serde(tag = "status", rename_all = "lowercase")]
pub enum UpdateCheckResult {
/// No newer version on the feed.
None,
Available {
version: String,
},
/// The feed could not be asked; safe to show (never a secret).
Error {
message: String,
},
}
/// When the last check attempt (background or manual) started and how many
/// failed in a row, shared so a manual check feeds the same scheduler the
/// background loop uses: success resets the 6 h interval and the failure
/// count, a failure advances the backoff by one step. `running` also
/// serializes checks, so a manual and a background check never run at once.
#[derive(Default)]
pub struct UpdateSchedule {
state: Mutex<Schedule>,
running: tokio::sync::Mutex<()>,
}
#[derive(Default, Clone, Copy)]
struct Schedule {
last_attempt: Option<SystemTime>,
failures: u32,
}
impl UpdateSchedule {
/// Whether a check is due at `now`, per the last recorded attempt.
fn is_due(&self, now: SystemTime) -> bool {
let s = lock(&self.state);
check_due(s.last_attempt, s.failures, now)
}
/// Records the outcome of a check attempt that started at `now`.
fn record(&self, now: SystemTime, success: bool) {
let mut s = lock(&self.state);
s.last_attempt = Some(now);
s.failures = if success {
0
} else {
s.failures.saturating_add(1)
};
}
/// Runs one check attempt right now, unconditionally: for a manual
/// check, which the user asked for regardless of whether one is due.
/// Serialized against any other check (background or manual) via
/// `running`, and recorded for the scheduler exactly like a background
/// attempt.
async fn run(&self, app: &AppHandle) -> UpdateCheckResult {
self.attempt(false, || check(app))
.await
.expect("an unconditional attempt always runs")
}
/// For the background loop: like [`UpdateSchedule::run`], but only if a
/// check is still due once `running` is held (see `attempt`).
async fn run_if_due(&self, app: &AppHandle) {
self.attempt(true, || check(app)).await;
}
/// One serialized, recorded check attempt: takes `running`, then (if
/// `only_if_due`) re-checks `is_due` before calling `check`. Without
/// that re-check, a background tick that found a check due but then
/// had to wait behind a manual check (or another tick) would run its
/// own check right after, although the one it waited for just made the
/// next one not due any more. `None`: skipped, nothing recorded.
async fn attempt<F, Fut>(&self, only_if_due: bool, check: F) -> Option<UpdateCheckResult>
where
F: FnOnce() -> Fut,
Fut: Future<Output = UpdateCheckResult>,
{
let _serialize = self.running.lock().await;
let now = SystemTime::now();
if only_if_due && !self.is_due(now) {
return None;
}
let result = check().await;
self.record(now, !matches!(result, UpdateCheckResult::Error { .. }));
Some(result)
}
}
/// Payload of `update-progress`. /// Payload of `update-progress`.
#[derive(Serialize, Clone, Debug, PartialEq)] #[derive(Serialize, Clone, Debug, PartialEq)]
pub struct Progress { pub struct Progress {
@@ -67,27 +177,22 @@ pub struct Progress {
} }
/// Starts the periodic update check. Only on Windows: Debian builds do not /// Starts the periodic update check. Only on Windows: Debian builds do not
/// update themselves. /// update themselves (a manual check from the settings still asks the feed
/// on Linux, see `check_for_update_now`).
pub fn spawn(app: AppHandle) { pub fn spawn(app: AppHandle) {
if !cfg!(windows) { if !cfg!(windows) {
log::info!("update check disabled on this platform"); log::info!("update check disabled on this platform");
return; return;
} }
thread::spawn(move || { thread::spawn(move || loop {
let mut last_attempt = None; let now = SystemTime::now();
let mut failures = 0; // Cheap early exit so most wake-ups never touch `running`; the due
loop { // check that decides whether a check actually runs happens again
let now = SystemTime::now(); // inside `run_if_due`, once `running` is held (see its doc comment).
if check_due(last_attempt, failures, now) { if app.state::<UpdateSchedule>().is_due(now) {
last_attempt = Some(now); tauri::async_runtime::block_on(app.state::<UpdateSchedule>().run_if_due(&app));
if tauri::async_runtime::block_on(check(&app)) {
failures = 0;
} else {
failures = failures.saturating_add(1);
}
}
thread::sleep(WAKE_INTERVAL);
} }
thread::sleep(WAKE_INTERVAL);
}); });
} }
@@ -110,32 +215,66 @@ fn check_due(last_attempt: Option<SystemTime>, failures: u32, now: SystemTime) -
.map_or(true, |elapsed| elapsed >= wait) .map_or(true, |elapsed| elapsed >= wait)
} }
/// Asks the release feed for a newer version; `false` if the check failed. /// Asks the release feed for a newer version: the one implementation the
/// Failures (offline, no release yet) are expected and only logged. /// background loop and a manual check (`check_for_update_now`) both run.
async fn check(app: &AppHandle) -> bool { /// A failed check (offline, no release yet) is expected; only logged here,
let result = match app.updater_builder().timeout(CHECK_TIMEOUT).build() { /// and shown to the user only by a manual check (via the returned message).
///
/// The feed only ever has a `windows-x86_64` entry (Debian builds never
/// self-update, see `RELEASING.md`). On Windows the automatic target lookup
/// finds it on its own; on any other platform it is asked for explicitly
/// ([`WINDOWS_TARGET`]), only to learn the version number — see
/// [`check_outcome`] for why nothing is stored or announced there.
async fn check(app: &AppHandle) -> UpdateCheckResult {
let is_windows = cfg!(windows);
let mut builder = app.updater_builder().timeout(CHECK_TIMEOUT);
if !is_windows {
builder = builder.target(WINDOWS_TARGET);
}
let result = match builder.build() {
Ok(updater) => updater.check().await, Ok(updater) => updater.check().await,
Err(e) => Err(e), Err(e) => Err(e),
}; };
match result { match result {
Ok(Some(update)) => { Ok(found) => {
log::info!("update available: {}", update.version); let version = found.as_ref().map(|update| update.version.clone());
let version = update.version.clone(); match &version {
*lock(&app.state::<PendingUpdate>().update) = Some(update); Some(v) => log::info!("update available: {v}"),
let _ = app.emit("update-available", info(app, version)); None => log::info!("no update available"),
true }
} let (outcome, offer_install) = check_outcome(is_windows, version.clone());
Ok(None) => { if let (Some(update), true) = (found, offer_install) {
log::info!("no update available"); *lock(&app.state::<PendingUpdate>().update) = Some(update);
true let _ = app.emit(
"update-available",
info(app, version.expect("offer_install implies a version")),
);
}
outcome
} }
Err(e) => { Err(e) => {
log::info!("update check failed: {e}"); log::info!("update check failed: {e}");
false UpdateCheckResult::Error {
message: format!("Update-Prüfung fehlgeschlagen: {e}"),
}
} }
} }
} }
/// What a feed answer (`version`, if any) means on this platform: the
/// result to return either way, and whether to remember the update for
/// `install_update` and announce it to the main window's banner. Only
/// Windows self-updates, so only there is a found update ever stored or
/// announced; elsewhere a manual check still reports the version (the
/// settings show it with a "not on this platform" hint instead of an
/// install button), but nothing is kept to install.
fn check_outcome(is_windows: bool, version: Option<String>) -> (UpdateCheckResult, bool) {
match version {
Some(version) => (UpdateCheckResult::Available { version }, is_windows),
None => (UpdateCheckResult::None, false),
}
}
/// Whether this is the first start of `version` (e.g. right after an /// Whether this is the first start of `version` (e.g. right after an
/// update), going by the version remembered in `path`; remembers `version` /// update), going by the version remembered in `path`; remembers `version`
/// for the next start. /// for the next start.
@@ -161,6 +300,24 @@ fn info(app: &AppHandle, version: String) -> UpdateInfo {
} }
} }
/// "Nach Updates suchen" in the settings: runs the same check as the
/// background loop, immediately, reusing its scheduling (a success resets
/// the 6 h interval and the failure count, same as a background success)
/// and never running at the same time as a background check. Works on
/// every platform; see `can_self_update` for whether this build can then
/// install what it finds.
#[tauri::command]
pub async fn check_for_update_now(app: AppHandle) -> UpdateCheckResult {
app.state::<UpdateSchedule>().run(&app).await
}
/// Whether this build can install an update itself (Windows only: Debian
/// builds ship a `.deb` and never self-update, see `spawn`).
#[tauri::command]
pub fn can_self_update() -> bool {
cfg!(windows)
}
/// The update found by the last check, if any. /// The update found by the last check, if any.
#[tauri::command] #[tauri::command]
pub fn get_update(app: AppHandle) -> Option<UpdateInfo> { pub fn get_update(app: AppHandle) -> Option<UpdateInfo> {
@@ -174,6 +331,11 @@ pub fn get_update(app: AppHandle) -> Option<UpdateInfo> {
/// app. Returns only on failure. /// app. Returns only on failure.
#[tauri::command] #[tauri::command]
pub async fn install_update(app: AppHandle) -> Result<(), String> { pub async fn install_update(app: AppHandle) -> Result<(), String> {
// Defense in depth: `check` only ever stores a pending update on
// Windows, but this guard holds even if that ever changes.
if !cfg!(windows) {
return Err(LINUX_CANNOT_INSTALL.to_string());
}
let pending = app.state::<PendingUpdate>(); let pending = app.state::<PendingUpdate>();
if pending.installing.swap(true, Ordering::SeqCst) { if pending.installing.swap(true, Ordering::SeqCst) {
return Err("Das Update wird bereits installiert".to_string()); return Err("Das Update wird bereits installiert".to_string());
@@ -350,4 +512,117 @@ mod tests {
let reports = reported(&mut meter, &[half, half, half, half, half], None); let reports = reported(&mut meter, &[half, half, half, half, half], None);
assert_eq!(reports, [MIB / 2, MIB, 2 * MIB]); assert_eq!(reports, [MIB / 2, MIB, 2 * MIB]);
} }
#[test]
fn update_check_result_maps_to_a_tagged_status() {
assert_eq!(
serde_json::to_value(UpdateCheckResult::None).unwrap(),
serde_json::json!({"status": "none"})
);
assert_eq!(
serde_json::to_value(UpdateCheckResult::Available {
version: "0.3.0".into()
})
.unwrap(),
serde_json::json!({"status": "available", "version": "0.3.0"})
);
assert_eq!(
serde_json::to_value(UpdateCheckResult::Error {
message: "Update-Prüfung fehlgeschlagen: x".into()
})
.unwrap(),
serde_json::json!({"status": "error", "message": "Update-Prüfung fehlgeschlagen: x"})
);
}
/// Only Windows self-updates: elsewhere a found update is still
/// reported (so the settings can show the version), but never stored
/// for `install_update` or announced to the banner.
#[test]
fn only_windows_offers_to_install_a_found_update() {
assert_eq!(
check_outcome(true, Some("0.3.0".into())),
(
UpdateCheckResult::Available {
version: "0.3.0".into()
},
true
)
);
assert_eq!(
check_outcome(false, Some("0.3.0".into())),
(
UpdateCheckResult::Available {
version: "0.3.0".into()
},
false
)
);
assert_eq!(check_outcome(true, None), (UpdateCheckResult::None, false));
assert_eq!(check_outcome(false, None), (UpdateCheckResult::None, false));
}
/// A manual check feeds the very scheduler the background loop reads
/// (`record` is the one function either kind of attempt calls): a
/// failure advances the backoff by exactly the one step a single
/// failure always does (never more just for being a manual attempt),
/// and a success resets the interval to 6 h and the failure count.
#[test]
fn a_manual_checks_result_feeds_the_background_scheduler() {
let schedule = UpdateSchedule::default();
assert!(schedule.is_due(t0()), "nothing attempted yet");
// One failed manual check: due again after the 1st retry delay,
// exactly as check_due(_, 1, _) says, not sooner and not later.
schedule.record(t0(), false);
assert!(!schedule.is_due(t0() + MIN - Duration::from_secs(1)));
assert!(schedule.is_due(t0() + MIN));
// A second failed attempt (background or manual, the scheduler does
// not distinguish) advances to the 2nd retry delay, not further.
schedule.record(t0() + MIN, false);
assert!(!schedule.is_due(t0() + MIN + 5 * MIN - Duration::from_secs(1)));
assert!(schedule.is_due(t0() + MIN + 5 * MIN));
// A manual check that then succeeds resets the interval to 6 h and
// the failure count, exactly like a background success.
schedule.record(t0() + MIN, true);
assert!(!schedule.is_due(t0() + MIN + 6 * HOUR - MIN));
assert!(schedule.is_due(t0() + MIN + 6 * HOUR));
}
/// A background tick that found a check due, but only got `running`
/// after a manual check finished, must not check again: `is_due` is
/// re-checked once the lock is held. Sequential here (the tick's own
/// early `is_due` happened before the manual check, so only the
/// re-check inside `attempt` can stop it).
#[test]
fn a_background_attempt_rechecks_due_once_it_holds_the_lock() {
let schedule = UpdateSchedule::default();
assert!(
schedule.is_due(SystemTime::now()),
"the tick saw a due check"
);
let manual = tauri::async_runtime::block_on(
schedule.attempt(false, || async { UpdateCheckResult::None }),
);
assert_eq!(manual, Some(UpdateCheckResult::None));
let mut checked = false;
let background = tauri::async_runtime::block_on(schedule.attempt(true, || {
checked = true;
async { UpdateCheckResult::None }
}));
assert_eq!(background, None);
assert!(!checked, "no second check right after the manual one");
// A manual check always runs, due or not.
let again = tauri::async_runtime::block_on(schedule.attempt(false, || async {
UpdateCheckResult::Error {
message: "x".into(),
}
}));
assert!(matches!(again, Some(UpdateCheckResult::Error { .. })));
}
} }
+2 -4
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "Gesprächsrekorder", "productName": "Gesprächsrekorder",
"version": "0.1.1", "version": "0.2.2",
"identifier": "eu.euvino.callrecorder", "identifier": "eu.euvino.callrecorder",
"build": { "build": {
"frontendDist": "../ui/dist", "frontendDist": "../ui/dist",
@@ -51,8 +51,7 @@
"active": true, "active": true,
"targets": [ "targets": [
"nsis", "nsis",
"deb", "deb"
"appimage"
], ],
"icon": [ "icon": [
"icons/32x32.png", "icons/32x32.png",
@@ -72,7 +71,6 @@
"updater": { "updater": {
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDIwM0EzNUEyMTUwOThERUQKUldUdGpRa1ZvalU2SVBtYVZRaWlWMVBCNzFTd1BRbmtmdU9sZXMrVTltckNiYlRSSmZHcWpNMHUK", "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDIwM0EzNUEyMTUwOThERUQKUldUdGpRa1ZvalU2SVBtYVZRaWlWMVBCNzFTd1BRbmtmdU9sZXMrVTltckNiYlRSSmZHcWpNMHUK",
"endpoints": [ "endpoints": [
"https://gitea.euvino.eu/public/call-recorder/releases/latest/download/latest.json",
"https://gitea.euvino.eu/public/call-recorder/raw/branch/master/latest.json" "https://gitea.euvino.eu/public/call-recorder/raw/branch/master/latest.json"
], ],
"windows": { "windows": {
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "ui", "name": "ui",
"private": true, "private": true,
"version": "0.1.1", "version": "0.2.2",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
+4 -11
View File
@@ -8,6 +8,8 @@
onRecordingState, onRecordingState,
onUpdateAvailable, onUpdateAvailable,
onUpdateProgress, onUpdateProgress,
updateProgressText,
UPDATE_BUSY_HINT,
type UpdateInfo, type UpdateInfo,
type UpdateProgress, type UpdateProgress,
} from './api' } from './api'
@@ -62,16 +64,7 @@
} }
} }
function megabytes(bytes: number): string { let progressText = $derived(updateProgressText(progress))
return (bytes / 1024 / 1024).toLocaleString('de-DE', { maximumFractionDigits: 1 }) + ' MB'
}
let progressText = $derived.by(() => {
if (!progress) return 'Update wird heruntergeladen…'
if (progress.total === null) return `Update wird heruntergeladen… ${megabytes(progress.downloaded)}`
if (progress.downloaded >= progress.total) return 'Update wird installiert…'
return `Update wird heruntergeladen… ${Math.floor((progress.downloaded * 100) / progress.total)} %`
})
</script> </script>
{#if update} {#if update}
@@ -84,7 +77,7 @@
Installieren &amp; neu starten Installieren &amp; neu starten
</button> </button>
{#if !update.can_install} {#if !update.can_install}
<span class="hint">Nach der laufenden Aufnahme/Verarbeitung möglich</span> <span class="hint">{UPDATE_BUSY_HINT}</span>
{/if} {/if}
{/if} {/if}
{#if error} {#if error}
+76 -10
View File
@@ -15,9 +15,32 @@ export interface Settings {
autostart: boolean autostart: boolean
start_after_secs: number start_after_secs: number
end_after_secs: number end_after_secs: number
/** Whose backend key is stored; set by the app at login. */
backend_username: string | null
/** When the stored backend key expires (RFC 3339); set by the app. */
backend_key_expires_at: string | null
/** The backend the stored key belongs to; set by the app. */
backend_key_base_url: string | null
} }
export type Service = 'deepscript' | 'anthropic' /** The backend this build talks to (fixed per build, not a setting). */
export interface BackendServer {
base_url: string
/** Where the admin manages their keys. */
keys_url: string
}
/** Login status for the settings, checked with the backend. */
export interface BackendStatus {
logged_in: boolean
username: string | null
/** RFC 3339. */
expires_at: string | null
/** `false` if the key could not be checked; username and expiry are then the stored ones. */
reachable: boolean
}
export type Service = 'deepscript'
export interface DeviceInfo { export interface DeviceInfo {
id: string id: string
@@ -67,6 +90,10 @@ export interface CallListItem {
interrupted: boolean interrupted: boolean
/** The name the user gave the call, if any. */ /** The name the user gave the call, if any. */
title: string | null title: string | null
/** The CRM's id of the transcript, from its last upload. */
crm_transcript_id: string | null
/** When the transcript was last uploaded (RFC 3339). */
uploaded_at: string | null
} }
/** A transcript line; `speaker_key` is "me" or "remote:<n>". */ /** A transcript line; `speaker_key` is "me" or "remote:<n>". */
@@ -87,17 +114,14 @@ export interface SpeakerMerge {
} }
export interface CallDetail { export interface CallDetail {
call: CallListItem & { error: string | null; account_id: string | null } call: CallListItem & { error: string | null; transcribed_at: string | null }
/** The transcript with speaker merges applied. */ /** The transcript with speaker merges applied. */
segments: SegmentView[] segments: SegmentView[]
/** Renamed speakers by key. */ /** Renamed speakers by key. */
speaker_names: Record<string, string> speaker_names: Record<string, string>
merges: SpeakerMerge[] merges: SpeakerMerge[]
} /** The transcript is being uploaded right now. */
uploading: boolean
export interface Account {
id: string
name: string
} }
/** A newer version the release feed offers. */ /** A newer version the release feed offers. */
@@ -113,6 +137,15 @@ export interface UpdateProgress {
total: number | null total: number | null
} }
/** Why the install button is disabled, shown next to it as a hint. */
export const UPDATE_BUSY_HINT = 'Nach der laufenden Aufnahme/Verarbeitung möglich'
/** What a check (background or manual) found. */
export type UpdateCheckResult =
| { status: 'none' }
| { status: 'available'; version: string }
| { status: 'error'; message: string }
export interface Levels { export interface Levels {
mic: number mic: number
out: number out: number
@@ -149,12 +182,26 @@ export const unmergeSpeaker = (id: CallId, fromKey: string) =>
/** `null` or an empty title restores the default heading. */ /** `null` or an empty title restores the default heading. */
export const renameCall = (id: CallId, title: string | null) => export const renameCall = (id: CallId, title: string | null) =>
invoke<void>('rename_call', { id, title }) invoke<void>('rename_call', { id, title })
export const listAccounts = () => invoke<Account[]>('list_accounts') export const backendServer = () => invoke<BackendServer>('backend_server')
export const setAccount = (id: CallId, accountId: string | null) => export const backendStatus = () => invoke<BackendStatus>('backend_status')
invoke<void>('set_account', { id, accountId }) /** Resolves once the login window created a key; rejects if it was closed or failed. */
export const backendLogin = () => invoke<void>('backend_login')
export const backendLogout = () => invoke<void>('backend_logout')
/** Opens the backend's key management page in the system browser. */
export const openBackendKeysPage = () => invoke<void>('open_backend_keys_page')
/** Logs in first if needed; resolves once the CRM has the transcript. */
export const uploadTranscript = (id: CallId) => invoke<void>('upload_transcript', { id })
export const getUpdate = () => invoke<UpdateInfo | null>('get_update') export const getUpdate = () => invoke<UpdateInfo | null>('get_update')
/** Resolves only on failure: on success the app restarts. */ /** Resolves only on failure: on success the app restarts. */
export const installUpdate = () => invoke<void>('install_update') export const installUpdate = () => invoke<void>('install_update')
/** This build's own version, for the settings' "Updates" section. */
export const getAppVersion = () => invoke<string>('get_app_version')
/** Whether this build can install an update itself (Windows only). */
export const canSelfUpdate = () => invoke<boolean>('can_self_update')
/** "Nach Updates suchen": runs the same check as the background loop,
* immediately. An `available` result leaves the same state `getUpdate`
* reads, so the main window's banner shows it too. */
export const checkForUpdateNow = () => invoke<UpdateCheckResult>('check_for_update_now')
export const onRecordingState = (handler: (state: RecordingState) => void): Promise<UnlistenFn> => export const onRecordingState = (handler: (state: RecordingState) => void): Promise<UnlistenFn> =>
listen<RecordingState>('recording-state', (event) => handler(event.payload)) listen<RecordingState>('recording-state', (event) => handler(event.payload))
@@ -166,6 +213,12 @@ export const onPromptChanged = (handler: () => void): Promise<UnlistenFn> =>
/** A call's status changed (processing started, done or failed). */ /** A call's status changed (processing started, done or failed). */
export const onCallUpdated = (handler: (id: CallId) => void): Promise<UnlistenFn> => export const onCallUpdated = (handler: (id: CallId) => void): Promise<UnlistenFn> =>
listen<{ id: CallId }>('call-updated', (event) => handler(event.payload.id)) listen<{ id: CallId }>('call-updated', (event) => handler(event.payload.id))
/** The backend login changed (logged in, logged out, key discarded). */
export const onBackendChanged = (handler: () => void): Promise<UnlistenFn> =>
listen<null>('backend-changed', () => handler())
/** Creating the key failed; the login window stays open for another try. */
export const onBackendLoginError = (handler: (message: string) => void): Promise<UnlistenFn> =>
listen<{ message: string }>('backend-login-error', (event) => handler(event.payload.message))
export const onUpdateAvailable = (handler: (info: UpdateInfo) => void): Promise<UnlistenFn> => export const onUpdateAvailable = (handler: (info: UpdateInfo) => void): Promise<UnlistenFn> =>
listen<UpdateInfo>('update-available', (event) => handler(event.payload)) listen<UpdateInfo>('update-available', (event) => handler(event.payload))
export const onUpdateProgress = ( export const onUpdateProgress = (
@@ -182,6 +235,19 @@ export function meterFill(level: number): number {
return Math.min(1, Math.max(0, (db + 60) / 60)) return Math.min(1, Math.max(0, (db + 60) / 60))
} }
function megabytes(bytes: number): string {
return (bytes / 1024 / 1024).toLocaleString('de-DE', { maximumFractionDigits: 1 }) + ' MB'
}
/** Text shown while an update installs (the banner and the settings'
* Updates section share this). */
export function updateProgressText(progress: UpdateProgress | null): string {
if (!progress) return 'Update wird heruntergeladen…'
if (progress.total === null) return `Update wird heruntergeladen… ${megabytes(progress.downloaded)}`
if (progress.downloaded >= progress.total) return 'Update wird installiert…'
return `Update wird heruntergeladen… ${Math.floor((progress.downloaded * 100) / progress.total)} %`
}
/** Error text of a rejected command. */ /** Error text of a rejected command. */
export function errorText(err: unknown): string { export function errorText(err: unknown): string {
return typeof err === 'string' ? err : err instanceof Error ? err.message : String(err) return typeof err === 'string' ? err : err instanceof Error ? err.message : String(err)
+11
View File
@@ -53,3 +53,14 @@ export function formatOffset(secs: number): string {
const ss = pad(total % 60) const ss = pad(total % 60)
return h > 0 ? `${h}:${mm}:${ss}` : `${mm}:${ss}` return h > 0 ? `${h}:${mm}:${ss}` : `${mm}:${ss}`
} }
/** "06.11.2027". */
export function formatDate(iso: string): string {
const d = new Date(iso)
return `${pad(d.getDate())}.${pad(d.getMonth() + 1)}.${d.getFullYear()}`
}
/** "06.11.2026 14:05". */
export function formatDateTime(iso: string): string {
return `${formatDate(iso)} ${clock(new Date(iso))}`
}
+64 -105
View File
@@ -5,9 +5,9 @@
errorText, errorText,
getCall, getCall,
getRecordingState, getRecordingState,
listAccounts,
listCalls, listCalls,
mergeSpeakers, mergeSpeakers,
onBackendLoginError,
onCallEnded, onCallEnded,
onCallUpdated, onCallUpdated,
onPromptChanged, onPromptChanged,
@@ -15,19 +15,18 @@
renameCall, renameCall,
renameSpeaker, renameSpeaker,
retryCall, retryCall,
setAccount,
showRecorder, showRecorder,
startManualRecording, startManualRecording,
transcribeCall, transcribeCall,
unmergeSpeaker, unmergeSpeaker,
type Account, uploadTranscript,
type CallDetail, type CallDetail,
type CallId, type CallId,
type CallListItem, type CallListItem,
type RecordingState, type RecordingState,
} from '../lib/api' } from '../lib/api'
import CallList from '../lib/CallList.svelte' import CallList from '../lib/CallList.svelte'
import { formatDetailTime, formatMinutes } from '../lib/format' import { formatDateTime, formatDetailTime, formatMinutes } from '../lib/format'
import StatusPill from '../lib/StatusPill.svelte' import StatusPill from '../lib/StatusPill.svelte'
import TranscriptView from '../lib/TranscriptView.svelte' import TranscriptView from '../lib/TranscriptView.svelte'
import UpdateBanner from '../lib/UpdateBanner.svelte' import UpdateBanner from '../lib/UpdateBanner.svelte'
@@ -35,7 +34,6 @@
let calls = $state<CallListItem[]>([]) let calls = $state<CallListItem[]>([])
let loaded = $state(false) let loaded = $state(false)
let listError = $state('') let listError = $state('')
let accounts = $state<Account[]>([])
let recordingState = $state<RecordingState>({ state: 'idle' }) let recordingState = $state<RecordingState>({ state: 'idle' })
let recordBusy = $state(false) let recordBusy = $state(false)
@@ -46,7 +44,11 @@
let detailError = $state('') let detailError = $state('')
let actionError = $state('') let actionError = $state('')
let busy = $state(false) let busy = $state(false)
let tab = $state<'summary' | 'transcript'>('transcript')
// Uploads run per call and may outlive the selection (the login can
// take a while); their errors are kept per call too.
let uploading = $state<CallId[]>([])
let uploadErrors = $state<Record<CallId, string>>({})
let editingTitle = $state(false) let editingTitle = $state(false)
let titleDraft = $state('') let titleDraft = $state('')
@@ -122,6 +124,10 @@
if (id === selectedId) refreshDetail() if (id === selectedId) refreshDetail()
}), }),
onCallEnded(refreshList), onCallEnded(refreshList),
// Creating the key failed; the login window stays open for another try.
onBackendLoginError((msg) => {
for (const id of uploading) uploadErrors[id] = msg
}),
onPromptChanged(refreshList), onPromptChanged(refreshList),
onRecordingState((state) => { onRecordingState((state) => {
recordingState = state recordingState = state
@@ -132,9 +138,6 @@
getRecordingState() getRecordingState()
.then((state) => (recordingState = state)) .then((state) => (recordingState = state))
.catch((err) => (recordError = errorText(err))) .catch((err) => (recordError = errorText(err)))
listAccounts()
.then((list) => (accounts = list))
.catch((err) => (listError = errorText(err)))
return () => unlisten.forEach((u) => u.then((off) => off())) return () => unlisten.forEach((u) => u.then((off) => off()))
}) })
@@ -186,18 +189,23 @@
refreshList() refreshList()
}) })
function changeAccount(event: Event) { /** Uploads the shown call's transcript (logging in first if needed). A
const select = event.currentTarget as HTMLSelectElement * call already uploaded has no button any more: the CRM never gets a
const previous = detail?.call.account_id ?? '' * duplicate. */
run(async (id) => { async function upload() {
try { if (!detail) return
await setAccount(id, select.value || null) const id = detail.call.id
} catch (err) { if (uploading.includes(id)) return
select.value = previous uploading = [...uploading, id]
throw err delete uploadErrors[id]
} try {
await refreshDetail() await uploadTranscript(id)
}) delete uploadErrors[id]
} catch (err) {
uploadErrors[id] = errorText(err)
} finally {
uploading = uploading.filter((u) => u !== id)
}
} }
async function rename(speakerKey: string, name: string) { async function rename(speakerKey: string, name: string) {
@@ -256,12 +264,11 @@
return parts.join(' · ') return parts.join(' · ')
} }
/** The account list plus the stored account if it is no longer listed. */ // Also while an upload started elsewhere (e.g. before switching views)
let accountOptions = $derived.by(() => { // still runs in the app.
const stored = detail?.call.account_id let isUploading = $derived(
if (!stored || accounts.some((a) => a.id === stored)) return accounts detail !== null && (uploading.includes(detail.call.id) || detail.uploading),
return [...accounts, { id: stored, name: `${stored} (unbekannt)` }] )
})
// A failed start (e.g. missing key) also marks the call failed; its // A failed start (e.g. missing key) also marks the call failed; its
// error is then shown once, in the failure box. // error is then shown once, in the failure box.
@@ -332,15 +339,11 @@
<p class="error">{titleError}</p> <p class="error">{titleError}</p>
{/if} {/if}
<div class="toolbar"> <div class="toolbar">
<label class="customer"> {#if call.status === 'done' && call.uploaded_at}
<span>Kunde:</span> <span class="muted uploaded">
<select value={call.account_id ?? ''} disabled={busy} onchange={changeAccount}> Hochgeladen am {formatDateTime(call.uploaded_at)} (ID {call.crm_transcript_id})
<option value="">— kein Kunde —</option> </span>
{#each accountOptions as account (account.id)} {/if}
<option value={account.id}>{account.name}</option>
{/each}
</select>
</label>
<span class="actions"> <span class="actions">
{#if call.status === 'awaiting_decision'} {#if call.status === 'awaiting_decision'}
<button class="btn primary" disabled={busy} onclick={transcribe}>Transkribieren</button> <button class="btn primary" disabled={busy} onclick={transcribe}>Transkribieren</button>
@@ -348,16 +351,24 @@
{:else if call.status === 'failed'} {:else if call.status === 'failed'}
<button class="btn primary" disabled={busy} onclick={retry}>Erneut versuchen</button> <button class="btn primary" disabled={busy} onclick={retry}>Erneut versuchen</button>
<button class="btn danger" disabled={busy} onclick={discard}>Verwerfen</button> <button class="btn danger" disabled={busy} onclick={discard}>Verwerfen</button>
{:else if call.status === 'done'} {:else if call.status === 'done' && !call.uploaded_at}
<span title="Kommt in einer späteren Version"> <button
<button class="btn" disabled>In Kundenakte speichern</button> class="btn primary"
</span> disabled={!call.transcribed_at || isUploading}
title={call.transcribed_at ? 'Transkript ins CRM hochladen' : 'Noch kein Transkript'}
onclick={upload}
>
{isUploading ? 'wird hochgeladen…' : 'Transkript hochladen'}
</button>
{/if} {/if}
</span> </span>
</div> </div>
{#if shownActionError} {#if shownActionError}
<p class="error">{shownActionError}</p> <p class="error">{shownActionError}</p>
{/if} {/if}
{#if uploadErrors[call.id]}
<p class="error">{uploadErrors[call.id]}</p>
{/if}
</header> </header>
<div class="body"> <div class="body">
@@ -377,33 +388,13 @@
<div>{call.error ?? 'Unbekannter Fehler'}</div> <div>{call.error ?? 'Unbekannter Fehler'}</div>
</div> </div>
{:else} {:else}
<div class="tabs" role="tablist"> <TranscriptView
<button segments={detail.segments}
role="tab" merges={detail.merges}
aria-selected={tab === 'summary'} onrename={rename}
class:active={tab === 'summary'} onmerge={merge}
onclick={() => (tab = 'summary')}>Zusammenfassung</button onunmerge={unmerge}
> />
<button
role="tab"
aria-selected={tab === 'transcript'}
class:active={tab === 'transcript'}
onclick={() => (tab = 'transcript')}>Transkript</button
>
</div>
<div class="tab-panel" role="tabpanel">
{#if tab === 'summary'}
<p class="muted">Die Zusammenfassung kommt in einer späteren Version.</p>
{:else}
<TranscriptView
segments={detail.segments}
merges={detail.merges}
onrename={rename}
onmerge={merge}
onunmerge={unmerge}
/>
{/if}
</div>
{/if} {/if}
</div> </div>
{:else if detailError} {:else if detailError}
@@ -552,23 +543,18 @@
margin-top: 12px; margin-top: 12px;
} }
.customer {
display: inline-flex;
align-items: center;
gap: 8px;
font-weight: 600;
}
.customer select {
max-width: 260px;
}
.actions { .actions {
display: inline-flex; display: inline-flex;
align-items: center;
flex-wrap: wrap;
gap: 8px; gap: 8px;
margin-left: auto; margin-left: auto;
} }
.uploaded {
font-size: 12px;
}
.detail-header .error { .detail-header .error {
margin: 10px 0 0; margin: 10px 0 0;
} }
@@ -588,31 +574,4 @@
background: var(--rec-soft); background: var(--rec-soft);
color: var(--rec); color: var(--rec);
} }
.tabs {
display: flex;
gap: 4px;
border-bottom: 1px solid var(--border);
}
.tabs button {
padding: 8px 14px;
border: none;
border-bottom: 2px solid transparent;
margin-bottom: -1px;
background: none;
font: inherit;
font-weight: 600;
color: var(--muted);
cursor: pointer;
}
.tabs button.active {
color: var(--primary);
border-bottom-color: var(--primary);
}
.tab-panel {
padding-top: 14px;
}
</style> </style>
+284 -4
View File
@@ -1,37 +1,208 @@
<script lang="ts"> <script lang="ts">
import { onMount } from 'svelte' import { onMount } from 'svelte'
import { formatDate } from '../lib/format'
import { import {
backendLogin,
backendLogout,
backendServer,
backendStatus,
canSelfUpdate,
checkForUpdateNow,
errorText, errorText,
getAppVersion,
getSettings, getSettings,
getUpdate,
hasApiKey, hasApiKey,
installUpdate,
listDevices, listDevices,
meterFill, meterFill,
onBackendChanged,
onBackendLoginError,
onUpdateAvailable,
onUpdateProgress,
openBackendKeysPage,
saveSettings, saveSettings,
setApiKey, setApiKey,
testDevices, testDevices,
updateProgressText,
UPDATE_BUSY_HINT,
type BackendServer,
type BackendStatus,
type DeviceInfo, type DeviceInfo,
type DeviceLevels, type DeviceLevels,
type Devices, type Devices,
type Service, type Service,
type Settings, type Settings,
type UpdateCheckResult,
type UpdateInfo,
type UpdateProgress,
} from '../lib/api' } from '../lib/api'
const services: { id: Service; name: string }[] = [ const services: { id: Service; name: string }[] = [
{ id: 'deepscript', name: 'DeepScript' }, { id: 'deepscript', name: 'DeepScript' },
{ id: 'anthropic', name: 'Anthropic (Claude)' },
] ]
let settings = $state<Settings | null>(null) let settings = $state<Settings | null>(null)
let devices = $state<Devices>({ inputs: [], outputs: [] }) let devices = $state<Devices>({ inputs: [], outputs: [] })
let keySaved = $state<Record<Service, boolean>>({ deepscript: false, anthropic: false }) let keySaved = $state<Record<Service, boolean>>({ deepscript: false })
let keyInput = $state<Record<Service, string>>({ deepscript: '', anthropic: '' }) let keyInput = $state<Record<Service, string>>({ deepscript: '' })
let newApp = $state('') let newApp = $state('')
let testing = $state(false) let testing = $state(false)
let testResult = $state<DeviceLevels | null>(null) let testResult = $state<DeviceLevels | null>(null)
let message = $state('') let message = $state('')
let error = $state('') let error = $state('')
onMount(load) let server = $state<BackendServer | null>(null)
let backend = $state<BackendStatus | null>(null)
let backendBusy = $state(false)
let backendError = $state('')
// Status answers can arrive out of order; only the newest is applied.
let statusRequest = 0
let appVersion = $state('')
/** `null` until known: whether this build can install an update itself
* (Windows only); avoids guessing wrong for an instant. */
let selfUpdateCapable = $state<boolean | null>(null)
let checking = $state(false)
let checkResult = $state<UpdateCheckResult | null>(null)
let pendingUpdate = $state<UpdateInfo | null>(null)
let installing = $state(false)
let installProgress = $state<UpdateProgress | null>(null)
let installError = $state('')
/** The version to show as "available", if any. On Windows this comes
* from `pendingUpdate` (kept in sync with the banner by `get_update`/
* `update-available`, so it is current even without a manual check).
* Everywhere else the backend never stores `pendingUpdate` for a found
* update (see `updater::check_outcome`), so a manual check's own result
* is the only source. It is also the fallback whenever `pendingUpdate`
* is not known (e.g. the follow-up `getUpdate()` failed, or
* `canSelfUpdate()` failed): a found update is never hidden. */
let availableVersion = $derived(
(selfUpdateCapable === true ? pendingUpdate?.version : undefined) ??
(checkResult?.status === 'available' ? checkResult.version : undefined),
)
/** Whether the install button/progress can be offered for
* `availableVersion`: only once this build is confirmed able to
* self-update AND `pendingUpdate` (with its `can_install` guard) is
* actually known. */
let canOfferInstall = $derived(selfUpdateCapable === true && pendingUpdate !== null)
onMount(() => {
load()
backendServer()
.then((s) => (server = s))
.catch((err) => (backendError = errorText(err)))
refreshBackend()
getAppVersion()
.then((v) => (appVersion = v))
.catch(() => {})
canSelfUpdate()
.then((v) => (selfUpdateCapable = v))
.catch(() => {})
getUpdate()
.then((u) => (pendingUpdate = u))
.catch(() => {})
const unlisten = [
onBackendChanged(refreshBackend),
onBackendLoginError((msg) => (backendError = msg)),
onUpdateAvailable((info) => (pendingUpdate = info)),
onUpdateProgress((progress) => (installProgress = progress)),
]
return () => unlisten.forEach((u) => u.then((off) => off()))
})
/** "Nach Updates suchen": runs the same check as the background loop,
* immediately. An available update also arrives via `update-available`
* (so the main window's banner shows it too, on Windows), but is applied
* here as well in case that event is missed. That follow-up fetch is
* best-effort: if it fails, the "available" result just found still
* stands — it must never be replaced by that unrelated failure. */
async function checkUpdateNow() {
checking = true
checkResult = null
try {
checkResult = await checkForUpdateNow()
} catch (err) {
checkResult = { status: 'error', message: errorText(err) }
checking = false
return
}
if (checkResult.status === 'available') await refreshPendingUpdate()
checking = false
}
async function refreshPendingUpdate() {
try {
pendingUpdate = await getUpdate()
} catch {
// Optional refresh; the next event or check tries again.
}
}
/** "Installieren & neu starten" for the update found above; reuses the
* install command and guard the main window's banner uses. */
async function installUpdateNow() {
installing = true
installProgress = null
installError = ''
try {
// Returns only on failure: on success the app restarts.
await installUpdate()
} catch (err) {
installError = errorText(err)
refreshPendingUpdate()
} finally {
installing = false
}
}
/** Checks the stored key with the backend. */
async function refreshBackend() {
const request = ++statusRequest
try {
const status = await backendStatus()
if (request === statusRequest) backend = status
} catch (err) {
if (request === statusRequest) backendError = errorText(err)
}
}
async function login() {
backendBusy = true
backendError = ''
try {
await backendLogin()
} catch (err) {
backendError = errorText(err)
} finally {
backendBusy = false
refreshBackend()
}
}
async function logout() {
backendBusy = true
backendError = ''
try {
await backendLogout()
} catch (err) {
backendError = errorText(err)
} finally {
backendBusy = false
refreshBackend()
}
}
async function openKeysPage(event: Event) {
event.preventDefault()
try {
await openBackendKeysPage()
} catch (err) {
backendError = errorText(err)
}
}
async function load() { async function load() {
try { try {
@@ -146,6 +317,46 @@
{/each} {/each}
</section> </section>
<section class="card">
<h2>Backend</h2>
<div class="grid">
<span>Server</span>
<span>{server ? new URL(server.base_url).host : '…'}</span>
<span>Status</span>
<span class="backend-status">
{#if backend === null}
<span class="muted">wird geprüft …</span>
{:else if backend.logged_in}
{backend.username ? `Angemeldet als ${backend.username}` : 'Angemeldet'}{backend.expires_at
? `, gültig bis ${formatDate(backend.expires_at)}`
: ''}
{#if !backend.reachable}
<span class="muted">(Backend nicht erreichbar)</span>
{/if}
{:else}
Nicht angemeldet
{/if}
</span>
</div>
<div class="backend-actions">
<button class="btn small" disabled={backendBusy} onclick={login}>
{backendBusy ? 'Anmeldung läuft …' : backend?.logged_in ? 'Neu anmelden' : 'Anmelden'}
</button>
{#if backend?.logged_in}
<button class="btn small danger" disabled={backendBusy} onclick={logout}>Abmelden</button>
{/if}
</div>
{#if backendError}
<p class="error">{backendError}</p>
{/if}
{#if server}
<p class="muted keys-hint">
Schlüssel auf dem Server verwalten:
<a href={server.keys_url} onclick={openKeysPage}>{server.keys_url}</a>
</p>
{/if}
</section>
<section class="card"> <section class="card">
<h2>Audio</h2> <h2>Audio</h2>
<div class="grid"> <div class="grid">
@@ -263,6 +474,54 @@
</div> </div>
</section> </section>
<section class="card">
<h2>Updates</h2>
<div class="grid">
<span>Version</span>
<span>{appVersion || '…'}</span>
</div>
<div class="update-check">
<button class="btn" disabled={checking} onclick={checkUpdateNow}>
{checking ? 'Suche…' : 'Nach Updates suchen'}
</button>
{#if checkResult?.status === 'none'}
<span class="muted">Keine neue Version verfügbar (aktuell: {appVersion})</span>
{:else if checkResult?.status === 'error'}
<span class="error">{checkResult.message}</span>
{/if}
</div>
{#if availableVersion !== undefined}
<div class="update-available">
<span>Update verfügbar (v{availableVersion})</span>
{#if canOfferInstall}
{#if installing}
<span>{updateProgressText(installProgress)}</span>
{:else}
<button
class="btn primary small"
disabled={!pendingUpdate?.can_install}
onclick={installUpdateNow}
>
Installieren &amp; neu starten
</button>
{#if !pendingUpdate?.can_install}
<span class="muted">{UPDATE_BUSY_HINT}</span>
{/if}
{/if}
{#if installError}
<span class="error">{installError}</span>
{/if}
{:else if selfUpdateCapable !== true}
<!-- Not able to self-update, or unknown (`canSelfUpdate()`
failed): never an install button, just the hint. -->
<span class="muted">
Updates gibt es unter Windows automatisch; unter Linux bitte das .deb neu installieren.
</span>
{/if}
</div>
{/if}
</section>
<div class="footer"> <div class="footer">
<button class="btn primary" onclick={() => run(persist, 'Einstellungen gespeichert ✓')}> <button class="btn primary" onclick={() => run(persist, 'Einstellungen gespeichert ✓')}>
Speichern Speichern
@@ -377,6 +636,27 @@
gap: 8px; gap: 8px;
} }
.backend-actions {
display: flex;
gap: 8px;
margin-top: 12px;
}
.keys-hint {
margin: 10px 0 0;
font-size: 12px;
overflow-wrap: anywhere;
}
.update-check,
.update-available {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px 10px;
margin-top: 12px;
}
.footer { .footer {
display: flex; display: flex;
align-items: center; align-items: center;