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:
@@ -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())
|
||||
}
|
||||
Reference in New Issue
Block a user