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>
428 lines
14 KiB
Rust
428 lines
14 KiB
Rust
//! Offline downloads: resumable HTTP transfers of Plex media parts with a small
|
|
//! JSON catalog, so downloaded titles stay browsable and playable offline.
|
|
//!
|
|
//! URLs carrying Plex tokens are only held in memory. The catalog stores the
|
|
//! server-relative source path; resuming after a restart asks the interface for
|
|
//! a freshly signed URL.
|
|
|
|
use std::collections::HashMap;
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::Arc;
|
|
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
|
|
|
use futures_util::StreamExt;
|
|
use parking_lot::Mutex;
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::Value;
|
|
use tauri::{AppHandle, Emitter, Manager, Runtime};
|
|
use tokio::io::AsyncWriteExt;
|
|
use tokio::sync::{watch, Semaphore};
|
|
|
|
const MAX_ACTIVE: usize = 2;
|
|
|
|
#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
|
|
#[serde(rename_all = "lowercase")]
|
|
pub enum Status {
|
|
Queued,
|
|
Downloading,
|
|
Paused,
|
|
Completed,
|
|
Failed,
|
|
}
|
|
|
|
#[derive(Clone, Serialize, Deserialize, Debug)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct Item {
|
|
pub id: String,
|
|
pub file_path: String,
|
|
pub total: u64,
|
|
pub received: u64,
|
|
pub status: Status,
|
|
#[serde(default)]
|
|
pub error: Option<String>,
|
|
#[serde(default)]
|
|
pub meta: Value,
|
|
pub created_at: u64,
|
|
#[serde(default)]
|
|
pub speed: u64,
|
|
}
|
|
|
|
pub struct Downloads {
|
|
items: Mutex<Vec<Item>>,
|
|
dir: Mutex<Option<PathBuf>>,
|
|
cancels: Mutex<HashMap<String, watch::Sender<bool>>>,
|
|
permits: Arc<Semaphore>,
|
|
client: reqwest::Client,
|
|
}
|
|
|
|
impl Default for Downloads {
|
|
fn default() -> Self {
|
|
Downloads {
|
|
items: Mutex::new(Vec::new()),
|
|
dir: Mutex::new(None),
|
|
cancels: Mutex::new(HashMap::new()),
|
|
permits: Arc::new(Semaphore::new(MAX_ACTIVE)),
|
|
client: reqwest::Client::builder()
|
|
.connect_timeout(Duration::from_secs(20))
|
|
.user_agent("Kaleido")
|
|
.build()
|
|
.expect("http client"),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn now() -> u64 {
|
|
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
|
|
}
|
|
|
|
fn catalog_path<R: Runtime>(app: &AppHandle<R>) -> PathBuf {
|
|
crate::system::data_dir(app).join("downloads.json")
|
|
}
|
|
|
|
fn save<R: Runtime>(app: &AppHandle<R>) {
|
|
let state = app.state::<Downloads>();
|
|
let items = state.items.lock().clone();
|
|
let path = catalog_path(app);
|
|
if let Some(parent) = path.parent() {
|
|
let _ = std::fs::create_dir_all(parent);
|
|
}
|
|
if let Ok(text) = serde_json::to_string_pretty(&items) {
|
|
let tmp = path.with_extension("json.tmp");
|
|
if std::fs::write(&tmp, text).is_ok() {
|
|
let _ = std::fs::rename(tmp, path);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Loads the catalog at startup. Interrupted transfers become paused: their
|
|
/// signed URLs were never persisted.
|
|
pub fn restore<R: Runtime>(app: &AppHandle<R>) {
|
|
let Ok(text) = std::fs::read_to_string(catalog_path(app)) else { return };
|
|
let Ok(mut items) = serde_json::from_str::<Vec<Item>>(&text) else { return };
|
|
for item in items.iter_mut() {
|
|
if matches!(item.status, Status::Downloading | Status::Queued) {
|
|
// Marked so the interface resumes it once it has a signed URL again.
|
|
item.status = Status::Paused;
|
|
item.error = Some("interrupted".into());
|
|
}
|
|
if item.status == Status::Completed && !Path::new(&item.file_path).exists() {
|
|
item.status = Status::Failed;
|
|
item.error = Some("The downloaded file is missing.".into());
|
|
}
|
|
item.speed = 0;
|
|
}
|
|
*app.state::<Downloads>().items.lock() = items;
|
|
}
|
|
|
|
fn update<R: Runtime>(app: &AppHandle<R>, id: &str, f: impl FnOnce(&mut Item)) -> Option<Item> {
|
|
let state = app.state::<Downloads>();
|
|
let mut items = state.items.lock();
|
|
let item = items.iter_mut().find(|i| i.id == id)?;
|
|
f(item);
|
|
let snapshot = item.clone();
|
|
drop(items);
|
|
let _ = app.emit("download", &snapshot);
|
|
Some(snapshot)
|
|
}
|
|
|
|
fn sanitize(name: &str) -> String {
|
|
let cleaned: String = name
|
|
.chars()
|
|
.map(|c| if "<>:\"/\\|?*".contains(c) || c.is_control() { '_' } else { c })
|
|
.collect();
|
|
let trimmed = cleaned.trim().trim_end_matches('.').to_string();
|
|
if trimmed.is_empty() {
|
|
"Untitled".into()
|
|
} else {
|
|
trimmed.chars().take(120).collect()
|
|
}
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct StartRequest {
|
|
id: String,
|
|
url: String,
|
|
folder: String,
|
|
file_name: String,
|
|
#[serde(default)]
|
|
meta: Value,
|
|
/// Artwork to keep with the download: name → signed URL.
|
|
#[serde(default)]
|
|
assets: HashMap<String, String>,
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub async fn download_start<R: Runtime>(app: AppHandle<R>, request: StartRequest) -> Result<Item, String> {
|
|
let state = app.state::<Downloads>();
|
|
let dir = state.dir.lock().clone().ok_or("Choose a download folder first.")?;
|
|
// The folder may be nested ("Show/Season 1"); sanitize each component.
|
|
let folder = request
|
|
.folder
|
|
.split(['/', '\\'])
|
|
.filter(|c| !c.trim().is_empty() && *c != "." && *c != "..")
|
|
.fold(dir.clone(), |p, c| p.join(sanitize(c)));
|
|
tokio::fs::create_dir_all(&folder).await.map_err(|e| format!("Cannot create the download folder: {e}"))?;
|
|
let file_path = folder.join(sanitize(&request.file_name));
|
|
|
|
let mut meta = request.meta.clone();
|
|
if let Value::Object(map) = &mut meta {
|
|
let mut local = serde_json::Map::new();
|
|
for (name, url) in &request.assets {
|
|
let target = folder.join(format!(".{}.jpg", sanitize(name)));
|
|
if fetch_to(&state.client, url, &target).await.is_ok() {
|
|
local.insert(name.clone(), Value::String(target.display().to_string()));
|
|
}
|
|
}
|
|
map.insert("localAssets".into(), Value::Object(local));
|
|
}
|
|
|
|
let item = Item {
|
|
id: request.id.clone(),
|
|
file_path: file_path.display().to_string(),
|
|
total: 0,
|
|
received: 0,
|
|
status: Status::Queued,
|
|
error: None,
|
|
meta,
|
|
created_at: now(),
|
|
speed: 0,
|
|
};
|
|
{
|
|
let mut items = state.items.lock();
|
|
items.retain(|i| i.id != item.id);
|
|
items.insert(0, item.clone());
|
|
}
|
|
save(&app);
|
|
let _ = app.emit("download", &item);
|
|
spawn(app.clone(), request.id, request.url);
|
|
Ok(item)
|
|
}
|
|
|
|
async fn fetch_to(client: &reqwest::Client, url: &str, target: &Path) -> Result<(), String> {
|
|
let bytes = client.get(url).send().await.map_err(|e| e.to_string())?.error_for_status().map_err(|e| e.to_string())?.bytes().await.map_err(|e| e.to_string())?;
|
|
tokio::fs::write(target, bytes).await.map_err(|e| e.to_string())
|
|
}
|
|
|
|
fn spawn<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
|
|
let (tx, rx) = watch::channel(false);
|
|
app.state::<Downloads>().cancels.lock().insert(id.clone(), tx);
|
|
tauri::async_runtime::spawn(async move {
|
|
let permits = app.state::<Downloads>().permits.clone();
|
|
let _permit = tokio::select! {
|
|
p = permits.acquire_owned() => p,
|
|
_ = cancelled(rx.clone()) => return,
|
|
};
|
|
let result = transfer(&app, &id, &url, rx).await;
|
|
app.state::<Downloads>().cancels.lock().remove(&id);
|
|
match result {
|
|
Ok(true) => {
|
|
update(&app, &id, |i| {
|
|
i.status = Status::Completed;
|
|
i.speed = 0;
|
|
i.received = i.total.max(i.received);
|
|
});
|
|
}
|
|
Ok(false) => {}
|
|
Err(e) => {
|
|
update(&app, &id, |i| {
|
|
i.status = Status::Failed;
|
|
i.error = Some(e);
|
|
i.speed = 0;
|
|
});
|
|
}
|
|
}
|
|
save(&app);
|
|
});
|
|
}
|
|
|
|
async fn cancelled(mut rx: watch::Receiver<bool>) {
|
|
while !*rx.borrow() {
|
|
if rx.changed().await.is_err() {
|
|
std::future::pending::<()>().await;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Returns Ok(true) when complete, Ok(false) when paused/removed.
|
|
async fn transfer<R: Runtime>(app: &AppHandle<R>, id: &str, url: &str, rx: watch::Receiver<bool>) -> Result<bool, String> {
|
|
let Some(item) = app.state::<Downloads>().items.lock().iter().find(|i| i.id == id).cloned() else { return Ok(false) };
|
|
let final_path = PathBuf::from(&item.file_path);
|
|
let part_path = final_path.with_extension(format!(
|
|
"{}.part",
|
|
final_path.extension().and_then(|e| e.to_str()).unwrap_or("bin")
|
|
));
|
|
let existing = tokio::fs::metadata(&part_path).await.map(|m| m.len()).unwrap_or(0);
|
|
|
|
let client = app.state::<Downloads>().client.clone();
|
|
let mut request = client.get(url);
|
|
if existing > 0 {
|
|
request = request.header("Range", format!("bytes={existing}-"));
|
|
}
|
|
let response = request.send().await.map_err(|e| format!("Could not reach the server: {e}"))?;
|
|
let status = response.status();
|
|
if status.as_u16() == 401 || status.as_u16() == 403 {
|
|
return Err("The server does not allow downloads for this account.".into());
|
|
}
|
|
if !status.is_success() {
|
|
return Err(format!("The server could not provide this file ({status})."));
|
|
}
|
|
let resumed = status.as_u16() == 206;
|
|
let start = if resumed { existing } else { 0 };
|
|
let total = response.content_length().map(|l| l + start).unwrap_or(0);
|
|
let mut file = tokio::fs::OpenOptions::new()
|
|
.create(true)
|
|
.write(true)
|
|
.append(resumed)
|
|
.truncate(!resumed)
|
|
.open(&part_path)
|
|
.await
|
|
.map_err(|e| format!("Cannot write the download: {e}"))?;
|
|
|
|
update(app, id, |i| {
|
|
i.status = Status::Downloading;
|
|
i.total = total;
|
|
i.received = start;
|
|
i.error = None;
|
|
});
|
|
save(app);
|
|
|
|
let mut stream = response.bytes_stream();
|
|
let mut received = start;
|
|
let mut last_emit = Instant::now();
|
|
let mut last_save = Instant::now();
|
|
let mut window_bytes = 0u64;
|
|
let mut window_start = Instant::now();
|
|
let mut speed = 0u64;
|
|
loop {
|
|
if *rx.borrow() {
|
|
file.flush().await.ok();
|
|
return Ok(false);
|
|
}
|
|
let chunk = tokio::select! {
|
|
c = stream.next() => c,
|
|
_ = cancelled(rx.clone()) => { file.flush().await.ok(); return Ok(false); }
|
|
};
|
|
let Some(chunk) = chunk else { break };
|
|
let chunk = chunk.map_err(|e| format!("The transfer was interrupted: {e}"))?;
|
|
file.write_all(&chunk).await.map_err(|e| format!("Cannot write the download: {e}"))?;
|
|
received += chunk.len() as u64;
|
|
window_bytes += chunk.len() as u64;
|
|
let elapsed = window_start.elapsed();
|
|
if elapsed >= Duration::from_secs(1) {
|
|
speed = (window_bytes as f64 / elapsed.as_secs_f64()) as u64;
|
|
window_bytes = 0;
|
|
window_start = Instant::now();
|
|
}
|
|
if last_emit.elapsed() >= Duration::from_millis(250) {
|
|
last_emit = Instant::now();
|
|
update(app, id, |i| {
|
|
i.received = received;
|
|
i.speed = speed;
|
|
});
|
|
}
|
|
if last_save.elapsed() >= Duration::from_secs(5) {
|
|
last_save = Instant::now();
|
|
save(app);
|
|
}
|
|
}
|
|
file.flush().await.map_err(|e| e.to_string())?;
|
|
drop(file);
|
|
if total > 0 && received < total {
|
|
return Err("The transfer ended early. Resume to continue.".into());
|
|
}
|
|
tokio::fs::rename(&part_path, &final_path).await.map_err(|e| format!("Cannot finish the download: {e}"))?;
|
|
update(app, id, |i| i.received = received);
|
|
Ok(true)
|
|
}
|
|
|
|
fn cancel<R: Runtime>(app: &AppHandle<R>, id: &str) {
|
|
if let Some(tx) = app.state::<Downloads>().cancels.lock().remove(id) {
|
|
let _ = tx.send(true);
|
|
}
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub fn download_pause<R: Runtime>(app: AppHandle<R>, id: String) {
|
|
cancel(&app, &id);
|
|
update(&app, &id, |i| {
|
|
if i.status != Status::Completed {
|
|
i.status = Status::Paused;
|
|
i.speed = 0;
|
|
}
|
|
});
|
|
save(&app);
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub fn download_resume<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
|
|
cancel(&app, &id);
|
|
update(&app, &id, |i| {
|
|
i.status = Status::Queued;
|
|
i.error = None;
|
|
});
|
|
spawn(app, id, url);
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub async fn download_remove<R: Runtime>(app: AppHandle<R>, id: String, delete_files: bool) -> Result<(), String> {
|
|
cancel(&app, &id);
|
|
let removed = {
|
|
let state = app.state::<Downloads>();
|
|
let mut items = state.items.lock();
|
|
let pos = items.iter().position(|i| i.id == id);
|
|
pos.map(|p| items.remove(p))
|
|
};
|
|
if let (Some(item), true) = (removed, delete_files) {
|
|
let path = PathBuf::from(&item.file_path);
|
|
// Give the cancelled transfer a moment to release its file handle.
|
|
tokio::time::sleep(Duration::from_millis(150)).await;
|
|
let _ = tokio::fs::remove_file(&path).await;
|
|
let part = path.with_extension(format!("{}.part", path.extension().and_then(|e| e.to_str()).unwrap_or("bin")));
|
|
let _ = tokio::fs::remove_file(&part).await;
|
|
if let Value::Object(assets) = &item.meta["localAssets"] {
|
|
for v in assets.values() {
|
|
if let Some(p) = v.as_str() {
|
|
let _ = tokio::fs::remove_file(p).await;
|
|
}
|
|
}
|
|
}
|
|
// Remove now-empty folders (season, then show), never the download root.
|
|
let root = app.state::<Downloads>().dir.lock().clone();
|
|
let mut folder = path.parent().map(|p| p.to_path_buf());
|
|
while let Some(f) = folder {
|
|
if Some(&f) == root.as_ref() || tokio::fs::remove_dir(&f).await.is_err() {
|
|
break;
|
|
}
|
|
folder = f.parent().map(|p| p.to_path_buf());
|
|
}
|
|
}
|
|
save(&app);
|
|
let _ = app.emit("download-removed", &id);
|
|
Ok(())
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub fn download_list<R: Runtime>(app: AppHandle<R>) -> Vec<Item> {
|
|
app.state::<Downloads>().items.lock().clone()
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub fn download_set_dir<R: Runtime>(app: AppHandle<R>, dir: String) -> Result<(), String> {
|
|
let path = PathBuf::from(dir);
|
|
std::fs::create_dir_all(&path).map_err(|e| format!("Cannot use this folder: {e}"))?;
|
|
*app.state::<Downloads>().dir.lock() = Some(path);
|
|
Ok(())
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub fn download_write_meta<R: Runtime>(app: AppHandle<R>, id: String, meta: Value) {
|
|
update(&app, &id, |i| {
|
|
let assets = i.meta.get("localAssets").cloned();
|
|
i.meta = meta;
|
|
if let (Some(a), Value::Object(m)) = (assets, &mut i.meta) {
|
|
m.insert("localAssets".into(), a);
|
|
}
|
|
});
|
|
save(&app);
|
|
}
|