//! Small platform services: credential storage, app paths, power and disk. use std::sync::mpsc::{channel, Sender}; use parking_lot::Mutex; use serde::Serialize; use serde_json::{json, Value}; use tauri::{AppHandle, Manager, Runtime}; const SERVICE: &str = "tv.kaleido.desktop"; fn entry(key: &str) -> Result { keyring::Entry::new(SERVICE, key).map_err(|e| e.to_string()) } /// Secrets (Plex tokens) live in the OS's credential store (Windows Credential /// Manager, the macOS Keychain), never in plain files; except in macOS debug /// builds, see `dev_secrets`. #[tauri::command] pub fn secret_get(app: AppHandle, key: String) -> Result, String> { if let Some(path) = dev_secrets(&app) { return Ok(read_dev_secrets(&path).get(&key).and_then(|v| v.as_str()).map(String::from)); } match entry(&key)?.get_password() { Ok(v) => Ok(Some(v)), Err(keyring::Error::NoEntry) => Ok(None), Err(e) => Err(e.to_string()), } } #[tauri::command] pub fn secret_set(app: AppHandle, key: String, value: String) -> Result<(), String> { if let Some(path) = dev_secrets(&app) { let mut all = read_dev_secrets(&path); all.insert(key, Value::String(value)); return write_dev_secrets(&path, &all); } let entry = entry(&key)?; match entry.set_password(&value) { Ok(()) => Ok(()), // A Keychain item left by a differently signed build can be impossible to // update yet still block adding; replacing it recovers. Err(keyring::Error::PlatformFailure(_)) if cfg!(target_os = "macos") => { let _ = entry.delete_credential(); entry.set_password(&value).map_err(|e| e.to_string()) } Err(e) => Err(e.to_string()), } } #[tauri::command] pub fn secret_delete(app: AppHandle, key: String) -> Result<(), String> { if let Some(path) = dev_secrets(&app) { let mut all = read_dev_secrets(&path); all.remove(&key); return write_dev_secrets(&path, &all); } match entry(&key)?.delete_credential() { Ok(()) | Err(keyring::Error::NoEntry) => Ok(()), Err(e) => Err(e.to_string()), } } /// macOS ties Keychain access to the app's code signature, and every debug /// build is a new unsigned binary, so the Keychain would ask for permission /// after each rebuild. Debug builds there keep secrets in a private file in the /// app data folder instead (development only, like the `.env` sign-in). fn dev_secrets(app: &AppHandle) -> Option { if !(cfg!(debug_assertions) && cfg!(target_os = "macos")) { return None; } app.path().app_data_dir().ok().map(|d| d.join("dev-secrets.json")) } fn read_dev_secrets(path: &std::path::Path) -> serde_json::Map { std::fs::read_to_string(path).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default() } fn write_dev_secrets(path: &std::path::Path, all: &serde_json::Map) -> Result<(), String> { use std::io::Write; if let Some(dir) = path.parent() { std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; } let mut options = std::fs::OpenOptions::new(); options.write(true).create(true).truncate(true); #[cfg(unix)] std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); let mut file = options.open(path).map_err(|e| e.to_string())?; file.write_all(Value::Object(all.clone()).to_string().as_bytes()).map_err(|e| e.to_string()) } #[derive(Serialize)] #[serde(rename_all = "camelCase")] pub struct AppInfo { version: String, data_dir: String, default_download_dir: String, platform: String, os_version: String, device_name: String, /// Graphics adapters by name (decides which upscaling tiers are offered). gpus: Vec, } #[tauri::command] pub fn app_info(app: AppHandle) -> AppInfo { let paths = app.path(); let data = paths.app_data_dir().map(|p| p.display().to_string()).unwrap_or_default(); let downloads = paths .video_dir() .map(|p| p.join("Kaleido")) .or_else(|_| paths.app_data_dir().map(|p| p.join("Downloads"))) .map(|p| p.display().to_string()) .unwrap_or_default(); AppInfo { version: app.package_info().version.to_string(), data_dir: data, default_download_dir: downloads, platform: std::env::consts::OS.to_string(), os_version: crate::platform::os_version(), device_name: crate::platform::device_name(), gpus: crate::platform::gpu_names(), } } /// Development builds can start signed in from the repository's ignored `.env` /// (`PLEX_SERVER_URL`, `PLEX_TOKEN`). Release builds never read it. #[tauri::command] pub fn dev_session() -> Option { if !cfg!(debug_assertions) { return None; } let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); let path = std::env::var("KALEIDO_DEV_ENV") .ok() .map(std::path::PathBuf::from) .into_iter() .chain([root.join(".env"), root.join("../Custom plex client/.env")]) .find(|p| p.exists())?; let text = std::fs::read_to_string(path).ok()?; let mut server = None; let mut token = None; for line in text.lines() { if let Some((k, v)) = line.split_once('=') { let v = v.trim().trim_matches('"').to_string(); match k.trim() { "PLEX_SERVER_URL" => server = Some(v), "PLEX_TOKEN" => token = Some(v), _ => {} } } } Some(json!({ "server": server?, "token": token? })) } static AWAKE: Mutex>> = Mutex::new(None); /// Prevents display sleep during playback. #[tauri::command] pub fn keep_awake(enabled: bool) { let mut guard = AWAKE.lock(); if let Some(stop) = guard.take() { let _ = stop.send(()); } if !enabled { return; } let (tx, rx) = channel::<()>(); *guard = Some(tx); std::thread::spawn(move || crate::platform::hold_awake(rx)); } #[derive(Serialize)] #[serde(rename_all = "camelCase")] pub struct DiskSpace { free: u64, total: u64, } #[tauri::command] pub fn disk_space(path: String) -> Result { // Walk up to an existing folder; the download folder may not exist yet. let mut p = std::path::PathBuf::from(&path); while !p.exists() { if !p.pop() { break; } } Ok(DiskSpace { free: fs2::available_space(&p).map_err(|e| e.to_string())?, total: fs2::total_space(&p).map_err(|e| e.to_string())?, }) } #[allow(dead_code)] pub fn data_dir(app: &AppHandle) -> std::path::PathBuf { app.path().app_data_dir().unwrap_or_else(|_| std::env::temp_dir().join("Kaleido")) } /// Saves a URL (e.g. server logs) to a file the user chose. #[tauri::command] pub async fn save_url(url: String, path: String) -> Result { use futures_util::StreamExt; use tokio::io::AsyncWriteExt; let response = reqwest::Client::new().get(&url).send().await.map_err(|e| e.to_string())?; if !response.status().is_success() { return Err(format!("The server returned {}", response.status())); } let mut file = tokio::fs::File::create(&path).await.map_err(|e| e.to_string())?; let mut stream = response.bytes_stream(); let mut total = 0u64; while let Some(chunk) = stream.next().await { let chunk = chunk.map_err(|e| e.to_string())?; total += chunk.len() as u64; file.write_all(&chunk).await.map_err(|e| e.to_string())?; } file.flush().await.map_err(|e| e.to_string())?; Ok(total) }