Files
call-recorder/src-tauri/src/commands.rs
T
2026-11-05 15:53:47 +01:00

310 lines
9.5 KiB
Rust

//! Tauri commands and the UI side effects of recording (windows, events),
//! shared by the UI, the tray and call detection.
//!
//! 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 serde::Serialize;
use tauri::{AppHandle, Emitter, Manager, State};
use tauri_plugin_autostart::ManagerExt;
use crate::state::{AppState, CallBrief, DeviceLevels, Ended, PendingPrompt, RecordingState};
const LEVELS_INTERVAL: Duration = Duration::from_millis(100);
type CmdResult<T> = Result<T, String>;
/// Payload of the `call-ended` event: a call awaits the prompt's decision.
#[derive(Serialize, Clone)]
struct CallEnded {
id: CallId,
}
#[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
}
/// The call the end-of-call prompt asks about, so the prompt can render even
/// if it missed the `call-ended` event.
#[tauri::command]
pub fn get_pending_prompt(state: State<'_, AppState>) -> Option<PendingPrompt> {
state.pending_prompt()
}
#[tauri::command]
pub fn get_call_brief(state: State<'_, AppState>, id: CallId) -> CmdResult<CallBrief> {
state.call_brief(id)
}
/// Deletes a finished call's audio and row. Closes the prompt if no call
/// waits for it any more; otherwise the prompt reloads and shows the next.
#[tauri::command]
pub async fn discard_call(app: AppHandle, id: CallId) -> CmdResult<()> {
blocking(app, move |app| {
if app.state::<AppState>().discard_call(id)? == 0 {
set_window_visible(app, "prompt", false);
}
Ok(())
})
.await
}
/// Placeholder until transcription exists; the prompt shows the error.
#[tauri::command]
pub fn transcribe_call(id: CallId) -> CmdResult<()> {
let _ = id;
Err("Transkription ist noch nicht verfügbar".to_string())
}
/// Starts a manual recording, shows the floating window and streams levels.
pub fn start_manual(app: &AppHandle) -> CmdResult<CallId> {
let call_id = app.state::<AppState>().start_manual_recording()?;
on_started(app, call_id);
Ok(call_id)
}
/// Starts recording a call that detection found (`app` is its display
/// name, `root_pid` the process tree whose audio is the far end).
pub fn start_detected(app: &AppHandle, name: &str, root_pid: u32) -> CmdResult<CallId> {
let call_id = app
.state::<AppState>()
.start_detected_recording(name, root_pid)?;
on_started(app, call_id);
Ok(call_id)
}
/// Stops the current recording at the user's request (■ Stopp), manual or
/// detected. Detection then leaves the ongoing call alone until the call
/// app releases the mic.
pub fn stop(app: &AppHandle) -> CmdResult<()> {
let state = app.state::<AppState>();
let ended = state.stop_recording();
if ended.is_some() {
state.suppress_detected_call();
}
after_stop(app, ended)
}
/// Stops the current recording because detection saw the call end. A
/// manual recording is left running.
pub fn end_detected_call(app: &AppHandle) {
let ended = app.state::<AppState>().stop_detected_recording();
if let Err(e) = after_stop(app, ended) {
log::error!("finishing the detected call failed: {e}");
}
}
/// Throws the current recording away. Never shows the prompt; detection
/// then leaves the ongoing call alone until the call app releases the mic.
pub fn discard(app: &AppHandle) -> CmdResult<()> {
let state = app.state::<AppState>();
let ended = state.discard_current_recording();
if ended.is_some() {
state.suppress_detected_call();
}
sync_recorder_window(app);
ended.map_or(Ok(()), |ended| ended.result)
}
/// Streams levels, shows the floating window and announces a recording
/// that just started.
fn on_started(app: &AppHandle, call_id: CallId) {
spawn_level_emitter(app.clone(), call_id);
set_window_visible(app, "recorder", true);
emit_state(app, &app.state::<AppState>().recording_state());
}
/// After a recording stopped: updates the floating window and, if the call
/// was saved, asks what to do with it in the prompt window.
fn after_stop(app: &AppHandle, ended: Option<Ended>) -> CmdResult<()> {
sync_recorder_window(app);
let Some(ended) = ended else {
return Ok(());
};
ended.result?;
let id = ended.call_id;
app.state::<AppState>().queue_prompt(id);
show_and_focus(app, "prompt");
if let Err(e) = app.emit("call-ended", CallEnded { id }) {
log::error!("could not emit call-ended: {e}");
}
Ok(())
}
/// Announces the actual recording state and hides the floating window only
/// if nothing records any more: detection may already have started the
/// next recording.
fn sync_recorder_window(app: &AppHandle) {
let state = app.state::<AppState>().recording_state();
if matches!(state, RecordingState::Idle) {
set_window_visible(app, "recorder", false);
}
emit_state(app, &state);
}
/// 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) {
show_and_focus(app, "main");
}
/// Brings the floating window to the front (tray "Aufnahme manuell
/// starten" while a recording runs).
pub fn show_recorder(app: &AppHandle) {
show_and_focus(app, "recorder");
}
fn show_and_focus(app: &AppHandle, label: &str) {
if let Some(window) = app.get_webview_window(label) {
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())?
}