diff --git a/crates/core/src/backend.rs b/crates/core/src/backend.rs index c95bf06..7caf1ac 100644 --- a/crates/core/src/backend.rs +++ b/crates/core/src/backend.rs @@ -16,33 +16,12 @@ 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 { @@ -137,8 +116,8 @@ pub struct BackendClient { } impl BackendClient { - /// `base_url` as checked by [`normalize_url`]; a trailing slash is - /// ignored. + /// `base_url` is the backend's https origin (plus path prefix, if + /// any); a trailing slash is ignored. pub fn new(transport: Arc, base_url: &str) -> Self { Self { transport, @@ -146,6 +125,12 @@ impl BackendClient { } } + /// 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) @@ -351,8 +336,9 @@ 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); + /// 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 @@ -372,11 +358,11 @@ pub async fn upload_with_login( }; match client.upload_transcript(&key, text).await { Err(BackendError::InvalidKey) => { - login.discard_key().await; + 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().await; + login.discard_key(&key).await; } result.map_err(|e| e.user_message()) } @@ -467,31 +453,6 @@ mod tests { } } - #[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!( @@ -510,8 +471,10 @@ mod tests { 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] @@ -831,12 +794,12 @@ mod tests { assert!(!format!("{:?}", stored("euv_secret", None)).contains("euv_secret")); } - /// Scripted [`Login`]: hands out the given results in order and counts - /// discards. + /// Scripted [`Login`]: hands out the given results in order and + /// records the discarded keys. struct FakeLogin { results: Mutex>>, logins: Mutex, - discards: Mutex, + discarded: Mutex>, } impl FakeLogin { @@ -844,12 +807,19 @@ mod tests { Self { results: Mutex::new(results), logins: Mutex::new(0), - discards: Mutex::new(0), + discarded: Mutex::new(Vec::new()), } } fn counts(&self) -> (usize, usize) { - (*self.logins.lock().unwrap(), *self.discards.lock().unwrap()) + ( + *self.logins.lock().unwrap(), + self.discarded.lock().unwrap().len(), + ) + } + + fn discarded(&self) -> Vec { + self.discarded.lock().unwrap().clone() } } @@ -860,8 +830,8 @@ mod tests { self.results.lock().unwrap().remove(0) } - async fn discard_key(&self) { - *self.discards.lock().unwrap() += 1; + async fn discard_key(&self, refused: &str) { + self.discarded.lock().unwrap().push(refused.to_string()); } } @@ -923,6 +893,7 @@ mod tests { 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() @@ -943,6 +914,7 @@ mod tests { 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(); } diff --git a/crates/core/src/call_view.rs b/crates/core/src/call_view.rs index eb9141f..99790b9 100644 --- a/crates/core/src/call_view.rs +++ b/crates/core/src/call_view.rs @@ -97,6 +97,9 @@ pub struct CallDetail { pub speaker_names: BTreeMap, /// The call's speaker merges, by source speaker number. pub merges: Vec, + /// 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 { @@ -126,6 +129,7 @@ impl CallDetail { }, segments, merges: merge_views(merges, &speaker_names), + uploading: false, speaker_names, } } @@ -440,6 +444,7 @@ mod tests { "into_key": "remote:1", "into_label": "Sprecher 1", }], + "uploading": false, }) ); } diff --git a/crates/core/src/settings.rs b/crates/core/src/settings.rs index f19db66..76006c6 100644 --- a/crates/core/src/settings.rs +++ b/crates/core/src/settings.rs @@ -11,8 +11,6 @@ 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", @@ -41,13 +39,14 @@ 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>, + /// 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, } impl Default for Settings { @@ -62,9 +61,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, + backend_key_base_url: None, } } } @@ -86,28 +85,18 @@ 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> { + /// 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 { 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)) + 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 @@ -158,23 +147,26 @@ 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); + assert_eq!(s.backend_key_base_url, None); } #[test] - fn validate_rejects_a_backend_url_that_is_not_https() { - let s = Settings { - backend_url: "http://test.euvinopro.eu".into(), - ..Settings::default() - }; + 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!( - s.validate(), - Err( - "Backend-URL: bitte eine https-Adresse wie https://test.euvinopro.eu angeben" - .to_string() - ) + Settings::load(&path), + Settings { + retention_days: 9, + ..Settings::default() + } ); } @@ -186,6 +178,7 @@ mod tests { .unwrap() .into(), ), + backend_key_base_url: Some("https://test.euvinopro.eu".into()), ..Settings::default() } } @@ -195,15 +188,14 @@ mod tests { 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, + backend_key_base_url: Some("https://elsewhere.example".into()), ..Settings::default() }; - let (saved, backend_changed) = current.edited(edited).unwrap(); + let saved = current.edited(edited).unwrap(); - assert!(!backend_changed); assert_eq!( saved, Settings { @@ -213,28 +205,8 @@ mod tests { ); } - #[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() diff --git a/src-tauri/src/backend.rs b/src-tauri/src/backend.rs index ecb04fc..c87aaa1 100644 --- a/src-tauri/src/backend.rs +++ b/src-tauri/src/backend.rs @@ -20,7 +20,8 @@ use recorder_core::model::CallId; use serde::Serialize; use tauri::webview::PageLoadEvent; use tauri::{ - AppHandle, Emitter, Manager, Url, WebviewUrl, WebviewWindow, WebviewWindowBuilder, WindowEvent, + AppHandle, Emitter, Manager, State, Url, WebviewUrl, WebviewWindow, WebviewWindowBuilder, + WindowEvent, }; use tauri_plugin_opener::OpenerExt; use tokio::sync::oneshot; @@ -28,6 +29,20 @@ 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"; @@ -85,6 +100,14 @@ impl Drop for CreatingClaim<'_> { } } +/// 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 { @@ -94,8 +117,6 @@ pub struct BackendStatus { /// `false` if the stored key could not be checked; username and expiry /// are then the stored ones. pub reachable: bool, - /// Where the admin manages their keys. - pub keys_url: String, } /// Payload of `backend-login-error`: creating the key failed, the login @@ -105,8 +126,18 @@ 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 is discarded. +/// backend. A key the backend refuses, or one of another backend, is +/// discarded. #[tauri::command] pub async fn backend_status(app: AppHandle) -> CmdResult { let state = app.state::(); @@ -117,7 +148,6 @@ pub async fn backend_status(app: AppHandle) -> CmdResult { username: None, expires_at: None, reachable: true, - keys_url: client.keys_page_url(), }; let Some(stored) = stored else { return Ok(status); @@ -131,7 +161,11 @@ pub async fn backend_status(app: AppHandle) -> CmdResult { } KeyCheck::Invalid => { log::info!("backend: the stored key was refused, discarding it"); - blocking(&app, |state| state.discard_backend_key()).await?; + let refused = stored.key; + blocking(&app, move |state| { + state.discard_refused_backend_key(&refused) + }) + .await?; } KeyCheck::Unknown(e) => { log::info!( @@ -175,24 +209,33 @@ pub fn open_backend_keys_page(app: AppHandle) -> CmdResult<()> { /// "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::(); + 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 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)?; - processing::emit_updated(&app, id); - Ok(()) + state.mark_uploaded(id, &crm_id) } /// [`Login`] through the login window, for the upload. @@ -206,12 +249,20 @@ impl Login for AppLogin { login(&self.app).await } - async fn discard_key(&self) { - log::info!("backend: the key was refused, discarding it"); - if let Err(e) = blocking(&self.app, |state| state.discard_backend_key()).await { - log::error!("backend: {e}"); + 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}"), } - emit_changed(&self.app); } } @@ -294,6 +345,7 @@ fn create_key(window: WebviewWindow, client: BackendClient) { } 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 }); } } @@ -340,8 +392,11 @@ async fn store_key(app: &AppHandle, client: &BackendClient, key: &NewKey) -> Res None } }; - let key = key.clone(); - blocking(app, move |state| state.store_backend_key(&key, username)).await?; + 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(()) } diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index e866277..8adf399 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -37,23 +37,16 @@ pub fn get_settings(state: State<'_, AppState>) -> Settings { state.settings() } -/// Saves the settings. A changed backend URL ends the backend login -/// (`backend-changed`). May delete from the keyring, so it runs on the -/// blocking pool. #[tauri::command] -pub async fn save_settings(app: AppHandle, settings: Settings) -> CmdResult<()> { - blocking(app, move |app| { - let autostart = settings.autostart; - let backend_changed = app.state::().save_settings(settings)?; - apply_autostart(app, autostart); - if backend_changed { - if let Err(e) = app.emit_to("main", "backend-changed", ()) { - log::error!("could not emit backend-changed: {e}"); - } - } - Ok(()) - }) - .await +pub fn save_settings( + app: AppHandle, + state: State<'_, AppState>, + settings: Settings, +) -> CmdResult<()> { + let autostart = settings.autostart; + state.save_settings(settings)?; + apply_autostart(&app, autostart); + Ok(()) } /// Stores `key` in the keyring; an empty key deletes the entry. diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index c45598d..bc3680b 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -36,8 +36,13 @@ pub fn run() { .plugin(tauri_plugin_notification::init()) .plugin(tauri_plugin_updater::Builder::new().build()) // Only for `open_backend_keys_page`: no capability grants the UI - // the plugin's commands. - .plugin(tauri_plugin_opener::init()) + // 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| { // Release builds log to a file in the app log directory (on // Windows %LOCALAPPDATA%\eu.euvino.callrecorder\logs), debug @@ -147,6 +152,7 @@ pub fn run() { commands::merge_speakers, commands::unmerge_speaker, commands::rename_call, + backend::backend_server, backend::backend_status, backend::backend_login, backend::backend_logout, diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index 2abcefb..5225837 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -157,6 +157,26 @@ pub struct AppState { /// Set while a recording starts or the devices are tested, so neither /// runs twice and `current` is never locked for longer than a moment. 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>, +} + +/// 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. @@ -189,6 +209,9 @@ impl AppState { pending_prompts: Mutex::new(VecDeque::new()), processing: Mutex::new(HashSet::new()), devices_busy: AtomicBool::new(false), + backend_url: crate::backend::BACKEND_URL.to_string(), + backend_key_lock: Mutex::new(()), + uploading: Mutex::new(HashSet::new()), } } @@ -198,50 +221,78 @@ impl AppState { /// Validates, saves and applies the settings the user edited; the /// detector picks up the new allowlist and delays immediately. The - /// backend login is kept, unless the backend URL changed: then its key - /// is discarded (it belongs to the old backend) and `true` returned. - /// Deletes from the keyring, so call it off the UI thread. - pub fn save_settings(&self, edited: Settings) -> Result { + /// backend login (managed by the app) is kept. + pub fn save_settings(&self, edited: Settings) -> Result<(), String> { let mut current = lock(&self.settings); - let (settings, backend_changed) = current.edited(edited)?; - if backend_changed { - self.secrets - .delete(Service::Backend) - .map_err(|e| format!("Backend-Schlüssel konnte nicht entfernt werden: {e}"))?; - } + let settings = current.edited(edited)?; save(&settings, &self.settings_path)?; lock(&self.detector).set_config(detector_config(&settings)); *current = settings; - Ok(backend_changed) + Ok(()) } - /// Client of the configured backend. + /// 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.settings().backend_url) + BackendClient::new(self.transport.clone(), &self.backend_url) } - /// The stored backend key with its expiry. Reads the keyring, so call - /// it off the UI thread. + /// 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 { + 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: self.settings().backend_key_expires_at, + expires_at: settings.backend_key_expires_at, }) } - /// Stores a key the login created (in the keyring) and whose it is and - /// when it expires (in the settings). - pub fn store_backend_key(&self, key: &NewKey, username: Option) -> Result<(), String> { + /// 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, + ) -> 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()); }) } @@ -254,17 +305,51 @@ impl AppState { }) } - /// Forgets the backend key (keyring) and its login (settings). + /// "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 { + 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. + pub fn claim_upload(&self, id: CallId) -> Result, String> { + if !lock(&self.uploading).insert(id) { + return Err("Wird bereits hochgeladen".to_string()); + } + 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> { @@ -511,14 +596,16 @@ impl AppState { Ok(calls.iter().map(CallListItem::of).collect()) } - /// The selected call with its transcript (speaker merges applied) and - /// speaker names. + /// The selected call with its transcript (speaker merges applied), + /// speaker names and whether it is being uploaded. pub fn call_detail(&self, id: CallId) -> Result { let call = self.find_call(id)?; 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 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 @@ -1337,7 +1424,7 @@ mod tests { end_after_secs: 30, ..Settings::default() }; - assert_eq!(f.state.save_settings(valid.clone()), Ok(false)); + assert_eq!(f.state.save_settings(valid.clone()), Ok(())); assert_eq!(f.state.settings(), valid); } @@ -1348,13 +1435,19 @@ mod tests { } } + const BASE: &str = crate::backend::BACKEND_URL; + #[test] - fn a_stored_backend_key_comes_with_its_login() { + 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"), Some("hinrichs".into())) + .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(); @@ -1368,16 +1461,55 @@ mod tests { 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"), None).unwrap(); + 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 @@ -1393,13 +1525,14 @@ mod tests { 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"), Some("hinrichs".into())) + .store_backend_key(&new_key("euv_k"), BASE, Some("hinrichs".into())) .unwrap(); f.state.discard_backend_key().unwrap(); @@ -1409,13 +1542,33 @@ mod tests { 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 saving_settings_keeps_the_backend_login_unless_the_url_changes() { + fn only_the_refused_key_is_discarded() { let f = fixture(); f.state - .store_backend_key(&new_key("euv_k"), Some("hinrichs".into())) + .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 { @@ -1423,28 +1576,45 @@ mod tests { ..Settings::default() }; - assert_eq!(f.state.save_settings(edited.clone()), Ok(false)); - assert!(f.state.backend_key().is_some()); - assert_eq!( - f.state.settings().backend_username.as_deref(), - Some("hinrichs") - ); - assert_eq!(f.state.settings().retention_days, 14); + assert_eq!(f.state.save_settings(edited), Ok(())); - let other_backend = Settings { - backend_url: "https://other.example/".into(), - ..edited - }; - assert_eq!(f.state.save_settings(other_backend), Ok(true)); - assert_eq!(f.state.backend_key(), None); - assert_eq!(f.state.settings().backend_url, "https://other.example"); - assert_eq!(f.state.settings().backend_username, None); + 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://other.example/euvadm" + "https://test.euvinopro.eu/euvadm" ); } + #[test] + fn a_call_is_uploaded_once_at_a_time() { + let f = fixture(); + let (id, _, _) = finished_call(&f, "a"); + 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(id + 1).is_ok(), "other calls are free"); + + drop(claim); + assert!(!f.state.is_uploading(id)); + assert!(f.state.claim_upload(id).is_ok()); + } + #[test] fn an_upload_is_recorded_on_the_call() { let f = fixture(); diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index feac54b..c21e3f8 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -15,12 +15,19 @@ export interface Settings { autostart: boolean start_after_secs: number end_after_secs: number - /** The euvino admin backend, e.g. "https://test.euvinopro.eu". */ - backend_url: string /** 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 +} + +/** 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. */ @@ -31,8 +38,6 @@ export interface BackendStatus { expires_at: string | null /** `false` if the key could not be checked; username and expiry are then the stored ones. */ reachable: boolean - /** Where the admin manages their keys. */ - keys_url: string } export type Service = 'deepscript' @@ -115,6 +120,8 @@ export interface CallDetail { /** Renamed speakers by key. */ speaker_names: Record merges: SpeakerMerge[] + /** The transcript is being uploaded right now. */ + uploading: boolean } /** A newer version the release feed offers. */ @@ -166,6 +173,7 @@ export const unmergeSpeaker = (id: CallId, fromKey: string) => /** `null` or an empty title restores the default heading. */ export const renameCall = (id: CallId, title: string | null) => invoke('rename_call', { id, title }) +export const backendServer = () => invoke('backend_server') export const backendStatus = () => invoke('backend_status') /** Resolves once the login window created a key; rejects if it was closed or failed. */ export const backendLogin = () => invoke('backend_login') diff --git a/ui/src/routes/Main.svelte b/ui/src/routes/Main.svelte index 0844f8b..eeb5f8a 100644 --- a/ui/src/routes/Main.svelte +++ b/ui/src/routes/Main.svelte @@ -273,6 +273,12 @@ return parts.join(' · ') } + // Also while an upload started elsewhere (e.g. before switching views) + // still runs in the app. + let isUploading = $derived( + detail !== null && (uploading.includes(detail.call.id) || detail.uploading), + ) + // A failed start (e.g. missing key) also marks the call failed; its // error is then shown once, in the failure box. let shownActionError = $derived(actionError !== detail?.call.error ? actionError : '') @@ -361,11 +367,11 @@ {:else if call.status === 'done'}