Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
472 lines
15 KiB
Rust
472 lines
15 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::call_view::{CallDetail, CallListItem};
|
|
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::processing;
|
|
use crate::state::{
|
|
AppState, CallBrief, DeviceLevels, DiscardError, Ended, PendingPrompt, PreparedPlayback,
|
|
RecordingState,
|
|
};
|
|
|
|
const LEVELS_INTERVAL: Duration = Duration::from_millis(100);
|
|
/// `set_api_key`/`has_api_key` refuse this service: its key is managed only
|
|
/// by the backend login (`backend::login`), which holds `backend_key_lock`
|
|
/// and binds the key to this build's backend.
|
|
const BACKEND_KEY_MANAGED: &str = "Dieser Schlüssel wird über die Backend-Anmeldung verwaltet";
|
|
|
|
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,
|
|
}
|
|
|
|
/// This build's own version, for the settings' "Updates" section.
|
|
#[tauri::command]
|
|
pub fn get_app_version(app: AppHandle) -> String {
|
|
app.package_info().version.to_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. Refuses
|
|
/// `Service::Backend` (see [`BACKEND_KEY_MANAGED`]).
|
|
#[tauri::command]
|
|
pub async fn set_api_key(app: AppHandle, service: Service, key: String) -> CmdResult<()> {
|
|
reject_backend_service(service)?;
|
|
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. Refuses
|
|
/// `Service::Backend` (see [`BACKEND_KEY_MANAGED`]).
|
|
#[tauri::command]
|
|
pub async fn has_api_key(app: AppHandle, service: Service) -> CmdResult<bool> {
|
|
reject_backend_service(service)?;
|
|
blocking(app, move |app| {
|
|
let key = app.state::<AppState>().secrets.get(service);
|
|
Ok(key.is_some_and(|key| !key.is_empty()))
|
|
})
|
|
.await
|
|
}
|
|
|
|
/// Refuses direct keyring access to `Service::Backend`: its key is only
|
|
/// ever set by the backend login flow.
|
|
fn reject_backend_service(service: Service) -> CmdResult<()> {
|
|
if service == Service::Backend {
|
|
return Err(BACKEND_KEY_MANAGED.to_string());
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[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)
|
|
}
|
|
|
|
/// The main window's call list, newest first.
|
|
#[tauri::command]
|
|
pub fn list_calls(state: State<'_, AppState>) -> CmdResult<Vec<CallListItem>> {
|
|
state.call_list()
|
|
}
|
|
|
|
/// The selected call with its transcript.
|
|
#[tauri::command]
|
|
pub fn get_call(state: State<'_, AppState>, id: CallId) -> CmdResult<CallDetail> {
|
|
state.call_detail(id)
|
|
}
|
|
|
|
/// Renames a speaker of a call (an empty name restores the default label).
|
|
#[tauri::command]
|
|
pub fn rename_speaker(
|
|
app: AppHandle,
|
|
state: State<'_, AppState>,
|
|
id: CallId,
|
|
speaker_key: String,
|
|
name: String,
|
|
) -> CmdResult<()> {
|
|
state.rename_speaker(id, &speaker_key, &name)?;
|
|
processing::emit_updated(&app, id);
|
|
Ok(())
|
|
}
|
|
|
|
/// Merges remote speaker `from_key` into `into_key` (undone by
|
|
/// [`unmerge_speaker`]).
|
|
#[tauri::command]
|
|
pub fn merge_speakers(
|
|
app: AppHandle,
|
|
state: State<'_, AppState>,
|
|
id: CallId,
|
|
from_key: String,
|
|
into_key: String,
|
|
) -> CmdResult<()> {
|
|
state.merge_speakers(id, &from_key, &into_key)?;
|
|
processing::emit_updated(&app, id);
|
|
Ok(())
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub fn unmerge_speaker(
|
|
app: AppHandle,
|
|
state: State<'_, AppState>,
|
|
id: CallId,
|
|
from_key: String,
|
|
) -> CmdResult<()> {
|
|
state.unmerge_speaker(id, &from_key)?;
|
|
processing::emit_updated(&app, id);
|
|
Ok(())
|
|
}
|
|
|
|
/// Names a call (an empty or missing title restores the default heading).
|
|
#[tauri::command]
|
|
pub fn rename_call(
|
|
app: AppHandle,
|
|
state: State<'_, AppState>,
|
|
id: CallId,
|
|
title: Option<String>,
|
|
) -> CmdResult<()> {
|
|
state.rename_call(id, title.as_deref())?;
|
|
processing::emit_updated(&app, id);
|
|
Ok(())
|
|
}
|
|
|
|
/// Mixes the call's two tracks into one file to play in the detail view
|
|
/// (or reuses the cached mix); the main window plays it from the
|
|
/// `playback` scheme ([`crate::playback`]).
|
|
#[tauri::command]
|
|
pub async fn prepare_playback(app: AppHandle, id: CallId) -> CmdResult<PreparedPlayback> {
|
|
blocking(app, move |app| app.state::<AppState>().prepare_playback(id)).await
|
|
}
|
|
|
|
/// The player is done with the mix of `lease`: it is removed from disk
|
|
/// unless a newer player of the same call holds it.
|
|
#[tauri::command]
|
|
pub async fn release_playback(app: AppHandle, id: CallId, lease: u64) -> CmdResult<()> {
|
|
blocking(app, move |app| {
|
|
app.state::<AppState>().release_playback(id, lease);
|
|
Ok(())
|
|
})
|
|
.await
|
|
}
|
|
|
|
/// 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.
|
|
/// While its DeepScript jobs are still on record, nothing is deleted and a
|
|
/// cleanup starts, so a later try can succeed.
|
|
#[tauri::command]
|
|
pub async fn discard_call(app: AppHandle, id: CallId) -> CmdResult<()> {
|
|
blocking(app, move |app| {
|
|
match app.state::<AppState>().discard_call(id) {
|
|
Ok(_) => {}
|
|
Err(e @ DiscardError::CleanupPending) => {
|
|
processing::delete_leftover_jobs(app, vec![id]);
|
|
return Err(e.to_string());
|
|
}
|
|
Err(e @ DiscardError::Other(_)) => return Err(e.to_string()),
|
|
}
|
|
prompt_queue_changed(app);
|
|
Ok(())
|
|
})
|
|
.await
|
|
}
|
|
|
|
/// Transkribieren in the end-of-call prompt: starts processing in the
|
|
/// background and returns at once; the call leaves the prompt.
|
|
#[tauri::command]
|
|
pub async fn transcribe_call(app: AppHandle, id: CallId) -> CmdResult<()> {
|
|
blocking(app, move |app| processing::start(app, id, false)).await
|
|
}
|
|
|
|
/// Processes a failed (or still undecided) call again.
|
|
#[tauri::command]
|
|
pub async fn retry_call(app: AppHandle, id: CallId) -> CmdResult<()> {
|
|
blocking(app, move |app| processing::start(app, id, true)).await
|
|
}
|
|
|
|
/// After a call left the prompt queue: hides the prompt if no call waits
|
|
/// any more, and tells it to reload (`prompt-changed`) otherwise.
|
|
pub fn prompt_queue_changed(app: &AppHandle) {
|
|
if app.state::<AppState>().prompts_waiting() == 0 {
|
|
set_window_visible(app, "prompt", false);
|
|
}
|
|
if let Err(e) = app.emit("prompt-changed", ()) {
|
|
log::error!("could not emit prompt-changed: {e}");
|
|
}
|
|
}
|
|
|
|
/// 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 (`name` is its display
|
|
/// name, `exe` and `root_pid` identify the call app, whose output device
|
|
/// is recorded).
|
|
pub fn start_detected(app: &AppHandle, name: &str, exe: &str, root_pid: u32) -> CmdResult<CallId> {
|
|
let call_id = app
|
|
.state::<AppState>()
|
|
.start_detected_recording(name, exe, 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: the tray's "Aufnahme manuell
|
|
/// starten" and the main window's record button both call this instead of
|
|
/// starting a second recording when one is already running.
|
|
pub fn focus_recorder(app: &AppHandle) {
|
|
show_and_focus(app, "recorder");
|
|
}
|
|
|
|
/// Main window record button while a recording already runs: shows/focuses
|
|
/// the floating recorder window instead of starting another recording.
|
|
/// Shares [`focus_recorder`] with the tray handler.
|
|
#[tauri::command]
|
|
pub fn show_recorder(app: AppHandle) {
|
|
focus_recorder(&app);
|
|
}
|
|
|
|
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())?
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn the_backend_key_is_managed_only_by_the_login() {
|
|
assert_eq!(
|
|
reject_backend_service(Service::Backend),
|
|
Err(BACKEND_KEY_MANAGED.to_string())
|
|
);
|
|
assert_eq!(reject_backend_service(Service::DeepScript), Ok(()));
|
|
}
|
|
}
|