From f045424e972ca5132f30ffa3b312e63b88dd7305 Mon Sep 17 00:00:00 2001 From: hauke Date: Fri, 6 Nov 2026 14:54:38 +0100 Subject: [PATCH] feat #14740: link to the euvino admin backend MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Settings section "Backend": backend URL, login status checked live (logged in as / until, not logged in, backend unreachable), Anmelden / Neu anmelden, Abmelden and the link to the key management page - login window "backend-login": the backend's own login page in an incognito webview without any Tauri capability; after a page load behind the login, its cookies create a key (one request, never stored or logged), the key goes to the keyring, the window closes; closing it cancels; one login at a time, later requests wait for the same result - call detail: "Transkript hochladen" / "Erneut hochladen" (with a confirmation), "wird hochgeladen…", "Hochgeladen am … (ID …)" and inline errors; logs in first when there is no usable key - saving a different backend URL discards the key of the old backend Co-Authored-By: Claude Opus 5.5 (1M context) --- Cargo.lock | 55 +++++ src-tauri/Cargo.toml | 3 + src-tauri/src/backend.rs | 430 ++++++++++++++++++++++++++++++++++ src-tauri/src/commands.rs | 25 +- src-tauri/src/lib.rs | 19 +- src-tauri/src/state.rs | 229 +++++++++++++++++- ui/src/lib/api.ts | 38 ++- ui/src/lib/format.ts | 11 + ui/src/routes/Main.svelte | 75 +++++- ui/src/routes/Settings.svelte | 134 ++++++++++- 10 files changed, 990 insertions(+), 29 deletions(-) create mode 100644 src-tauri/src/backend.rs diff --git a/Cargo.lock b/Cargo.lock index d7bcf7d..23a085c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -447,6 +447,7 @@ dependencies = [ name = "call-recorder" version = "0.1.1" dependencies = [ + "async-trait", "chrono", "log", "recorder-audio", @@ -458,9 +459,11 @@ dependencies = [ "tauri-plugin-autostart", "tauri-plugin-log", "tauri-plugin-notification", + "tauri-plugin-opener", "tauri-plugin-single-instance", "tauri-plugin-updater", "tempfile", + "tokio", ] [[package]] @@ -2059,6 +2062,25 @@ version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +[[package]] +name = "is-docker" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3" +dependencies = [ + "once_cell", +] + +[[package]] +name = "is-wsl" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5" +dependencies = [ + "is-docker", + "once_cell", +] + [[package]] name = "itoa" version = "1.0.18" @@ -2981,6 +3003,17 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "open" +version = "5.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d8c8b8e725ad26404d6896eb2f064294a0a7b4f1d9120210d85544684c4ca95" +dependencies = [ + "dunce", + "is-wsl", + "libc", +] + [[package]] name = "openssl-probe" version = "0.2.2" @@ -4712,6 +4745,28 @@ dependencies = [ "zbus 5.19.0", ] +[[package]] +name = "tauri-plugin-opener" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53810be1b4fed22bb6ac3f4cab5a2b80d9391d1af436bda145607532bc0bb219" +dependencies = [ + "dunce", + "glob", + "objc2-app-kit", + "objc2-foundation", + "open", + "schemars 0.8.22", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "thiserror 2.0.21", + "url", + "windows", + "zbus 5.19.0", +] + [[package]] name = "tauri-plugin-single-instance" version = "2.5.5" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 2f82ed7..7cd237e 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -27,3 +27,6 @@ tempfile = "3" recorder-core = { path = "../crates/core" } recorder-audio = { path = "../crates/audio" } tauri-plugin-updater = "2" +tauri-plugin-opener = "2" +tokio = { version = "1", features = ["sync"] } +async-trait = "0.1" diff --git a/src-tauri/src/backend.rs b/src-tauri/src/backend.rs new file mode 100644 index 0000000..ecb04fc --- /dev/null +++ b/src-tauri/src/backend.rs @@ -0,0 +1,430 @@ +//! Link to the euvino admin backend: the login window that turns the +//! admin's browser session into an API key, the login status for the +//! settings, and the upload of a call's transcript. +//! +//! The login window shows the backend's own login page, a remote origin: it +//! has no Tauri capability (see `capabilities/default.json`), so the page +//! cannot invoke any command. It runs in incognito mode, so the session +//! never outlives the window. After each page load on the backend the app +//! reads the window's cookies for the backend and uses them for the one +//! request that creates a key. Neither the cookies nor the key are ever +//! logged; the key is stored only in the keyring. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Mutex; + +use async_trait::async_trait; +use chrono::{DateTime, Local}; +use recorder_core::backend::{self, BackendClient, KeyCheck, Login, LoginStep, NewKey}; +use recorder_core::model::CallId; +use serde::Serialize; +use tauri::webview::PageLoadEvent; +use tauri::{ + AppHandle, Emitter, Manager, Url, WebviewUrl, WebviewWindow, WebviewWindowBuilder, WindowEvent, +}; +use tauri_plugin_opener::OpenerExt; +use tokio::sync::oneshot; + +use crate::processing; +use crate::state::AppState; + +/// Label of the login window. +pub const LOGIN_WINDOW: &str = "backend-login"; +const CANCELLED: &str = "Anmeldung abgebrochen"; + +type CmdResult = Result; +/// A login's outcome: the new key, or the message why there is none. +type LoginResult = Result; + +/// Everyone waiting for the login that runs in the login window. Only one +/// login runs at a time; later requests wait for the same result. +#[derive(Default)] +pub struct LoginWaiters { + waiters: Mutex>>, + /// Set while a key is being created, so page loads in quick succession + /// do not create several. + creating: AtomicBool, +} + +impl LoginWaiters { + /// Waits for the login. `true` if no login was running yet, so the + /// caller has to start one. + fn join(&self) -> (oneshot::Receiver, bool) { + let (tx, rx) = oneshot::channel(); + let mut waiters = lock(&self.waiters); + let first = waiters.is_empty(); + waiters.push(tx); + (rx, first) + } + + /// Whether anyone waits for a login. + fn waiting(&self) -> bool { + !lock(&self.waiters).is_empty() + } + + /// Ends the login with `result` for everyone waiting. + fn finish(&self, result: LoginResult) { + for waiter in lock(&self.waiters).drain(..) { + let _ = waiter.send(result.clone()); + } + } + + /// Claims the right to create a key; `None` while another page load + /// is already creating one. + fn claim_creating(&self) -> Option> { + (!self.creating.swap(true, Ordering::SeqCst)).then_some(CreatingClaim(&self.creating)) + } +} + +/// Releases [`LoginWaiters::creating`] when dropped. +struct CreatingClaim<'a>(&'a AtomicBool); + +impl Drop for CreatingClaim<'_> { + fn drop(&mut self) { + self.0.store(false, Ordering::SeqCst); + } +} + +/// Answer of `backend_status`. +#[derive(Serialize, Clone, Debug, PartialEq)] +pub struct BackendStatus { + pub logged_in: bool, + pub username: Option, + pub expires_at: Option>, + /// `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 +/// window stays open for another try. +#[derive(Serialize, Clone)] +struct LoginError { + message: String, +} + +/// Whether a backend key is stored, and whose it is: checked with the +/// backend. A key the backend refuses is discarded. +#[tauri::command] +pub async fn backend_status(app: AppHandle) -> CmdResult { + let state = app.state::(); + let client = state.backend_client(); + let stored = blocking(&app, |state| Ok(state.backend_key())).await?; + let mut status = BackendStatus { + logged_in: false, + username: None, + expires_at: None, + reachable: true, + keys_url: client.keys_page_url(), + }; + let Some(stored) = stored else { + return Ok(status); + }; + match client.check_key(&stored.key).await { + KeyCheck::Valid(info) => { + state.refresh_backend_login(&info)?; + status.logged_in = true; + status.username = Some(info.username); + status.expires_at = Some(info.expires_at); + } + KeyCheck::Invalid => { + log::info!("backend: the stored key was refused, discarding it"); + blocking(&app, |state| state.discard_backend_key()).await?; + } + KeyCheck::Unknown(e) => { + log::info!( + "backend: could not check the stored key: {}", + e.user_message() + ); + let settings = state.settings(); + status.logged_in = true; + status.username = settings.backend_username; + status.expires_at = settings.backend_key_expires_at; + status.reachable = false; + } + } + Ok(status) +} + +/// "Anmelden": runs the login in the login window (a new key replaces the +/// stored one). +#[tauri::command] +pub async fn backend_login(app: AppHandle) -> CmdResult<()> { + login(&app).await.map(|_key| ()) +} + +/// "Abmelden": forgets the key locally (it stays valid on the server until +/// the admin deletes it there or it expires). +#[tauri::command] +pub async fn backend_logout(app: AppHandle) -> CmdResult<()> { + blocking(&app, |state| state.discard_backend_key()).await?; + emit_changed(&app); + Ok(()) +} + +/// Opens the backend's key management page in the system browser. +#[tauri::command] +pub fn open_backend_keys_page(app: AppHandle) -> CmdResult<()> { + let url = app.state::().backend_client().keys_page_url(); + app.opener() + .open_url(url, None::<&str>) + .map_err(|e| format!("Browser konnte nicht geöffnet werden: {e}")) +} + +/// "Transkript hochladen": uploads the call's transcript as the user sees +/// it, logging in first if needed, and records the CRM's id on the call. +#[tauri::command] +pub async fn upload_transcript(app: AppHandle, id: CallId) -> CmdResult<()> { + let state = app.state::(); + let detail = state.call_detail(id)?; + if detail.call.transcribed_at.is_none() { + return Err("Das Gespräch ist noch nicht transkribiert".to_string()); + } + let text = detail.upload_text()?; + let client = state.backend_client(); + let stored = blocking(&app, |state| Ok(state.backend_key())).await?; + let login = AppLogin { app: app.clone() }; + let crm_id = backend::upload_with_login(&client, &login, stored, Local::now(), &text) + .await + .inspect_err(|e| log::warn!("call {id}: upload failed: {e}"))?; + log::info!("call {id}: transcript uploaded (CRM id {crm_id})"); + state.mark_uploaded(id, &crm_id)?; + processing::emit_updated(&app, id); + Ok(()) +} + +/// [`Login`] through the login window, for the upload. +struct AppLogin { + app: AppHandle, +} + +#[async_trait] +impl Login for AppLogin { + async fn login(&self) -> Result { + 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}"); + } + emit_changed(&self.app); + } +} + +/// Runs the login in the login window, or waits for the one already +/// running (and brings its window to the front). Returns the new key, +/// already stored. +pub async fn login(app: &AppHandle) -> LoginResult { + let waiters = app.state::(); + let (result, first) = waiters.join(); + match app.get_webview_window(LOGIN_WINDOW) { + Some(window) => { + let _ = window.unminimize(); + let _ = window.set_focus(); + } + None if first => { + if let Err(e) = open_login_window(app) { + log::error!("backend: could not open the login window: {e}"); + waiters.finish(Err(format!( + "Anmeldefenster konnte nicht geöffnet werden: {e}" + ))); + } + } + None => {} + } + result.await.unwrap_or_else(|_| Err(CANCELLED.to_string())) +} + +fn open_login_window(app: &AppHandle) -> tauri::Result<()> { + let client = app.state::().backend_client(); + let url = Url::parse(&client.login_url()).map_err(tauri::Error::InvalidUrl)?; + let window = WebviewWindowBuilder::new(app, LOGIN_WINDOW, WebviewUrl::External(url)) + .title("Anmeldung euvino Admin") + .inner_size(1000.0, 760.0) + .incognito(true) + .on_page_load(move |window, payload| { + if payload.event() == PageLoadEvent::Finished + && client.is_logged_in_page(payload.url().as_str()) + { + create_key(window, client.clone()); + } + }) + .build()?; + let app = app.clone(); + window.on_window_event(move |event| { + if let WindowEvent::Destroyed = event { + // Closed by the user: the login is cancelled. After a + // finished login nobody waits any more. + app.state::() + .finish(Err(CANCELLED.to_string())); + } + }); + Ok(()) +} + +/// The login window shows a backend page behind the login: creates a key +/// with the window's session, in the background. `client` is the backend +/// the window was opened for. +fn create_key(window: WebviewWindow, client: BackendClient) { + tauri::async_runtime::spawn(async move { + let app = window.app_handle().clone(); + let waiters = app.state::(); + if !waiters.waiting() { + return; + } + let Some(_claim) = waiters.claim_creating() else { + return; + }; + match try_create_key(&client, &window).await { + LoginStep::Done(key) => { + let result = store_key(&app, &client, &key).await.map(|()| key.key); + waiters.finish(result); + emit_changed(&app); + let _ = window.destroy(); + } + LoginStep::Wait => {} + LoginStep::Fail(message) => { + log::warn!("backend: the login cannot create a key: {message}"); + waiters.finish(Err(message)); + let _ = window.destroy(); + } + LoginStep::Retry(message) => { + log::warn!("backend: creating the key failed: {message}"); + let _ = app.emit_to("main", "backend-login-error", LoginError { message }); + } + } + }); +} + +/// Creates a key with the cookies the login window holds for the backend. +/// The cookies are used for this one request and dropped. +async fn try_create_key(client: &BackendClient, window: &WebviewWindow) -> LoginStep { + let Ok(url) = Url::parse(&client.keys_page_url()) else { + return LoginStep::Wait; + }; + // Off the async runtime: on Windows reading cookies blocks until the + // main thread answers. + let reader = window.clone(); + let cookies = tauri::async_runtime::spawn_blocking(move || reader.cookies_for_url(url)).await; + let cookies = match cookies { + Ok(Ok(cookies)) => cookies, + Ok(Err(e)) => return LoginStep::Retry(format!("Anmeldedaten nicht lesbar: {e}")), + Err(e) => return LoginStep::Retry(format!("Anmeldedaten nicht lesbar: {e}")), + }; + if cookies.is_empty() { + return LoginStep::Wait; + } + let cookie_header = cookies + .iter() + .map(|cookie| format!("{}={}", cookie.name(), cookie.value())) + .collect::>() + .join("; "); + let label = backend::key_label(hostname().as_deref()); + LoginStep::of(client.create_key(&cookie_header, &label).await) +} + +/// Stores a new key with whose it is (asked from the backend; left empty if +/// that fails) and its expiry. +async fn store_key(app: &AppHandle, client: &BackendClient, key: &NewKey) -> Result<(), String> { + let username = match client.key_info(&key.key).await { + Ok(info) => Some(info.username), + Err(e) => { + log::warn!( + "backend: could not ask whose the new key is: {}", + e.user_message() + ); + None + } + }; + let key = key.clone(); + blocking(app, move |state| state.store_backend_key(&key, username)).await?; + log::info!("backend: logged in, key stored"); + Ok(()) +} + +/// The computer's name, for the key's label. +fn hostname() -> Option { + std::env::var("COMPUTERNAME") + .ok() + .or_else(|| std::fs::read_to_string("/etc/hostname").ok()) + .or_else(|| std::env::var("HOSTNAME").ok()) + .map(|name| name.trim().to_string()) + .filter(|name| !name.is_empty()) +} + +/// Tells the settings that the login changed (`backend-changed`). +fn emit_changed(app: &AppHandle) { + if let Err(e) = app.emit_to("main", "backend-changed", ()) { + log::error!("could not emit backend-changed: {e}"); + } +} + +/// Runs `f` with the app state on the blocking pool (keyring access). +async fn blocking(app: &AppHandle, f: F) -> CmdResult +where + T: Send + 'static, + F: FnOnce(&AppState) -> CmdResult + Send + 'static, +{ + let app = app.clone(); + tauri::async_runtime::spawn_blocking(move || f(&app.state::())) + .await + .map_err(|e| e.to_string())? +} + +fn lock(mutex: &Mutex) -> std::sync::MutexGuard<'_, T> { + mutex + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn everyone_waiting_gets_the_one_login_result() { + let waiters = LoginWaiters::default(); + assert!(!waiters.waiting()); + + let (first, starts) = waiters.join(); + let (second, starts_again) = waiters.join(); + assert!(starts); + assert!(!starts_again); + assert!(waiters.waiting()); + + waiters.finish(Ok("euv_k".into())); + + assert_eq!(first.blocking_recv().unwrap(), Ok("euv_k".to_string())); + assert_eq!(second.blocking_recv().unwrap(), Ok("euv_k".to_string())); + assert!(!waiters.waiting()); + } + + #[test] + fn a_finished_login_leaves_the_next_one_to_start_anew() { + let waiters = LoginWaiters::default(); + let (first, _) = waiters.join(); + waiters.finish(Err(CANCELLED.into())); + // A late "window destroyed" reaches nobody. + waiters.finish(Err("ignored".into())); + assert_eq!(first.blocking_recv().unwrap(), Err(CANCELLED.to_string())); + + let (next, starts) = waiters.join(); + assert!(starts); + waiters.finish(Ok("euv_new".into())); + assert_eq!(next.blocking_recv().unwrap(), Ok("euv_new".to_string())); + } + + #[test] + fn only_one_key_is_created_at_a_time() { + let waiters = LoginWaiters::default(); + let claim = waiters.claim_creating(); + assert!(claim.is_some()); + assert!(waiters.claim_creating().is_none()); + drop(claim); + assert!(waiters.claim_creating().is_some()); + } +} diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 8adf399..e866277 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -37,16 +37,23 @@ 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 fn save_settings( - app: AppHandle, - state: State<'_, AppState>, - settings: Settings, -) -> CmdResult<()> { - let autostart = settings.autostart; - state.save_settings(settings)?; - apply_autostart(&app, autostart); - Ok(()) +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 } /// 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 ebd15d7..c45598d 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,3 +1,4 @@ +mod backend; mod commands; mod detection; mod processing; @@ -34,6 +35,9 @@ 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()) .setup(|app| { // Release builds log to a file in the app log directory (on // Windows %LOCALAPPDATA%\eu.euvino.callrecorder\logs), debug @@ -89,6 +93,7 @@ pub fn run() { processing::clear_upload_dir(app.handle()); app.manage(state); app.manage(PendingUpdate::default()); + app.manage(backend::LoginWaiters::default()); // Windows are created here (`create: false` in tauri.conf.json) // instead of by Tauri before `setup` runs: their webviews load // immediately and invoke commands (list_calls, get_recording_state, @@ -110,10 +115,13 @@ pub fn run() { }) .on_window_event(|window, event| { // Closing a window only hides it; the app keeps running in the - // tray (for call detection) until "Beenden". + // tray (for call detection) until "Beenden". The login window + // really closes: that cancels the login. if let WindowEvent::CloseRequested { api, .. } = event { - api.prevent_close(); - let _ = window.hide(); + if window.label() != backend::LOGIN_WINDOW { + api.prevent_close(); + let _ = window.hide(); + } } }) .invoke_handler(tauri::generate_handler![ @@ -139,6 +147,11 @@ pub fn run() { commands::merge_speakers, commands::unmerge_speaker, commands::rename_call, + backend::backend_status, + backend::backend_login, + backend::backend_logout, + backend::open_backend_keys_page, + backend::upload_transcript, updater::get_update, updater::install_update, ]) diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index f0c0a8f..2abcefb 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -17,13 +17,14 @@ use std::time::{Duration, Instant}; use chrono::{DateTime, Local}; use recorder_audio::RenderSession; +use recorder_core::backend::{BackendClient, KeyInfo, NewKey, StoredKey}; use recorder_core::call_view::{self, CallDetail, CallListItem}; use recorder_core::capture::{CaptureSource, OutputTarget}; use recorder_core::detect::{CallDetector, DetectorEvent, MicSession}; use recorder_core::http::{HttpTransport, ReqwestTransport}; use recorder_core::model::{Call, CallId, CallStatus, Speaker}; use recorder_core::recorder::Recorder; -use recorder_core::secrets::SecretStore; +use recorder_core::secrets::{SecretStore, Service}; use recorder_core::settings::Settings; use recorder_core::store::Store; use serde::Serialize; @@ -195,15 +196,85 @@ impl AppState { lock(&self.settings).clone() } - /// Validates, saves and applies the settings; the detector picks up the - /// new allowlist and delays immediately. - pub fn save_settings(&self, settings: Settings) -> Result<(), String> { - settings.validate()?; - settings - .save(&self.settings_path) - .map_err(|e| format!("Einstellungen konnten nicht gespeichert werden: {e}"))?; + /// 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 { + 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}"))?; + } + save(&settings, &self.settings_path)?; lock(&self.detector).set_config(detector_config(&settings)); - *lock(&self.settings) = settings; + *current = settings; + Ok(backend_changed) + } + + /// Client of the configured backend. + pub fn backend_client(&self) -> BackendClient { + BackendClient::new(self.transport.clone(), &self.settings().backend_url) + } + + /// The stored backend key with its expiry. Reads the keyring, so call + /// it off the UI thread. + pub fn backend_key(&self) -> Option { + let key = self + .secrets + .get(Service::Backend) + .filter(|key| !key.trim().is_empty())?; + Some(StoredKey { + key, + expires_at: self.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> { + 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); + }) + } + + /// Takes over whose the stored key is and when it expires, as the + /// backend reports it. + pub fn refresh_backend_login(&self, info: &KeyInfo) -> Result<(), String> { + self.update_settings(|s| { + s.backend_username = Some(info.username.clone()); + s.backend_key_expires_at = Some(info.expires_at); + }) + } + + /// Forgets the backend key (keyring) and its login (settings). + pub fn discard_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; + }) + } + + /// Changes and saves settings the app manages itself; saves only if + /// something changed. + fn update_settings(&self, change: impl FnOnce(&mut Settings)) -> Result<(), String> { + let mut current = lock(&self.settings); + let mut settings = current.clone(); + change(&mut settings); + if settings != *current { + save(&settings, &self.settings_path)?; + *current = settings; + } Ok(()) } @@ -495,6 +566,15 @@ impl AppState { self.store.set_title(id, title).map_err(|e| e.to_string()) } + /// Records that call `id`'s transcript was just uploaded and the CRM + /// gave it `crm_transcript_id`. + pub fn mark_uploaded(&self, id: CallId, crm_transcript_id: &str) -> Result<(), String> { + self.find_call(id)?; + self.store + .set_uploaded(id, crm_transcript_id, Local::now()) + .map_err(|e| format!("Upload konnte nicht vermerkt werden: {e}")) + } + fn find_call(&self, id: CallId) -> Result { self.store .get_call(id) @@ -696,6 +776,12 @@ fn detected_output_target( } } +fn save(settings: &Settings, path: &Path) -> Result<(), String> { + settings + .save(path) + .map_err(|e| format!("Einstellungen konnten nicht gespeichert werden: {e}")) +} + fn output_target(settings: &Settings) -> OutputTarget { match &settings.output_device { Some(id) => OutputTarget::Device(id.clone()), @@ -713,8 +799,9 @@ fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { #[cfg(test)] mod tests { use chrono::TimeZone; + use recorder_core::backend::{KeyInfo, NewKey, StoredKey}; use recorder_core::model::{Segment, Speaker}; - use recorder_core::secrets::MemorySecrets; + use recorder_core::secrets::{MemorySecrets, Service}; use super::*; @@ -1250,10 +1337,130 @@ mod tests { end_after_secs: 30, ..Settings::default() }; - assert_eq!(f.state.save_settings(valid.clone()), Ok(())); + assert_eq!(f.state.save_settings(valid.clone()), Ok(false)); assert_eq!(f.state.settings(), valid); } + fn new_key(key: &str) -> NewKey { + NewKey { + key: key.into(), + expires_at: Local.with_ymd_and_hms(2027, 11, 6, 10, 0, 0).unwrap(), + } + } + + #[test] + fn a_stored_backend_key_comes_with_its_login() { + let f = fixture(); + assert_eq!(f.state.backend_key(), None); + + f.state + .store_backend_key(&new_key("euv_k"), Some("hinrichs".into())) + .unwrap(); + + let expires_at = Local.with_ymd_and_hms(2027, 11, 6, 10, 0, 0).unwrap(); + assert_eq!( + f.state.backend_key(), + Some(StoredKey { + key: "euv_k".into(), + expires_at: Some(expires_at), + }) + ); + let saved = Settings::load(&f.dir.path().join("settings.json")); + assert_eq!(saved.backend_username.as_deref(), Some("hinrichs")); + assert_eq!(saved.backend_key_expires_at, Some(expires_at)); + assert!(!fs::read_to_string(f.dir.path().join("settings.json")) + .unwrap() + .contains("euv_k")); + assert_eq!(f.state.settings(), saved); + } + + #[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(); + let later = Local.with_ymd_and_hms(2028, 1, 1, 0, 0, 0).unwrap(); + + f.state + .refresh_backend_login(&KeyInfo { + label: "l".into(), + hint: "h".into(), + username: "hinrichs".into(), + created_at: later, + expires_at: later, + }) + .unwrap(); + + let settings = f.state.settings(); + assert_eq!(settings.backend_username.as_deref(), Some("hinrichs")); + assert_eq!(settings.backend_key_expires_at, Some(later)); + } + + #[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())) + .unwrap(); + + f.state.discard_backend_key().unwrap(); + + assert_eq!(f.state.backend_key(), None); + assert_eq!(f.state.secrets.get(Service::Backend), None); + let settings = f.state.settings(); + assert_eq!(settings.backend_username, None); + assert_eq!(settings.backend_key_expires_at, None); + } + + #[test] + fn saving_settings_keeps_the_backend_login_unless_the_url_changes() { + let f = fixture(); + f.state + .store_backend_key(&new_key("euv_k"), Some("hinrichs".into())) + .unwrap(); + // The settings page sends what it loaded, maybe before the login. + let edited = Settings { + retention_days: 14, + ..Settings::default() + }; + + assert_eq!(f.state.save_settings(edited.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); + + 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_eq!( + f.state.backend_client().login_url(), + "https://other.example/euvadm" + ); + } + + #[test] + fn an_upload_is_recorded_on_the_call() { + let f = fixture(); + let (id, _, _) = finished_call(&f, "a"); + + f.state.mark_uploaded(id, "4711").unwrap(); + + let call = f.state.store.get_call(id).unwrap().unwrap(); + assert_eq!(call.crm_transcript_id.as_deref(), Some("4711")); + assert!(call.uploaded_at.is_some()); + assert_eq!( + f.state.mark_uploaded(id + 1, "1"), + Err("Gespräch nicht gefunden".to_string()) + ); + } + fn render_session(exe: &str, root_pid: u32, device: &str) -> RenderSession { RenderSession { exe: exe.to_string(), diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index 15bc4db..feac54b 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -15,6 +15,24 @@ 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 +} + +/** Login status for the settings, checked with the backend. */ +export interface BackendStatus { + logged_in: boolean + username: string | null + /** RFC 3339. */ + expires_at: string | null + /** `false` if the key could not be checked; username and expiry are then the stored ones. */ + reachable: boolean + /** Where the admin manages their keys. */ + keys_url: string } export type Service = 'deepscript' @@ -67,6 +85,10 @@ export interface CallListItem { interrupted: boolean /** The name the user gave the call, if any. */ title: string | null + /** The CRM's id of the transcript, from its last upload. */ + crm_transcript_id: string | null + /** When the transcript was last uploaded (RFC 3339). */ + uploaded_at: string | null } /** A transcript line; `speaker_key` is "me" or "remote:". */ @@ -87,7 +109,7 @@ export interface SpeakerMerge { } export interface CallDetail { - call: CallListItem & { error: string | null } + call: CallListItem & { error: string | null; transcribed_at: string | null } /** The transcript with speaker merges applied. */ segments: SegmentView[] /** Renamed speakers by key. */ @@ -144,6 +166,14 @@ 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 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') +export const backendLogout = () => invoke('backend_logout') +/** Opens the backend's key management page in the system browser. */ +export const openBackendKeysPage = () => invoke('open_backend_keys_page') +/** Logs in first if needed; resolves once the CRM has the transcript. */ +export const uploadTranscript = (id: CallId) => invoke('upload_transcript', { id }) export const getUpdate = () => invoke('get_update') /** Resolves only on failure: on success the app restarts. */ export const installUpdate = () => invoke('install_update') @@ -158,6 +188,12 @@ export const onPromptChanged = (handler: () => void): Promise => /** A call's status changed (processing started, done or failed). */ export const onCallUpdated = (handler: (id: CallId) => void): Promise => listen<{ id: CallId }>('call-updated', (event) => handler(event.payload.id)) +/** The backend login changed (logged in, logged out, key discarded). */ +export const onBackendChanged = (handler: () => void): Promise => + listen('backend-changed', () => handler()) +/** Creating the key failed; the login window stays open for another try. */ +export const onBackendLoginError = (handler: (message: string) => void): Promise => + listen<{ message: string }>('backend-login-error', (event) => handler(event.payload.message)) export const onUpdateAvailable = (handler: (info: UpdateInfo) => void): Promise => listen('update-available', (event) => handler(event.payload)) export const onUpdateProgress = ( diff --git a/ui/src/lib/format.ts b/ui/src/lib/format.ts index 77d52d8..08cef0c 100644 --- a/ui/src/lib/format.ts +++ b/ui/src/lib/format.ts @@ -53,3 +53,14 @@ export function formatOffset(secs: number): string { const ss = pad(total % 60) return h > 0 ? `${h}:${mm}:${ss}` : `${mm}:${ss}` } + +/** "06.11.2027". */ +export function formatDate(iso: string): string { + const d = new Date(iso) + return `${pad(d.getDate())}.${pad(d.getMonth() + 1)}.${d.getFullYear()}` +} + +/** "06.11.2026 14:05". */ +export function formatDateTime(iso: string): string { + return `${formatDate(iso)} ${clock(new Date(iso))}` +} diff --git a/ui/src/routes/Main.svelte b/ui/src/routes/Main.svelte index 7024883..0844f8b 100644 --- a/ui/src/routes/Main.svelte +++ b/ui/src/routes/Main.svelte @@ -7,6 +7,7 @@ getRecordingState, listCalls, mergeSpeakers, + onBackendLoginError, onCallEnded, onCallUpdated, onPromptChanged, @@ -18,13 +19,14 @@ startManualRecording, transcribeCall, unmergeSpeaker, + uploadTranscript, type CallDetail, type CallId, type CallListItem, type RecordingState, } from '../lib/api' import CallList from '../lib/CallList.svelte' - import { formatDetailTime, formatMinutes } from '../lib/format' + import { formatDateTime, formatDetailTime, formatMinutes } from '../lib/format' import StatusPill from '../lib/StatusPill.svelte' import TranscriptView from '../lib/TranscriptView.svelte' import UpdateBanner from '../lib/UpdateBanner.svelte' @@ -43,6 +45,12 @@ let actionError = $state('') let busy = $state(false) + // Uploads run per call and may outlive the selection (the login can + // take a while); their errors are kept per call too. + let uploading = $state([]) + let uploadErrors = $state>({}) + let confirmingUpload = $state(false) + let editingTitle = $state(false) let titleDraft = $state('') let savingTitle = $state(false) @@ -98,6 +106,7 @@ actionError = '' editingTitle = false titleError = '' + confirmingUpload = false refreshDetail() } @@ -108,6 +117,7 @@ actionError = '' editingTitle = false titleError = '' + confirmingUpload = false } onMount(() => { @@ -117,6 +127,10 @@ if (id === selectedId) refreshDetail() }), onCallEnded(refreshList), + // Creating the key failed; the login window stays open for another try. + onBackendLoginError((msg) => { + for (const id of uploading) uploadErrors[id] = msg + }), onPromptChanged(refreshList), onRecordingState((state) => { recordingState = state @@ -178,6 +192,31 @@ refreshList() }) + /** "Transkript hochladen"; an upload done before asks first. */ + function uploadClick() { + if (!detail) return + if (detail.call.uploaded_at) confirmingUpload = true + else upload() + } + + /** Uploads the shown call's transcript (logging in first if needed). */ + async function upload() { + if (!detail) return + const id = detail.call.id + confirmingUpload = false + if (uploading.includes(id)) return + uploading = [...uploading, id] + delete uploadErrors[id] + try { + await uploadTranscript(id) + delete uploadErrors[id] + } catch (err) { + uploadErrors[id] = errorText(err) + } finally { + uploading = uploading.filter((u) => u !== id) + } + } + async function rename(speakerKey: string, name: string) { if (!detail) return await renameSpeaker(detail.call.id, speakerKey, name) @@ -303,6 +342,11 @@

{titleError}

{/if}
+ {#if call.status === 'done' && call.uploaded_at} + + Hochgeladen am {formatDateTime(call.uploaded_at)} (ID {call.crm_transcript_id}) + + {/if} {#if call.status === 'awaiting_decision'} @@ -310,16 +354,32 @@ {:else if call.status === 'failed'} + {:else if call.status === 'done' && confirmingUpload} + Dieses Transkript wurde bereits hochgeladen. Nochmal hochladen? + + {:else if call.status === 'done'} - - - + {/if}
{#if shownActionError}

{shownActionError}

{/if} + {#if uploadErrors[call.id]} +

{uploadErrors[call.id]}

+ {/if}
@@ -496,10 +556,17 @@ .actions { display: inline-flex; + align-items: center; + flex-wrap: wrap; gap: 8px; margin-left: auto; } + .uploaded, + .confirm { + font-size: 12px; + } + .detail-header .error { margin: 10px 0 0; } diff --git a/ui/src/routes/Settings.svelte b/ui/src/routes/Settings.svelte index 9bb2c22..1256b21 100644 --- a/ui/src/routes/Settings.svelte +++ b/ui/src/routes/Settings.svelte @@ -1,14 +1,22 @@