Fix playback, account, download and library bugs found in review
All checks were successful
Validate Kaleido Desktop / validate (push) Successful in 1m22s

- Clear cached library data when the account or profile behind the
  server connection changes, not only on Home user switches.
- TitleArt falls back to the title when there is no server, so the
  player no longer crashes offline.
- Playback keeps the server it started on: progress, watched state and
  transcodes never go to a server selected later, a download only
  reports to its own server, and switching account or server ends a
  stream from the old one.
- Closing or replacing playback during setup can no longer start the
  file afterwards.
- Transcodes save the chosen audio/subtitle tracks on the server before
  starting (and name them in the request), apply the language and
  subtitle preferences, and keep the current tracks across quality
  changes.
- Offline playback saves its resume point and watched count in the
  download's metadata.
- Download tasks take over from a previous task for the same title only
  after it exits, and pause/remove stay wired to the current task.
- Downloads prefer a single-file version and refuse split ones instead
  of saving only part one.
- Download artwork is named per file, so episodes in one season folder
  no longer overwrite or delete each other's images.
- Library grids refetch loaded pages when the cache is invalidated.
- Request timeouts and cancellation also cover the response body.
- Hero rotation resumes after being scrolled back into view.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-04 22:41:12 -07:00
parent c70aeede74
commit 8755d16735
9 changed files with 399 additions and 99 deletions

View file

