Files
call-recorder/src-tauri/src/lib.rs
T
2026-11-10 13:52:26 +01:00

205 lines
8.9 KiB
Rust

mod backend;
mod commands;
mod detection;
mod playback;
mod processing;
mod state;
mod tray;
mod updater;
use recorder_core::pipeline;
use recorder_core::secrets::KeyringSecrets;
use recorder_core::store::Store;
use tauri::{AppHandle, Manager, WebviewWindowBuilder, WindowEvent};
use tauri_plugin_autostart::MacosLauncher;
use tauri_plugin_log::{RotationStrategy, Target, TargetKind, TimezoneStrategy};
use crate::state::AppState;
use crate::updater::{PendingUpdate, UpdateSchedule};
/// Command-line flag the login item starts the app with; the main window
/// then stays hidden in the tray.
const AUTOSTART_ARG: &str = "--autostart";
/// Size at which the log file is rotated; two old files are kept.
const LOG_FILE_SIZE: u128 = 1_000_000;
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
// Must be registered first: a second launch only focuses the first.
.plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| {
commands::show_main(app);
}))
.plugin(tauri_plugin_autostart::init(
MacosLauncher::LaunchAgent,
Some(vec![AUTOSTART_ARG]),
))
.plugin(tauri_plugin_notification::init())
.plugin(tauri_plugin_updater::Builder::new().build())
// Only for `open_backend_keys_page`: no capability grants the UI
// the plugin's commands, and no link-click script is injected (it
// would also run in the remote login page).
.plugin(
tauri_plugin_opener::Builder::new()
.open_js_links_on_click(false)
.build(),
)
// A call's mix for the player: only for the main window, whatever
// other webviews (the remote backend login) ask for.
.register_asynchronous_uri_scheme_protocol(playback::SCHEME, |ctx, request, responder| {
let webview = ctx.webview_label().to_string();
let dir = ctx
.app_handle()
.try_state::<AppState>()
.map(|state| state.playback_dir().to_path_buf());
tauri::async_runtime::spawn_blocking(move || {
responder.respond(match dir {
Some(dir) => playback::respond(&webview, &request, &dir),
None => playback::unavailable(),
})
});
})
.setup(|app| {
// Release builds log to a file in the app log directory (on
// Windows %LOCALAPPDATA%\eu.euvino.callrecorder\logs), debug
// builds to stdout as well. Never log API keys or transcripts.
let mut targets = vec![Target::new(TargetKind::LogDir { file_name: None })];
if cfg!(debug_assertions) {
targets.push(Target::new(TargetKind::Stdout));
}
app.handle().plugin(
tauri_plugin_log::Builder::new()
.targets(targets)
.level(log::LevelFilter::Info)
// flacenc logs per-encode statistics at Info.
.level_for("flacenc", log::LevelFilter::Warn)
// The updater plugin logs an Error for every endpoint
// that fails, also for the expected 404 of a feed URL
// that is not served while the other one is. Every
// check and install result reaches `updater`, which
// logs it (failed checks at Info, failed installs at
// Error), so the plugin's own lines are dropped.
.level_for("tauri_plugin_updater", log::LevelFilter::Off)
.max_file_size(LOG_FILE_SIZE)
.rotation_strategy(RotationStrategy::KeepSome(2))
.timezone_strategy(TimezoneStrategy::UseLocal)
.build(),
)?;
let data_dir = app.path().app_data_dir()?;
let config_dir = app.path().app_config_dir()?;
// Served to the main window only, by the `playback` scheme.
let playback_dir = app.path().app_cache_dir()?.join("playback");
std::fs::create_dir_all(&data_dir)?;
let store = Store::open(&data_dir.join("calls.sqlite"))?;
let recovery = pipeline::recover_on_startup(&store)?;
log::info!("startup recovery: {recovery:?}");
let state = AppState::new(
store,
Box::new(KeyringSecrets),
config_dir.join("settings.json"),
data_dir.join("recordings"),
playback_dir,
);
let leftover_jobs = state.store.calls_with_remote_jobs().unwrap_or_else(|e| {
log::error!("could not read leftover remote jobs: {e}");
Vec::new()
});
let autostart = state.settings().autostart;
let new_version = updater::first_start_of_version(
&config_dir.join("last-version"),
&app.package_info().version.to_string(),
);
// Off the main thread: the keyring can be slow to answer.
std::thread::spawn(KeyringSecrets::remove_unused_keys);
// Before anything can start a run.
processing::clear_upload_dir(app.handle());
// Before any window can ask for a mix.
state.clear_playback_cache();
app.manage(state);
app.manage(PendingUpdate::default());
app.manage(UpdateSchedule::default());
app.manage(backend::LoginWaiters::default());
// Windows are created here (`create: false` in tauri.conf.json)
// instead of by Tauri before `setup` runs: their webviews load
// immediately and invoke commands (list_calls, get_recording_state,
// get_pending_prompt) that need `AppState` to already be managed,
// which otherwise fails with "state not managed" right after start.
create_windows(app.handle())?;
commands::apply_autostart(app.handle(), autostart);
processing::delete_leftover_jobs(app.handle(), leftover_jobs);
tray::create(app.handle())?;
detection::spawn(app.handle().clone());
updater::spawn(app.handle().clone());
// After an update the installer restarts the app with its old
// arguments; the main window shows the new version even then.
if new_version || !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". The login window
// really closes: that cancels the login.
if let WindowEvent::CloseRequested { api, .. } = event {
if window.label() != backend::LOGIN_WINDOW {
api.prevent_close();
let _ = window.hide();
}
}
})
.invoke_handler(tauri::generate_handler![
commands::get_app_version,
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::show_recorder,
commands::stop_recording,
commands::discard_current_recording,
commands::get_pending_prompt,
commands::get_call_brief,
commands::discard_call,
commands::transcribe_call,
commands::retry_call,
commands::list_calls,
commands::get_call,
commands::rename_speaker,
commands::merge_speakers,
commands::unmerge_speaker,
commands::rename_call,
commands::prepare_playback,
commands::release_playback,
backend::backend_server,
backend::backend_status,
backend::backend_login,
backend::backend_logout,
backend::open_backend_keys_page,
backend::upload_transcript,
updater::get_update,
updater::install_update,
updater::check_for_update_now,
updater::can_self_update,
])
.run(tauri::generate_context!())
.expect("error while building tauri application");
}
/// Builds the windows declared in `tauri.conf.json` (there `"create": false`,
/// so Tauri does not build them itself before `setup` runs). Must run after
/// `app.manage(state)` and before anything that could show or use a window,
/// so no webview can invoke a command before `AppState` is managed.
fn create_windows(app: &AppHandle) -> tauri::Result<()> {
for config in app.config().app.windows.clone() {
WebviewWindowBuilder::from_config(app, &config)?.build()?;
}
Ok(())
}