From 58e96a2954adf5282f580efd4aaebff644029a67 Mon Sep 17 00:00:00 2001 From: hauke Date: Fri, 6 Nov 2026 14:52:50 +0100 Subject: [PATCH] feat #14740: admin backend client and transcript upload text recorder-core side of linking the app to the euvino admin backend: - backend: BackendClient (create a key with the admin's session cookie, check a key, upload a transcript; redirects never followed), German error messages, the login-window decision (LoginStep) and the upload flow with login, one retry after a refused key and no loop - call_view: the upload text (header + merged, renamed lines) and the upload fields on the call - store: schema v3 with crm_transcript_id and uploaded_at - settings: backend_url (validated https), the app-managed login fields, kept on edit and cleared when the backend URL changes - secrets: Service::Backend; http: per-request follow_redirects; FakeTransport can script transport errors Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/core/src/backend.rs | 991 +++++++++++++++++++++++ crates/core/src/call_view.rs | 153 +++- crates/core/src/http.rs | 43 +- crates/core/src/lib.rs | 1 + crates/core/src/model.rs | 4 + crates/core/src/retention.rs | 2 + crates/core/src/secrets.rs | 9 +- crates/core/src/settings.rs | 116 +++ crates/core/src/store.rs | 129 ++- crates/core/src/testing.rs | 25 +- crates/core/src/transcribe/deepscript.rs | 4 + 11 files changed, 1447 insertions(+), 30 deletions(-) create mode 100644 crates/core/src/backend.rs diff --git a/crates/core/src/backend.rs b/crates/core/src/backend.rs new file mode 100644 index 0000000..c95bf06 --- /dev/null +++ b/crates/core/src/backend.rs @@ -0,0 +1,991 @@ +//! 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 backend the app talks to unless the user sets another one. +pub const DEFAULT_URL: &str = "https://test.euvinopro.eu"; +/// 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; + +/// Checks a backend URL the user typed: `https` with a host, no user name, +/// query or fragment. Returns it without trailing slashes. +pub fn normalize_url(url: &str) -> Result { + let invalid = || { + "Backend-URL: bitte eine https-Adresse wie https://test.euvinopro.eu angeben".to_string() + }; + let parsed = Url::parse(url.trim()).map_err(|_| invalid())?; + let usable = parsed.scheme() == "https" + && parsed.host_str().is_some_and(|host| !host.is_empty()) + && parsed.username().is_empty() + && parsed.password().is_none() + && parsed.query().is_none() + && parsed.fragment().is_none(); + if !usable { + return Err(invalid()); + } + Ok(parsed.as_str().trim_end_matches('/').to_string()) +} + +/// The label of a key this app creates: "Gesprächsrekorder ()", +/// 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, +} + +impl fmt::Debug for NewKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("NewKey") + .field("key", &"") + .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, + pub expires_at: DateTime, +} + +/// 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, + base_url: String, +} + +impl BackendClient { + /// `base_url` as checked by [`normalize_url`]; a trailing slash is + /// ignored. + pub fn new(transport: Arc, base_url: &str) -> Self { + Self { + transport, + base_url: base_url.trim_end_matches('/').to_string(), + } + } + + /// 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 { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct Created { + key: String, + expires_at: DateTime, + } + + 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::() { + 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 { + 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 { + 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::().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 { + 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) -> 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>, +} + +impl fmt::Debug for StoredKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("StoredKey") + .field("key", &"") + .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) -> 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; + /// Forgets the stored key the backend refused. + async fn discard_key(&self); +} + +/// 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, + now: DateTime, + text: &str, +) -> Result { + 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().await; + let key = login.login().await?; + let result = client.upload_transcript(&key, text).await; + if result == Err(BackendError::InvalidKey) { + login.discard_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::() + .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::() else { + return String::new(); + }; + let errors: Vec = 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, 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.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 urls_must_be_https_with_a_host() { + assert_eq!( + normalize_url(" https://test.euvinopro.eu/ "), + Ok("https://test.euvinopro.eu".to_string()) + ); + assert_eq!( + normalize_url("https://backend.example:8443/sub/"), + Ok("https://backend.example:8443/sub".to_string()) + ); + let invalid = "Backend-URL: bitte eine https-Adresse wie https://test.euvinopro.eu angeben"; + for url in [ + "", + "test.euvinopro.eu", + "http://test.euvinopro.eu", + "https://", + "https://user:pw@test.euvinopro.eu", + "https://test.euvinopro.eu/?a=1", + "https://test.euvinopro.eu/#x", + "ftp://test.euvinopro.eu", + ] { + assert_eq!(normalize_url(url), Err(invalid.to_string()), "{url:?}"); + } + } + + #[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); + let slash = BackendClient::new(Arc::new(FakeTransport::new()), "https://backend.example/"); + assert_eq!(slash.login_url(), "https://backend.example/euvadm"); + } + + #[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, + "boom", + 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>) -> 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 counts + /// discards. + struct FakeLogin { + results: Mutex>>, + logins: Mutex, + discards: Mutex, + } + + impl FakeLogin { + fn new(results: Vec>) -> Self { + Self { + results: Mutex::new(results), + logins: Mutex::new(0), + discards: Mutex::new(0), + } + } + + fn counts(&self) -> (usize, usize) { + (*self.logins.lock().unwrap(), *self.discards.lock().unwrap()) + } + } + + #[async_trait] + impl Login for FakeLogin { + async fn login(&self) -> Result { + *self.logins.lock().unwrap() += 1; + self.results.lock().unwrap().remove(0) + } + + async fn discard_key(&self) { + *self.discards.lock().unwrap() += 1; + } + } + + fn now() -> DateTime { + at(2026, 11, 6, 12, 0) + } + + fn valid(key: &str) -> Option { + 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)); + 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)); + 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)); + } +} diff --git a/crates/core/src/call_view.rs b/crates/core/src/call_view.rs index e11731e..eb9141f 100644 --- a/crates/core/src/call_view.rs +++ b/crates/core/src/call_view.rs @@ -21,6 +21,10 @@ pub struct CallListItem { pub interrupted: bool, /// The name the user gave the call, if any. pub title: Option, + /// The id the CRM gave the transcript at its last upload. + pub crm_transcript_id: Option, + /// When the transcript was last uploaded. + pub uploaded_at: Option>, } impl CallListItem { @@ -33,6 +37,8 @@ impl CallListItem { status: call.status, interrupted: call.interrupted, title: call.title.clone(), + crm_transcript_id: call.crm_transcript_id.clone(), + uploaded_at: call.uploaded_at, } } } @@ -45,12 +51,14 @@ pub fn duration_secs(call: &Call) -> i64 { } /// The selected call's header data: its list row plus the error of a -/// failed run. +/// failed run and when it was transcribed (only a transcribed call can be +/// uploaded). #[derive(Serialize, Clone, Debug, PartialEq)] pub struct CallHeader { #[serde(flatten)] pub item: CallListItem, pub error: Option, + pub transcribed_at: Option>, } /// A transcript line with the speaker's display label. @@ -114,6 +122,7 @@ impl CallDetail { call: CallHeader { item: CallListItem::of(call), error: call.error.clone(), + transcribed_at: call.transcribed_at, }, segments, merges: merge_views(merges, &speaker_names), @@ -122,6 +131,70 @@ impl CallDetail { } } +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 { + let lines: Vec = 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::>() + .join("\n")) + } +} + +/// Why [`CallDetail::upload_text`] has nothing to upload. +pub const NO_TRANSCRIPT: &str = "Kein Transkript zum Hochladen"; + +/// Position in the recording: "04:07", or "1:02:07" from one hour on (like +/// the transcript view). +fn offset(secs: f64) -> String { + let total = if secs.is_finite() && secs > 0.0 { + secs as u64 + } else { + 0 + }; + let (h, m, s) = (total / 3600, total % 3600 / 60, total % 60); + if h > 0 { + format!("{h}:{m:02}:{s:02}") + } else { + format!("{m:02}:{s:02}") + } +} + fn merge_views( merges: &BTreeMap, speaker_names: &BTreeMap, @@ -175,6 +248,8 @@ mod tests { transcribed_at: None, audio_deleted: false, title: None, + crm_transcript_id: None, + uploaded_at: None, } } @@ -213,11 +288,18 @@ mod tests { status: CallStatus::AwaitingDecision, interrupted: true, title: None, + crm_transcript_id: None, + uploaded_at: None, } ); c.title = Some("Angebot Rioja".into()); - assert_eq!(CallListItem::of(&c).title.as_deref(), Some("Angebot Rioja")); + c.crm_transcript_id = Some("4711".into()); + c.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] @@ -328,6 +410,7 @@ mod tests { c.status = CallStatus::Failed; c.error = Some("Netzwerkfehler".into()); c.title = Some("Reklamation".into()); + c.transcribed_at = Some(at(10, 20, 0)); let merges = keys(&[("remote:2", "remote:1")]); let value = @@ -344,7 +427,10 @@ mod tests { "status": "failed", "interrupted": false, "title": "Reklamation", + "crm_transcript_id": null, + "uploaded_at": null, "error": "Netzwerkfehler", + "transcribed_at": serde_json::to_value(at(10, 20, 0)).unwrap(), }, "segments": [], "speaker_names": {}, @@ -357,4 +443,67 @@ mod tests { }) ); } + + 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"); + } } diff --git a/crates/core/src/http.rs b/crates/core/src/http.rs index d941a6d..34363f5 100644 --- a/crates/core/src/http.rs +++ b/crates/core/src/http.rs @@ -50,6 +50,9 @@ pub struct HttpRequest { pub url: String, pub headers: Vec<(String, String)>, pub body: HttpBody, + /// `false` returns a redirect (3xx) as the response instead of + /// following it. + pub follow_redirects: bool, } impl HttpRequest { @@ -98,22 +101,30 @@ pub trait HttpTransport: Send + Sync { async fn send(&self, req: HttpRequest) -> Result; } -/// Live `HttpTransport` backed by `reqwest` (rustls). Shares one -/// `reqwest::Client` (connection pooling) with a 10 minute request timeout +/// Live `HttpTransport` backed by `reqwest` (rustls). Shares its +/// `reqwest::Client`s (connection pooling) with a 10 minute request timeout /// and a 30 second connect timeout, matching the DeepScript client's -/// worst-case wait. +/// worst-case wait. reqwest sets the redirect policy per client, so there +/// is one that follows redirects and one that does not. pub struct ReqwestTransport { client: reqwest::Client, + no_redirect_client: reqwest::Client, } impl ReqwestTransport { pub fn new() -> Self { - let client = reqwest::Client::builder() - .timeout(Duration::from_secs(10 * 60)) - .connect_timeout(Duration::from_secs(30)) - .build() - .expect("failed to build reqwest client"); - ReqwestTransport { client } + let build = |redirects| { + reqwest::Client::builder() + .timeout(Duration::from_secs(10 * 60)) + .connect_timeout(Duration::from_secs(30)) + .redirect(redirects) + .build() + .expect("failed to build reqwest client") + }; + ReqwestTransport { + client: build(reqwest::redirect::Policy::default()), + no_redirect_client: build(reqwest::redirect::Policy::none()), + } } } @@ -126,10 +137,15 @@ impl Default for ReqwestTransport { #[async_trait] impl HttpTransport for ReqwestTransport { async fn send(&self, req: HttpRequest) -> Result { + let client = if req.follow_redirects { + &self.client + } else { + &self.no_redirect_client + }; let mut builder = match req.method { - Method::Get => self.client.get(&req.url), - Method::Post => self.client.post(&req.url), - Method::Delete => self.client.delete(&req.url), + Method::Get => client.get(&req.url), + Method::Post => client.post(&req.url), + Method::Delete => client.delete(&req.url), }; for (name, value) in &req.headers { builder = builder.header(name, value); @@ -202,6 +218,7 @@ mod tests { url: url.to_string(), headers: vec![], body: HttpBody::Empty, + follow_redirects: true, } } @@ -224,6 +241,7 @@ mod tests { url: "https://api.example.com/b?x=1".to_string(), headers: vec![("x-test".to_string(), "1".to_string())], body: HttpBody::Empty, + follow_redirects: true, }) .await .unwrap(); @@ -264,6 +282,7 @@ mod tests { url: "https://api.example.com".to_string(), headers: vec![("Authorization".to_string(), "Bearer xyz".to_string())], body: HttpBody::Empty, + follow_redirects: true, }; assert_eq!(req.header("authorization"), Some("Bearer xyz")); assert_eq!(req.header("missing"), None); diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index d8cce5c..1c34549 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -5,6 +5,7 @@ //! without a GUI or network. pub mod audio; +pub mod backend; pub mod call_view; pub mod capture; pub mod detect; diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs index fd19902..204e743 100644 --- a/crates/core/src/model.rs +++ b/crates/core/src/model.rs @@ -39,6 +39,10 @@ pub struct Call { pub audio_deleted: bool, /// The name the user gave the call, if any. pub title: Option, + /// The id the CRM gave the transcript at its last upload. + pub crm_transcript_id: Option, + /// When the transcript was last uploaded. + pub uploaded_at: Option>, } /// A single transcribed word with its timing and speaker attribution. diff --git a/crates/core/src/retention.rs b/crates/core/src/retention.rs index 1011b6b..f8cb46c 100644 --- a/crates/core/src/retention.rs +++ b/crates/core/src/retention.rs @@ -89,6 +89,8 @@ mod tests { transcribed_at: None, audio_deleted: false, title: None, + crm_transcript_id: None, + uploaded_at: None, } } diff --git a/crates/core/src/secrets.rs b/crates/core/src/secrets.rs index a6ec99b..bc53580 100644 --- a/crates/core/src/secrets.rs +++ b/crates/core/src/secrets.rs @@ -1,5 +1,7 @@ //! API keys, stored only in the OS keyring (Windows Credential Manager, -//! Linux Secret Service) under the service `eu.euvino.callrecorder`. +//! Linux Secret Service) under the service `eu.euvino.callrecorder`: the +//! DeepScript key the user enters and the euvino admin backend key the +//! login creates. use std::collections::HashMap; use std::sync::Mutex; @@ -15,6 +17,7 @@ pub const KEYRING_SERVICE: &str = "eu.euvino.callrecorder"; #[serde(rename_all = "lowercase")] pub enum Service { DeepScript, + Backend, } impl Service { @@ -22,6 +25,7 @@ impl Service { pub fn user(self) -> &'static str { match self { Service::DeepScript => "deepscript", + Service::Backend => "backend", } } } @@ -117,7 +121,7 @@ impl SecretStore for MemorySecrets { mod tests { use super::*; - const SERVICES: &[Service] = &[Service::DeepScript]; + const SERVICES: &[Service] = &[Service::DeepScript, Service::Backend]; #[test] fn memory_secrets_roundtrip() { @@ -126,6 +130,7 @@ mod tests { secrets.set(Service::DeepScript, "ds-key").unwrap(); assert_eq!(secrets.get(Service::DeepScript).as_deref(), Some("ds-key")); + assert_eq!(secrets.get(Service::Backend), None); secrets.delete(Service::DeepScript).unwrap(); assert_eq!(secrets.get(Service::DeepScript), None); diff --git a/crates/core/src/settings.rs b/crates/core/src/settings.rs index a177f60..f19db66 100644 --- a/crates/core/src/settings.rs +++ b/crates/core/src/settings.rs @@ -8,8 +8,11 @@ use std::io; use std::ops::RangeInclusive; use std::path::Path; +use chrono::{DateTime, Local}; use serde::{Deserialize, Serialize}; +use crate::backend; + /// Executables whose mic use counts as a call (matched case-insensitively). const DEFAULT_ALLOWLIST: [&str; 6] = [ "ms-teams.exe", @@ -38,6 +41,13 @@ pub struct Settings { pub autostart: bool, pub start_after_secs: u64, pub end_after_secs: u64, + /// The euvino admin backend transcripts are uploaded to. + pub backend_url: String, + /// 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, + /// When the stored backend key expires. Set by the app at login. + pub backend_key_expires_at: Option>, } impl Default for Settings { @@ -52,6 +62,9 @@ impl Default for Settings { autostart: true, start_after_secs: 3, end_after_secs: 10, + backend_url: backend::DEFAULT_URL.to_string(), + backend_username: None, + backend_key_expires_at: None, } } } @@ -73,9 +86,30 @@ impl Settings { END_AFTER_SECS.end() )); } + backend::normalize_url(&self.backend_url)?; Ok(()) } + /// The settings after the user saved `edited` over these: checked, with + /// the backend URL normalized and the backend login (which only the app + /// changes) kept. If the backend URL changed, the login is cleared and + /// `true` returned: the stored key belongs to the old backend and must + /// be discarded. + pub fn edited(&self, mut edited: Settings) -> Result<(Settings, bool), String> { + edited.validate()?; + edited.backend_url = backend::normalize_url(&edited.backend_url)?; + let backend_changed = backend::normalize_url(&self.backend_url) + .map_or(true, |current| current != edited.backend_url); + if backend_changed { + edited.backend_username = None; + edited.backend_key_expires_at = None; + } else { + edited.backend_username = self.backend_username.clone(); + edited.backend_key_expires_at = self.backend_key_expires_at; + } + Ok((edited, backend_changed)) + } + /// Reads the settings file. A missing or unreadable file yields the /// defaults; fields missing from the file take their default value. pub fn load(path: &Path) -> Settings { @@ -124,6 +158,88 @@ mod tests { assert!(s.autostart); assert_eq!(s.start_after_secs, 3); assert_eq!(s.end_after_secs, 10); + assert_eq!(s.backend_url, "https://test.euvinopro.eu"); + assert_eq!(s.backend_username, None); + assert_eq!(s.backend_key_expires_at, None); + } + + #[test] + fn validate_rejects_a_backend_url_that_is_not_https() { + let s = Settings { + backend_url: "http://test.euvinopro.eu".into(), + ..Settings::default() + }; + assert_eq!( + s.validate(), + Err( + "Backend-URL: bitte eine https-Adresse wie https://test.euvinopro.eu angeben" + .to_string() + ) + ); + } + + 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(), + ), + ..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_url: "https://test.euvinopro.eu/".into(), + backend_username: None, + backend_key_expires_at: None, + ..Settings::default() + }; + + let (saved, backend_changed) = current.edited(edited).unwrap(); + + assert!(!backend_changed); + assert_eq!( + saved, + Settings { + retention_days: 30, + ..logged_in() + } + ); + } + + #[test] + fn an_edit_of_the_backend_url_ends_the_login() { + let edited = Settings { + backend_url: " https://other.example/ ".into(), + ..logged_in() + }; + + let (saved, backend_changed) = logged_in().edited(edited).unwrap(); + + assert!(backend_changed); + assert_eq!(saved.backend_url, "https://other.example"); + assert_eq!(saved.backend_username, None); + assert_eq!(saved.backend_key_expires_at, None); + } + + #[test] + fn an_invalid_edit_is_refused() { + let edited = Settings { + backend_url: "test.euvinopro.eu".into(), + ..Settings::default() + }; + assert!(logged_in().edited(edited).is_err()); + let edited = Settings { + start_after_secs: 0, + ..Settings::default() + }; + assert!(logged_in().edited(edited).is_err()); } #[test] diff --git a/crates/core/src/store.rs b/crates/core/src/store.rs index 2df2d7b..930955d 100644 --- a/crates/core/src/store.rs +++ b/crates/core/src/store.rs @@ -114,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 /// 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. pub struct Store { @@ -355,6 +361,22 @@ impl Store { 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, + ) -> 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) -> Result<()> { let conn = self.conn.lock().unwrap(); conn.execute( @@ -514,9 +536,9 @@ fn ids_with_status(conn: &rusqlite::Connection, status: CallStatus) -> Result Result { let id: CallId = row.get(0)?; @@ -531,6 +553,8 @@ fn row_to_call(row: &Row) -> Result { let transcribed_at: Option = row.get(9)?; let audio_deleted: bool = row.get(10)?; let title: Option = row.get(11)?; + let crm_transcript_id: Option = row.get(12)?; + let uploaded_at: Option = row.get(13)?; Ok(Call { id, @@ -545,6 +569,8 @@ fn row_to_call(row: &Row) -> Result { transcribed_at: opt_dt_from_str(transcribed_at)?, audio_deleted, title, + crm_transcript_id, + uploaded_at: opt_dt_from_str(uploaded_at)?, }) } @@ -653,6 +679,19 @@ CREATE TABLE IF NOT EXISTS remote_jobs ( remote_id TEXT NOT NULL, PRIMARY KEY (call_id, track, remote_id) ); +"; + + /// The schema of user_version 2, exactly as release 0.1.1 created it: + /// version 1 plus these statements. + const RELEASED_V2_STEP_SQL: &str = " +ALTER TABLE calls ADD COLUMN title TEXT; + +CREATE TABLE speaker_merges ( + call_id INTEGER NOT NULL REFERENCES calls(id) ON DELETE CASCADE, + from_key TEXT NOT NULL, + into_key TEXT NOT NULL, + PRIMARY KEY (call_id, from_key) +); "; fn user_version(path: &Path) -> i64 { @@ -676,16 +715,17 @@ CREATE TABLE IF NOT EXISTS remote_jobs ( } #[test] - fn a_new_database_starts_at_version_2() { + fn a_new_database_starts_at_version_3() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("calls.sqlite"); let store = Store::open(&path).unwrap(); let id = new_call(&store); store.set_title(id, Some("Angebot")).unwrap(); store.set_speaker_merge(id, "remote:2", "remote:1").unwrap(); + store.set_uploaded(id, "4711", Local::now()).unwrap(); drop(store); - assert_eq!(user_version(&path), 2); + assert_eq!(user_version(&path), 3); } #[test] @@ -742,7 +782,7 @@ CREATE TABLE IF NOT EXISTS remote_jobs ( store.set_title(1, Some("Lieferung März")).unwrap(); store.set_speaker_merge(1, "remote:2", "remote:1").unwrap(); drop(store); - assert_eq!(user_version(&path), 2); + assert_eq!(user_version(&path), 3); let store = Store::open(&path).unwrap(); let call = store.get_call(1).unwrap().unwrap(); assert_eq!(call.title.as_deref(), Some("Lieferung März")); @@ -753,6 +793,83 @@ CREATE TABLE IF NOT EXISTS remote_jobs ( assert_eq!(store.list_calls().unwrap().len(), 1); } + #[test] + fn a_version_2_database_is_upgraded_keeping_its_data() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("calls.sqlite"); + let started = "2026-11-05T10:14:00+01:00"; + { + let conn = rusqlite::Connection::open(&path).unwrap(); + conn.execute_batch(RELEASED_V1_SCHEMA_SQL).unwrap(); + conn.execute_batch(RELEASED_V2_STEP_SQL).unwrap(); + conn.execute_batch("PRAGMA user_version = 2;").unwrap(); + conn.execute( + "INSERT INTO calls (app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, account_id, title) \ + VALUES ('Microsoft Teams', ?1, ?1, 'done', 0, NULL, '/rec/1-mic.wav', '/rec/1-out.wav', ?1, 1, NULL, 'Angebot')", + rusqlite::params![started], + ) + .unwrap(); + conn.execute_batch( + "INSERT INTO segments (call_id, seq, speaker, start_ts, end_ts, text) VALUES \ + (1, 0, 'remote:2', 0.0, 1.5, 'Hallo.'); \ + INSERT INTO speaker_merges (call_id, from_key, into_key) VALUES (1, 'remote:2', 'remote:1');", + ) + .unwrap(); + } + + let store = Store::open(&path).unwrap(); + + let call = store.get_call(1).unwrap().expect("call kept"); + assert_eq!(call.title.as_deref(), Some("Angebot")); + assert!(call.audio_deleted); + assert_eq!(call.crm_transcript_id, None); + assert_eq!(call.uploaded_at, None); + assert_eq!(store.segments(1).unwrap().len(), 1); + assert_eq!( + store.speaker_merges(1).unwrap(), + merge_map(&[("remote:2", "remote:1")]) + ); + + // The new columns work, and opening again changes nothing. + let uploaded = Local::now(); + store.set_uploaded(1, "crm-1", 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] fn speaker_merges_are_set_replaced_and_removed() { let store = Store::open_in_memory().unwrap(); diff --git a/crates/core/src/testing.rs b/crates/core/src/testing.rs index 9557af8..4db1702 100644 --- a/crates/core/src/testing.rs +++ b/crates/core/src/testing.rs @@ -10,8 +10,7 @@ use crate::http::{HttpRequest, HttpResponse, HttpTransport, Method, TransportErr struct Expectation { method: Method, url: String, - status: u16, - body: Vec, + response: Result, } /// Scripted [`HttpTransport`]: queue expected requests in order with @@ -36,11 +35,24 @@ impl FakeTransport { /// Queues the next expected request and the response to return for it. pub fn expect(&self, method: Method, url: &str, status: u16, body: impl Into>) { + 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) { self.expectations.lock().unwrap().push(Expectation { method, url: url.to_string(), - status, - body: body.into(), + response, }); } @@ -92,9 +104,6 @@ impl HttpTransport for FakeTransport { ); } self.requests.lock().unwrap().push(req); - Ok(HttpResponse { - status: expectation.status, - body: expectation.body, - }) + expectation.response } } diff --git a/crates/core/src/transcribe/deepscript.rs b/crates/core/src/transcribe/deepscript.rs index 66d10f6..7e8d296 100644 --- a/crates/core/src/transcribe/deepscript.rs +++ b/crates/core/src/transcribe/deepscript.rs @@ -86,6 +86,7 @@ impl DeepScript { url: format!("{}/transcriptions/{remote_id}/status", self.base_url), headers: vec![self.auth_header()], body: HttpBody::Empty, + follow_redirects: true, }; let resp = match self.transport.send(req).await { Ok(resp) => resp, @@ -115,6 +116,7 @@ impl DeepScript { url: format!("{}/transcriptions/{remote_id}", self.base_url), headers: vec![self.auth_header()], body: HttpBody::Empty, + follow_redirects: true, }; let resp = self.send(req).await?; match resp.status { @@ -205,6 +207,7 @@ impl Transcriber for DeepScript { url: format!("{}/transcriptions", self.base_url), headers: vec![self.auth_header()], body: HttpBody::Multipart(parts), + follow_redirects: true, }; let resp = self.send(req).await?; @@ -265,6 +268,7 @@ impl Transcriber for DeepScript { url: format!("{}/transcriptions/{remote_id}", self.base_url), headers: vec![self.auth_header()], body: HttpBody::Empty, + follow_redirects: true, }; let resp = self.send(req).await?; match resp.status {