@ -5,8 +5,9 @@
//! server-relative source path; resuming after a restart asks the interface for
//! a freshly signed URL.
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
@ -47,10 +48,19 @@ pub struct Item {
pub speed: u64,
}
/// The transfer task that currently owns a download (and its `.part` file).
struct Worker {
generation: u64,
cancel: watch::Sender<bool>,
/// Closes once the task has exited and let go of the file.
done: watch::Receiver<()>,
}
pub struct Downloads {
items: Mutex<Vec<Item>>,
dir: Mutex<Option<PathBuf>>,
cancels: Mutex<HashMap<String, watch::Sender<bool>>>,
workers: Mutex<HashMap<String, Worker>>,
generation: AtomicU64,
permits: Arc<Semaphore>,
client: reqwest::Client,
}
@ -60,7 +70,8 @@ impl Default for Downloads {
Downloads {
items: Mutex::new(Vec::new()),
dir: Mutex::new(None),
cancels: Mutex::new(HashMap::new()),
workers: Mutex::new(HashMap::new()),
generation: AtomicU64::new(0),
permits: Arc::new(Semaphore::new(MAX_ACTIVE)),
client: reqwest::Client::builder()
.connect_timeout(Duration::from_secs(20))
@ -168,8 +179,11 @@ pub async fn download_start<R: Runtime>(app: AppHandle<R>, request: StartRequest
let mut meta = request.meta.clone();
if let Value::Object(map) = &mut meta {
let mut local = serde_json::Map::new();
// Episodes share their season's folder, so artwork is named after the file it
// belongs to: one episode's still never replaces another's.
let stem = file_path.file_stem().and_then(|s| s.to_str()).map(sanitize).unwrap_or_else(|| sanitize(&request.id));
for (name, url) in &request.assets {
let target = folder.join(format!(".{}.jpg", sanitize(name)));
let target = folder.join(format!(".{stem}.{}.jpg", sanitize(name)));
if fetch_to(&state.client, url, &target).await.is_ok() {
local.insert(name.clone(), Value::String(target.display().to_string()));
}
@ -204,21 +218,48 @@ async fn fetch_to(client: &reqwest::Client, url: &str, target: &Path) -> Result<
tokio::fs::write(target, bytes).await.map_err(|e| e.to_string())
}
/// Starts a transfer task for `id`, taking over from any task still running for it:
/// that one is cancelled and the new one waits for it to exit before touching the file.
fn spawn<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
let state = app.state::<Downloads>();
let generation = state.generation.fetch_add(1, Ordering::Relaxed);
let (tx, rx) = watch::channel(false);
app.state::<Downloads>().cancels.lock().insert(id.clone(), tx);
let (done_tx, done_rx) = watch::channel(());
let previous = state.workers.lock().insert(id.clone(), Worker { generation, cancel: tx, done: done_rx });
let previous = previous.map(|w| {
let _ = w.cancel.send(true);
w.done
});
tauri::async_runtime::spawn(async move {
// Held until this task ends: whoever waits on `done` then knows the file is free.
let _done = done_tx;
let took_over = previous.is_some();
if let Some(done) = previous {
exited(done).await;
}
let stopped = rx.clone();
if *stopped.borrow() {
release(&app, &id, generation);
return;
}
let permits = app.state::<Downloads>().permits.clone();
let _permit = tokio::select! {
p = permits.acquire_owned() => p,
_ = cancelled(rx.clone()) => return,
_ = cancelled(rx.clone()) => { release(&app, &id, generation); return; }
};
let result = transfer(&app, &id, &url, rx).await;
app.state::<Downloads>().cancels.lock().remove(&id);
// The task it replaced may have finished the file just as it was stopped.
let result = if took_over && finished_file(&app, &id) { Ok(true) } else { transfer(&app, &id, &url, rx).await };
release(&app, &id, generation);
// Once paused, removed or replaced, the outcome is no longer this task's to
// report, except a finished file, which is complete whatever happened since.
if *stopped.borrow() && !matches!(result, Ok(true)) {
return;
}
match result {
Ok(true) => {
update(&app, &id, |i| {
i.status = Status::Completed;
i.error = None;
i.speed = 0;
i.received = i.total.max(i.received);
});
@ -236,6 +277,30 @@ fn spawn<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
});
}
/// Drops the worker entry, unless a newer task has taken it over.
fn release<R: Runtime>(app: &AppHandle<R>, id: &str, generation: u64) {
let state = app.state::<Downloads>();
let mut workers = state.workers.lock();
if workers.get(id).map(|w| w.generation) == Some(generation) {
workers.remove(id);
}
}
/// The download's file is in place and nothing is left to transfer.
fn finished_file<R: Runtime>(app: &AppHandle<R>, id: &str) -> bool {
let Some(path) = app.state::<Downloads>().items.lock().iter().find(|i| i.id == id).map(|i| PathBuf::from(&i.file_path)) else { return false };
path.exists() && !part_path(&path).exists()
}
fn part_path(path: &Path) -> PathBuf {
path.with_extension(format!("{}.part", path.extension().and_then(|e| e.to_str()).unwrap_or("bin")))
}
/// Resolves once a worker task has exited.
async fn exited(mut done: watch::Receiver<()>) {
while done.changed().await.is_ok() {}
}
async fn cancelled(mut rx: watch::Receiver<bool>) {
while !*rx.borrow() {
if rx.changed().await.is_err() {
@ -248,10 +313,7 @@ async fn cancelled(mut rx: watch::Receiver<bool>) {
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 part_path = part_path(&final_path);
let existing = tokio::fs::metadata(&part_path).await.map(|m| m.len()).unwrap_or(0);
let client = app.state::<Downloads>().client.clone();
@ -259,7 +321,10 @@ async fn transfer<R: Runtime>(app: &AppHandle<R>, id: &str, url: &str, rx: watch
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 response = tokio::select! {
r = request.send() => r.map_err(|e| format!("Could not reach the server: {e}"))?,
_ = cancelled(rx.clone()) => return Ok(false),
};
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());
@ -336,10 +401,14 @@ async fn transfer<R: Runtime>(app: &AppHandle<R>, id: &str, url: &str, rx: watch
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);
}
/// Stops the transfer for `id`, if one is running; the receiver closes once it has exited.
/// The entry stays until then, so a task started meanwhile knows to wait for it.
fn cancel<R: Runtime>(app: &AppHandle<R>, id: &str) -> Option<watch::Receiver<()>> {
let state = app.state::<Downloads>();
let workers = state.workers.lock();
let worker = workers.get(id)?;
let _ = worker.cancel.send(true);
Some(worker.done.clone())
}
#[tauri::command]
@ -356,7 +425,7 @@ pub fn download_pause<R: Runtime>(app: AppHandle<R>, id: String) {
#[tauri::command]
pub fn download_resume<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
cancel(&app, &id);
// `spawn` takes over from a transfer still winding down.
update(&app, &id, |i| {
i.status = Status::Queued;
i.error = None;
@ -366,7 +435,7 @@ pub fn download_resume<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
#[tauri::command]
pub async fn download_remove<R: Runtime>(app: AppHandle<R>, id: String, delete_files: bool) -> Result<(), String> {
cancel(&app, &id);
let running = cancel(&app, &id);
let removed = {
let state = app.state::<Downloads>();
let mut items = state.items.lock();
@ -375,14 +444,24 @@ pub async fn download_remove<R: Runtime>(app: AppHandle<R>, id: String, delete_f
};
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 the cancelled transfer release its file handle first.
if let Some(done) = running {
let _ = tokio::time::timeout(Duration::from_secs(10), exited(done)).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;
let _ = tokio::fs::remove_file(part_path(&path)).await;
// Older downloads shared artwork between a season's episodes: keep what others still use.
let in_use: HashSet<String> = app
.state::<Downloads>()
.items
.lock()
.iter()
.filter_map(|i| i.meta.get("localAssets").and_then(Value::as_object))
.flat_map(|a| a.values().filter_map(Value::as_str).map(str::to_owned))
.collect();
if let Value::Object(assets) = &item.meta["localAssets"] {
for v in assets.values() {
if let Some(p) = v.as_str() {
if let Some(p) = v.as_str().filter(|p| !in_use.contains(*p)) {
let _ = tokio::fs::remove_file(p).await;
}
}