From 8cfa0f05eb31acb4539b7c8749989c40f50ed234 Mon Sep 17 00:00:00 2001 From: IxianPixel Date: Fri, 6 Nov 2026 17:34:22 +0000 Subject: [PATCH] Warn before watch history is left behind, and re-apply it later (#2) --- CHANGELOG.md | 8 ++ README.md | 7 +- crates/jm-core/src/job.rs | 6 + crates/jm-core/src/userdata.rs | 29 +++++ crates/jm-server/examples/demo.rs | 17 ++- crates/jm-server/src/api.rs | 109 +++++++++++++++++++ crates/jm-server/src/export.rs | 115 +++++++++++++------- crates/jm-server/src/peer.rs | 32 +++++- crates/jm-server/src/runner.rs | 114 +++++++++++++++---- crates/jm-server/tests/e2e.rs | 89 +++++++++++++++ crates/jm-server/tests/fake_jellyfin/mod.rs | 38 ++++++- docs/ARCHITECTURE.md | 2 + ui/src/lib/Jobs.svelte | 45 ++++++++ ui/src/lib/Library.svelte | 63 ++++++++++- ui/src/lib/api.ts | 10 ++ 15 files changed, 611 insertions(+), 73 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 706dd85..9114f88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,12 @@ TVDB/TMDB/IMDb ID, then name), bringing the show's NFO and artwork only if that server doesn't have the show. Moving the last season also trashes the leftover show folder on the source. (#4) +- **Warning before watch history is left behind.** Moving something asks + first if anyone with watch history for it has no account on the other + server. Dry runs and the move itself say so too. (#2) +- **Re-apply watch history.** A finished move remembers whose history it + couldn't apply. Once their account exists, one button in Moves applies it, + without touching anyone else's. (#2) ### Updated @@ -33,6 +39,8 @@ next scan. Sizes of folders a move touched are measured again at once. (#1) - **Switching servers in the Library could show an empty list** when both libraries had the same ID. +- **Errors passed on from the other server** now show its message rather than + raw JSON and an HTTP status. ## v0.1.1 diff --git a/README.md b/README.md index 267d2ad..75ce43c 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,12 @@ One agent runs next to each Jellyfin and sees the same media folders. The 4. **Index.** The destination asks Jellyfin to scan that folder, then waits until the item and every episode appear. 5. **Restore watch history.** Jellyfin gives moved files new item IDs, so - jellymove re-applies each user's data to the new items, matching users by name. + jellymove re-applies each user's data to the new items, matching users by + name. Before a move starts, jellymove warns if someone with watch history + has no account on the other server. If you move anyway, their history is + kept with the move: create the user there, then use **Re-apply watch + history** on the move in Moves. Only their history is applied, so anything + others have watched since is left alone. 6. **Clean up.** The source moves its folder to `.jellymove-trash/` in the same library and rescans. It is not deleted: the **Trash** tab shows what's waiting on each server, how much space it uses, and empties it when you're diff --git a/crates/jm-core/src/job.rs b/crates/jm-core/src/job.rs index d1df5a3..e414e5f 100644 --- a/crates/jm-core/src/job.rs +++ b/crates/jm-core/src/job.rs @@ -206,6 +206,11 @@ pub struct Job { /// into a show the destination already has. #[serde(default)] pub skip_files: Vec, + /// Users with watch state on the source who have no account here, so + /// their watch state wasn't (or won't be) applied. Their records stay in + /// `export.user_data` and can be re-applied once the account exists. + #[serde(default)] + pub missing_users: Vec, pub progress: Progress, /// Human-readable log of what happened, newest last. pub log: Vec, @@ -238,6 +243,7 @@ impl Job { target_item_id: None, target_location: None, skip_files: Vec::new(), + missing_users: Vec::new(), progress: Progress::default(), log: Vec::new(), } diff --git a/crates/jm-core/src/userdata.rs b/crates/jm-core/src/userdata.rs index c37fb1e..6f0b4f4 100644 --- a/crates/jm-core/src/userdata.rs +++ b/crates/jm-core/src/userdata.rs @@ -51,10 +51,39 @@ pub fn same_user(a: &str, b: &str) -> bool { a.trim().eq_ignore_ascii_case(b.trim()) } +/// Users with watch state in `records` who have no account among `users`, +/// each named once, in the order they first appear. +pub fn missing_users<'a>( + records: &'a [UserDataRecord], + users: impl IntoIterator + Clone, +) -> Vec { + let mut out: Vec = Vec::new(); + for r in records { + let known = users.clone().into_iter().any(|u| same_user(u, &r.user_name)); + if !known && !out.iter().any(|m| same_user(m, &r.user_name)) { + out.push(r.user_name.clone()); + } + } + out +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn finds_users_with_no_account() { + let rec = |name: &str| UserDataRecord { + user_name: name.into(), + key: ItemKey::Root, + data: UserData::default(), + }; + let records = [rec("Alice"), rec("Bob"), rec("bob "), rec("Carol")]; + let here = ["alice", "Carol"]; + assert_eq!(missing_users(&records, here.iter().copied()), ["Bob"]); + assert!(missing_users(&records[..1], here.iter().copied()).is_empty()); + } + #[test] fn empty_detection() { assert!(UserData::default().is_empty()); diff --git a/crates/jm-server/examples/demo.rs b/crates/jm-server/examples/demo.rs index 0fc3293..f6fcf13 100644 --- a/crates/jm-server/examples/demo.rs +++ b/crates/jm-server/examples/demo.rs @@ -44,9 +44,14 @@ fn libs(root: &Path) -> Vec { #[tokio::main] async fn main() -> anyhow::Result<()> { tracing_subscriber_init(); - let tmp = tempfile::tempdir()?; - let cloud = tmp.path().join("cloud"); - let home = tmp.path().join("home"); + // One fixed folder, emptied on each start: a temp folder per run would + // be left behind (hundreds of MB) whenever the demo is killed. + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/demo"); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root)?; + let root = root.canonicalize()?; + let cloud = root.join("cloud"); + let home = root.join("home"); for r in [&cloud, &home] { std::fs::create_dir_all(r.join("movies"))?; std::fs::create_dir_all(r.join("tv"))?; @@ -82,7 +87,11 @@ async fn main() -> anyhow::Result<()> { let fake_cloud = Fake::new(libs(&cloud)); let fake_home = Fake::new(libs(&home)); + // Bob only has an account on cloud, so his watch history can't follow a + // move to home until one is created there. + fake_cloud.add_user("u2", "Bob"); if let Some(id) = fake_cloud.find("Movie", "Arrival") { + fake_cloud.set_user_data_for("u2", &id, serde_json::json!({"PlaybackPositionTicks": 36_000_000_000i64})); fake_cloud.set_user_data(&id, serde_json::json!({"Played": true, "PlayCount": 1})); } let jf_cloud = fake_cloud.serve().await; @@ -124,7 +133,7 @@ async fn main() -> anyhow::Result<()> { axum::serve(listener, jm_server::api::router(state)).await })); } - println!("demo media in {}", tmp.path().display()); + println!("demo media in {}", root.display()); println!("cloud: http://127.0.0.1:8097 home: http://127.0.0.1:8098 (Ctrl+C to stop)"); tokio::signal::ctrl_c().await?; Ok(()) diff --git a/crates/jm-server/src/api.rs b/crates/jm-server/src/api.rs index f375645..ab408c7 100644 --- a/crates/jm-server/src/api.rs +++ b/crates/jm-server/src/api.rs @@ -61,8 +61,10 @@ pub fn router(state: Shared) -> Router { .route("/items", get(ui_items)) .route("/seasons", get(ui_seasons)) .route("/moves", post(ui_move)) + .route("/moves/check", get(ui_check_move)) .route("/jobs", get(ui_jobs)) .route("/jobs/{id}/retry", post(ui_retry)) + .route("/jobs/{id}/reapply", post(ui_reapply)) .route("/trash", get(ui_trash)) .route("/trash/empty", post(ui_empty_trash)) .route("/events", get(events)); @@ -77,6 +79,9 @@ pub fn router(state: Shared) -> Router { .route("/exports/{id}/files/{idx}", get(peer_file)) .route("/exports/{id}/complete", post(peer_complete_export)) .route("/jobs", get(peer_jobs).post(peer_create_job)) + .route("/jobs/{id}/reapply", post(peer_reapply)) + .route("/users", get(peer_users)) + .route("/watchers", get(peer_watchers)) .route("/trash", get(peer_trash)) .route("/trash/empty", post(peer_empty_trash)) .layer(middleware::from_fn_with_state( @@ -337,6 +342,72 @@ async fn ui_jobs(State(state): State) -> ApiResult { })) } +#[derive(Deserialize)] +struct CheckMoveQuery { + /// Where the item is now. + from: Side, + item_id: String, +} + +#[derive(Serialize)] +struct MoveCheck { + /// Users with watch state for the item on the source. + watchers: Vec, + /// Those of them with no account on the destination, whose watch state + /// won't carry over. + missing_users: Vec, +} + +/// Before a move: whose watch history wouldn't carry over, because the +/// destination has no user with that name. +async fn ui_check_move( + State(state): State, + Query(q): Query, +) -> ApiResult { + let peer = state.peer()?; + let (watchers, dest_users) = match q.from { + Side::Local => ( + export::watchers(&state, &q.item_id).await?, + peer.users().await?, + ), + Side::Peer => ( + peer.watchers(&q.item_id).await?, + state + .jellyfin + .users() + .await? + .into_iter() + .map(|u| u.name) + .collect(), + ), + }; + let missing_users = watchers + .iter() + .filter(|w| !dest_users.iter().any(|u| jm_core::userdata::same_user(u, w))) + .cloned() + .collect(); + Ok(Json(MoveCheck { + watchers, + missing_users, + })) +} + +/// Re-apply skipped watch history on a finished move. The job lives on the +/// destination, which may be the peer. +async fn ui_reapply(State(state): State, Path(id): Path) -> ApiResult { + let job_id: JobId = id + .parse() + .map_err(|_| ApiError(StatusCode::BAD_REQUEST, "bad job id".into()))?; + match state.store.get_job(job_id).await? { + Some(job) => { + let mut job = runner::reapply_user_data(&state, job).await?; + job.export = None; + Ok(Json(job)) + } + None => Ok(Json(state.peer()?.reapply(&id).await?)), + } +} + async fn ui_retry(State(state): State, Path(id): Path) -> ApiResult { let id: JobId = id .parse() @@ -518,6 +589,44 @@ async fn peer_create_job( Ok(Json(job)) } +async fn peer_reapply(State(state): State, Path(id): Path) -> ApiResult { + let job_id: JobId = id + .parse() + .map_err(|_| ApiError(StatusCode::BAD_REQUEST, "bad job id".into()))?; + let job = state + .store + .get_job(job_id) + .await? + .ok_or(ApiError(StatusCode::NOT_FOUND, "no such job".into()))?; + let mut job = runner::reapply_user_data(&state, job).await?; + job.export = None; + Ok(Json(job)) +} + +async fn peer_users(State(state): State) -> ApiResult> { + Ok(Json( + state + .jellyfin + .users() + .await? + .into_iter() + .map(|u| u.name) + .collect(), + )) +} + +#[derive(Deserialize)] +struct WatchersQuery { + item: String, +} + +async fn peer_watchers( + State(state): State, + Query(q): Query, +) -> ApiResult> { + Ok(Json(export::watchers(&state, &q.item).await?)) +} + async fn peer_jobs(State(state): State) -> ApiResult> { let mut jobs = state.store.list_jobs(100).await?; for j in &mut jobs { diff --git a/crates/jm-server/src/export.rs b/crates/jm-server/src/export.rs index a247bb6..280ae8c 100644 --- a/crates/jm-server/src/export.rs +++ b/crates/jm-server/src/export.rs @@ -288,48 +288,7 @@ async fn prepare(state: &AppState, item_id: &str) -> anyhow::Result<(ExportInfo, } // Capture each user's watch state now, before anything moves. - let mut user_data = Vec::new(); - let mut episode_keys = Vec::new(); - for user in jf.users().await? { - // A season's own watch state isn't carried: on the destination it - // would land on the whole show. - if kind != ItemKind::Season { - let root = jf - .items(&ItemQuery { - ids: Some(item_id), - user_id: Some(&user.id), - ..Default::default() - }) - .await?; - if let Some(ud) = root.into_iter().next().and_then(|i| i.user_data) { - push_record(&mut user_data, &user.name, ItemKey::Root, ud.into()); - } - } - if kind.has_episodes() { - let episodes = jf - .items(&ItemQuery { - parent_id: Some(item_id), - include_types: &["Episode"], - recursive: true, - user_id: Some(&user.id), - ..Default::default() - }) - .await?; - for ep in episodes { - let (Some(season), Some(episode)) = (ep.parent_index_number, ep.index_number) - else { - continue; - }; - let key = ItemKey::Episode { season, episode }; - if !episode_keys.contains(&key) { - episode_keys.push(key); - } - if let Some(ud) = ep.user_data { - push_record(&mut user_data, &user.name, key, ud.into()); - } - } - } - } + let (user_data, episode_keys) = capture_user_data(state, item_id, kind).await?; let (name, season) = match season { None => (item.name, None), @@ -369,6 +328,78 @@ async fn prepare(state: &AppState, item_id: &str) -> anyhow::Result<(ExportInfo, Ok((info, folder.display().to_string(), location)) } +/// Every user's watch state for an item: the item itself (not for a season, +/// whose own state would land on the whole show at the destination) and, for +/// shows and seasons, each episode. Also returns every episode's key. +pub async fn capture_user_data( + state: &AppState, + item_id: &str, + kind: ItemKind, +) -> anyhow::Result<(Vec, Vec)> { + let jf = &state.jellyfin; + let mut user_data = Vec::new(); + let mut episode_keys = Vec::new(); + for user in jf.users().await? { + if kind != ItemKind::Season { + let root = jf + .items(&ItemQuery { + ids: Some(item_id), + user_id: Some(&user.id), + ..Default::default() + }) + .await?; + if let Some(ud) = root.into_iter().next().and_then(|i| i.user_data) { + push_record(&mut user_data, &user.name, ItemKey::Root, ud.into()); + } + } + if kind.has_episodes() { + let episodes = jf + .items(&ItemQuery { + parent_id: Some(item_id), + include_types: &["Episode"], + recursive: true, + user_id: Some(&user.id), + ..Default::default() + }) + .await?; + for ep in episodes { + let (Some(season), Some(episode)) = (ep.parent_index_number, ep.index_number) + else { + continue; + }; + let key = ItemKey::Episode { season, episode }; + if !episode_keys.contains(&key) { + episode_keys.push(key); + } + if let Some(ud) = ep.user_data { + push_record(&mut user_data, &user.name, key, ud.into()); + } + } + } + } + Ok((user_data, episode_keys)) +} + +/// Names of the users who have watch state for an item, for the check before +/// a move. +pub async fn watchers(state: &AppState, item_id: &str) -> anyhow::Result> { + let item = state.jellyfin.item(item_id).await?; + let kind = match item.kind.as_str() { + "Movie" => ItemKind::Movie, + "Series" => ItemKind::Series, + "Season" => ItemKind::Season, + other => bail!("can only move movies, shows and seasons, not {other}"), + }; + let (records, _) = capture_user_data(state, item_id, kind).await?; + let mut names: Vec = Vec::new(); + for r in records { + if !names.contains(&r.user_name) { + names.push(r.user_name); + } + } + Ok(names) +} + fn push_record( out: &mut Vec, user: &str, diff --git a/crates/jm-server/src/peer.rs b/crates/jm-server/src/peer.rs index ed0e413..972f25b 100644 --- a/crates/jm-server/src/peer.rs +++ b/crates/jm-server/src/peer.rs @@ -58,7 +58,14 @@ impl PeerClient { let status = resp.status(); if !status.is_success() { let body = resp.text().await.unwrap_or_default(); - anyhow::bail!("peer refused {what}: HTTP {status}: {body}"); + // Our own API answers {"error": "..."}; pass on just the message. + let message = serde_json::from_str::(&body) + .ok() + .and_then(|v| v.get("error")?.as_str().map(str::to_string)); + match message { + Some(m) => anyhow::bail!("peer refused {what}: {m}"), + None => anyhow::bail!("peer refused {what}: HTTP {status}: {body}"), + } } Ok(resp.json().await?) } @@ -145,6 +152,29 @@ impl PeerClient { .await } + /// Names of the users on the peer's Jellyfin. + pub async fn users(&self) -> anyhow::Result> { + self.send(self.http.get(self.url("/users")), "list users") + .await + } + + /// Users on the peer with watch state for one of its items. + pub async fn watchers(&self, item_id: &str) -> anyhow::Result> { + self.send( + self.http.get(self.url("/watchers")).query(&[("item", item_id)]), + "check watch history", + ) + .await + } + + pub async fn reapply(&self, job_id: &str) -> anyhow::Result { + self.send( + self.http.post(self.url(&format!("/jobs/{job_id}/reapply"))), + "re-apply watch history", + ) + .await + } + pub async fn jobs(&self) -> anyhow::Result> { self.send(self.http.get(self.url("/jobs")), "list jobs") .await diff --git a/crates/jm-server/src/runner.rs b/crates/jm-server/src/runner.rs index b2bd579..312fbdc 100644 --- a/crates/jm-server/src/runner.rs +++ b/crates/jm-server/src/runner.rs @@ -8,7 +8,7 @@ use anyhow::{Context, bail}; use jm_core::job::{ExportInfo, SeasonInfo}; use jm_core::paths::join_relative; use jm_core::safety::check_inside_library; -use jm_core::userdata::{ItemKey, same_user}; +use jm_core::userdata::{ItemKey, UserDataRecord, missing_users, same_user}; use jm_core::{ItemKind, Job, JobStatus, Stage}; use jm_jellyfin::ItemQuery; @@ -230,6 +230,17 @@ async fn plan(state: &Shared, job: &mut Job) -> anyhow::Result { lib.name, )); job.skip_files = skip; + + // Watch state is matched to users by name; say now whose won't carry over. + let users = state.jellyfin.users().await?; + job.missing_users = missing_users(&info.user_data, users.iter().map(|u| u.name.as_str())); + if !job.missing_users.is_empty() { + job.note(format!( + "watch history won't carry over for {}: no user with that name on this server. \ + Create them in Jellyfin here first, or re-apply it from Moves afterwards", + job.missing_users.join(", ") + )); + } job.export = Some(info); if job.dry_run { @@ -493,6 +504,34 @@ async fn missing_episodes( async fn apply_user_data(state: &Shared, job: &mut Job) -> anyhow::Result<()> { let info = info(job)?.clone(); + let (applied, no_item, missing) = apply_records(state, job, &info.user_data).await?; + job.note(format!("restored {applied} watch-state records")); + if !missing.is_empty() { + job.note(format!( + "skipped watch history for users missing on this server: {}. \ + Create them in Jellyfin, then use Re-apply watch history in Moves", + missing.join(", ") + )); + } + if no_item > 0 { + job.note(format!( + "skipped {no_item} records whose episode wasn't found" + )); + } + job.missing_users = missing; + job.advance(Stage::UserDataApplied); + Ok(()) +} + +/// Write `records` to the moved item and its episodes for every user who has +/// an account here. Returns (records applied, records whose episode wasn't +/// found, users with no account). +async fn apply_records( + state: &Shared, + job: &Job, + records: &[UserDataRecord], +) -> anyhow::Result<(usize, usize, Vec)> { + let info = info(job)?; let root_id = job.target_item_id.clone().context("no target item")?; let episodes = if info.kind.has_episodes() { episode_ids(state, &root_id).await? @@ -500,15 +539,11 @@ async fn apply_user_data(state: &Shared, job: &mut Job) -> anyhow::Result<()> { HashMap::new() }; let users = state.jellyfin.users().await?; + let missing = missing_users(records, users.iter().map(|u| u.name.as_str())); - let (mut applied, mut no_user, mut no_item) = (0, 0, 0); - let mut unknown_users: Vec = Vec::new(); - for rec in &info.user_data { + let (mut applied, mut no_item) = (0, 0); + for rec in records { let Some(user) = users.iter().find(|u| same_user(&u.name, &rec.user_name)) else { - no_user += 1; - if !unknown_users.contains(&rec.user_name) { - unknown_users.push(rec.user_name.clone()); - } continue; }; let item_id = match rec.key { @@ -525,20 +560,59 @@ async fn apply_user_data(state: &Shared, job: &mut Job) -> anyhow::Result<()> { .await?; applied += 1; } - job.note(format!("restored {applied} watch-state records")); - if no_user > 0 { - job.note(format!( - "skipped {no_user} records for users missing on this server: {}", - unknown_users.join(", ") - )); + Ok((applied, no_item, missing)) +} + +/// After a move, apply the watch state of users who had no account here at +/// the time, once their accounts exist. Only their records are applied, so +/// anything other users have watched since is left alone. +pub async fn reapply_user_data(state: &Shared, mut job: Job) -> anyhow::Result { + if job.dry_run || job.status != JobStatus::Done { + bail!("watch history can only be re-applied to a finished move"); } - if no_item > 0 { - job.note(format!( - "skipped {no_item} records whose episode wasn't found" - )); + if job.missing_users.is_empty() { + bail!("this move has no skipped watch history to re-apply"); } - job.advance(Stage::UserDataApplied); - Ok(()) + let info = info(&job)?.clone(); + let root_id = job.target_item_id.clone().context("no target item")?; + if state.jellyfin.item(&root_id).await.is_err() { + bail!( + "{} is no longer where it was moved to on {} (moved again?), \ + so its watch history can't be re-applied", + job.name, + state.cfg.node_name + ); + } + let users = state.jellyfin.users().await?; + let records: Vec = info + .user_data + .iter() + .filter(|r| job.missing_users.iter().any(|m| same_user(m, &r.user_name))) + .cloned() + .collect(); + let still_missing = missing_users(&records, users.iter().map(|u| u.name.as_str())); + let here = &state.cfg.node_name; + if still_missing.len() == job.missing_users.len() { + bail!( + "there's no user called {} on {here} yet; create them in Jellyfin on {here} first", + still_missing.join(" or ") + ); + } + let (applied, no_item, missing) = apply_records(state, &job, &records).await?; + job.note(format!( + "re-applied {applied} watch-state records{}", + if no_item > 0 { + format!(" ({no_item} episodes not found)") + } else { + String::new() + } + )); + if !missing.is_empty() { + job.note(format!("still no user here called: {}", missing.join(", "))); + } + job.missing_users = missing; + state.save(&job).await?; + Ok(job) } async fn clean_source(state: &Shared, job: &mut Job) -> anyhow::Result<()> { diff --git a/crates/jm-server/tests/e2e.rs b/crates/jm-server/tests/e2e.rs index 40eaf62..aa195fe 100644 --- a/crates/jm-server/tests/e2e.rs +++ b/crates/jm-server/tests/e2e.rs @@ -726,6 +726,95 @@ async fn refuses_a_season_folder_holding_other_seasons() { ); } +#[tokio::test] +async fn warns_about_missing_users_and_reapplies_their_watch_state_later() { + let (cloud, home) = pair(seed_movie).await; + // Cloud has a second user, Bob, whom home doesn't know yet. + cloud.fake.add_user("u2", "Bob"); + let movie = cloud.fake.find("Movie", "Alien").unwrap(); + cloud.fake.set_user_data(&movie, json!({"Played": true})); + cloud + .fake + .set_user_data_for("u2", &movie, json!({"PlaybackPositionTicks": 777})); + + // Before moving, the UI can see whose watch history won't carry over, + // whichever side it asks from. + let check = get( + &cloud.url, + &format!("/api/moves/check?from=local&item_id={movie}"), + ) + .await; + assert_eq!(check["watchers"], json!(["Alice", "Bob"])); + assert_eq!(check["missing_users"], json!(["Bob"])); + let check = get( + &home.url, + &format!("/api/moves/check?from=peer&item_id={movie}"), + ) + .await; + assert_eq!(check["missing_users"], json!(["Bob"])); + + // A dry run says so too. + let dry: Value = post( + &cloud.url, + "/api/moves", + json!({"from": "local", "item_id": movie, "name": "Alien", "dry_run": true}), + ) + .await + .json() + .await + .unwrap(); + let dry = wait_job(&cloud.url, dry["id"].as_str().unwrap()).await; + assert_eq!(dry["status"]["kind"], "Planned"); + assert_eq!(dry["missing_users"], json!(["Bob"])); + assert!( + dry["log"] + .as_array() + .unwrap() + .iter() + .any(|l| l.as_str().unwrap().contains("won't carry over for Bob")), + "{dry:#}" + ); + + // The move goes ahead; Alice's watch state follows, Bob's is kept. + let job = move_item(&cloud.url, "local", &movie, "Alien").await; + assert_eq!(job["missing_users"], json!(["Bob"])); + let new_id = home.fake.find("Movie", "Alien").unwrap(); + assert_eq!(home.fake.get_user_data(&new_id).unwrap()["Played"], true); + let id = job["id"].as_str().unwrap(); + + // Re-applying before Bob has an account explains what to do. + let r = post(&cloud.url, &format!("/api/jobs/{id}/reapply"), json!({})).await; + assert!(!r.status().is_success()); + let text = r.text().await.unwrap(); + assert!( + text.contains("no user called Bob on home yet; create them in Jellyfin on home first"), + "{text}" + ); + assert!(!text.contains("HTTP 502"), "{text}"); + + // Alice carries on watching on home in the meantime. + home.fake + .set_user_data(&new_id, json!({"Played": true, "PlayCount": 5})); + + // Once home has a "bob" (names match ignoring case), re-apply from the + // cloud UI: the job runs on home, so the request is passed on. + home.fake.add_user("u9", "bob"); + let r = post(&cloud.url, &format!("/api/jobs/{id}/reapply"), json!({})).await; + assert!(r.status().is_success(), "{}", r.text().await.unwrap()); + let job: Value = r.json().await.unwrap(); + assert_eq!(job["missing_users"], json!([])); + assert_eq!( + home.fake.get_user_data_for("u9", &new_id).unwrap()["PlaybackPositionTicks"], + 777 + ); + // Alice's newer watch state wasn't overwritten by the old snapshot. + assert_eq!(home.fake.get_user_data(&new_id).unwrap()["PlayCount"], 5); + + // Nothing left to re-apply. + let r = post(&home.url, &format!("/api/jobs/{id}/reapply"), json!({})).await; + assert!(r.text().await.unwrap().contains("no skipped watch history")); +} + #[tokio::test] async fn peer_api_rejects_bad_token_and_ui_requires_csrf_header() { let (cloud, _home) = pair(|_| {}).await; diff --git a/crates/jm-server/tests/fake_jellyfin/mod.rs b/crates/jm-server/tests/fake_jellyfin/mod.rs index 09393c2..200adb1 100644 --- a/crates/jm-server/tests/fake_jellyfin/mod.rs +++ b/crates/jm-server/tests/fake_jellyfin/mod.rs @@ -47,6 +47,8 @@ pub struct Fake { items: Arc>>, /// (user id, item id) → UserData JSON pub user_data: Arc>>, + /// (user id, name) + users: Arc>>, } pub fn id_for(path: &Path) -> String { @@ -103,6 +105,7 @@ impl Fake { libs: Arc::new(libs), items: Default::default(), user_data: Default::default(), + users: Arc::new(Mutex::new(vec![("u1".into(), "Alice".into())])), }; f.scan(); f @@ -258,6 +261,25 @@ impl Fake { .map(|i| i.id.clone()) } + pub fn add_user(&self, id: &str, name: &str) { + self.users.lock().unwrap().push((id.into(), name.into())); + } + + pub fn set_user_data_for(&self, user: &str, item: &str, data: Value) { + self.user_data + .lock() + .unwrap() + .insert((user.into(), item.into()), data); + } + + pub fn get_user_data_for(&self, user: &str, item: &str) -> Option { + self.user_data + .lock() + .unwrap() + .get(&(user.to_string(), item.to_string())) + .cloned() + } + pub fn set_user_data(&self, item: &str, data: Value) { self.user_data .lock() @@ -281,10 +303,7 @@ impl Fake { Json(json!({"ServerName": "fake", "Version": "10.11.0", "Id": "x"})) }), ) - .route( - "/Users", - get(|| async { Json(json!([{"Id": "u1", "Name": "Alice"}])) }), - ) + .route("/Users", get(users)) .route("/Library/VirtualFolders", get(virtual_folders)) .route("/Items", get(items)) .route("/Library/Media/Updated", post(media_updated)) @@ -297,6 +316,17 @@ impl Fake { } } +async fn users(State(f): State) -> Json { + Json(Value::Array( + f.users + .lock() + .unwrap() + .iter() + .map(|(id, name)| json!({"Id": id, "Name": name})) + .collect(), + )) +} + async fn virtual_folders(State(f): State) -> Json { Json(Value::Array( f.libs diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index b70b3c0..35f73ce 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -36,12 +36,14 @@ forwarding. | `GET /info` | Node name, version, Jellyfin version | | `GET /libraries`, `GET /items?library=&search=` | Browse the peer's Jellyfin | | `GET /seasons?series=` | A show's seasons, with each one's folder if it has its own | +| `GET /users`, `GET /watchers?item=` | User names; users with watch state for an item. Used to warn before a move whose watch history wouldn't carry over | | `POST /exports {item_id}` | Source: start checking, hashing and capturing user data. Idempotent per item. | | `GET /exports/{id}` | Poll: `Preparing` → `Ready` (with `ExportInfo`) or `Failed` | | `GET /exports/{id}/files/{idx}` | Range-capable download of manifest entry `idx` | | `POST /exports/{id}/complete {job_id?, moved_to?}` | Source: move folder to a new trash entry and rescan. Idempotent. | | `GET /trash`, `POST /trash/empty {ids}` | List the source's trash entries; delete entries by ID (never by path) | | `POST /jobs`, `GET /jobs` | Create or list jobs on the peer (destination) | +| `POST /jobs/{id}/reapply` | Apply the watch state of users who had no account when the move ran (`Job.missing_users`), once they do | ## Job stages diff --git a/ui/src/lib/Jobs.svelte b/ui/src/lib/Jobs.svelte index a321dcc..f199a3b 100644 --- a/ui/src/lib/Jobs.svelte +++ b/ui/src/lib/Jobs.svelte @@ -8,11 +8,24 @@ let { localName }: Props = $props(); let retryError = $state(null); + let reapplying = $state(null); let open = $state>({}); const sorted = $derived(Object.values(moves.jobs).sort((a, b) => b.created.localeCompare(a.created))); const error = $derived(retryError ?? moves.error); + async function reapply(id: string) { + reapplying = id; + try { + trackMove(await api.reapply(id)); + retryError = null; + } catch (e) { + retryError = (e as Error).message; + } finally { + reapplying = null; + } + } + async function retry(id: string) { try { trackMove(await api.retry(id)); @@ -97,6 +110,21 @@

{j.status.detail}

{/if} + {#if j.missing_users?.length} + {@const one = j.missing_users.length === 1} + {@const done = j.status.kind === 'Done'} +
+

+ Watch history {done ? "didn't" : "won't"} carry over for {j.missing_users.join(', ')}: + {j.target_node} has no user with {one ? 'that name' : 'those names'}. + {#if done}Create {one ? 'the user' : 'them'} in Jellyfin on {j.target_node}, then re-apply it.{/if} +

+ {#if done} + + {/if} +
+ {/if} + @@ -229,6 +257,23 @@ margin: 0.7rem 0 0; font-size: 0.9rem; } + .missing { + margin-top: 0.7rem; + padding: 0.6rem 0.8rem; + border: 1px solid color-mix(in srgb, var(--local) 55%, var(--line)); + border-radius: 8px; + font-size: 0.9rem; + display: flex; + gap: 0.8rem; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + } + .missing p { + margin: 0; + flex: 1; + min-width: 16rem; + } .logtoggle { margin-top: 0.7rem; font-size: 0.8rem; diff --git a/ui/src/lib/Library.svelte b/ui/src/lib/Library.svelte index d3188d3..555de22 100644 --- a/ui/src/lib/Library.svelte +++ b/ui/src/lib/Library.svelte @@ -196,11 +196,28 @@ return () => clearTimeout(timer); }); - async function move(item: Movable, dryRun: boolean) { + /** A move waiting for the user to accept that some watch history won't carry over. */ + type Confirm = { item: Movable; missing: string[] }; + let confirming = $state(null); + + function names(list: string[]): string { + return list.length < 2 ? list.join('') : `${list.slice(0, -1).join(', ')} and ${list[list.length - 1]}`; + } + + async function move(item: Movable, dryRun: boolean, checked = false) { busy = item.id; notice = null; error = null; + confirming = null; try { + // Watch history is matched by user name; warn before it gets left behind. + if (!dryRun && !checked) { + const check = await api.checkMove(side, item); + if (check.missing_users.length) { + confirming = { item, missing: check.missing_users }; + return; + } + } trackMove(await api.move(side, item, dryRun)); notice = dryRun ? `Planning a dry run for “${item.name}”. Check Moves for the plan.` @@ -213,6 +230,22 @@ } +{#snippet missingUsers(c: Confirm)} + {@const one = c.missing.length === 1} +
+

+ {names(c.missing)} + {one ? 'has' : 'have'} watch history for this, but {destName} has no user with {one ? 'that name' : 'those names'}, so + it won't carry over. Create {one ? 'the user' : 'them'} in Jellyfin on {destName} first, or move anyway and re-apply + it later from Moves. +

+
+ + +
+
+{/snippet} + {#snippet moveTag(mark: Mark)} {#if mark.moving} Moving to {mark.to}… @@ -293,6 +326,9 @@ {/if} + {#if confirming?.item.id === item.id} + {@render missingUsers(confirming)} + {/if} {#if open[item.id]} {@const st = seasons[item.id]} {#if !st || 'loading' in st} @@ -324,6 +360,9 @@ {/if} + {#if confirming?.item.id === season.id} + {@render missingUsers(confirming)} + {/if} {:else} Jellyfin lists no seasons for this show. {/each} @@ -446,6 +485,28 @@ padding-right: 0; white-space: nowrap; } + .confirm-move { + margin: 0.6rem 0 0.1rem 3.5rem; + padding: 0.7rem 0.9rem; + border: 1px solid color-mix(in srgb, var(--local) 55%, var(--line)); + border-radius: 8px; + font-size: 0.9rem; + white-space: normal; + } + .parts .confirm-move { + margin-left: 0; + } + .parts td.wrap { + white-space: normal; + } + .confirm-move p { + margin: 0; + } + .confirm-buttons { + display: flex; + gap: 0.4rem; + margin-top: 0.6rem; + } .tag { font-size: 0.82rem; border: 1px solid var(--line); diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index da4b2bf..50a6e35 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -105,6 +105,13 @@ export interface Job { target_folder_jellyfin: string | null; progress: { bytes_done: number; bytes_total: number; current_file: string | null }; log: string[]; + /** Users whose watch history didn't (or won't) carry over: no account on the target. */ + missing_users?: string[]; +} + +export interface MoveCheck { + watchers: string[]; + missing_users: string[]; } export interface JobsView { @@ -167,10 +174,13 @@ export const api = { ), seasons: (node: Side, series: string) => call('GET', `/seasons?${new URLSearchParams({ node, series })}`), + checkMove: (from: Side, item: Movable) => + call('GET', `/moves/check?${new URLSearchParams({ from, item_id: item.id })}`), move: (from: Side, item: Movable, dry_run: boolean) => call('POST', '/moves', { from, item_id: item.id, name: item.name, dry_run }), jobs: () => call('GET', '/jobs'), retry: (id: string) => call('POST', `/jobs/${id}/retry`), + reapply: (id: string) => call('POST', `/jobs/${id}/reapply`), trash: (node: Side) => call('GET', `/trash?node=${node}`), emptyTrash: (node: Side, ids: string[]) => call('POST', '/trash/empty', { node, ids }), };