Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d3e0add86 | ||
|
|
24cebd7e71 | ||
|
|
9e53d0b390 | ||
|
|
48000f47eb | ||
|
|
79e31d5331 | ||
|
|
20eb53af4b | ||
|
|
6183feaf82 | ||
|
|
f38550f3aa | ||
|
|
ad73e901a0 | ||
|
|
0b735b2e98 | ||
|
|
9ded4f14d4 | ||
|
|
5751684ef8 | ||
|
|
6a14f50e4c | ||
|
|
8c47388eee | ||
|
|
a74cfa5864 | ||
|
|
8d757fd639 | ||
|
|
c57eb9511d | ||
|
|
7a45d20f46 | ||
|
|
802a6f81fd | ||
|
|
0ae6ed304f | ||
|
|
183c135b1d | ||
|
|
299c93f8d6 | ||
|
|
36cefaab5f | ||
|
|
697f13e13a | ||
|
|
35e560020c | ||
|
|
3a16c76257 | ||
|
|
d0ece263a2 | ||
|
|
a0f89454f9 | ||
|
|
083edf32a2 | ||
|
|
687d4bccfe | ||
|
|
fa55dcb7bc | ||
|
|
dad98b4558 | ||
|
|
96eec22971 | ||
|
|
1735f431dd | ||
|
|
782b24a6de | ||
|
|
3358de7888 | ||
|
|
f045424e97 | ||
|
|
58e96a2954 | ||
|
|
54a81e5ba0 | ||
|
|
eff07d2f59 | ||
|
|
572c685396 |
Generated
+63
-1
@@ -445,9 +445,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "call-recorder"
|
||||
version = "0.1.1"
|
||||
version = "0.4.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"chrono",
|
||||
"http-range",
|
||||
"log",
|
||||
"recorder-audio",
|
||||
"recorder-core",
|
||||
@@ -458,9 +460,11 @@ dependencies = [
|
||||
"tauri-plugin-autostart",
|
||||
"tauri-plugin-log",
|
||||
"tauri-plugin-notification",
|
||||
"tauri-plugin-opener",
|
||||
"tauri-plugin-single-instance",
|
||||
"tauri-plugin-updater",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1800,6 +1804,12 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http-range"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2149c4b4b83390c71fab669730347d578ec6bdf759f2160c581ad8b8819733b4"
|
||||
|
||||
[[package]]
|
||||
name = "httparse"
|
||||
version = "1.10.1"
|
||||
@@ -2059,6 +2069,25 @@ version = "2.12.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
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]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
@@ -2981,6 +3010,17 @@ version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
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]]
|
||||
name = "openssl-probe"
|
||||
version = "0.2.2"
|
||||
@@ -4712,6 +4752,28 @@ dependencies = [
|
||||
"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]]
|
||||
name = "tauri-plugin-single-instance"
|
||||
version = "2.5.5"
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
# Gesprächsrekorder
|
||||
|
||||
A Tauri 2 desktop app that records calls (Teams, MicroSIP, browser-based
|
||||
softphones, …), then transcribes and summarizes them.
|
||||
softphones, …) and transcribes them.
|
||||
|
||||
## Workspace layout
|
||||
|
||||
- `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
|
||||
a GUI, a sound device or network access.
|
||||
- `crates/audio` (`recorder-audio`) — audio capture and WAV/FLAC encoding.
|
||||
|
||||
+31
-48
@@ -3,7 +3,7 @@
|
||||
A release consists of:
|
||||
|
||||
- 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,
|
||||
- `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`
|
||||
point to `${RELEASE_BASE_URL}/releases/download/v<version>/<file>`.
|
||||
- `UPDATE_JSON_URLS`: where the app looks for `latest.json`. `build-release.sh`
|
||||
writes them, in this order, into `plugins.updater.endpoints` in
|
||||
`src-tauri/tauri.conf.json`.
|
||||
writes them into `plugins.updater.endpoints` in `src-tauri/tauri.conf.json`.
|
||||
|
||||
Do not edit the endpoints in `tauri.conf.json` by hand. Change `release.env`; the
|
||||
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
|
||||
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.
|
||||
A `404` or a network error on one moves on to the next one:
|
||||
Verified on Gitea 1.27.3: `releases/latest/download/<file>` does **not** redirect
|
||||
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).
|
||||
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
|
||||
```
|
||||
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
|
||||
installed version also asks URL 1, so step 8 is no longer needed.
|
||||
- **Only URL 2 works:** a later version may drop URL 1. Step 8 (committing
|
||||
`latest.json`) stays part of every release.
|
||||
|
||||
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.
|
||||
Versions 0.1.0 and 0.1.1 were built with both URLs compiled in (the endpoints
|
||||
are fixed at build time; installed apps keep asking the URLs they were built
|
||||
with). They still try `releases/latest/download/latest.json` first on every
|
||||
check; that is harmless — it 404s and the app falls through to the
|
||||
`raw/branch/master` URL, which answers normally.
|
||||
|
||||
## 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
|
||||
`ui/package.json` (the build updates `Cargo.lock` too), and writes the endpoints
|
||||
from `release.env` into `tauri.conf.json`,
|
||||
- builds the Windows installer (`scripts/build-windows.sh`), the `.deb` and the
|
||||
`.AppImage`, each with its `.sig`,
|
||||
- builds the Windows installer (`scripts/build-windows.sh`) and the `.deb`, each
|
||||
with its `.sig`,
|
||||
- copies them to `dist-release/0.1.1/` under ASCII names (`Gespraechsrekorder_…`)
|
||||
and writes `latest.json` with `scripts/make-latest-json.sh`.
|
||||
|
||||
@@ -134,7 +115,6 @@ e.g. for the first release `0.1.0`.
|
||||
|------------------------------------------------------|--------------------------------------|
|
||||
| `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.AppImage` (+ `.sig`) | Debian AppImage |
|
||||
| `latest.json` | Update feed |
|
||||
|
||||
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
|
||||
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
|
||||
names (`latest.json` points to them). Upload the installers, packages and `.sig`
|
||||
files first and **`latest.json` last**. As soon as `latest.json` is visible,
|
||||
installed apps may try to download the files it lists.
|
||||
7. Upload the installer, the `.deb` and their `.sig` files from
|
||||
`dist-release/0.1.1/` as release assets, keeping the file names (`latest.json`
|
||||
points to them). `latest.json` itself does not need to be uploaded as a release
|
||||
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
|
||||
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
|
||||
```
|
||||
|
||||
Committing `latest.json` is mandatory for every release — it is the only
|
||||
place the feed lives.
|
||||
|
||||
9. Check the feed:
|
||||
|
||||
```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 .
|
||||
```
|
||||
|
||||
The URL(s) that work must show the new version, and the `url` entries must
|
||||
download.
|
||||
It must show the new version, and the `url` entry must download.
|
||||
|
||||
## 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
|
||||
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.
|
||||
- `latest.json` also lists the AppImage (`linux-x86_64`). The Debian builds do not
|
||||
check for updates yet.
|
||||
- `latest.json` only lists `windows-x86_64`. Debian installs from the `.deb` and
|
||||
does not self-update, so Linux has no entry in the feed.
|
||||
|
||||
@@ -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(""));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
//! Mixes the two 16 kHz mono tracks of a call into one mono track for
|
||||
//! playback.
|
||||
//!
|
||||
//! The tracks are summed at full level and passed through a soft clipper,
|
||||
//! so a passage where only one side speaks keeps its original loudness
|
||||
//! while both sides speaking loudly at once never wraps around or clips
|
||||
//! hard. [`mix_wavs`] streams both files in chunks, so even a long call
|
||||
//! never sits in memory.
|
||||
|
||||
use std::fs::{self, File};
|
||||
use std::io::{self, BufReader, ErrorKind};
|
||||
use std::path::Path;
|
||||
|
||||
use hound::{SampleFormat, WavReader, WavSpec, WavWriter};
|
||||
|
||||
use super::wav::SAMPLE_RATE;
|
||||
|
||||
/// Samples read per track and step in [`mix_wavs`] (about one second).
|
||||
const CHUNK_SAMPLES: usize = 16_384;
|
||||
/// Up to this level (half of full scale) the sum passes unchanged; above,
|
||||
/// the soft clipper compresses it towards full scale.
|
||||
const KNEE: f32 = 0.5;
|
||||
|
||||
/// The format of both tracks and of the mixed file.
|
||||
fn spec() -> WavSpec {
|
||||
WavSpec {
|
||||
channels: 1,
|
||||
sample_rate: SAMPLE_RATE,
|
||||
bits_per_sample: 16,
|
||||
sample_format: SampleFormat::Int,
|
||||
}
|
||||
}
|
||||
|
||||
/// Mixes `a` and `b` sample by sample and appends the result to `out`.
|
||||
/// The output is as long as the longer input; the shorter one counts as
|
||||
/// silence after its end. Never clips hard: see [`soft_clip`].
|
||||
pub fn mix_samples(a: &[i16], b: &[i16], out: &mut Vec<i16>) {
|
||||
let len = a.len().max(b.len());
|
||||
out.reserve(len);
|
||||
for i in 0..len {
|
||||
let sum = to_f32(a.get(i).copied().unwrap_or(0)) + to_f32(b.get(i).copied().unwrap_or(0));
|
||||
out.push(to_i16(soft_clip(sum)));
|
||||
}
|
||||
}
|
||||
|
||||
fn to_f32(sample: i16) -> f32 {
|
||||
sample as f32 / i16::MAX as f32
|
||||
}
|
||||
|
||||
fn to_i16(sample: f32) -> i16 {
|
||||
(sample.clamp(-1.0, 1.0) * i16::MAX as f32).round() as i16
|
||||
}
|
||||
|
||||
/// Linear up to [`KNEE`]; above, `tanh` bends the level smoothly (same
|
||||
/// slope at the knee) towards, but never beyond, full scale.
|
||||
fn soft_clip(x: f32) -> f32 {
|
||||
let level = x.abs();
|
||||
if level <= KNEE {
|
||||
return x;
|
||||
}
|
||||
let room = 1.0 - KNEE;
|
||||
x.signum() * (KNEE + room * ((level - KNEE) / room).tanh())
|
||||
}
|
||||
|
||||
/// One source track; `None` if the file is missing or holds no audio.
|
||||
type Track = Option<hound::WavIntoSamples<BufReader<File>, i16>>;
|
||||
|
||||
/// Whether the WAV at `path` holds audio to play: it is a 16 kHz mono
|
||||
/// 16-bit PCM track whose header counts at least one sample. The one rule
|
||||
/// both [`mix_wavs`] and the detail view's "audio available" go by.
|
||||
pub fn has_audio(path: &Path) -> bool {
|
||||
open_track(path).is_some()
|
||||
}
|
||||
|
||||
/// Opens a track for [`mix_wavs`]; `None` unless it [has audio](has_audio).
|
||||
/// Why an existing file is left out is logged.
|
||||
fn open_track(path: &Path) -> Track {
|
||||
if path.as_os_str().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let reader = match WavReader::open(path) {
|
||||
Ok(reader) => reader,
|
||||
Err(hound::Error::IoError(e)) if e.kind() == ErrorKind::NotFound => return None,
|
||||
Err(e) => {
|
||||
log::warn!("left out {}: {e}", path.display());
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if reader.spec() != spec() {
|
||||
log::warn!("left out {}: not 16 kHz mono 16-bit PCM", path.display());
|
||||
return None;
|
||||
}
|
||||
if reader.len() == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(reader.into_samples())
|
||||
}
|
||||
|
||||
/// Reads up to [`CHUNK_SAMPLES`] samples of `track` into `buf` (cleared
|
||||
/// first).
|
||||
fn read_chunk(track: &mut Track, buf: &mut Vec<i16>) -> io::Result<()> {
|
||||
buf.clear();
|
||||
let Some(samples) = track else {
|
||||
return Ok(());
|
||||
};
|
||||
for sample in samples.take(CHUNK_SAMPLES) {
|
||||
buf.push(sample.map_err(|e| io::Error::new(ErrorKind::InvalidData, e))?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Mixes the WAV tracks at `a` and `b` (16 kHz mono 16-bit PCM, as written
|
||||
/// by [`super::TrackWriter`]) into a new WAV at `dest` and returns its
|
||||
/// length in samples. A track without audio ([`has_audio`]: missing,
|
||||
/// empty or not in that format) is left out; with neither track holding
|
||||
/// audio nothing is written and the error is [`ErrorKind::NotFound`].
|
||||
///
|
||||
/// Writes `dest` with a `.part` suffix first and renames it at the end, so
|
||||
/// `dest` is never a half-written file.
|
||||
pub fn mix_wavs(a: &Path, b: &Path, dest: &Path) -> io::Result<u64> {
|
||||
let mut track_a = open_track(a);
|
||||
let mut track_b = open_track(b);
|
||||
if track_a.is_none() && track_b.is_none() {
|
||||
return Err(io::Error::new(
|
||||
ErrorKind::NotFound,
|
||||
"no audio in either track",
|
||||
));
|
||||
}
|
||||
|
||||
let mut part = dest.as_os_str().to_owned();
|
||||
part.push(".part");
|
||||
let part = Path::new(&part);
|
||||
let result = write_mix(&mut track_a, &mut track_b, part);
|
||||
match result {
|
||||
Ok(samples) => {
|
||||
fs::rename(part, dest)?;
|
||||
Ok(samples)
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = fs::remove_file(part);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_mix(a: &mut Track, b: &mut Track, path: &Path) -> io::Result<u64> {
|
||||
let mut writer = WavWriter::create(path, spec()).map_err(hound_to_io)?;
|
||||
let (mut buf_a, mut buf_b, mut mixed) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let mut written = 0u64;
|
||||
loop {
|
||||
read_chunk(a, &mut buf_a)?;
|
||||
read_chunk(b, &mut buf_b)?;
|
||||
if buf_a.is_empty() && buf_b.is_empty() {
|
||||
break;
|
||||
}
|
||||
mixed.clear();
|
||||
mix_samples(&buf_a, &buf_b, &mut mixed);
|
||||
for &sample in &mixed {
|
||||
writer.write_sample(sample).map_err(hound_to_io)?;
|
||||
}
|
||||
written += mixed.len() as u64;
|
||||
}
|
||||
writer.finalize().map_err(hound_to_io)?;
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
fn hound_to_io(e: hound::Error) -> io::Error {
|
||||
match e {
|
||||
hound::Error::IoError(e) => e,
|
||||
other => io::Error::other(other),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::audio::TrackWriter;
|
||||
|
||||
fn mix(a: &[i16], b: &[i16]) -> Vec<i16> {
|
||||
let mut out = Vec::new();
|
||||
mix_samples(a, b, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quiet_samples_of_equal_length_are_summed() {
|
||||
assert_eq!(mix(&[100, -200, 0], &[50, 300, -7]), vec![150, 100, -7]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_longer_track_continues_alone() {
|
||||
assert_eq!(mix(&[1, 2], &[10, 20, 30, 40]), vec![11, 22, 30, 40]);
|
||||
assert_eq!(mix(&[10, 20, 30], &[1]), vec![11, 20, 30]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_track_leaves_the_other_unchanged_up_to_the_knee() {
|
||||
let half = (KNEE * i16::MAX as f32) as i16;
|
||||
let track = [0, 1234, -1234, half, -half, i16::MIN + 1];
|
||||
let mut expected = track.to_vec();
|
||||
// Beyond the knee even a single track is compressed (but stays
|
||||
// loud and keeps its sign).
|
||||
let last = mix(&[], &track)[5];
|
||||
expected[5] = last;
|
||||
assert!(last < -28_000, "{last}");
|
||||
assert_eq!(mix(&[], &track), expected);
|
||||
assert_eq!(mix(&track, &[]), expected);
|
||||
assert_eq!(mix(&[], &[]), Vec::<i16>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_scale_on_both_sides_stays_within_full_scale() {
|
||||
let out = mix(
|
||||
&[i16::MAX, i16::MIN, i16::MAX],
|
||||
&[i16::MAX, i16::MIN, i16::MIN],
|
||||
);
|
||||
// Loud, with the right sign, and softly short of full scale.
|
||||
assert!(out[0] > 30_000 && out[0] < i16::MAX, "{}", out[0]);
|
||||
assert!(out[1] < -30_000 && out[1] > -i16::MAX, "{}", out[1]);
|
||||
// Opposite full-scale samples cancel instead of wrapping around.
|
||||
assert!(out[2].abs() <= 1, "{}", out[2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_soft_clip_is_monotonic_and_bounded() {
|
||||
let mut last = -1.0f32;
|
||||
for step in -400..=400 {
|
||||
let x = step as f32 / 200.0; // -2.0 ..= 2.0
|
||||
let y = soft_clip(x);
|
||||
assert!(y >= last, "not monotonic at {x}");
|
||||
assert!(y.abs() < 1.0, "{x} -> {y}");
|
||||
last = y;
|
||||
}
|
||||
}
|
||||
|
||||
fn write_track(path: &Path, samples: &[f32]) {
|
||||
let mut writer = TrackWriter::create(path).unwrap();
|
||||
writer.write(samples).unwrap();
|
||||
writer.finalize().unwrap();
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> Vec<i16> {
|
||||
WavReader::open(path)
|
||||
.unwrap()
|
||||
.into_samples::<i16>()
|
||||
.map(Result::unwrap)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_files_are_mixed_across_several_chunks() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (a, b, dest) = (
|
||||
dir.path().join("a.wav"),
|
||||
dir.path().join("b.wav"),
|
||||
dir.path().join("m.wav"),
|
||||
);
|
||||
let long = CHUNK_SAMPLES * 2 + 100;
|
||||
write_track(&a, &vec![0.1; long]);
|
||||
write_track(&b, &vec![0.2; CHUNK_SAMPLES + 7]);
|
||||
|
||||
assert_eq!(mix_wavs(&a, &b, &dest).unwrap(), long as u64);
|
||||
|
||||
let mixed = read(&dest);
|
||||
assert_eq!(mixed.len(), long);
|
||||
let both = to_i16(0.1) + to_i16(0.2);
|
||||
assert!((mixed[0] - both).abs() <= 1);
|
||||
assert!((mixed[CHUNK_SAMPLES + 6] - both).abs() <= 1);
|
||||
assert_eq!(mixed[CHUNK_SAMPLES + 7], to_i16(0.1));
|
||||
assert_eq!(mixed[long - 1], to_i16(0.1));
|
||||
assert!(!dir.path().join("m.wav.part").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_or_empty_file_is_left_out() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (a, empty, dest) = (
|
||||
dir.path().join("a.wav"),
|
||||
dir.path().join("e.wav"),
|
||||
dir.path().join("m.wav"),
|
||||
);
|
||||
write_track(&a, &[0.25; 10]);
|
||||
write_track(&empty, &[]);
|
||||
|
||||
assert_eq!(
|
||||
mix_wavs(&dir.path().join("gone.wav"), &a, &dest).unwrap(),
|
||||
10
|
||||
);
|
||||
assert_eq!(read(&dest), vec![to_i16(0.25); 10]);
|
||||
assert_eq!(mix_wavs(&a, &empty, &dest).unwrap(), 10);
|
||||
assert_eq!(read(&dest), vec![to_i16(0.25); 10]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_audio_in_either_file_nothing_is_written() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (empty, dest) = (dir.path().join("e.wav"), dir.path().join("m.wav"));
|
||||
write_track(&empty, &[]);
|
||||
|
||||
let err = mix_wavs(&empty, &dir.path().join("gone.wav"), &dest).unwrap_err();
|
||||
assert_eq!(err.kind(), ErrorKind::NotFound);
|
||||
assert!(!dest.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_is_not_a_track_is_left_out() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (a, junk, other, dest) = (
|
||||
dir.path().join("a.wav"),
|
||||
dir.path().join("j.wav"),
|
||||
dir.path().join("o.wav"),
|
||||
dir.path().join("m.wav"),
|
||||
);
|
||||
write_track(&a, &[0.25; 10]);
|
||||
fs::write(&junk, b"not a wav file at all").unwrap();
|
||||
let stereo = WavSpec {
|
||||
channels: 2,
|
||||
..spec()
|
||||
};
|
||||
let mut writer = WavWriter::create(&other, stereo).unwrap();
|
||||
writer.write_sample(1i16).unwrap();
|
||||
writer.write_sample(1i16).unwrap();
|
||||
writer.finalize().unwrap();
|
||||
|
||||
assert_eq!(mix_wavs(&a, &junk, &dest).unwrap(), 10);
|
||||
assert_eq!(mix_wavs(&other, &a, &dest).unwrap(), 10);
|
||||
let err = mix_wavs(&junk, &other, &dest).unwrap_err();
|
||||
assert_eq!(err.kind(), ErrorKind::NotFound);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_track_has_audio_only_with_samples_in_the_track_format() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = |name: &str| dir.path().join(name);
|
||||
assert!(!has_audio(&path("gone.wav")), "missing");
|
||||
assert!(!has_audio(Path::new("")), "no path");
|
||||
write_track(&path("empty.wav"), &[]);
|
||||
assert!(!has_audio(&path("empty.wav")), "header only");
|
||||
// Larger than a header, but its header says it holds nothing.
|
||||
let mut bytes = fs::read(path("empty.wav")).unwrap();
|
||||
bytes.extend([0u8; 100]);
|
||||
fs::write(path("unrepaired.wav"), bytes).unwrap();
|
||||
assert!(
|
||||
!has_audio(&path("unrepaired.wav")),
|
||||
"data not in the header"
|
||||
);
|
||||
fs::write(path("junk.wav"), vec![7u8; 100]).unwrap();
|
||||
assert!(!has_audio(&path("junk.wav")), "not a wav");
|
||||
write_track(&path("one.wav"), &[0.1]);
|
||||
assert!(has_audio(&path("one.wav")));
|
||||
}
|
||||
}
|
||||
@@ -11,10 +11,12 @@ mod conditioner;
|
||||
mod flac;
|
||||
mod gap;
|
||||
mod level;
|
||||
mod mix;
|
||||
mod wav;
|
||||
|
||||
pub use conditioner::Conditioner;
|
||||
pub use flac::encode_flac;
|
||||
pub use gap::GapFiller;
|
||||
pub use level::rms_level;
|
||||
pub use wav::{repair_wav, TrackWriter};
|
||||
pub use mix::{has_audio, mix_samples, mix_wavs};
|
||||
pub use wav::{repair_wav, TrackWriter, SAMPLE_RATE};
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
+471
-15
@@ -6,6 +6,7 @@ use std::collections::BTreeMap;
|
||||
use chrono::{DateTime, Local};
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::corrections::correct_segment_text;
|
||||
use crate::merge;
|
||||
use crate::model::{Call, CallId, CallStatus, Segment, Speaker};
|
||||
|
||||
@@ -18,25 +19,92 @@ pub struct CallListItem {
|
||||
/// Whole seconds from start to end; 0 while recording.
|
||||
pub duration_secs: i64,
|
||||
pub status: CallStatus,
|
||||
/// What the status pill shows and whether the row needs the user's
|
||||
/// attention — see [`ListState`]. Computed from `status` and
|
||||
/// [`uploaded_here`] so the UI does not re-implement the rule.
|
||||
pub list_state: ListState,
|
||||
/// Whether this row needs the user to act on it (the dot in
|
||||
/// `CallList.svelte` and the sidebar header's "N offen" count). Equal
|
||||
/// to `list_state.needs_action()`, kept as its own field so the UI
|
||||
/// does not need to know `ListState`'s variants to filter by it.
|
||||
pub needs_action: bool,
|
||||
pub interrupted: bool,
|
||||
/// The name the user gave the call, if any.
|
||||
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 {
|
||||
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);
|
||||
let list_state = ListState::of(call.status, uploaded);
|
||||
Self {
|
||||
id: call.id,
|
||||
app: call.app.clone(),
|
||||
started_at: call.started_at,
|
||||
duration_secs: duration_secs(call),
|
||||
status: call.status,
|
||||
list_state,
|
||||
needs_action: list_state.needs_action(),
|
||||
interrupted: call.interrupted,
|
||||
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 },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the call list row (and the detail header's pill) shows about a
|
||||
/// call's status. Mirrors [`CallStatus`] one-to-one, except that `Done`
|
||||
/// splits in two: a call is only ever shown as done ("fertig") once its
|
||||
/// transcript has actually reached *this build's* backend ([`uploaded_here`]);
|
||||
/// otherwise — never uploaded, or uploaded to a different backend — it is
|
||||
/// `ReadyToUpload` ("bereit zum Hochladen"), because from this build's
|
||||
/// point of view the CRM has not seen it yet.
|
||||
#[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ListState {
|
||||
Recording,
|
||||
AwaitingDecision,
|
||||
Processing,
|
||||
Failed,
|
||||
Done,
|
||||
ReadyToUpload,
|
||||
}
|
||||
|
||||
impl ListState {
|
||||
fn of(status: CallStatus, uploaded_here: bool) -> Self {
|
||||
match status {
|
||||
CallStatus::Recording => ListState::Recording,
|
||||
CallStatus::AwaitingDecision => ListState::AwaitingDecision,
|
||||
CallStatus::Processing => ListState::Processing,
|
||||
CallStatus::Failed => ListState::Failed,
|
||||
CallStatus::Done if uploaded_here => ListState::Done,
|
||||
CallStatus::Done => ListState::ReadyToUpload,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a row in this state needs the user to act on it: not yet
|
||||
/// transcribed, or transcribed but not uploaded here. Excludes
|
||||
/// `Failed` (already shown in red) and the transient
|
||||
/// `Recording`/`Processing` states.
|
||||
pub fn needs_action(self) -> bool {
|
||||
matches!(self, ListState::AwaitingDecision | ListState::ReadyToUpload)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whole seconds from `started_at` to `ended_at`; 0 while the call has not
|
||||
/// ended (and never negative).
|
||||
pub fn duration_secs(call: &Call) -> i64 {
|
||||
@@ -44,14 +112,25 @@ pub fn duration_secs(call: &Call) -> i64 {
|
||||
.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
|
||||
/// 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)]
|
||||
pub struct CallHeader {
|
||||
#[serde(flatten)]
|
||||
pub item: CallListItem,
|
||||
pub error: Option<String>,
|
||||
pub account_id: Option<String>,
|
||||
pub transcribed_at: Option<DateTime<Local>>,
|
||||
}
|
||||
|
||||
/// A transcript line with the speaker's display label.
|
||||
@@ -90,17 +169,49 @@ pub struct CallDetail {
|
||||
pub speaker_names: BTreeMap<String, String>,
|
||||
/// The call's speaker merges, by source speaker number.
|
||||
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,
|
||||
/// Whether the call's audio is still on disk to be played
|
||||
/// ([`crate::playback::audio_available`]). Set by the app; `false` from
|
||||
/// [`CallDetail::of`], which does not look at the files.
|
||||
pub audio_available: bool,
|
||||
/// Whether retention deleted the call's audio (as opposed to the files
|
||||
/// being missing for another reason).
|
||||
pub audio_deleted: bool,
|
||||
/// The call's language, or the last-used one for a call without its
|
||||
/// own yet ([`preselect_language`]): what the language picker next to
|
||||
/// "Transkribieren"/"Erneut versuchen" starts on.
|
||||
pub language: String,
|
||||
}
|
||||
|
||||
/// The language the picker starts on for `call`: the one it was
|
||||
/// transcribed in, else `last_used` (the settings' `language`).
|
||||
pub fn preselect_language(call: &Call, last_used: &str) -> String {
|
||||
call.language
|
||||
.clone()
|
||||
.unwrap_or_else(|| last_used.to_string())
|
||||
}
|
||||
|
||||
impl CallDetail {
|
||||
/// `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`]); `last_used_language` is the settings'
|
||||
/// `language` (see [`preselect_language`]). The call's language picks
|
||||
/// the [`correct_segment_text`] applied to each segment's text —
|
||||
/// non-destructively, so it also corrects transcripts from before the
|
||||
/// correction existed.
|
||||
pub fn of(
|
||||
call: &Call,
|
||||
segments: &[Segment],
|
||||
speaker_names: BTreeMap<String, String>,
|
||||
merges: &BTreeMap<String, String>,
|
||||
backend_url: &str,
|
||||
last_used_language: &str,
|
||||
) -> Self {
|
||||
// A call with segments always has its language (see the store's
|
||||
// schema v5); the fallback only covers a call not transcribed yet.
|
||||
let language = preselect_language(call, last_used_language);
|
||||
let segments = merge::apply_merges(segments, merges)
|
||||
.iter()
|
||||
.map(|segment| SegmentView {
|
||||
@@ -108,22 +219,90 @@ impl CallDetail {
|
||||
label: merge::label(&segment.speaker, &speaker_names),
|
||||
start: segment.start,
|
||||
end: segment.end,
|
||||
text: segment.text.clone(),
|
||||
text: correct_segment_text(&segment.text, &language),
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
call: CallHeader {
|
||||
item: CallListItem::of(call),
|
||||
item: CallListItem::of(call, backend_url),
|
||||
error: call.error.clone(),
|
||||
account_id: call.account_id.clone(),
|
||||
transcribed_at: call.transcribed_at,
|
||||
},
|
||||
segments,
|
||||
merges: merge_views(merges, &speaker_names),
|
||||
uploading: false,
|
||||
audio_available: false,
|
||||
audio_deleted: call.audio_deleted,
|
||||
speaker_names,
|
||||
language,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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(
|
||||
merges: &BTreeMap<String, String>,
|
||||
speaker_names: &BTreeMap<String, String>,
|
||||
@@ -159,6 +338,11 @@ mod tests {
|
||||
use super::*;
|
||||
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> {
|
||||
Local.with_ymd_and_hms(2026, 11, 5, h, m, s).unwrap()
|
||||
}
|
||||
@@ -176,8 +360,11 @@ mod tests {
|
||||
out_path: PathBuf::from("7-out.wav"),
|
||||
transcribed_at: None,
|
||||
audio_deleted: false,
|
||||
account_id: None,
|
||||
title: None,
|
||||
crm_transcript_id: None,
|
||||
crm_base_url: None,
|
||||
language: None,
|
||||
uploaded_at: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,20 +394,125 @@ mod tests {
|
||||
c.status = CallStatus::AwaitingDecision;
|
||||
c.interrupted = true;
|
||||
assert_eq!(
|
||||
CallListItem::of(&c),
|
||||
CallListItem::of(&c, BACKEND),
|
||||
CallListItem {
|
||||
id: 7,
|
||||
app: "Microsoft Teams".into(),
|
||||
started_at: at(10, 14, 0),
|
||||
duration_secs: 60,
|
||||
status: CallStatus::AwaitingDecision,
|
||||
list_state: ListState::AwaitingDecision,
|
||||
needs_action: true,
|
||||
interrupted: true,
|
||||
title: None,
|
||||
crm_transcript_id: None,
|
||||
uploaded_at: None,
|
||||
}
|
||||
);
|
||||
|
||||
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 done_is_fertig_only_once_uploaded_to_this_backend() {
|
||||
let mut c = call(Some(at(10, 15, 0)));
|
||||
c.status = CallStatus::Done;
|
||||
|
||||
// Never uploaded.
|
||||
assert_eq!(
|
||||
CallListItem::of(&c, BACKEND).list_state,
|
||||
ListState::ReadyToUpload
|
||||
);
|
||||
|
||||
// Uploaded, but to a different backend.
|
||||
c.crm_transcript_id = Some("4711".into());
|
||||
c.crm_base_url = Some(OTHER_BACKEND.into());
|
||||
assert_eq!(
|
||||
CallListItem::of(&c, BACKEND).list_state,
|
||||
ListState::ReadyToUpload
|
||||
);
|
||||
|
||||
// Uploaded to this build's backend.
|
||||
c.crm_base_url = Some(BACKEND.into());
|
||||
assert_eq!(CallListItem::of(&c, BACKEND).list_state, ListState::Done);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn needs_action_marks_awaiting_and_ready_to_upload_only() {
|
||||
let mut c = call(Some(at(10, 15, 0)));
|
||||
|
||||
c.status = CallStatus::AwaitingDecision;
|
||||
assert!(CallListItem::of(&c, BACKEND).needs_action, "awaiting");
|
||||
|
||||
c.status = CallStatus::Done;
|
||||
assert!(
|
||||
CallListItem::of(&c, BACKEND).needs_action,
|
||||
"done, never uploaded"
|
||||
);
|
||||
|
||||
for status in [
|
||||
CallStatus::Processing,
|
||||
CallStatus::Failed,
|
||||
CallStatus::Recording,
|
||||
] {
|
||||
c.status = status;
|
||||
assert!(
|
||||
!CallListItem::of(&c, BACKEND).needs_action,
|
||||
"{status:?} must not show the dot"
|
||||
);
|
||||
}
|
||||
|
||||
c.status = CallStatus::Done;
|
||||
c.crm_transcript_id = Some("4711".into());
|
||||
c.crm_base_url = Some(BACKEND.into());
|
||||
assert!(
|
||||
!CallListItem::of(&c, BACKEND).needs_action,
|
||||
"done and uploaded here"
|
||||
);
|
||||
}
|
||||
|
||||
#[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]
|
||||
@@ -239,6 +531,8 @@ mod tests {
|
||||
&segments,
|
||||
names.clone(),
|
||||
&BTreeMap::new(),
|
||||
BACKEND,
|
||||
"de",
|
||||
);
|
||||
|
||||
let lines: Vec<_> = detail
|
||||
@@ -283,7 +577,14 @@ mod tests {
|
||||
("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,
|
||||
"de",
|
||||
);
|
||||
|
||||
let lines: Vec<_> = detail
|
||||
.segments
|
||||
@@ -330,12 +631,19 @@ mod tests {
|
||||
let mut c = call(Some(at(10, 15, 0)));
|
||||
c.status = CallStatus::Failed;
|
||||
c.error = Some("Netzwerkfehler".into());
|
||||
c.account_id = Some("mock-2".into());
|
||||
c.title = Some("Reklamation".into());
|
||||
c.transcribed_at = Some(at(10, 20, 0));
|
||||
let merges = keys(&[("remote:2", "remote:1")]);
|
||||
|
||||
let value =
|
||||
serde_json::to_value(CallDetail::of(&c, &[], BTreeMap::new(), &merges)).unwrap();
|
||||
let value = serde_json::to_value(CallDetail::of(
|
||||
&c,
|
||||
&[],
|
||||
BTreeMap::new(),
|
||||
&merges,
|
||||
BACKEND,
|
||||
"de",
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
value,
|
||||
@@ -346,10 +654,14 @@ mod tests {
|
||||
"started_at": serde_json::to_value(at(10, 14, 0)).unwrap(),
|
||||
"duration_secs": 60,
|
||||
"status": "failed",
|
||||
"list_state": "failed",
|
||||
"needs_action": false,
|
||||
"interrupted": false,
|
||||
"title": "Reklamation",
|
||||
"crm_transcript_id": null,
|
||||
"uploaded_at": null,
|
||||
"error": "Netzwerkfehler",
|
||||
"account_id": "mock-2",
|
||||
"transcribed_at": serde_json::to_value(at(10, 20, 0)).unwrap(),
|
||||
},
|
||||
"segments": [],
|
||||
"speaker_names": {},
|
||||
@@ -359,7 +671,151 @@ mod tests {
|
||||
"into_key": "remote:1",
|
||||
"into_label": "Sprecher 1",
|
||||
}],
|
||||
"uploading": false,
|
||||
"audio_available": false,
|
||||
"audio_deleted": false,
|
||||
"language": "de",
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/// With German as the last-used language (what matters for a call
|
||||
/// without its own, see `CallDetail::of`).
|
||||
fn detail_with(c: &Call, segments: &[Segment], names: &[(&str, &str)]) -> CallDetail {
|
||||
detail_last_used(c, segments, names, "de")
|
||||
}
|
||||
|
||||
fn detail_last_used(
|
||||
c: &Call,
|
||||
segments: &[Segment],
|
||||
names: &[(&str, &str)],
|
||||
last_used_language: &str,
|
||||
) -> CallDetail {
|
||||
CallDetail::of(
|
||||
c,
|
||||
segments,
|
||||
keys(names),
|
||||
&keys(&[("remote:2", "remote:1")]),
|
||||
BACKEND,
|
||||
last_used_language,
|
||||
)
|
||||
}
|
||||
|
||||
#[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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_segment_mistranscribed_as_english_is_corrected_in_the_detail_view() {
|
||||
let c = call(Some(at(10, 15, 0)));
|
||||
let segments = [
|
||||
segment(Speaker::Me, 0.0, "Cheers!"),
|
||||
segment(Speaker::Remote(3), 3.0, "Perfect."),
|
||||
segment(Speaker::Remote(1), 6.0, "Cheers, see you later."),
|
||||
];
|
||||
|
||||
let detail = detail_with(&c, &segments, &[]);
|
||||
|
||||
let texts: Vec<_> = detail.segments.iter().map(|s| s.text.as_str()).collect();
|
||||
assert_eq!(texts, ["Tschüss!", "Perfekt.", "Cheers, see you later."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrections_are_not_applied_outside_german_calls() {
|
||||
let mut c = call(Some(at(10, 15, 0)));
|
||||
c.language = Some("en".into());
|
||||
let segments = [segment(Speaker::Me, 0.0, "Cheers!")];
|
||||
|
||||
// German was used last, but this call is English.
|
||||
let detail = detail_last_used(&c, &segments, &[], "de");
|
||||
|
||||
assert_eq!(detail.segments[0].text, "Cheers!");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrections_follow_the_calls_language_not_the_last_used_one() {
|
||||
let mut c = call(Some(at(10, 15, 0)));
|
||||
c.language = Some("de".into());
|
||||
let segments = [segment(Speaker::Me, 0.0, "Cheers!")];
|
||||
|
||||
let detail = detail_last_used(&c, &segments, &[], "en");
|
||||
|
||||
assert_eq!(detail.segments[0].text, "Tschüss!");
|
||||
assert_eq!(detail.language, "de");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_preselected_language_is_the_calls_own_else_the_last_used() {
|
||||
let mut c = call(None);
|
||||
assert_eq!(preselect_language(&c, "fr"), "fr");
|
||||
|
||||
c.language = Some("it".into());
|
||||
assert_eq!(preselect_language(&c, "fr"), "it");
|
||||
assert_eq!(detail_last_used(&c, &[], &[], "fr").language, "it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_upload_text_uses_the_corrected_segment_text() {
|
||||
let c = call(Some(at(10, 46, 0)));
|
||||
let segments = [segment(Speaker::Me, 0.0, "Cheers!")];
|
||||
|
||||
let text = detail_with(&c, &segments, &[]).upload_text().unwrap();
|
||||
|
||||
assert!(text.ends_with("Ich: Tschüss!"), "upload text was: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
//! A short, hard-coded list of German short utterances that the
|
||||
//! transcription service sometimes mistranscribes as English when they
|
||||
//! stand alone in an otherwise German call ("Tschüss" → "Cheers!",
|
||||
//! "Perfekt" → "Perfect."). Applied non-destructively wherever a segment's
|
||||
//! text is shown or uploaded (see [`crate::call_view::CallDetail::of`]),
|
||||
//! never to the stored segments themselves — fixing the list later fixes
|
||||
//! already-transcribed calls too.
|
||||
//!
|
||||
//! Not user-editable (yet): a fixed code constant, checked only against a
|
||||
//! segment's *entire* text, so it never touches a short mistranscription
|
||||
//! embedded in a longer sentence.
|
||||
|
||||
/// (mistranscribed English word, correct German word) pairs.
|
||||
const CORRECTIONS: &[(&str, &str)] = &[("Cheers", "Tschüss"), ("Perfect", "Perfekt")];
|
||||
|
||||
/// Returns `text`'s correction if the call's `language` is German (`"de"`)
|
||||
/// and `text` — ignoring surrounding whitespace and one run of trailing
|
||||
/// `. ! ? ,` — case-insensitively equals one of [`CORRECTIONS`]'s source
|
||||
/// words in full; the original trailing punctuation, if any, is kept (e.g.
|
||||
/// "Cheers!" → "Tschüss!"). Otherwise `text` is returned unchanged,
|
||||
/// including when it merely *contains* a source word ("Cheers, see you").
|
||||
pub fn correct_segment_text(text: &str, language: &str) -> String {
|
||||
if language != "de" {
|
||||
return text.to_string();
|
||||
}
|
||||
let trimmed = text.trim();
|
||||
let core = trimmed.trim_end_matches(['.', '!', '?', ',']);
|
||||
let punctuation = &trimmed[core.len()..];
|
||||
match CORRECTIONS
|
||||
.iter()
|
||||
.find(|(wrong, _)| core.eq_ignore_ascii_case(wrong))
|
||||
{
|
||||
Some((_, right)) => format!("{right}{punctuation}"),
|
||||
None => text.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_whole_mistranscribed_utterance_is_corrected_case_insensitively() {
|
||||
assert_eq!(correct_segment_text("Cheers!", "de"), "Tschüss!");
|
||||
assert_eq!(correct_segment_text("cheers", "de"), "Tschüss");
|
||||
assert_eq!(correct_segment_text("CHEERS!", "de"), "Tschüss!");
|
||||
assert_eq!(correct_segment_text("Perfect.", "de"), "Perfekt.");
|
||||
assert_eq!(correct_segment_text("perfect?", "de"), "Perfekt?");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn surrounding_whitespace_is_ignored_for_matching() {
|
||||
assert_eq!(correct_segment_text(" Cheers! ", "de"), "Tschüss!");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mistranscription_inside_a_longer_sentence_is_untouched() {
|
||||
assert_eq!(
|
||||
correct_segment_text("Cheers, see you", "de"),
|
||||
"Cheers, see you"
|
||||
);
|
||||
assert_eq!(
|
||||
correct_segment_text("That was perfect.", "de"),
|
||||
"That was perfect."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn not_applied_outside_german_calls() {
|
||||
assert_eq!(correct_segment_text("Cheers!", "en"), "Cheers!");
|
||||
assert_eq!(correct_segment_text("Cheers!", "auto"), "Cheers!");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_without_a_match_is_returned_unchanged() {
|
||||
assert_eq!(
|
||||
correct_segment_text("Hallo zusammen.", "de"),
|
||||
"Hallo zusammen."
|
||||
);
|
||||
}
|
||||
}
|
||||
+32
-14
@@ -1,7 +1,6 @@
|
||||
//! The HTTP transport seam: every outgoing request the DeepScript and Claude
|
||||
//! clients (Tasks 12/13) make goes through [`HttpTransport`], so unit tests
|
||||
//! can swap in [`crate::testing::FakeTransport`] and run with the network
|
||||
//! unplugged. [`ReqwestTransport`] is the real implementation, exercised only
|
||||
//! The HTTP transport seam: every outgoing request the API clients make goes
|
||||
//! through [`HttpTransport`], so unit tests can swap in
|
||||
//! [`crate::testing::FakeTransport`] and run with the network unplugged. [`ReqwestTransport`] is the real implementation, exercised only
|
||||
//! by the live integration suite (`crates/core/tests/live_api.rs`).
|
||||
|
||||
use std::path::PathBuf;
|
||||
@@ -51,6 +50,9 @@ pub struct HttpRequest {
|
||||
pub url: String,
|
||||
pub headers: Vec<(String, String)>,
|
||||
pub body: HttpBody,
|
||||
/// `false` returns a redirect (3xx) as the response instead of
|
||||
/// following it.
|
||||
pub follow_redirects: bool,
|
||||
}
|
||||
|
||||
impl HttpRequest {
|
||||
@@ -99,22 +101,30 @@ pub trait HttpTransport: Send + Sync {
|
||||
async fn send(&self, req: HttpRequest) -> Result<HttpResponse, TransportError>;
|
||||
}
|
||||
|
||||
/// Live `HttpTransport` backed by `reqwest` (rustls). Shares one
|
||||
/// `reqwest::Client` (connection pooling) with a 10 minute request timeout
|
||||
/// and a 30 second connect timeout, matching the Claude/DeepScript clients'
|
||||
/// worst-case wait.
|
||||
/// Live `HttpTransport` backed by `reqwest` (rustls). Shares its
|
||||
/// `reqwest::Client`s (connection pooling) with a 10 minute request timeout
|
||||
/// and a 30 second connect timeout, matching the DeepScript client's
|
||||
/// 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 {
|
||||
client: reqwest::Client,
|
||||
no_redirect_client: reqwest::Client,
|
||||
}
|
||||
|
||||
impl ReqwestTransport {
|
||||
pub fn new() -> Self {
|
||||
let client = reqwest::Client::builder()
|
||||
let build = |redirects| {
|
||||
reqwest::Client::builder()
|
||||
.timeout(Duration::from_secs(10 * 60))
|
||||
.connect_timeout(Duration::from_secs(30))
|
||||
.redirect(redirects)
|
||||
.build()
|
||||
.expect("failed to build reqwest client");
|
||||
ReqwestTransport { client }
|
||||
.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]
|
||||
impl HttpTransport for ReqwestTransport {
|
||||
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 {
|
||||
Method::Get => self.client.get(&req.url),
|
||||
Method::Post => self.client.post(&req.url),
|
||||
Method::Delete => self.client.delete(&req.url),
|
||||
Method::Get => client.get(&req.url),
|
||||
Method::Post => client.post(&req.url),
|
||||
Method::Delete => client.delete(&req.url),
|
||||
};
|
||||
for (name, value) in &req.headers {
|
||||
builder = builder.header(name, value);
|
||||
@@ -203,6 +218,7 @@ mod tests {
|
||||
url: url.to_string(),
|
||||
headers: vec![],
|
||||
body: HttpBody::Empty,
|
||||
follow_redirects: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -225,6 +241,7 @@ mod tests {
|
||||
url: "https://api.example.com/b?x=1".to_string(),
|
||||
headers: vec![("x-test".to_string(), "1".to_string())],
|
||||
body: HttpBody::Empty,
|
||||
follow_redirects: true,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -265,6 +282,7 @@ mod tests {
|
||||
url: "https://api.example.com".to_string(),
|
||||
headers: vec![("Authorization".to_string(), "Bearer xyz".to_string())],
|
||||
body: HttpBody::Empty,
|
||||
follow_redirects: true,
|
||||
};
|
||||
assert_eq!(req.header("authorization"), Some("Bearer xyz"));
|
||||
assert_eq!(req.header("missing"), None);
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
//! Core domain logic for the Gesprächsrekorder call recorder.
|
||||
//!
|
||||
//! This crate will grow to hold call detection, recording orchestration,
|
||||
//! transcription and summarization logic, kept independent of the Tauri
|
||||
//! application shell so it can be unit-tested without a GUI or network.
|
||||
//! Call detection, recording orchestration and transcription, kept
|
||||
//! independent of the Tauri application shell so it can be unit-tested
|
||||
//! without a GUI or network.
|
||||
|
||||
pub mod accounts;
|
||||
pub mod audio;
|
||||
pub mod backend;
|
||||
pub mod call_view;
|
||||
pub mod capture;
|
||||
pub mod corrections;
|
||||
pub mod detect;
|
||||
pub mod http;
|
||||
pub mod merge;
|
||||
pub mod model;
|
||||
pub mod pipeline;
|
||||
pub mod playback;
|
||||
pub mod recorder;
|
||||
pub mod retention;
|
||||
pub mod secrets;
|
||||
|
||||
+13
-37
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use chrono::{DateTime, Local, NaiveDate};
|
||||
use chrono::{DateTime, Local};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Primary key of a `calls` row (SQLite `rowid`).
|
||||
@@ -37,9 +37,20 @@ pub struct Call {
|
||||
pub out_path: PathBuf,
|
||||
pub transcribed_at: Option<DateTime<Local>>,
|
||||
pub audio_deleted: bool,
|
||||
pub account_id: Option<String>,
|
||||
/// The name the user gave the call, if any.
|
||||
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>>,
|
||||
/// The language (ISO 639-1 code) the call is transcribed in, chosen
|
||||
/// when its transcription was started; `None` before that.
|
||||
pub language: Option<String>,
|
||||
}
|
||||
|
||||
/// A single transcribed word with its timing and speaker attribution.
|
||||
@@ -97,38 +108,3 @@ pub struct Segment {
|
||||
pub end: f64,
|
||||
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,
|
||||
}
|
||||
|
||||
@@ -22,9 +22,12 @@ use crate::transcribe::{TranscribeError, TranscribeOptions, Transcriber};
|
||||
/// Settings a pipeline run uses.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct PipelineOptions {
|
||||
/// ISO 639-1 code, or `"auto"`.
|
||||
/// The call's language, one of [`crate::settings::CALL_LANGUAGES`].
|
||||
pub language: String,
|
||||
pub deepscript_model: String,
|
||||
/// Custom words/names submitted with both tracks (DeepScript's
|
||||
/// `vocabulary` field).
|
||||
pub vocabulary: Vec<String>,
|
||||
}
|
||||
|
||||
/// Everything a pipeline run can fail with.
|
||||
@@ -108,7 +111,6 @@ async fn run(
|
||||
// Jobs whose delete failed in an earlier run.
|
||||
delete_remote_jobs(store, tr, id).await;
|
||||
}
|
||||
// SUMMARY SEAM (Task 14b): summarize here.
|
||||
store.set_status(id, CallStatus::Done, None)?;
|
||||
log::info!("call {id}: done");
|
||||
Ok(())
|
||||
@@ -141,6 +143,7 @@ async fn transcribe(
|
||||
language: opts.language.clone(),
|
||||
model: opts.deepscript_model.clone(),
|
||||
single_speaker,
|
||||
vocabulary: opts.vocabulary.clone(),
|
||||
};
|
||||
let (mic_opts, out_opts) = (track_opts(true), track_opts(false));
|
||||
let (mic_job, out_job) = tokio::join!(
|
||||
@@ -432,6 +435,7 @@ mod tests {
|
||||
PipelineOptions {
|
||||
language: "de".to_string(),
|
||||
deepscript_model: "premium".to_string(),
|
||||
vocabulary: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -548,6 +552,7 @@ mod tests {
|
||||
language: "de".to_string(),
|
||||
model: "premium".to_string(),
|
||||
single_speaker,
|
||||
vocabulary: Vec::new(),
|
||||
};
|
||||
assert_eq!(
|
||||
fake.submitted(),
|
||||
@@ -558,6 +563,27 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pipeline_forwards_the_vocabulary_to_both_tracks() {
|
||||
let f = fixture();
|
||||
let fake = FakeTranscriber::returning(vec![], vec![]);
|
||||
let opts = PipelineOptions {
|
||||
vocabulary: vec!["Tschüss".to_string(), "Euvino".to_string()],
|
||||
..opts()
|
||||
};
|
||||
|
||||
process_call(&f.store, &fake, f.id, &opts, &f.work_dir())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
for (_, submitted) in fake.submitted() {
|
||||
assert_eq!(
|
||||
submitted.vocabulary,
|
||||
vec!["Tschüss".to_string(), "Euvino".to_string()]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pipeline_transcription_failure_sets_failed_keeps_audio() {
|
||||
let f = fixture();
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
//! Playback of a call in the detail view while its audio is still on disk:
|
||||
//! both tracks are mixed into one cached mono WAV
|
||||
//! (`<playback dir>/<id>.wav`), which the app serves to the main window
|
||||
//! only (its `playback` URI scheme). The cache is rebuilt only when a track
|
||||
//! is newer than it, and removed with the call's audio and when the player
|
||||
//! lets go of it.
|
||||
|
||||
use std::fs;
|
||||
use std::io::{self, ErrorKind};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::audio::{has_audio, mix_wavs, SAMPLE_RATE};
|
||||
use crate::model::{Call, CallId, CallStatus};
|
||||
|
||||
/// The call's audio was deleted (by retention).
|
||||
pub const AUDIO_GONE: &str = "Audio nicht mehr vorhanden";
|
||||
/// Neither track holds audio (files missing or empty), though nothing
|
||||
/// deleted them.
|
||||
pub const AUDIO_MISSING: &str = "Audio nicht vorhanden";
|
||||
/// Mixing failed; the details (with file paths) only go to the log.
|
||||
pub const PREPARE_FAILED: &str = "Audio konnte nicht vorbereitet werden.";
|
||||
pub const RECORDING: &str = "Das Gespräch wird gerade aufgenommen";
|
||||
pub const PROCESSING: &str = "Das Gespräch wird gerade verarbeitet – Wiedergabe danach möglich";
|
||||
|
||||
/// What the UI needs besides the call id (from which it builds the
|
||||
/// `playback` URL): the mix's length.
|
||||
#[derive(Serialize, Clone, Copy, Debug, PartialEq)]
|
||||
pub struct PlaybackInfo {
|
||||
pub duration_secs: f64,
|
||||
}
|
||||
|
||||
/// Why `call` cannot be played, if it cannot: its tracks are still being
|
||||
/// written (recording) or read for transcription (processing), or its
|
||||
/// audio was deleted.
|
||||
pub fn refusal(call: &Call) -> Option<&'static str> {
|
||||
match call.status {
|
||||
CallStatus::Recording => Some(RECORDING),
|
||||
CallStatus::Processing => Some(PROCESSING),
|
||||
_ if call.audio_deleted => Some(AUDIO_GONE),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `call` still has audio to play: not deleted, and at least one
|
||||
/// track [has audio](has_audio) — the same rule the mix goes by.
|
||||
pub fn audio_available(call: &Call) -> bool {
|
||||
!call.audio_deleted && (has_audio(&call.mic_path) || has_audio(&call.out_path))
|
||||
}
|
||||
|
||||
/// Whether a cached mix last written at `cache` can be reused for tracks
|
||||
/// last written at `sources` (`None`: that track does not exist). It can if
|
||||
/// it exists and is newer than every existing track; with no track left
|
||||
/// there is nothing it could still stand for.
|
||||
pub fn is_fresh(cache: Option<SystemTime>, sources: &[Option<SystemTime>]) -> bool {
|
||||
let Some(cache) = cache else {
|
||||
return false;
|
||||
};
|
||||
let mut any = false;
|
||||
for source in sources.iter().flatten() {
|
||||
if *source >= cache {
|
||||
return false;
|
||||
}
|
||||
any = true;
|
||||
}
|
||||
any
|
||||
}
|
||||
|
||||
/// Where call `id`'s mix is cached in the playback directory `dir`.
|
||||
pub fn cache_path(dir: &Path, id: CallId) -> PathBuf {
|
||||
dir.join(format!("{id}.wav"))
|
||||
}
|
||||
|
||||
/// Returns call `call`'s mix in the playback directory `dir`, building it
|
||||
/// first unless a fresh one is cached ([`is_fresh`]). Refused (see
|
||||
/// [`refusal`]) while the call records or is processed and once its audio
|
||||
/// is gone; a cached mix of a call whose audio is gone is removed. Errors
|
||||
/// are fit for the UI: they never contain a file path.
|
||||
pub fn prepare(call: &Call, dir: &Path) -> Result<PlaybackInfo, String> {
|
||||
let path = cache_path(dir, call.id);
|
||||
if let Some(msg) = refusal(call) {
|
||||
if msg == AUDIO_GONE {
|
||||
remove_cached(dir, call.id);
|
||||
}
|
||||
return Err(msg.to_string());
|
||||
}
|
||||
let sources = [modified(&call.mic_path), modified(&call.out_path)];
|
||||
if is_fresh(modified(&path), &sources) {
|
||||
match duration_secs(&path) {
|
||||
Ok(duration_secs) => return Ok(PlaybackInfo { duration_secs }),
|
||||
Err(e) => log::warn!("call {}: rebuilding unreadable playback file: {e}", call.id),
|
||||
}
|
||||
}
|
||||
|
||||
let mixed =
|
||||
fs::create_dir_all(dir).and_then(|()| mix_wavs(&call.mic_path, &call.out_path, &path));
|
||||
match mixed {
|
||||
Ok(samples) => Ok(PlaybackInfo {
|
||||
duration_secs: samples as f64 / SAMPLE_RATE as f64,
|
||||
}),
|
||||
Err(e) if e.kind() == ErrorKind::NotFound => {
|
||||
remove_cached(dir, call.id);
|
||||
Err(AUDIO_MISSING.to_string())
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("call {}: could not mix for playback: {e}", call.id);
|
||||
Err(PREPARE_FAILED.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes call `id`'s cached mix, if any (with the call or its audio).
|
||||
/// Failures are logged: the playback directory is emptied at every start.
|
||||
pub fn remove_cached(dir: &Path, id: CallId) {
|
||||
let path = cache_path(dir, id);
|
||||
match fs::remove_file(&path) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == ErrorKind::NotFound => {}
|
||||
Err(e) => log::warn!("could not remove {}: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes every cached mix (at startup, so customer audio never lingers
|
||||
/// in the cache).
|
||||
pub fn clear_cache(dir: &Path) -> io::Result<()> {
|
||||
match fs::remove_dir_all(dir) {
|
||||
Err(e) if e.kind() == ErrorKind::NotFound => Ok(()),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
fn modified(path: &Path) -> Option<SystemTime> {
|
||||
fs::metadata(path).and_then(|m| m.modified()).ok()
|
||||
}
|
||||
|
||||
fn duration_secs(path: &Path) -> Result<f64, hound::Error> {
|
||||
let reader = hound::WavReader::open(path)?;
|
||||
Ok(reader.duration() as f64 / reader.spec().sample_rate as f64)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::fs::File;
|
||||
use std::time::Duration;
|
||||
|
||||
use chrono::Local;
|
||||
|
||||
use super::*;
|
||||
use crate::audio::TrackWriter;
|
||||
|
||||
fn call(dir: &Path, status: CallStatus) -> Call {
|
||||
Call {
|
||||
id: 7,
|
||||
app: "Microsoft Teams".to_string(),
|
||||
started_at: Local::now(),
|
||||
ended_at: Some(Local::now()),
|
||||
status,
|
||||
interrupted: false,
|
||||
error: None,
|
||||
mic_path: dir.join("7-mic.wav"),
|
||||
out_path: dir.join("7-out.wav"),
|
||||
transcribed_at: None,
|
||||
audio_deleted: false,
|
||||
title: None,
|
||||
crm_transcript_id: None,
|
||||
crm_base_url: None,
|
||||
language: None,
|
||||
uploaded_at: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn write_track(path: &Path, samples: &[f32]) {
|
||||
let mut writer = TrackWriter::create(path).unwrap();
|
||||
writer.write(samples).unwrap();
|
||||
writer.finalize().unwrap();
|
||||
}
|
||||
|
||||
/// A call with one second on the mic and half a second on the output.
|
||||
fn recorded_call(dir: &Path, status: CallStatus) -> Call {
|
||||
let call = call(dir, status);
|
||||
write_track(&call.mic_path, &vec![0.1; 16_000]);
|
||||
write_track(&call.out_path, &vec![0.2; 8_000]);
|
||||
call
|
||||
}
|
||||
|
||||
fn set_modified(path: &Path, time: SystemTime) {
|
||||
File::options()
|
||||
.write(true)
|
||||
.open(path)
|
||||
.unwrap()
|
||||
.set_modified(time)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cache_newer_than_every_track_is_fresh() {
|
||||
let t = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000);
|
||||
let s = Duration::from_secs(1);
|
||||
assert!(is_fresh(Some(t), &[Some(t - s), Some(t - s)]));
|
||||
assert!(is_fresh(Some(t), &[None, Some(t - s)]));
|
||||
assert!(!is_fresh(Some(t), &[Some(t - s), Some(t + s)]));
|
||||
assert!(!is_fresh(Some(t), &[Some(t), Some(t - s)]), "same time");
|
||||
assert!(!is_fresh(None, &[Some(t - s), Some(t - s)]), "no cache");
|
||||
assert!(!is_fresh(Some(t), &[None, None]), "no tracks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recording_processing_and_deleted_calls_are_refused() {
|
||||
let dir = Path::new("/nonexistent");
|
||||
assert_eq!(refusal(&call(dir, CallStatus::Recording)), Some(RECORDING));
|
||||
assert_eq!(
|
||||
refusal(&call(dir, CallStatus::Processing)),
|
||||
Some(PROCESSING)
|
||||
);
|
||||
let mut deleted = call(dir, CallStatus::Done);
|
||||
deleted.audio_deleted = true;
|
||||
assert_eq!(refusal(&deleted), Some(AUDIO_GONE));
|
||||
for status in [
|
||||
CallStatus::AwaitingDecision,
|
||||
CallStatus::Done,
|
||||
CallStatus::Failed,
|
||||
] {
|
||||
assert_eq!(refusal(&call(dir, status)), None, "{status:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_is_available_while_a_track_holds_audio() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut c = call(dir.path(), CallStatus::Done);
|
||||
assert!(!audio_available(&c), "no files");
|
||||
write_track(&c.out_path, &[]);
|
||||
assert!(!audio_available(&c), "header only");
|
||||
write_track(&c.mic_path, &[0.1; 10]);
|
||||
assert!(audio_available(&c));
|
||||
c.audio_deleted = true;
|
||||
assert!(!audio_available(&c), "deleted by retention");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mix_is_built_once_and_reused() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let playback = dir.path().join("playback");
|
||||
let c = recorded_call(dir.path(), CallStatus::Done);
|
||||
|
||||
let info = prepare(&c, &playback).unwrap();
|
||||
let mix = playback.join("7.wav");
|
||||
assert!(mix.exists());
|
||||
assert!((info.duration_secs - 1.0).abs() < 1e-9);
|
||||
|
||||
// Marked as written long ago: a rebuild would show a new time.
|
||||
let old = SystemTime::now() - Duration::from_secs(60);
|
||||
set_modified(&c.mic_path, old - Duration::from_secs(60));
|
||||
set_modified(&c.out_path, old - Duration::from_secs(60));
|
||||
set_modified(&mix, old);
|
||||
assert_eq!(prepare(&c, &playback).unwrap(), info);
|
||||
assert_eq!(modified(&mix), Some(old), "reused, not rebuilt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mix_is_rebuilt_when_a_track_is_newer() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let playback = dir.path().join("playback");
|
||||
let c = recorded_call(dir.path(), CallStatus::AwaitingDecision);
|
||||
prepare(&c, &playback).unwrap();
|
||||
let mix = cache_path(&playback, c.id);
|
||||
let old = SystemTime::now() - Duration::from_secs(60);
|
||||
set_modified(&mix, old);
|
||||
|
||||
// Two seconds now; the file is newer than the cache.
|
||||
write_track(&c.mic_path, &vec![0.1; 32_000]);
|
||||
let second = prepare(&c, &playback).unwrap();
|
||||
assert!((second.duration_secs - 2.0).abs() < 1e-9);
|
||||
assert_ne!(modified(&mix), Some(old));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_call_with_one_track_plays_that_track() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let c = call(dir.path(), CallStatus::Failed);
|
||||
write_track(&c.out_path, &vec![0.2; 4_000]);
|
||||
let info = prepare(&c, &dir.path().join("playback")).unwrap();
|
||||
assert!((info.duration_secs - 0.25).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_call_builds_nothing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let playback = dir.path().join("playback");
|
||||
for status in [CallStatus::Recording, CallStatus::Processing] {
|
||||
let c = recorded_call(dir.path(), status);
|
||||
assert!(prepare(&c, &playback).is_err());
|
||||
assert!(!cache_path(&playback, c.id).exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleted_audio_removes_the_cached_mix() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let playback = dir.path().join("playback");
|
||||
let mut c = recorded_call(dir.path(), CallStatus::Done);
|
||||
prepare(&c, &playback).unwrap();
|
||||
let mix = cache_path(&playback, c.id);
|
||||
|
||||
// Retention deleted the audio.
|
||||
fs::remove_file(&c.mic_path).unwrap();
|
||||
fs::remove_file(&c.out_path).unwrap();
|
||||
c.audio_deleted = true;
|
||||
assert_eq!(prepare(&c, &playback), Err(AUDIO_GONE.to_string()));
|
||||
assert!(!mix.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_files_remove_the_cached_mix() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let playback = dir.path().join("playback");
|
||||
let c = recorded_call(dir.path(), CallStatus::Done);
|
||||
prepare(&c, &playback).unwrap();
|
||||
let mix = cache_path(&playback, c.id);
|
||||
|
||||
fs::remove_file(&c.mic_path).unwrap();
|
||||
fs::remove_file(&c.out_path).unwrap();
|
||||
assert_eq!(prepare(&c, &playback), Err(AUDIO_MISSING.to_string()));
|
||||
assert!(!mix.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_mix_reports_no_file_paths() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let c = recorded_call(dir.path(), CallStatus::Done);
|
||||
// The playback directory cannot be created: a file is in the way.
|
||||
let blocked = dir.path().join("playback");
|
||||
fs::write(&blocked, b"").unwrap();
|
||||
|
||||
assert_eq!(prepare(&c, &blocked), Err(PREPARE_FAILED.to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cache_is_removed_per_call_and_cleared_as_a_whole() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let playback = dir.path().join("playback");
|
||||
let c = recorded_call(dir.path(), CallStatus::Done);
|
||||
prepare(&c, &playback).unwrap();
|
||||
fs::write(playback.join("8.wav"), b"other").unwrap();
|
||||
|
||||
remove_cached(&playback, c.id);
|
||||
assert!(!cache_path(&playback, c.id).exists());
|
||||
assert!(playback.join("8.wav").exists());
|
||||
remove_cached(&playback, c.id); // already gone: no error
|
||||
|
||||
clear_cache(&playback).unwrap();
|
||||
assert!(!playback.exists());
|
||||
clear_cache(&playback).unwrap(); // already gone: no error
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use crate::model::{Call, CallId, CallStatus};
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RetentionAction {
|
||||
/// Delete the call's audio file(s) on disk; the row stays (it has a
|
||||
/// summary/transcript worth keeping).
|
||||
/// transcript worth keeping).
|
||||
DeleteAudio(CallId),
|
||||
/// Delete the whole call row (and everything derived from it).
|
||||
DeleteCall(CallId),
|
||||
@@ -88,8 +88,11 @@ mod tests {
|
||||
out_path: PathBuf::from("/tmp/out.wav"),
|
||||
transcribed_at: None,
|
||||
audio_deleted: false,
|
||||
account_id: None,
|
||||
title: None,
|
||||
crm_transcript_id: None,
|
||||
crm_base_url: None,
|
||||
language: None,
|
||||
uploaded_at: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! 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::sync::Mutex;
|
||||
@@ -15,7 +17,7 @@ pub const KEYRING_SERVICE: &str = "eu.euvino.callrecorder";
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Service {
|
||||
DeepScript,
|
||||
Anthropic,
|
||||
Backend,
|
||||
}
|
||||
|
||||
impl Service {
|
||||
@@ -23,7 +25,7 @@ impl Service {
|
||||
pub fn user(self) -> &'static str {
|
||||
match self {
|
||||
Service::DeepScript => "deepscript",
|
||||
Service::Anthropic => "anthropic",
|
||||
Service::Backend => "backend",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,6 +47,10 @@ pub trait SecretStore: Send + Sync {
|
||||
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.
|
||||
pub struct KeyringSecrets;
|
||||
|
||||
@@ -53,6 +59,21 @@ impl KeyringSecrets {
|
||||
keyring::Entry::new(KEYRING_SERVICE, s.user())
|
||||
.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 {
|
||||
@@ -100,6 +121,8 @@ impl SecretStore for MemorySecrets {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const SERVICES: &[Service] = &[Service::DeepScript, Service::Backend];
|
||||
|
||||
#[test]
|
||||
fn memory_secrets_roundtrip() {
|
||||
let secrets = MemorySecrets::default();
|
||||
@@ -107,16 +130,23 @@ mod tests {
|
||||
|
||||
secrets.set(Service::DeepScript, "ds-key").unwrap();
|
||||
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();
|
||||
assert_eq!(secrets.get(Service::DeepScript), None);
|
||||
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]
|
||||
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();
|
||||
assert_eq!(json, format!("\"{}\"", s.user()));
|
||||
assert_eq!(serde_json::from_str::<Service>(&json).unwrap(), s);
|
||||
|
||||
+394
-3
@@ -8,6 +8,7 @@ use std::io;
|
||||
use std::ops::RangeInclusive;
|
||||
use std::path::Path;
|
||||
|
||||
use chrono::{DateTime, Local};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Executables whose mic use counts as a call (matched case-insensitively).
|
||||
@@ -25,6 +26,43 @@ pub const START_AFTER_SECS: RangeInclusive<u64> = 1..=30;
|
||||
/// Allowed mic release before a call counts as ended, in seconds. Too short
|
||||
/// splits a call, e.g. when the headset is switched.
|
||||
pub const END_AFTER_SECS: RangeInclusive<u64> = 3..=120;
|
||||
/// Allowed retention period, in days (the settings UI checks the same).
|
||||
pub const RETENTION_DAYS: RangeInclusive<u32> = 1..=3650;
|
||||
|
||||
/// The only `deepscript_model` values the settings UI offers (DeepScript's
|
||||
/// OpenAPI spec also lists `"standard"`, not offered here). An older
|
||||
/// settings.json with `"standard"` or anything else falls back to the
|
||||
/// default on load (see [`Settings::load`]) rather than failing.
|
||||
pub const DEEPSCRIPT_MODELS: [&str; 2] = ["premium", "premium_jade"];
|
||||
|
||||
/// The languages (ISO 639-1) a call can be transcribed in, chosen per call
|
||||
/// when its transcription is started. All are in DeepScript's
|
||||
/// `GET /v1/languages`; its `"auto"` is not offered.
|
||||
pub const CALL_LANGUAGES: [&str; 5] = ["de", "en", "es", "fr", "it"];
|
||||
|
||||
/// Checks a call language chosen in the UI; the error is shown as is.
|
||||
pub fn check_call_language(language: &str) -> Result<(), String> {
|
||||
if CALL_LANGUAGES.contains(&language) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("Unbekannte Sprache: {language}"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Default custom-vocabulary terms: short standalone German words/names
|
||||
/// DeepScript otherwise tends to mistranscribe or drop.
|
||||
const DEFAULT_VOCABULARY: [&str; 5] = ["Tschüss", "Perfekt", "Servus", "Moin", "Euvino"];
|
||||
|
||||
/// Hard cap on the vocabulary list sent with every DeepScript submission.
|
||||
/// DeepScript's OpenAPI spec does not document a limit for the
|
||||
/// per-transcription `vocabulary` field itself (only for its separate,
|
||||
/// *saved* vocabularies, capped there at 500 words — see
|
||||
/// `POST /v1/vocabularies`); these two numbers are ours, chosen to keep
|
||||
/// that field small.
|
||||
pub const MAX_VOCABULARY_TERMS: usize = 200;
|
||||
/// Hard cap on one vocabulary term's length (characters), for the same
|
||||
/// reason as [`MAX_VOCABULARY_TERMS`].
|
||||
pub const MAX_VOCABULARY_TERM_LEN: usize = 60;
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
||||
#[serde(default)]
|
||||
@@ -32,12 +70,29 @@ pub struct Settings {
|
||||
pub allowlist: Vec<String>,
|
||||
pub mic_device: Option<String>,
|
||||
pub output_device: Option<String>,
|
||||
/// The language of the transcription started last (one of
|
||||
/// [`CALL_LANGUAGES`]), preselected for the next call. Set by the app
|
||||
/// when a transcription is started, not by the settings page.
|
||||
pub language: String,
|
||||
pub deepscript_model: String,
|
||||
/// Custom words/names submitted with every transcription (DeepScript's
|
||||
/// `vocabulary` field), e.g. names and product terms that are often
|
||||
/// misheard. Normalized on load and on every edit (see
|
||||
/// [`normalize_vocabulary`]): trimmed, blanks dropped, deduplicated
|
||||
/// case-insensitively, order kept.
|
||||
pub vocabulary: Vec<String>,
|
||||
pub retention_days: u32,
|
||||
pub autostart: bool,
|
||||
pub start_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 {
|
||||
@@ -48,10 +103,14 @@ impl Default for Settings {
|
||||
output_device: None,
|
||||
language: "de".to_string(),
|
||||
deepscript_model: "premium".to_string(),
|
||||
vocabulary: DEFAULT_VOCABULARY.iter().map(|s| s.to_string()).collect(),
|
||||
retention_days: 7,
|
||||
autostart: true,
|
||||
start_after_secs: 3,
|
||||
end_after_secs: 10,
|
||||
backend_username: None,
|
||||
backend_key_expires_at: None,
|
||||
backend_key_base_url: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -73,16 +132,75 @@ impl Settings {
|
||||
END_AFTER_SECS.end()
|
||||
));
|
||||
}
|
||||
if !RETENTION_DAYS.contains(&self.retention_days) {
|
||||
return Err(format!(
|
||||
"Aufbewahrung: {}–{} Tage",
|
||||
RETENTION_DAYS.start(),
|
||||
RETENTION_DAYS.end()
|
||||
));
|
||||
}
|
||||
if !DEEPSCRIPT_MODELS.contains(&self.deepscript_model.as_str()) {
|
||||
return Err(format!(
|
||||
"Transkriptionsmodell: nur {} möglich",
|
||||
DEEPSCRIPT_MODELS.join(" oder ")
|
||||
));
|
||||
}
|
||||
if self.vocabulary.len() > MAX_VOCABULARY_TERMS {
|
||||
return Err(format!(
|
||||
"Vokabular: höchstens {MAX_VOCABULARY_TERMS} Begriffe"
|
||||
));
|
||||
}
|
||||
if let Some(term) = self
|
||||
.vocabulary
|
||||
.iter()
|
||||
.find(|term| term.chars().count() > MAX_VOCABULARY_TERM_LEN)
|
||||
{
|
||||
return Err(format!(
|
||||
"Vokabular: „{term}“ ist länger als {MAX_VOCABULARY_TERM_LEN} Zeichen"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The settings after the user saved `edited` over these: normalized
|
||||
/// (see [`normalize_vocabulary`]), checked, with the backend login and
|
||||
/// the last-used language (which only the app changes) kept, so a
|
||||
/// settings page loaded before a login or a transcription cannot undo
|
||||
/// them.
|
||||
pub fn edited(&self, mut edited: Settings) -> Result<Settings, String> {
|
||||
edited.vocabulary = normalize_vocabulary(edited.vocabulary);
|
||||
edited.validate()?;
|
||||
edited.language = self.language.clone();
|
||||
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
|
||||
/// defaults; fields missing from the file take their default value.
|
||||
/// defaults; fields missing from the file take their default value. A
|
||||
/// `deepscript_model` outside [`DEEPSCRIPT_MODELS`] (e.g. an older
|
||||
/// file's `"standard"`) falls back to the default instead of failing, and
|
||||
/// so does a `retention_days` outside [`RETENTION_DAYS`] and a
|
||||
/// `language` outside [`CALL_LANGUAGES`]; `vocabulary` is normalized
|
||||
/// (see [`normalize_vocabulary`]).
|
||||
pub fn load(path: &Path) -> Settings {
|
||||
fs::read_to_string(path)
|
||||
let mut settings: Settings = fs::read_to_string(path)
|
||||
.ok()
|
||||
.and_then(|json| serde_json::from_str(&json).ok())
|
||||
.unwrap_or_default()
|
||||
.unwrap_or_default();
|
||||
if !DEEPSCRIPT_MODELS.contains(&settings.deepscript_model.as_str()) {
|
||||
settings.deepscript_model = Settings::default().deepscript_model;
|
||||
}
|
||||
if check_call_language(&settings.language).is_err() {
|
||||
settings.language = Settings::default().language;
|
||||
}
|
||||
// 0 would delete all audio on the next pass.
|
||||
if !RETENTION_DAYS.contains(&settings.retention_days) {
|
||||
settings.retention_days = Settings::default().retention_days;
|
||||
}
|
||||
settings.vocabulary = normalize_vocabulary(settings.vocabulary);
|
||||
settings
|
||||
}
|
||||
|
||||
/// Writes the settings file (creating its directory), replacing the old
|
||||
@@ -98,6 +216,23 @@ impl Settings {
|
||||
}
|
||||
}
|
||||
|
||||
/// Trims each term, drops blanks, and deduplicates case-insensitively while
|
||||
/// keeping the first occurrence's spelling and order.
|
||||
fn normalize_vocabulary(terms: Vec<String>) -> Vec<String> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
terms
|
||||
.into_iter()
|
||||
.filter_map(|term| {
|
||||
let trimmed = term.trim();
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
seen.insert(trimmed.to_lowercase())
|
||||
.then(|| trimmed.to_string())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -120,10 +255,150 @@ mod tests {
|
||||
assert_eq!(s.output_device, None);
|
||||
assert_eq!(s.language, "de");
|
||||
assert_eq!(s.deepscript_model, "premium");
|
||||
assert_eq!(
|
||||
s.vocabulary,
|
||||
vec!["Tschüss", "Perfekt", "Servus", "Moin", "Euvino"]
|
||||
);
|
||||
assert_eq!(s.retention_days, 7);
|
||||
assert!(s.autostart);
|
||||
assert_eq!(s.start_after_secs, 3);
|
||||
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()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_older_files_model_and_a_missing_vocabulary_fall_back_to_the_default() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("settings.json");
|
||||
fs::write(&path, r#"{"deepscript_model": "standard"}"#).unwrap();
|
||||
assert_eq!(Settings::load(&path), Settings::default());
|
||||
|
||||
fs::write(&path, r#"{"deepscript_model": "nonsense"}"#).unwrap();
|
||||
assert_eq!(Settings::load(&path), Settings::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loading_normalizes_the_stored_vocabulary() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("settings.json");
|
||||
fs::write(
|
||||
&path,
|
||||
r#"{"vocabulary": [" Tschüss ", "", "TSCHÜSS", " ", "Euvino"]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
Settings::load(&path).vocabulary,
|
||||
vec!["Tschüss".to_string(), "Euvino".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_five_call_languages_are_accepted() {
|
||||
for language in CALL_LANGUAGES {
|
||||
assert_eq!(check_call_language(language), Ok(()), "{language}");
|
||||
}
|
||||
assert_eq!(CALL_LANGUAGES, ["de", "en", "es", "fr", "it"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_call_language_is_refused() {
|
||||
assert_eq!(
|
||||
check_call_language("auto"),
|
||||
Err("Unbekannte Sprache: auto".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
check_call_language("pt"),
|
||||
Err("Unbekannte Sprache: pt".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_stored_language_falls_back_to_the_default() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("settings.json");
|
||||
fs::write(&path, r#"{"language": "auto"}"#).unwrap();
|
||||
assert_eq!(Settings::load(&path).language, "de");
|
||||
|
||||
fs::write(&path, r#"{"language": "it"}"#).unwrap();
|
||||
assert_eq!(Settings::load(&path).language, "it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_keeps_the_last_used_language_which_only_the_app_changes() {
|
||||
let current = Settings {
|
||||
language: "fr".into(),
|
||||
..Settings::default()
|
||||
};
|
||||
let edited = Settings {
|
||||
language: "de".into(),
|
||||
..Settings::default()
|
||||
};
|
||||
|
||||
assert_eq!(current.edited(edited).unwrap().language, "fr");
|
||||
}
|
||||
|
||||
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]
|
||||
@@ -161,6 +436,122 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_checks_the_retention_period() {
|
||||
for days in [1, 3650] {
|
||||
let s = Settings {
|
||||
retention_days: days,
|
||||
..Settings::default()
|
||||
};
|
||||
assert_eq!(s.validate(), Ok(()), "{days} days");
|
||||
}
|
||||
for days in [0, 3651] {
|
||||
let s = Settings {
|
||||
retention_days: days,
|
||||
..Settings::default()
|
||||
};
|
||||
assert_eq!(
|
||||
s.validate(),
|
||||
Err("Aufbewahrung: 1–3650 Tage".to_string()),
|
||||
"{days} days"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retention_period_out_of_range_falls_back_to_the_default_on_load() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("settings.json");
|
||||
for days in [0, 3651] {
|
||||
fs::write(
|
||||
&path,
|
||||
format!(
|
||||
r#"{{"retention_days": {days}, "mic_device": "headset", "backend_key_base_url": "https://crm.example"}}"#
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
Settings::load(&path),
|
||||
Settings {
|
||||
mic_device: Some("headset".into()),
|
||||
backend_key_base_url: Some("https://crm.example".into()),
|
||||
..Settings::default()
|
||||
},
|
||||
"{days} days"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_rejects_a_model_outside_the_offered_two() {
|
||||
for model in ["standard", "nonsense", ""] {
|
||||
let s = Settings {
|
||||
deepscript_model: model.to_string(),
|
||||
..Settings::default()
|
||||
};
|
||||
assert_eq!(
|
||||
s.validate(),
|
||||
Err("Transkriptionsmodell: nur premium oder premium_jade möglich".to_string())
|
||||
);
|
||||
}
|
||||
for model in ["premium", "premium_jade"] {
|
||||
let s = Settings {
|
||||
deepscript_model: model.to_string(),
|
||||
..Settings::default()
|
||||
};
|
||||
assert_eq!(s.validate(), Ok(()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_rejects_too_many_vocabulary_terms() {
|
||||
let s = Settings {
|
||||
vocabulary: (0..=MAX_VOCABULARY_TERMS).map(|n| n.to_string()).collect(),
|
||||
..Settings::default()
|
||||
};
|
||||
assert_eq!(
|
||||
s.validate(),
|
||||
Err(format!(
|
||||
"Vokabular: höchstens {MAX_VOCABULARY_TERMS} Begriffe"
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_rejects_a_too_long_vocabulary_term() {
|
||||
let s = Settings {
|
||||
vocabulary: vec!["a".repeat(MAX_VOCABULARY_TERM_LEN + 1)],
|
||||
..Settings::default()
|
||||
};
|
||||
assert_eq!(
|
||||
s.validate(),
|
||||
Err(format!(
|
||||
"Vokabular: „{}“ ist länger als {MAX_VOCABULARY_TERM_LEN} Zeichen",
|
||||
"a".repeat(MAX_VOCABULARY_TERM_LEN + 1)
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_normalizes_the_vocabulary_before_validating_and_saving() {
|
||||
let edited = Settings {
|
||||
vocabulary: vec![
|
||||
" Tschüss ".to_string(),
|
||||
"".to_string(),
|
||||
"TSCHÜSS".to_string(),
|
||||
"Kisling".to_string(),
|
||||
],
|
||||
..Settings::default()
|
||||
};
|
||||
|
||||
let saved = logged_in().edited(edited).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
saved.vocabulary,
|
||||
vec!["Tschüss".to_string(), "Kisling".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_load_missing_file_returns_default() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
+331
-108
@@ -1,5 +1,5 @@
|
||||
//! SQLite-backed persistence for calls, their transcripts, summaries,
|
||||
//! speaker renames and outstanding remote transcription/summary jobs.
|
||||
//! SQLite-backed persistence for calls, their transcripts, speaker renames
|
||||
//! and merges, and outstanding remote transcription jobs.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -10,7 +10,7 @@ use rusqlite::{params, Connection, Row, TransactionBehavior};
|
||||
use thiserror::Error;
|
||||
|
||||
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.
|
||||
const MAX_TITLE_CHARS: usize = 120;
|
||||
@@ -22,8 +22,8 @@ pub enum StoreError {
|
||||
Sqlite(#[from] rusqlite::Error),
|
||||
|
||||
/// A value read back from SQLite could not be interpreted, e.g. an
|
||||
/// unknown `status` string, invalid RFC 3339 timestamp, unparsable
|
||||
/// speaker key or malformed summary JSON.
|
||||
/// unknown `status` string, invalid RFC 3339 timestamp or unparsable
|
||||
/// speaker key.
|
||||
#[error("corrupt stored value: {0}")]
|
||||
Corrupt(String),
|
||||
|
||||
@@ -51,7 +51,9 @@ pub struct RecoveryReport {
|
||||
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 = "
|
||||
CREATE TABLE IF NOT EXISTS calls (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
@@ -112,9 +114,41 @@ 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;
|
||||
";
|
||||
|
||||
/// Version 5: the language a call is transcribed in, chosen per call when
|
||||
/// its transcription is started. Before this version every transcription
|
||||
/// used the then default German: backfilled for the calls one was started
|
||||
/// for, so their corrections (`call_view`) stay as they were; a call still
|
||||
/// waiting gets its language when the user decides.
|
||||
const SCHEMA_V5_SQL: &str = "
|
||||
ALTER TABLE calls ADD COLUMN language TEXT;
|
||||
UPDATE calls SET language = 'de' WHERE status NOT IN ('recording', 'awaiting_decision');
|
||||
";
|
||||
|
||||
/// Schema steps by `PRAGMA user_version`: entry `i` takes a database from
|
||||
/// 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,
|
||||
SCHEMA_V5_SQL,
|
||||
];
|
||||
|
||||
/// SQLite-backed store for calls and everything derived from them.
|
||||
pub struct Store {
|
||||
@@ -152,8 +186,8 @@ impl Store {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO calls \
|
||||
(app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, account_id) \
|
||||
VALUES (?1, ?2, NULL, ?3, 0, NULL, ?4, ?5, NULL, 0, NULL)",
|
||||
(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)",
|
||||
params![
|
||||
app,
|
||||
dt_to_str(started_at),
|
||||
@@ -271,33 +305,6 @@ impl Store {
|
||||
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<()> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
conn.execute(
|
||||
@@ -380,6 +387,35 @@ impl Store {
|
||||
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(())
|
||||
}
|
||||
|
||||
/// Sets the language (ISO 639-1 code) the call is transcribed in.
|
||||
pub fn set_language(&self, id: CallId, language: &str) -> Result<()> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
conn.execute(
|
||||
"UPDATE calls SET language = ?1 WHERE id = ?2",
|
||||
params![language, id],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn mark_transcribed(&self, id: CallId, at: DateTime<Local>) -> Result<()> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
conn.execute(
|
||||
@@ -398,8 +434,9 @@ impl Store {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Deletes a call and every row derived from it (segments, summary,
|
||||
/// speaker names and merges, remote jobs).
|
||||
/// Deletes a call and every row derived from it (segments, speaker
|
||||
/// names and merges, remote jobs; also the `summaries` table of schema
|
||||
/// v1, which nothing writes).
|
||||
pub fn delete_call(&self, id: CallId) -> Result<()> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction()?;
|
||||
@@ -413,15 +450,6 @@ impl Store {
|
||||
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<()> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
conn.execute(
|
||||
@@ -470,7 +498,7 @@ impl Store {
|
||||
/// `AwaitingDecision`, with `interrupted` set and `ended_at` set to now
|
||||
/// if it was not already set (a later pass corrects it from the WAV
|
||||
/// length).
|
||||
/// - `Processing` calls were mid-transcription/summarization: they move
|
||||
/// - `Processing` calls were mid-transcription: they move
|
||||
/// to `Failed` with a fixed error message.
|
||||
///
|
||||
/// Both updates run in a single transaction.
|
||||
@@ -547,9 +575,9 @@ fn ids_with_status(conn: &rusqlite::Connection, status: CallStatus) -> Result<Ve
|
||||
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, language 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, language FROM calls WHERE id = ?1";
|
||||
|
||||
fn row_to_call(row: &Row) -> Result<Call> {
|
||||
let id: CallId = row.get(0)?;
|
||||
@@ -563,8 +591,11 @@ fn row_to_call(row: &Row) -> Result<Call> {
|
||||
let out_path: String = row.get(8)?;
|
||||
let transcribed_at: Option<String> = row.get(9)?;
|
||||
let audio_deleted: bool = row.get(10)?;
|
||||
let account_id: Option<String> = row.get(11)?;
|
||||
let title: Option<String> = row.get(12)?;
|
||||
let title: Option<String> = row.get(11)?;
|
||||
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)?;
|
||||
let language: Option<String> = row.get(15)?;
|
||||
|
||||
Ok(Call {
|
||||
id,
|
||||
@@ -578,8 +609,11 @@ fn row_to_call(row: &Row) -> Result<Call> {
|
||||
out_path: PathBuf::from(out_path),
|
||||
transcribed_at: opt_dt_from_str(transcribed_at)?,
|
||||
audio_deleted,
|
||||
account_id,
|
||||
title,
|
||||
crm_transcript_id,
|
||||
crm_base_url,
|
||||
uploaded_at: opt_dt_from_str(uploaded_at)?,
|
||||
language,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -637,9 +671,7 @@ mod tests {
|
||||
|
||||
use chrono::Local;
|
||||
|
||||
use crate::model::{
|
||||
CallId, CallStatus, NaechsterKontakt, Owner, Segment, Speaker, Summary, Todo,
|
||||
};
|
||||
use crate::model::{CallId, CallStatus, Segment, Speaker};
|
||||
use crate::store::Store;
|
||||
|
||||
/// The schema of user_version 1, exactly as the first release created
|
||||
@@ -690,6 +722,35 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
|
||||
remote_id TEXT NOT NULL,
|
||||
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;
|
||||
";
|
||||
|
||||
/// The schema of user_version 4, exactly as release 0.2.2 created it
|
||||
/// (copied from `SCHEMA_V4_SQL` at `HEAD`): version 3 plus these
|
||||
/// statements.
|
||||
const RELEASED_V4_STEP_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;
|
||||
";
|
||||
|
||||
fn user_version(path: &Path) -> i64 {
|
||||
@@ -713,16 +774,19 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_database_starts_at_version_2() {
|
||||
fn a_new_database_starts_at_version_5() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("calls.sqlite");
|
||||
let store = Store::open(&path).unwrap();
|
||||
let id = new_call(&store);
|
||||
store.set_title(id, Some("Angebot")).unwrap();
|
||||
store.set_speaker_merge(id, "remote:2", "remote:1").unwrap();
|
||||
store
|
||||
.set_uploaded(id, "4711", "https://backend.example", Local::now())
|
||||
.unwrap();
|
||||
drop(store);
|
||||
|
||||
assert_eq!(user_version(&path), 2);
|
||||
assert_eq!(user_version(&path), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -754,7 +818,6 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
|
||||
let call = store.get_call(1).unwrap().expect("call kept");
|
||||
assert_eq!(call.app, "Microsoft Teams");
|
||||
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.title, None);
|
||||
let texts: Vec<_> = store
|
||||
@@ -780,7 +843,7 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
|
||||
store.set_title(1, Some("Lieferung März")).unwrap();
|
||||
store.set_speaker_merge(1, "remote:2", "remote:1").unwrap();
|
||||
drop(store);
|
||||
assert_eq!(user_version(&path), 2);
|
||||
assert_eq!(user_version(&path), 5);
|
||||
let store = Store::open(&path).unwrap();
|
||||
let call = store.get_call(1).unwrap().unwrap();
|
||||
assert_eq!(call.title.as_deref(), Some("Lieferung März"));
|
||||
@@ -791,6 +854,214 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
|
||||
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), 5);
|
||||
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), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_version_4_database_is_upgraded_backfilling_german_for_started_transcriptions() {
|
||||
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(RELEASED_V4_STEP_SQL).unwrap();
|
||||
conn.execute_batch("PRAGMA user_version = 4;").unwrap();
|
||||
for (app, status) in [
|
||||
("Microsoft Teams", "done"),
|
||||
("Zoom", "failed"),
|
||||
("MicroSIP", "awaiting_decision"),
|
||||
] {
|
||||
conn.execute(
|
||||
"INSERT INTO calls \
|
||||
(app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted) \
|
||||
VALUES (?1, ?2, ?2, ?3, 0, NULL, '/rec/mic.wav', '/rec/out.wav', NULL, 0)",
|
||||
rusqlite::params![app, started, status],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
let store = Store::open(&path).unwrap();
|
||||
|
||||
// Transcriptions started before this version all used the then
|
||||
// default German; a call still waiting has no language yet.
|
||||
let languages: Vec<_> = (1..=3)
|
||||
.map(|id| store.get_call(id).unwrap().unwrap().language)
|
||||
.collect();
|
||||
assert_eq!(
|
||||
languages,
|
||||
[Some("de".to_string()), Some("de".to_string()), None]
|
||||
);
|
||||
assert_eq!(user_version(&path), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_language_is_stored_per_call() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
let id = new_call(&store);
|
||||
let other = new_call(&store);
|
||||
assert_eq!(store.get_call(id).unwrap().unwrap().language, None);
|
||||
|
||||
store.set_language(id, "fr").unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store.get_call(id).unwrap().unwrap().language.as_deref(),
|
||||
Some("fr")
|
||||
);
|
||||
assert_eq!(store.get_call(other).unwrap().unwrap().language, None);
|
||||
}
|
||||
|
||||
#[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]
|
||||
fn speaker_merges_are_set_replaced_and_removed() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
@@ -939,38 +1210,6 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
|
||||
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]
|
||||
fn speaker_names_upsert() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
@@ -1167,21 +1406,6 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
|
||||
}],
|
||||
)
|
||||
.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_merge(id, "remote:2", "remote:1").unwrap();
|
||||
store
|
||||
@@ -1192,7 +1416,6 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
|
||||
|
||||
assert_eq!(store.get_call(id).unwrap(), None);
|
||||
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.remote_jobs(id).unwrap(), Vec::new());
|
||||
assert_eq!(store.speaker_merges(id).unwrap(), BTreeMap::new());
|
||||
|
||||
@@ -10,8 +10,7 @@ use crate::http::{HttpRequest, HttpResponse, HttpTransport, Method, TransportErr
|
||||
struct Expectation {
|
||||
method: Method,
|
||||
url: String,
|
||||
status: u16,
|
||||
body: Vec<u8>,
|
||||
response: Result<HttpResponse, TransportError>,
|
||||
}
|
||||
|
||||
/// 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.
|
||||
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 {
|
||||
method,
|
||||
url: url.to_string(),
|
||||
status,
|
||||
body: body.into(),
|
||||
response,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -92,9 +104,6 @@ impl HttpTransport for FakeTransport {
|
||||
);
|
||||
}
|
||||
self.requests.lock().unwrap().push(req);
|
||||
Ok(HttpResponse {
|
||||
status: expectation.status,
|
||||
body: expectation.body,
|
||||
})
|
||||
expectation.response
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,6 +86,7 @@ impl DeepScript {
|
||||
url: format!("{}/transcriptions/{remote_id}/status", self.base_url),
|
||||
headers: vec![self.auth_header()],
|
||||
body: HttpBody::Empty,
|
||||
follow_redirects: true,
|
||||
};
|
||||
let resp = match self.transport.send(req).await {
|
||||
Ok(resp) => resp,
|
||||
@@ -115,6 +116,7 @@ impl DeepScript {
|
||||
url: format!("{}/transcriptions/{remote_id}", self.base_url),
|
||||
headers: vec![self.auth_header()],
|
||||
body: HttpBody::Empty,
|
||||
follow_redirects: true,
|
||||
};
|
||||
let resp = self.send(req).await?;
|
||||
match resp.status {
|
||||
@@ -199,12 +201,22 @@ impl Transcriber for DeepScript {
|
||||
value: "1".to_string(),
|
||||
});
|
||||
}
|
||||
if !opts.vocabulary.is_empty() {
|
||||
parts.push(Part::Text {
|
||||
name: "vocabulary".to_string(),
|
||||
// The documented format: "JSON array of custom words, or
|
||||
// comma-separated string."
|
||||
value: serde_json::to_string(&opts.vocabulary)
|
||||
.expect("Vec<String> always serializes"),
|
||||
});
|
||||
}
|
||||
|
||||
let req = HttpRequest {
|
||||
method: Method::Post,
|
||||
url: format!("{}/transcriptions", self.base_url),
|
||||
headers: vec![self.auth_header()],
|
||||
body: HttpBody::Multipart(parts),
|
||||
follow_redirects: true,
|
||||
};
|
||||
|
||||
let resp = self.send(req).await?;
|
||||
@@ -265,6 +277,7 @@ impl Transcriber for DeepScript {
|
||||
url: format!("{}/transcriptions/{remote_id}", self.base_url),
|
||||
headers: vec![self.auth_header()],
|
||||
body: HttpBody::Empty,
|
||||
follow_redirects: true,
|
||||
};
|
||||
let resp = self.send(req).await?;
|
||||
match resp.status {
|
||||
@@ -381,6 +394,7 @@ mod tests {
|
||||
language: language.to_string(),
|
||||
model: model.to_string(),
|
||||
single_speaker,
|
||||
vocabulary: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -435,6 +449,57 @@ mod tests {
|
||||
transport.assert_done();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn submit_sends_vocabulary_as_a_json_array_string() {
|
||||
let transport = Arc::new(FakeTransport::new());
|
||||
transport.expect(
|
||||
Method::Post,
|
||||
&format!("{BASE}/transcriptions"),
|
||||
202,
|
||||
r#"{"data":{"id":"job-voc","status":"queued","model":"premium","originalFileName":"mic.flac","createdOn":"2026-01-01T00:00:00Z"}}"#,
|
||||
);
|
||||
let ds = deep_script(&transport);
|
||||
let mut vocab_opts = opts("premium", "de", true);
|
||||
vocab_opts.vocabulary = vec!["Tschüss".to_string(), "Euvino".to_string()];
|
||||
|
||||
ds.submit(Path::new("mic.flac"), &vocab_opts).await.unwrap();
|
||||
|
||||
let requests = transport.requests();
|
||||
let HttpBody::Multipart(parts) = &requests[0].body else {
|
||||
panic!("expected multipart body");
|
||||
};
|
||||
assert!(parts.contains(&Part::Text {
|
||||
name: "vocabulary".to_string(),
|
||||
value: r#"["Tschüss","Euvino"]"#.to_string(),
|
||||
}));
|
||||
transport.assert_done();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn submit_omits_vocabulary_when_empty() {
|
||||
let transport = Arc::new(FakeTransport::new());
|
||||
transport.expect(
|
||||
Method::Post,
|
||||
&format!("{BASE}/transcriptions"),
|
||||
202,
|
||||
r#"{"data":{"id":"job-novoc","status":"queued","model":"premium","originalFileName":"mic.flac","createdOn":"2026-01-01T00:00:00Z"}}"#,
|
||||
);
|
||||
let ds = deep_script(&transport);
|
||||
|
||||
ds.submit(Path::new("mic.flac"), &opts("premium", "de", true))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let requests = transport.requests();
|
||||
let HttpBody::Multipart(parts) = &requests[0].body else {
|
||||
panic!("expected multipart body");
|
||||
};
|
||||
assert!(!parts
|
||||
.iter()
|
||||
.any(|p| matches!(p, Part::Text { name, .. } if name == "vocabulary")));
|
||||
transport.assert_done();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn submit_without_hint_for_output_track() {
|
||||
let transport = Arc::new(FakeTransport::new());
|
||||
|
||||
@@ -24,6 +24,9 @@ pub struct TranscribeOptions {
|
||||
/// the user) — the output track may have several, so this is left
|
||||
/// unset there.
|
||||
pub single_speaker: bool,
|
||||
/// Custom words/names to bias the transcription towards (DeepScript's
|
||||
/// `vocabulary` field); empty omits the field entirely.
|
||||
pub vocabulary: Vec<String>,
|
||||
}
|
||||
|
||||
/// Uploads an audio file to a remote speech-to-text service, waits for the
|
||||
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"version": "0.3.1",
|
||||
"pub_date": "2026-11-10T13:23:27Z",
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVUdGpRa1ZvalU2SURncUNMNDdEMzVWc3pESHpGdFhHUmJVZVEvOWIxeTZjWWVKaTYvZmRRb0NqK1lpNzB6UDlPSy9lVjkvN2xOWXFFSCs5aUJLdGZhNnV2N2ZaM2Q1ZFFRPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzk0MzE2OTgwCWZpbGU6R2VzcHLDpGNoc3Jla29yZGVyXzAuMy4xX3g2NC1zZXR1cC5leGUJdmVyc2lvbjowLjMuMQozYnFtdGxXQlNkcCtTWHRGdFRhOE9xNnhBeDVLdE16cEp6allUYzNZU1Y5Q3JaUlc3V2o4WjV2OWZRNFRVVFJ2WitJUTVxZ3U5WkU3Umx6SS9Sb1REdz09Cg==",
|
||||
"url": "https://gitea.euvino.eu/public/call-recorder/releases/download/v0.3.1/Gespraechsrekorder_0.3.1_x64-setup.exe"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds a signed release of Gesprächsrekorder into dist-release/<version>/:
|
||||
# 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
|
||||
# ui/package.json and leaves those changes for you to commit. Never tags or
|
||||
# publishes anything; see RELEASING.md.
|
||||
@@ -157,7 +157,7 @@ grep -qx "version = \"${VERSION}\"" "${CARGO_TOML}" || die "could not set the ve
|
||||
|
||||
# --- Build ------------------------------------------------------------------
|
||||
"${SCRIPT_DIR}/build-windows.sh"
|
||||
(cd "${REPO_ROOT}" && cargo tauri build --bundles deb appimage)
|
||||
(cd "${REPO_ROOT}" && cargo tauri build --bundles deb)
|
||||
|
||||
# --- Collect ----------------------------------------------------------------
|
||||
OUT="${REPO_ROOT}/dist-release/${VERSION}"
|
||||
@@ -183,7 +183,6 @@ collect() {
|
||||
}
|
||||
collect "${WINDOWS_BUNDLE}" "*_${VERSION}_x64-setup.exe"
|
||||
collect "${LINUX_BUNDLE}/deb" "*_${VERSION}_amd64.deb"
|
||||
collect "${LINUX_BUNDLE}/appimage" "*_${VERSION}_amd64.AppImage"
|
||||
|
||||
"${SCRIPT_DIR}/make-latest-json.sh" "${VERSION}" "${OUT}"
|
||||
jq -e . "${OUT}/latest.json" >/dev/null || die "latest.json is not valid JSON"
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
# Writes <dir>/latest.json, the update feed the app reads, from the signed
|
||||
# release artifacts in <dir>:
|
||||
# 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>/
|
||||
# (scripts/release.env).
|
||||
#
|
||||
@@ -38,7 +39,6 @@ signed_file() {
|
||||
}
|
||||
|
||||
WINDOWS="$(signed_file "*_${VERSION}_x64-setup.exe")"
|
||||
LINUX="$(signed_file "*_${VERSION}_amd64.AppImage")"
|
||||
|
||||
jq -n \
|
||||
--arg version "${VERSION}" \
|
||||
@@ -46,8 +46,6 @@ jq -n \
|
||||
--arg base "${RELEASE_BASE_URL}/releases/download/v${VERSION}" \
|
||||
--arg windows_file "$(basename "${WINDOWS}")" \
|
||||
--rawfile windows_sig "${WINDOWS}.sig" \
|
||||
--arg linux_file "$(basename "${LINUX}")" \
|
||||
--rawfile linux_sig "${LINUX}.sig" \
|
||||
'{
|
||||
version: $version,
|
||||
pub_date: $pub_date,
|
||||
@@ -55,10 +53,6 @@ jq -n \
|
||||
"windows-x86_64": {
|
||||
signature: ($windows_sig | gsub("\\s"; "")),
|
||||
url: "\($base)/\($windows_file | @uri)"
|
||||
},
|
||||
"linux-x86_64": {
|
||||
signature: ($linux_sig | gsub("\\s"; "")),
|
||||
url: "\($base)/\($linux_file | @uri)"
|
||||
}
|
||||
}
|
||||
}' >"${DIR}/latest.json"
|
||||
|
||||
+3
-7
@@ -6,13 +6,9 @@
|
||||
|
||||
RELEASE_BASE_URL="https://gitea.euvino.eu/public/call-recorder"
|
||||
|
||||
# Where the app looks for latest.json, tried in this order until one answers
|
||||
# with a release:
|
||||
# 1. latest.json as an asset of the newest release,
|
||||
# 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).
|
||||
# Where the app looks for latest.json: committed to the root of master.
|
||||
# Gitea 1.27.3 does not redirect releases/latest/download/<file> to a
|
||||
# release's assets, so that URL is not offered here. See RELEASING.md.
|
||||
UPDATE_JSON_URLS=(
|
||||
"${RELEASE_BASE_URL}/releases/latest/download/latest.json"
|
||||
"${RELEASE_BASE_URL}/raw/branch/master/latest.json"
|
||||
)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "call-recorder"
|
||||
version = "0.1.1"
|
||||
version = "0.4.0"
|
||||
description = "Gesprächsrekorder desktop app"
|
||||
edition = "2021"
|
||||
|
||||
@@ -27,3 +27,7 @@ tempfile = "3"
|
||||
recorder-core = { path = "../crates/core" }
|
||||
recorder-audio = { path = "../crates/audio" }
|
||||
tauri-plugin-updater = "2"
|
||||
tauri-plugin-opener = "2"
|
||||
tokio = { version = "1", features = ["sync"] }
|
||||
async-trait = "0.1"
|
||||
http-range = "0.1.6"
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
+62
-20
@@ -8,7 +8,6 @@
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use recorder_core::accounts::{self, Account};
|
||||
use recorder_core::call_view::{CallDetail, CallListItem};
|
||||
use recorder_core::capture::Devices;
|
||||
use recorder_core::model::CallId;
|
||||
@@ -20,10 +19,15 @@ use tauri_plugin_autostart::ManagerExt;
|
||||
|
||||
use crate::processing;
|
||||
use crate::state::{
|
||||
AppState, CallBrief, DeviceLevels, DiscardError, Ended, PendingPrompt, RecordingState,
|
||||
AppState, CallBrief, DeviceLevels, DiscardError, Ended, PendingPrompt, PreparedPlayback,
|
||||
RecordingState,
|
||||
};
|
||||
|
||||
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>;
|
||||
|
||||
@@ -33,6 +37,12 @@ struct CallEnded {
|
||||
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]
|
||||
pub fn get_settings(state: State<'_, AppState>) -> Settings {
|
||||
state.settings()
|
||||
@@ -50,9 +60,11 @@ pub fn save_settings(
|
||||
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]
|
||||
pub async fn set_api_key(app: AppHandle, service: Service, key: String) -> CmdResult<()> {
|
||||
reject_backend_service(service)?;
|
||||
blocking(app, move |app| {
|
||||
let secrets = &app.state::<AppState>().secrets;
|
||||
let key = key.trim();
|
||||
@@ -66,9 +78,11 @@ pub async fn set_api_key(app: AppHandle, service: Service, key: String) -> CmdRe
|
||||
.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]
|
||||
pub async fn has_api_key(app: AppHandle, service: Service) -> CmdResult<bool> {
|
||||
reject_backend_service(service)?;
|
||||
blocking(app, move |app| {
|
||||
let key = app.state::<AppState>().secrets.get(service);
|
||||
Ok(key.is_some_and(|key| !key.is_empty()))
|
||||
@@ -76,6 +90,15 @@ pub async fn has_api_key(app: AppHandle, service: Service) -> CmdResult<bool> {
|
||||
.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]
|
||||
pub async fn list_devices() -> CmdResult<Devices> {
|
||||
tauri::async_runtime::spawn_blocking(recorder_audio::list_devices)
|
||||
@@ -186,19 +209,23 @@ pub fn rename_call(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Mixes the call's two tracks into one file to play in the detail view
|
||||
/// (or reuses the cached mix); the main window plays it from the
|
||||
/// `playback` scheme ([`crate::playback`]).
|
||||
#[tauri::command]
|
||||
pub fn list_accounts() -> Vec<Account> {
|
||||
accounts::list()
|
||||
pub async fn prepare_playback(app: AppHandle, id: CallId) -> CmdResult<PreparedPlayback> {
|
||||
blocking(app, move |app| app.state::<AppState>().prepare_playback(id)).await
|
||||
}
|
||||
|
||||
/// Assigns a call to a customer account, or to none.
|
||||
/// The player is done with the mix of `lease`: it is removed from disk
|
||||
/// unless a newer player of the same call holds it.
|
||||
#[tauri::command]
|
||||
pub fn set_account(
|
||||
state: State<'_, AppState>,
|
||||
id: CallId,
|
||||
account_id: Option<String>,
|
||||
) -> CmdResult<()> {
|
||||
state.set_account(id, account_id.as_deref())
|
||||
pub async fn release_playback(app: AppHandle, id: CallId, lease: u64) -> CmdResult<()> {
|
||||
blocking(app, move |app| {
|
||||
app.state::<AppState>().release_playback(id, lease);
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Deletes a finished call's audio and row. Closes the prompt if no call
|
||||
@@ -214,7 +241,7 @@ pub async fn discard_call(app: AppHandle, id: CallId) -> CmdResult<()> {
|
||||
processing::delete_leftover_jobs(app, vec![id]);
|
||||
return Err(e.to_string());
|
||||
}
|
||||
Err(e @ DiscardError::Other(_)) => return Err(e.to_string()),
|
||||
Err(e) => return Err(e.to_string()),
|
||||
}
|
||||
prompt_queue_changed(app);
|
||||
Ok(())
|
||||
@@ -223,16 +250,17 @@ pub async fn discard_call(app: AppHandle, id: CallId) -> CmdResult<()> {
|
||||
}
|
||||
|
||||
/// Transkribieren in the end-of-call prompt: starts processing in the
|
||||
/// background and returns at once; the call leaves the prompt.
|
||||
/// background in the chosen `language` and returns at once; the call
|
||||
/// leaves the prompt.
|
||||
#[tauri::command]
|
||||
pub async fn transcribe_call(app: AppHandle, id: CallId) -> CmdResult<()> {
|
||||
blocking(app, move |app| processing::start(app, id, false)).await
|
||||
pub async fn transcribe_call(app: AppHandle, id: CallId, language: String) -> CmdResult<()> {
|
||||
blocking(app, move |app| processing::start(app, id, false, language)).await
|
||||
}
|
||||
|
||||
/// Processes a failed (or still undecided) call again.
|
||||
/// Processes a failed (or still undecided) call again, in `language`.
|
||||
#[tauri::command]
|
||||
pub async fn retry_call(app: AppHandle, id: CallId) -> CmdResult<()> {
|
||||
blocking(app, move |app| processing::start(app, id, true)).await
|
||||
pub async fn retry_call(app: AppHandle, id: CallId, language: String) -> CmdResult<()> {
|
||||
blocking(app, move |app| processing::start(app, id, true, language)).await
|
||||
}
|
||||
|
||||
/// After a call left the prompt queue: hides the prompt if no call waits
|
||||
@@ -428,3 +456,17 @@ where
|
||||
.await
|
||||
.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(()));
|
||||
}
|
||||
}
|
||||
|
||||
+54
-4
@@ -1,6 +1,9 @@
|
||||
mod backend;
|
||||
mod commands;
|
||||
mod detection;
|
||||
mod playback;
|
||||
mod processing;
|
||||
mod retention;
|
||||
mod state;
|
||||
mod tray;
|
||||
mod updater;
|
||||
@@ -13,7 +16,7 @@ use tauri_plugin_autostart::MacosLauncher;
|
||||
use tauri_plugin_log::{RotationStrategy, Target, TargetKind, TimezoneStrategy};
|
||||
|
||||
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
|
||||
/// then stays hidden in the tray.
|
||||
@@ -34,6 +37,29 @@ pub fn run() {
|
||||
))
|
||||
.plugin(tauri_plugin_notification::init())
|
||||
.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(),
|
||||
)
|
||||
// A call's mix for the player: only for the main window, whatever
|
||||
// other webviews (the remote backend login) ask for.
|
||||
.register_asynchronous_uri_scheme_protocol(playback::SCHEME, |ctx, request, responder| {
|
||||
let webview = ctx.webview_label().to_string();
|
||||
let dir = ctx
|
||||
.app_handle()
|
||||
.try_state::<AppState>()
|
||||
.map(|state| state.playback_dir().to_path_buf());
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
responder.respond(match dir {
|
||||
Some(dir) => playback::respond(&webview, &request, &dir),
|
||||
None => playback::unavailable(),
|
||||
})
|
||||
});
|
||||
})
|
||||
.setup(|app| {
|
||||
// Release builds log to a file in the app log directory (on
|
||||
// Windows %LOCALAPPDATA%\eu.euvino.callrecorder\logs), debug
|
||||
@@ -63,6 +89,8 @@ pub fn run() {
|
||||
|
||||
let data_dir = app.path().app_data_dir()?;
|
||||
let config_dir = app.path().app_config_dir()?;
|
||||
// Served to the main window only, by the `playback` scheme.
|
||||
let playback_dir = app.path().app_cache_dir()?.join("playback");
|
||||
std::fs::create_dir_all(&data_dir)?;
|
||||
let store = Store::open(&data_dir.join("calls.sqlite"))?;
|
||||
let recovery = pipeline::recover_on_startup(&store)?;
|
||||
@@ -73,6 +101,7 @@ pub fn run() {
|
||||
Box::new(KeyringSecrets),
|
||||
config_dir.join("settings.json"),
|
||||
data_dir.join("recordings"),
|
||||
playback_dir,
|
||||
);
|
||||
let leftover_jobs = state.store.calls_with_remote_jobs().unwrap_or_else(|e| {
|
||||
log::error!("could not read leftover remote jobs: {e}");
|
||||
@@ -83,10 +112,16 @@ pub fn run() {
|
||||
&config_dir.join("last-version"),
|
||||
&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.
|
||||
processing::clear_upload_dir(app.handle());
|
||||
// Before any window can ask for a mix.
|
||||
state.clear_playback_cache();
|
||||
app.manage(state);
|
||||
app.manage(PendingUpdate::default());
|
||||
app.manage(UpdateSchedule::default());
|
||||
app.manage(backend::LoginWaiters::default());
|
||||
// Windows are created here (`create: false` in tauri.conf.json)
|
||||
// instead of by Tauri before `setup` runs: their webviews load
|
||||
// immediately and invoke commands (list_calls, get_recording_state,
|
||||
@@ -95,6 +130,9 @@ pub fn run() {
|
||||
create_windows(app.handle())?;
|
||||
commands::apply_autostart(app.handle(), autostart);
|
||||
processing::delete_leftover_jobs(app.handle(), leftover_jobs);
|
||||
// After the startup recovery and the cache clears, with the
|
||||
// windows there to hear what it deleted.
|
||||
retention::spawn(app.handle().clone());
|
||||
|
||||
tray::create(app.handle())?;
|
||||
detection::spawn(app.handle().clone());
|
||||
@@ -108,13 +146,17 @@ pub fn run() {
|
||||
})
|
||||
.on_window_event(|window, event| {
|
||||
// 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 window.label() != backend::LOGIN_WINDOW {
|
||||
api.prevent_close();
|
||||
let _ = window.hide();
|
||||
}
|
||||
}
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
commands::get_app_version,
|
||||
commands::get_settings,
|
||||
commands::save_settings,
|
||||
commands::set_api_key,
|
||||
@@ -137,10 +179,18 @@ pub fn run() {
|
||||
commands::merge_speakers,
|
||||
commands::unmerge_speaker,
|
||||
commands::rename_call,
|
||||
commands::list_accounts,
|
||||
commands::set_account,
|
||||
commands::prepare_playback,
|
||||
commands::release_playback,
|
||||
backend::backend_server,
|
||||
backend::backend_status,
|
||||
backend::backend_login,
|
||||
backend::backend_logout,
|
||||
backend::open_backend_keys_page,
|
||||
backend::upload_transcript,
|
||||
updater::get_update,
|
||||
updater::install_update,
|
||||
updater::check_for_update_now,
|
||||
updater::can_self_update,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while building tauri application");
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
//! The `playback` URI scheme: serves a call's cached mix
|
||||
//! ([`recorder_core::playback`]) to the main window, and to no other
|
||||
//! webview — the backend-login window shows a remote page, which must
|
||||
//! never read customer audio.
|
||||
//!
|
||||
//! The URL carries only the call id: `playback://localhost/<id>` on Linux
|
||||
//! and macOS, `http://playback.localhost/<id>` on Windows (what the UI's
|
||||
//! `convertFileSrc(id, 'playback')` builds). Range requests are answered
|
||||
//! so the player can seek without loading the whole file.
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{self, ErrorKind, Read, Seek, SeekFrom};
|
||||
use std::path::Path;
|
||||
|
||||
use http_range::HttpRange;
|
||||
use recorder_core::model::CallId;
|
||||
use recorder_core::playback::cache_path;
|
||||
use tauri::http::header::{
|
||||
ACCEPT_RANGES, ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_EXPOSE_HEADERS, CACHE_CONTROL,
|
||||
CONTENT_LENGTH, CONTENT_RANGE, CONTENT_TYPE, RANGE,
|
||||
};
|
||||
use tauri::http::{response, Method, Request, Response, StatusCode};
|
||||
|
||||
/// The scheme's name (see the module docs for its URLs).
|
||||
pub const SCHEME: &str = "playback";
|
||||
/// The only webview the scheme answers.
|
||||
pub const PLAYER_WEBVIEW: &str = "main";
|
||||
/// The most bytes one range response carries (like Tauri's asset protocol).
|
||||
const MAX_RANGE_LEN: u64 = 1024 * 1024;
|
||||
|
||||
/// Answers `request` from webview `webview` with call `<id>`'s mix in the
|
||||
/// playback directory `dir`: 403 for any webview but the main window, 404
|
||||
/// for anything but a plain numeric id or a mix that is not there, 206 for
|
||||
/// a satisfiable range (at most [`MAX_RANGE_LEN`] bytes), 416 otherwise.
|
||||
pub fn respond(webview: &str, request: &Request<Vec<u8>>, dir: &Path) -> Response<Vec<u8>> {
|
||||
if webview != PLAYER_WEBVIEW {
|
||||
log::warn!("playback refused to webview {webview}");
|
||||
return empty(StatusCode::FORBIDDEN);
|
||||
}
|
||||
let method = request.method();
|
||||
if method != Method::GET && method != Method::HEAD {
|
||||
return empty(StatusCode::METHOD_NOT_ALLOWED);
|
||||
}
|
||||
let Some(id) = call_id(request.uri().path()) else {
|
||||
return empty(StatusCode::NOT_FOUND);
|
||||
};
|
||||
let range = request
|
||||
.headers()
|
||||
.get(RANGE)
|
||||
.map(|value| value.to_str().unwrap_or_default());
|
||||
match serve(&cache_path(dir, id), range, method == Method::HEAD) {
|
||||
Ok(response) => response,
|
||||
Err(e) if e.kind() == ErrorKind::NotFound => empty(StatusCode::NOT_FOUND),
|
||||
Err(e) => {
|
||||
log::error!("call {id}: could not serve the playback file: {e}");
|
||||
empty(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The answer while the app state is not set up yet (no window can play
|
||||
/// before it is, so this is never expected).
|
||||
pub fn unavailable() -> Response<Vec<u8>> {
|
||||
empty(StatusCode::SERVICE_UNAVAILABLE)
|
||||
}
|
||||
|
||||
/// The call id of a request path: exactly `/<digits>`.
|
||||
fn call_id(path: &str) -> Option<CallId> {
|
||||
let digits = path.strip_prefix('/')?;
|
||||
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
digits.parse().ok()
|
||||
}
|
||||
|
||||
fn serve(path: &Path, range: Option<&str>, head: bool) -> io::Result<Response<Vec<u8>>> {
|
||||
let mut file = File::open(path)?;
|
||||
let len = file.metadata()?.len();
|
||||
let builder = headers();
|
||||
let Some(range) = range else {
|
||||
let mut body = Vec::new();
|
||||
if !head {
|
||||
file.read_to_end(&mut body)?;
|
||||
}
|
||||
return Ok(build(builder.header(CONTENT_LENGTH, len), body));
|
||||
};
|
||||
// A media element asks for one range at a time; of several, the first.
|
||||
let Some(range) = HttpRange::parse(range, len)
|
||||
.ok()
|
||||
.and_then(|r| r.first().copied())
|
||||
else {
|
||||
return Ok(build(
|
||||
builder
|
||||
.status(StatusCode::RANGE_NOT_SATISFIABLE)
|
||||
.header(CONTENT_RANGE, format!("bytes */{len}")),
|
||||
Vec::new(),
|
||||
));
|
||||
};
|
||||
let start = range.start;
|
||||
let count = range.length.min(MAX_RANGE_LEN);
|
||||
let mut body = Vec::new();
|
||||
if !head {
|
||||
file.seek(SeekFrom::Start(start))?;
|
||||
file.take(count).read_to_end(&mut body)?;
|
||||
}
|
||||
Ok(build(
|
||||
builder
|
||||
.status(StatusCode::PARTIAL_CONTENT)
|
||||
.header(
|
||||
CONTENT_RANGE,
|
||||
format!("bytes {start}-{}/{len}", start + count - 1),
|
||||
)
|
||||
.header(CONTENT_LENGTH, count),
|
||||
body,
|
||||
))
|
||||
}
|
||||
|
||||
/// Headers of every answer that carries the mix. Any origin may read it:
|
||||
/// only the main window's own page can reach the scheme at all (the
|
||||
/// webview check above), and on Linux it fetches the mix cross-origin.
|
||||
fn headers() -> response::Builder {
|
||||
Response::builder()
|
||||
.header(CONTENT_TYPE, "audio/wav")
|
||||
.header(CACHE_CONTROL, "no-store")
|
||||
.header(ACCEPT_RANGES, "bytes")
|
||||
.header(ACCESS_CONTROL_ALLOW_ORIGIN, "*")
|
||||
.header(ACCESS_CONTROL_EXPOSE_HEADERS, "content-range")
|
||||
}
|
||||
|
||||
fn build(builder: response::Builder, body: Vec<u8>) -> Response<Vec<u8>> {
|
||||
builder
|
||||
.body(body)
|
||||
.unwrap_or_else(|_| empty(StatusCode::INTERNAL_SERVER_ERROR))
|
||||
}
|
||||
|
||||
fn empty(status: StatusCode) -> Response<Vec<u8>> {
|
||||
let mut response = Response::new(Vec::new());
|
||||
*response.status_mut() = status;
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(CACHE_CONTROL, "no-store".parse().unwrap());
|
||||
response
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::fs;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A playback directory with a 10-byte "mix" for call 7.
|
||||
fn dir() -> tempfile::TempDir {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
fs::write(cache_path(dir.path(), 7), b"0123456789").unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn get(uri: &str, range: Option<&str>) -> Request<Vec<u8>> {
|
||||
let mut builder = Request::builder().uri(uri);
|
||||
if let Some(range) = range {
|
||||
builder = builder.header(RANGE, range);
|
||||
}
|
||||
builder.body(Vec::new()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_main_window_gets_the_mix() {
|
||||
let dir = dir();
|
||||
let request = get("playback://localhost/7", None);
|
||||
for webview in ["backend-login", "prompt", "recorder", "", "Main"] {
|
||||
let response = respond(webview, &request, dir.path());
|
||||
assert_eq!(response.status(), StatusCode::FORBIDDEN, "{webview}");
|
||||
assert!(response.body().is_empty());
|
||||
}
|
||||
|
||||
let response = respond("main", &request, dir.path());
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.body(), b"0123456789");
|
||||
assert_eq!(response.headers()[CONTENT_TYPE], "audio/wav");
|
||||
assert_eq!(response.headers()[CACHE_CONTROL], "no-store");
|
||||
assert_eq!(response.headers()[CONTENT_LENGTH], "10");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_platform_url_forms_name_the_call() {
|
||||
let dir = dir();
|
||||
for uri in ["playback://localhost/7", "http://playback.localhost/7"] {
|
||||
let response = respond("main", &get(uri, None), dir.path());
|
||||
assert_eq!(response.status(), StatusCode::OK, "{uri}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_but_a_numeric_call_id_is_served() {
|
||||
let dir = dir();
|
||||
fs::write(dir.path().join("secret.wav"), b"x").unwrap();
|
||||
fs::write(dir.path().join("7.wav.part"), b"x").unwrap();
|
||||
for path in [
|
||||
"/",
|
||||
"/7.wav",
|
||||
"/secret",
|
||||
"/../7",
|
||||
"/%2e%2e%2f7",
|
||||
"/7/",
|
||||
"/7.wav.part",
|
||||
"/-7",
|
||||
"/+7",
|
||||
"/%EF%BC%97",
|
||||
"/99999999999999999999999",
|
||||
"/8",
|
||||
] {
|
||||
let request = get(&format!("playback://localhost{path}"), None);
|
||||
let response = respond("main", &request, dir.path());
|
||||
assert_eq!(response.status(), StatusCode::NOT_FOUND, "{path}");
|
||||
}
|
||||
assert_eq!(call_id("/7"), Some(7));
|
||||
assert_eq!(call_id("/0012"), Some(12));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_is_served_partially() {
|
||||
let dir = dir();
|
||||
let response = respond(
|
||||
"main",
|
||||
&get("playback://localhost/7", Some("bytes=2-5")),
|
||||
dir.path(),
|
||||
);
|
||||
assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT);
|
||||
assert_eq!(response.body(), b"2345");
|
||||
assert_eq!(response.headers()[CONTENT_RANGE], "bytes 2-5/10");
|
||||
assert_eq!(response.headers()[CONTENT_LENGTH], "4");
|
||||
|
||||
let open_ended = respond(
|
||||
"main",
|
||||
&get("playback://localhost/7", Some("bytes=8-")),
|
||||
dir.path(),
|
||||
);
|
||||
assert_eq!(open_ended.body(), b"89");
|
||||
assert_eq!(open_ended.headers()[CONTENT_RANGE], "bytes 8-9/10");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_beyond_the_end_is_not_satisfiable() {
|
||||
let dir = dir();
|
||||
let response = respond(
|
||||
"main",
|
||||
&get("playback://localhost/7", Some("bytes=20-30")),
|
||||
dir.path(),
|
||||
);
|
||||
assert_eq!(response.status(), StatusCode::RANGE_NOT_SATISFIABLE);
|
||||
assert_eq!(response.headers()[CONTENT_RANGE], "bytes */10");
|
||||
assert!(response.body().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_range_is_cut_to_the_maximum() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let len = MAX_RANGE_LEN as usize * 2 + 3;
|
||||
fs::write(cache_path(dir.path(), 1), vec![1u8; len]).unwrap();
|
||||
let response = respond(
|
||||
"main",
|
||||
&get("playback://localhost/1", Some("bytes=1-")),
|
||||
dir.path(),
|
||||
);
|
||||
assert_eq!(response.body().len(), MAX_RANGE_LEN as usize);
|
||||
assert_eq!(
|
||||
response.headers()[CONTENT_RANGE],
|
||||
format!("bytes 1-{}/{len}", MAX_RANGE_LEN).as_str()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn head_has_no_body_and_other_methods_are_refused() {
|
||||
let dir = dir();
|
||||
let head = Request::builder()
|
||||
.method(Method::HEAD)
|
||||
.uri("playback://localhost/7")
|
||||
.body(Vec::new())
|
||||
.unwrap();
|
||||
let response = respond("main", &head, dir.path());
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.headers()[CONTENT_LENGTH], "10");
|
||||
assert!(response.body().is_empty());
|
||||
|
||||
let post = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri("playback://localhost/7")
|
||||
.body(Vec::new())
|
||||
.unwrap();
|
||||
let response = respond("main", &post, dir.path());
|
||||
assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ use std::path::PathBuf;
|
||||
use recorder_core::model::{CallId, CallStatus};
|
||||
use recorder_core::pipeline::{self, PipelineOptions};
|
||||
use recorder_core::secrets::Service;
|
||||
use recorder_core::settings::check_call_language;
|
||||
use recorder_core::transcribe::deepscript::DeepScript;
|
||||
use recorder_core::transcribe::TranscribeError;
|
||||
use serde::Serialize;
|
||||
@@ -57,13 +58,22 @@ impl Drop for Claim {
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts processing call `id` in the background and returns at once; the
|
||||
/// call leaves the end-of-call prompt. `retry` also allows failed calls.
|
||||
/// Without a DeepScript key nothing starts: the call is marked failed and
|
||||
/// the error returned. Reads the keyring, so call it off the UI thread.
|
||||
pub fn start(app: &AppHandle, id: CallId, retry: bool) -> Result<(), String> {
|
||||
/// Starts processing call `id` in `language` in the background and returns
|
||||
/// at once; the call leaves the end-of-call prompt. `retry` also allows
|
||||
/// failed calls. The language is stored with the call and remembered for
|
||||
/// the next one; one outside `CALL_LANGUAGES` is refused before anything
|
||||
/// changes. Without a DeepScript key nothing starts: the call is marked
|
||||
/// failed and the error returned. Reads the keyring, so call it off the UI
|
||||
/// thread.
|
||||
pub fn start(app: &AppHandle, id: CallId, retry: bool, language: String) -> Result<(), String> {
|
||||
check_call_language(&language)?;
|
||||
let claim = Claim::take(app, id, retry)?;
|
||||
let state = app.state::<AppState>();
|
||||
state
|
||||
.store
|
||||
.set_language(id, &language)
|
||||
.map_err(|e| format!("Interner Fehler: {e}"))?;
|
||||
state.remember_language(&language);
|
||||
|
||||
let Some(key) = deepscript_key(&state) else {
|
||||
let msg = TranscribeError::MissingKey.user_message();
|
||||
@@ -76,8 +86,9 @@ pub fn start(app: &AppHandle, id: CallId, retry: bool) -> Result<(), String> {
|
||||
let work_dir = upload_dir(app)?;
|
||||
let settings = state.settings();
|
||||
let opts = PipelineOptions {
|
||||
language: settings.language,
|
||||
language,
|
||||
deepscript_model: settings.deepscript_model,
|
||||
vocabulary: settings.vocabulary,
|
||||
};
|
||||
// A fresh client per run, so a key changed in the settings applies to
|
||||
// the next run.
|
||||
|
||||
@@ -0,0 +1,504 @@
|
||||
//! The scheduled retention job: once at startup and then every hour (by the
|
||||
//! wall clock, so also right after standby) it deletes what the retention
|
||||
//! period (`retention_days` in the settings, read anew for every pass) has
|
||||
//! run out for, as planned by [`plan_retention`]: the audio of transcribed
|
||||
//! calls N days after the transcription (transcript, title, speaker names
|
||||
//! and merges, CRM upload stay), and undecided recordings with their row N
|
||||
//! days after the call ended. Failed calls keep their audio. A call that is
|
||||
//! in use (recorded, processed, uploaded, played, or its DeepScript jobs
|
||||
//! still on record) is skipped and tried again by the next pass; errors are
|
||||
//! logged, never fatal.
|
||||
|
||||
use std::panic::{self, AssertUnwindSafe};
|
||||
use std::slice;
|
||||
use std::thread;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use chrono::{DateTime, Local};
|
||||
use recorder_core::model::{Call, CallId};
|
||||
use recorder_core::retention::{plan_retention, RetentionAction};
|
||||
use tauri::{AppHandle, Manager};
|
||||
|
||||
use crate::commands;
|
||||
use crate::processing;
|
||||
use crate::state::{AppState, AudioDeleteError, DiscardError};
|
||||
|
||||
/// How often a pass runs.
|
||||
const PASS_INTERVAL: Duration = Duration::from_secs(60 * 60);
|
||||
/// How often the job looks at the wall clock to see whether a pass is due.
|
||||
const WAKE_INTERVAL: Duration = Duration::from_secs(60);
|
||||
|
||||
/// What one pass did, per call.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub struct PassReport {
|
||||
pub audio_deleted: Vec<CallId>,
|
||||
pub calls_deleted: Vec<CallId>,
|
||||
/// In use or changed since planned; tried again by the next pass.
|
||||
pub skipped: Vec<CallId>,
|
||||
/// Those of `skipped` whose DeepScript jobs are still on record.
|
||||
pub cleanup_pending: Vec<CallId>,
|
||||
pub failed: Vec<CallId>,
|
||||
}
|
||||
|
||||
impl PassReport {
|
||||
/// The calls whose row or audio changed.
|
||||
fn changed(&self) -> impl Iterator<Item = CallId> + '_ {
|
||||
self.audio_deleted
|
||||
.iter()
|
||||
.chain(&self.calls_deleted)
|
||||
.copied()
|
||||
}
|
||||
|
||||
fn is_empty(&self) -> bool {
|
||||
self == &PassReport::default()
|
||||
}
|
||||
|
||||
/// "2 audio deleted, 1 call deleted, 1 skipped, 0 failed" for the log.
|
||||
fn summary(&self) -> String {
|
||||
let calls = self.calls_deleted.len();
|
||||
format!(
|
||||
"{} audio deleted, {calls} {} deleted, {} skipped, {} failed",
|
||||
self.audio_deleted.len(),
|
||||
if calls == 1 { "call" } else { "calls" },
|
||||
self.skipped.len(),
|
||||
self.failed.len()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the job: a pass right away and then every [`PASS_INTERVAL`].
|
||||
/// Call once the startup recovery, the cache clears and the windows are
|
||||
/// done. One thread runs every pass, so two never run at once.
|
||||
pub fn spawn(app: AppHandle) {
|
||||
let started = thread::Builder::new()
|
||||
.name("retention".into())
|
||||
.spawn(move || {
|
||||
let mut last_pass = None;
|
||||
loop {
|
||||
let now = SystemTime::now();
|
||||
if pass_due(last_pass, now) {
|
||||
last_pass = Some(now);
|
||||
// A panic must not end the job: the next pass retries.
|
||||
if panic::catch_unwind(AssertUnwindSafe(|| run(&app))).is_err() {
|
||||
log::error!("retention: the pass panicked");
|
||||
}
|
||||
}
|
||||
thread::sleep(WAKE_INTERVAL);
|
||||
}
|
||||
});
|
||||
if let Err(e) = started {
|
||||
log::error!("retention: could not start the job: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// One pass, and tells the UI what changed: `call-updated` per call (the
|
||||
/// list and an open detail refresh; the player shows the retention note),
|
||||
/// and the prompt, if an undecided call it waits for was deleted.
|
||||
fn run(app: &AppHandle) {
|
||||
let report = run_pass(&app.state::<AppState>(), Local::now());
|
||||
for id in report.changed() {
|
||||
processing::emit_updated(app, id);
|
||||
}
|
||||
if !report.calls_deleted.is_empty() {
|
||||
commands::prompt_queue_changed(app);
|
||||
}
|
||||
// As "Verwerfen" does: once their jobs are gone, a later pass can
|
||||
// delete them.
|
||||
processing::delete_leftover_jobs(app, report.cleanup_pending.clone());
|
||||
if !report.is_empty() {
|
||||
log::info!("retention: {}", report.summary());
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs one pass over all calls as of `now`, with the retention period
|
||||
/// currently set.
|
||||
pub fn run_pass(state: &AppState, now: DateTime<Local>) -> PassReport {
|
||||
let calls = match state.store.list_calls() {
|
||||
Ok(calls) => calls,
|
||||
Err(e) => {
|
||||
log::error!("retention: could not list the calls: {e}");
|
||||
return PassReport::default();
|
||||
}
|
||||
};
|
||||
let retention_days = state.settings().retention_days;
|
||||
let plan = plan_retention(&calls, now, retention_days);
|
||||
execute(state, &plan, now, retention_days)
|
||||
}
|
||||
|
||||
/// Carries out `plan`, made as of `now` for `retention_days`. Each call is
|
||||
/// planned again from its row as it is when the action runs, while nothing
|
||||
/// else can take it: a call that changed since (e.g. a "Transkribieren"
|
||||
/// that failed meanwhile, so it keeps its audio) is skipped. A call deleted
|
||||
/// meanwhile is ignored.
|
||||
fn execute(
|
||||
state: &AppState,
|
||||
plan: &[RetentionAction],
|
||||
now: DateTime<Local>,
|
||||
retention_days: u32,
|
||||
) -> PassReport {
|
||||
let mut report = PassReport::default();
|
||||
for &action in plan {
|
||||
let still_planned =
|
||||
|call: &Call| plan_retention(slice::from_ref(call), now, retention_days) == [action];
|
||||
match action {
|
||||
RetentionAction::DeleteAudio(id) => match state.delete_audio(id, still_planned) {
|
||||
Ok(()) => report.audio_deleted.push(id),
|
||||
Err(AudioDeleteError::Busy(why)) => {
|
||||
log::info!("retention: call {id}: audio kept for now: {why}");
|
||||
report.skipped.push(id);
|
||||
}
|
||||
Err(AudioDeleteError::NotFound) => {
|
||||
log::info!("retention: call {id}: already deleted");
|
||||
}
|
||||
Err(AudioDeleteError::Failed(e)) => {
|
||||
log::error!("retention: call {id}: audio not deleted: {e}");
|
||||
report.failed.push(id);
|
||||
}
|
||||
},
|
||||
// The same path, and refusals, as "Verwerfen".
|
||||
RetentionAction::DeleteCall(id) => match state.discard_call_if(id, still_planned) {
|
||||
Ok(_) => report.calls_deleted.push(id),
|
||||
Err(e @ DiscardError::Busy(_)) => {
|
||||
log::info!("retention: call {id}: kept for now: {e}");
|
||||
report.skipped.push(id);
|
||||
}
|
||||
Err(e @ DiscardError::CleanupPending) => {
|
||||
log::info!("retention: call {id}: kept for now: {e}");
|
||||
report.skipped.push(id);
|
||||
report.cleanup_pending.push(id);
|
||||
}
|
||||
Err(DiscardError::NotFound) => {
|
||||
log::info!("retention: call {id}: already deleted");
|
||||
}
|
||||
Err(DiscardError::Other(e)) => {
|
||||
log::error!("retention: call {id}: not deleted: {e}");
|
||||
report.failed.push(id);
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
report
|
||||
}
|
||||
|
||||
/// Whether the next pass is due at `now`, given when the last one started
|
||||
/// (`None`: none yet). Uses the wall clock, which keeps running in standby;
|
||||
/// a clock that went back makes the pass due.
|
||||
fn pass_due(last: Option<SystemTime>, now: SystemTime) -> bool {
|
||||
let Some(last) = last else {
|
||||
return true;
|
||||
};
|
||||
now.duration_since(last)
|
||||
.map_or(true, |elapsed| elapsed >= PASS_INTERVAL)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use chrono::Duration as Days;
|
||||
use recorder_core::model::CallStatus;
|
||||
use recorder_core::secrets::MemorySecrets;
|
||||
use recorder_core::store::Store;
|
||||
|
||||
use super::*;
|
||||
|
||||
struct Fixture {
|
||||
state: AppState,
|
||||
dir: tempfile::TempDir,
|
||||
}
|
||||
|
||||
fn fixture() -> Fixture {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let state = AppState::new(
|
||||
Store::open_in_memory().unwrap(),
|
||||
Box::new(MemorySecrets::default()),
|
||||
dir.path().join("settings.json"),
|
||||
dir.path().join("recordings"),
|
||||
dir.path().join("playback"),
|
||||
);
|
||||
Fixture { state, dir }
|
||||
}
|
||||
|
||||
/// A call with both track files that ended `ended_days_ago` and, if
|
||||
/// `transcribed_days_ago` is given, was transcribed then (status
|
||||
/// `Done`); otherwise it awaits the decision.
|
||||
fn call(
|
||||
f: &Fixture,
|
||||
name: &str,
|
||||
now: DateTime<Local>,
|
||||
ended_days_ago: i64,
|
||||
transcribed_days_ago: Option<i64>,
|
||||
) -> CallId {
|
||||
let mic = f.dir.path().join(format!("{name}-mic.wav"));
|
||||
let out = f.dir.path().join(format!("{name}-out.wav"));
|
||||
fs::write(&mic, b"mic").unwrap();
|
||||
fs::write(&out, b"out").unwrap();
|
||||
let store = &f.state.store;
|
||||
let ended = now - Days::days(ended_days_ago);
|
||||
let id = store
|
||||
.create_call("Microsoft Teams", ended - Days::minutes(5), &mic, &out)
|
||||
.unwrap();
|
||||
store.finish_recording(id, ended, false).unwrap();
|
||||
if let Some(days) = transcribed_days_ago {
|
||||
store.set_status(id, CallStatus::Done, None).unwrap();
|
||||
store.mark_transcribed(id, now - Days::days(days)).unwrap();
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
fn tracks(f: &Fixture, id: CallId) -> [PathBuf; 2] {
|
||||
let call = f.state.store.get_call(id).unwrap().unwrap();
|
||||
[call.mic_path, call.out_path]
|
||||
}
|
||||
|
||||
fn has_audio(f: &Fixture, id: CallId) -> bool {
|
||||
let call = f.state.store.get_call(id).unwrap().unwrap();
|
||||
!call.audio_deleted && tracks(f, id).iter().all(|p| p.exists())
|
||||
}
|
||||
|
||||
fn sorted(mut ids: Vec<CallId>) -> Vec<CallId> {
|
||||
ids.sort();
|
||||
ids
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pass_does_exactly_what_the_plan_says_and_skips_calls_in_use() {
|
||||
let f = fixture();
|
||||
let now = Local::now();
|
||||
let done_old = call(&f, "done-old", now, 9, Some(8));
|
||||
let done_new = call(&f, "done-new", now, 3, Some(2));
|
||||
let undecided_old = call(&f, "undecided-old", now, 8, None);
|
||||
let undecided_new = call(&f, "undecided-new", now, 6, None);
|
||||
let failed_old = call(&f, "failed-old", now, 30, None);
|
||||
f.state
|
||||
.store
|
||||
.set_status(failed_old, CallStatus::Failed, Some("Fehler"))
|
||||
.unwrap();
|
||||
let uploading = call(&f, "uploading", now, 9, Some(8));
|
||||
let upload = f.state.claim_upload(uploading).unwrap();
|
||||
// Its DeepScript jobs are still on record: not deleted yet.
|
||||
let cleanup = call(&f, "cleanup", now, 8, None);
|
||||
f.state
|
||||
.store
|
||||
.record_remote_job(cleanup, "mic", "job-1")
|
||||
.unwrap();
|
||||
let undecided_old_tracks = tracks(&f, undecided_old);
|
||||
let store = &f.state.store;
|
||||
store.set_speaker_name(done_old, "me", "Hauke").unwrap();
|
||||
store
|
||||
.set_speaker_merge(done_old, "remote:2", "remote:1")
|
||||
.unwrap();
|
||||
store.set_title(done_old, Some("Bestellung")).unwrap();
|
||||
|
||||
let report = run_pass(&f.state, now);
|
||||
|
||||
assert_eq!(
|
||||
PassReport {
|
||||
audio_deleted: sorted(report.audio_deleted),
|
||||
calls_deleted: report.calls_deleted,
|
||||
skipped: sorted(report.skipped),
|
||||
cleanup_pending: report.cleanup_pending,
|
||||
failed: report.failed,
|
||||
},
|
||||
PassReport {
|
||||
audio_deleted: vec![done_old],
|
||||
calls_deleted: vec![undecided_old],
|
||||
skipped: sorted(vec![uploading, cleanup]),
|
||||
cleanup_pending: vec![cleanup],
|
||||
failed: vec![],
|
||||
}
|
||||
);
|
||||
assert!(!has_audio(&f, done_old));
|
||||
let kept = store.get_call(done_old).unwrap().unwrap();
|
||||
assert_eq!(kept.title.as_deref(), Some("Bestellung"));
|
||||
assert_eq!(
|
||||
store
|
||||
.speaker_names(done_old)
|
||||
.unwrap()
|
||||
.get("me")
|
||||
.map(String::as_str),
|
||||
Some("Hauke")
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.speaker_merges(done_old)
|
||||
.unwrap()
|
||||
.get("remote:2")
|
||||
.map(String::as_str),
|
||||
Some("remote:1")
|
||||
);
|
||||
assert_eq!(f.state.store.get_call(undecided_old).unwrap(), None);
|
||||
assert!(undecided_old_tracks.iter().all(|p| !p.exists()));
|
||||
for kept in [done_new, undecided_new, failed_old, uploading, cleanup] {
|
||||
assert!(has_audio(&f, kept), "call {kept} keeps its audio");
|
||||
}
|
||||
assert_eq!(f.state.store.remote_jobs(cleanup).unwrap().len(), 1);
|
||||
|
||||
// The next pass tries the skipped call again; nothing is done twice.
|
||||
drop(upload);
|
||||
let report = run_pass(&f.state, now);
|
||||
assert_eq!(report.audio_deleted, vec![uploading]);
|
||||
assert_eq!(report.calls_deleted, Vec::<CallId>::new());
|
||||
assert_eq!(report.skipped, vec![cleanup]);
|
||||
assert!(!has_audio(&f, uploading));
|
||||
}
|
||||
|
||||
/// The plan for the calls as they are now, with 7 days.
|
||||
fn plan(f: &Fixture, now: DateTime<Local>) -> Vec<RetentionAction> {
|
||||
plan_retention(&f.state.store.list_calls().unwrap(), now, 7)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_undecided_call_that_changed_after_planning_is_kept() {
|
||||
let f = fixture();
|
||||
let now = Local::now();
|
||||
let failed = call(&f, "failed", now, 8, None);
|
||||
let processing = call(&f, "processing", now, 8, None);
|
||||
let transcribed = call(&f, "transcribed", now, 8, None);
|
||||
let plan = plan(&f, now);
|
||||
assert_eq!(plan.len(), 3);
|
||||
|
||||
// "Transkribieren" without a key marks the call failed (and lets go
|
||||
// of it) between planning and the delete.
|
||||
let store = &f.state.store;
|
||||
store
|
||||
.set_status(failed, CallStatus::Failed, Some("Kein API-Schlüssel"))
|
||||
.unwrap();
|
||||
store
|
||||
.set_status(processing, CallStatus::Processing, None)
|
||||
.unwrap();
|
||||
store
|
||||
.set_status(transcribed, CallStatus::Done, None)
|
||||
.unwrap();
|
||||
store.mark_transcribed(transcribed, now).unwrap();
|
||||
|
||||
let report = execute(&f.state, &plan, now, 7);
|
||||
assert_eq!(report.calls_deleted, Vec::<CallId>::new());
|
||||
assert_eq!(
|
||||
sorted(report.skipped),
|
||||
sorted(vec![failed, processing, transcribed])
|
||||
);
|
||||
for id in [failed, processing, transcribed] {
|
||||
assert!(has_audio(&f, id), "call {id} keeps its audio");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_transcribed_call_that_changed_after_planning_keeps_its_audio() {
|
||||
let f = fixture();
|
||||
let now = Local::now();
|
||||
let failed = call(&f, "failed", now, 9, Some(8));
|
||||
let undecided = call(&f, "undecided", now, 9, Some(8));
|
||||
let plan = plan(&f, now);
|
||||
assert_eq!(plan.len(), 2);
|
||||
assert!(plan
|
||||
.iter()
|
||||
.all(|action| matches!(action, RetentionAction::DeleteAudio(_))));
|
||||
let store = &f.state.store;
|
||||
store
|
||||
.set_status(failed, CallStatus::Failed, Some("Fehler"))
|
||||
.unwrap();
|
||||
store
|
||||
.set_status(undecided, CallStatus::AwaitingDecision, None)
|
||||
.unwrap();
|
||||
|
||||
let report = execute(&f.state, &plan, now, 7);
|
||||
assert_eq!(report.audio_deleted, Vec::<CallId>::new());
|
||||
assert_eq!(sorted(report.skipped), sorted(vec![failed, undecided]));
|
||||
assert!(has_audio(&f, failed));
|
||||
assert!(has_audio(&f, undecided));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_call_deleted_after_planning_is_ignored() {
|
||||
let f = fixture();
|
||||
let now = Local::now();
|
||||
let done = call(&f, "done", now, 9, Some(8));
|
||||
let undecided = call(&f, "undecided", now, 8, None);
|
||||
let plan = plan(&f, now);
|
||||
f.state.discard_call(done).unwrap();
|
||||
f.state.discard_call(undecided).unwrap();
|
||||
|
||||
assert_eq!(execute(&f.state, &plan, now, 7), PassReport::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_call_that_fails_does_not_stop_the_pass() {
|
||||
let f = fixture();
|
||||
let now = Local::now();
|
||||
let broken = call(&f, "broken", now, 9, Some(8));
|
||||
// A directory where the mic track should be: removing it fails.
|
||||
let [mic, _] = tracks(&f, broken);
|
||||
fs::remove_file(&mic).unwrap();
|
||||
fs::create_dir(&mic).unwrap();
|
||||
let fine = call(&f, "fine", now, 9, Some(8));
|
||||
|
||||
let report = run_pass(&f.state, now);
|
||||
assert_eq!(report.failed, vec![broken]);
|
||||
assert_eq!(report.audio_deleted, vec![fine]);
|
||||
assert!(
|
||||
!f.state
|
||||
.store
|
||||
.get_call(broken)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.audio_deleted
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_retention_period_applies_to_the_next_pass() {
|
||||
let f = fixture();
|
||||
let now = Local::now();
|
||||
let id = call(&f, "a", now, 4, Some(3));
|
||||
assert_eq!(run_pass(&f.state, now), PassReport::default());
|
||||
|
||||
let mut settings = f.state.settings();
|
||||
settings.retention_days = 2;
|
||||
f.state.save_settings(settings).unwrap();
|
||||
assert_eq!(run_pass(&f.state, now).audio_deleted, vec![id]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_summary_counts_each_outcome() {
|
||||
let report = PassReport {
|
||||
audio_deleted: vec![1, 2],
|
||||
calls_deleted: vec![3],
|
||||
skipped: vec![4],
|
||||
cleanup_pending: vec![],
|
||||
failed: vec![],
|
||||
};
|
||||
assert_eq!(
|
||||
report.summary(),
|
||||
"2 audio deleted, 1 call deleted, 1 skipped, 0 failed"
|
||||
);
|
||||
}
|
||||
|
||||
const MIN: Duration = Duration::from_secs(60);
|
||||
|
||||
fn t0() -> SystemTime {
|
||||
SystemTime::UNIX_EPOCH + Duration::from_secs(1_800_000_000)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_pass_is_due_at_once() {
|
||||
assert!(pass_due(None, t0()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_next_pass_is_due_an_hour_later() {
|
||||
assert!(!pass_due(Some(t0()), t0() + 59 * MIN));
|
||||
assert!(pass_due(Some(t0()), t0() + 60 * MIN));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pass_is_due_after_standby_by_the_wall_clock() {
|
||||
assert!(pass_due(Some(t0()), t0() + 48 * 60 * MIN));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pass_is_due_when_the_clock_went_back() {
|
||||
assert!(pass_due(Some(t0()), t0() - 60 * MIN));
|
||||
}
|
||||
}
|
||||
+1318
-66
File diff suppressed because it is too large
Load Diff
+303
-28
@@ -2,12 +2,18 @@
|
||||
//! 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
|
||||
//! 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
|
||||
//! (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::future::Future;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Mutex;
|
||||
@@ -42,6 +48,17 @@ const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(15 * 60);
|
||||
const MIB: u64 = 1024 * 1024;
|
||||
/// Why the banner cannot install yet; the banner shows the same hint.
|
||||
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.
|
||||
#[derive(Default)]
|
||||
@@ -58,6 +75,99 @@ pub struct UpdateInfo {
|
||||
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`.
|
||||
#[derive(Serialize, Clone, Debug, PartialEq)]
|
||||
pub struct Progress {
|
||||
@@ -67,27 +177,22 @@ pub struct Progress {
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
if !cfg!(windows) {
|
||||
log::info!("update check disabled on this platform");
|
||||
return;
|
||||
}
|
||||
thread::spawn(move || {
|
||||
let mut last_attempt = None;
|
||||
let mut failures = 0;
|
||||
loop {
|
||||
thread::spawn(move || loop {
|
||||
let now = SystemTime::now();
|
||||
if check_due(last_attempt, failures, now) {
|
||||
last_attempt = Some(now);
|
||||
if tauri::async_runtime::block_on(check(&app)) {
|
||||
failures = 0;
|
||||
} else {
|
||||
failures = failures.saturating_add(1);
|
||||
}
|
||||
// Cheap early exit so most wake-ups never touch `running`; the due
|
||||
// check that decides whether a check actually runs happens again
|
||||
// inside `run_if_due`, once `running` is held (see its doc comment).
|
||||
if app.state::<UpdateSchedule>().is_due(now) {
|
||||
tauri::async_runtime::block_on(app.state::<UpdateSchedule>().run_if_due(&app));
|
||||
}
|
||||
thread::sleep(WAKE_INTERVAL);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -110,31 +215,65 @@ fn check_due(last_attempt: Option<SystemTime>, failures: u32, now: SystemTime) -
|
||||
.map_or(true, |elapsed| elapsed >= wait)
|
||||
}
|
||||
|
||||
/// Asks the release feed for a newer version; `false` if the check failed.
|
||||
/// Failures (offline, no release yet) are expected and only logged.
|
||||
async fn check(app: &AppHandle) -> bool {
|
||||
let result = match app.updater_builder().timeout(CHECK_TIMEOUT).build() {
|
||||
/// Asks the release feed for a newer version: the one implementation the
|
||||
/// background loop and a manual check (`check_for_update_now`) both run.
|
||||
/// A failed check (offline, no release yet) is expected; only logged here,
|
||||
/// 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,
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
match result {
|
||||
Ok(Some(update)) => {
|
||||
log::info!("update available: {}", update.version);
|
||||
let version = update.version.clone();
|
||||
*lock(&app.state::<PendingUpdate>().update) = Some(update);
|
||||
let _ = app.emit("update-available", info(app, version));
|
||||
true
|
||||
Ok(found) => {
|
||||
let version = found.as_ref().map(|update| update.version.clone());
|
||||
match &version {
|
||||
Some(v) => log::info!("update available: {v}"),
|
||||
None => log::info!("no update available"),
|
||||
}
|
||||
Ok(None) => {
|
||||
log::info!("no update available");
|
||||
true
|
||||
let (outcome, offer_install) = check_outcome(is_windows, version.clone());
|
||||
if let (Some(update), true) = (found, offer_install) {
|
||||
*lock(&app.state::<PendingUpdate>().update) = Some(update);
|
||||
let _ = app.emit(
|
||||
"update-available",
|
||||
info(app, version.expect("offer_install implies a version")),
|
||||
);
|
||||
}
|
||||
outcome
|
||||
}
|
||||
Err(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
|
||||
/// update), going by the version remembered in `path`; remembers `version`
|
||||
@@ -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.
|
||||
#[tauri::command]
|
||||
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.
|
||||
#[tauri::command]
|
||||
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>();
|
||||
if pending.installing.swap(true, Ordering::SeqCst) {
|
||||
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);
|
||||
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 { .. })));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Gesprächsrekorder",
|
||||
"version": "0.1.1",
|
||||
"version": "0.4.0",
|
||||
"identifier": "eu.euvino.callrecorder",
|
||||
"build": {
|
||||
"frontendDist": "../ui/dist",
|
||||
@@ -36,7 +36,7 @@
|
||||
"label": "prompt",
|
||||
"title": "Gespräch beendet",
|
||||
"url": "index.html#/prompt",
|
||||
"width": 340,
|
||||
"width": 400,
|
||||
"height": 180,
|
||||
"alwaysOnTop": true,
|
||||
"visible": false,
|
||||
@@ -51,8 +51,7 @@
|
||||
"active": true,
|
||||
"targets": [
|
||||
"nsis",
|
||||
"deb",
|
||||
"appimage"
|
||||
"deb"
|
||||
],
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
@@ -72,7 +71,6 @@
|
||||
"updater": {
|
||||
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDIwM0EzNUEyMTUwOThERUQKUldUdGpRa1ZvalU2SVBtYVZRaWlWMVBCNzFTd1BRbmtmdU9sZXMrVTltckNiYlRSSmZHcWpNMHUK",
|
||||
"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"
|
||||
],
|
||||
"windows": {
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ui",
|
||||
"private": true,
|
||||
"version": "0.1.1",
|
||||
"version": "0.4.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -28,12 +28,15 @@
|
||||
aria-current={call.id === selectedId}
|
||||
onclick={() => onselect(call.id)}
|
||||
>
|
||||
{#if call.needs_action}
|
||||
<span class="dot" title="Offen" aria-label="Offen"></span>
|
||||
{/if}
|
||||
<span class="title">{call.title ?? appLine(call)}</span>
|
||||
<span class="meta">
|
||||
<span class="muted">
|
||||
{call.title ? `${appLine(call)} · ` : ''}{formatListTime(call.started_at)}
|
||||
</span>
|
||||
<StatusPill status={call.status} interrupted={call.interrupted} />
|
||||
<StatusPill state={call.list_state} interrupted={call.interrupted} />
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
@@ -53,11 +56,12 @@
|
||||
}
|
||||
|
||||
.row {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
width: 100%;
|
||||
padding: 9px 10px;
|
||||
padding: 9px 10px 9px 18px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
background: none;
|
||||
@@ -67,6 +71,20 @@
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.dot {
|
||||
position: absolute;
|
||||
left: 7px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--primary);
|
||||
/* A thin ring so the dot stays visible against the selected row's
|
||||
primary-soft background (and the hover background). */
|
||||
box-shadow: 0 0 0 2px var(--surface);
|
||||
}
|
||||
|
||||
.row:hover {
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<script lang="ts">
|
||||
import { CALL_LANGUAGES } from './api'
|
||||
|
||||
// The language a call is transcribed in, picked next to "Transkribieren"
|
||||
// and "Erneut versuchen".
|
||||
let { value = $bindable(), disabled = false }: { value: string; disabled?: boolean } = $props()
|
||||
</script>
|
||||
|
||||
<select bind:value {disabled} title="Sprache des Gesprächs" aria-label="Sprache des Gesprächs">
|
||||
{#each CALL_LANGUAGES as language (language.code)}
|
||||
<option value={language.code}>{language.label}</option>
|
||||
{/each}
|
||||
</select>
|
||||
@@ -0,0 +1,251 @@
|
||||
<script lang="ts">
|
||||
import { onDestroy } from 'svelte'
|
||||
import { errorText, playbackUrl, preparePlayback, releasePlayback, type CallId } from './api'
|
||||
import { formatOffset } from './format'
|
||||
|
||||
let {
|
||||
callId,
|
||||
estimate,
|
||||
ontime,
|
||||
onplaying,
|
||||
}: {
|
||||
callId: CallId
|
||||
/** The call's length from its times, shown until the mix is ready. */
|
||||
estimate: number
|
||||
/** The playback position, once the mix is loaded (also while paused). */
|
||||
ontime?: (secs: number) => void
|
||||
onplaying?: (playing: boolean) => void
|
||||
} = $props()
|
||||
|
||||
let audio: HTMLAudioElement
|
||||
/** Resolves once the mix is loaded; `false` if preparing it failed. */
|
||||
let loading: Promise<boolean> | null = null
|
||||
let preparing = $state(false)
|
||||
let playing = $state(false)
|
||||
// svelte-ignore state_referenced_locally
|
||||
let duration = $state(estimate)
|
||||
let position = $state(0)
|
||||
/** While the slider is dragged it shows the drag, not the audio. */
|
||||
let dragging = $state(false)
|
||||
let error = $state('')
|
||||
/** The mix held in memory where the webview cannot stream it (Linux). */
|
||||
let blobUrl: string | null = null
|
||||
/** This player's hold on the mix on disk (see `releasePlayback`). */
|
||||
let lease: number | null = null
|
||||
/** Set once the player is gone: a load still under way stops at the next
|
||||
* step and keeps nothing (no blob, no mix on disk). */
|
||||
let destroyed = false
|
||||
const abort = new AbortController()
|
||||
|
||||
const LOAD_FAILED = 'Audio konnte nicht geladen werden.'
|
||||
|
||||
/** Lets go of the mix on disk (once). */
|
||||
function release() {
|
||||
if (lease === null) return
|
||||
releasePlayback(callId, lease).catch(() => {})
|
||||
lease = null
|
||||
}
|
||||
|
||||
/** Mixes the call (first use only) and loads the mix into the player. */
|
||||
function load(): Promise<boolean> {
|
||||
loading ??= (async () => {
|
||||
preparing = true
|
||||
error = ''
|
||||
try {
|
||||
const prepared = await preparePlayback(callId)
|
||||
lease = prepared.lease
|
||||
if (destroyed) return false
|
||||
duration = prepared.duration_secs
|
||||
const url = playbackUrl(callId)
|
||||
try {
|
||||
await loadSource(url)
|
||||
} catch (err) {
|
||||
if (destroyed) return false
|
||||
if (!(err instanceof MediaError) || err.code !== MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED) {
|
||||
throw err
|
||||
}
|
||||
// WebKitGTK (Linux) plays no media from a custom scheme such as
|
||||
// playback:// (WebView2 gets http://playback.localhost instead),
|
||||
// but fetches it fine: there the mix is played from memory, and
|
||||
// the file is not needed any more.
|
||||
const response = await fetch(url, { signal: abort.signal })
|
||||
if (!response.ok) throw new Error(LOAD_FAILED)
|
||||
const blob = await response.blob()
|
||||
if (destroyed) return false
|
||||
blobUrl = URL.createObjectURL(blob)
|
||||
release()
|
||||
await loadSource(blobUrl)
|
||||
}
|
||||
return !destroyed
|
||||
} catch (err) {
|
||||
// A retry creates a new blob: this one is of no use any more.
|
||||
if (blobUrl) URL.revokeObjectURL(blobUrl)
|
||||
blobUrl = null
|
||||
if (destroyed) return false
|
||||
error = err instanceof MediaError ? LOAD_FAILED : errorText(err)
|
||||
loading = null // a later click tries again
|
||||
return false
|
||||
} finally {
|
||||
if (destroyed) release()
|
||||
preparing = false
|
||||
}
|
||||
})()
|
||||
return loading
|
||||
}
|
||||
|
||||
/** Loads `src` into the player; rejects with its `MediaError`. */
|
||||
function loadSource(src: string): Promise<void> {
|
||||
const ready = new Promise<void>((resolve, reject) => {
|
||||
const ok = () => {
|
||||
audio.removeEventListener('error', fail)
|
||||
resolve()
|
||||
}
|
||||
const fail = () => {
|
||||
audio.removeEventListener('loadedmetadata', ok)
|
||||
reject(audio.error)
|
||||
}
|
||||
audio.addEventListener('loadedmetadata', ok, { once: true })
|
||||
audio.addEventListener('error', fail, { once: true })
|
||||
})
|
||||
audio.src = src
|
||||
return ready
|
||||
}
|
||||
|
||||
async function start() {
|
||||
try {
|
||||
await audio.play()
|
||||
} catch (err) {
|
||||
error = `Wiedergabe nicht möglich: ${errorText(err)}`
|
||||
}
|
||||
}
|
||||
|
||||
async function toggle() {
|
||||
if (playing) {
|
||||
audio.pause()
|
||||
} else if (await load()) {
|
||||
await start()
|
||||
}
|
||||
}
|
||||
|
||||
/** Jumps to `secs` and plays from there (a click on a transcript line). */
|
||||
export async function playFrom(secs: number) {
|
||||
if (!(await load())) return
|
||||
audio.currentTime = Math.min(secs, duration)
|
||||
position = audio.currentTime
|
||||
if (audio.paused) await start()
|
||||
}
|
||||
|
||||
async function seekTo(secs: number) {
|
||||
dragging = false
|
||||
position = secs
|
||||
if (!(await load())) return
|
||||
audio.currentTime = secs
|
||||
}
|
||||
|
||||
function ontimeupdate() {
|
||||
if (!dragging) position = audio.currentTime
|
||||
ontime?.(audio.currentTime)
|
||||
}
|
||||
|
||||
function setPlaying(value: boolean) {
|
||||
playing = value
|
||||
onplaying?.(value)
|
||||
}
|
||||
|
||||
onDestroy(() => {
|
||||
destroyed = true
|
||||
abort.abort()
|
||||
// Lets go of the file and the memory, so the call can be deleted right
|
||||
// away and no customer audio stays behind.
|
||||
audio?.pause()
|
||||
audio?.removeAttribute('src')
|
||||
audio?.load()
|
||||
if (blobUrl) URL.revokeObjectURL(blobUrl)
|
||||
blobUrl = null
|
||||
release()
|
||||
onplaying?.(false)
|
||||
})
|
||||
</script>
|
||||
|
||||
<div class="player">
|
||||
<audio
|
||||
bind:this={audio}
|
||||
preload="metadata"
|
||||
{ontimeupdate}
|
||||
onplay={() => setPlaying(true)}
|
||||
onpause={() => setPlaying(false)}
|
||||
onended={() => setPlaying(false)}
|
||||
></audio>
|
||||
<button
|
||||
class="play"
|
||||
disabled={preparing}
|
||||
title={playing ? 'Pause' : 'Abspielen'}
|
||||
aria-label={playing ? 'Pause' : 'Abspielen'}
|
||||
onclick={toggle}
|
||||
>
|
||||
{#if preparing}…{:else if playing}❚❚{:else}▶{/if}
|
||||
</button>
|
||||
<input
|
||||
class="timeline"
|
||||
type="range"
|
||||
min="0"
|
||||
max={duration || 1}
|
||||
step="0.1"
|
||||
value={position}
|
||||
disabled={preparing}
|
||||
aria-label="Position"
|
||||
oninput={(e) => {
|
||||
dragging = true
|
||||
position = Number(e.currentTarget.value)
|
||||
}}
|
||||
onchange={(e) => seekTo(Number(e.currentTarget.value))}
|
||||
/>
|
||||
<span class="time">{formatOffset(position)} / {formatOffset(duration)}</span>
|
||||
{#if preparing}
|
||||
<span class="muted">Audio wird vorbereitet…</span>
|
||||
{:else if error}
|
||||
<span class="error">{error}</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.player {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px 10px;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.play {
|
||||
flex-shrink: 0;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: 50%;
|
||||
border: none;
|
||||
background: var(--primary);
|
||||
color: #fff;
|
||||
font-size: 11px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.play:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.timeline {
|
||||
flex: 1 1 160px;
|
||||
min-width: 120px;
|
||||
accent-color: var(--primary);
|
||||
}
|
||||
|
||||
.time {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
@@ -1,21 +1,22 @@
|
||||
<script lang="ts">
|
||||
import type { CallStatus } from './api'
|
||||
import type { ListState } from './api'
|
||||
|
||||
let { status, interrupted = false }: { status: CallStatus; interrupted?: boolean } = $props()
|
||||
let { state, interrupted = false }: { state: ListState; interrupted?: boolean } = $props()
|
||||
|
||||
const pills: Record<CallStatus, { text: string; kind: string }> = {
|
||||
const pills: Record<ListState, { text: string; kind: string }> = {
|
||||
done: { text: 'fertig', kind: 'done' },
|
||||
ready_to_upload: { text: 'bereit zum Hochladen', kind: 'ready' },
|
||||
processing: { text: 'wird verarbeitet…', kind: 'processing' },
|
||||
awaiting_decision: { text: 'nicht transkribiert', kind: 'awaiting' },
|
||||
failed: { text: 'fehlgeschlagen', kind: 'failed' },
|
||||
recording: { text: 'Aufnahme läuft', kind: 'recording' },
|
||||
}
|
||||
|
||||
let pill = $derived(pills[status])
|
||||
let pill = $derived(pills[state])
|
||||
</script>
|
||||
|
||||
<span class="pill status {pill.kind}">
|
||||
{pill.text}{#if interrupted && status === 'awaiting_decision'}, unterbrochen{/if}
|
||||
{pill.text}{#if interrupted && state === 'awaiting_decision'}, unterbrochen{/if}
|
||||
</span>
|
||||
|
||||
<style>
|
||||
@@ -28,6 +29,11 @@
|
||||
color: var(--ok);
|
||||
}
|
||||
|
||||
.ready {
|
||||
background: var(--primary-soft);
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
.processing {
|
||||
background: #fff4d6;
|
||||
color: #8a6100;
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
onrename,
|
||||
onmerge,
|
||||
onunmerge,
|
||||
activeIndex = null,
|
||||
follow = false,
|
||||
onseek,
|
||||
}: {
|
||||
/** The transcript with merges applied: merged speakers no longer appear. */
|
||||
segments: SegmentView[]
|
||||
@@ -18,8 +21,45 @@
|
||||
onmerge: (fromKey: string, intoKey: string) => Promise<void>
|
||||
/** Undoes the merge of `fromKey`. */
|
||||
onunmerge: (fromKey: string) => Promise<void>
|
||||
/** The line being heard; it is highlighted. */
|
||||
activeIndex?: number | null
|
||||
/** Scrolls the line being heard into view when it leaves the view. */
|
||||
follow?: boolean
|
||||
/** Plays from `secs`, a line's start (only while the audio is there). */
|
||||
onseek?: (secs: number) => void
|
||||
} = $props()
|
||||
|
||||
let lineElements: HTMLElement[] = $state([])
|
||||
|
||||
/** A click on a line's text plays from it, unless text was selected. */
|
||||
function lineClick(start: number) {
|
||||
if (window.getSelection()?.toString()) return
|
||||
onseek?.(start)
|
||||
}
|
||||
|
||||
/** The nearest ancestor that scrolls vertically. */
|
||||
function scrollParent(node: HTMLElement): HTMLElement | null {
|
||||
for (let el = node.parentElement; el; el = el.parentElement) {
|
||||
if (/(auto|scroll)/.test(getComputedStyle(el).overflowY)) return el
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// Following the playback scrolls only once the line has left the view
|
||||
// (also when it hides under the sticky player), and then centres it.
|
||||
$effect(() => {
|
||||
if (!follow || activeIndex === null) return
|
||||
const line = lineElements[activeIndex]
|
||||
const parent = line && scrollParent(line)
|
||||
if (!line || !parent) return
|
||||
const view = parent.getBoundingClientRect()
|
||||
const box = line.getBoundingClientRect()
|
||||
const covered = parseFloat(getComputedStyle(line).scrollMarginTop) || 0
|
||||
if (box.top < view.top + covered || box.bottom > view.bottom) {
|
||||
line.scrollIntoView({ block: 'center' })
|
||||
}
|
||||
})
|
||||
|
||||
// "Ich" is always the primary blue; remote speakers cycle through the rest.
|
||||
const ME_COLOR = '#3b5bdb'
|
||||
const REMOTE_COLORS = ['#2b8a3e', '#c2255c', '#e8590c', '#7048e8', '#0c8599', '#5c940d']
|
||||
@@ -186,8 +226,27 @@
|
||||
|
||||
<div class="lines">
|
||||
{#each segments as segment, i (i)}
|
||||
<div class="line">
|
||||
<!-- The time is the keyboard-accessible way to play a line. -->
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="line"
|
||||
class:active={i === activeIndex}
|
||||
class:seekable={onseek !== undefined}
|
||||
bind:this={lineElements[i]}
|
||||
onclick={() => lineClick(segment.start)}
|
||||
>
|
||||
{#if onseek}
|
||||
<button
|
||||
class="time"
|
||||
title="Ab hier abspielen"
|
||||
onclick={(e) => {
|
||||
e.stopPropagation()
|
||||
onseek(segment.start)
|
||||
}}>{formatOffset(segment.start)}</button
|
||||
>
|
||||
{:else}
|
||||
<span class="time">{formatOffset(segment.start)}</span>
|
||||
{/if}
|
||||
<span class="speaker" style:color={speakerColor(segment.speaker_key)}>{segment.label}</span>
|
||||
<span class="text">{segment.text}</span>
|
||||
</div>
|
||||
@@ -324,12 +383,33 @@
|
||||
.lines {
|
||||
display: grid;
|
||||
grid-template-columns: auto auto 1fr;
|
||||
gap: 8px 12px;
|
||||
margin-top: 14px;
|
||||
column-gap: 12px;
|
||||
margin: 10px -8px 0;
|
||||
}
|
||||
|
||||
/* One row of the transcript grid that can be highlighted as a whole. */
|
||||
.line {
|
||||
display: contents;
|
||||
display: grid;
|
||||
grid-column: 1 / -1;
|
||||
grid-template-columns: subgrid;
|
||||
padding: 4px 8px;
|
||||
border-radius: 6px;
|
||||
/* Room for the sticky player when the line is scrolled into view. */
|
||||
scroll-margin-top: 64px;
|
||||
}
|
||||
|
||||
.line.seekable {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.line.seekable:hover {
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.line.active,
|
||||
.line.active:hover {
|
||||
background: var(--primary-soft);
|
||||
box-shadow: inset 3px 0 0 var(--primary);
|
||||
}
|
||||
|
||||
.time {
|
||||
@@ -339,6 +419,22 @@
|
||||
padding-top: 1px;
|
||||
}
|
||||
|
||||
button.time {
|
||||
align-self: start;
|
||||
border: none;
|
||||
background: none;
|
||||
padding: 1px 0 0;
|
||||
font-family: inherit;
|
||||
line-height: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button.time:hover {
|
||||
color: var(--primary);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.speaker {
|
||||
font-weight: 600;
|
||||
max-width: 160px;
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
onRecordingState,
|
||||
onUpdateAvailable,
|
||||
onUpdateProgress,
|
||||
updateProgressText,
|
||||
UPDATE_BUSY_HINT,
|
||||
type UpdateInfo,
|
||||
type UpdateProgress,
|
||||
} from './api'
|
||||
@@ -62,16 +64,7 @@
|
||||
}
|
||||
}
|
||||
|
||||
function megabytes(bytes: number): string {
|
||||
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)} %`
|
||||
})
|
||||
let progressText = $derived(updateProgressText(progress))
|
||||
</script>
|
||||
|
||||
{#if update}
|
||||
@@ -84,7 +77,7 @@
|
||||
Installieren & neu starten
|
||||
</button>
|
||||
{#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 error}
|
||||
|
||||
+133
-11
@@ -1,23 +1,58 @@
|
||||
// Typed wrappers around the Tauri commands and events of the app shell.
|
||||
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import { convertFileSrc, invoke } from '@tauri-apps/api/core'
|
||||
import { listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||
|
||||
export type CallId = number
|
||||
|
||||
/** The languages a call can be transcribed in (the backend's `CALL_LANGUAGES`). */
|
||||
export const CALL_LANGUAGES = [
|
||||
{ code: 'de', label: 'Deutsch' },
|
||||
{ code: 'en', label: 'Englisch' },
|
||||
{ code: 'es', label: 'Spanisch' },
|
||||
{ code: 'fr', label: 'Französisch' },
|
||||
{ code: 'it', label: 'Italienisch' },
|
||||
] as const
|
||||
|
||||
export interface Settings {
|
||||
allowlist: string[]
|
||||
mic_device: string | null
|
||||
output_device: string | null
|
||||
/** Language of the transcription started last; set by the app, not the settings page. */
|
||||
language: string
|
||||
deepscript_model: string
|
||||
/** Custom words/names submitted with every transcription. */
|
||||
vocabulary: string[]
|
||||
retention_days: number
|
||||
autostart: boolean
|
||||
start_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 {
|
||||
id: string
|
||||
@@ -47,6 +82,8 @@ export interface CallBrief {
|
||||
started_at: string
|
||||
ended_at: string | null
|
||||
duration_secs: number
|
||||
/** What the language picker starts on: the call's own language, else the last used. */
|
||||
language: string
|
||||
}
|
||||
|
||||
/** The call the end-of-call prompt shows, and how many wait behind it. */
|
||||
@@ -56,6 +93,18 @@ export interface PendingPrompt extends CallBrief {
|
||||
|
||||
export type CallStatus = 'recording' | 'awaiting_decision' | 'processing' | 'done' | 'failed'
|
||||
|
||||
/** What the status pill shows and whether the row needs the user's
|
||||
* attention. Mirrors `CallStatus`, except `done` splits into `done`
|
||||
* (uploaded to this build's backend — "fertig") and `ready_to_upload`
|
||||
* (not uploaded here yet — "bereit zum Hochladen"). */
|
||||
export type ListState =
|
||||
| 'recording'
|
||||
| 'awaiting_decision'
|
||||
| 'processing'
|
||||
| 'failed'
|
||||
| 'done'
|
||||
| 'ready_to_upload'
|
||||
|
||||
/** A row of the main window's call list. Times are RFC 3339. */
|
||||
export interface CallListItem {
|
||||
id: CallId
|
||||
@@ -64,9 +113,17 @@ export interface CallListItem {
|
||||
/** 0 while recording. */
|
||||
duration_secs: number
|
||||
status: CallStatus
|
||||
list_state: ListState
|
||||
/** Whether this row needs the user to act on it (the dot in the list,
|
||||
* counted in the sidebar header's "N offen"). */
|
||||
needs_action: boolean
|
||||
interrupted: boolean
|
||||
/** The name the user gave the call, if any. */
|
||||
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>". */
|
||||
@@ -87,17 +144,28 @@ export interface SpeakerMerge {
|
||||
}
|
||||
|
||||
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. */
|
||||
segments: SegmentView[]
|
||||
/** Renamed speakers by key. */
|
||||
speaker_names: Record<string, string>
|
||||
merges: SpeakerMerge[]
|
||||
/** The transcript is being uploaded right now. */
|
||||
uploading: boolean
|
||||
/** The call's audio is still on this PC and can be played. */
|
||||
audio_available: boolean
|
||||
/** Retention deleted the call's audio (not just: the files are missing). */
|
||||
audio_deleted: boolean
|
||||
/** What the language picker starts on: the call's own language, else the last used. */
|
||||
language: string
|
||||
}
|
||||
|
||||
export interface Account {
|
||||
id: string
|
||||
name: string
|
||||
/** A call's two tracks mixed into one file, ready to play from
|
||||
* `playbackUrl`. */
|
||||
export interface PreparedPlayback {
|
||||
duration_secs: number
|
||||
/** Hand back with `releasePlayback` once the player is done. */
|
||||
lease: number
|
||||
}
|
||||
|
||||
/** A newer version the release feed offers. */
|
||||
@@ -113,6 +181,15 @@ export interface UpdateProgress {
|
||||
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 {
|
||||
mic: number
|
||||
out: number
|
||||
@@ -134,9 +211,21 @@ export const stopRecording = () => invoke<void>('stop_recording')
|
||||
export const discardCurrentRecording = () => invoke<void>('discard_current_recording')
|
||||
export const getPendingPrompt = () => invoke<PendingPrompt | null>('get_pending_prompt')
|
||||
export const getCallBrief = (id: CallId) => invoke<CallBrief>('get_call_brief', { id })
|
||||
export const transcribeCall = (id: CallId) => invoke<void>('transcribe_call', { id })
|
||||
export const retryCall = (id: CallId) => invoke<void>('retry_call', { id })
|
||||
export const transcribeCall = (id: CallId, language: string) =>
|
||||
invoke<void>('transcribe_call', { id, language })
|
||||
export const retryCall = (id: CallId, language: string) =>
|
||||
invoke<void>('retry_call', { id, language })
|
||||
export const discardCall = (id: CallId) => invoke<void>('discard_call', { id })
|
||||
/** Mixes the call's tracks (or reuses the cached mix); refused while the
|
||||
* call is recorded or processed and once its audio is gone. */
|
||||
export const preparePlayback = (id: CallId) =>
|
||||
invoke<PreparedPlayback>('prepare_playback', { id })
|
||||
/** The player is done with the mix: it is removed from disk. */
|
||||
export const releasePlayback = (id: CallId, lease: number) =>
|
||||
invoke<void>('release_playback', { id, lease })
|
||||
/** Where the main window plays a prepared mix from (the app's `playback`
|
||||
* scheme; other windows are refused). */
|
||||
export const playbackUrl = (id: CallId) => convertFileSrc(String(id), 'playback')
|
||||
export const listCalls = () => invoke<CallListItem[]>('list_calls')
|
||||
export const getCall = (id: CallId) => invoke<CallDetail>('get_call', { id })
|
||||
/** An empty name restores the default label. */
|
||||
@@ -149,12 +238,26 @@ export const unmergeSpeaker = (id: CallId, fromKey: string) =>
|
||||
/** `null` or an empty title restores the default heading. */
|
||||
export const renameCall = (id: CallId, title: string | null) =>
|
||||
invoke<void>('rename_call', { id, title })
|
||||
export const listAccounts = () => invoke<Account[]>('list_accounts')
|
||||
export const setAccount = (id: CallId, accountId: string | null) =>
|
||||
invoke<void>('set_account', { id, accountId })
|
||||
export const backendServer = () => invoke<BackendServer>('backend_server')
|
||||
export const backendStatus = () => invoke<BackendStatus>('backend_status')
|
||||
/** 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')
|
||||
/** Resolves only on failure: on success the app restarts. */
|
||||
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> =>
|
||||
listen<RecordingState>('recording-state', (event) => handler(event.payload))
|
||||
@@ -166,6 +269,12 @@ export const onPromptChanged = (handler: () => void): Promise<UnlistenFn> =>
|
||||
/** A call's status changed (processing started, done or failed). */
|
||||
export const onCallUpdated = (handler: (id: CallId) => void): Promise<UnlistenFn> =>
|
||||
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> =>
|
||||
listen<UpdateInfo>('update-available', (event) => handler(event.payload))
|
||||
export const onUpdateProgress = (
|
||||
@@ -182,6 +291,19 @@ export function meterFill(level: number): number {
|
||||
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. */
|
||||
export function errorText(err: unknown): string {
|
||||
return typeof err === 'string' ? err : err instanceof Error ? err.message : String(err)
|
||||
|
||||
@@ -53,3 +53,14 @@ export function formatOffset(secs: number): string {
|
||||
const ss = pad(total % 60)
|
||||
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))}`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
// Couples playback to the transcript: which line is being heard.
|
||||
|
||||
/** The part of a transcript line the lookup needs. */
|
||||
export interface Timed {
|
||||
start: number
|
||||
end: number
|
||||
}
|
||||
|
||||
/** Index of the line heard at `secs`: the one whose `[start, end)` holds
|
||||
* it — of overlapping lines (both sides talking at once) the one that
|
||||
* started last. `null` before the first line, in a pause between lines and
|
||||
* after the last one. */
|
||||
export function segmentAt(segments: readonly Timed[], secs: number): number | null {
|
||||
let found: number | null = null
|
||||
segments.forEach((segment, i) => {
|
||||
if (segment.start <= secs && secs < segment.end) {
|
||||
if (found === null || segment.start >= segments[found].start) found = i
|
||||
}
|
||||
})
|
||||
return found
|
||||
}
|
||||
+352
-94
@@ -5,9 +5,10 @@
|
||||
errorText,
|
||||
getCall,
|
||||
getRecordingState,
|
||||
listAccounts,
|
||||
getSettings,
|
||||
listCalls,
|
||||
mergeSpeakers,
|
||||
onBackendLoginError,
|
||||
onCallEnded,
|
||||
onCallUpdated,
|
||||
onPromptChanged,
|
||||
@@ -15,19 +16,21 @@
|
||||
renameCall,
|
||||
renameSpeaker,
|
||||
retryCall,
|
||||
setAccount,
|
||||
showRecorder,
|
||||
startManualRecording,
|
||||
transcribeCall,
|
||||
unmergeSpeaker,
|
||||
type Account,
|
||||
uploadTranscript,
|
||||
type CallDetail,
|
||||
type CallId,
|
||||
type CallListItem,
|
||||
type RecordingState,
|
||||
} from '../lib/api'
|
||||
import CallList from '../lib/CallList.svelte'
|
||||
import { formatDetailTime, formatMinutes } from '../lib/format'
|
||||
import { formatDateTime, formatDetailTime, formatMinutes } from '../lib/format'
|
||||
import LanguageSelect from '../lib/LanguageSelect.svelte'
|
||||
import Player from '../lib/Player.svelte'
|
||||
import { segmentAt } from '../lib/playback'
|
||||
import StatusPill from '../lib/StatusPill.svelte'
|
||||
import TranscriptView from '../lib/TranscriptView.svelte'
|
||||
import UpdateBanner from '../lib/UpdateBanner.svelte'
|
||||
@@ -35,7 +38,6 @@
|
||||
let calls = $state<CallListItem[]>([])
|
||||
let loaded = $state(false)
|
||||
let listError = $state('')
|
||||
let accounts = $state<Account[]>([])
|
||||
|
||||
let recordingState = $state<RecordingState>({ state: 'idle' })
|
||||
let recordBusy = $state(false)
|
||||
@@ -44,9 +46,32 @@
|
||||
let selectedId = $state<CallId | null>(null)
|
||||
let detail = $state<CallDetail | null>(null)
|
||||
let detailError = $state('')
|
||||
/** The language picked for the shown call's transcription. */
|
||||
let language = $state('de')
|
||||
let actionError = $state('')
|
||||
let busy = $state(false)
|
||||
let tab = $state<'summary' | 'transcript'>('transcript')
|
||||
|
||||
// "Löschen" (transcribed calls): confirmed with a dialog instead of
|
||||
// running straight away like the other actions.
|
||||
let deleteDialogOpen = $state(false)
|
||||
let deleteBusy = $state(false)
|
||||
let deleteError = $state('')
|
||||
|
||||
// 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>>({})
|
||||
|
||||
// Playback of the shown call (the player itself lives in `Player`).
|
||||
let player = $state<ReturnType<typeof Player>>()
|
||||
/** The playback position once the mix is loaded, else `null`. */
|
||||
let playerTime = $state<number | null>(null)
|
||||
let playing = $state(false)
|
||||
/** Whether the transcript scrolls along; scrolling by hand ends it. */
|
||||
let follow = $state(true)
|
||||
/** For "… werden N Tage nach der Transkription gelöscht". */
|
||||
let retentionDays = $state<number | null>(null)
|
||||
let retentionPeriod = $derived(retentionDays === 1 ? '1 Tag' : `${retentionDays} Tage`)
|
||||
|
||||
let editingTitle = $state(false)
|
||||
let titleDraft = $state('')
|
||||
@@ -87,6 +112,12 @@
|
||||
try {
|
||||
const next = await getCall(id)
|
||||
if (request === detailRequest && id === selectedId) {
|
||||
// A refresh of the same call keeps what the user picked, unless the
|
||||
// backend's suggestion changed (e.g. it was transcribed from the
|
||||
// prompt in another language and failed).
|
||||
if (next.call.id !== detail?.call.id || next.language !== detail?.language) {
|
||||
language = next.language
|
||||
}
|
||||
detail = next
|
||||
detailError = ''
|
||||
}
|
||||
@@ -95,24 +126,36 @@
|
||||
}
|
||||
}
|
||||
|
||||
function resetPlayback() {
|
||||
playerTime = null
|
||||
playing = false
|
||||
follow = true
|
||||
}
|
||||
|
||||
function select(id: CallId) {
|
||||
if (id === selectedId) return
|
||||
selectedId = id
|
||||
resetPlayback()
|
||||
detail = null
|
||||
detailError = ''
|
||||
actionError = ''
|
||||
editingTitle = false
|
||||
titleError = ''
|
||||
deleteDialogOpen = false
|
||||
deleteError = ''
|
||||
refreshDetail()
|
||||
}
|
||||
|
||||
function clearSelection() {
|
||||
selectedId = null
|
||||
resetPlayback()
|
||||
detail = null
|
||||
detailError = ''
|
||||
actionError = ''
|
||||
editingTitle = false
|
||||
titleError = ''
|
||||
deleteDialogOpen = false
|
||||
deleteError = ''
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
@@ -122,6 +165,10 @@
|
||||
if (id === selectedId) refreshDetail()
|
||||
}),
|
||||
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),
|
||||
onRecordingState((state) => {
|
||||
recordingState = state
|
||||
@@ -129,12 +176,15 @@
|
||||
}),
|
||||
]
|
||||
refreshList()
|
||||
// Read on every visit: the settings page is a route of this window, so
|
||||
// a changed retention period is shown on the way back. Without it the
|
||||
// "no audio" line just leaves the period out.
|
||||
getSettings()
|
||||
.then((settings) => (retentionDays = settings.retention_days))
|
||||
.catch((err) => console.warn('settings not read:', errorText(err)))
|
||||
getRecordingState()
|
||||
.then((state) => (recordingState = state))
|
||||
.catch((err) => (recordError = errorText(err)))
|
||||
listAccounts()
|
||||
.then((list) => (accounts = list))
|
||||
.catch((err) => (listError = errorText(err)))
|
||||
return () => unlisten.forEach((u) => u.then((off) => off()))
|
||||
})
|
||||
|
||||
@@ -178,26 +228,74 @@
|
||||
}
|
||||
}
|
||||
|
||||
const transcribe = () => run(transcribeCall)
|
||||
const retry = () => run(retryCall)
|
||||
const transcribe = () => run((id) => transcribeCall(id, language))
|
||||
const retry = () => run((id) => retryCall(id, language))
|
||||
const discard = () =>
|
||||
run(discardCall, () => {
|
||||
clearSelection()
|
||||
refreshList()
|
||||
})
|
||||
|
||||
function changeAccount(event: Event) {
|
||||
const select = event.currentTarget as HTMLSelectElement
|
||||
const previous = detail?.call.account_id ?? ''
|
||||
run(async (id) => {
|
||||
try {
|
||||
await setAccount(id, select.value || null)
|
||||
} catch (err) {
|
||||
select.value = previous
|
||||
throw err
|
||||
/** "Löschen" on a transcribed call: asks for confirmation first. */
|
||||
function askDelete() {
|
||||
deleteError = ''
|
||||
deleteDialogOpen = true
|
||||
}
|
||||
|
||||
function cancelDelete() {
|
||||
deleteDialogOpen = false
|
||||
deleteError = ''
|
||||
}
|
||||
|
||||
/** Confirmed delete: same backend path as "Verwerfen" (`discard_call`).
|
||||
* On success the selection moves to the next call in the list, or clears
|
||||
* if none is left. */
|
||||
async function confirmDelete() {
|
||||
if (!detail) return
|
||||
const id = detail.call.id
|
||||
deleteBusy = true
|
||||
try {
|
||||
await discardCall(id)
|
||||
deleteDialogOpen = false
|
||||
selectAfterDelete(id)
|
||||
refreshList()
|
||||
} catch (err) {
|
||||
deleteError = errorText(err)
|
||||
} finally {
|
||||
deleteBusy = false
|
||||
}
|
||||
}
|
||||
|
||||
/** Selects the call that took `deletedId`'s place in the list (or the one
|
||||
* before it, if `deletedId` was last), else clears the selection. */
|
||||
function selectAfterDelete(deletedId: CallId) {
|
||||
const index = calls.findIndex((c) => c.id === deletedId)
|
||||
const remaining = calls.filter((c) => c.id !== deletedId)
|
||||
if (remaining.length === 0) {
|
||||
clearSelection()
|
||||
return
|
||||
}
|
||||
const next = remaining[Math.min(Math.max(index, 0), remaining.length - 1)]
|
||||
select(next.id)
|
||||
}
|
||||
|
||||
/** Uploads the shown call's transcript (logging in first if needed). A
|
||||
* call already uploaded has no button any more: the CRM never gets a
|
||||
* duplicate. */
|
||||
async function upload() {
|
||||
if (!detail) return
|
||||
const id = detail.call.id
|
||||
if (uploading.includes(id)) return
|
||||
uploading = [...uploading, id]
|
||||
delete uploadErrors[id]
|
||||
try {
|
||||
await uploadTranscript(id)
|
||||
delete uploadErrors[id]
|
||||
} catch (err) {
|
||||
uploadErrors[id] = errorText(err)
|
||||
} finally {
|
||||
uploading = uploading.filter((u) => u !== id)
|
||||
}
|
||||
await refreshDetail()
|
||||
})
|
||||
}
|
||||
|
||||
async function rename(speakerKey: string, name: string) {
|
||||
@@ -249,6 +347,28 @@
|
||||
node.select()
|
||||
}
|
||||
|
||||
/** A click on a transcript line: plays from there and follows again. */
|
||||
function playFrom(secs: number) {
|
||||
follow = true
|
||||
player?.playFrom(secs)
|
||||
}
|
||||
|
||||
const SCROLL_KEYS = ['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End', ' ']
|
||||
|
||||
/** Scrolling the detail by hand while playing stops following the
|
||||
* playback (until "folgen" or a click on a line). Only user input counts:
|
||||
* the transcript's own scrolling raises none of these events. */
|
||||
function manualScroll(event: Event) {
|
||||
if (!playing) return
|
||||
if (event instanceof KeyboardEvent) {
|
||||
const target = event.target as HTMLElement
|
||||
if (!SCROLL_KEYS.includes(event.key) || target.closest('input, textarea, button')) return
|
||||
}
|
||||
// A press on the scroll bar (not on the content).
|
||||
if (event instanceof PointerEvent && event.target !== event.currentTarget) return
|
||||
follow = false
|
||||
}
|
||||
|
||||
/** "Microsoft Teams · heute 10:14 · 32 min" (no duration while recording). */
|
||||
function defaultTitle(call: CallListItem): string {
|
||||
const parts = [call.app, formatDetailTime(call.started_at)]
|
||||
@@ -256,23 +376,31 @@
|
||||
return parts.join(' · ')
|
||||
}
|
||||
|
||||
/** The account list plus the stored account if it is no longer listed. */
|
||||
let accountOptions = $derived.by(() => {
|
||||
const stored = detail?.call.account_id
|
||||
if (!stored || accounts.some((a) => a.id === stored)) return accounts
|
||||
return [...accounts, { id: stored, name: `${stored} (unbekannt)` }]
|
||||
})
|
||||
// Also while an upload started elsewhere (e.g. before switching views)
|
||||
// still runs in the app.
|
||||
let isUploading = $derived(
|
||||
detail !== null && (uploading.includes(detail.call.id) || detail.uploading),
|
||||
)
|
||||
|
||||
// A failed start (e.g. missing key) also marks the call failed; its
|
||||
// error is then shown once, in the failure box.
|
||||
let shownActionError = $derived(actionError !== detail?.call.error ? actionError : '')
|
||||
|
||||
// Calls that still need the user's attention (not transcribed, or
|
||||
// transcribed but not uploaded here) — shown as "Gespräche · N offen".
|
||||
let openCount = $derived(calls.filter((c) => c.needs_action).length)
|
||||
|
||||
/** The transcript line being heard, highlighted while the mix is loaded. */
|
||||
let activeIndex = $derived(
|
||||
detail && playerTime !== null ? segmentAt(detail.segments, playerTime) : null,
|
||||
)
|
||||
</script>
|
||||
|
||||
<main class="main">
|
||||
<UpdateBanner />
|
||||
<aside class="sidebar">
|
||||
<header class="sidebar-header">
|
||||
<h1>Gespräche</h1>
|
||||
<h1>Gespräche{#if openCount > 0}<span class="open-count" title="{openCount} offen" aria-label="{openCount} offen">{openCount}</span>{/if}</h1>
|
||||
<div class="header-actions">
|
||||
<button
|
||||
class="btn small record-btn"
|
||||
@@ -300,7 +428,15 @@
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<section class="detail">
|
||||
<!-- The handlers only watch for scrolling by hand (see manualScroll). -->
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<section
|
||||
class="detail"
|
||||
onwheel={manualScroll}
|
||||
ontouchmove={manualScroll}
|
||||
onkeydown={manualScroll}
|
||||
onpointerdown={manualScroll}
|
||||
>
|
||||
{#if detail}
|
||||
{@const call = detail.call}
|
||||
<header class="detail-header">
|
||||
@@ -321,7 +457,7 @@
|
||||
<button class="edit-title" title="Titel ändern" onclick={startTitleEdit}>✎</button>
|
||||
</h1>
|
||||
{/if}
|
||||
<StatusPill status={call.status} interrupted={call.interrupted} />
|
||||
<StatusPill state={call.list_state} interrupted={call.interrupted} />
|
||||
</div>
|
||||
{#if editingTitle}
|
||||
<p class="muted subline">Enter speichert, Esc bricht ab. Leer = Standardtitel.</p>
|
||||
@@ -332,34 +468,79 @@
|
||||
<p class="error">{titleError}</p>
|
||||
{/if}
|
||||
<div class="toolbar">
|
||||
<label class="customer">
|
||||
<span>Kunde:</span>
|
||||
<select value={call.account_id ?? ''} disabled={busy} onchange={changeAccount}>
|
||||
<option value="">— kein Kunde —</option>
|
||||
{#each accountOptions as account (account.id)}
|
||||
<option value={account.id}>{account.name}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</label>
|
||||
{#if call.status === 'done' && call.uploaded_at}
|
||||
<span class="muted uploaded">
|
||||
Hochgeladen am {formatDateTime(call.uploaded_at)} (ID {call.crm_transcript_id})
|
||||
</span>
|
||||
{/if}
|
||||
<span class="actions">
|
||||
{#if call.status === 'awaiting_decision'}
|
||||
<LanguageSelect bind:value={language} disabled={busy} />
|
||||
<button class="btn primary" disabled={busy} onclick={transcribe}>Transkribieren</button>
|
||||
<button class="btn danger" disabled={busy} onclick={discard}>Verwerfen</button>
|
||||
{:else if call.status === 'failed'}
|
||||
<LanguageSelect bind:value={language} disabled={busy} />
|
||||
<button class="btn primary" disabled={busy} onclick={retry}>Erneut versuchen</button>
|
||||
<button class="btn danger" disabled={busy} onclick={discard}>Verwerfen</button>
|
||||
{:else if call.status === 'done'}
|
||||
<span title="Kommt in einer späteren Version">
|
||||
<button class="btn" disabled>In Kundenakte speichern</button>
|
||||
</span>
|
||||
{#if !call.uploaded_at}
|
||||
<button
|
||||
class="btn primary"
|
||||
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}
|
||||
<button class="btn danger" disabled={deleteBusy || isUploading} onclick={askDelete}>
|
||||
Löschen
|
||||
</button>
|
||||
{/if}
|
||||
</span>
|
||||
</div>
|
||||
{#if shownActionError}
|
||||
<p class="error">{shownActionError}</p>
|
||||
{/if}
|
||||
{#if uploadErrors[call.id]}
|
||||
<p class="error">{uploadErrors[call.id]}</p>
|
||||
{/if}
|
||||
</header>
|
||||
|
||||
{#if call.status !== 'recording' && call.status !== 'processing'}
|
||||
{#if detail.audio_available}
|
||||
<div class="playback-bar">
|
||||
{#key call.id}
|
||||
<Player
|
||||
bind:this={player}
|
||||
callId={call.id}
|
||||
estimate={call.duration_secs}
|
||||
ontime={(secs) => (playerTime = secs)}
|
||||
onplaying={(value) => (playing = value)}
|
||||
/>
|
||||
{/key}
|
||||
{#if call.status === 'done' && detail.segments.length > 0}
|
||||
<button
|
||||
class="btn small follow"
|
||||
class:on={follow}
|
||||
aria-pressed={follow}
|
||||
title="Das Transkript scrollt mit der Wiedergabe mit"
|
||||
onclick={() => (follow = !follow)}>folgen</button
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
{:else if detail.audio_deleted && retentionDays !== null}
|
||||
<p class="muted no-audio">
|
||||
Audio nicht mehr vorhanden – Aufnahmen werden {retentionPeriod} nach der
|
||||
Transkription gelöscht (<a href="#/settings">Einstellungen</a>).
|
||||
</p>
|
||||
{:else if detail.audio_deleted}
|
||||
<p class="muted no-audio">Audio nicht mehr vorhanden.</p>
|
||||
{:else}
|
||||
<p class="muted no-audio">Audio nicht vorhanden.</p>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
<div class="body">
|
||||
{#if call.status === 'recording'}
|
||||
<p class="state rec">● Aufnahme läuft</p>
|
||||
@@ -376,24 +557,6 @@
|
||||
<strong>Verarbeitung fehlgeschlagen</strong>
|
||||
<div>{call.error ?? 'Unbekannter Fehler'}</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="tabs" role="tablist">
|
||||
<button
|
||||
role="tab"
|
||||
aria-selected={tab === 'summary'}
|
||||
class:active={tab === 'summary'}
|
||||
onclick={() => (tab = 'summary')}>Zusammenfassung</button
|
||||
>
|
||||
<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}
|
||||
@@ -401,11 +564,46 @@
|
||||
onrename={rename}
|
||||
onmerge={merge}
|
||||
onunmerge={unmerge}
|
||||
{activeIndex}
|
||||
follow={follow && playing}
|
||||
onseek={detail.audio_available ? playFrom : undefined}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if deleteDialogOpen}
|
||||
<div
|
||||
class="dialog-backdrop"
|
||||
onclick={cancelDelete}
|
||||
onkeydown={(e) => e.key === 'Escape' && cancelDelete()}
|
||||
role="presentation"
|
||||
>
|
||||
<div
|
||||
class="dialog"
|
||||
role="alertdialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="delete-dialog-title"
|
||||
tabindex="-1"
|
||||
onclick={(e) => e.stopPropagation()}
|
||||
onkeydown={(e) => e.stopPropagation()}
|
||||
>
|
||||
<p class="dialog-title" id="delete-dialog-title">Gespräch löschen?</p>
|
||||
<p>Audio und Transkript werden unwiderruflich von diesem PC gelöscht.</p>
|
||||
{#if call.uploaded_at}
|
||||
<p>Die Kopie im CRM bleibt erhalten.</p>
|
||||
{/if}
|
||||
{#if deleteError}
|
||||
<p class="error">{deleteError}</p>
|
||||
{/if}
|
||||
<div class="dialog-actions">
|
||||
<button class="btn danger" disabled={deleteBusy} onclick={confirmDelete}>
|
||||
Löschen
|
||||
</button>
|
||||
<button class="btn" disabled={deleteBusy} onclick={cancelDelete}>Abbrechen</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{:else if detailError}
|
||||
<p class="error pad">{detailError}</p>
|
||||
{:else if loaded && selectedId === null && calls.length > 0}
|
||||
@@ -444,21 +642,47 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 14px 12px 10px 16px;
|
||||
gap: 4px;
|
||||
padding: 12px 6px 8px 10px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.sidebar-header h1 {
|
||||
font-size: 16px;
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
font-size: 15px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.open-count {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-left: 4px;
|
||||
min-width: 14px;
|
||||
height: 14px;
|
||||
padding: 0 3px;
|
||||
border-radius: 999px;
|
||||
background: var(--primary-soft);
|
||||
color: var(--primary);
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
.record-btn {
|
||||
padding: 2px 6px;
|
||||
font-size: 11px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
@@ -475,9 +699,9 @@
|
||||
|
||||
.gear {
|
||||
color: var(--muted);
|
||||
font-size: 18px;
|
||||
font-size: 15px;
|
||||
line-height: 1;
|
||||
padding: 4px 6px;
|
||||
padding: 3px 4px;
|
||||
border-radius: 6px;
|
||||
text-decoration: none;
|
||||
}
|
||||
@@ -552,27 +776,52 @@
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.customer {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.customer select {
|
||||
max-width: 260px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.uploaded {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.detail-header .error {
|
||||
margin: 10px 0 0;
|
||||
}
|
||||
|
||||
/* Stays at the top while the transcript scrolls under it. */
|
||||
.playback-bar {
|
||||
position: sticky;
|
||||
top: -18px; /* the detail's top padding: flush with its edge */
|
||||
z-index: 2;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin: 0 -24px 14px;
|
||||
padding: 8px 24px;
|
||||
background: var(--bg);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.follow {
|
||||
flex-shrink: 0;
|
||||
color: var(--muted);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.follow.on {
|
||||
border-color: var(--primary);
|
||||
background: var(--primary-soft);
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
.no-audio {
|
||||
margin: 0 0 14px;
|
||||
}
|
||||
|
||||
.state {
|
||||
color: var(--muted);
|
||||
}
|
||||
@@ -589,30 +838,39 @@
|
||||
color: var(--rec);
|
||||
}
|
||||
|
||||
.tabs {
|
||||
.dialog-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(29, 35, 48, 0.4);
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.tabs button {
|
||||
padding: 8px 14px;
|
||||
border: none;
|
||||
border-bottom: 2px solid transparent;
|
||||
margin-bottom: -1px;
|
||||
background: none;
|
||||
font: inherit;
|
||||
.dialog {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 12px 32px rgba(29, 35, 48, 0.25);
|
||||
padding: 20px;
|
||||
width: min(420px, calc(100vw - 32px));
|
||||
}
|
||||
|
||||
.dialog-title {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: var(--muted);
|
||||
cursor: pointer;
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
|
||||
.tabs button.active {
|
||||
color: var(--primary);
|
||||
border-bottom-color: var(--primary);
|
||||
.dialog p {
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
|
||||
.tab-panel {
|
||||
padding-top: 14px;
|
||||
.dialog-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -11,13 +11,21 @@
|
||||
type PendingPrompt,
|
||||
} from '../lib/api'
|
||||
import { formatMinutes, formatTimeRange } from '../lib/format'
|
||||
import LanguageSelect from '../lib/LanguageSelect.svelte'
|
||||
|
||||
let brief = $state<PendingPrompt | null>(null)
|
||||
let busy = $state(false)
|
||||
let error = $state('')
|
||||
let language = $state('de')
|
||||
|
||||
function show(next: PendingPrompt | null) {
|
||||
if (next?.id !== brief?.id) error = ''
|
||||
// A refresh of the same call keeps what the user picked, unless the
|
||||
// backend's suggestion changed (e.g. a transcription started from the
|
||||
// main window in another language).
|
||||
if (next && (next.id !== brief?.id || next.language !== brief?.language)) {
|
||||
language = next.language
|
||||
}
|
||||
brief = next
|
||||
}
|
||||
|
||||
@@ -54,6 +62,8 @@
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
|
||||
const transcribe = () => run((id) => transcribeCall(id, language))
|
||||
</script>
|
||||
|
||||
<main class="prompt">
|
||||
@@ -64,7 +74,8 @@
|
||||
<div class="muted">Weitere Gespräche warten: {brief.more_waiting}</div>
|
||||
{/if}
|
||||
<div class="actions">
|
||||
<button class="btn primary" disabled={busy} onclick={() => run(transcribeCall)}>
|
||||
<LanguageSelect bind:value={language} disabled={busy} />
|
||||
<button class="btn primary" disabled={busy} onclick={transcribe}>
|
||||
Transkribieren
|
||||
</button>
|
||||
<button class="btn danger" disabled={busy} onclick={() => run(discardCall)}>Verwerfen</button>
|
||||
|
||||
+346
-13
@@ -1,41 +1,217 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte'
|
||||
import { formatDate } from '../lib/format'
|
||||
import {
|
||||
backendLogin,
|
||||
backendLogout,
|
||||
backendServer,
|
||||
backendStatus,
|
||||
canSelfUpdate,
|
||||
checkForUpdateNow,
|
||||
errorText,
|
||||
getAppVersion,
|
||||
getSettings,
|
||||
getUpdate,
|
||||
hasApiKey,
|
||||
installUpdate,
|
||||
listDevices,
|
||||
meterFill,
|
||||
onBackendChanged,
|
||||
onBackendLoginError,
|
||||
onUpdateAvailable,
|
||||
onUpdateProgress,
|
||||
openBackendKeysPage,
|
||||
saveSettings,
|
||||
setApiKey,
|
||||
testDevices,
|
||||
updateProgressText,
|
||||
UPDATE_BUSY_HINT,
|
||||
type BackendServer,
|
||||
type BackendStatus,
|
||||
type DeviceInfo,
|
||||
type DeviceLevels,
|
||||
type Devices,
|
||||
type Service,
|
||||
type Settings,
|
||||
type UpdateCheckResult,
|
||||
type UpdateInfo,
|
||||
type UpdateProgress,
|
||||
} from '../lib/api'
|
||||
|
||||
const services: { id: Service; name: string }[] = [
|
||||
{ id: 'deepscript', name: 'DeepScript' },
|
||||
{ id: 'anthropic', name: 'Anthropic (Claude)' },
|
||||
]
|
||||
|
||||
let settings = $state<Settings | null>(null)
|
||||
/** The vocabulary textarea's raw text, one term per line; converted
|
||||
* to/from `settings.vocabulary` on load/save (the backend trims, drops
|
||||
* blanks and deduplicates — see `Settings::edited`). */
|
||||
let vocabularyText = $state('')
|
||||
let devices = $state<Devices>({ inputs: [], outputs: [] })
|
||||
let keySaved = $state<Record<Service, boolean>>({ deepscript: false, anthropic: false })
|
||||
let keyInput = $state<Record<Service, string>>({ deepscript: '', anthropic: '' })
|
||||
let keySaved = $state<Record<Service, boolean>>({ deepscript: false })
|
||||
let keyInput = $state<Record<Service, string>>({ deepscript: '' })
|
||||
let newApp = $state('')
|
||||
let testing = $state(false)
|
||||
let testResult = $state<DeviceLevels | null>(null)
|
||||
let message = $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() {
|
||||
try {
|
||||
settings = await getSettings()
|
||||
vocabularyText = settings.vocabulary.join('\n')
|
||||
for (const { id } of services) keySaved[id] = await hasApiKey(id)
|
||||
devices = await listDevices()
|
||||
} catch (err) {
|
||||
@@ -90,14 +266,29 @@
|
||||
settings ? delayError(settings.start_after_secs, 1, 30, 'Start nach') : '',
|
||||
)
|
||||
let endError = $derived(settings ? delayError(settings.end_after_secs, 3, 120, 'Ende nach') : '')
|
||||
/** The range the backend accepts (`RETENTION_DAYS`). */
|
||||
function retentionValid(days: number | null | undefined): days is number {
|
||||
return typeof days === 'number' && Number.isInteger(days) && days >= 1 && days <= 3650
|
||||
}
|
||||
|
||||
/** The retention period in the hint ("7 Tage", "1 Tag"; "N Tage" while
|
||||
* the field holds no valid value). */
|
||||
let retentionShown = $derived.by(() => {
|
||||
const days = settings?.retention_days
|
||||
if (!retentionValid(days)) return 'N Tage'
|
||||
return days === 1 ? '1 Tag' : `${days} Tage`
|
||||
})
|
||||
|
||||
async function persist() {
|
||||
if (!settings) return
|
||||
if (startError || endError) throw startError || endError
|
||||
if (!Number.isInteger(settings.retention_days) || settings.retention_days < 1) {
|
||||
throw 'Aufbewahrung: bitte eine ganze Zahl ab 1 eingeben'
|
||||
}
|
||||
if (!retentionValid(settings.retention_days)) throw 'Aufbewahrung: 1–3650 Tage'
|
||||
settings.vocabulary = vocabularyText.split('\n')
|
||||
await saveSettings($state.snapshot(settings))
|
||||
// Re-read: the backend trims/dedupes the vocabulary, so the textarea
|
||||
// should show the cleaned-up list, not what was just typed.
|
||||
settings = await getSettings()
|
||||
vocabularyText = settings.vocabulary.join('\n')
|
||||
}
|
||||
|
||||
async function runTest() {
|
||||
@@ -146,6 +337,46 @@
|
||||
{/each}
|
||||
</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">
|
||||
<h2>Audio</h2>
|
||||
<div class="grid">
|
||||
@@ -251,18 +482,84 @@
|
||||
<section class="card">
|
||||
<h2>Allgemein</h2>
|
||||
<div class="grid">
|
||||
<label for="language">Sprache der Gespräche</label>
|
||||
<select id="language" bind:value={settings.language}>
|
||||
<option value="de">Deutsch</option>
|
||||
<option value="en">Englisch</option>
|
||||
</select>
|
||||
<label for="retention">Aufbewahrung der Audiodateien</label>
|
||||
<span><input id="retention" type="number" min="1" bind:value={settings.retention_days} /> Tage</span>
|
||||
<span><input id="retention" type="number" min="1" max="3650" bind:value={settings.retention_days} /> Tage</span>
|
||||
<span></span>
|
||||
<span class="muted">
|
||||
Audio wird {retentionShown} nach der Transkription gelöscht, nicht transkribierte
|
||||
Aufnahmen {retentionShown} nach dem Gespräch; das Transkript bleibt.
|
||||
</span>
|
||||
<label for="autostart">Beim Anmelden starten</label>
|
||||
<input id="autostart" type="checkbox" bind:checked={settings.autostart} />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h2>Transkription</h2>
|
||||
<div class="grid">
|
||||
<label for="deepscript-model">Modell</label>
|
||||
<select id="deepscript-model" bind:value={settings.deepscript_model}>
|
||||
<option value="premium">Premium</option>
|
||||
<option value="premium_jade">Premium Jade</option>
|
||||
</select>
|
||||
<span></span>
|
||||
<span class="muted">Gilt für neue Transkriptionen.</span>
|
||||
</div>
|
||||
<label for="vocabulary" class="vocabulary-label">Vokabular (ein Begriff pro Zeile)</label>
|
||||
<textarea id="vocabulary" rows="6" bind:value={vocabularyText}></textarea>
|
||||
<p class="muted">
|
||||
Namen, Firmen- und Produktbegriffe, die oft falsch erkannt werden.
|
||||
</p>
|
||||
</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 & 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">
|
||||
<button class="btn primary" onclick={() => run(persist, 'Einstellungen gespeichert ✓')}>
|
||||
Speichern
|
||||
@@ -316,6 +613,21 @@
|
||||
justify-self: start;
|
||||
}
|
||||
|
||||
.vocabulary-label {
|
||||
display: block;
|
||||
margin-top: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
textarea#vocabulary {
|
||||
width: 100%;
|
||||
max-width: 420px;
|
||||
margin-top: 6px;
|
||||
font-family: inherit;
|
||||
font-size: 13px;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin: 12px 0;
|
||||
padding: 8px 10px;
|
||||
@@ -377,6 +689,27 @@
|
||||
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 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
Reference in New Issue
Block a user