Kaleido-Desktop/src-tauri/src/system.rs
Elijah 00d72e70f4 Create Kaleido Desktop, a cinematic Plex client for Windows
Tauri 2 shell with a React/TypeScript interface and libmpv playback composed
beneath the web view (DirectComposition on Windows). Shared code with per-OS
platform modules and configs so macOS and Linux can follow.

- Plex sign-in (browser, plex.tv/link or manual), server selection, Plex Home
- Home, Movies and TV Shows (Discover, Library, Collections), search, people
- Title pages with logos, ratings, cast, extras, seasons and episodes
- Direct play with Plex conversion fallback, tracks, markers, autoplay
- Metadata editing, artwork, fix match, refresh, analyze and deletion
- Resumable offline downloads
- App settings and Plex server administration with a live dashboard
- Signed updater feed and Forgejo CI

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 16:26:37 -07:00

161 lines
5 KiB
Rust

//! 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, String> {
keyring::Entry::new(SERVICE, key).map_err(|e| e.to_string())
}
/// Secrets (Plex tokens) live in Windows Credential Manager, never in plain files.
#[tauri::command]
pub fn secret_get(key: String) -> Result<Option<String>, String> {
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(key: String, value: String) -> Result<(), String> {
entry(&key)?.set_password(&value).map_err(|e| e.to_string())
}
#[tauri::command]
pub fn secret_delete(key: String) -> Result<(), String> {
match entry(&key)?.delete_credential() {
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
Err(e) => Err(e.to_string()),
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AppInfo {
version: String,
data_dir: String,
default_download_dir: String,
platform: String,
device_name: String,
}
#[tauri::command]
pub fn app_info<R: Runtime>(app: AppHandle<R>) -> 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(),
device_name: std::env::var("COMPUTERNAME").unwrap_or_else(|_| "Windows PC".into()),
}
}
/// 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<Value> {
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<Option<Sender<()>>> = 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<DiskSpace, String> {
// 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<R: Runtime>(app: &AppHandle<R>) -> 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<u64, String> {
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)
}