//! Finding, starting and logging the record-daemon process. //! //! Ported from the old Tauri app's `daemon_ipc.rs`. The daemon binary ships next to the //! app; inside a checkout it is found in `record-daemon/target/{release,debug}`. use std::path::{Path, PathBuf}; use std::time::Duration; use crate::ipc::Client; /// Set this to point the app and the daemon at a scratch directory, as scripts do. pub const HOME_ENV: &str = "RECORD_DAEMON_HOME"; /// Where the review screen keeps one audio file per track of a clip. pub fn audio_cache_dir() -> PathBuf { data_dir() .map(|p| p.join("audio-cache")) .unwrap_or_else(|| PathBuf::from("./audio-cache")) } /// The daemon's data directory, shared with the daemon itself. pub fn data_dir() -> Option { if let Some(home) = std::env::var_os(HOME_ENV).filter(|value| !value.is_empty()) { return Some(PathBuf::from(home).join("data")); } directories::ProjectDirs::from("com", "leaguerecorder", "record-daemon") .map(|dirs| dirs.data_dir().to_path_buf()) } /// Where recordings and timelines live. pub fn recordings_dir() -> PathBuf { data_dir() .map(|p| p.join("recordings")) .unwrap_or_else(|| PathBuf::from("./recordings")) } /// The folder the daemon keeps its daily logs in. pub fn log_dir() -> Option { let dir = data_dir()?.join("logs"); std::fs::create_dir_all(&dir).ok()?; Some(dir) } /// The `--log-file` the app starts the daemon with. /// /// The daemon takes the stem of the path and adds the date and the extension (see `init_logging` /// in `record-daemon/src/main.rs`), so it writes `daemon.YYYY-MM-DD.log` beside this path /// rather than the path itself. pub fn log_file() -> Option { Some(log_dir()?.join("daemon.log")) } /// Find the record-daemon binary next to the app, in an installed `resources` folder, or in a /// development checkout. /// /// A checkout can hold both `target/debug` and `target/release`, one of them stale; the newest /// build wins, so the app talks to the daemon that was built last ("cargo build" then "cargo /// run", rather than a release build from another week). pub fn find_binary() -> Option { let name = if cfg!(windows) { "record-daemon.exe" } else { "record-daemon" }; if let Ok(exe) = std::env::current_exe() { let exe_dir = exe.parent()?; let beside = exe_dir.join(name); if beside.exists() { return Some(beside); } if let Some(parent) = exe_dir.parent() { let resources = parent.join("resources").join(name); if resources.exists() { return Some(resources); } } if let Some(found) = newest_build(exe_dir, name) { return Some(found); } } newest_build(&std::env::current_dir().ok()?, name) } /// The most recently built daemon in a checkout, walking up from `start`. fn newest_build(start: &Path, name: &str) -> Option { let mut dir = start.to_path_buf(); for _ in 0..6 { let candidates = [ dir.join("record-daemon/target/release").join(name), dir.join("record-daemon/target/debug").join(name), ]; if let Some(found) = candidates .into_iter() .filter_map(|path| { let modified = std::fs::metadata(&path).ok()?.modified().ok()?; Some((modified, path)) }) .max_by_key(|(modified, _)| *modified) .map(|(_, path)| path) { return Some(found); } if !dir.pop() { break; } } None } /// Start the daemon detached, so it outlives the app. pub fn spawn() -> Result { let binary = find_binary().ok_or_else(|| { "record-daemon was not found next to the app or in record-daemon/target".to_string() })?; let log = log_file().ok_or_else(|| "no data directory for the daemon log".to_string())?; let mut command = std::process::Command::new(&binary); command.arg("--foreground").arg("--log-file").arg(&log); if let Some(dir) = binary.parent() { // The daemon finds its bundled OBS plugin data relative to itself. command.current_dir(dir); } #[cfg(windows)] { use std::os::windows::process::CommandExt; // CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS command.creation_flags(0x0000_0200 | 0x0000_0008); } command .stdin(std::process::Stdio::null()) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()); command .spawn() .map_err(|e| format!("cannot start record-daemon: {e}"))?; Ok(binary) } /// Wait up to `timeout` for the daemon to answer, starting it if it isn't running yet. pub async fn ensure_running() -> Result<(), String> { let client = Client::new(); if client.is_running().await { return Ok(()); } spawn()?; let deadline = std::time::Instant::now() + Duration::from_secs(30); loop { if client.is_running().await { return Ok(()); } if std::time::Instant::now() >= deadline { return Err("record-daemon did not answer within 30 s".to_string()); } tokio::time::sleep(Duration::from_millis(500)).await; } } /// The last `n` lines of the log the daemon is writing now. pub fn read_logs(n: usize) -> Result { let path = current_log().ok_or_else(|| "the recorder has written no log yet".to_string())?; let text = std::fs::read_to_string(&path) .map_err(|e| format!("cannot read {}: {e}", path.display()))?; let lines: Vec = text.lines().rev().take(n).map(strip_ansi).collect(); Ok(lines.into_iter().rev().collect::>().join("\n")) } /// What a log line says without the color codes. /// /// The daemon used to write ANSI escapes into the file, so lines from before that fix carry /// them. `ESC [ params final` is the only form tracing emitted. fn strip_ansi(line: &str) -> String { if !line.contains('\u{1b}') { return line.to_string(); } let mut out = String::with_capacity(line.len()); let mut chars = line.chars(); while let Some(c) = chars.next() { if c != '\u{1b}' { out.push(c); } else if chars.next() == Some('[') { for c in chars.by_ref() { if ('@'..='~').contains(&c) { break; } } } } out } /// The log file the daemon is appending to now, as text for the Advanced tab. pub fn log_path() -> String { current_log() .map(|p| p.display().to_string()) .unwrap_or_else(|| "None yet".to_string()) } /// The log file the daemon is appending to now. pub fn current_log() -> Option { let dir = data_dir()?.join("logs"); newest_log(&dir) } /// The newest daily file in the logs folder. /// /// The daemon rolls the log over at midnight, so the folder holds one file per day and the /// newest is the one still being written. The date in the name is in ISO order, so comparing /// names finds it without reading each file's timestamp. fn newest_log(dir: &Path) -> Option { std::fs::read_dir(dir) .ok()? .filter_map(|entry| { let path = entry.ok()?.path(); let name = path.file_name()?.to_str()?; let date = name.strip_prefix("daemon.")?.strip_suffix(".log")?; date.starts_with(|c: char| c.is_ascii_digit()) .then_some(path) }) .max() } /// Open a folder. pub fn open_folder(path: &Path) { #[cfg(windows)] { let _ = std::process::Command::new("explorer").arg(path).spawn(); } #[cfg(not(windows))] let _ = path; } #[cfg(test)] mod tests { use super::*; fn temp_dir() -> PathBuf { let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&dir).unwrap(); dir } #[test] fn the_newest_day_is_the_log_the_daemon_writes() { let dir = temp_dir(); std::fs::write(dir.join("daemon.2026-11-21.log"), "yesterday").unwrap(); let today = dir.join("daemon.2026-11-22.log"); std::fs::write(&today, "today").unwrap(); std::fs::write(dir.join("notes.txt"), "not a log").unwrap(); assert_eq!(newest_log(&dir), Some(today)); let _ = std::fs::remove_dir_all(dir); } #[test] fn a_folder_without_a_log_has_no_log_to_read() { let dir = temp_dir(); assert_eq!(newest_log(&dir), None); let _ = std::fs::remove_dir_all(dir); } #[test] fn a_log_line_loses_its_color_codes() { let line = "\u{1b}[2m2026-11-23T23:06:51Z\u{1b}[0m \u{1b}[32m INFO\u{1b}[0m record_daemon: ready"; assert_eq!( strip_ansi(line), "2026-11-23T23:06:51Z INFO record_daemon: ready" ); } }