feat #14740: settings, keyring, tray and manual recording
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Generated
+1086
-12
File diff suppressed because it is too large
Load Diff
@@ -16,6 +16,7 @@ thiserror = "1.0"
|
|||||||
rubato = "0.15"
|
rubato = "0.15"
|
||||||
flacenc = "0.5"
|
flacenc = "0.5"
|
||||||
hound = "3.5"
|
hound = "3.5"
|
||||||
|
keyring = { version = "3", features = ["windows-native", "sync-secret-service", "crypto-rust"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempfile = "3"
|
tempfile = "3"
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
//! PulseAudio on Linux). The [`Recorder`](crate::recorder::Recorder) only sees
|
//! PulseAudio on Linux). The [`Recorder`](crate::recorder::Recorder) only sees
|
||||||
//! this trait, which keeps it testable with fake sources.
|
//! this trait, which keeps it testable with fake sources.
|
||||||
|
|
||||||
|
use serde::Serialize;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
/// Format of the interleaved `f32` samples a [`CaptureSource`] delivers.
|
/// Format of the interleaved `f32` samples a [`CaptureSource`] delivers.
|
||||||
@@ -28,14 +29,14 @@ pub enum OutputTarget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// One audio endpoint as shown in the device picker.
|
/// One audio endpoint as shown in the device picker.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||||
pub struct DeviceInfo {
|
pub struct DeviceInfo {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Available capture inputs (microphones) and outputs (render endpoints).
|
/// Available capture inputs (microphones) and outputs (render endpoints).
|
||||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
|
||||||
pub struct Devices {
|
pub struct Devices {
|
||||||
pub inputs: Vec<DeviceInfo>,
|
pub inputs: Vec<DeviceInfo>,
|
||||||
pub outputs: Vec<DeviceInfo>,
|
pub outputs: Vec<DeviceInfo>,
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ pub mod capture;
|
|||||||
pub mod model;
|
pub mod model;
|
||||||
pub mod recorder;
|
pub mod recorder;
|
||||||
pub mod retention;
|
pub mod retention;
|
||||||
|
pub mod secrets;
|
||||||
|
pub mod settings;
|
||||||
pub mod store;
|
pub mod store;
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
//! API keys, stored only in the OS keyring (Windows Credential Manager,
|
||||||
|
//! Linux Secret Service) under the service `eu.euvino.callrecorder`.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use thiserror::Error;
|
||||||
|
|
||||||
|
/// Keyring service name all keys are stored under.
|
||||||
|
pub const KEYRING_SERVICE: &str = "eu.euvino.callrecorder";
|
||||||
|
|
||||||
|
/// The external services whose API keys the app keeps.
|
||||||
|
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum Service {
|
||||||
|
DeepScript,
|
||||||
|
Anthropic,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Service {
|
||||||
|
/// Keyring user name of this service's entry.
|
||||||
|
pub fn user(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Service::DeepScript => "deepscript",
|
||||||
|
Service::Anthropic => "anthropic",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum SecretError {
|
||||||
|
#[error("Schlüsselbund-Fehler: {0}")]
|
||||||
|
Keyring(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type Result<T> = std::result::Result<T, SecretError>;
|
||||||
|
|
||||||
|
pub trait SecretStore: Send + Sync {
|
||||||
|
/// The stored key, or `None` if there is none (or the keyring cannot be
|
||||||
|
/// read).
|
||||||
|
fn get(&self, s: Service) -> Option<String>;
|
||||||
|
fn set(&self, s: Service, v: &str) -> Result<()>;
|
||||||
|
/// Removes the key; removing a key that does not exist is not an error.
|
||||||
|
fn delete(&self, s: Service) -> Result<()>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The OS keyring.
|
||||||
|
pub struct KeyringSecrets;
|
||||||
|
|
||||||
|
impl KeyringSecrets {
|
||||||
|
fn entry(s: Service) -> Result<keyring::Entry> {
|
||||||
|
keyring::Entry::new(KEYRING_SERVICE, s.user())
|
||||||
|
.map_err(|e| SecretError::Keyring(e.to_string()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SecretStore for KeyringSecrets {
|
||||||
|
fn get(&self, s: Service) -> Option<String> {
|
||||||
|
Self::entry(s).ok()?.get_password().ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set(&self, s: Service, v: &str) -> Result<()> {
|
||||||
|
Self::entry(s)?
|
||||||
|
.set_password(v)
|
||||||
|
.map_err(|e| SecretError::Keyring(e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn delete(&self, s: Service) -> Result<()> {
|
||||||
|
match Self::entry(s)?.delete_credential() {
|
||||||
|
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
|
||||||
|
Err(e) => Err(SecretError::Keyring(e.to_string())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// In-memory secret store for tests.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct MemorySecrets {
|
||||||
|
keys: Mutex<HashMap<Service, String>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SecretStore for MemorySecrets {
|
||||||
|
fn get(&self, s: Service) -> Option<String> {
|
||||||
|
self.keys.lock().unwrap().get(&s).cloned()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set(&self, s: Service, v: &str) -> Result<()> {
|
||||||
|
self.keys.lock().unwrap().insert(s, v.to_string());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn delete(&self, s: Service) -> Result<()> {
|
||||||
|
self.keys.lock().unwrap().remove(&s);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn memory_secrets_roundtrip() {
|
||||||
|
let secrets = MemorySecrets::default();
|
||||||
|
assert_eq!(secrets.get(Service::DeepScript), None);
|
||||||
|
|
||||||
|
secrets.set(Service::DeepScript, "ds-key").unwrap();
|
||||||
|
assert_eq!(secrets.get(Service::DeepScript).as_deref(), Some("ds-key"));
|
||||||
|
assert_eq!(secrets.get(Service::Anthropic), None);
|
||||||
|
|
||||||
|
secrets.delete(Service::DeepScript).unwrap();
|
||||||
|
assert_eq!(secrets.get(Service::DeepScript), None);
|
||||||
|
secrets.delete(Service::DeepScript).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn service_serializes_as_keyring_user() {
|
||||||
|
for s in [Service::DeepScript, Service::Anthropic] {
|
||||||
|
let json = serde_json::to_string(&s).unwrap();
|
||||||
|
assert_eq!(json, format!("\"{}\"", s.user()));
|
||||||
|
assert_eq!(serde_json::from_str::<Service>(&json).unwrap(), s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
//! 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::path::Path;
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// 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",
|
||||||
|
];
|
||||||
|
|
||||||
|
#[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,
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Settings {
|
||||||
|
/// 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -162,6 +162,17 @@ impl Store {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Sets the track file paths, for callers that derive them from the
|
||||||
|
/// call id and so can only know them after [`Store::create_call`].
|
||||||
|
pub fn set_paths(&self, id: CallId, mic_path: &Path, out_path: &Path) -> Result<()> {
|
||||||
|
let conn = self.conn.lock().unwrap();
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE calls SET mic_path = ?1, out_path = ?2 WHERE id = ?3",
|
||||||
|
params![path_to_str(mic_path)?, path_to_str(out_path)?, id],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn set_status(&self, id: CallId, status: CallStatus, error: Option<&str>) -> Result<()> {
|
pub fn set_status(&self, id: CallId, status: CallStatus, error: Option<&str>) -> Result<()> {
|
||||||
let conn = self.conn.lock().unwrap();
|
let conn = self.conn.lock().unwrap();
|
||||||
conn.execute(
|
conn.execute(
|
||||||
@@ -495,7 +506,7 @@ fn speaker_from_key(key: &str) -> Result<Speaker> {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use std::path::Path;
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
use chrono::Local;
|
use chrono::Local;
|
||||||
|
|
||||||
@@ -744,6 +755,22 @@ mod tests {
|
|||||||
assert_eq!(recovered.ended_at, Some(original_ended_at));
|
assert_eq!(recovered.ended_at, Some(original_ended_at));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn set_paths_updates_track_paths() {
|
||||||
|
let store = Store::open_in_memory().unwrap();
|
||||||
|
let id = store
|
||||||
|
.create_call("Manuell", Local::now(), Path::new(""), Path::new(""))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
store
|
||||||
|
.set_paths(id, Path::new("/rec/1-mic.wav"), Path::new("/rec/1-out.wav"))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let call = store.get_call(id).unwrap().unwrap();
|
||||||
|
assert_eq!(call.mic_path, PathBuf::from("/rec/1-mic.wav"));
|
||||||
|
assert_eq!(call.out_path, PathBuf::from("/rec/1-out.wav"));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn delete_call_cascades() {
|
fn delete_call_cascades() {
|
||||||
let store = Store::open_in_memory().unwrap();
|
let store = Store::open_in_memory().unwrap();
|
||||||
|
|||||||
@@ -17,5 +17,11 @@ tauri-build = { version = "2.7.4", features = [] }
|
|||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
tauri = { version = "2.12.5", features = [] }
|
tauri = { version = "2.12.5", features = ["tray-icon"] }
|
||||||
tauri-plugin-log = "2"
|
tauri-plugin-log = "2"
|
||||||
|
tauri-plugin-autostart = "2"
|
||||||
|
tauri-plugin-single-instance = "2"
|
||||||
|
chrono = { version = "0.4", features = ["serde"] }
|
||||||
|
tempfile = "3"
|
||||||
|
recorder-core = { path = "../crates/core" }
|
||||||
|
recorder-audio = { path = "../crates/audio" }
|
||||||
|
|||||||
+1
-1
@@ -1,3 +1,3 @@
|
|||||||
fn main() {
|
fn main() {
|
||||||
tauri_build::build()
|
tauri_build::build()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,201 @@
|
|||||||
|
//! Tauri commands and the UI side effects of recording (windows, events).
|
||||||
|
//!
|
||||||
|
//! The handlers stay thin: the work happens in [`AppState`]. Anything that
|
||||||
|
//! blocks (audio devices, stopping a recorder, the keyring) runs on the
|
||||||
|
//! blocking pool so the UI thread never waits on it.
|
||||||
|
|
||||||
|
use std::thread;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use recorder_core::capture::Devices;
|
||||||
|
use recorder_core::model::CallId;
|
||||||
|
use recorder_core::secrets::Service;
|
||||||
|
use recorder_core::settings::Settings;
|
||||||
|
use tauri::{AppHandle, Emitter, Manager, State};
|
||||||
|
use tauri_plugin_autostart::ManagerExt;
|
||||||
|
|
||||||
|
use crate::state::{AppState, DeviceLevels, RecordingState};
|
||||||
|
|
||||||
|
const LEVELS_INTERVAL: Duration = Duration::from_millis(100);
|
||||||
|
|
||||||
|
type CmdResult<T> = Result<T, String>;
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn get_settings(state: State<'_, AppState>) -> Settings {
|
||||||
|
state.settings()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stores `key` in the keyring; an empty key deletes the entry.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn set_api_key(app: AppHandle, service: Service, key: String) -> CmdResult<()> {
|
||||||
|
blocking(app, move |app| {
|
||||||
|
let secrets = &app.state::<AppState>().secrets;
|
||||||
|
let key = key.trim();
|
||||||
|
let result = if key.is_empty() {
|
||||||
|
secrets.delete(service)
|
||||||
|
} else {
|
||||||
|
secrets.set(service, key)
|
||||||
|
};
|
||||||
|
result.map_err(|e| e.to_string())
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a key is stored. Never returns the key itself.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn has_api_key(app: AppHandle, service: Service) -> CmdResult<bool> {
|
||||||
|
blocking(app, move |app| {
|
||||||
|
let key = app.state::<AppState>().secrets.get(service);
|
||||||
|
Ok(key.is_some_and(|key| !key.is_empty()))
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn list_devices() -> CmdResult<Devices> {
|
||||||
|
tauri::async_runtime::spawn_blocking(recorder_audio::list_devices)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn test_devices(app: AppHandle) -> CmdResult<DeviceLevels> {
|
||||||
|
blocking(app, |app| app.state::<AppState>().test_devices()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn get_recording_state(state: State<'_, AppState>) -> RecordingState {
|
||||||
|
state.recording_state()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn start_manual_recording(app: AppHandle) -> CmdResult<CallId> {
|
||||||
|
blocking(app, start_manual).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn stop_recording(app: AppHandle) -> CmdResult<()> {
|
||||||
|
blocking(app, stop).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn discard_current_recording(app: AppHandle) -> CmdResult<()> {
|
||||||
|
blocking(app, discard).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts a manual recording, shows the floating window and streams levels.
|
||||||
|
pub fn start_manual(app: &AppHandle) -> CmdResult<CallId> {
|
||||||
|
let state = app.state::<AppState>().start_manual_recording()?;
|
||||||
|
let RecordingState::Recording { call_id, .. } = state else {
|
||||||
|
return Err("Aufnahme wurde nicht gestartet".to_string());
|
||||||
|
};
|
||||||
|
spawn_level_emitter(app.clone(), call_id);
|
||||||
|
set_window_visible(app, "recorder", true);
|
||||||
|
emit_state(app, &state);
|
||||||
|
Ok(call_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stops the current recording and hides the floating window.
|
||||||
|
pub fn stop(app: &AppHandle) -> CmdResult<()> {
|
||||||
|
let result = app.state::<AppState>().stop_recording();
|
||||||
|
set_window_visible(app, "recorder", false);
|
||||||
|
emit_state(app, &RecordingState::Idle);
|
||||||
|
result.map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Throws the current recording away and hides the floating window.
|
||||||
|
pub fn discard(app: &AppHandle) -> CmdResult<()> {
|
||||||
|
let result = app.state::<AppState>().discard_current_recording();
|
||||||
|
set_window_visible(app, "recorder", false);
|
||||||
|
emit_state(app, &RecordingState::Idle);
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Enables or disables launching at login. Debug builds leave the login
|
||||||
|
/// items alone so `cargo tauri dev` never registers a dev binary.
|
||||||
|
pub fn apply_autostart(app: &AppHandle, enabled: bool) {
|
||||||
|
if cfg!(debug_assertions) {
|
||||||
|
log::info!("debug build: not changing autostart (wanted {enabled})");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let autolaunch = app.autolaunch();
|
||||||
|
let result = if enabled {
|
||||||
|
autolaunch.enable()
|
||||||
|
} else {
|
||||||
|
autolaunch.disable()
|
||||||
|
};
|
||||||
|
if let Err(e) = result {
|
||||||
|
log::error!("could not apply autostart={enabled}: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn show_main(app: &AppHandle) {
|
||||||
|
if let Some(window) = app.get_webview_window("main") {
|
||||||
|
let _ = window.unminimize();
|
||||||
|
let _ = window.show();
|
||||||
|
let _ = window.set_focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Brings back the floating window if the user closed it mid-recording.
|
||||||
|
pub fn show_recorder_if_recording(app: &AppHandle) {
|
||||||
|
if matches!(
|
||||||
|
app.state::<AppState>().recording_state(),
|
||||||
|
RecordingState::Recording { .. }
|
||||||
|
) {
|
||||||
|
set_window_visible(app, "recorder", true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Emits `levels` every 100 ms until `call_id` stops being the current
|
||||||
|
/// recording.
|
||||||
|
fn spawn_level_emitter(app: AppHandle, call_id: CallId) {
|
||||||
|
thread::spawn(move || loop {
|
||||||
|
thread::sleep(LEVELS_INTERVAL);
|
||||||
|
let Some(levels) = app.state::<AppState>().levels(call_id) else {
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
let _ = app.emit("levels", levels);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit_state(app: &AppHandle, state: &RecordingState) {
|
||||||
|
if let Err(e) = app.emit("recording-state", state) {
|
||||||
|
log::error!("could not emit recording-state: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_window_visible(app: &AppHandle, label: &str, visible: bool) {
|
||||||
|
if let Some(window) = app.get_webview_window(label) {
|
||||||
|
let result = if visible {
|
||||||
|
window.show()
|
||||||
|
} else {
|
||||||
|
window.hide()
|
||||||
|
};
|
||||||
|
if let Err(e) = result {
|
||||||
|
log::error!("could not change visibility of window {label}: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn blocking<T, F>(app: AppHandle, f: F) -> CmdResult<T>
|
||||||
|
where
|
||||||
|
T: Send + 'static,
|
||||||
|
F: FnOnce(&AppHandle) -> CmdResult<T> + Send + 'static,
|
||||||
|
{
|
||||||
|
tauri::async_runtime::spawn_blocking(move || f(&app))
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
}
|
||||||
+78
-13
@@ -1,16 +1,81 @@
|
|||||||
|
mod commands;
|
||||||
|
mod state;
|
||||||
|
mod tray;
|
||||||
|
|
||||||
|
use recorder_core::secrets::KeyringSecrets;
|
||||||
|
use recorder_core::store::Store;
|
||||||
|
use tauri::{Manager, WindowEvent};
|
||||||
|
use tauri_plugin_autostart::MacosLauncher;
|
||||||
|
|
||||||
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
/// Command-line flag the login item starts the app with; the main window
|
||||||
|
/// then stays hidden in the tray.
|
||||||
|
const AUTOSTART_ARG: &str = "--autostart";
|
||||||
|
|
||||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||||
pub fn run() {
|
pub fn run() {
|
||||||
tauri::Builder::default()
|
tauri::Builder::default()
|
||||||
.setup(|app| {
|
// Must be registered first: a second launch only focuses the first.
|
||||||
if cfg!(debug_assertions) {
|
.plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| {
|
||||||
app.handle().plugin(
|
commands::show_main(app);
|
||||||
tauri_plugin_log::Builder::default()
|
}))
|
||||||
.level(log::LevelFilter::Info)
|
.plugin(tauri_plugin_autostart::init(
|
||||||
.build(),
|
MacosLauncher::LaunchAgent,
|
||||||
)?;
|
Some(vec![AUTOSTART_ARG]),
|
||||||
}
|
))
|
||||||
Ok(())
|
.setup(|app| {
|
||||||
})
|
if cfg!(debug_assertions) {
|
||||||
.run(tauri::generate_context!())
|
app.handle().plugin(
|
||||||
.expect("error while building tauri application");
|
tauri_plugin_log::Builder::default()
|
||||||
|
.level(log::LevelFilter::Info)
|
||||||
|
.build(),
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let data_dir = app.path().app_data_dir()?;
|
||||||
|
let config_dir = app.path().app_config_dir()?;
|
||||||
|
std::fs::create_dir_all(&data_dir)?;
|
||||||
|
let store = Store::open(&data_dir.join("calls.sqlite"))?;
|
||||||
|
let recovery = store.startup_recovery()?;
|
||||||
|
log::info!("startup recovery: {recovery:?}");
|
||||||
|
|
||||||
|
let state = AppState::new(
|
||||||
|
store,
|
||||||
|
Box::new(KeyringSecrets),
|
||||||
|
config_dir.join("settings.json"),
|
||||||
|
data_dir.join("recordings"),
|
||||||
|
);
|
||||||
|
let autostart = state.settings().autostart;
|
||||||
|
app.manage(state);
|
||||||
|
commands::apply_autostart(app.handle(), autostart);
|
||||||
|
|
||||||
|
tray::create(app.handle())?;
|
||||||
|
if !std::env::args().any(|arg| arg == AUTOSTART_ARG) {
|
||||||
|
commands::show_main(app.handle());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.on_window_event(|window, event| {
|
||||||
|
// Closing a window only hides it; the app keeps running in the
|
||||||
|
// tray (for call detection) until "Beenden".
|
||||||
|
if let WindowEvent::CloseRequested { api, .. } = event {
|
||||||
|
api.prevent_close();
|
||||||
|
let _ = window.hide();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.invoke_handler(tauri::generate_handler![
|
||||||
|
commands::get_settings,
|
||||||
|
commands::save_settings,
|
||||||
|
commands::set_api_key,
|
||||||
|
commands::has_api_key,
|
||||||
|
commands::list_devices,
|
||||||
|
commands::test_devices,
|
||||||
|
commands::get_recording_state,
|
||||||
|
commands::start_manual_recording,
|
||||||
|
commands::stop_recording,
|
||||||
|
commands::discard_current_recording,
|
||||||
|
])
|
||||||
|
.run(tauri::generate_context!())
|
||||||
|
.expect("error while building tauri application");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,5 +2,5 @@
|
|||||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
call_recorder_lib::run();
|
call_recorder_lib::run();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,279 @@
|
|||||||
|
//! Application state shared by commands, the tray and background threads.
|
||||||
|
//!
|
||||||
|
//! Holds the store, the settings, the secret store and the recording that is
|
||||||
|
//! currently running. Everything here is independent of windows and events;
|
||||||
|
//! the command layer turns results into UI updates.
|
||||||
|
|
||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::sync::{Mutex, MutexGuard};
|
||||||
|
use std::thread;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use chrono::{DateTime, Local};
|
||||||
|
use recorder_core::capture::OutputTarget;
|
||||||
|
use recorder_core::model::{CallId, CallStatus};
|
||||||
|
use recorder_core::recorder::Recorder;
|
||||||
|
use recorder_core::secrets::SecretStore;
|
||||||
|
use recorder_core::settings::Settings;
|
||||||
|
use recorder_core::store::Store;
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
/// `app` value of calls started from the tray or UI instead of detection.
|
||||||
|
const MANUAL_APP: &str = "Manuell";
|
||||||
|
/// How long [`AppState::test_devices`] records.
|
||||||
|
const TEST_DURATION: Duration = Duration::from_secs(5);
|
||||||
|
const TEST_POLL: Duration = Duration::from_millis(50);
|
||||||
|
|
||||||
|
/// Payload of the `recording-state` event.
|
||||||
|
#[derive(Serialize, Clone, Debug)]
|
||||||
|
#[serde(tag = "state", rename_all = "lowercase")]
|
||||||
|
pub enum RecordingState {
|
||||||
|
Idle,
|
||||||
|
Recording {
|
||||||
|
call_id: CallId,
|
||||||
|
app: String,
|
||||||
|
started_at: DateTime<Local>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Payload of the `levels` event.
|
||||||
|
#[derive(Serialize, Clone, Debug)]
|
||||||
|
pub struct Levels {
|
||||||
|
pub mic: f32,
|
||||||
|
pub out: f32,
|
||||||
|
pub failed_tracks: Vec<&'static str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Result of [`AppState::test_devices`]: peak rms level per track.
|
||||||
|
#[derive(Serialize, Clone, Copy, Debug)]
|
||||||
|
pub struct DeviceLevels {
|
||||||
|
pub mic: f32,
|
||||||
|
pub out: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct CurrentRecording {
|
||||||
|
call_id: CallId,
|
||||||
|
app: String,
|
||||||
|
started_at: DateTime<Local>,
|
||||||
|
recorder: Recorder,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct AppState {
|
||||||
|
pub store: Store,
|
||||||
|
pub secrets: Box<dyn SecretStore>,
|
||||||
|
settings: Mutex<Settings>,
|
||||||
|
settings_path: PathBuf,
|
||||||
|
recordings_dir: PathBuf,
|
||||||
|
current: Mutex<Option<CurrentRecording>>,
|
||||||
|
/// 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,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Releases [`AppState::devices_busy`] when dropped.
|
||||||
|
struct DevicesClaim<'a>(&'a AtomicBool);
|
||||||
|
|
||||||
|
impl Drop for DevicesClaim<'_> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.0.store(false, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppState {
|
||||||
|
pub fn new(
|
||||||
|
store: Store,
|
||||||
|
secrets: Box<dyn SecretStore>,
|
||||||
|
settings_path: PathBuf,
|
||||||
|
recordings_dir: PathBuf,
|
||||||
|
) -> Self {
|
||||||
|
let settings = Settings::load(&settings_path);
|
||||||
|
Self {
|
||||||
|
store,
|
||||||
|
secrets,
|
||||||
|
settings: Mutex::new(settings),
|
||||||
|
settings_path,
|
||||||
|
recordings_dir,
|
||||||
|
current: Mutex::new(None),
|
||||||
|
devices_busy: AtomicBool::new(false),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn settings(&self) -> Settings {
|
||||||
|
lock(&self.settings).clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save_settings(&self, settings: Settings) -> Result<(), String> {
|
||||||
|
settings
|
||||||
|
.save(&self.settings_path)
|
||||||
|
.map_err(|e| format!("Einstellungen konnten nicht gespeichert werden: {e}"))?;
|
||||||
|
*lock(&self.settings) = settings;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn recording_state(&self) -> RecordingState {
|
||||||
|
match lock(&self.current).as_ref() {
|
||||||
|
Some(cur) => RecordingState::Recording {
|
||||||
|
call_id: cur.call_id,
|
||||||
|
app: cur.app.clone(),
|
||||||
|
started_at: cur.started_at,
|
||||||
|
},
|
||||||
|
None => RecordingState::Idle,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Levels of the recording `call_id`, or `None` once it is no longer
|
||||||
|
/// the current recording.
|
||||||
|
pub fn levels(&self, call_id: CallId) -> Option<Levels> {
|
||||||
|
let current = lock(&self.current);
|
||||||
|
let cur = current.as_ref().filter(|cur| cur.call_id == call_id)?;
|
||||||
|
let (mic, out) = cur.recorder.levels();
|
||||||
|
Some(Levels {
|
||||||
|
mic,
|
||||||
|
out,
|
||||||
|
failed_tracks: cur.recorder.failed_tracks(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a call row and starts recording the configured mic and
|
||||||
|
/// output device into `recordings/<id>-mic.wav` / `<id>-out.wav`.
|
||||||
|
pub fn start_manual_recording(&self) -> Result<RecordingState, String> {
|
||||||
|
let _claim = self.claim_devices("Es läuft bereits eine Aufnahme")?;
|
||||||
|
let settings = self.settings();
|
||||||
|
fs::create_dir_all(&self.recordings_dir)
|
||||||
|
.map_err(|e| format!("Aufnahmeordner konnte nicht angelegt werden: {e}"))?;
|
||||||
|
|
||||||
|
let started_at = Local::now();
|
||||||
|
let call_id = self
|
||||||
|
.store
|
||||||
|
.create_call(MANUAL_APP, started_at, Path::new(""), Path::new(""))
|
||||||
|
.map_err(|e| format!("Gespräch konnte nicht angelegt werden: {e}"))?;
|
||||||
|
let (mic_path, out_path) = self.track_paths(call_id);
|
||||||
|
|
||||||
|
let started = self
|
||||||
|
.store
|
||||||
|
.set_paths(call_id, &mic_path, &out_path)
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
.and_then(|()| {
|
||||||
|
let mic = recorder_audio::mic_source(settings.mic_device.as_deref());
|
||||||
|
let out = recorder_audio::output_source(output_target(&settings));
|
||||||
|
Recorder::start(mic, out, &mic_path, &out_path).map_err(|e| e.to_string())
|
||||||
|
});
|
||||||
|
let recorder = match started {
|
||||||
|
Ok(recorder) => recorder,
|
||||||
|
Err(err) => {
|
||||||
|
if let Err(e) = self.store.delete_call(call_id) {
|
||||||
|
log::error!("could not delete call {call_id} after failed start: {e}");
|
||||||
|
}
|
||||||
|
return Err(format!("Aufnahme konnte nicht gestartet werden: {err}"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
*lock(&self.current) = Some(CurrentRecording {
|
||||||
|
call_id,
|
||||||
|
app: MANUAL_APP.to_string(),
|
||||||
|
started_at,
|
||||||
|
recorder,
|
||||||
|
});
|
||||||
|
Ok(self.recording_state())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stops the current recording and finalizes its row. Returns `Ok(false)`
|
||||||
|
/// if nothing was recording. A recorder error still finishes the row and
|
||||||
|
/// marks the call as failed.
|
||||||
|
pub fn stop_recording(&self) -> Result<bool, String> {
|
||||||
|
let Some(cur) = lock(&self.current).take() else {
|
||||||
|
return Ok(false);
|
||||||
|
};
|
||||||
|
let result = cur.recorder.stop();
|
||||||
|
let id = cur.call_id;
|
||||||
|
self.store
|
||||||
|
.finish_recording(id, Local::now(), false)
|
||||||
|
.map_err(|e| format!("Gespräch konnte nicht gespeichert werden: {e}"))?;
|
||||||
|
if let Err(err) = result {
|
||||||
|
let msg = format!("Aufnahme fehlerhaft: {err}");
|
||||||
|
if let Err(e) = self.store.set_status(id, CallStatus::Failed, Some(&msg)) {
|
||||||
|
log::error!("could not mark call {id} as failed: {e}");
|
||||||
|
}
|
||||||
|
return Err(msg);
|
||||||
|
}
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Discards the current recording: deletes both WAVs and the call row.
|
||||||
|
pub fn discard_current_recording(&self) -> Result<(), String> {
|
||||||
|
let Some(cur) = lock(&self.current).take() else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
cur.recorder.discard();
|
||||||
|
self.store
|
||||||
|
.delete_call(cur.call_id)
|
||||||
|
.map_err(|e| format!("Gespräch konnte nicht gelöscht werden: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Records both configured devices into a temporary directory for five
|
||||||
|
/// seconds and returns the peak level of each track.
|
||||||
|
pub fn test_devices(&self) -> Result<DeviceLevels, String> {
|
||||||
|
let _claim = self.claim_devices("Während einer Aufnahme ist kein Test möglich")?;
|
||||||
|
let settings = self.settings();
|
||||||
|
let dir = tempfile::tempdir()
|
||||||
|
.map_err(|e| format!("Testordner konnte nicht angelegt werden: {e}"))?;
|
||||||
|
let mic = recorder_audio::mic_source(settings.mic_device.as_deref());
|
||||||
|
let out = recorder_audio::output_source(output_target(&settings));
|
||||||
|
let recorder = Recorder::start(
|
||||||
|
mic,
|
||||||
|
out,
|
||||||
|
&dir.path().join("test-mic.wav"),
|
||||||
|
&dir.path().join("test-out.wav"),
|
||||||
|
)
|
||||||
|
.map_err(|e| format!("Test fehlgeschlagen: {e}"))?;
|
||||||
|
|
||||||
|
let mut peak = DeviceLevels { mic: 0.0, out: 0.0 };
|
||||||
|
let until = Instant::now() + TEST_DURATION;
|
||||||
|
while Instant::now() < until {
|
||||||
|
thread::sleep(TEST_POLL);
|
||||||
|
let (mic, out) = recorder.levels();
|
||||||
|
peak.mic = peak.mic.max(mic);
|
||||||
|
peak.out = peak.out.max(out);
|
||||||
|
}
|
||||||
|
recorder.discard();
|
||||||
|
Ok(peak)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reserves the audio devices for a recording start or a test. Fails
|
||||||
|
/// with `recording_msg` while a recording runs.
|
||||||
|
fn claim_devices(&self, recording_msg: &str) -> Result<DevicesClaim<'_>, String> {
|
||||||
|
if self.devices_busy.swap(true, Ordering::SeqCst) {
|
||||||
|
return Err("Die Audiogeräte werden gerade getestet oder gestartet".to_string());
|
||||||
|
}
|
||||||
|
let claim = DevicesClaim(&self.devices_busy);
|
||||||
|
// Checked after claiming: a start that just finished has already
|
||||||
|
// stored its recording before releasing the claim.
|
||||||
|
if lock(&self.current).is_some() {
|
||||||
|
return Err(recording_msg.to_string());
|
||||||
|
}
|
||||||
|
Ok(claim)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn track_paths(&self, id: CallId) -> (PathBuf, PathBuf) {
|
||||||
|
(
|
||||||
|
self.recordings_dir.join(format!("{id}-mic.wav")),
|
||||||
|
self.recordings_dir.join(format!("{id}-out.wav")),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn output_target(settings: &Settings) -> OutputTarget {
|
||||||
|
match &settings.output_device {
|
||||||
|
Some(id) => OutputTarget::Device(id.clone()),
|
||||||
|
None => OutputTarget::DefaultRender,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Locks ignoring poisoning: a panic in one command must not wedge the app.
|
||||||
|
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||||
|
mutex
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
//! Tray icon with "Öffnen", "Aufnahme manuell starten" and "Beenden".
|
||||||
|
|
||||||
|
use std::thread;
|
||||||
|
|
||||||
|
use tauri::menu::{Menu, MenuItem, PredefinedMenuItem};
|
||||||
|
use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};
|
||||||
|
use tauri::{AppHandle, Manager};
|
||||||
|
|
||||||
|
use crate::commands;
|
||||||
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
const OPEN: &str = "open";
|
||||||
|
const RECORD: &str = "record";
|
||||||
|
const QUIT: &str = "quit";
|
||||||
|
|
||||||
|
pub fn create(app: &AppHandle) -> tauri::Result<()> {
|
||||||
|
let menu = Menu::with_items(
|
||||||
|
app,
|
||||||
|
&[
|
||||||
|
&MenuItem::with_id(app, OPEN, "Öffnen", true, None::<&str>)?,
|
||||||
|
&MenuItem::with_id(app, RECORD, "Aufnahme manuell starten", true, None::<&str>)?,
|
||||||
|
&PredefinedMenuItem::separator(app)?,
|
||||||
|
&MenuItem::with_id(app, QUIT, "Beenden", true, None::<&str>)?,
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
|
||||||
|
let mut builder = TrayIconBuilder::with_id("main")
|
||||||
|
.tooltip("Gesprächsrekorder")
|
||||||
|
.menu(&menu)
|
||||||
|
.show_menu_on_left_click(false)
|
||||||
|
.on_menu_event(|app, event| match event.id().as_ref() {
|
||||||
|
OPEN => {
|
||||||
|
commands::show_main(app);
|
||||||
|
commands::show_recorder_if_recording(app);
|
||||||
|
}
|
||||||
|
RECORD => {
|
||||||
|
// Opening the audio devices can take a moment; keep the
|
||||||
|
// event loop free.
|
||||||
|
let app = app.clone();
|
||||||
|
thread::spawn(move || {
|
||||||
|
if let Err(e) = commands::start_manual(&app) {
|
||||||
|
log::error!("manual recording from tray failed: {e}");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
QUIT => quit(app),
|
||||||
|
_ => {}
|
||||||
|
})
|
||||||
|
.on_tray_icon_event(|tray, event| {
|
||||||
|
if let TrayIconEvent::Click {
|
||||||
|
button: MouseButton::Left,
|
||||||
|
button_state: MouseButtonState::Up,
|
||||||
|
..
|
||||||
|
} = event
|
||||||
|
{
|
||||||
|
commands::show_main(tray.app_handle());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if let Some(icon) = app.default_window_icon() {
|
||||||
|
builder = builder.icon(icon.clone());
|
||||||
|
}
|
||||||
|
builder.build(app)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finalizes a running recording, then exits.
|
||||||
|
fn quit(app: &AppHandle) {
|
||||||
|
let app = app.clone();
|
||||||
|
thread::spawn(move || {
|
||||||
|
if let Err(e) = app.state::<AppState>().stop_recording() {
|
||||||
|
log::error!("stopping the recording on quit failed: {e}");
|
||||||
|
}
|
||||||
|
app.exit(0);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -17,10 +17,12 @@
|
|||||||
"width": 1000,
|
"width": 1000,
|
||||||
"height": 680,
|
"height": 680,
|
||||||
"resizable": true,
|
"resizable": true,
|
||||||
"fullscreen": false
|
"fullscreen": false,
|
||||||
|
"visible": false
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"label": "recorder",
|
"label": "recorder",
|
||||||
|
"title": "Gesprächsrekorder",
|
||||||
"url": "index.html#/recorder",
|
"url": "index.html#/recorder",
|
||||||
"width": 300,
|
"width": 300,
|
||||||
"height": 200,
|
"height": 200,
|
||||||
@@ -30,6 +32,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"label": "prompt",
|
"label": "prompt",
|
||||||
|
"title": "Gespräch beendet",
|
||||||
"url": "index.html#/prompt",
|
"url": "index.html#/prompt",
|
||||||
"width": 340,
|
"width": 340,
|
||||||
"height": 180,
|
"height": 180,
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="en">
|
<html lang="de">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
|
|||||||
+34
-3
@@ -1,3 +1,34 @@
|
|||||||
<main>
|
<script lang="ts">
|
||||||
<h1>Gesprächsrekorder</h1>
|
import { onMount } from 'svelte'
|
||||||
</main>
|
import Recorder from './routes/Recorder.svelte'
|
||||||
|
import Settings from './routes/Settings.svelte'
|
||||||
|
|
||||||
|
let route = $state(currentRoute())
|
||||||
|
|
||||||
|
function currentRoute(): string {
|
||||||
|
return window.location.hash.replace(/^#/, '') || '/'
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
const update = () => (route = currentRoute())
|
||||||
|
window.addEventListener('hashchange', update)
|
||||||
|
return () => window.removeEventListener('hashchange', update)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if route === '/recorder'}
|
||||||
|
<Recorder />
|
||||||
|
{:else if route === '/settings'}
|
||||||
|
<Settings />
|
||||||
|
{:else if route === '/prompt'}
|
||||||
|
<main class="page">
|
||||||
|
<p class="muted">Gespräch beendet.</p>
|
||||||
|
</main>
|
||||||
|
{:else}
|
||||||
|
<main class="page">
|
||||||
|
<header class="page-header">
|
||||||
|
<h1>Gesprächsrekorder</h1>
|
||||||
|
<a class="btn" href="#/settings" title="Einstellungen">⚙ Einstellungen</a>
|
||||||
|
</header>
|
||||||
|
</main>
|
||||||
|
{/if}
|
||||||
|
|||||||
+162
-23
@@ -1,40 +1,179 @@
|
|||||||
:root {
|
:root {
|
||||||
--text: #6b6375;
|
--text: #1d2330;
|
||||||
--text-h: #08060d;
|
--muted: #6b7280;
|
||||||
--bg: #fff;
|
--bg: #f5f6f9;
|
||||||
|
--surface: #fff;
|
||||||
|
--border: #e2e4ea;
|
||||||
|
--control-border: #cfd3dc;
|
||||||
|
--primary: #3b5bdb;
|
||||||
|
--primary-soft: #eef2ff;
|
||||||
|
--rec: #c62828;
|
||||||
|
--rec-soft: #fde8e8;
|
||||||
|
--ok: #1e7b34;
|
||||||
|
--ok-soft: #e6f4ea;
|
||||||
|
--meter-bg: #e8eaf0;
|
||||||
|
|
||||||
font: 18px/145% system-ui, 'Segoe UI', Roboto, sans-serif;
|
font: 14px/1.45 'Segoe UI', system-ui, -apple-system, Roboto, sans-serif;
|
||||||
color-scheme: light dark;
|
|
||||||
color: var(--text);
|
color: var(--text);
|
||||||
background: var(--bg);
|
background: var(--bg);
|
||||||
font-synthesis: none;
|
color-scheme: light;
|
||||||
text-rendering: optimizeLegibility;
|
|
||||||
-webkit-font-smoothing: antialiased;
|
-webkit-font-smoothing: antialiased;
|
||||||
-moz-osx-font-smoothing: grayscale;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (prefers-color-scheme: dark) {
|
* {
|
||||||
:root {
|
box-sizing: border-box;
|
||||||
--text: #9ca3af;
|
|
||||||
--text-h: #f3f4f6;
|
|
||||||
--bg: #16171d;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
|
background: var(--bg);
|
||||||
}
|
}
|
||||||
|
|
||||||
h1 {
|
h1 {
|
||||||
font-family: inherit;
|
font-size: 20px;
|
||||||
font-weight: 500;
|
font-weight: 600;
|
||||||
color: var(--text-h);
|
margin: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
main {
|
h2 {
|
||||||
display: flex;
|
font-size: 12px;
|
||||||
min-height: 100svh;
|
font-weight: 600;
|
||||||
place-content: center;
|
color: var(--muted);
|
||||||
place-items: center;
|
text-transform: uppercase;
|
||||||
text-align: center;
|
letter-spacing: 0.04em;
|
||||||
|
margin: 0 0 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
a {
|
||||||
|
color: var(--primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.page {
|
||||||
|
max-width: 760px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 20px 24px 32px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 16px;
|
||||||
|
margin-bottom: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.muted {
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
color: var(--rec);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
padding: 6px 14px;
|
||||||
|
border-radius: 6px;
|
||||||
|
border: 1px solid var(--control-border);
|
||||||
|
background: var(--surface);
|
||||||
|
color: var(--text);
|
||||||
|
font: inherit;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
text-decoration: none;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn:hover:not(:disabled) {
|
||||||
|
border-color: var(--primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn:disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn.primary {
|
||||||
|
background: var(--primary);
|
||||||
|
border-color: var(--primary);
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn.danger {
|
||||||
|
color: var(--rec);
|
||||||
|
border-color: #f0b4b4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn.small {
|
||||||
|
padding: 3px 10px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pill {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-radius: 999px;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pill.rec {
|
||||||
|
background: var(--rec-soft);
|
||||||
|
color: var(--rec);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pill.ok {
|
||||||
|
background: var(--ok-soft);
|
||||||
|
color: var(--ok);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pill.missing {
|
||||||
|
background: #eee;
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
.meter {
|
||||||
|
height: 6px;
|
||||||
|
border-radius: 3px;
|
||||||
|
background: var(--meter-bg);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.meter > div {
|
||||||
|
height: 100%;
|
||||||
|
background: linear-gradient(90deg, #37b24d, #f59f00);
|
||||||
|
transition: width 90ms linear;
|
||||||
|
}
|
||||||
|
|
||||||
|
input,
|
||||||
|
select {
|
||||||
|
font: inherit;
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--text);
|
||||||
|
padding: 5px 8px;
|
||||||
|
border: 1px solid var(--control-border);
|
||||||
|
border-radius: 6px;
|
||||||
|
background: var(--surface);
|
||||||
|
}
|
||||||
|
|
||||||
|
input:focus,
|
||||||
|
select:focus {
|
||||||
|
outline: 2px solid var(--primary-soft);
|
||||||
|
border-color: var(--primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
font-size: 13px;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
// Typed wrappers around the Tauri commands and events of the app shell.
|
||||||
|
|
||||||
|
import { invoke } from '@tauri-apps/api/core'
|
||||||
|
import { listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||||
|
|
||||||
|
export type CallId = number
|
||||||
|
|
||||||
|
export interface Settings {
|
||||||
|
allowlist: string[]
|
||||||
|
mic_device: string | null
|
||||||
|
output_device: string | null
|
||||||
|
language: string
|
||||||
|
deepscript_model: string
|
||||||
|
retention_days: number
|
||||||
|
autostart: boolean
|
||||||
|
start_after_secs: number
|
||||||
|
end_after_secs: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Service = 'deepscript' | 'anthropic'
|
||||||
|
|
||||||
|
export interface DeviceInfo {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Devices {
|
||||||
|
inputs: DeviceInfo[]
|
||||||
|
outputs: DeviceInfo[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DeviceLevels {
|
||||||
|
mic: number
|
||||||
|
out: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Track = 'mic' | 'out'
|
||||||
|
|
||||||
|
export type RecordingState =
|
||||||
|
| { state: 'idle' }
|
||||||
|
| { state: 'recording'; call_id: CallId; app: string; started_at: string }
|
||||||
|
|
||||||
|
export interface Levels {
|
||||||
|
mic: number
|
||||||
|
out: number
|
||||||
|
failed_tracks: Track[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getSettings = () => invoke<Settings>('get_settings')
|
||||||
|
export const saveSettings = (settings: Settings) => invoke<void>('save_settings', { settings })
|
||||||
|
export const setApiKey = (service: Service, key: string) =>
|
||||||
|
invoke<void>('set_api_key', { service, key })
|
||||||
|
export const hasApiKey = (service: Service) => invoke<boolean>('has_api_key', { service })
|
||||||
|
export const listDevices = () => invoke<Devices>('list_devices')
|
||||||
|
export const testDevices = () => invoke<DeviceLevels>('test_devices')
|
||||||
|
export const getRecordingState = () => invoke<RecordingState>('get_recording_state')
|
||||||
|
export const startManualRecording = () => invoke<CallId>('start_manual_recording')
|
||||||
|
export const stopRecording = () => invoke<void>('stop_recording')
|
||||||
|
export const discardCurrentRecording = () => invoke<void>('discard_current_recording')
|
||||||
|
|
||||||
|
export const onRecordingState = (handler: (state: RecordingState) => void): Promise<UnlistenFn> =>
|
||||||
|
listen<RecordingState>('recording-state', (event) => handler(event.payload))
|
||||||
|
export const onLevels = (handler: (levels: Levels) => void): Promise<UnlistenFn> =>
|
||||||
|
listen<Levels>('levels', (event) => handler(event.payload))
|
||||||
|
|
||||||
|
/** Maps an rms level (0..1) to a meter fill (0..1) on a -60..0 dB scale. */
|
||||||
|
export function meterFill(level: number): number {
|
||||||
|
if (level <= 0) return 0
|
||||||
|
const db = 20 * Math.log10(level)
|
||||||
|
return Math.min(1, Math.max(0, (db + 60) / 60))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Error text of a rejected command. */
|
||||||
|
export function errorText(err: unknown): string {
|
||||||
|
return typeof err === 'string' ? err : err instanceof Error ? err.message : String(err)
|
||||||
|
}
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount } from 'svelte'
|
||||||
|
import {
|
||||||
|
discardCurrentRecording,
|
||||||
|
errorText,
|
||||||
|
getRecordingState,
|
||||||
|
meterFill,
|
||||||
|
onLevels,
|
||||||
|
onRecordingState,
|
||||||
|
stopRecording,
|
||||||
|
type Levels,
|
||||||
|
type RecordingState,
|
||||||
|
type Track,
|
||||||
|
} from '../lib/api'
|
||||||
|
|
||||||
|
let recording = $state<RecordingState>({ state: 'idle' })
|
||||||
|
let levels = $state<Levels>({ mic: 0, out: 0, failed_tracks: [] })
|
||||||
|
let now = $state(Date.now())
|
||||||
|
let busy = $state(false)
|
||||||
|
let error = $state('')
|
||||||
|
|
||||||
|
const tracks: { track: Track; label: string; failed: string }[] = [
|
||||||
|
{ track: 'mic', label: 'Mikrofon (ich)', failed: '⚠ Mikrofonspur ausgefallen' },
|
||||||
|
{ track: 'out', label: 'Lautsprecher (Gegenseite)', failed: '⚠ Lautsprecherspur ausgefallen' },
|
||||||
|
]
|
||||||
|
|
||||||
|
let elapsed = $derived(
|
||||||
|
recording.state === 'recording'
|
||||||
|
? formatElapsed(now - new Date(recording.started_at).getTime())
|
||||||
|
: '00:00',
|
||||||
|
)
|
||||||
|
|
||||||
|
function formatElapsed(ms: number): string {
|
||||||
|
const total = Math.max(0, Math.floor(ms / 1000))
|
||||||
|
const mm = String(Math.floor(total / 60)).padStart(2, '0')
|
||||||
|
const ss = String(total % 60).padStart(2, '0')
|
||||||
|
return `${mm}:${ss}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function setRecording(state: RecordingState) {
|
||||||
|
recording = state
|
||||||
|
if (state.state === 'recording') {
|
||||||
|
levels = { mic: 0, out: 0, failed_tracks: [] }
|
||||||
|
error = ''
|
||||||
|
busy = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
const unlisten = [onRecordingState(setRecording), onLevels((l) => (levels = l))]
|
||||||
|
getRecordingState().then(setRecording)
|
||||||
|
const timer = setInterval(() => (now = Date.now()), 1000)
|
||||||
|
return () => {
|
||||||
|
clearInterval(timer)
|
||||||
|
unlisten.forEach((p) => p.then((off) => off()))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
async function run(action: () => Promise<void>) {
|
||||||
|
busy = true
|
||||||
|
error = ''
|
||||||
|
try {
|
||||||
|
await action()
|
||||||
|
} catch (err) {
|
||||||
|
error = errorText(err)
|
||||||
|
} finally {
|
||||||
|
busy = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<main class="recorder">
|
||||||
|
<div class="status">
|
||||||
|
<span class="pill rec">● Aufnahme läuft</span>
|
||||||
|
<span class="muted">
|
||||||
|
{recording.state === 'recording' ? recording.app : ''} · {elapsed}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#each tracks as { track, label, failed } (track)}
|
||||||
|
<div class="track">
|
||||||
|
<div class="label">{label}</div>
|
||||||
|
<div class="meter"><div style:width="{meterFill(levels[track]) * 100}%"></div></div>
|
||||||
|
{#if levels.failed_tracks.includes(track)}
|
||||||
|
<div class="failed">{failed}</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
|
||||||
|
<div class="actions">
|
||||||
|
<button class="btn" disabled={busy} onclick={() => run(stopRecording)}>■ Stopp</button>
|
||||||
|
<button class="btn danger" disabled={busy} onclick={() => run(discardCurrentRecording)}>
|
||||||
|
Verwerfen
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{#if error}
|
||||||
|
<div class="error">{error}</div>
|
||||||
|
{/if}
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
:global(body:has(.recorder)) {
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recorder {
|
||||||
|
min-height: 100vh;
|
||||||
|
background: var(--surface);
|
||||||
|
padding: 8px 12px;
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1.3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status .muted {
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
.track {
|
||||||
|
margin-top: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.label {
|
||||||
|
font-size: 11px;
|
||||||
|
color: var(--muted);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
margin-bottom: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.failed {
|
||||||
|
font-size: 11px;
|
||||||
|
color: var(--rec);
|
||||||
|
margin-top: 1px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
margin-top: 9px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,336 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount } from 'svelte'
|
||||||
|
import {
|
||||||
|
errorText,
|
||||||
|
getSettings,
|
||||||
|
hasApiKey,
|
||||||
|
listDevices,
|
||||||
|
meterFill,
|
||||||
|
saveSettings,
|
||||||
|
setApiKey,
|
||||||
|
testDevices,
|
||||||
|
type DeviceInfo,
|
||||||
|
type DeviceLevels,
|
||||||
|
type Devices,
|
||||||
|
type Service,
|
||||||
|
type Settings,
|
||||||
|
} from '../lib/api'
|
||||||
|
|
||||||
|
const services: { id: Service; name: string }[] = [
|
||||||
|
{ id: 'deepscript', name: 'DeepScript' },
|
||||||
|
{ id: 'anthropic', name: 'Anthropic (Claude)' },
|
||||||
|
]
|
||||||
|
|
||||||
|
let settings = $state<Settings | null>(null)
|
||||||
|
let devices = $state<Devices>({ inputs: [], outputs: [] })
|
||||||
|
let keySaved = $state<Record<Service, boolean>>({ deepscript: false, anthropic: false })
|
||||||
|
let keyInput = $state<Record<Service, string>>({ deepscript: '', anthropic: '' })
|
||||||
|
let newApp = $state('')
|
||||||
|
let testing = $state(false)
|
||||||
|
let testResult = $state<DeviceLevels | null>(null)
|
||||||
|
let message = $state('')
|
||||||
|
let error = $state('')
|
||||||
|
|
||||||
|
onMount(load)
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
try {
|
||||||
|
settings = await getSettings()
|
||||||
|
for (const { id } of services) keySaved[id] = await hasApiKey(id)
|
||||||
|
devices = await listDevices()
|
||||||
|
} catch (err) {
|
||||||
|
error = errorText(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The device list plus the saved device if it is currently unavailable. */
|
||||||
|
function withSaved(list: DeviceInfo[], saved: string | null): DeviceInfo[] {
|
||||||
|
if (saved === null || list.some((d) => d.id === saved)) return list
|
||||||
|
return [...list, { id: saved, name: `${saved} (nicht verfügbar)` }]
|
||||||
|
}
|
||||||
|
|
||||||
|
async function run(action: () => Promise<void>, done = '') {
|
||||||
|
message = ''
|
||||||
|
error = ''
|
||||||
|
try {
|
||||||
|
await action()
|
||||||
|
message = done
|
||||||
|
} catch (err) {
|
||||||
|
error = errorText(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function storeKey(service: Service, key: string) {
|
||||||
|
return run(async () => {
|
||||||
|
await setApiKey(service, key)
|
||||||
|
keySaved[service] = await hasApiKey(service)
|
||||||
|
keyInput[service] = ''
|
||||||
|
}, key ? 'Schlüssel gespeichert' : 'Schlüssel entfernt')
|
||||||
|
}
|
||||||
|
|
||||||
|
function addApp() {
|
||||||
|
const name = newApp.trim().toLowerCase()
|
||||||
|
if (settings && name && !settings.allowlist.includes(name)) {
|
||||||
|
settings.allowlist = [...settings.allowlist, name]
|
||||||
|
}
|
||||||
|
newApp = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeApp(name: string) {
|
||||||
|
if (settings) settings.allowlist = settings.allowlist.filter((a) => a !== name)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function persist() {
|
||||||
|
if (!settings) return
|
||||||
|
if (!Number.isInteger(settings.retention_days) || settings.retention_days < 1) {
|
||||||
|
throw 'Aufbewahrung: bitte eine ganze Zahl ab 1 eingeben'
|
||||||
|
}
|
||||||
|
await saveSettings($state.snapshot(settings))
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runTest() {
|
||||||
|
testing = true
|
||||||
|
testResult = null
|
||||||
|
await run(async () => {
|
||||||
|
await persist()
|
||||||
|
testResult = await testDevices()
|
||||||
|
})
|
||||||
|
testing = false
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<main class="page">
|
||||||
|
<header class="page-header">
|
||||||
|
<h1>Einstellungen</h1>
|
||||||
|
<a class="btn" href="#/">← Zurück</a>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{#if settings}
|
||||||
|
<section class="card">
|
||||||
|
<h2>API-Schlüssel</h2>
|
||||||
|
{#each services as { id, name } (id)}
|
||||||
|
<div class="key-row">
|
||||||
|
<span class="key-name">{name}</span>
|
||||||
|
{#if keySaved[id]}
|
||||||
|
<span class="pill ok">gespeichert ✓</span>
|
||||||
|
{:else}
|
||||||
|
<span class="pill missing">fehlt</span>
|
||||||
|
{/if}
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
placeholder={keySaved[id] ? 'Neuen Schlüssel eingeben' : 'Schlüssel eingeben'}
|
||||||
|
autocomplete="off"
|
||||||
|
bind:value={keyInput[id]}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
class="btn small"
|
||||||
|
disabled={!keyInput[id].trim()}
|
||||||
|
onclick={() => storeKey(id, keyInput[id])}>Speichern</button
|
||||||
|
>
|
||||||
|
{#if keySaved[id]}
|
||||||
|
<button class="btn small danger" onclick={() => storeKey(id, '')}>Entfernen</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card">
|
||||||
|
<h2>Audio</h2>
|
||||||
|
<div class="grid">
|
||||||
|
<label for="mic">Mikrofon</label>
|
||||||
|
<select id="mic" bind:value={settings.mic_device}>
|
||||||
|
<option value={null}>Standardgerät</option>
|
||||||
|
{#each withSaved(devices.inputs, settings.mic_device) as d (d.id)}
|
||||||
|
<option value={d.id}>{d.name}</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
<label for="out">Lautsprecher</label>
|
||||||
|
<select id="out" bind:value={settings.output_device}>
|
||||||
|
<option value={null}>Standardgerät</option>
|
||||||
|
{#each withSaved(devices.outputs, settings.output_device) as d (d.id)}
|
||||||
|
<option value={d.id}>{d.name}</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<p class="hint">
|
||||||
|
Bitte mit Headset telefonieren – sonst landet die Gegenseite auch auf der Mikrofonspur.
|
||||||
|
</p>
|
||||||
|
<div class="test">
|
||||||
|
<button class="btn" disabled={testing} onclick={runTest}>
|
||||||
|
{testing ? 'Test läuft …' : 'Test'}
|
||||||
|
</button>
|
||||||
|
<span class="muted">
|
||||||
|
{testing
|
||||||
|
? 'Bitte 5 Sekunden sprechen und etwas abspielen.'
|
||||||
|
: 'Nimmt 5 Sekunden auf und zeigt den Pegel beider Spuren.'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{#if testResult}
|
||||||
|
<div class="levels">
|
||||||
|
<span>Mikrofon</span>
|
||||||
|
<div class="meter"><div style:width="{meterFill(testResult.mic) * 100}%"></div></div>
|
||||||
|
<span>Lautsprecher</span>
|
||||||
|
<div class="meter"><div style:width="{meterFill(testResult.out) * 100}%"></div></div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card">
|
||||||
|
<h2>Gesprächserkennung</h2>
|
||||||
|
<p class="muted">Programme, deren Mikrofonnutzung als Gespräch zählt:</p>
|
||||||
|
<ul class="allowlist">
|
||||||
|
{#each settings.allowlist as name (name)}
|
||||||
|
<li>
|
||||||
|
<span>{name}</span>
|
||||||
|
<button class="remove" title="Entfernen" onclick={() => removeApp(name)}>✕</button>
|
||||||
|
</li>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
<form
|
||||||
|
class="add"
|
||||||
|
onsubmit={(e) => {
|
||||||
|
e.preventDefault()
|
||||||
|
addApp()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<input placeholder="z. B. zoom.exe" bind:value={newApp} />
|
||||||
|
<button class="btn small" type="submit" disabled={!newApp.trim()}>Hinzufügen</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card">
|
||||||
|
<h2>Allgemein</h2>
|
||||||
|
<div class="grid">
|
||||||
|
<label for="language">Sprache der Gespräche</label>
|
||||||
|
<select id="language" bind:value={settings.language}>
|
||||||
|
<option value="de">Deutsch</option>
|
||||||
|
<option value="en">Englisch</option>
|
||||||
|
</select>
|
||||||
|
<label for="retention">Aufbewahrung der Audiodateien</label>
|
||||||
|
<span><input id="retention" type="number" min="1" bind:value={settings.retention_days} /> Tage</span>
|
||||||
|
<label for="autostart">Beim Anmelden starten</label>
|
||||||
|
<input id="autostart" type="checkbox" bind:checked={settings.autostart} />
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="footer">
|
||||||
|
<button class="btn primary" onclick={() => run(persist, 'Einstellungen gespeichert ✓')}>
|
||||||
|
Speichern
|
||||||
|
</button>
|
||||||
|
{#if message}<span class="saved">{message}</span>{/if}
|
||||||
|
{#if error}<span class="error">{error}</span>{/if}
|
||||||
|
</div>
|
||||||
|
{:else if error}
|
||||||
|
<p class="error">{error}</p>
|
||||||
|
{/if}
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.key-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.key-name {
|
||||||
|
width: 150px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.key-row input {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 220px 1fr;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.grid select {
|
||||||
|
max-width: 380px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.grid input[type='number'] {
|
||||||
|
width: 70px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.grid input[type='checkbox'] {
|
||||||
|
justify-self: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hint {
|
||||||
|
margin: 12px 0;
|
||||||
|
padding: 8px 10px;
|
||||||
|
border-radius: 6px;
|
||||||
|
background: #fff4d6;
|
||||||
|
color: #8a6100;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.test {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.levels {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 100px 1fr;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px 10px;
|
||||||
|
margin-top: 10px;
|
||||||
|
max-width: 420px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.allowlist {
|
||||||
|
list-style: none;
|
||||||
|
margin: 8px 0;
|
||||||
|
padding: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.allowlist li {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
padding: 2px 4px 2px 10px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: var(--primary-soft);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remove {
|
||||||
|
border: none;
|
||||||
|
background: none;
|
||||||
|
color: var(--muted);
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remove:hover {
|
||||||
|
color: var(--rec);
|
||||||
|
}
|
||||||
|
|
||||||
|
.add {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.footer {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.saved {
|
||||||
|
color: var(--ok);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
Reference in New Issue
Block a user