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) <noreply@anthropic.com>
329 lines
10 KiB
Rust
329 lines
10 KiB
Rust
//! User settings, persisted as JSON in the app config directory.
|
||
//!
|
||
//! Secrets (API keys) are never part of the settings; they live in the OS
|
||
//! keyring (see [`crate::secrets`]).
|
||
|
||
use std::fs;
|
||
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",
|
||
"teams.exe",
|
||
"microsip.exe",
|
||
"msedge.exe",
|
||
"chrome.exe",
|
||
"firefox.exe",
|
||
];
|
||
|
||
/// Allowed continuous mic use before a call counts as started, in seconds.
|
||
pub const START_AFTER_SECS: RangeInclusive<u64> = 1..=30;
|
||
/// Allowed mic release before a call counts as ended, in seconds. Too short
|
||
/// splits a call, e.g. when the headset is switched.
|
||
pub const END_AFTER_SECS: RangeInclusive<u64> = 3..=120;
|
||
|
||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
||
#[serde(default)]
|
||
pub struct Settings {
|
||
pub allowlist: Vec<String>,
|
||
pub mic_device: Option<String>,
|
||
pub output_device: Option<String>,
|
||
pub language: String,
|
||
pub deepscript_model: String,
|
||
pub retention_days: u32,
|
||
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<String>,
|
||
/// When the stored backend key expires. Set by the app at login.
|
||
pub backend_key_expires_at: Option<DateTime<Local>>,
|
||
}
|
||
|
||
impl Default for Settings {
|
||
fn default() -> Self {
|
||
Self {
|
||
allowlist: DEFAULT_ALLOWLIST.iter().map(|s| s.to_string()).collect(),
|
||
mic_device: None,
|
||
output_device: None,
|
||
language: "de".to_string(),
|
||
deepscript_model: "premium".to_string(),
|
||
retention_days: 7,
|
||
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,
|
||
}
|
||
}
|
||
}
|
||
|
||
impl Settings {
|
||
/// Checks the values the user can type in; the error is shown as is.
|
||
pub fn validate(&self) -> Result<(), String> {
|
||
if !START_AFTER_SECS.contains(&self.start_after_secs) {
|
||
return Err(format!(
|
||
"Start nach: {}–{} Sekunden",
|
||
START_AFTER_SECS.start(),
|
||
START_AFTER_SECS.end()
|
||
));
|
||
}
|
||
if !END_AFTER_SECS.contains(&self.end_after_secs) {
|
||
return Err(format!(
|
||
"Ende nach: {}–{} Sekunden",
|
||
END_AFTER_SECS.start(),
|
||
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 {
|
||
fs::read_to_string(path)
|
||
.ok()
|
||
.and_then(|json| serde_json::from_str(&json).ok())
|
||
.unwrap_or_default()
|
||
}
|
||
|
||
/// Writes the settings file (creating its directory), replacing the old
|
||
/// file atomically so a crash never leaves a half-written file behind.
|
||
pub fn save(&self, path: &Path) -> io::Result<()> {
|
||
if let Some(dir) = path.parent() {
|
||
fs::create_dir_all(dir)?;
|
||
}
|
||
let json = serde_json::to_string_pretty(self).map_err(io::Error::other)?;
|
||
let tmp = path.with_extension("json.tmp");
|
||
fs::write(&tmp, json)?;
|
||
fs::rename(&tmp, path)
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn settings_default_values() {
|
||
let s = Settings::default();
|
||
assert_eq!(
|
||
s.allowlist,
|
||
vec![
|
||
"ms-teams.exe",
|
||
"teams.exe",
|
||
"microsip.exe",
|
||
"msedge.exe",
|
||
"chrome.exe",
|
||
"firefox.exe"
|
||
]
|
||
);
|
||
assert_eq!(s.mic_device, None);
|
||
assert_eq!(s.output_device, None);
|
||
assert_eq!(s.language, "de");
|
||
assert_eq!(s.deepscript_model, "premium");
|
||
assert_eq!(s.retention_days, 7);
|
||
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]
|
||
fn validate_accepts_the_defaults_and_the_bounds() {
|
||
assert_eq!(Settings::default().validate(), Ok(()));
|
||
for (start, end) in [(1, 3), (30, 120)] {
|
||
let s = Settings {
|
||
start_after_secs: start,
|
||
end_after_secs: end,
|
||
..Settings::default()
|
||
};
|
||
assert_eq!(s.validate(), Ok(()), "start {start}, end {end}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn validate_rejects_start_after_out_of_range() {
|
||
for start in [0, 31] {
|
||
let s = Settings {
|
||
start_after_secs: start,
|
||
..Settings::default()
|
||
};
|
||
assert_eq!(s.validate(), Err("Start nach: 1–30 Sekunden".to_string()));
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn validate_rejects_end_after_out_of_range() {
|
||
for end in [2, 121] {
|
||
let s = Settings {
|
||
end_after_secs: end,
|
||
..Settings::default()
|
||
};
|
||
assert_eq!(s.validate(), Err("Ende nach: 3–120 Sekunden".to_string()));
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn settings_load_missing_file_returns_default() {
|
||
let dir = tempfile::tempdir().unwrap();
|
||
assert_eq!(
|
||
Settings::load(&dir.path().join("settings.json")),
|
||
Settings::default()
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn settings_load_corrupt_file_returns_default() {
|
||
let dir = tempfile::tempdir().unwrap();
|
||
let path = dir.path().join("settings.json");
|
||
fs::write(&path, "{ not json").unwrap();
|
||
assert_eq!(Settings::load(&path), Settings::default());
|
||
}
|
||
|
||
#[test]
|
||
fn settings_load_partial_json_fills_defaults() {
|
||
let dir = tempfile::tempdir().unwrap();
|
||
let path = dir.path().join("settings.json");
|
||
fs::write(&path, r#"{"retention_days": 30, "mic_device": "headset"}"#).unwrap();
|
||
let s = Settings::load(&path);
|
||
assert_eq!(s.retention_days, 30);
|
||
assert_eq!(s.mic_device.as_deref(), Some("headset"));
|
||
assert_eq!(
|
||
s,
|
||
Settings {
|
||
retention_days: 30,
|
||
mic_device: Some("headset".into()),
|
||
..Settings::default()
|
||
}
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn settings_save_then_load_roundtrips() {
|
||
let dir = tempfile::tempdir().unwrap();
|
||
let path = dir.path().join("nested").join("settings.json");
|
||
let s = Settings {
|
||
allowlist: vec!["zoom.exe".into()],
|
||
output_device: Some("speakers".into()),
|
||
autostart: false,
|
||
..Settings::default()
|
||
};
|
||
s.save(&path).unwrap();
|
||
assert_eq!(Settings::load(&path), s);
|
||
}
|
||
}
|