//! Link to the euvino admin backend: the login window that turns the //! admin's browser session into an API key, the login status for the //! settings, and the upload of a call's transcript. //! //! The login window shows the backend's own login page, a remote origin: it //! has no Tauri capability (see `capabilities/default.json`), so the page //! cannot invoke any command. It runs in incognito mode, so the session //! never outlives the window. After each page load on the backend the app //! reads the window's cookies for the backend and uses them for the one //! request that creates a key. Neither the cookies nor the key are ever //! logged; the key is stored only in the keyring. use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Mutex; use async_trait::async_trait; use chrono::{DateTime, Local}; use recorder_core::backend::{self, BackendClient, KeyCheck, Login, LoginStep, NewKey}; use recorder_core::model::CallId; use serde::Serialize; use tauri::webview::PageLoadEvent; use tauri::{ AppHandle, Emitter, Manager, State, Url, WebviewUrl, WebviewWindow, WebviewWindowBuilder, WindowEvent, }; use tauri_plugin_opener::OpenerExt; use tokio::sync::oneshot; use crate::processing; use crate::state::AppState; // The backend this build talks to: the one place to change it. It is not a // setting; a key created on one backend is never sent to another. /// Release builds: the production euvino admin backend. pub(crate) const RELEASE_BACKEND_URL: &str = "https://backend.euvinopro.eu"; /// Debug builds (`cargo tauri dev`) always use the test backend, never the /// production one. `pub(crate)`: `state.rs` tests the exact test-backend → /// release-backend transition against this value (a key bound to one must /// never work for the other). pub(crate) const DEV_BACKEND_URL: &str = "https://test.euvinopro.eu"; /// The backend of this build (no trailing slash). pub const BACKEND_URL: &str = if cfg!(debug_assertions) { DEV_BACKEND_URL } else { RELEASE_BACKEND_URL }; /// Label of the login window. pub const LOGIN_WINDOW: &str = "backend-login"; const CANCELLED: &str = "Anmeldung abgebrochen"; type CmdResult = 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_server`: the backend of this build. #[derive(Serialize, Clone, Debug, PartialEq)] pub struct BackendServer { pub base_url: String, /// Where the admin manages their keys. pub keys_url: String, } /// Answer of `backend_status`. #[derive(Serialize, Clone, Debug, PartialEq)] pub struct BackendStatus { pub logged_in: bool, pub username: Option, pub expires_at: Option>, /// `false` if the stored key could not be checked; username and expiry /// are then the stored ones. pub reachable: bool, } /// Payload of `backend-login-error`: creating the key failed, the login /// window stays open for another try. #[derive(Serialize, Clone)] struct LoginError { message: String, } /// The backend this build talks to, for the settings (no network). #[tauri::command] pub fn backend_server(state: State<'_, AppState>) -> BackendServer { BackendServer { base_url: state.backend_url().to_string(), keys_url: state.backend_client().keys_page_url(), } } /// Whether a backend key is stored, and whose it is: checked with the /// backend. A key the backend refuses, or one of another backend, is /// discarded. #[tauri::command] pub async fn backend_status(app: AppHandle) -> CmdResult { 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, }; let Some(stored) = stored else { return Ok(status); }; match client.check_key(&stored.key).await { KeyCheck::Valid(info) => { state.refresh_backend_login(&info)?; status.logged_in = true; status.username = Some(info.username); status.expires_at = Some(info.expires_at); } KeyCheck::Invalid => { log::info!("backend: the stored key was refused, discarding it"); let refused = stored.key; blocking(&app, move |state| { state.discard_refused_backend_key(&refused) }) .await?; } KeyCheck::Unknown(e) => { log::info!( "backend: could not check the stored key: {}", e.user_message() ); let settings = state.settings(); status.logged_in = true; status.username = settings.backend_username; status.expires_at = settings.backend_key_expires_at; status.reachable = false; } } Ok(status) } /// "Anmelden": runs the login in the login window (a new key replaces the /// stored one). #[tauri::command] pub async fn backend_login(app: AppHandle) -> CmdResult<()> { login(&app).await.map(|_key| ()) } /// "Abmelden": forgets the key locally (it stays valid on the server until /// the admin deletes it there or it expires). #[tauri::command] pub async fn backend_logout(app: AppHandle) -> CmdResult<()> { blocking(&app, |state| state.discard_backend_key()).await?; emit_changed(&app); Ok(()) } /// Opens the backend's key management page in the system browser. #[tauri::command] pub fn open_backend_keys_page(app: AppHandle) -> CmdResult<()> { let url = app.state::().backend_client().keys_page_url(); app.opener() .open_url(url, None::<&str>) .map_err(|e| format!("Browser konnte nicht geöffnet werden: {e}")) } /// "Transkript hochladen": uploads the call's transcript as the user sees /// it, logging in first if needed, and records the CRM's id on the call. /// One upload per call at a time; `call-updated` tells the views when it /// starts and ends. #[tauri::command] pub async fn upload_transcript(app: AppHandle, id: CallId) -> CmdResult<()> { let state = app.state::(); let claim = state.claim_upload(id)?; processing::emit_updated(&app, id); let result = upload(&app, &state, id).await; drop(claim); processing::emit_updated(&app, id); result } async fn upload(app: &AppHandle, state: &AppState, id: CallId) -> CmdResult<()> { let detail = state.call_detail(id)?; if detail.call.transcribed_at.is_none() { return Err("Das Gespräch ist noch nicht transkribiert".to_string()); } let text = detail.upload_text()?; let client = state.backend_client(); let stored = blocking(app, |state| Ok(state.backend_key())).await?; let login = AppLogin { app: app.clone() }; let crm_id = backend::upload_with_login(&client, &login, stored, Local::now(), &text) .await .inspect_err(|e| log::warn!("call {id}: upload failed: {e}"))?; log::info!("call {id}: transcript uploaded (CRM id {crm_id})"); if let Err(e) = state.mark_uploaded(id, &crm_id) { // The CRM already has it: a retry must never send it again, even // though the row itself still shows no crm_transcript_id. state.note_upload_confirmed_but_unsaved(id); log::error!("call {id}: uploaded (CRM id {crm_id}) but could not save locally: {e}"); return Err(unsaved_upload_message(&crm_id, &e)); } Ok(()) } /// Message for an upload that reached the CRM (`crm_id`) but whose local /// record (`mark_uploaded`) failed with `e`: names the CRM id so the user /// can find it there, and says plainly not to upload the call again (the /// app also refuses on its own, see `AppState::note_upload_confirmed_but_unsaved`). fn unsaved_upload_message(crm_id: &str, e: &str) -> String { format!("Hochgeladen (ID {crm_id}), aber lokal nicht gespeichert: {e} – nicht erneut hochladen") } /// [`Login`] through the login window, for the upload. struct AppLogin { app: AppHandle, } #[async_trait] impl Login for AppLogin { async fn login(&self) -> Result { login(&self.app).await } async fn discard_key(&self, refused: &str) { let refused = refused.to_string(); match blocking(&self.app, move |state| { state.discard_refused_backend_key(&refused) }) .await { Ok(true) => { log::info!("backend: the key was refused, discarded it"); emit_changed(&self.app); } Ok(false) => log::info!("backend: the refused key was already replaced"), Err(e) => log::error!("backend: {e}"), } } } /// Runs the login in the login window, or waits for the one already /// running (and brings its window to the front). Returns the new key, /// already stored. pub async fn login(app: &AppHandle) -> LoginResult { let waiters = app.state::(); 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 message = format!("{message} – bitte die Seite im Anmeldefenster neu laden"); let _ = app.emit_to("main", "backend-login-error", LoginError { message }); } } }); } /// Creates a key with the cookies the login window holds for the backend. /// The cookies are used for this one request and dropped. async fn try_create_key(client: &BackendClient, window: &WebviewWindow) -> LoginStep { let Ok(url) = Url::parse(&client.keys_page_url()) else { return LoginStep::Wait; }; // Off the async runtime: on Windows reading cookies blocks until the // main thread answers. let reader = window.clone(); let cookies = tauri::async_runtime::spawn_blocking(move || reader.cookies_for_url(url)).await; let cookies = match cookies { Ok(Ok(cookies)) => cookies, Ok(Err(e)) => return LoginStep::Retry(format!("Anmeldedaten nicht lesbar: {e}")), Err(e) => return LoginStep::Retry(format!("Anmeldedaten nicht lesbar: {e}")), }; if cookies.is_empty() { return LoginStep::Wait; } let cookie_header = cookies .iter() .map(|cookie| format!("{}={}", cookie.name(), cookie.value())) .collect::>() .join("; "); let label = backend::key_label(hostname().as_deref()); LoginStep::of(client.create_key(&cookie_header, &label).await) } /// Stores a new key with whose it is (asked from the backend; left empty if /// that fails) and its expiry. async fn store_key(app: &AppHandle, client: &BackendClient, key: &NewKey) -> Result<(), String> { let username = match client.key_info(&key.key).await { Ok(info) => Some(info.username), Err(e) => { log::warn!( "backend: could not ask whose the new key is: {}", e.user_message() ); None } }; let (key, base_url) = (key.clone(), client.base_url().to_string()); blocking(app, move |state| { state.store_backend_key(&key, &base_url, username) }) .await?; log::info!("backend: logged in, key stored"); Ok(()) } /// The computer's name, for the key's label. fn hostname() -> Option { 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 backend_urls_have_no_trailing_slash_and_use_https() { for url in [RELEASE_BACKEND_URL, DEV_BACKEND_URL] { assert!(!url.ends_with('/'), "{url}"); assert!(url.starts_with("https://"), "{url}"); } // Release and dev talk to different backends: a key from one must // never be usable on the other (see AppState::backend_key). assert_ne!(RELEASE_BACKEND_URL, DEV_BACKEND_URL); } #[test] fn the_unsaved_upload_message_names_the_crm_id_and_warns_against_retrying() { assert_eq!( unsaved_upload_message("4711", "disk full"), "Hochgeladen (ID 4711), aber lokal nicht gespeichert: disk full – nicht erneut hochladen" ); } #[test] fn everyone_waiting_gets_the_one_login_result() { let waiters = LoginWaiters::default(); assert!(!waiters.waiting()); let (first, starts) = waiters.join(); let (second, starts_again) = waiters.join(); assert!(starts); assert!(!starts_again); assert!(waiters.waiting()); waiters.finish(Ok("euv_k".into())); assert_eq!(first.blocking_recv().unwrap(), Ok("euv_k".to_string())); assert_eq!(second.blocking_recv().unwrap(), Ok("euv_k".to_string())); assert!(!waiters.waiting()); } #[test] fn a_finished_login_leaves_the_next_one_to_start_anew() { let waiters = LoginWaiters::default(); let (first, _) = waiters.join(); waiters.finish(Err(CANCELLED.into())); // A late "window destroyed" reaches nobody. waiters.finish(Err("ignored".into())); assert_eq!(first.blocking_recv().unwrap(), Err(CANCELLED.to_string())); let (next, starts) = waiters.join(); assert!(starts); waiters.finish(Ok("euv_new".into())); assert_eq!(next.blocking_recv().unwrap(), Ok("euv_new".to_string())); } #[test] fn only_one_key_is_created_at_a_time() { let waiters = LoginWaiters::default(); let claim = waiters.claim_creating(); assert!(claim.is_some()); assert!(waiters.claim_creating().is_none()); drop(claim); assert!(waiters.claim_creating().is_some()); } }