diff --git a/crates/capri-computer/src/extras.rs b/crates/capri-computer/src/extras.rs new file mode 100644 index 0000000..585a8dc --- /dev/null +++ b/crates/capri-computer/src/extras.rs @@ -0,0 +1,138 @@ +//! Smaller helpers: opening URIs through the desktop portal (no `xdg-open` script), the Steam +//! Cyberpunk 2077 fast path, and freedesktop Trash with a private recovery copy. +use std::path::{Path, PathBuf}; + +use anyhow::{bail, ensure, Context, Result}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; + +/// `org.freedesktop.portal.OpenURI.OpenURI` (steam://, https://). +pub async fn open_uri(uri: &str) -> Result<()> { + let conn = zbus::Connection::session().await?; + let opts: std::collections::HashMap<&str, zbus::zvariant::Value> = std::collections::HashMap::new(); + conn.call_method(Some("org.freedesktop.portal.Desktop"), "/org/freedesktop/portal/desktop", Some("org.freedesktop.portal.OpenURI"), "OpenURI", &("", uri, opts)).await.context("The desktop could not pass the request to Steam.")?; + Ok(()) +} + +pub const CYBERPUNK: u32 = 1_091_500; + +/// Steam library roots: native, `~/.steam/steam`, Flatpak, plus `libraryfolders.vdf` paths. +pub fn steam_libraries(home: &Path) -> Vec { + let roots = [home.join(".local/share/Steam"), home.join(".steam/steam"), home.join(".var/app/com.valvesoftware.Steam/.local/share/Steam")]; + let mut out: Vec = vec![]; + for root in roots.iter().filter(|r| r.is_dir()) { + out.push(root.clone()); + let vdf = std::fs::read_to_string(root.join("steamapps/libraryfolders.vdf")).unwrap_or_default(); + for line in vdf.lines() { + let parts: Vec<&str> = line.split('"').collect(); + if parts.len() >= 4 && parts[1] == "path" { + out.push(PathBuf::from(parts[3].replace("\\\\", "\\"))); + } + } + } + out.dedup(); + out +} + +/// `installed` when an appmanifest has StateFlags bit 4; `running` per `registry.vdf`. +pub fn steam_game_state(home: &Path, app: u32) -> &'static str { + let running = [home.join(".steam/registry.vdf"), home.join(".var/app/com.valvesoftware.Steam/.steam/registry.vdf")] + .iter() + .filter_map(|p| std::fs::read_to_string(p).ok()) + .any(|t| t.lines().any(|l| l.contains("\"RunningAppID\"") && l.contains(&format!("\"{app}\"")))); + if running { + return "running"; + } + let installed = steam_libraries(home).iter().any(|lib| { + std::fs::read_to_string(lib.join(format!("steamapps/appmanifest_{app}.acf"))) + .ok() + .and_then(|t| t.lines().find(|l| l.contains("\"StateFlags\"")).and_then(|l| l.split('"').nth(3)).and_then(|v| v.parse::().ok())) + .is_some_and(|f| f & 4 != 0) + }); + if installed { "installed" } else { "not-installed" } +} + +/// Moves a regular single-link file to the freedesktop Trash after a verified private recovery +/// copy (`/desktop/file-recovery/.backup`). No permanent-delete fallback. +pub fn trash_with_recovery(file: &Path, recovery_dir: &Path, recovery_total: u64) -> Result { + let meta = std::fs::symlink_metadata(file)?; + use std::os::unix::fs::MetadataExt; + ensure!(meta.file_type().is_file() && meta.nlink() == 1, "Folders and linked files are not supported."); + ensure!(meta.len() <= 20 << 20, "The file is larger than 20 MiB."); + ensure!(recovery_total + meta.len() <= 1 << 30, "The recovery storage is full."); + let bytes = std::fs::read(file)?; + let sha = hex::encode(Sha256::digest(&bytes)); + std::fs::create_dir_all(recovery_dir)?; + let id = uuid::Uuid::new_v4().to_string(); + let backup = recovery_dir.join(format!("{id}.backup")); + { + use std::io::Write; + use std::os::unix::fs::OpenOptionsExt; + let mut f = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(&backup)?; + f.write_all(&bytes)?; + f.sync_all()?; + } + ensure!(hex::encode(Sha256::digest(std::fs::read(&backup)?)) == sha, "The recovery copy could not be verified."); + let now = std::fs::symlink_metadata(file)?; + if now.ino() != meta.ino() || now.len() != meta.len() { + let _ = std::fs::remove_file(&backup); + bail!("The selected file changed. Ask again and review a new confirmation."); + } + let home = std::env::var_os("XDG_DATA_HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(".local/share")); + let trash = home.join("Trash"); + std::fs::create_dir_all(trash.join("files"))?; + std::fs::create_dir_all(trash.join("info"))?; + let stem = file.file_name().context("Invalid file")?.to_string_lossy().to_string(); + let mut name = stem.clone(); + let mut n = 1; + let info = loop { + let info = trash.join("info").join(format!("{name}.trashinfo")); + let created = std::fs::OpenOptions::new().write(true).create_new(true).open(&info); + if let Ok(mut f) = created { + use std::io::Write; + let path: String = url::form_urlencoded::byte_serialize(file.to_string_lossy().as_bytes()).collect::().replace("%2F", "/"); + writeln!(f, "[Trash Info]\nPath={path}\nDeletionDate={}", chrono::Local::now().format("%Y-%m-%dT%H:%M:%S"))?; + break info; + } + n += 1; + name = format!("{stem}.{n}"); + }; + if let Err(e) = std::fs::rename(file, trash.join("files").join(&name)) { + let _ = std::fs::remove_file(&info); + bail!("The file could not be moved to the Trash: {e}"); + } + ensure!(!file.exists(), "The file is still present."); + Ok(json!({"ok": true, "confirmation": "Moved the file to Recycle Bin.", "recoveryId": id, "backup": format!("{id}.backup"), "sha": sha, "bytes": meta.len()})) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn steam_fixture() { + let home = tempfile::tempdir().unwrap(); + let lib = home.path().join("games"); + let steam = home.path().join(".local/share/Steam/steamapps"); + std::fs::create_dir_all(&steam).unwrap(); + std::fs::create_dir_all(lib.join("steamapps")).unwrap(); + std::fs::write(steam.join("libraryfolders.vdf"), format!("\"libraryfolders\"\n{{\n\t\"1\"\n\t{{\n\t\t\"path\"\t\t\"{}\"\n\t}}\n}}\n", lib.display())).unwrap(); + assert_eq!(steam_game_state(home.path(), CYBERPUNK), "not-installed"); + std::fs::write(lib.join("steamapps/appmanifest_1091500.acf"), "\"AppState\"\n{\n\t\"StateFlags\"\t\t\"4\"\n}\n").unwrap(); + assert_eq!(steam_game_state(home.path(), CYBERPUNK), "installed"); + } + + #[test] + fn trash_keeps_a_verified_copy() { + let dir = tempfile::tempdir().unwrap(); + // SAFETY: test-only environment change before any thread reads it. + unsafe { std::env::set_var("XDG_DATA_HOME", dir.path().join("share")) }; + let file = dir.path().join("note.txt"); + std::fs::write(&file, b"hello").unwrap(); + let r = trash_with_recovery(&file, &dir.path().join("recovery"), 0).unwrap(); + assert!(!file.exists()); + assert_eq!(std::fs::read(dir.path().join("recovery").join(r["backup"].as_str().unwrap())).unwrap(), b"hello"); + assert!(dir.path().join("share/Trash/files/note.txt").exists()); + assert!(trash_with_recovery(dir.path(), &dir.path().join("recovery"), 0).is_err(), "folders refused"); + } +}