Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
687d4bccfe | ||
|
|
fa55dcb7bc | ||
|
|
dad98b4558 | ||
|
|
96eec22971 | ||
|
|
1735f431dd | ||
|
|
782b24a6de | ||
|
|
3358de7888 | ||
|
|
f045424e97 | ||
|
|
58e96a2954 | ||
|
|
54a81e5ba0 | ||
|
|
eff07d2f59 | ||
|
|
572c685396 |
Generated
+56
-1
@@ -445,8 +445,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "call-recorder"
|
name = "call-recorder"
|
||||||
version = "0.1.1"
|
version = "0.2.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"async-trait",
|
||||||
"chrono",
|
"chrono",
|
||||||
"log",
|
"log",
|
||||||
"recorder-audio",
|
"recorder-audio",
|
||||||
@@ -458,9 +459,11 @@ dependencies = [
|
|||||||
"tauri-plugin-autostart",
|
"tauri-plugin-autostart",
|
||||||
"tauri-plugin-log",
|
"tauri-plugin-log",
|
||||||
"tauri-plugin-notification",
|
"tauri-plugin-notification",
|
||||||
|
"tauri-plugin-opener",
|
||||||
"tauri-plugin-single-instance",
|
"tauri-plugin-single-instance",
|
||||||
"tauri-plugin-updater",
|
"tauri-plugin-updater",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
|
"tokio",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2059,6 +2062,25 @@ version = "2.12.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
|
checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "is-docker"
|
||||||
|
version = "0.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3"
|
||||||
|
dependencies = [
|
||||||
|
"once_cell",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "is-wsl"
|
||||||
|
version = "0.4.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5"
|
||||||
|
dependencies = [
|
||||||
|
"is-docker",
|
||||||
|
"once_cell",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "itoa"
|
name = "itoa"
|
||||||
version = "1.0.18"
|
version = "1.0.18"
|
||||||
@@ -2981,6 +3003,17 @@ version = "1.21.4"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "open"
|
||||||
|
version = "5.4.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8d8c8b8e725ad26404d6896eb2f064294a0a7b4f1d9120210d85544684c4ca95"
|
||||||
|
dependencies = [
|
||||||
|
"dunce",
|
||||||
|
"is-wsl",
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "openssl-probe"
|
name = "openssl-probe"
|
||||||
version = "0.2.2"
|
version = "0.2.2"
|
||||||
@@ -4712,6 +4745,28 @@ dependencies = [
|
|||||||
"zbus 5.19.0",
|
"zbus 5.19.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tauri-plugin-opener"
|
||||||
|
version = "2.7.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "53810be1b4fed22bb6ac3f4cab5a2b80d9391d1af436bda145607532bc0bb219"
|
||||||
|
dependencies = [
|
||||||
|
"dunce",
|
||||||
|
"glob",
|
||||||
|
"objc2-app-kit",
|
||||||
|
"objc2-foundation",
|
||||||
|
"open",
|
||||||
|
"schemars 0.8.22",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"tauri",
|
||||||
|
"tauri-plugin",
|
||||||
|
"thiserror 2.0.21",
|
||||||
|
"url",
|
||||||
|
"windows",
|
||||||
|
"zbus 5.19.0",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-plugin-single-instance"
|
name = "tauri-plugin-single-instance"
|
||||||
version = "2.5.5"
|
version = "2.5.5"
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
# Gesprächsrekorder
|
# Gesprächsrekorder
|
||||||
|
|
||||||
A Tauri 2 desktop app that records calls (Teams, MicroSIP, browser-based
|
A Tauri 2 desktop app that records calls (Teams, MicroSIP, browser-based
|
||||||
softphones, …), then transcribes and summarizes them.
|
softphones, …) and transcribes them.
|
||||||
|
|
||||||
## Workspace layout
|
## Workspace layout
|
||||||
|
|
||||||
- `crates/core` (`recorder-core`) — core domain logic: call detection,
|
- `crates/core` (`recorder-core`) — core domain logic: call detection,
|
||||||
recording orchestration, transcription and summarization. Independent of
|
recording orchestration and transcription. Independent of
|
||||||
the Tauri app shell and the audio backend so it can be unit-tested without
|
the Tauri app shell and the audio backend so it can be unit-tested without
|
||||||
a GUI, a sound device or network access.
|
a GUI, a sound device or network access.
|
||||||
- `crates/audio` (`recorder-audio`) — audio capture and WAV/FLAC encoding.
|
- `crates/audio` (`recorder-audio`) — audio capture and WAV/FLAC encoding.
|
||||||
|
|||||||
+31
-48
@@ -3,7 +3,7 @@
|
|||||||
A release consists of:
|
A release consists of:
|
||||||
|
|
||||||
- the Windows NSIS installer (per-user, no admin rights), cross-built on Debian,
|
- the Windows NSIS installer (per-user, no admin rights), cross-built on Debian,
|
||||||
- the Debian `.deb` and `.AppImage`,
|
- the Debian `.deb`,
|
||||||
- an updater signature (`.sig`) for each of them,
|
- an updater signature (`.sig`) for each of them,
|
||||||
- `latest.json`, the update feed the installed Windows apps read.
|
- `latest.json`, the update feed the installed Windows apps read.
|
||||||
|
|
||||||
@@ -46,8 +46,7 @@ restarts the app. Debian builds do not update themselves.
|
|||||||
`https://gitea.euvino.eu/public/call-recorder`. The download URLs in `latest.json`
|
`https://gitea.euvino.eu/public/call-recorder`. The download URLs in `latest.json`
|
||||||
point to `${RELEASE_BASE_URL}/releases/download/v<version>/<file>`.
|
point to `${RELEASE_BASE_URL}/releases/download/v<version>/<file>`.
|
||||||
- `UPDATE_JSON_URLS`: where the app looks for `latest.json`. `build-release.sh`
|
- `UPDATE_JSON_URLS`: where the app looks for `latest.json`. `build-release.sh`
|
||||||
writes them, in this order, into `plugins.updater.endpoints` in
|
writes them into `plugins.updater.endpoints` in `src-tauri/tauri.conf.json`.
|
||||||
`src-tauri/tauri.conf.json`.
|
|
||||||
|
|
||||||
Do not edit the endpoints in `tauri.conf.json` by hand. Change `release.env`; the
|
Do not edit the endpoints in `tauri.conf.json` by hand. Change `release.env`; the
|
||||||
next release build writes them into `tauri.conf.json`.
|
next release build writes them into `tauri.conf.json`.
|
||||||
@@ -55,43 +54,25 @@ next release build writes them into `tauri.conf.json`.
|
|||||||
The repository and its releases must be readable without logging in: the app
|
The repository and its releases must be readable without logging in: the app
|
||||||
downloads anonymously.
|
downloads anonymously.
|
||||||
|
|
||||||
### The two feed URLs
|
### The feed URL
|
||||||
|
|
||||||
The app tries the endpoints in order and uses the first one that returns a release.
|
Verified on Gitea 1.27.3: `releases/latest/download/<file>` does **not** redirect
|
||||||
A `404` or a network error on one moves on to the next one:
|
to a release's assets, even for the newest non-draft, non-prerelease release —
|
||||||
|
requesting it returns `404`. So the feed lives only at
|
||||||
|
|
||||||
1. `https://gitea.euvino.eu/public/call-recorder/releases/latest/download/latest.json`:
|
```
|
||||||
`latest.json` as an asset of the newest release (not a draft, not a pre-release).
|
https://gitea.euvino.eu/public/call-recorder/raw/branch/master/latest.json
|
||||||
This works only if Gitea redirects `releases/latest/download/<file>` to the newest
|
|
||||||
release.
|
|
||||||
2. `https://gitea.euvino.eu/public/call-recorder/raw/branch/master/latest.json`:
|
|
||||||
`latest.json` committed to the root of `master`.
|
|
||||||
|
|
||||||
Each release serves both:
|
|
||||||
|
|
||||||
- uploading the release assets covers URL 1 (step 7 below);
|
|
||||||
- committing `latest.json` to the root of `master` covers URL 2 (step 8 below).
|
|
||||||
|
|
||||||
The endpoints are compiled into the app. Installed versions keep asking the URLs
|
|
||||||
they were built with, which is why both are configured from the start.
|
|
||||||
|
|
||||||
After the first release, check which URL works:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
curl -sIL https://gitea.euvino.eu/public/call-recorder/releases/latest/download/latest.json
|
|
||||||
curl -sIL https://gitea.euvino.eu/public/call-recorder/raw/branch/master/latest.json
|
|
||||||
```
|
```
|
||||||
|
|
||||||
The final status of a working URL is `200`. Then:
|
`latest.json` committed to the root of `master`. This makes committing
|
||||||
|
`latest.json` after every release **mandatory**, not optional (step 8 below) —
|
||||||
|
there is no redirect to fall back on.
|
||||||
|
|
||||||
- **URL 1 works:** a later version may drop URL 2 from `UPDATE_JSON_URLS`. Every
|
Versions 0.1.0 and 0.1.1 were built with both URLs compiled in (the endpoints
|
||||||
installed version also asks URL 1, so step 8 is no longer needed.
|
are fixed at build time; installed apps keep asking the URLs they were built
|
||||||
- **Only URL 2 works:** a later version may drop URL 1. Step 8 (committing
|
with). They still try `releases/latest/download/latest.json` first on every
|
||||||
`latest.json`) stays part of every release.
|
check; that is harmless — it 404s and the app falls through to the
|
||||||
|
`raw/branch/master` URL, which answers normally.
|
||||||
Caveat: if URL 1 answered `200` with something that is not JSON (e.g. an HTML page),
|
|
||||||
the updater would stop there instead of trying URL 2. Gitea answers a missing file
|
|
||||||
with `404`, which falls through as intended.
|
|
||||||
|
|
||||||
## Releasing a version
|
## Releasing a version
|
||||||
|
|
||||||
@@ -120,8 +101,8 @@ e.g. for the first release `0.1.0`.
|
|||||||
- sets the version in `src-tauri/tauri.conf.json`, `src-tauri/Cargo.toml` and
|
- sets the version in `src-tauri/tauri.conf.json`, `src-tauri/Cargo.toml` and
|
||||||
`ui/package.json` (the build updates `Cargo.lock` too), and writes the endpoints
|
`ui/package.json` (the build updates `Cargo.lock` too), and writes the endpoints
|
||||||
from `release.env` into `tauri.conf.json`,
|
from `release.env` into `tauri.conf.json`,
|
||||||
- builds the Windows installer (`scripts/build-windows.sh`), the `.deb` and the
|
- builds the Windows installer (`scripts/build-windows.sh`) and the `.deb`, each
|
||||||
`.AppImage`, each with its `.sig`,
|
with its `.sig`,
|
||||||
- copies them to `dist-release/0.1.1/` under ASCII names (`Gespraechsrekorder_…`)
|
- copies them to `dist-release/0.1.1/` under ASCII names (`Gespraechsrekorder_…`)
|
||||||
and writes `latest.json` with `scripts/make-latest-json.sh`.
|
and writes `latest.json` with `scripts/make-latest-json.sh`.
|
||||||
|
|
||||||
@@ -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_x64-setup.exe` (+ `.sig`) | Windows installer and update package |
|
||||||
| `Gespraechsrekorder_0.1.1_amd64.deb` (+ `.sig`) | Debian package |
|
| `Gespraechsrekorder_0.1.1_amd64.deb` (+ `.sig`) | Debian package |
|
||||||
| `Gespraechsrekorder_0.1.1_amd64.AppImage` (+ `.sig`) | Debian AppImage |
|
|
||||||
| `latest.json` | Update feed |
|
| `latest.json` | Update feed |
|
||||||
|
|
||||||
4. Commit the version bump the script left in the working tree:
|
4. Commit the version bump the script left in the working tree:
|
||||||
@@ -155,12 +135,14 @@ e.g. for the first release `0.1.0`.
|
|||||||
<https://gitea.euvino.eu/public/call-recorder/releases/new>. Do not mark it as a
|
<https://gitea.euvino.eu/public/call-recorder/releases/new>. Do not mark it as a
|
||||||
draft or a pre-release, otherwise it is not the "latest" release.
|
draft or a pre-release, otherwise it is not the "latest" release.
|
||||||
|
|
||||||
7. Upload every file from `dist-release/0.1.1/` as a release asset, keeping the file
|
7. Upload the installer, the `.deb` and their `.sig` files from
|
||||||
names (`latest.json` points to them). Upload the installers, packages and `.sig`
|
`dist-release/0.1.1/` as release assets, keeping the file names (`latest.json`
|
||||||
files first and **`latest.json` last**. As soon as `latest.json` is visible,
|
points to them). `latest.json` itself does not need to be uploaded as a release
|
||||||
installed apps may try to download the files it lists.
|
asset: the feed is served from the committed file (step 8), not from
|
||||||
|
`releases/latest/download/latest.json` (see "The feed URL" above).
|
||||||
|
|
||||||
8. Only after all assets are uploaded, publish the feed for URL 2 as well:
|
8. Only after all assets from step 7 are uploaded and downloadable (their URLs are
|
||||||
|
what the feed will point to), commit the feed:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
cp dist-release/0.1.1/latest.json latest.json
|
cp dist-release/0.1.1/latest.json latest.json
|
||||||
@@ -169,15 +151,16 @@ e.g. for the first release `0.1.0`.
|
|||||||
git push origin master
|
git push origin master
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Committing `latest.json` is mandatory for every release — it is the only
|
||||||
|
place the feed lives.
|
||||||
|
|
||||||
9. Check the feed:
|
9. Check the feed:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
curl -sL https://gitea.euvino.eu/public/call-recorder/releases/latest/download/latest.json | jq .
|
|
||||||
curl -sL https://gitea.euvino.eu/public/call-recorder/raw/branch/master/latest.json | jq .
|
curl -sL https://gitea.euvino.eu/public/call-recorder/raw/branch/master/latest.json | jq .
|
||||||
```
|
```
|
||||||
|
|
||||||
The URL(s) that work must show the new version, and the `url` entries must
|
It must show the new version, and the `url` entry must download.
|
||||||
download.
|
|
||||||
|
|
||||||
## Checking an update on Windows 11
|
## Checking an update on Windows 11
|
||||||
|
|
||||||
@@ -211,5 +194,5 @@ and 30 minutes, then every 6 hours. The log
|
|||||||
- `RELEASE_ALLOW_KEY_MISMATCH=1` lets `build-release.sh` build with a key that does
|
- `RELEASE_ALLOW_KEY_MISMATCH=1` lets `build-release.sh` build with a key that does
|
||||||
not match `plugins.updater.pubkey`. Use it only to test the pipeline with a throwaway
|
not match `plugins.updater.pubkey`. Use it only to test the pipeline with a throwaway
|
||||||
key. Installed apps reject such a release, so never publish it.
|
key. Installed apps reject such a release, so never publish it.
|
||||||
- `latest.json` also lists the AppImage (`linux-x86_64`). The Debian builds do not
|
- `latest.json` only lists `windows-x86_64`. Debian installs from the `.deb` and
|
||||||
check for updates yet.
|
does not self-update, so Linux has no entry in the feed.
|
||||||
|
|||||||
@@ -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,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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,6 +21,10 @@ pub struct CallListItem {
|
|||||||
pub interrupted: bool,
|
pub interrupted: bool,
|
||||||
/// The name the user gave the call, if any.
|
/// The name the user gave the call, if any.
|
||||||
pub title: Option<String>,
|
pub title: Option<String>,
|
||||||
|
/// The id the CRM gave the transcript at its last upload.
|
||||||
|
pub crm_transcript_id: Option<String>,
|
||||||
|
/// When the transcript was last uploaded.
|
||||||
|
pub uploaded_at: Option<DateTime<Local>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CallListItem {
|
impl CallListItem {
|
||||||
@@ -33,6 +37,8 @@ impl CallListItem {
|
|||||||
status: call.status,
|
status: call.status,
|
||||||
interrupted: call.interrupted,
|
interrupted: call.interrupted,
|
||||||
title: call.title.clone(),
|
title: call.title.clone(),
|
||||||
|
crm_transcript_id: call.crm_transcript_id.clone(),
|
||||||
|
uploaded_at: call.uploaded_at,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -45,13 +51,14 @@ pub fn duration_secs(call: &Call) -> i64 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The selected call's header data: its list row plus the error of a
|
/// The selected call's header data: its list row plus the error of a
|
||||||
/// failed run and the assigned account.
|
/// failed run and when it was transcribed (only a transcribed call can be
|
||||||
|
/// uploaded).
|
||||||
#[derive(Serialize, Clone, Debug, PartialEq)]
|
#[derive(Serialize, Clone, Debug, PartialEq)]
|
||||||
pub struct CallHeader {
|
pub struct CallHeader {
|
||||||
#[serde(flatten)]
|
#[serde(flatten)]
|
||||||
pub item: CallListItem,
|
pub item: CallListItem,
|
||||||
pub error: Option<String>,
|
pub error: Option<String>,
|
||||||
pub account_id: Option<String>,
|
pub transcribed_at: Option<DateTime<Local>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A transcript line with the speaker's display label.
|
/// A transcript line with the speaker's display label.
|
||||||
@@ -90,6 +97,9 @@ pub struct CallDetail {
|
|||||||
pub speaker_names: BTreeMap<String, String>,
|
pub speaker_names: BTreeMap<String, String>,
|
||||||
/// The call's speaker merges, by source speaker number.
|
/// The call's speaker merges, by source speaker number.
|
||||||
pub merges: Vec<MergeView>,
|
pub merges: Vec<MergeView>,
|
||||||
|
/// Whether the transcript is being uploaded right now. Set by the app,
|
||||||
|
/// which tracks its uploads; `false` from [`CallDetail::of`].
|
||||||
|
pub uploading: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CallDetail {
|
impl CallDetail {
|
||||||
@@ -115,15 +125,80 @@ impl CallDetail {
|
|||||||
call: CallHeader {
|
call: CallHeader {
|
||||||
item: CallListItem::of(call),
|
item: CallListItem::of(call),
|
||||||
error: call.error.clone(),
|
error: call.error.clone(),
|
||||||
account_id: call.account_id.clone(),
|
transcribed_at: call.transcribed_at,
|
||||||
},
|
},
|
||||||
segments,
|
segments,
|
||||||
merges: merge_views(merges, &speaker_names),
|
merges: merge_views(merges, &speaker_names),
|
||||||
|
uploading: false,
|
||||||
speaker_names,
|
speaker_names,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl CallDetail {
|
||||||
|
/// The transcript as plain text for the CRM, as the user sees it
|
||||||
|
/// (speaker merges and renames applied): a header with title, date,
|
||||||
|
/// call app and duration, a blank line, then one `[mm:ss] Name: text`
|
||||||
|
/// line per segment (`h:mm:ss` from one hour on). Blank segments are
|
||||||
|
/// left out; with none left, the error is [`NO_TRANSCRIPT`].
|
||||||
|
pub fn upload_text(&self) -> Result<String, String> {
|
||||||
|
let lines: Vec<String> = self
|
||||||
|
.segments
|
||||||
|
.iter()
|
||||||
|
.filter(|segment| !segment.text.trim().is_empty())
|
||||||
|
.map(|segment| {
|
||||||
|
format!(
|
||||||
|
"[{}] {}: {}",
|
||||||
|
offset(segment.start),
|
||||||
|
segment.label,
|
||||||
|
segment.text.trim()
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if lines.is_empty() {
|
||||||
|
return Err(NO_TRANSCRIPT.to_string());
|
||||||
|
}
|
||||||
|
let item = &self.call.item;
|
||||||
|
let date = item.started_at.format("%d.%m.%Y %H:%M").to_string();
|
||||||
|
let title = match &item.title {
|
||||||
|
Some(title) => title.clone(),
|
||||||
|
None => format!("{} · {date}", item.app),
|
||||||
|
};
|
||||||
|
let minutes = ((item.duration_secs as f64 / 60.0).round() as i64).max(1);
|
||||||
|
let header = [
|
||||||
|
format!("Titel: {title}"),
|
||||||
|
format!("Datum: {date}"),
|
||||||
|
format!("Kanal: {}", item.app),
|
||||||
|
format!("Dauer: {minutes} min"),
|
||||||
|
String::new(),
|
||||||
|
];
|
||||||
|
Ok(header
|
||||||
|
.into_iter()
|
||||||
|
.chain(lines)
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why [`CallDetail::upload_text`] has nothing to upload.
|
||||||
|
pub const NO_TRANSCRIPT: &str = "Kein Transkript zum Hochladen";
|
||||||
|
|
||||||
|
/// Position in the recording: "04:07", or "1:02:07" from one hour on (like
|
||||||
|
/// the transcript view).
|
||||||
|
fn offset(secs: f64) -> String {
|
||||||
|
let total = if secs.is_finite() && secs > 0.0 {
|
||||||
|
secs as u64
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
|
let (h, m, s) = (total / 3600, total % 3600 / 60, total % 60);
|
||||||
|
if h > 0 {
|
||||||
|
format!("{h}:{m:02}:{s:02}")
|
||||||
|
} else {
|
||||||
|
format!("{m:02}:{s:02}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn merge_views(
|
fn merge_views(
|
||||||
merges: &BTreeMap<String, String>,
|
merges: &BTreeMap<String, String>,
|
||||||
speaker_names: &BTreeMap<String, String>,
|
speaker_names: &BTreeMap<String, String>,
|
||||||
@@ -176,8 +251,9 @@ mod tests {
|
|||||||
out_path: PathBuf::from("7-out.wav"),
|
out_path: PathBuf::from("7-out.wav"),
|
||||||
transcribed_at: None,
|
transcribed_at: None,
|
||||||
audio_deleted: false,
|
audio_deleted: false,
|
||||||
account_id: None,
|
|
||||||
title: None,
|
title: None,
|
||||||
|
crm_transcript_id: None,
|
||||||
|
uploaded_at: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -216,11 +292,18 @@ mod tests {
|
|||||||
status: CallStatus::AwaitingDecision,
|
status: CallStatus::AwaitingDecision,
|
||||||
interrupted: true,
|
interrupted: true,
|
||||||
title: None,
|
title: None,
|
||||||
|
crm_transcript_id: None,
|
||||||
|
uploaded_at: None,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
c.title = Some("Angebot Rioja".into());
|
c.title = Some("Angebot Rioja".into());
|
||||||
assert_eq!(CallListItem::of(&c).title.as_deref(), Some("Angebot Rioja"));
|
c.crm_transcript_id = Some("4711".into());
|
||||||
|
c.uploaded_at = Some(at(11, 0, 0));
|
||||||
|
let item = CallListItem::of(&c);
|
||||||
|
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]
|
#[test]
|
||||||
@@ -330,8 +413,8 @@ mod tests {
|
|||||||
let mut c = call(Some(at(10, 15, 0)));
|
let mut c = call(Some(at(10, 15, 0)));
|
||||||
c.status = CallStatus::Failed;
|
c.status = CallStatus::Failed;
|
||||||
c.error = Some("Netzwerkfehler".into());
|
c.error = Some("Netzwerkfehler".into());
|
||||||
c.account_id = Some("mock-2".into());
|
|
||||||
c.title = Some("Reklamation".into());
|
c.title = Some("Reklamation".into());
|
||||||
|
c.transcribed_at = Some(at(10, 20, 0));
|
||||||
let merges = keys(&[("remote:2", "remote:1")]);
|
let merges = keys(&[("remote:2", "remote:1")]);
|
||||||
|
|
||||||
let value =
|
let value =
|
||||||
@@ -348,8 +431,10 @@ mod tests {
|
|||||||
"status": "failed",
|
"status": "failed",
|
||||||
"interrupted": false,
|
"interrupted": false,
|
||||||
"title": "Reklamation",
|
"title": "Reklamation",
|
||||||
|
"crm_transcript_id": null,
|
||||||
|
"uploaded_at": null,
|
||||||
"error": "Netzwerkfehler",
|
"error": "Netzwerkfehler",
|
||||||
"account_id": "mock-2",
|
"transcribed_at": serde_json::to_value(at(10, 20, 0)).unwrap(),
|
||||||
},
|
},
|
||||||
"segments": [],
|
"segments": [],
|
||||||
"speaker_names": {},
|
"speaker_names": {},
|
||||||
@@ -359,7 +444,71 @@ mod tests {
|
|||||||
"into_key": "remote:1",
|
"into_key": "remote:1",
|
||||||
"into_label": "Sprecher 1",
|
"into_label": "Sprecher 1",
|
||||||
}],
|
}],
|
||||||
|
"uploading": false,
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn detail_with(c: &Call, segments: &[Segment], names: &[(&str, &str)]) -> CallDetail {
|
||||||
|
CallDetail::of(c, segments, keys(names), &keys(&[("remote:2", "remote:1")]))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+32
-14
@@ -1,7 +1,6 @@
|
|||||||
//! The HTTP transport seam: every outgoing request the DeepScript and Claude
|
//! The HTTP transport seam: every outgoing request the API clients make goes
|
||||||
//! clients (Tasks 12/13) make goes through [`HttpTransport`], so unit tests
|
//! through [`HttpTransport`], so unit tests can swap in
|
||||||
//! can swap in [`crate::testing::FakeTransport`] and run with the network
|
//! [`crate::testing::FakeTransport`] and run with the network unplugged. [`ReqwestTransport`] is the real implementation, exercised only
|
||||||
//! unplugged. [`ReqwestTransport`] is the real implementation, exercised only
|
|
||||||
//! by the live integration suite (`crates/core/tests/live_api.rs`).
|
//! by the live integration suite (`crates/core/tests/live_api.rs`).
|
||||||
|
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
@@ -51,6 +50,9 @@ pub struct HttpRequest {
|
|||||||
pub url: String,
|
pub url: String,
|
||||||
pub headers: Vec<(String, String)>,
|
pub headers: Vec<(String, String)>,
|
||||||
pub body: HttpBody,
|
pub body: HttpBody,
|
||||||
|
/// `false` returns a redirect (3xx) as the response instead of
|
||||||
|
/// following it.
|
||||||
|
pub follow_redirects: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HttpRequest {
|
impl HttpRequest {
|
||||||
@@ -99,22 +101,30 @@ pub trait HttpTransport: Send + Sync {
|
|||||||
async fn send(&self, req: HttpRequest) -> Result<HttpResponse, TransportError>;
|
async fn send(&self, req: HttpRequest) -> Result<HttpResponse, TransportError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Live `HttpTransport` backed by `reqwest` (rustls). Shares one
|
/// Live `HttpTransport` backed by `reqwest` (rustls). Shares its
|
||||||
/// `reqwest::Client` (connection pooling) with a 10 minute request timeout
|
/// `reqwest::Client`s (connection pooling) with a 10 minute request timeout
|
||||||
/// and a 30 second connect timeout, matching the Claude/DeepScript clients'
|
/// and a 30 second connect timeout, matching the DeepScript client's
|
||||||
/// worst-case wait.
|
/// worst-case wait. reqwest sets the redirect policy per client, so there
|
||||||
|
/// is one that follows redirects and one that does not.
|
||||||
pub struct ReqwestTransport {
|
pub struct ReqwestTransport {
|
||||||
client: reqwest::Client,
|
client: reqwest::Client,
|
||||||
|
no_redirect_client: reqwest::Client,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ReqwestTransport {
|
impl ReqwestTransport {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
let client = reqwest::Client::builder()
|
let build = |redirects| {
|
||||||
|
reqwest::Client::builder()
|
||||||
.timeout(Duration::from_secs(10 * 60))
|
.timeout(Duration::from_secs(10 * 60))
|
||||||
.connect_timeout(Duration::from_secs(30))
|
.connect_timeout(Duration::from_secs(30))
|
||||||
|
.redirect(redirects)
|
||||||
.build()
|
.build()
|
||||||
.expect("failed to build reqwest client");
|
.expect("failed to build reqwest client")
|
||||||
ReqwestTransport { client }
|
};
|
||||||
|
ReqwestTransport {
|
||||||
|
client: build(reqwest::redirect::Policy::default()),
|
||||||
|
no_redirect_client: build(reqwest::redirect::Policy::none()),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,10 +137,15 @@ impl Default for ReqwestTransport {
|
|||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl HttpTransport for ReqwestTransport {
|
impl HttpTransport for ReqwestTransport {
|
||||||
async fn send(&self, req: HttpRequest) -> Result<HttpResponse, TransportError> {
|
async fn send(&self, req: HttpRequest) -> Result<HttpResponse, TransportError> {
|
||||||
|
let client = if req.follow_redirects {
|
||||||
|
&self.client
|
||||||
|
} else {
|
||||||
|
&self.no_redirect_client
|
||||||
|
};
|
||||||
let mut builder = match req.method {
|
let mut builder = match req.method {
|
||||||
Method::Get => self.client.get(&req.url),
|
Method::Get => client.get(&req.url),
|
||||||
Method::Post => self.client.post(&req.url),
|
Method::Post => client.post(&req.url),
|
||||||
Method::Delete => self.client.delete(&req.url),
|
Method::Delete => client.delete(&req.url),
|
||||||
};
|
};
|
||||||
for (name, value) in &req.headers {
|
for (name, value) in &req.headers {
|
||||||
builder = builder.header(name, value);
|
builder = builder.header(name, value);
|
||||||
@@ -203,6 +218,7 @@ mod tests {
|
|||||||
url: url.to_string(),
|
url: url.to_string(),
|
||||||
headers: vec![],
|
headers: vec![],
|
||||||
body: HttpBody::Empty,
|
body: HttpBody::Empty,
|
||||||
|
follow_redirects: true,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -225,6 +241,7 @@ mod tests {
|
|||||||
url: "https://api.example.com/b?x=1".to_string(),
|
url: "https://api.example.com/b?x=1".to_string(),
|
||||||
headers: vec![("x-test".to_string(), "1".to_string())],
|
headers: vec![("x-test".to_string(), "1".to_string())],
|
||||||
body: HttpBody::Empty,
|
body: HttpBody::Empty,
|
||||||
|
follow_redirects: true,
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -265,6 +282,7 @@ mod tests {
|
|||||||
url: "https://api.example.com".to_string(),
|
url: "https://api.example.com".to_string(),
|
||||||
headers: vec![("Authorization".to_string(), "Bearer xyz".to_string())],
|
headers: vec![("Authorization".to_string(), "Bearer xyz".to_string())],
|
||||||
body: HttpBody::Empty,
|
body: HttpBody::Empty,
|
||||||
|
follow_redirects: true,
|
||||||
};
|
};
|
||||||
assert_eq!(req.header("authorization"), Some("Bearer xyz"));
|
assert_eq!(req.header("authorization"), Some("Bearer xyz"));
|
||||||
assert_eq!(req.header("missing"), None);
|
assert_eq!(req.header("missing"), None);
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
//! Core domain logic for the Gesprächsrekorder call recorder.
|
//! Core domain logic for the Gesprächsrekorder call recorder.
|
||||||
//!
|
//!
|
||||||
//! This crate will grow to hold call detection, recording orchestration,
|
//! Call detection, recording orchestration and transcription, kept
|
||||||
//! transcription and summarization logic, kept independent of the Tauri
|
//! independent of the Tauri application shell so it can be unit-tested
|
||||||
//! application shell so it can be unit-tested without a GUI or network.
|
//! without a GUI or network.
|
||||||
|
|
||||||
pub mod accounts;
|
|
||||||
pub mod audio;
|
pub mod audio;
|
||||||
|
pub mod backend;
|
||||||
pub mod call_view;
|
pub mod call_view;
|
||||||
pub mod capture;
|
pub mod capture;
|
||||||
pub mod detect;
|
pub mod detect;
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use chrono::{DateTime, Local, NaiveDate};
|
use chrono::{DateTime, Local};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
/// Primary key of a `calls` row (SQLite `rowid`).
|
/// Primary key of a `calls` row (SQLite `rowid`).
|
||||||
@@ -37,9 +37,12 @@ pub struct Call {
|
|||||||
pub out_path: PathBuf,
|
pub out_path: PathBuf,
|
||||||
pub transcribed_at: Option<DateTime<Local>>,
|
pub transcribed_at: Option<DateTime<Local>>,
|
||||||
pub audio_deleted: bool,
|
pub audio_deleted: bool,
|
||||||
pub account_id: Option<String>,
|
|
||||||
/// The name the user gave the call, if any.
|
/// The name the user gave the call, if any.
|
||||||
pub title: Option<String>,
|
pub title: Option<String>,
|
||||||
|
/// The id the CRM gave the transcript at its last upload.
|
||||||
|
pub crm_transcript_id: Option<String>,
|
||||||
|
/// When the transcript was last uploaded.
|
||||||
|
pub uploaded_at: Option<DateTime<Local>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A single transcribed word with its timing and speaker attribution.
|
/// A single transcribed word with its timing and speaker attribution.
|
||||||
@@ -97,38 +100,3 @@ pub struct Segment {
|
|||||||
pub end: f64,
|
pub end: f64,
|
||||||
pub text: String,
|
pub text: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Who owns a to-do coming out of the call summary.
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
#[serde(rename_all = "lowercase")]
|
|
||||||
pub enum Owner {
|
|
||||||
Ich,
|
|
||||||
Kunde,
|
|
||||||
Sonstige,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A single action item extracted from the call summary.
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
|
||||||
pub struct Todo {
|
|
||||||
pub text: String,
|
|
||||||
pub owner: Owner,
|
|
||||||
pub faellig: Option<NaiveDate>,
|
|
||||||
#[serde(default)]
|
|
||||||
pub erledigt: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The next agreed point of contact, if any.
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
|
|
||||||
pub struct NaechsterKontakt {
|
|
||||||
pub datum: Option<NaiveDate>,
|
|
||||||
pub notiz: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Structured summary produced by Claude for a finished call.
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
|
||||||
pub struct Summary {
|
|
||||||
pub kernpunkte: Vec<String>,
|
|
||||||
pub vereinbarungen: Vec<String>,
|
|
||||||
pub todos: Vec<Todo>,
|
|
||||||
pub naechster_kontakt: NaechsterKontakt,
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -108,7 +108,6 @@ async fn run(
|
|||||||
// Jobs whose delete failed in an earlier run.
|
// Jobs whose delete failed in an earlier run.
|
||||||
delete_remote_jobs(store, tr, id).await;
|
delete_remote_jobs(store, tr, id).await;
|
||||||
}
|
}
|
||||||
// SUMMARY SEAM (Task 14b): summarize here.
|
|
||||||
store.set_status(id, CallStatus::Done, None)?;
|
store.set_status(id, CallStatus::Done, None)?;
|
||||||
log::info!("call {id}: done");
|
log::info!("call {id}: done");
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ use crate::model::{Call, CallId, CallStatus};
|
|||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum RetentionAction {
|
pub enum RetentionAction {
|
||||||
/// Delete the call's audio file(s) on disk; the row stays (it has a
|
/// Delete the call's audio file(s) on disk; the row stays (it has a
|
||||||
/// summary/transcript worth keeping).
|
/// transcript worth keeping).
|
||||||
DeleteAudio(CallId),
|
DeleteAudio(CallId),
|
||||||
/// Delete the whole call row (and everything derived from it).
|
/// Delete the whole call row (and everything derived from it).
|
||||||
DeleteCall(CallId),
|
DeleteCall(CallId),
|
||||||
@@ -88,8 +88,9 @@ mod tests {
|
|||||||
out_path: PathBuf::from("/tmp/out.wav"),
|
out_path: PathBuf::from("/tmp/out.wav"),
|
||||||
transcribed_at: None,
|
transcribed_at: None,
|
||||||
audio_deleted: false,
|
audio_deleted: false,
|
||||||
account_id: None,
|
|
||||||
title: None,
|
title: None,
|
||||||
|
crm_transcript_id: None,
|
||||||
|
uploaded_at: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
//! API keys, stored only in the OS keyring (Windows Credential Manager,
|
//! API keys, stored only in the OS keyring (Windows Credential Manager,
|
||||||
//! Linux Secret Service) under the service `eu.euvino.callrecorder`.
|
//! Linux Secret Service) under the service `eu.euvino.callrecorder`: the
|
||||||
|
//! DeepScript key the user enters and the euvino admin backend key the
|
||||||
|
//! login creates.
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
@@ -15,7 +17,7 @@ pub const KEYRING_SERVICE: &str = "eu.euvino.callrecorder";
|
|||||||
#[serde(rename_all = "lowercase")]
|
#[serde(rename_all = "lowercase")]
|
||||||
pub enum Service {
|
pub enum Service {
|
||||||
DeepScript,
|
DeepScript,
|
||||||
Anthropic,
|
Backend,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Service {
|
impl Service {
|
||||||
@@ -23,7 +25,7 @@ impl Service {
|
|||||||
pub fn user(self) -> &'static str {
|
pub fn user(self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
Service::DeepScript => "deepscript",
|
Service::DeepScript => "deepscript",
|
||||||
Service::Anthropic => "anthropic",
|
Service::Backend => "backend",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -45,6 +47,10 @@ pub trait SecretStore: Send + Sync {
|
|||||||
fn delete(&self, s: Service) -> Result<()>;
|
fn delete(&self, s: Service) -> Result<()>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Keyring users of keys that earlier versions stored and this one no
|
||||||
|
/// longer uses: the Anthropic key of the dropped Claude summary.
|
||||||
|
const UNUSED_USERS: [&str; 1] = ["anthropic"];
|
||||||
|
|
||||||
/// The OS keyring.
|
/// The OS keyring.
|
||||||
pub struct KeyringSecrets;
|
pub struct KeyringSecrets;
|
||||||
|
|
||||||
@@ -53,6 +59,21 @@ impl KeyringSecrets {
|
|||||||
keyring::Entry::new(KEYRING_SERVICE, s.user())
|
keyring::Entry::new(KEYRING_SERVICE, s.user())
|
||||||
.map_err(|e| SecretError::Keyring(e.to_string()))
|
.map_err(|e| SecretError::Keyring(e.to_string()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Best-effort deletes the keys earlier versions stored and this one no
|
||||||
|
/// longer uses, so no stale secret lingers in the keyring. Missing
|
||||||
|
/// entries and failures are only logged (never the key).
|
||||||
|
pub fn remove_unused_keys() {
|
||||||
|
for user in UNUSED_USERS {
|
||||||
|
let result =
|
||||||
|
keyring::Entry::new(KEYRING_SERVICE, user).and_then(|e| e.delete_credential());
|
||||||
|
match result {
|
||||||
|
Ok(()) => log::info!("removed the unused keyring entry {user:?}"),
|
||||||
|
Err(keyring::Error::NoEntry) => {}
|
||||||
|
Err(e) => log::info!("could not remove the unused keyring entry {user:?}: {e}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SecretStore for KeyringSecrets {
|
impl SecretStore for KeyringSecrets {
|
||||||
@@ -100,6 +121,8 @@ impl SecretStore for MemorySecrets {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
const SERVICES: &[Service] = &[Service::DeepScript, Service::Backend];
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn memory_secrets_roundtrip() {
|
fn memory_secrets_roundtrip() {
|
||||||
let secrets = MemorySecrets::default();
|
let secrets = MemorySecrets::default();
|
||||||
@@ -107,16 +130,23 @@ mod tests {
|
|||||||
|
|
||||||
secrets.set(Service::DeepScript, "ds-key").unwrap();
|
secrets.set(Service::DeepScript, "ds-key").unwrap();
|
||||||
assert_eq!(secrets.get(Service::DeepScript).as_deref(), Some("ds-key"));
|
assert_eq!(secrets.get(Service::DeepScript).as_deref(), Some("ds-key"));
|
||||||
assert_eq!(secrets.get(Service::Anthropic), None);
|
assert_eq!(secrets.get(Service::Backend), None);
|
||||||
|
|
||||||
secrets.delete(Service::DeepScript).unwrap();
|
secrets.delete(Service::DeepScript).unwrap();
|
||||||
assert_eq!(secrets.get(Service::DeepScript), None);
|
assert_eq!(secrets.get(Service::DeepScript), None);
|
||||||
secrets.delete(Service::DeepScript).unwrap();
|
secrets.delete(Service::DeepScript).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unused_keys_never_include_a_key_in_use() {
|
||||||
|
for &s in SERVICES {
|
||||||
|
assert!(!UNUSED_USERS.contains(&s.user()), "{s:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn service_serializes_as_keyring_user() {
|
fn service_serializes_as_keyring_user() {
|
||||||
for s in [Service::DeepScript, Service::Anthropic] {
|
for &s in SERVICES {
|
||||||
let json = serde_json::to_string(&s).unwrap();
|
let json = serde_json::to_string(&s).unwrap();
|
||||||
assert_eq!(json, format!("\"{}\"", s.user()));
|
assert_eq!(json, format!("\"{}\"", s.user()));
|
||||||
assert_eq!(serde_json::from_str::<Service>(&json).unwrap(), s);
|
assert_eq!(serde_json::from_str::<Service>(&json).unwrap(), s);
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ use std::io;
|
|||||||
use std::ops::RangeInclusive;
|
use std::ops::RangeInclusive;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
|
use chrono::{DateTime, Local};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
/// Executables whose mic use counts as a call (matched case-insensitively).
|
/// Executables whose mic use counts as a call (matched case-insensitively).
|
||||||
@@ -38,6 +39,14 @@ pub struct Settings {
|
|||||||
pub autostart: bool,
|
pub autostart: bool,
|
||||||
pub start_after_secs: u64,
|
pub start_after_secs: u64,
|
||||||
pub end_after_secs: u64,
|
pub end_after_secs: u64,
|
||||||
|
/// Whose backend key is stored (the key itself is in the keyring). Set
|
||||||
|
/// by the app at login, not by the user.
|
||||||
|
pub backend_username: Option<String>,
|
||||||
|
/// When the stored backend key expires. Set by the app at login.
|
||||||
|
pub backend_key_expires_at: Option<DateTime<Local>>,
|
||||||
|
/// The backend the stored key was created for: it is sent to that one
|
||||||
|
/// only. Set by the app at login.
|
||||||
|
pub backend_key_base_url: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for Settings {
|
impl Default for Settings {
|
||||||
@@ -52,6 +61,9 @@ impl Default for Settings {
|
|||||||
autostart: true,
|
autostart: true,
|
||||||
start_after_secs: 3,
|
start_after_secs: 3,
|
||||||
end_after_secs: 10,
|
end_after_secs: 10,
|
||||||
|
backend_username: None,
|
||||||
|
backend_key_expires_at: None,
|
||||||
|
backend_key_base_url: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -76,6 +88,17 @@ impl Settings {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The settings after the user saved `edited` over these: checked, with
|
||||||
|
/// the backend login (which only the app changes) kept, so a settings
|
||||||
|
/// page loaded before a login cannot undo it.
|
||||||
|
pub fn edited(&self, mut edited: Settings) -> Result<Settings, String> {
|
||||||
|
edited.validate()?;
|
||||||
|
edited.backend_username = self.backend_username.clone();
|
||||||
|
edited.backend_key_expires_at = self.backend_key_expires_at;
|
||||||
|
edited.backend_key_base_url = self.backend_key_base_url.clone();
|
||||||
|
Ok(edited)
|
||||||
|
}
|
||||||
|
|
||||||
/// Reads the settings file. A missing or unreadable file yields the
|
/// Reads the settings file. A missing or unreadable file yields the
|
||||||
/// defaults; fields missing from the file take their default value.
|
/// defaults; fields missing from the file take their default value.
|
||||||
pub fn load(path: &Path) -> Settings {
|
pub fn load(path: &Path) -> Settings {
|
||||||
@@ -124,6 +147,71 @@ mod tests {
|
|||||||
assert!(s.autostart);
|
assert!(s.autostart);
|
||||||
assert_eq!(s.start_after_secs, 3);
|
assert_eq!(s.start_after_secs, 3);
|
||||||
assert_eq!(s.end_after_secs, 10);
|
assert_eq!(s.end_after_secs, 10);
|
||||||
|
assert_eq!(s.backend_username, None);
|
||||||
|
assert_eq!(s.backend_key_expires_at, None);
|
||||||
|
assert_eq!(s.backend_key_base_url, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_backend_url_in_an_older_file_is_ignored() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let path = dir.path().join("settings.json");
|
||||||
|
fs::write(
|
||||||
|
&path,
|
||||||
|
r#"{"retention_days": 9, "backend_url": "https://other.example"}"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
Settings::load(&path),
|
||||||
|
Settings {
|
||||||
|
retention_days: 9,
|
||||||
|
..Settings::default()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn logged_in() -> Settings {
|
||||||
|
Settings {
|
||||||
|
backend_username: Some("hinrichs".into()),
|
||||||
|
backend_key_expires_at: Some(
|
||||||
|
chrono::DateTime::parse_from_rfc3339("2027-11-06T10:00:00+01:00")
|
||||||
|
.unwrap()
|
||||||
|
.into(),
|
||||||
|
),
|
||||||
|
backend_key_base_url: Some("https://test.euvinopro.eu".into()),
|
||||||
|
..Settings::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_edit_keeps_the_backend_login_which_only_the_app_changes() {
|
||||||
|
let current = logged_in();
|
||||||
|
let edited = Settings {
|
||||||
|
retention_days: 30,
|
||||||
|
backend_username: None,
|
||||||
|
backend_key_expires_at: None,
|
||||||
|
backend_key_base_url: Some("https://elsewhere.example".into()),
|
||||||
|
..Settings::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
let saved = current.edited(edited).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
saved,
|
||||||
|
Settings {
|
||||||
|
retention_days: 30,
|
||||||
|
..logged_in()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_invalid_edit_is_refused() {
|
||||||
|
let edited = Settings {
|
||||||
|
start_after_secs: 0,
|
||||||
|
..Settings::default()
|
||||||
|
};
|
||||||
|
assert!(logged_in().edited(edited).is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
+139
-108
@@ -1,5 +1,5 @@
|
|||||||
//! SQLite-backed persistence for calls, their transcripts, summaries,
|
//! SQLite-backed persistence for calls, their transcripts, speaker renames
|
||||||
//! speaker renames and outstanding remote transcription/summary jobs.
|
//! and merges, and outstanding remote transcription jobs.
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
@@ -10,7 +10,7 @@ use rusqlite::{params, Connection, Row, TransactionBehavior};
|
|||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
use crate::merge::{self, MergeError};
|
use crate::merge::{self, MergeError};
|
||||||
use crate::model::{Call, CallId, CallStatus, Segment, Speaker, Summary};
|
use crate::model::{Call, CallId, CallStatus, Segment, Speaker};
|
||||||
|
|
||||||
/// Longest call title, in characters.
|
/// Longest call title, in characters.
|
||||||
const MAX_TITLE_CHARS: usize = 120;
|
const MAX_TITLE_CHARS: usize = 120;
|
||||||
@@ -22,8 +22,8 @@ pub enum StoreError {
|
|||||||
Sqlite(#[from] rusqlite::Error),
|
Sqlite(#[from] rusqlite::Error),
|
||||||
|
|
||||||
/// A value read back from SQLite could not be interpreted, e.g. an
|
/// A value read back from SQLite could not be interpreted, e.g. an
|
||||||
/// unknown `status` string, invalid RFC 3339 timestamp, unparsable
|
/// unknown `status` string, invalid RFC 3339 timestamp or unparsable
|
||||||
/// speaker key or malformed summary JSON.
|
/// speaker key.
|
||||||
#[error("corrupt stored value: {0}")]
|
#[error("corrupt stored value: {0}")]
|
||||||
Corrupt(String),
|
Corrupt(String),
|
||||||
|
|
||||||
@@ -51,7 +51,9 @@ pub struct RecoveryReport {
|
|||||||
pub failed: Vec<CallId>,
|
pub failed: Vec<CallId>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Version 1: the first release.
|
/// Version 1: the first release. `calls.account_id` (the customer mock) and
|
||||||
|
/// `summaries` are no longer used; they stay so no migration has to drop
|
||||||
|
/// them.
|
||||||
const SCHEMA_V1_SQL: &str = "
|
const SCHEMA_V1_SQL: &str = "
|
||||||
CREATE TABLE IF NOT EXISTS calls (
|
CREATE TABLE IF NOT EXISTS calls (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
@@ -112,9 +114,15 @@ 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;
|
||||||
|
";
|
||||||
|
|
||||||
/// Schema steps by `PRAGMA user_version`: entry `i` takes a database from
|
/// Schema steps by `PRAGMA user_version`: entry `i` takes a database from
|
||||||
/// version `i` to `i + 1`. A new database runs all of them.
|
/// version `i` to `i + 1`. A new database runs all of them.
|
||||||
const MIGRATIONS: &[&str] = &[SCHEMA_V1_SQL, SCHEMA_V2_SQL];
|
const MIGRATIONS: &[&str] = &[SCHEMA_V1_SQL, SCHEMA_V2_SQL, SCHEMA_V3_SQL];
|
||||||
|
|
||||||
/// SQLite-backed store for calls and everything derived from them.
|
/// SQLite-backed store for calls and everything derived from them.
|
||||||
pub struct Store {
|
pub struct Store {
|
||||||
@@ -152,8 +160,8 @@ impl Store {
|
|||||||
let conn = self.conn.lock().unwrap();
|
let conn = self.conn.lock().unwrap();
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"INSERT INTO calls \
|
"INSERT INTO calls \
|
||||||
(app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, account_id) \
|
(app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted) \
|
||||||
VALUES (?1, ?2, NULL, ?3, 0, NULL, ?4, ?5, NULL, 0, NULL)",
|
VALUES (?1, ?2, NULL, ?3, 0, NULL, ?4, ?5, NULL, 0)",
|
||||||
params![
|
params![
|
||||||
app,
|
app,
|
||||||
dt_to_str(started_at),
|
dt_to_str(started_at),
|
||||||
@@ -271,33 +279,6 @@ impl Store {
|
|||||||
Ok(segments)
|
Ok(segments)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn save_summary(&self, id: CallId, summary: &Summary, edited: bool) -> Result<()> {
|
|
||||||
let conn = self.conn.lock().unwrap();
|
|
||||||
let json = serde_json::to_string(summary)
|
|
||||||
.map_err(|e| StoreError::Corrupt(format!("failed to serialize summary: {e}")))?;
|
|
||||||
conn.execute(
|
|
||||||
"INSERT INTO summaries (call_id, json, edited) VALUES (?1, ?2, ?3) \
|
|
||||||
ON CONFLICT(call_id) DO UPDATE SET json = excluded.json, edited = excluded.edited",
|
|
||||||
params![id, json, edited],
|
|
||||||
)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn summary(&self, id: CallId) -> Result<Option<Summary>> {
|
|
||||||
let conn = self.conn.lock().unwrap();
|
|
||||||
let mut stmt = conn.prepare("SELECT json FROM summaries WHERE call_id = ?1")?;
|
|
||||||
let mut rows = stmt.query(params![id])?;
|
|
||||||
match rows.next()? {
|
|
||||||
Some(row) => {
|
|
||||||
let json: String = row.get(0)?;
|
|
||||||
let summary = serde_json::from_str(&json)
|
|
||||||
.map_err(|e| StoreError::Corrupt(format!("invalid summary json: {e}")))?;
|
|
||||||
Ok(Some(summary))
|
|
||||||
}
|
|
||||||
None => Ok(None),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_speaker_name(&self, id: CallId, speaker_key: &str, name: &str) -> Result<()> {
|
pub fn set_speaker_name(&self, id: CallId, speaker_key: &str, name: &str) -> Result<()> {
|
||||||
let conn = self.conn.lock().unwrap();
|
let conn = self.conn.lock().unwrap();
|
||||||
conn.execute(
|
conn.execute(
|
||||||
@@ -380,6 +361,22 @@ impl Store {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Records that the transcript was uploaded to the CRM at `at`, which
|
||||||
|
/// gave it `crm_transcript_id`; replaces an earlier upload's record.
|
||||||
|
pub fn set_uploaded(
|
||||||
|
&self,
|
||||||
|
id: CallId,
|
||||||
|
crm_transcript_id: &str,
|
||||||
|
at: DateTime<Local>,
|
||||||
|
) -> Result<()> {
|
||||||
|
let conn = self.conn.lock().unwrap();
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE calls SET crm_transcript_id = ?1, uploaded_at = ?2 WHERE id = ?3",
|
||||||
|
params![crm_transcript_id, dt_to_str(at), id],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn mark_transcribed(&self, id: CallId, at: DateTime<Local>) -> Result<()> {
|
pub fn mark_transcribed(&self, id: CallId, at: DateTime<Local>) -> Result<()> {
|
||||||
let conn = self.conn.lock().unwrap();
|
let conn = self.conn.lock().unwrap();
|
||||||
conn.execute(
|
conn.execute(
|
||||||
@@ -398,8 +395,9 @@ impl Store {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Deletes a call and every row derived from it (segments, summary,
|
/// Deletes a call and every row derived from it (segments, speaker
|
||||||
/// speaker names and merges, remote jobs).
|
/// names and merges, remote jobs; also the `summaries` table of schema
|
||||||
|
/// v1, which nothing writes).
|
||||||
pub fn delete_call(&self, id: CallId) -> Result<()> {
|
pub fn delete_call(&self, id: CallId) -> Result<()> {
|
||||||
let mut conn = self.conn.lock().unwrap();
|
let mut conn = self.conn.lock().unwrap();
|
||||||
let tx = conn.transaction()?;
|
let tx = conn.transaction()?;
|
||||||
@@ -413,15 +411,6 @@ impl Store {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_account(&self, id: CallId, account_id: Option<&str>) -> Result<()> {
|
|
||||||
let conn = self.conn.lock().unwrap();
|
|
||||||
conn.execute(
|
|
||||||
"UPDATE calls SET account_id = ?1 WHERE id = ?2",
|
|
||||||
params![account_id, id],
|
|
||||||
)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn record_remote_job(&self, id: CallId, track: &str, remote_id: &str) -> Result<()> {
|
pub fn record_remote_job(&self, id: CallId, track: &str, remote_id: &str) -> Result<()> {
|
||||||
let conn = self.conn.lock().unwrap();
|
let conn = self.conn.lock().unwrap();
|
||||||
conn.execute(
|
conn.execute(
|
||||||
@@ -470,7 +459,7 @@ impl Store {
|
|||||||
/// `AwaitingDecision`, with `interrupted` set and `ended_at` set to now
|
/// `AwaitingDecision`, with `interrupted` set and `ended_at` set to now
|
||||||
/// if it was not already set (a later pass corrects it from the WAV
|
/// if it was not already set (a later pass corrects it from the WAV
|
||||||
/// length).
|
/// length).
|
||||||
/// - `Processing` calls were mid-transcription/summarization: they move
|
/// - `Processing` calls were mid-transcription: they move
|
||||||
/// to `Failed` with a fixed error message.
|
/// to `Failed` with a fixed error message.
|
||||||
///
|
///
|
||||||
/// Both updates run in a single transaction.
|
/// Both updates run in a single transaction.
|
||||||
@@ -547,9 +536,9 @@ fn ids_with_status(conn: &rusqlite::Connection, status: CallStatus) -> Result<Ve
|
|||||||
Ok(ids)
|
Ok(ids)
|
||||||
}
|
}
|
||||||
|
|
||||||
const SELECT_ALL_CALLS_SQL: &str = "SELECT id, app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, account_id, title FROM calls";
|
const SELECT_ALL_CALLS_SQL: &str = "SELECT id, app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, title, crm_transcript_id, uploaded_at 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 FROM calls WHERE id = ?1";
|
||||||
|
|
||||||
fn row_to_call(row: &Row) -> Result<Call> {
|
fn row_to_call(row: &Row) -> Result<Call> {
|
||||||
let id: CallId = row.get(0)?;
|
let id: CallId = row.get(0)?;
|
||||||
@@ -563,8 +552,9 @@ fn row_to_call(row: &Row) -> Result<Call> {
|
|||||||
let out_path: String = row.get(8)?;
|
let out_path: String = row.get(8)?;
|
||||||
let transcribed_at: Option<String> = row.get(9)?;
|
let transcribed_at: Option<String> = row.get(9)?;
|
||||||
let audio_deleted: bool = row.get(10)?;
|
let audio_deleted: bool = row.get(10)?;
|
||||||
let account_id: Option<String> = row.get(11)?;
|
let title: Option<String> = row.get(11)?;
|
||||||
let title: Option<String> = row.get(12)?;
|
let crm_transcript_id: Option<String> = row.get(12)?;
|
||||||
|
let uploaded_at: Option<String> = row.get(13)?;
|
||||||
|
|
||||||
Ok(Call {
|
Ok(Call {
|
||||||
id,
|
id,
|
||||||
@@ -578,8 +568,9 @@ fn row_to_call(row: &Row) -> Result<Call> {
|
|||||||
out_path: PathBuf::from(out_path),
|
out_path: PathBuf::from(out_path),
|
||||||
transcribed_at: opt_dt_from_str(transcribed_at)?,
|
transcribed_at: opt_dt_from_str(transcribed_at)?,
|
||||||
audio_deleted,
|
audio_deleted,
|
||||||
account_id,
|
|
||||||
title,
|
title,
|
||||||
|
crm_transcript_id,
|
||||||
|
uploaded_at: opt_dt_from_str(uploaded_at)?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -637,9 +628,7 @@ mod tests {
|
|||||||
|
|
||||||
use chrono::Local;
|
use chrono::Local;
|
||||||
|
|
||||||
use crate::model::{
|
use crate::model::{CallId, CallStatus, Segment, Speaker};
|
||||||
CallId, CallStatus, NaechsterKontakt, Owner, Segment, Speaker, Summary, Todo,
|
|
||||||
};
|
|
||||||
use crate::store::Store;
|
use crate::store::Store;
|
||||||
|
|
||||||
/// The schema of user_version 1, exactly as the first release created
|
/// The schema of user_version 1, exactly as the first release created
|
||||||
@@ -690,6 +679,19 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
|
|||||||
remote_id TEXT NOT NULL,
|
remote_id TEXT NOT NULL,
|
||||||
PRIMARY KEY (call_id, track, remote_id)
|
PRIMARY KEY (call_id, track, remote_id)
|
||||||
);
|
);
|
||||||
|
";
|
||||||
|
|
||||||
|
/// The schema of user_version 2, exactly as release 0.1.1 created it:
|
||||||
|
/// version 1 plus these statements.
|
||||||
|
const RELEASED_V2_STEP_SQL: &str = "
|
||||||
|
ALTER TABLE calls ADD COLUMN title TEXT;
|
||||||
|
|
||||||
|
CREATE TABLE speaker_merges (
|
||||||
|
call_id INTEGER NOT NULL REFERENCES calls(id) ON DELETE CASCADE,
|
||||||
|
from_key TEXT NOT NULL,
|
||||||
|
into_key TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (call_id, from_key)
|
||||||
|
);
|
||||||
";
|
";
|
||||||
|
|
||||||
fn user_version(path: &Path) -> i64 {
|
fn user_version(path: &Path) -> i64 {
|
||||||
@@ -713,16 +715,17 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_new_database_starts_at_version_2() {
|
fn a_new_database_starts_at_version_3() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
let path = dir.path().join("calls.sqlite");
|
let path = dir.path().join("calls.sqlite");
|
||||||
let store = Store::open(&path).unwrap();
|
let store = Store::open(&path).unwrap();
|
||||||
let id = new_call(&store);
|
let id = new_call(&store);
|
||||||
store.set_title(id, Some("Angebot")).unwrap();
|
store.set_title(id, Some("Angebot")).unwrap();
|
||||||
store.set_speaker_merge(id, "remote:2", "remote:1").unwrap();
|
store.set_speaker_merge(id, "remote:2", "remote:1").unwrap();
|
||||||
|
store.set_uploaded(id, "4711", Local::now()).unwrap();
|
||||||
drop(store);
|
drop(store);
|
||||||
|
|
||||||
assert_eq!(user_version(&path), 2);
|
assert_eq!(user_version(&path), 3);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -754,7 +757,6 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
|
|||||||
let call = store.get_call(1).unwrap().expect("call kept");
|
let call = store.get_call(1).unwrap().expect("call kept");
|
||||||
assert_eq!(call.app, "Microsoft Teams");
|
assert_eq!(call.app, "Microsoft Teams");
|
||||||
assert_eq!(call.status, CallStatus::Done);
|
assert_eq!(call.status, CallStatus::Done);
|
||||||
assert_eq!(call.account_id.as_deref(), Some("mock-2"));
|
|
||||||
assert_eq!(call.mic_path, PathBuf::from("/rec/1-mic.wav"));
|
assert_eq!(call.mic_path, PathBuf::from("/rec/1-mic.wav"));
|
||||||
assert_eq!(call.title, None);
|
assert_eq!(call.title, None);
|
||||||
let texts: Vec<_> = store
|
let texts: Vec<_> = store
|
||||||
@@ -780,7 +782,7 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
|
|||||||
store.set_title(1, Some("Lieferung März")).unwrap();
|
store.set_title(1, Some("Lieferung März")).unwrap();
|
||||||
store.set_speaker_merge(1, "remote:2", "remote:1").unwrap();
|
store.set_speaker_merge(1, "remote:2", "remote:1").unwrap();
|
||||||
drop(store);
|
drop(store);
|
||||||
assert_eq!(user_version(&path), 2);
|
assert_eq!(user_version(&path), 3);
|
||||||
let store = Store::open(&path).unwrap();
|
let store = Store::open(&path).unwrap();
|
||||||
let call = store.get_call(1).unwrap().unwrap();
|
let call = store.get_call(1).unwrap().unwrap();
|
||||||
assert_eq!(call.title.as_deref(), Some("Lieferung März"));
|
assert_eq!(call.title.as_deref(), Some("Lieferung März"));
|
||||||
@@ -791,6 +793,83 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
|
|||||||
assert_eq!(store.list_calls().unwrap().len(), 1);
|
assert_eq!(store.list_calls().unwrap().len(), 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_version_2_database_is_upgraded_keeping_its_data() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let path = dir.path().join("calls.sqlite");
|
||||||
|
let started = "2026-11-05T10:14:00+01:00";
|
||||||
|
{
|
||||||
|
let conn = rusqlite::Connection::open(&path).unwrap();
|
||||||
|
conn.execute_batch(RELEASED_V1_SCHEMA_SQL).unwrap();
|
||||||
|
conn.execute_batch(RELEASED_V2_STEP_SQL).unwrap();
|
||||||
|
conn.execute_batch("PRAGMA user_version = 2;").unwrap();
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO calls (app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, account_id, title) \
|
||||||
|
VALUES ('Microsoft Teams', ?1, ?1, 'done', 0, NULL, '/rec/1-mic.wav', '/rec/1-out.wav', ?1, 1, NULL, 'Angebot')",
|
||||||
|
rusqlite::params![started],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
conn.execute_batch(
|
||||||
|
"INSERT INTO segments (call_id, seq, speaker, start_ts, end_ts, text) VALUES \
|
||||||
|
(1, 0, 'remote:2', 0.0, 1.5, 'Hallo.'); \
|
||||||
|
INSERT INTO speaker_merges (call_id, from_key, into_key) VALUES (1, 'remote:2', 'remote:1');",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
let store = Store::open(&path).unwrap();
|
||||||
|
|
||||||
|
let call = store.get_call(1).unwrap().expect("call kept");
|
||||||
|
assert_eq!(call.title.as_deref(), Some("Angebot"));
|
||||||
|
assert!(call.audio_deleted);
|
||||||
|
assert_eq!(call.crm_transcript_id, None);
|
||||||
|
assert_eq!(call.uploaded_at, None);
|
||||||
|
assert_eq!(store.segments(1).unwrap().len(), 1);
|
||||||
|
assert_eq!(
|
||||||
|
store.speaker_merges(1).unwrap(),
|
||||||
|
merge_map(&[("remote:2", "remote:1")])
|
||||||
|
);
|
||||||
|
|
||||||
|
// The new columns work, and opening again changes nothing.
|
||||||
|
let uploaded = Local::now();
|
||||||
|
store.set_uploaded(1, "crm-1", uploaded).unwrap();
|
||||||
|
drop(store);
|
||||||
|
assert_eq!(user_version(&path), 3);
|
||||||
|
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.uploaded_at, Some(uploaded));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_upload_is_recorded_and_replaced_by_the_next() {
|
||||||
|
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", first).unwrap();
|
||||||
|
let call = store.get_call(id).unwrap().unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
(call.crm_transcript_id.as_deref(), call.uploaded_at),
|
||||||
|
(Some("4711"), Some(first))
|
||||||
|
);
|
||||||
|
|
||||||
|
store.set_uploaded(id, "4712", 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.uploaded_at),
|
||||||
|
(Some("4712"), Some(second))
|
||||||
|
);
|
||||||
|
let untouched = store.get_call(other).unwrap().unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
(untouched.crm_transcript_id, untouched.uploaded_at),
|
||||||
|
(None, None)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn speaker_merges_are_set_replaced_and_removed() {
|
fn speaker_merges_are_set_replaced_and_removed() {
|
||||||
let store = Store::open_in_memory().unwrap();
|
let store = Store::open_in_memory().unwrap();
|
||||||
@@ -939,38 +1018,6 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
|
|||||||
assert_eq!(store.segments(id).unwrap(), second);
|
assert_eq!(store.segments(id).unwrap(), second);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn summary_roundtrip_with_null_dates() {
|
|
||||||
let store = Store::open_in_memory().unwrap();
|
|
||||||
let id = store
|
|
||||||
.create_call(
|
|
||||||
"teams.exe",
|
|
||||||
Local::now(),
|
|
||||||
Path::new("/tmp/mic.wav"),
|
|
||||||
Path::new("/tmp/out.wav"),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
assert_eq!(store.summary(id).unwrap(), None);
|
|
||||||
|
|
||||||
let summary = Summary {
|
|
||||||
kernpunkte: vec!["Punkt 1".to_string()],
|
|
||||||
vereinbarungen: vec!["Angebot folgt".to_string()],
|
|
||||||
todos: vec![Todo {
|
|
||||||
text: "Angebot schicken".to_string(),
|
|
||||||
owner: Owner::Ich,
|
|
||||||
faellig: None,
|
|
||||||
erledigt: false,
|
|
||||||
}],
|
|
||||||
naechster_kontakt: NaechsterKontakt {
|
|
||||||
datum: None,
|
|
||||||
notiz: None,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
store.save_summary(id, &summary, false).unwrap();
|
|
||||||
assert_eq!(store.summary(id).unwrap(), Some(summary));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn speaker_names_upsert() {
|
fn speaker_names_upsert() {
|
||||||
let store = Store::open_in_memory().unwrap();
|
let store = Store::open_in_memory().unwrap();
|
||||||
@@ -1167,21 +1214,6 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
|
|||||||
}],
|
}],
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
store
|
|
||||||
.save_summary(
|
|
||||||
id,
|
|
||||||
&Summary {
|
|
||||||
kernpunkte: vec![],
|
|
||||||
vereinbarungen: vec![],
|
|
||||||
todos: vec![],
|
|
||||||
naechster_kontakt: NaechsterKontakt {
|
|
||||||
datum: None,
|
|
||||||
notiz: None,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
false,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
store.set_speaker_name(id, "me", "Ich").unwrap();
|
store.set_speaker_name(id, "me", "Ich").unwrap();
|
||||||
store.set_speaker_merge(id, "remote:2", "remote:1").unwrap();
|
store.set_speaker_merge(id, "remote:2", "remote:1").unwrap();
|
||||||
store
|
store
|
||||||
@@ -1192,7 +1224,6 @@ CREATE TABLE IF NOT EXISTS remote_jobs (
|
|||||||
|
|
||||||
assert_eq!(store.get_call(id).unwrap(), None);
|
assert_eq!(store.get_call(id).unwrap(), None);
|
||||||
assert_eq!(store.segments(id).unwrap(), Vec::new());
|
assert_eq!(store.segments(id).unwrap(), Vec::new());
|
||||||
assert_eq!(store.summary(id).unwrap(), None);
|
|
||||||
assert_eq!(store.speaker_names(id).unwrap(), BTreeMap::new());
|
assert_eq!(store.speaker_names(id).unwrap(), BTreeMap::new());
|
||||||
assert_eq!(store.remote_jobs(id).unwrap(), Vec::new());
|
assert_eq!(store.remote_jobs(id).unwrap(), Vec::new());
|
||||||
assert_eq!(store.speaker_merges(id).unwrap(), BTreeMap::new());
|
assert_eq!(store.speaker_merges(id).unwrap(), BTreeMap::new());
|
||||||
|
|||||||
@@ -10,8 +10,7 @@ use crate::http::{HttpRequest, HttpResponse, HttpTransport, Method, TransportErr
|
|||||||
struct Expectation {
|
struct Expectation {
|
||||||
method: Method,
|
method: Method,
|
||||||
url: String,
|
url: String,
|
||||||
status: u16,
|
response: Result<HttpResponse, TransportError>,
|
||||||
body: Vec<u8>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Scripted [`HttpTransport`]: queue expected requests in order with
|
/// Scripted [`HttpTransport`]: queue expected requests in order with
|
||||||
@@ -36,11 +35,24 @@ impl FakeTransport {
|
|||||||
|
|
||||||
/// Queues the next expected request and the response to return for it.
|
/// Queues the next expected request and the response to return for it.
|
||||||
pub fn expect(&self, method: Method, url: &str, status: u16, body: impl Into<Vec<u8>>) {
|
pub fn expect(&self, method: Method, url: &str, status: u16, body: impl Into<Vec<u8>>) {
|
||||||
|
let response = HttpResponse {
|
||||||
|
status,
|
||||||
|
body: body.into(),
|
||||||
|
};
|
||||||
|
self.push(method, url, Ok(response));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Queues the next expected request and the transport error it fails
|
||||||
|
/// with (e.g. the server is unreachable).
|
||||||
|
pub fn fail(&self, method: Method, url: &str, error: TransportError) {
|
||||||
|
self.push(method, url, Err(error));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push(&self, method: Method, url: &str, response: Result<HttpResponse, TransportError>) {
|
||||||
self.expectations.lock().unwrap().push(Expectation {
|
self.expectations.lock().unwrap().push(Expectation {
|
||||||
method,
|
method,
|
||||||
url: url.to_string(),
|
url: url.to_string(),
|
||||||
status,
|
response,
|
||||||
body: body.into(),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,9 +104,6 @@ impl HttpTransport for FakeTransport {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
self.requests.lock().unwrap().push(req);
|
self.requests.lock().unwrap().push(req);
|
||||||
Ok(HttpResponse {
|
expectation.response
|
||||||
status: expectation.status,
|
|
||||||
body: expectation.body,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -86,6 +86,7 @@ impl DeepScript {
|
|||||||
url: format!("{}/transcriptions/{remote_id}/status", self.base_url),
|
url: format!("{}/transcriptions/{remote_id}/status", self.base_url),
|
||||||
headers: vec![self.auth_header()],
|
headers: vec![self.auth_header()],
|
||||||
body: HttpBody::Empty,
|
body: HttpBody::Empty,
|
||||||
|
follow_redirects: true,
|
||||||
};
|
};
|
||||||
let resp = match self.transport.send(req).await {
|
let resp = match self.transport.send(req).await {
|
||||||
Ok(resp) => resp,
|
Ok(resp) => resp,
|
||||||
@@ -115,6 +116,7 @@ impl DeepScript {
|
|||||||
url: format!("{}/transcriptions/{remote_id}", self.base_url),
|
url: format!("{}/transcriptions/{remote_id}", self.base_url),
|
||||||
headers: vec![self.auth_header()],
|
headers: vec![self.auth_header()],
|
||||||
body: HttpBody::Empty,
|
body: HttpBody::Empty,
|
||||||
|
follow_redirects: true,
|
||||||
};
|
};
|
||||||
let resp = self.send(req).await?;
|
let resp = self.send(req).await?;
|
||||||
match resp.status {
|
match resp.status {
|
||||||
@@ -205,6 +207,7 @@ impl Transcriber for DeepScript {
|
|||||||
url: format!("{}/transcriptions", self.base_url),
|
url: format!("{}/transcriptions", self.base_url),
|
||||||
headers: vec![self.auth_header()],
|
headers: vec![self.auth_header()],
|
||||||
body: HttpBody::Multipart(parts),
|
body: HttpBody::Multipart(parts),
|
||||||
|
follow_redirects: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
let resp = self.send(req).await?;
|
let resp = self.send(req).await?;
|
||||||
@@ -265,6 +268,7 @@ impl Transcriber for DeepScript {
|
|||||||
url: format!("{}/transcriptions/{remote_id}", self.base_url),
|
url: format!("{}/transcriptions/{remote_id}", self.base_url),
|
||||||
headers: vec![self.auth_header()],
|
headers: vec![self.auth_header()],
|
||||||
body: HttpBody::Empty,
|
body: HttpBody::Empty,
|
||||||
|
follow_redirects: true,
|
||||||
};
|
};
|
||||||
let resp = self.send(req).await?;
|
let resp = self.send(req).await?;
|
||||||
match resp.status {
|
match resp.status {
|
||||||
|
|||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"version": "0.2.0",
|
||||||
|
"pub_date": "2026-11-06T14:19:53Z",
|
||||||
|
"platforms": {
|
||||||
|
"windows-x86_64": {
|
||||||
|
"signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVUdGpRa1ZvalU2SUtlUG9ZajRMcmFHb0dxNG1OM1lWZEExbzhsSjYzdUJxY1NrY2xERmRGbGJEV3c0UWRjdmVuaHFtWXlzYVU2alFJY0k4V1hoZ1FWdDVNV0xkclRQV2c0PQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzOTc0NzYxCWZpbGU6R2VzcHLDpGNoc3Jla29yZGVyXzAuMi4wX3g2NC1zZXR1cC5leGUJdmVyc2lvbjowLjIuMApna2tpeVdYMkhDU2d4ZjAwVTJaQjBBMG0yL010V2xIc3Awc0QzOXJsK2lmUi9oM1hwWmlvL2dNdFQzVzQrTys1ZnNmZHpXM0JicTRzd1d2MXp5YjhEQT09Cg==",
|
||||||
|
"url": "https://gitea.euvino.eu/public/call-recorder/releases/download/v0.2.0/Gespraechsrekorder_0.2.0_x64-setup.exe"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# Builds a signed release of Gesprächsrekorder into dist-release/<version>/:
|
# Builds a signed release of Gesprächsrekorder into dist-release/<version>/:
|
||||||
# the Windows NSIS installer (cross-built via build-windows.sh), the Linux
|
# the Windows NSIS installer (cross-built via build-windows.sh), the Linux
|
||||||
# deb and AppImage, their updater signatures (.sig) and latest.json.
|
# deb, their updater signatures (.sig) and latest.json.
|
||||||
# Sets <version> in tauri.conf.json, src-tauri/Cargo.toml and
|
# Sets <version> in tauri.conf.json, src-tauri/Cargo.toml and
|
||||||
# ui/package.json and leaves those changes for you to commit. Never tags or
|
# ui/package.json and leaves those changes for you to commit. Never tags or
|
||||||
# publishes anything; see RELEASING.md.
|
# publishes anything; see RELEASING.md.
|
||||||
@@ -157,7 +157,7 @@ grep -qx "version = \"${VERSION}\"" "${CARGO_TOML}" || die "could not set the ve
|
|||||||
|
|
||||||
# --- Build ------------------------------------------------------------------
|
# --- Build ------------------------------------------------------------------
|
||||||
"${SCRIPT_DIR}/build-windows.sh"
|
"${SCRIPT_DIR}/build-windows.sh"
|
||||||
(cd "${REPO_ROOT}" && cargo tauri build --bundles deb appimage)
|
(cd "${REPO_ROOT}" && cargo tauri build --bundles deb)
|
||||||
|
|
||||||
# --- Collect ----------------------------------------------------------------
|
# --- Collect ----------------------------------------------------------------
|
||||||
OUT="${REPO_ROOT}/dist-release/${VERSION}"
|
OUT="${REPO_ROOT}/dist-release/${VERSION}"
|
||||||
@@ -183,7 +183,6 @@ collect() {
|
|||||||
}
|
}
|
||||||
collect "${WINDOWS_BUNDLE}" "*_${VERSION}_x64-setup.exe"
|
collect "${WINDOWS_BUNDLE}" "*_${VERSION}_x64-setup.exe"
|
||||||
collect "${LINUX_BUNDLE}/deb" "*_${VERSION}_amd64.deb"
|
collect "${LINUX_BUNDLE}/deb" "*_${VERSION}_amd64.deb"
|
||||||
collect "${LINUX_BUNDLE}/appimage" "*_${VERSION}_amd64.AppImage"
|
|
||||||
|
|
||||||
"${SCRIPT_DIR}/make-latest-json.sh" "${VERSION}" "${OUT}"
|
"${SCRIPT_DIR}/make-latest-json.sh" "${VERSION}" "${OUT}"
|
||||||
jq -e . "${OUT}/latest.json" >/dev/null || die "latest.json is not valid JSON"
|
jq -e . "${OUT}/latest.json" >/dev/null || die "latest.json is not valid JSON"
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
# Writes <dir>/latest.json, the update feed the app reads, from the signed
|
# Writes <dir>/latest.json, the update feed the app reads, from the signed
|
||||||
# release artifacts in <dir>:
|
# release artifacts in <dir>:
|
||||||
# windows-x86_64 -> *_<version>_x64-setup.exe (+ .sig)
|
# windows-x86_64 -> *_<version>_x64-setup.exe (+ .sig)
|
||||||
# linux-x86_64 -> *_<version>_amd64.AppImage (+ .sig)
|
# Debian builds do not self-update, so the .deb is not listed here (it is
|
||||||
|
# still a release asset, just not part of the feed).
|
||||||
# The download URLs point at ${RELEASE_BASE_URL}/releases/download/v<version>/
|
# The download URLs point at ${RELEASE_BASE_URL}/releases/download/v<version>/
|
||||||
# (scripts/release.env).
|
# (scripts/release.env).
|
||||||
#
|
#
|
||||||
@@ -38,7 +39,6 @@ signed_file() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
WINDOWS="$(signed_file "*_${VERSION}_x64-setup.exe")"
|
WINDOWS="$(signed_file "*_${VERSION}_x64-setup.exe")"
|
||||||
LINUX="$(signed_file "*_${VERSION}_amd64.AppImage")"
|
|
||||||
|
|
||||||
jq -n \
|
jq -n \
|
||||||
--arg version "${VERSION}" \
|
--arg version "${VERSION}" \
|
||||||
@@ -46,8 +46,6 @@ jq -n \
|
|||||||
--arg base "${RELEASE_BASE_URL}/releases/download/v${VERSION}" \
|
--arg base "${RELEASE_BASE_URL}/releases/download/v${VERSION}" \
|
||||||
--arg windows_file "$(basename "${WINDOWS}")" \
|
--arg windows_file "$(basename "${WINDOWS}")" \
|
||||||
--rawfile windows_sig "${WINDOWS}.sig" \
|
--rawfile windows_sig "${WINDOWS}.sig" \
|
||||||
--arg linux_file "$(basename "${LINUX}")" \
|
|
||||||
--rawfile linux_sig "${LINUX}.sig" \
|
|
||||||
'{
|
'{
|
||||||
version: $version,
|
version: $version,
|
||||||
pub_date: $pub_date,
|
pub_date: $pub_date,
|
||||||
@@ -55,10 +53,6 @@ jq -n \
|
|||||||
"windows-x86_64": {
|
"windows-x86_64": {
|
||||||
signature: ($windows_sig | gsub("\\s"; "")),
|
signature: ($windows_sig | gsub("\\s"; "")),
|
||||||
url: "\($base)/\($windows_file | @uri)"
|
url: "\($base)/\($windows_file | @uri)"
|
||||||
},
|
|
||||||
"linux-x86_64": {
|
|
||||||
signature: ($linux_sig | gsub("\\s"; "")),
|
|
||||||
url: "\($base)/\($linux_file | @uri)"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}' >"${DIR}/latest.json"
|
}' >"${DIR}/latest.json"
|
||||||
|
|||||||
+3
-7
@@ -6,13 +6,9 @@
|
|||||||
|
|
||||||
RELEASE_BASE_URL="https://gitea.euvino.eu/public/call-recorder"
|
RELEASE_BASE_URL="https://gitea.euvino.eu/public/call-recorder"
|
||||||
|
|
||||||
# Where the app looks for latest.json, tried in this order until one answers
|
# Where the app looks for latest.json: committed to the root of master.
|
||||||
# with a release:
|
# Gitea 1.27.3 does not redirect releases/latest/download/<file> to a
|
||||||
# 1. latest.json as an asset of the newest release,
|
# release's assets, so that URL is not offered here. See RELEASING.md.
|
||||||
# 2. latest.json committed to the root of master.
|
|
||||||
# Once it is clear which one Gitea serves, the other can be dropped here (it
|
|
||||||
# then disappears from the next version built).
|
|
||||||
UPDATE_JSON_URLS=(
|
UPDATE_JSON_URLS=(
|
||||||
"${RELEASE_BASE_URL}/releases/latest/download/latest.json"
|
|
||||||
"${RELEASE_BASE_URL}/raw/branch/master/latest.json"
|
"${RELEASE_BASE_URL}/raw/branch/master/latest.json"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "call-recorder"
|
name = "call-recorder"
|
||||||
version = "0.1.1"
|
version = "0.2.1"
|
||||||
description = "Gesprächsrekorder desktop app"
|
description = "Gesprächsrekorder desktop app"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
@@ -27,3 +27,6 @@ tempfile = "3"
|
|||||||
recorder-core = { path = "../crates/core" }
|
recorder-core = { path = "../crates/core" }
|
||||||
recorder-audio = { path = "../crates/audio" }
|
recorder-audio = { path = "../crates/audio" }
|
||||||
tauri-plugin-updater = "2"
|
tauri-plugin-updater = "2"
|
||||||
|
tauri-plugin-opener = "2"
|
||||||
|
tokio = { version = "1", features = ["sync"] }
|
||||||
|
async-trait = "0.1"
|
||||||
|
|||||||
@@ -0,0 +1,493 @@
|
|||||||
|
//! 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. Switch to "https://backend.euvinopro.eu" here, then
|
||||||
|
/// release, once that backend is live.
|
||||||
|
const RELEASE_BACKEND_URL: &str = "https://test.euvinopro.eu";
|
||||||
|
/// Debug builds (`cargo tauri dev`) always use the test backend.
|
||||||
|
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})");
|
||||||
|
state.mark_uploaded(id, &crm_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`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}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn everyone_waiting_gets_the_one_login_result() {
|
||||||
|
let waiters = LoginWaiters::default();
|
||||||
|
assert!(!waiters.waiting());
|
||||||
|
|
||||||
|
let (first, starts) = waiters.join();
|
||||||
|
let (second, starts_again) = waiters.join();
|
||||||
|
assert!(starts);
|
||||||
|
assert!(!starts_again);
|
||||||
|
assert!(waiters.waiting());
|
||||||
|
|
||||||
|
waiters.finish(Ok("euv_k".into()));
|
||||||
|
|
||||||
|
assert_eq!(first.blocking_recv().unwrap(), Ok("euv_k".to_string()));
|
||||||
|
assert_eq!(second.blocking_recv().unwrap(), Ok("euv_k".to_string()));
|
||||||
|
assert!(!waiters.waiting());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_finished_login_leaves_the_next_one_to_start_anew() {
|
||||||
|
let waiters = LoginWaiters::default();
|
||||||
|
let (first, _) = waiters.join();
|
||||||
|
waiters.finish(Err(CANCELLED.into()));
|
||||||
|
// A late "window destroyed" reaches nobody.
|
||||||
|
waiters.finish(Err("ignored".into()));
|
||||||
|
assert_eq!(first.blocking_recv().unwrap(), Err(CANCELLED.to_string()));
|
||||||
|
|
||||||
|
let (next, starts) = waiters.join();
|
||||||
|
assert!(starts);
|
||||||
|
waiters.finish(Ok("euv_new".into()));
|
||||||
|
assert_eq!(next.blocking_recv().unwrap(), Ok("euv_new".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_one_key_is_created_at_a_time() {
|
||||||
|
let waiters = LoginWaiters::default();
|
||||||
|
let claim = waiters.claim_creating();
|
||||||
|
assert!(claim.is_some());
|
||||||
|
assert!(waiters.claim_creating().is_none());
|
||||||
|
drop(claim);
|
||||||
|
assert!(waiters.claim_creating().is_some());
|
||||||
|
}
|
||||||
|
}
|
||||||
+39
-18
@@ -8,7 +8,6 @@
|
|||||||
use std::thread;
|
use std::thread;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use recorder_core::accounts::{self, Account};
|
|
||||||
use recorder_core::call_view::{CallDetail, CallListItem};
|
use recorder_core::call_view::{CallDetail, CallListItem};
|
||||||
use recorder_core::capture::Devices;
|
use recorder_core::capture::Devices;
|
||||||
use recorder_core::model::CallId;
|
use recorder_core::model::CallId;
|
||||||
@@ -24,6 +23,10 @@ use crate::state::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
const LEVELS_INTERVAL: Duration = Duration::from_millis(100);
|
const LEVELS_INTERVAL: Duration = Duration::from_millis(100);
|
||||||
|
/// `set_api_key`/`has_api_key` refuse this service: its key is managed only
|
||||||
|
/// by the backend login (`backend::login`), which holds `backend_key_lock`
|
||||||
|
/// and binds the key to this build's backend.
|
||||||
|
const BACKEND_KEY_MANAGED: &str = "Dieser Schlüssel wird über die Backend-Anmeldung verwaltet";
|
||||||
|
|
||||||
type CmdResult<T> = Result<T, String>;
|
type CmdResult<T> = Result<T, String>;
|
||||||
|
|
||||||
@@ -33,6 +36,12 @@ struct CallEnded {
|
|||||||
id: CallId,
|
id: CallId,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// This build's own version, for the settings' "Updates" section.
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn get_app_version(app: AppHandle) -> String {
|
||||||
|
app.package_info().version.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn get_settings(state: State<'_, AppState>) -> Settings {
|
pub fn get_settings(state: State<'_, AppState>) -> Settings {
|
||||||
state.settings()
|
state.settings()
|
||||||
@@ -50,9 +59,11 @@ pub fn save_settings(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Stores `key` in the keyring; an empty key deletes the entry.
|
/// Stores `key` in the keyring; an empty key deletes the entry. Refuses
|
||||||
|
/// `Service::Backend` (see [`BACKEND_KEY_MANAGED`]).
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn set_api_key(app: AppHandle, service: Service, key: String) -> CmdResult<()> {
|
pub async fn set_api_key(app: AppHandle, service: Service, key: String) -> CmdResult<()> {
|
||||||
|
reject_backend_service(service)?;
|
||||||
blocking(app, move |app| {
|
blocking(app, move |app| {
|
||||||
let secrets = &app.state::<AppState>().secrets;
|
let secrets = &app.state::<AppState>().secrets;
|
||||||
let key = key.trim();
|
let key = key.trim();
|
||||||
@@ -66,9 +77,11 @@ pub async fn set_api_key(app: AppHandle, service: Service, key: String) -> CmdRe
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether a key is stored. Never returns the key itself.
|
/// Whether a key is stored. Never returns the key itself. Refuses
|
||||||
|
/// `Service::Backend` (see [`BACKEND_KEY_MANAGED`]).
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn has_api_key(app: AppHandle, service: Service) -> CmdResult<bool> {
|
pub async fn has_api_key(app: AppHandle, service: Service) -> CmdResult<bool> {
|
||||||
|
reject_backend_service(service)?;
|
||||||
blocking(app, move |app| {
|
blocking(app, move |app| {
|
||||||
let key = app.state::<AppState>().secrets.get(service);
|
let key = app.state::<AppState>().secrets.get(service);
|
||||||
Ok(key.is_some_and(|key| !key.is_empty()))
|
Ok(key.is_some_and(|key| !key.is_empty()))
|
||||||
@@ -76,6 +89,15 @@ pub async fn has_api_key(app: AppHandle, service: Service) -> CmdResult<bool> {
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Refuses direct keyring access to `Service::Backend`: its key is only
|
||||||
|
/// ever set by the backend login flow.
|
||||||
|
fn reject_backend_service(service: Service) -> CmdResult<()> {
|
||||||
|
if service == Service::Backend {
|
||||||
|
return Err(BACKEND_KEY_MANAGED.to_string());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn list_devices() -> CmdResult<Devices> {
|
pub async fn list_devices() -> CmdResult<Devices> {
|
||||||
tauri::async_runtime::spawn_blocking(recorder_audio::list_devices)
|
tauri::async_runtime::spawn_blocking(recorder_audio::list_devices)
|
||||||
@@ -186,21 +208,6 @@ pub fn rename_call(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn list_accounts() -> Vec<Account> {
|
|
||||||
accounts::list()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Assigns a call to a customer account, or to none.
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn set_account(
|
|
||||||
state: State<'_, AppState>,
|
|
||||||
id: CallId,
|
|
||||||
account_id: Option<String>,
|
|
||||||
) -> CmdResult<()> {
|
|
||||||
state.set_account(id, account_id.as_deref())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Deletes a finished call's audio and row. Closes the prompt if no call
|
/// Deletes a finished call's audio and row. Closes the prompt if no call
|
||||||
/// waits for it any more; otherwise the prompt reloads and shows the next.
|
/// waits for it any more; otherwise the prompt reloads and shows the next.
|
||||||
/// While its DeepScript jobs are still on record, nothing is deleted and a
|
/// While its DeepScript jobs are still on record, nothing is deleted and a
|
||||||
@@ -428,3 +435,17 @@ where
|
|||||||
.await
|
.await
|
||||||
.map_err(|e| e.to_string())?
|
.map_err(|e| e.to_string())?
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_backend_key_is_managed_only_by_the_login() {
|
||||||
|
assert_eq!(
|
||||||
|
reject_backend_service(Service::Backend),
|
||||||
|
Err(BACKEND_KEY_MANAGED.to_string())
|
||||||
|
);
|
||||||
|
assert_eq!(reject_backend_service(Service::DeepScript), Ok(()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+27
-4
@@ -1,3 +1,4 @@
|
|||||||
|
mod backend;
|
||||||
mod commands;
|
mod commands;
|
||||||
mod detection;
|
mod detection;
|
||||||
mod processing;
|
mod processing;
|
||||||
@@ -13,7 +14,7 @@ use tauri_plugin_autostart::MacosLauncher;
|
|||||||
use tauri_plugin_log::{RotationStrategy, Target, TargetKind, TimezoneStrategy};
|
use tauri_plugin_log::{RotationStrategy, Target, TargetKind, TimezoneStrategy};
|
||||||
|
|
||||||
use crate::state::AppState;
|
use crate::state::AppState;
|
||||||
use crate::updater::PendingUpdate;
|
use crate::updater::{PendingUpdate, UpdateSchedule};
|
||||||
|
|
||||||
/// Command-line flag the login item starts the app with; the main window
|
/// Command-line flag the login item starts the app with; the main window
|
||||||
/// then stays hidden in the tray.
|
/// then stays hidden in the tray.
|
||||||
@@ -34,6 +35,14 @@ pub fn run() {
|
|||||||
))
|
))
|
||||||
.plugin(tauri_plugin_notification::init())
|
.plugin(tauri_plugin_notification::init())
|
||||||
.plugin(tauri_plugin_updater::Builder::new().build())
|
.plugin(tauri_plugin_updater::Builder::new().build())
|
||||||
|
// Only for `open_backend_keys_page`: no capability grants the UI
|
||||||
|
// the plugin's commands, and no link-click script is injected (it
|
||||||
|
// would also run in the remote login page).
|
||||||
|
.plugin(
|
||||||
|
tauri_plugin_opener::Builder::new()
|
||||||
|
.open_js_links_on_click(false)
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
.setup(|app| {
|
.setup(|app| {
|
||||||
// Release builds log to a file in the app log directory (on
|
// Release builds log to a file in the app log directory (on
|
||||||
// Windows %LOCALAPPDATA%\eu.euvino.callrecorder\logs), debug
|
// Windows %LOCALAPPDATA%\eu.euvino.callrecorder\logs), debug
|
||||||
@@ -83,10 +92,14 @@ pub fn run() {
|
|||||||
&config_dir.join("last-version"),
|
&config_dir.join("last-version"),
|
||||||
&app.package_info().version.to_string(),
|
&app.package_info().version.to_string(),
|
||||||
);
|
);
|
||||||
|
// Off the main thread: the keyring can be slow to answer.
|
||||||
|
std::thread::spawn(KeyringSecrets::remove_unused_keys);
|
||||||
// Before anything can start a run.
|
// Before anything can start a run.
|
||||||
processing::clear_upload_dir(app.handle());
|
processing::clear_upload_dir(app.handle());
|
||||||
app.manage(state);
|
app.manage(state);
|
||||||
app.manage(PendingUpdate::default());
|
app.manage(PendingUpdate::default());
|
||||||
|
app.manage(UpdateSchedule::default());
|
||||||
|
app.manage(backend::LoginWaiters::default());
|
||||||
// Windows are created here (`create: false` in tauri.conf.json)
|
// Windows are created here (`create: false` in tauri.conf.json)
|
||||||
// instead of by Tauri before `setup` runs: their webviews load
|
// instead of by Tauri before `setup` runs: their webviews load
|
||||||
// immediately and invoke commands (list_calls, get_recording_state,
|
// immediately and invoke commands (list_calls, get_recording_state,
|
||||||
@@ -108,13 +121,17 @@ pub fn run() {
|
|||||||
})
|
})
|
||||||
.on_window_event(|window, event| {
|
.on_window_event(|window, event| {
|
||||||
// Closing a window only hides it; the app keeps running in the
|
// Closing a window only hides it; the app keeps running in the
|
||||||
// tray (for call detection) until "Beenden".
|
// tray (for call detection) until "Beenden". The login window
|
||||||
|
// really closes: that cancels the login.
|
||||||
if let WindowEvent::CloseRequested { api, .. } = event {
|
if let WindowEvent::CloseRequested { api, .. } = event {
|
||||||
|
if window.label() != backend::LOGIN_WINDOW {
|
||||||
api.prevent_close();
|
api.prevent_close();
|
||||||
let _ = window.hide();
|
let _ = window.hide();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.invoke_handler(tauri::generate_handler![
|
.invoke_handler(tauri::generate_handler![
|
||||||
|
commands::get_app_version,
|
||||||
commands::get_settings,
|
commands::get_settings,
|
||||||
commands::save_settings,
|
commands::save_settings,
|
||||||
commands::set_api_key,
|
commands::set_api_key,
|
||||||
@@ -137,10 +154,16 @@ pub fn run() {
|
|||||||
commands::merge_speakers,
|
commands::merge_speakers,
|
||||||
commands::unmerge_speaker,
|
commands::unmerge_speaker,
|
||||||
commands::rename_call,
|
commands::rename_call,
|
||||||
commands::list_accounts,
|
backend::backend_server,
|
||||||
commands::set_account,
|
backend::backend_status,
|
||||||
|
backend::backend_login,
|
||||||
|
backend::backend_logout,
|
||||||
|
backend::open_backend_keys_page,
|
||||||
|
backend::upload_transcript,
|
||||||
updater::get_update,
|
updater::get_update,
|
||||||
updater::install_update,
|
updater::install_update,
|
||||||
|
updater::check_for_update_now,
|
||||||
|
updater::can_self_update,
|
||||||
])
|
])
|
||||||
.run(tauri::generate_context!())
|
.run(tauri::generate_context!())
|
||||||
.expect("error while building tauri application");
|
.expect("error while building tauri application");
|
||||||
|
|||||||
+414
-45
@@ -17,14 +17,14 @@ use std::time::{Duration, Instant};
|
|||||||
|
|
||||||
use chrono::{DateTime, Local};
|
use chrono::{DateTime, Local};
|
||||||
use recorder_audio::RenderSession;
|
use recorder_audio::RenderSession;
|
||||||
use recorder_core::accounts;
|
use recorder_core::backend::{BackendClient, KeyInfo, NewKey, StoredKey};
|
||||||
use recorder_core::call_view::{self, CallDetail, CallListItem};
|
use recorder_core::call_view::{self, CallDetail, CallListItem};
|
||||||
use recorder_core::capture::{CaptureSource, OutputTarget};
|
use recorder_core::capture::{CaptureSource, OutputTarget};
|
||||||
use recorder_core::detect::{CallDetector, DetectorEvent, MicSession};
|
use recorder_core::detect::{CallDetector, DetectorEvent, MicSession};
|
||||||
use recorder_core::http::{HttpTransport, ReqwestTransport};
|
use recorder_core::http::{HttpTransport, ReqwestTransport};
|
||||||
use recorder_core::model::{Call, CallId, CallStatus, Speaker};
|
use recorder_core::model::{Call, CallId, CallStatus, Speaker};
|
||||||
use recorder_core::recorder::Recorder;
|
use recorder_core::recorder::Recorder;
|
||||||
use recorder_core::secrets::SecretStore;
|
use recorder_core::secrets::{SecretStore, Service};
|
||||||
use recorder_core::settings::Settings;
|
use recorder_core::settings::Settings;
|
||||||
use recorder_core::store::Store;
|
use recorder_core::store::Store;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
@@ -157,6 +157,26 @@ pub struct AppState {
|
|||||||
/// Set while a recording starts or the devices are tested, so neither
|
/// Set while a recording starts or the devices are tested, so neither
|
||||||
/// runs twice and `current` is never locked for longer than a moment.
|
/// runs twice and `current` is never locked for longer than a moment.
|
||||||
devices_busy: AtomicBool,
|
devices_busy: AtomicBool,
|
||||||
|
/// The backend this build talks to ([`crate::backend::BACKEND_URL`]).
|
||||||
|
backend_url: String,
|
||||||
|
/// Held while the stored backend key and its login change, so a
|
||||||
|
/// compare-and-delete never removes a key stored meanwhile.
|
||||||
|
backend_key_lock: Mutex<()>,
|
||||||
|
/// Calls whose transcript is being uploaded; one upload per call.
|
||||||
|
uploading: Mutex<HashSet<CallId>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An upload reserved with [`AppState::claim_upload`]; released when
|
||||||
|
/// dropped, also if the upload fails or panics.
|
||||||
|
pub struct UploadClaim<'a> {
|
||||||
|
state: &'a AppState,
|
||||||
|
id: CallId,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for UploadClaim<'_> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
lock(&self.state.uploading).remove(&self.id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Releases [`AppState::devices_busy`] when dropped.
|
/// Releases [`AppState::devices_busy`] when dropped.
|
||||||
@@ -189,6 +209,14 @@ impl AppState {
|
|||||||
pending_prompts: Mutex::new(VecDeque::new()),
|
pending_prompts: Mutex::new(VecDeque::new()),
|
||||||
processing: Mutex::new(HashSet::new()),
|
processing: Mutex::new(HashSet::new()),
|
||||||
devices_busy: AtomicBool::new(false),
|
devices_busy: AtomicBool::new(false),
|
||||||
|
// Defensive: BACKEND_URL itself must never have a trailing
|
||||||
|
// slash (see backend::tests::backend_urls_have_no_trailing…),
|
||||||
|
// but a stored key's base_url is compared against this field.
|
||||||
|
backend_url: crate::backend::BACKEND_URL
|
||||||
|
.trim_end_matches('/')
|
||||||
|
.to_string(),
|
||||||
|
backend_key_lock: Mutex::new(()),
|
||||||
|
uploading: Mutex::new(HashSet::new()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -196,15 +224,156 @@ impl AppState {
|
|||||||
lock(&self.settings).clone()
|
lock(&self.settings).clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Validates, saves and applies the settings; the detector picks up the
|
/// Validates, saves and applies the settings the user edited; the
|
||||||
/// new allowlist and delays immediately.
|
/// detector picks up the new allowlist and delays immediately. The
|
||||||
pub fn save_settings(&self, settings: Settings) -> Result<(), String> {
|
/// backend login (managed by the app) is kept.
|
||||||
settings.validate()?;
|
pub fn save_settings(&self, edited: Settings) -> Result<(), String> {
|
||||||
settings
|
let mut current = lock(&self.settings);
|
||||||
.save(&self.settings_path)
|
let settings = current.edited(edited)?;
|
||||||
.map_err(|e| format!("Einstellungen konnten nicht gespeichert werden: {e}"))?;
|
save(&settings, &self.settings_path)?;
|
||||||
lock(&self.detector).set_config(detector_config(&settings));
|
lock(&self.detector).set_config(detector_config(&settings));
|
||||||
*lock(&self.settings) = settings;
|
*current = settings;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The backend this build talks to.
|
||||||
|
pub fn backend_url(&self) -> &str {
|
||||||
|
&self.backend_url
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Client of this build's backend.
|
||||||
|
pub fn backend_client(&self) -> BackendClient {
|
||||||
|
BackendClient::new(self.transport.clone(), &self.backend_url)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The stored backend key with its expiry, if it was created for this
|
||||||
|
/// build's backend. A key of another backend is discarded instead (as
|
||||||
|
/// if expired), so it is never sent anywhere else. Reads the keyring,
|
||||||
|
/// so call it off the UI thread.
|
||||||
|
pub fn backend_key(&self) -> Option<StoredKey> {
|
||||||
|
let _key_lock = lock(&self.backend_key_lock);
|
||||||
|
let key = self
|
||||||
|
.secrets
|
||||||
|
.get(Service::Backend)
|
||||||
|
.filter(|key| !key.trim().is_empty())?;
|
||||||
|
let settings = self.settings();
|
||||||
|
if settings.backend_key_base_url.as_deref() != Some(self.backend_url.as_str()) {
|
||||||
|
log::info!(
|
||||||
|
"backend: the stored key belongs to {:?}, not {:?}: discarding it",
|
||||||
|
settings.backend_key_base_url,
|
||||||
|
self.backend_url
|
||||||
|
);
|
||||||
|
if let Err(e) = self.forget_backend_key() {
|
||||||
|
log::error!("backend: {e}");
|
||||||
|
}
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(StoredKey {
|
||||||
|
key,
|
||||||
|
expires_at: settings.backend_key_expires_at,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stores a key the login created for the backend at `base_url` (in
|
||||||
|
/// the keyring) with whose it is, when it expires and its backend (in
|
||||||
|
/// the settings). A key of another backend than this build's is
|
||||||
|
/// refused and nothing stored.
|
||||||
|
pub fn store_backend_key(
|
||||||
|
&self,
|
||||||
|
key: &NewKey,
|
||||||
|
base_url: &str,
|
||||||
|
username: Option<String>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let base_url = base_url.trim_end_matches('/');
|
||||||
|
if base_url != self.backend_url {
|
||||||
|
return Err(format!(
|
||||||
|
"Der Schlüssel gehört zu einem anderen Server ({base_url}) und wurde nicht gespeichert."
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let _key_lock = lock(&self.backend_key_lock);
|
||||||
|
self.secrets
|
||||||
|
.set(Service::Backend, &key.key)
|
||||||
|
.map_err(|e| format!("Backend-Schlüssel konnte nicht gespeichert werden: {e}"))?;
|
||||||
|
self.update_settings(|s| {
|
||||||
|
s.backend_username = username;
|
||||||
|
s.backend_key_expires_at = Some(key.expires_at);
|
||||||
|
s.backend_key_base_url = Some(base_url.to_string());
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Takes over whose the stored key is and when it expires, as the
|
||||||
|
/// backend reports it.
|
||||||
|
pub fn refresh_backend_login(&self, info: &KeyInfo) -> Result<(), String> {
|
||||||
|
self.update_settings(|s| {
|
||||||
|
s.backend_username = Some(info.username.clone());
|
||||||
|
s.backend_key_expires_at = Some(info.expires_at);
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "Abmelden": forgets the backend key (keyring) and its login
|
||||||
|
/// (settings).
|
||||||
|
pub fn discard_backend_key(&self) -> Result<(), String> {
|
||||||
|
let _key_lock = lock(&self.backend_key_lock);
|
||||||
|
self.forget_backend_key()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Forgets the stored backend key only if it still is `refused`, the
|
||||||
|
/// key the backend just refused; a key stored meanwhile (by a login)
|
||||||
|
/// stays. Returns whether it was forgotten.
|
||||||
|
pub fn discard_refused_backend_key(&self, refused: &str) -> Result<bool, String> {
|
||||||
|
let _key_lock = lock(&self.backend_key_lock);
|
||||||
|
if self.secrets.get(Service::Backend).as_deref() != Some(refused) {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
self.forget_backend_key().map(|()| true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deletes the key and its login; the caller holds `backend_key_lock`.
|
||||||
|
/// The keyring is never called while the settings are locked.
|
||||||
|
fn forget_backend_key(&self) -> Result<(), String> {
|
||||||
|
self.secrets
|
||||||
|
.delete(Service::Backend)
|
||||||
|
.map_err(|e| format!("Backend-Schlüssel konnte nicht entfernt werden: {e}"))?;
|
||||||
|
self.update_settings(|s| {
|
||||||
|
s.backend_username = None;
|
||||||
|
s.backend_key_expires_at = None;
|
||||||
|
s.backend_key_base_url = None;
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reserves call `id` for one upload; released when the claim is
|
||||||
|
/// dropped. A second upload of the same call is refused meanwhile, and a
|
||||||
|
/// call that already carries a CRM transcript id is refused outright:
|
||||||
|
/// the CRM must never get a duplicate. Both checks happen while
|
||||||
|
/// `uploading` is locked, so a second upload can never slip in between
|
||||||
|
/// this check and the one upload it allows.
|
||||||
|
pub fn claim_upload(&self, id: CallId) -> Result<UploadClaim<'_>, String> {
|
||||||
|
let mut uploading = lock(&self.uploading);
|
||||||
|
if uploading.contains(&id) {
|
||||||
|
return Err("Wird bereits hochgeladen".to_string());
|
||||||
|
}
|
||||||
|
if self.find_call(id)?.crm_transcript_id.is_some() {
|
||||||
|
return Err("Bereits hochgeladen".to_string());
|
||||||
|
}
|
||||||
|
uploading.insert(id);
|
||||||
|
Ok(UploadClaim { state: self, id })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether call `id`'s transcript is being uploaded.
|
||||||
|
pub fn is_uploading(&self, id: CallId) -> bool {
|
||||||
|
lock(&self.uploading).contains(&id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Changes and saves settings the app manages itself; saves only if
|
||||||
|
/// something changed.
|
||||||
|
fn update_settings(&self, change: impl FnOnce(&mut Settings)) -> Result<(), String> {
|
||||||
|
let mut current = lock(&self.settings);
|
||||||
|
let mut settings = current.clone();
|
||||||
|
change(&mut settings);
|
||||||
|
if settings != *current {
|
||||||
|
save(&settings, &self.settings_path)?;
|
||||||
|
*current = settings;
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -441,14 +610,16 @@ impl AppState {
|
|||||||
Ok(calls.iter().map(CallListItem::of).collect())
|
Ok(calls.iter().map(CallListItem::of).collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The selected call with its transcript (speaker merges applied) and
|
/// The selected call with its transcript (speaker merges applied),
|
||||||
/// speaker names.
|
/// speaker names and whether it is being uploaded.
|
||||||
pub fn call_detail(&self, id: CallId) -> Result<CallDetail, String> {
|
pub fn call_detail(&self, id: CallId) -> Result<CallDetail, String> {
|
||||||
let call = self.find_call(id)?;
|
let call = self.find_call(id)?;
|
||||||
let segments = self.store.segments(id).map_err(|e| e.to_string())?;
|
let segments = self.store.segments(id).map_err(|e| e.to_string())?;
|
||||||
let names = self.store.speaker_names(id).map_err(|e| e.to_string())?;
|
let names = self.store.speaker_names(id).map_err(|e| e.to_string())?;
|
||||||
let merges = self.store.speaker_merges(id).map_err(|e| e.to_string())?;
|
let merges = self.store.speaker_merges(id).map_err(|e| e.to_string())?;
|
||||||
Ok(CallDetail::of(&call, &segments, names, &merges))
|
let mut detail = CallDetail::of(&call, &segments, names, &merges);
|
||||||
|
detail.uploading = self.is_uploading(id);
|
||||||
|
Ok(detail)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Renames a speaker of call `id`; a blank `name` restores the default
|
/// Renames a speaker of call `id`; a blank `name` restores the default
|
||||||
@@ -496,15 +667,13 @@ impl AppState {
|
|||||||
self.store.set_title(id, title).map_err(|e| e.to_string())
|
self.store.set_title(id, title).map_err(|e| e.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Assigns call `id` to one of the [`accounts`], or to none.
|
/// Records that call `id`'s transcript was just uploaded and the CRM
|
||||||
pub fn set_account(&self, id: CallId, account_id: Option<&str>) -> Result<(), String> {
|
/// gave it `crm_transcript_id`.
|
||||||
if account_id.is_some_and(|account| !accounts::exists(account)) {
|
pub fn mark_uploaded(&self, id: CallId, crm_transcript_id: &str) -> Result<(), String> {
|
||||||
return Err("Unbekannter Kunde".to_string());
|
|
||||||
}
|
|
||||||
self.find_call(id)?;
|
self.find_call(id)?;
|
||||||
self.store
|
self.store
|
||||||
.set_account(id, account_id)
|
.set_uploaded(id, crm_transcript_id, Local::now())
|
||||||
.map_err(|e| format!("Kunde konnte nicht gespeichert werden: {e}"))
|
.map_err(|e| format!("Upload konnte nicht vermerkt werden: {e}"))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn find_call(&self, id: CallId) -> Result<Call, String> {
|
fn find_call(&self, id: CallId) -> Result<Call, String> {
|
||||||
@@ -708,6 +877,12 @@ fn detected_output_target(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn save(settings: &Settings, path: &Path) -> Result<(), String> {
|
||||||
|
settings
|
||||||
|
.save(path)
|
||||||
|
.map_err(|e| format!("Einstellungen konnten nicht gespeichert werden: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
fn output_target(settings: &Settings) -> OutputTarget {
|
fn output_target(settings: &Settings) -> OutputTarget {
|
||||||
match &settings.output_device {
|
match &settings.output_device {
|
||||||
Some(id) => OutputTarget::Device(id.clone()),
|
Some(id) => OutputTarget::Device(id.clone()),
|
||||||
@@ -725,8 +900,9 @@ fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use chrono::TimeZone;
|
use chrono::TimeZone;
|
||||||
|
use recorder_core::backend::{KeyInfo, NewKey, StoredKey};
|
||||||
use recorder_core::model::{Segment, Speaker};
|
use recorder_core::model::{Segment, Speaker};
|
||||||
use recorder_core::secrets::MemorySecrets;
|
use recorder_core::secrets::{MemorySecrets, Service};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
@@ -1244,30 +1420,6 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_account_is_set_and_cleared() {
|
|
||||||
let f = fixture();
|
|
||||||
let (id, _, _) = finished_call(&f, "a");
|
|
||||||
let account = |f: &Fixture| f.state.store.get_call(id).unwrap().unwrap().account_id;
|
|
||||||
|
|
||||||
f.state.set_account(id, Some("mock-2")).unwrap();
|
|
||||||
assert_eq!(account(&f).as_deref(), Some("mock-2"));
|
|
||||||
f.state.set_account(id, None).unwrap();
|
|
||||||
assert_eq!(account(&f), None);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn only_known_accounts_and_calls_are_assigned() {
|
|
||||||
let f = fixture();
|
|
||||||
let (id, _, _) = finished_call(&f, "a");
|
|
||||||
assert!(f.state.set_account(id, Some("mock-99")).is_err());
|
|
||||||
assert!(f.state.set_account(id + 1, Some("mock-1")).is_err());
|
|
||||||
assert_eq!(
|
|
||||||
f.state.store.get_call(id).unwrap().unwrap().account_id,
|
|
||||||
None
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn invalid_detection_delays_are_not_saved() {
|
fn invalid_detection_delays_are_not_saved() {
|
||||||
let f = fixture();
|
let f = fixture();
|
||||||
@@ -1290,6 +1442,223 @@ mod tests {
|
|||||||
assert_eq!(f.state.settings(), valid);
|
assert_eq!(f.state.settings(), valid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn new_key(key: &str) -> NewKey {
|
||||||
|
NewKey {
|
||||||
|
key: key.into(),
|
||||||
|
expires_at: Local.with_ymd_and_hms(2027, 11, 6, 10, 0, 0).unwrap(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const BASE: &str = crate::backend::BACKEND_URL;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_stored_backend_key_comes_with_its_login_and_server() {
|
||||||
|
let f = fixture();
|
||||||
|
assert_eq!(f.state.backend_key(), None);
|
||||||
|
|
||||||
|
f.state
|
||||||
|
.store_backend_key(
|
||||||
|
&new_key("euv_k"),
|
||||||
|
&format!("{BASE}/"),
|
||||||
|
Some("hinrichs".into()),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let expires_at = Local.with_ymd_and_hms(2027, 11, 6, 10, 0, 0).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
f.state.backend_key(),
|
||||||
|
Some(StoredKey {
|
||||||
|
key: "euv_k".into(),
|
||||||
|
expires_at: Some(expires_at),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
let saved = Settings::load(&f.dir.path().join("settings.json"));
|
||||||
|
assert_eq!(saved.backend_username.as_deref(), Some("hinrichs"));
|
||||||
|
assert_eq!(saved.backend_key_expires_at, Some(expires_at));
|
||||||
|
assert_eq!(saved.backend_key_base_url.as_deref(), Some(BASE));
|
||||||
|
assert!(!fs::read_to_string(f.dir.path().join("settings.json"))
|
||||||
|
.unwrap()
|
||||||
|
.contains("euv_k"));
|
||||||
|
assert_eq!(f.state.settings(), saved);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_key_of_another_server_is_not_stored() {
|
||||||
|
let f = fixture();
|
||||||
|
|
||||||
|
let err = f
|
||||||
|
.state
|
||||||
|
.store_backend_key(&new_key("euv_k"), "https://other.example", None)
|
||||||
|
.unwrap_err();
|
||||||
|
|
||||||
|
assert!(err.contains("anderen Server"), "{err}");
|
||||||
|
assert_eq!(f.state.secrets.get(Service::Backend), None);
|
||||||
|
assert_eq!(f.state.settings(), Settings::default());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_stored_key_of_another_server_is_discarded_before_use() {
|
||||||
|
for recorded in [Some("https://other.example"), None] {
|
||||||
|
let f = fixture();
|
||||||
|
f.state
|
||||||
|
.store_backend_key(&new_key("euv_k"), BASE, Some("hinrichs".into()))
|
||||||
|
.unwrap();
|
||||||
|
// As if stored by a build for another backend.
|
||||||
|
f.state
|
||||||
|
.update_settings(|s| s.backend_key_base_url = recorded.map(str::to_string))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(f.state.backend_key(), None, "{recorded:?}");
|
||||||
|
|
||||||
|
assert_eq!(f.state.secrets.get(Service::Backend), None);
|
||||||
|
let settings = f.state.settings();
|
||||||
|
assert_eq!(settings.backend_username, None);
|
||||||
|
assert_eq!(settings.backend_key_expires_at, None);
|
||||||
|
assert_eq!(settings.backend_key_base_url, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_backend_login_is_refreshed_from_the_key_info() {
|
||||||
|
let f = fixture();
|
||||||
|
f.state
|
||||||
|
.store_backend_key(&new_key("euv_k"), BASE, None)
|
||||||
|
.unwrap();
|
||||||
|
let later = Local.with_ymd_and_hms(2028, 1, 1, 0, 0, 0).unwrap();
|
||||||
|
|
||||||
|
f.state
|
||||||
|
.refresh_backend_login(&KeyInfo {
|
||||||
|
label: "l".into(),
|
||||||
|
hint: "h".into(),
|
||||||
|
username: "hinrichs".into(),
|
||||||
|
created_at: later,
|
||||||
|
expires_at: later,
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let settings = f.state.settings();
|
||||||
|
assert_eq!(settings.backend_username.as_deref(), Some("hinrichs"));
|
||||||
|
assert_eq!(settings.backend_key_expires_at, Some(later));
|
||||||
|
assert_eq!(settings.backend_key_base_url.as_deref(), Some(BASE));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_discarded_backend_key_is_gone_with_its_login() {
|
||||||
|
let f = fixture();
|
||||||
|
f.state
|
||||||
|
.store_backend_key(&new_key("euv_k"), BASE, Some("hinrichs".into()))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
f.state.discard_backend_key().unwrap();
|
||||||
|
|
||||||
|
assert_eq!(f.state.backend_key(), None);
|
||||||
|
assert_eq!(f.state.secrets.get(Service::Backend), None);
|
||||||
|
let settings = f.state.settings();
|
||||||
|
assert_eq!(settings.backend_username, None);
|
||||||
|
assert_eq!(settings.backend_key_expires_at, None);
|
||||||
|
assert_eq!(settings.backend_key_base_url, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_the_refused_key_is_discarded() {
|
||||||
|
let f = fixture();
|
||||||
|
f.state
|
||||||
|
.store_backend_key(&new_key("euv_new"), BASE, None)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// A login stored a new key after the old one was refused.
|
||||||
|
assert_eq!(f.state.discard_refused_backend_key("euv_old"), Ok(false));
|
||||||
|
assert_eq!(
|
||||||
|
f.state.backend_key().map(|k| k.key).as_deref(),
|
||||||
|
Some("euv_new")
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(f.state.discard_refused_backend_key("euv_new"), Ok(true));
|
||||||
|
assert_eq!(f.state.backend_key(), None);
|
||||||
|
assert_eq!(f.state.settings().backend_key_base_url, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn saving_settings_keeps_the_backend_login() {
|
||||||
|
let f = fixture();
|
||||||
|
f.state
|
||||||
|
.store_backend_key(&new_key("euv_k"), BASE, Some("hinrichs".into()))
|
||||||
|
.unwrap();
|
||||||
|
// The settings page sends what it loaded, maybe before the login.
|
||||||
|
let edited = Settings {
|
||||||
|
retention_days: 14,
|
||||||
|
..Settings::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(f.state.save_settings(edited), Ok(()));
|
||||||
|
|
||||||
|
assert!(f.state.backend_key().is_some());
|
||||||
|
let settings = f.state.settings();
|
||||||
|
assert_eq!(settings.backend_username.as_deref(), Some("hinrichs"));
|
||||||
|
assert_eq!(settings.backend_key_base_url.as_deref(), Some(BASE));
|
||||||
|
assert_eq!(settings.retention_days, 14);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_backend_is_fixed_per_build() {
|
||||||
|
let f = fixture();
|
||||||
|
assert_eq!(f.state.backend_url(), "https://test.euvinopro.eu");
|
||||||
|
assert_eq!(
|
||||||
|
f.state.backend_client().login_url(),
|
||||||
|
"https://test.euvinopro.eu/euvadm"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_call_is_uploaded_once_at_a_time() {
|
||||||
|
let f = fixture();
|
||||||
|
let (id, _, _) = finished_call(&f, "a");
|
||||||
|
let (other, _, _) = finished_call(&f, "b");
|
||||||
|
assert!(!f.state.call_detail(id).unwrap().uploading);
|
||||||
|
|
||||||
|
let claim = f.state.claim_upload(id).unwrap();
|
||||||
|
assert!(f.state.is_uploading(id));
|
||||||
|
assert!(f.state.call_detail(id).unwrap().uploading);
|
||||||
|
assert_eq!(
|
||||||
|
f.state.claim_upload(id).err(),
|
||||||
|
Some("Wird bereits hochgeladen".to_string())
|
||||||
|
);
|
||||||
|
assert!(f.state.claim_upload(other).is_ok(), "other calls are free");
|
||||||
|
|
||||||
|
drop(claim);
|
||||||
|
assert!(!f.state.is_uploading(id));
|
||||||
|
assert!(f.state.claim_upload(id).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_call_already_uploaded_is_not_claimed_again() {
|
||||||
|
let f = fixture();
|
||||||
|
let (id, _, _) = finished_call(&f, "a");
|
||||||
|
f.state.mark_uploaded(id, "4711").unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
f.state.claim_upload(id).err(),
|
||||||
|
Some("Bereits hochgeladen".to_string())
|
||||||
|
);
|
||||||
|
assert!(!f.state.is_uploading(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_upload_is_recorded_on_the_call() {
|
||||||
|
let f = fixture();
|
||||||
|
let (id, _, _) = finished_call(&f, "a");
|
||||||
|
|
||||||
|
f.state.mark_uploaded(id, "4711").unwrap();
|
||||||
|
|
||||||
|
let call = f.state.store.get_call(id).unwrap().unwrap();
|
||||||
|
assert_eq!(call.crm_transcript_id.as_deref(), Some("4711"));
|
||||||
|
assert!(call.uploaded_at.is_some());
|
||||||
|
assert_eq!(
|
||||||
|
f.state.mark_uploaded(id + 1, "1"),
|
||||||
|
Err("Gespräch nicht gefunden".to_string())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
fn render_session(exe: &str, root_pid: u32, device: &str) -> RenderSession {
|
fn render_session(exe: &str, root_pid: u32, device: &str) -> RenderSession {
|
||||||
RenderSession {
|
RenderSession {
|
||||||
exe: exe.to_string(),
|
exe: exe.to_string(),
|
||||||
|
|||||||
+156
-21
@@ -2,10 +2,15 @@
|
|||||||
//! in `tauri.conf.json`) at startup and every 6 h (sooner after a failed
|
//! in `tauri.conf.json`) at startup and every 6 h (sooner after a failed
|
||||||
//! check), tells the main window about a newer version and installs it when
|
//! check), tells the main window about a newer version and installs it when
|
||||||
//! the user asks, but never while a recording runs or a call is being
|
//! the user asks, but never while a recording runs or a call is being
|
||||||
//! processed.
|
//! processed. The settings' "Nach Updates suchen" button
|
||||||
|
//! ([`check_for_update_now`]) runs the very same check immediately, counts
|
||||||
|
//! as an attempt for the same scheduler ([`UpdateSchedule`]) and never runs
|
||||||
|
//! at the same time as the background loop.
|
||||||
//!
|
//!
|
||||||
//! On Windows the NSIS installer runs in passive mode for the current user
|
//! On Windows the NSIS installer runs in passive mode for the current user
|
||||||
//! (no admin rights) and restarts the app; installing ends this process.
|
//! (no admin rights) and restarts the app; installing ends this process.
|
||||||
|
//! Debian builds never self-update; a manual check still asks the feed
|
||||||
|
//! there (see [`can_self_update`]).
|
||||||
|
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
@@ -58,6 +63,71 @@ pub struct UpdateInfo {
|
|||||||
pub can_install: bool,
|
pub can_install: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Answer of `check_for_update_now`: what a check (background or manual)
|
||||||
|
/// found. `Available` 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.
|
||||||
|
#[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: 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 {
|
||||||
|
let _serialize = self.running.lock().await;
|
||||||
|
let now = SystemTime::now();
|
||||||
|
let result = check(app).await;
|
||||||
|
self.record(now, !matches!(result, UpdateCheckResult::Error { .. }));
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Payload of `update-progress`.
|
/// Payload of `update-progress`.
|
||||||
#[derive(Serialize, Clone, Debug, PartialEq)]
|
#[derive(Serialize, Clone, Debug, PartialEq)]
|
||||||
pub struct Progress {
|
pub struct Progress {
|
||||||
@@ -67,27 +137,19 @@ pub struct Progress {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Starts the periodic update check. Only on Windows: Debian builds do not
|
/// Starts the periodic update check. Only on Windows: Debian builds do not
|
||||||
/// update themselves.
|
/// update themselves (a manual check from the settings still asks the feed
|
||||||
|
/// on Linux, see `check_for_update_now`).
|
||||||
pub fn spawn(app: AppHandle) {
|
pub fn spawn(app: AppHandle) {
|
||||||
if !cfg!(windows) {
|
if !cfg!(windows) {
|
||||||
log::info!("update check disabled on this platform");
|
log::info!("update check disabled on this platform");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
thread::spawn(move || {
|
thread::spawn(move || loop {
|
||||||
let mut last_attempt = None;
|
|
||||||
let mut failures = 0;
|
|
||||||
loop {
|
|
||||||
let now = SystemTime::now();
|
let now = SystemTime::now();
|
||||||
if check_due(last_attempt, failures, now) {
|
if app.state::<UpdateSchedule>().is_due(now) {
|
||||||
last_attempt = Some(now);
|
tauri::async_runtime::block_on(app.state::<UpdateSchedule>().run(&app));
|
||||||
if tauri::async_runtime::block_on(check(&app)) {
|
|
||||||
failures = 0;
|
|
||||||
} else {
|
|
||||||
failures = failures.saturating_add(1);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
thread::sleep(WAKE_INTERVAL);
|
thread::sleep(WAKE_INTERVAL);
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,9 +172,11 @@ fn check_due(last_attempt: Option<SystemTime>, failures: u32, now: SystemTime) -
|
|||||||
.map_or(true, |elapsed| elapsed >= wait)
|
.map_or(true, |elapsed| elapsed >= wait)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Asks the release feed for a newer version; `false` if the check failed.
|
/// Asks the release feed for a newer version: the one implementation the
|
||||||
/// Failures (offline, no release yet) are expected and only logged.
|
/// background loop and a manual check (`check_for_update_now`) both run.
|
||||||
async fn check(app: &AppHandle) -> bool {
|
/// A failed check (offline, no release yet) is expected; only logged here,
|
||||||
|
/// and shown to the user only by a manual check (via the returned message).
|
||||||
|
async fn check(app: &AppHandle) -> UpdateCheckResult {
|
||||||
let result = match app.updater_builder().timeout(CHECK_TIMEOUT).build() {
|
let result = match app.updater_builder().timeout(CHECK_TIMEOUT).build() {
|
||||||
Ok(updater) => updater.check().await,
|
Ok(updater) => updater.check().await,
|
||||||
Err(e) => Err(e),
|
Err(e) => Err(e),
|
||||||
@@ -122,16 +186,18 @@ async fn check(app: &AppHandle) -> bool {
|
|||||||
log::info!("update available: {}", update.version);
|
log::info!("update available: {}", update.version);
|
||||||
let version = update.version.clone();
|
let version = update.version.clone();
|
||||||
*lock(&app.state::<PendingUpdate>().update) = Some(update);
|
*lock(&app.state::<PendingUpdate>().update) = Some(update);
|
||||||
let _ = app.emit("update-available", info(app, version));
|
let _ = app.emit("update-available", info(app, version.clone()));
|
||||||
true
|
UpdateCheckResult::Available { version }
|
||||||
}
|
}
|
||||||
Ok(None) => {
|
Ok(None) => {
|
||||||
log::info!("no update available");
|
log::info!("no update available");
|
||||||
true
|
UpdateCheckResult::None
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
log::info!("update check failed: {e}");
|
log::info!("update check failed: {e}");
|
||||||
false
|
UpdateCheckResult::Error {
|
||||||
|
message: format!("Update-Server nicht erreichbar: {e}"),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -161,6 +227,24 @@ fn info(app: &AppHandle, version: String) -> UpdateInfo {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// "Nach Updates suchen" in the settings: runs the same check as the
|
||||||
|
/// background loop, immediately, reusing its scheduling (a success resets
|
||||||
|
/// the 6 h interval and the failure count, same as a background success)
|
||||||
|
/// and never running at the same time as a background check. Works on
|
||||||
|
/// every platform; see `can_self_update` for whether this build can then
|
||||||
|
/// install what it finds.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn check_for_update_now(app: AppHandle) -> UpdateCheckResult {
|
||||||
|
app.state::<UpdateSchedule>().run(&app).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether this build can install an update itself (Windows only: Debian
|
||||||
|
/// builds ship a `.deb` and never self-update, see `spawn`).
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn can_self_update() -> bool {
|
||||||
|
cfg!(windows)
|
||||||
|
}
|
||||||
|
|
||||||
/// The update found by the last check, if any.
|
/// The update found by the last check, if any.
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn get_update(app: AppHandle) -> Option<UpdateInfo> {
|
pub fn get_update(app: AppHandle) -> Option<UpdateInfo> {
|
||||||
@@ -350,4 +434,55 @@ mod tests {
|
|||||||
let reports = reported(&mut meter, &[half, half, half, half, half], None);
|
let reports = reported(&mut meter, &[half, half, half, half, half], None);
|
||||||
assert_eq!(reports, [MIB / 2, MIB, 2 * MIB]);
|
assert_eq!(reports, [MIB / 2, MIB, 2 * MIB]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn update_check_result_maps_to_a_tagged_status() {
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(UpdateCheckResult::None).unwrap(),
|
||||||
|
serde_json::json!({"status": "none"})
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(UpdateCheckResult::Available {
|
||||||
|
version: "0.3.0".into()
|
||||||
|
})
|
||||||
|
.unwrap(),
|
||||||
|
serde_json::json!({"status": "available", "version": "0.3.0"})
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(UpdateCheckResult::Error {
|
||||||
|
message: "Update-Server nicht erreichbar: x".into()
|
||||||
|
})
|
||||||
|
.unwrap(),
|
||||||
|
serde_json::json!({"status": "error", "message": "Update-Server nicht erreichbar: x"})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "Gesprächsrekorder",
|
"productName": "Gesprächsrekorder",
|
||||||
"version": "0.1.1",
|
"version": "0.2.1",
|
||||||
"identifier": "eu.euvino.callrecorder",
|
"identifier": "eu.euvino.callrecorder",
|
||||||
"build": {
|
"build": {
|
||||||
"frontendDist": "../ui/dist",
|
"frontendDist": "../ui/dist",
|
||||||
@@ -51,8 +51,7 @@
|
|||||||
"active": true,
|
"active": true,
|
||||||
"targets": [
|
"targets": [
|
||||||
"nsis",
|
"nsis",
|
||||||
"deb",
|
"deb"
|
||||||
"appimage"
|
|
||||||
],
|
],
|
||||||
"icon": [
|
"icon": [
|
||||||
"icons/32x32.png",
|
"icons/32x32.png",
|
||||||
@@ -72,7 +71,6 @@
|
|||||||
"updater": {
|
"updater": {
|
||||||
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDIwM0EzNUEyMTUwOThERUQKUldUdGpRa1ZvalU2SVBtYVZRaWlWMVBCNzFTd1BRbmtmdU9sZXMrVTltckNiYlRSSmZHcWpNMHUK",
|
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDIwM0EzNUEyMTUwOThERUQKUldUdGpRa1ZvalU2SVBtYVZRaWlWMVBCNzFTd1BRbmtmdU9sZXMrVTltckNiYlRSSmZHcWpNMHUK",
|
||||||
"endpoints": [
|
"endpoints": [
|
||||||
"https://gitea.euvino.eu/public/call-recorder/releases/latest/download/latest.json",
|
|
||||||
"https://gitea.euvino.eu/public/call-recorder/raw/branch/master/latest.json"
|
"https://gitea.euvino.eu/public/call-recorder/raw/branch/master/latest.json"
|
||||||
],
|
],
|
||||||
"windows": {
|
"windows": {
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "ui",
|
"name": "ui",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.1.1",
|
"version": "0.2.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
@@ -8,6 +8,8 @@
|
|||||||
onRecordingState,
|
onRecordingState,
|
||||||
onUpdateAvailable,
|
onUpdateAvailable,
|
||||||
onUpdateProgress,
|
onUpdateProgress,
|
||||||
|
updateProgressText,
|
||||||
|
UPDATE_BUSY_HINT,
|
||||||
type UpdateInfo,
|
type UpdateInfo,
|
||||||
type UpdateProgress,
|
type UpdateProgress,
|
||||||
} from './api'
|
} from './api'
|
||||||
@@ -62,16 +64,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function megabytes(bytes: number): string {
|
let progressText = $derived(updateProgressText(progress))
|
||||||
return (bytes / 1024 / 1024).toLocaleString('de-DE', { maximumFractionDigits: 1 }) + ' MB'
|
|
||||||
}
|
|
||||||
|
|
||||||
let progressText = $derived.by(() => {
|
|
||||||
if (!progress) return 'Update wird heruntergeladen…'
|
|
||||||
if (progress.total === null) return `Update wird heruntergeladen… ${megabytes(progress.downloaded)}`
|
|
||||||
if (progress.downloaded >= progress.total) return 'Update wird installiert…'
|
|
||||||
return `Update wird heruntergeladen… ${Math.floor((progress.downloaded * 100) / progress.total)} %`
|
|
||||||
})
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if update}
|
{#if update}
|
||||||
@@ -84,7 +77,7 @@
|
|||||||
Installieren & neu starten
|
Installieren & neu starten
|
||||||
</button>
|
</button>
|
||||||
{#if !update.can_install}
|
{#if !update.can_install}
|
||||||
<span class="hint">Nach der laufenden Aufnahme/Verarbeitung möglich</span>
|
<span class="hint">{UPDATE_BUSY_HINT}</span>
|
||||||
{/if}
|
{/if}
|
||||||
{/if}
|
{/if}
|
||||||
{#if error}
|
{#if error}
|
||||||
|
|||||||
+76
-10
@@ -15,9 +15,32 @@ export interface Settings {
|
|||||||
autostart: boolean
|
autostart: boolean
|
||||||
start_after_secs: number
|
start_after_secs: number
|
||||||
end_after_secs: number
|
end_after_secs: number
|
||||||
|
/** Whose backend key is stored; set by the app at login. */
|
||||||
|
backend_username: string | null
|
||||||
|
/** When the stored backend key expires (RFC 3339); set by the app. */
|
||||||
|
backend_key_expires_at: string | null
|
||||||
|
/** The backend the stored key belongs to; set by the app. */
|
||||||
|
backend_key_base_url: string | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export type Service = 'deepscript' | 'anthropic'
|
/** The backend this build talks to (fixed per build, not a setting). */
|
||||||
|
export interface BackendServer {
|
||||||
|
base_url: string
|
||||||
|
/** Where the admin manages their keys. */
|
||||||
|
keys_url: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Login status for the settings, checked with the backend. */
|
||||||
|
export interface BackendStatus {
|
||||||
|
logged_in: boolean
|
||||||
|
username: string | null
|
||||||
|
/** RFC 3339. */
|
||||||
|
expires_at: string | null
|
||||||
|
/** `false` if the key could not be checked; username and expiry are then the stored ones. */
|
||||||
|
reachable: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Service = 'deepscript'
|
||||||
|
|
||||||
export interface DeviceInfo {
|
export interface DeviceInfo {
|
||||||
id: string
|
id: string
|
||||||
@@ -67,6 +90,10 @@ export interface CallListItem {
|
|||||||
interrupted: boolean
|
interrupted: boolean
|
||||||
/** The name the user gave the call, if any. */
|
/** The name the user gave the call, if any. */
|
||||||
title: string | null
|
title: string | null
|
||||||
|
/** The CRM's id of the transcript, from its last upload. */
|
||||||
|
crm_transcript_id: string | null
|
||||||
|
/** When the transcript was last uploaded (RFC 3339). */
|
||||||
|
uploaded_at: string | null
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A transcript line; `speaker_key` is "me" or "remote:<n>". */
|
/** A transcript line; `speaker_key` is "me" or "remote:<n>". */
|
||||||
@@ -87,17 +114,14 @@ export interface SpeakerMerge {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface CallDetail {
|
export interface CallDetail {
|
||||||
call: CallListItem & { error: string | null; account_id: string | null }
|
call: CallListItem & { error: string | null; transcribed_at: string | null }
|
||||||
/** The transcript with speaker merges applied. */
|
/** The transcript with speaker merges applied. */
|
||||||
segments: SegmentView[]
|
segments: SegmentView[]
|
||||||
/** Renamed speakers by key. */
|
/** Renamed speakers by key. */
|
||||||
speaker_names: Record<string, string>
|
speaker_names: Record<string, string>
|
||||||
merges: SpeakerMerge[]
|
merges: SpeakerMerge[]
|
||||||
}
|
/** The transcript is being uploaded right now. */
|
||||||
|
uploading: boolean
|
||||||
export interface Account {
|
|
||||||
id: string
|
|
||||||
name: string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A newer version the release feed offers. */
|
/** A newer version the release feed offers. */
|
||||||
@@ -113,6 +137,15 @@ export interface UpdateProgress {
|
|||||||
total: number | null
|
total: number | null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Why the install button is disabled, shown next to it as a hint. */
|
||||||
|
export const UPDATE_BUSY_HINT = 'Nach der laufenden Aufnahme/Verarbeitung möglich'
|
||||||
|
|
||||||
|
/** What a check (background or manual) found. */
|
||||||
|
export type UpdateCheckResult =
|
||||||
|
| { status: 'none' }
|
||||||
|
| { status: 'available'; version: string }
|
||||||
|
| { status: 'error'; message: string }
|
||||||
|
|
||||||
export interface Levels {
|
export interface Levels {
|
||||||
mic: number
|
mic: number
|
||||||
out: number
|
out: number
|
||||||
@@ -149,12 +182,26 @@ export const unmergeSpeaker = (id: CallId, fromKey: string) =>
|
|||||||
/** `null` or an empty title restores the default heading. */
|
/** `null` or an empty title restores the default heading. */
|
||||||
export const renameCall = (id: CallId, title: string | null) =>
|
export const renameCall = (id: CallId, title: string | null) =>
|
||||||
invoke<void>('rename_call', { id, title })
|
invoke<void>('rename_call', { id, title })
|
||||||
export const listAccounts = () => invoke<Account[]>('list_accounts')
|
export const backendServer = () => invoke<BackendServer>('backend_server')
|
||||||
export const setAccount = (id: CallId, accountId: string | null) =>
|
export const backendStatus = () => invoke<BackendStatus>('backend_status')
|
||||||
invoke<void>('set_account', { id, accountId })
|
/** Resolves once the login window created a key; rejects if it was closed or failed. */
|
||||||
|
export const backendLogin = () => invoke<void>('backend_login')
|
||||||
|
export const backendLogout = () => invoke<void>('backend_logout')
|
||||||
|
/** Opens the backend's key management page in the system browser. */
|
||||||
|
export const openBackendKeysPage = () => invoke<void>('open_backend_keys_page')
|
||||||
|
/** Logs in first if needed; resolves once the CRM has the transcript. */
|
||||||
|
export const uploadTranscript = (id: CallId) => invoke<void>('upload_transcript', { id })
|
||||||
export const getUpdate = () => invoke<UpdateInfo | null>('get_update')
|
export const getUpdate = () => invoke<UpdateInfo | null>('get_update')
|
||||||
/** Resolves only on failure: on success the app restarts. */
|
/** Resolves only on failure: on success the app restarts. */
|
||||||
export const installUpdate = () => invoke<void>('install_update')
|
export const installUpdate = () => invoke<void>('install_update')
|
||||||
|
/** This build's own version, for the settings' "Updates" section. */
|
||||||
|
export const getAppVersion = () => invoke<string>('get_app_version')
|
||||||
|
/** Whether this build can install an update itself (Windows only). */
|
||||||
|
export const canSelfUpdate = () => invoke<boolean>('can_self_update')
|
||||||
|
/** "Nach Updates suchen": runs the same check as the background loop,
|
||||||
|
* immediately. An `available` result leaves the same state `getUpdate`
|
||||||
|
* reads, so the main window's banner shows it too. */
|
||||||
|
export const checkForUpdateNow = () => invoke<UpdateCheckResult>('check_for_update_now')
|
||||||
|
|
||||||
export const onRecordingState = (handler: (state: RecordingState) => void): Promise<UnlistenFn> =>
|
export const onRecordingState = (handler: (state: RecordingState) => void): Promise<UnlistenFn> =>
|
||||||
listen<RecordingState>('recording-state', (event) => handler(event.payload))
|
listen<RecordingState>('recording-state', (event) => handler(event.payload))
|
||||||
@@ -166,6 +213,12 @@ export const onPromptChanged = (handler: () => void): Promise<UnlistenFn> =>
|
|||||||
/** A call's status changed (processing started, done or failed). */
|
/** A call's status changed (processing started, done or failed). */
|
||||||
export const onCallUpdated = (handler: (id: CallId) => void): Promise<UnlistenFn> =>
|
export const onCallUpdated = (handler: (id: CallId) => void): Promise<UnlistenFn> =>
|
||||||
listen<{ id: CallId }>('call-updated', (event) => handler(event.payload.id))
|
listen<{ id: CallId }>('call-updated', (event) => handler(event.payload.id))
|
||||||
|
/** The backend login changed (logged in, logged out, key discarded). */
|
||||||
|
export const onBackendChanged = (handler: () => void): Promise<UnlistenFn> =>
|
||||||
|
listen<null>('backend-changed', () => handler())
|
||||||
|
/** Creating the key failed; the login window stays open for another try. */
|
||||||
|
export const onBackendLoginError = (handler: (message: string) => void): Promise<UnlistenFn> =>
|
||||||
|
listen<{ message: string }>('backend-login-error', (event) => handler(event.payload.message))
|
||||||
export const onUpdateAvailable = (handler: (info: UpdateInfo) => void): Promise<UnlistenFn> =>
|
export const onUpdateAvailable = (handler: (info: UpdateInfo) => void): Promise<UnlistenFn> =>
|
||||||
listen<UpdateInfo>('update-available', (event) => handler(event.payload))
|
listen<UpdateInfo>('update-available', (event) => handler(event.payload))
|
||||||
export const onUpdateProgress = (
|
export const onUpdateProgress = (
|
||||||
@@ -182,6 +235,19 @@ export function meterFill(level: number): number {
|
|||||||
return Math.min(1, Math.max(0, (db + 60) / 60))
|
return Math.min(1, Math.max(0, (db + 60) / 60))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function megabytes(bytes: number): string {
|
||||||
|
return (bytes / 1024 / 1024).toLocaleString('de-DE', { maximumFractionDigits: 1 }) + ' MB'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Text shown while an update installs (the banner and the settings'
|
||||||
|
* Updates section share this). */
|
||||||
|
export function updateProgressText(progress: UpdateProgress | null): string {
|
||||||
|
if (!progress) return 'Update wird heruntergeladen…'
|
||||||
|
if (progress.total === null) return `Update wird heruntergeladen… ${megabytes(progress.downloaded)}`
|
||||||
|
if (progress.downloaded >= progress.total) return 'Update wird installiert…'
|
||||||
|
return `Update wird heruntergeladen… ${Math.floor((progress.downloaded * 100) / progress.total)} %`
|
||||||
|
}
|
||||||
|
|
||||||
/** Error text of a rejected command. */
|
/** Error text of a rejected command. */
|
||||||
export function errorText(err: unknown): string {
|
export function errorText(err: unknown): string {
|
||||||
return typeof err === 'string' ? err : err instanceof Error ? err.message : String(err)
|
return typeof err === 'string' ? err : err instanceof Error ? err.message : String(err)
|
||||||
|
|||||||
@@ -53,3 +53,14 @@ export function formatOffset(secs: number): string {
|
|||||||
const ss = pad(total % 60)
|
const ss = pad(total % 60)
|
||||||
return h > 0 ? `${h}:${mm}:${ss}` : `${mm}:${ss}`
|
return h > 0 ? `${h}:${mm}:${ss}` : `${mm}:${ss}`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** "06.11.2027". */
|
||||||
|
export function formatDate(iso: string): string {
|
||||||
|
const d = new Date(iso)
|
||||||
|
return `${pad(d.getDate())}.${pad(d.getMonth() + 1)}.${d.getFullYear()}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "06.11.2026 14:05". */
|
||||||
|
export function formatDateTime(iso: string): string {
|
||||||
|
return `${formatDate(iso)} ${clock(new Date(iso))}`
|
||||||
|
}
|
||||||
|
|||||||
+54
-95
@@ -5,9 +5,9 @@
|
|||||||
errorText,
|
errorText,
|
||||||
getCall,
|
getCall,
|
||||||
getRecordingState,
|
getRecordingState,
|
||||||
listAccounts,
|
|
||||||
listCalls,
|
listCalls,
|
||||||
mergeSpeakers,
|
mergeSpeakers,
|
||||||
|
onBackendLoginError,
|
||||||
onCallEnded,
|
onCallEnded,
|
||||||
onCallUpdated,
|
onCallUpdated,
|
||||||
onPromptChanged,
|
onPromptChanged,
|
||||||
@@ -15,19 +15,18 @@
|
|||||||
renameCall,
|
renameCall,
|
||||||
renameSpeaker,
|
renameSpeaker,
|
||||||
retryCall,
|
retryCall,
|
||||||
setAccount,
|
|
||||||
showRecorder,
|
showRecorder,
|
||||||
startManualRecording,
|
startManualRecording,
|
||||||
transcribeCall,
|
transcribeCall,
|
||||||
unmergeSpeaker,
|
unmergeSpeaker,
|
||||||
type Account,
|
uploadTranscript,
|
||||||
type CallDetail,
|
type CallDetail,
|
||||||
type CallId,
|
type CallId,
|
||||||
type CallListItem,
|
type CallListItem,
|
||||||
type RecordingState,
|
type RecordingState,
|
||||||
} from '../lib/api'
|
} from '../lib/api'
|
||||||
import CallList from '../lib/CallList.svelte'
|
import CallList from '../lib/CallList.svelte'
|
||||||
import { formatDetailTime, formatMinutes } from '../lib/format'
|
import { formatDateTime, formatDetailTime, formatMinutes } from '../lib/format'
|
||||||
import StatusPill from '../lib/StatusPill.svelte'
|
import StatusPill from '../lib/StatusPill.svelte'
|
||||||
import TranscriptView from '../lib/TranscriptView.svelte'
|
import TranscriptView from '../lib/TranscriptView.svelte'
|
||||||
import UpdateBanner from '../lib/UpdateBanner.svelte'
|
import UpdateBanner from '../lib/UpdateBanner.svelte'
|
||||||
@@ -35,7 +34,6 @@
|
|||||||
let calls = $state<CallListItem[]>([])
|
let calls = $state<CallListItem[]>([])
|
||||||
let loaded = $state(false)
|
let loaded = $state(false)
|
||||||
let listError = $state('')
|
let listError = $state('')
|
||||||
let accounts = $state<Account[]>([])
|
|
||||||
|
|
||||||
let recordingState = $state<RecordingState>({ state: 'idle' })
|
let recordingState = $state<RecordingState>({ state: 'idle' })
|
||||||
let recordBusy = $state(false)
|
let recordBusy = $state(false)
|
||||||
@@ -46,7 +44,11 @@
|
|||||||
let detailError = $state('')
|
let detailError = $state('')
|
||||||
let actionError = $state('')
|
let actionError = $state('')
|
||||||
let busy = $state(false)
|
let busy = $state(false)
|
||||||
let tab = $state<'summary' | 'transcript'>('transcript')
|
|
||||||
|
// Uploads run per call and may outlive the selection (the login can
|
||||||
|
// take a while); their errors are kept per call too.
|
||||||
|
let uploading = $state<CallId[]>([])
|
||||||
|
let uploadErrors = $state<Record<CallId, string>>({})
|
||||||
|
|
||||||
let editingTitle = $state(false)
|
let editingTitle = $state(false)
|
||||||
let titleDraft = $state('')
|
let titleDraft = $state('')
|
||||||
@@ -122,6 +124,10 @@
|
|||||||
if (id === selectedId) refreshDetail()
|
if (id === selectedId) refreshDetail()
|
||||||
}),
|
}),
|
||||||
onCallEnded(refreshList),
|
onCallEnded(refreshList),
|
||||||
|
// Creating the key failed; the login window stays open for another try.
|
||||||
|
onBackendLoginError((msg) => {
|
||||||
|
for (const id of uploading) uploadErrors[id] = msg
|
||||||
|
}),
|
||||||
onPromptChanged(refreshList),
|
onPromptChanged(refreshList),
|
||||||
onRecordingState((state) => {
|
onRecordingState((state) => {
|
||||||
recordingState = state
|
recordingState = state
|
||||||
@@ -132,9 +138,6 @@
|
|||||||
getRecordingState()
|
getRecordingState()
|
||||||
.then((state) => (recordingState = state))
|
.then((state) => (recordingState = state))
|
||||||
.catch((err) => (recordError = errorText(err)))
|
.catch((err) => (recordError = errorText(err)))
|
||||||
listAccounts()
|
|
||||||
.then((list) => (accounts = list))
|
|
||||||
.catch((err) => (listError = errorText(err)))
|
|
||||||
return () => unlisten.forEach((u) => u.then((off) => off()))
|
return () => unlisten.forEach((u) => u.then((off) => off()))
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -186,18 +189,23 @@
|
|||||||
refreshList()
|
refreshList()
|
||||||
})
|
})
|
||||||
|
|
||||||
function changeAccount(event: Event) {
|
/** Uploads the shown call's transcript (logging in first if needed). A
|
||||||
const select = event.currentTarget as HTMLSelectElement
|
* call already uploaded has no button any more: the CRM never gets a
|
||||||
const previous = detail?.call.account_id ?? ''
|
* duplicate. */
|
||||||
run(async (id) => {
|
async function upload() {
|
||||||
|
if (!detail) return
|
||||||
|
const id = detail.call.id
|
||||||
|
if (uploading.includes(id)) return
|
||||||
|
uploading = [...uploading, id]
|
||||||
|
delete uploadErrors[id]
|
||||||
try {
|
try {
|
||||||
await setAccount(id, select.value || null)
|
await uploadTranscript(id)
|
||||||
|
delete uploadErrors[id]
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
select.value = previous
|
uploadErrors[id] = errorText(err)
|
||||||
throw err
|
} finally {
|
||||||
|
uploading = uploading.filter((u) => u !== id)
|
||||||
}
|
}
|
||||||
await refreshDetail()
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function rename(speakerKey: string, name: string) {
|
async function rename(speakerKey: string, name: string) {
|
||||||
@@ -256,12 +264,11 @@
|
|||||||
return parts.join(' · ')
|
return parts.join(' · ')
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The account list plus the stored account if it is no longer listed. */
|
// Also while an upload started elsewhere (e.g. before switching views)
|
||||||
let accountOptions = $derived.by(() => {
|
// still runs in the app.
|
||||||
const stored = detail?.call.account_id
|
let isUploading = $derived(
|
||||||
if (!stored || accounts.some((a) => a.id === stored)) return accounts
|
detail !== null && (uploading.includes(detail.call.id) || detail.uploading),
|
||||||
return [...accounts, { id: stored, name: `${stored} (unbekannt)` }]
|
)
|
||||||
})
|
|
||||||
|
|
||||||
// A failed start (e.g. missing key) also marks the call failed; its
|
// A failed start (e.g. missing key) also marks the call failed; its
|
||||||
// error is then shown once, in the failure box.
|
// error is then shown once, in the failure box.
|
||||||
@@ -332,15 +339,11 @@
|
|||||||
<p class="error">{titleError}</p>
|
<p class="error">{titleError}</p>
|
||||||
{/if}
|
{/if}
|
||||||
<div class="toolbar">
|
<div class="toolbar">
|
||||||
<label class="customer">
|
{#if call.status === 'done' && call.uploaded_at}
|
||||||
<span>Kunde:</span>
|
<span class="muted uploaded">
|
||||||
<select value={call.account_id ?? ''} disabled={busy} onchange={changeAccount}>
|
Hochgeladen am {formatDateTime(call.uploaded_at)} (ID {call.crm_transcript_id})
|
||||||
<option value="">— kein Kunde —</option>
|
</span>
|
||||||
{#each accountOptions as account (account.id)}
|
{/if}
|
||||||
<option value={account.id}>{account.name}</option>
|
|
||||||
{/each}
|
|
||||||
</select>
|
|
||||||
</label>
|
|
||||||
<span class="actions">
|
<span class="actions">
|
||||||
{#if call.status === 'awaiting_decision'}
|
{#if call.status === 'awaiting_decision'}
|
||||||
<button class="btn primary" disabled={busy} onclick={transcribe}>Transkribieren</button>
|
<button class="btn primary" disabled={busy} onclick={transcribe}>Transkribieren</button>
|
||||||
@@ -348,16 +351,24 @@
|
|||||||
{:else if call.status === 'failed'}
|
{:else if call.status === 'failed'}
|
||||||
<button class="btn primary" disabled={busy} onclick={retry}>Erneut versuchen</button>
|
<button class="btn primary" disabled={busy} onclick={retry}>Erneut versuchen</button>
|
||||||
<button class="btn danger" disabled={busy} onclick={discard}>Verwerfen</button>
|
<button class="btn danger" disabled={busy} onclick={discard}>Verwerfen</button>
|
||||||
{:else if call.status === 'done'}
|
{:else if call.status === 'done' && !call.uploaded_at}
|
||||||
<span title="Kommt in einer späteren Version">
|
<button
|
||||||
<button class="btn" disabled>In Kundenakte speichern</button>
|
class="btn primary"
|
||||||
</span>
|
disabled={!call.transcribed_at || isUploading}
|
||||||
|
title={call.transcribed_at ? 'Transkript ins CRM hochladen' : 'Noch kein Transkript'}
|
||||||
|
onclick={upload}
|
||||||
|
>
|
||||||
|
{isUploading ? 'wird hochgeladen…' : 'Transkript hochladen'}
|
||||||
|
</button>
|
||||||
{/if}
|
{/if}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
{#if shownActionError}
|
{#if shownActionError}
|
||||||
<p class="error">{shownActionError}</p>
|
<p class="error">{shownActionError}</p>
|
||||||
{/if}
|
{/if}
|
||||||
|
{#if uploadErrors[call.id]}
|
||||||
|
<p class="error">{uploadErrors[call.id]}</p>
|
||||||
|
{/if}
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<div class="body">
|
<div class="body">
|
||||||
@@ -376,24 +387,6 @@
|
|||||||
<strong>Verarbeitung fehlgeschlagen</strong>
|
<strong>Verarbeitung fehlgeschlagen</strong>
|
||||||
<div>{call.error ?? 'Unbekannter Fehler'}</div>
|
<div>{call.error ?? 'Unbekannter Fehler'}</div>
|
||||||
</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}
|
{:else}
|
||||||
<TranscriptView
|
<TranscriptView
|
||||||
segments={detail.segments}
|
segments={detail.segments}
|
||||||
@@ -404,8 +397,6 @@
|
|||||||
/>
|
/>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
{:else if detailError}
|
{:else if detailError}
|
||||||
<p class="error pad">{detailError}</p>
|
<p class="error pad">{detailError}</p>
|
||||||
{:else if loaded && selectedId === null && calls.length > 0}
|
{:else if loaded && selectedId === null && calls.length > 0}
|
||||||
@@ -552,23 +543,18 @@
|
|||||||
margin-top: 12px;
|
margin-top: 12px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.customer {
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 8px;
|
|
||||||
font-weight: 600;
|
|
||||||
}
|
|
||||||
|
|
||||||
.customer select {
|
|
||||||
max-width: 260px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.actions {
|
.actions {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
gap: 8px;
|
gap: 8px;
|
||||||
margin-left: auto;
|
margin-left: auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.uploaded {
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
.detail-header .error {
|
.detail-header .error {
|
||||||
margin: 10px 0 0;
|
margin: 10px 0 0;
|
||||||
}
|
}
|
||||||
@@ -588,31 +574,4 @@
|
|||||||
background: var(--rec-soft);
|
background: var(--rec-soft);
|
||||||
color: var(--rec);
|
color: var(--rec);
|
||||||
}
|
}
|
||||||
|
|
||||||
.tabs {
|
|
||||||
display: flex;
|
|
||||||
gap: 4px;
|
|
||||||
border-bottom: 1px solid var(--border);
|
|
||||||
}
|
|
||||||
|
|
||||||
.tabs button {
|
|
||||||
padding: 8px 14px;
|
|
||||||
border: none;
|
|
||||||
border-bottom: 2px solid transparent;
|
|
||||||
margin-bottom: -1px;
|
|
||||||
background: none;
|
|
||||||
font: inherit;
|
|
||||||
font-weight: 600;
|
|
||||||
color: var(--muted);
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
.tabs button.active {
|
|
||||||
color: var(--primary);
|
|
||||||
border-bottom-color: var(--primary);
|
|
||||||
}
|
|
||||||
|
|
||||||
.tab-panel {
|
|
||||||
padding-top: 14px;
|
|
||||||
}
|
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,37 +1,188 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { onMount } from 'svelte'
|
import { onMount } from 'svelte'
|
||||||
|
import { formatDate } from '../lib/format'
|
||||||
import {
|
import {
|
||||||
|
backendLogin,
|
||||||
|
backendLogout,
|
||||||
|
backendServer,
|
||||||
|
backendStatus,
|
||||||
|
canSelfUpdate,
|
||||||
|
checkForUpdateNow,
|
||||||
errorText,
|
errorText,
|
||||||
|
getAppVersion,
|
||||||
getSettings,
|
getSettings,
|
||||||
|
getUpdate,
|
||||||
hasApiKey,
|
hasApiKey,
|
||||||
|
installUpdate,
|
||||||
listDevices,
|
listDevices,
|
||||||
meterFill,
|
meterFill,
|
||||||
|
onBackendChanged,
|
||||||
|
onBackendLoginError,
|
||||||
|
onUpdateAvailable,
|
||||||
|
onUpdateProgress,
|
||||||
|
openBackendKeysPage,
|
||||||
saveSettings,
|
saveSettings,
|
||||||
setApiKey,
|
setApiKey,
|
||||||
testDevices,
|
testDevices,
|
||||||
|
updateProgressText,
|
||||||
|
UPDATE_BUSY_HINT,
|
||||||
|
type BackendServer,
|
||||||
|
type BackendStatus,
|
||||||
type DeviceInfo,
|
type DeviceInfo,
|
||||||
type DeviceLevels,
|
type DeviceLevels,
|
||||||
type Devices,
|
type Devices,
|
||||||
type Service,
|
type Service,
|
||||||
type Settings,
|
type Settings,
|
||||||
|
type UpdateCheckResult,
|
||||||
|
type UpdateInfo,
|
||||||
|
type UpdateProgress,
|
||||||
} from '../lib/api'
|
} from '../lib/api'
|
||||||
|
|
||||||
const services: { id: Service; name: string }[] = [
|
const services: { id: Service; name: string }[] = [
|
||||||
{ id: 'deepscript', name: 'DeepScript' },
|
{ id: 'deepscript', name: 'DeepScript' },
|
||||||
{ id: 'anthropic', name: 'Anthropic (Claude)' },
|
|
||||||
]
|
]
|
||||||
|
|
||||||
let settings = $state<Settings | null>(null)
|
let settings = $state<Settings | null>(null)
|
||||||
let devices = $state<Devices>({ inputs: [], outputs: [] })
|
let devices = $state<Devices>({ inputs: [], outputs: [] })
|
||||||
let keySaved = $state<Record<Service, boolean>>({ deepscript: false, anthropic: false })
|
let keySaved = $state<Record<Service, boolean>>({ deepscript: false })
|
||||||
let keyInput = $state<Record<Service, string>>({ deepscript: '', anthropic: '' })
|
let keyInput = $state<Record<Service, string>>({ deepscript: '' })
|
||||||
let newApp = $state('')
|
let newApp = $state('')
|
||||||
let testing = $state(false)
|
let testing = $state(false)
|
||||||
let testResult = $state<DeviceLevels | null>(null)
|
let testResult = $state<DeviceLevels | null>(null)
|
||||||
let message = $state('')
|
let message = $state('')
|
||||||
let error = $state('')
|
let error = $state('')
|
||||||
|
|
||||||
onMount(load)
|
let server = $state<BackendServer | null>(null)
|
||||||
|
let backend = $state<BackendStatus | null>(null)
|
||||||
|
let backendBusy = $state(false)
|
||||||
|
let backendError = $state('')
|
||||||
|
|
||||||
|
// Status answers can arrive out of order; only the newest is applied.
|
||||||
|
let statusRequest = 0
|
||||||
|
|
||||||
|
let appVersion = $state('')
|
||||||
|
/** `null` until known: whether this build can install an update itself
|
||||||
|
* (Windows only); avoids guessing wrong for an instant. */
|
||||||
|
let selfUpdateCapable = $state<boolean | null>(null)
|
||||||
|
let checking = $state(false)
|
||||||
|
let checkResult = $state<UpdateCheckResult | null>(null)
|
||||||
|
let pendingUpdate = $state<UpdateInfo | null>(null)
|
||||||
|
let installing = $state(false)
|
||||||
|
let installProgress = $state<UpdateProgress | null>(null)
|
||||||
|
let installError = $state('')
|
||||||
|
|
||||||
|
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), but is applied here as
|
||||||
|
* well in case that event is missed. */
|
||||||
|
async function checkUpdateNow() {
|
||||||
|
checking = true
|
||||||
|
checkResult = null
|
||||||
|
try {
|
||||||
|
const result = await checkForUpdateNow()
|
||||||
|
checkResult = result
|
||||||
|
if (result.status === 'available') pendingUpdate = await getUpdate()
|
||||||
|
} catch (err) {
|
||||||
|
checkResult = { status: 'error', message: errorText(err) }
|
||||||
|
} finally {
|
||||||
|
checking = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshPendingUpdate() {
|
||||||
|
try {
|
||||||
|
pendingUpdate = await getUpdate()
|
||||||
|
} catch {
|
||||||
|
// Optional refresh; the next event or check tries again.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "Installieren & neu starten" for the update found above; reuses the
|
||||||
|
* install command and guard the main window's banner uses. */
|
||||||
|
async function installUpdateNow() {
|
||||||
|
installing = true
|
||||||
|
installProgress = null
|
||||||
|
installError = ''
|
||||||
|
try {
|
||||||
|
// Returns only on failure: on success the app restarts.
|
||||||
|
await installUpdate()
|
||||||
|
} catch (err) {
|
||||||
|
installError = errorText(err)
|
||||||
|
refreshPendingUpdate()
|
||||||
|
} finally {
|
||||||
|
installing = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Checks the stored key with the backend. */
|
||||||
|
async function refreshBackend() {
|
||||||
|
const request = ++statusRequest
|
||||||
|
try {
|
||||||
|
const status = await backendStatus()
|
||||||
|
if (request === statusRequest) backend = status
|
||||||
|
} catch (err) {
|
||||||
|
if (request === statusRequest) backendError = errorText(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function login() {
|
||||||
|
backendBusy = true
|
||||||
|
backendError = ''
|
||||||
|
try {
|
||||||
|
await backendLogin()
|
||||||
|
} catch (err) {
|
||||||
|
backendError = errorText(err)
|
||||||
|
} finally {
|
||||||
|
backendBusy = false
|
||||||
|
refreshBackend()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function logout() {
|
||||||
|
backendBusy = true
|
||||||
|
backendError = ''
|
||||||
|
try {
|
||||||
|
await backendLogout()
|
||||||
|
} catch (err) {
|
||||||
|
backendError = errorText(err)
|
||||||
|
} finally {
|
||||||
|
backendBusy = false
|
||||||
|
refreshBackend()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openKeysPage(event: Event) {
|
||||||
|
event.preventDefault()
|
||||||
|
try {
|
||||||
|
await openBackendKeysPage()
|
||||||
|
} catch (err) {
|
||||||
|
backendError = errorText(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function load() {
|
async function load() {
|
||||||
try {
|
try {
|
||||||
@@ -146,6 +297,46 @@
|
|||||||
{/each}
|
{/each}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="card">
|
||||||
|
<h2>Backend</h2>
|
||||||
|
<div class="grid">
|
||||||
|
<span>Server</span>
|
||||||
|
<span>{server ? new URL(server.base_url).host : '…'}</span>
|
||||||
|
<span>Status</span>
|
||||||
|
<span class="backend-status">
|
||||||
|
{#if backend === null}
|
||||||
|
<span class="muted">wird geprüft …</span>
|
||||||
|
{:else if backend.logged_in}
|
||||||
|
{backend.username ? `Angemeldet als ${backend.username}` : 'Angemeldet'}{backend.expires_at
|
||||||
|
? `, gültig bis ${formatDate(backend.expires_at)}`
|
||||||
|
: ''}
|
||||||
|
{#if !backend.reachable}
|
||||||
|
<span class="muted">(Backend nicht erreichbar)</span>
|
||||||
|
{/if}
|
||||||
|
{:else}
|
||||||
|
Nicht angemeldet
|
||||||
|
{/if}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div class="backend-actions">
|
||||||
|
<button class="btn small" disabled={backendBusy} onclick={login}>
|
||||||
|
{backendBusy ? 'Anmeldung läuft …' : backend?.logged_in ? 'Neu anmelden' : 'Anmelden'}
|
||||||
|
</button>
|
||||||
|
{#if backend?.logged_in}
|
||||||
|
<button class="btn small danger" disabled={backendBusy} onclick={logout}>Abmelden</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{#if backendError}
|
||||||
|
<p class="error">{backendError}</p>
|
||||||
|
{/if}
|
||||||
|
{#if server}
|
||||||
|
<p class="muted keys-hint">
|
||||||
|
Schlüssel auf dem Server verwalten:
|
||||||
|
<a href={server.keys_url} onclick={openKeysPage}>{server.keys_url}</a>
|
||||||
|
</p>
|
||||||
|
{/if}
|
||||||
|
</section>
|
||||||
|
|
||||||
<section class="card">
|
<section class="card">
|
||||||
<h2>Audio</h2>
|
<h2>Audio</h2>
|
||||||
<div class="grid">
|
<div class="grid">
|
||||||
@@ -263,6 +454,48 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="card">
|
||||||
|
<h2>Updates</h2>
|
||||||
|
<div class="grid">
|
||||||
|
<span>Version</span>
|
||||||
|
<span>{appVersion || '…'}</span>
|
||||||
|
</div>
|
||||||
|
<div class="update-check">
|
||||||
|
<button class="btn" disabled={checking} onclick={checkUpdateNow}>
|
||||||
|
{checking ? 'Suche…' : 'Nach Updates suchen'}
|
||||||
|
</button>
|
||||||
|
{#if checkResult?.status === 'none'}
|
||||||
|
<span class="muted">Keine neue Version verfügbar (aktuell: {appVersion})</span>
|
||||||
|
{:else if checkResult?.status === 'error'}
|
||||||
|
<span class="error">{checkResult.message}</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{#if pendingUpdate && selfUpdateCapable !== null}
|
||||||
|
<div class="update-available">
|
||||||
|
<span>Update verfügbar (v{pendingUpdate.version})</span>
|
||||||
|
{#if selfUpdateCapable}
|
||||||
|
{#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}
|
||||||
|
<span class="muted">
|
||||||
|
Updates gibt es unter Windows automatisch; unter Linux bitte das .deb neu installieren.
|
||||||
|
</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</section>
|
||||||
|
|
||||||
<div class="footer">
|
<div class="footer">
|
||||||
<button class="btn primary" onclick={() => run(persist, 'Einstellungen gespeichert ✓')}>
|
<button class="btn primary" onclick={() => run(persist, 'Einstellungen gespeichert ✓')}>
|
||||||
Speichern
|
Speichern
|
||||||
@@ -377,6 +610,27 @@
|
|||||||
gap: 8px;
|
gap: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.backend-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
margin-top: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.keys-hint {
|
||||||
|
margin: 10px 0 0;
|
||||||
|
font-size: 12px;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
.update-check,
|
||||||
|
.update-available {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 6px 10px;
|
||||||
|
margin-top: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
.footer {
|
.footer {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
Reference in New Issue
Block a user