diff --git a/CHANGELOG.md b/CHANGELOG.md index fca6d0c..0d2c33b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,11 @@ space it takes, counting everything a move copies, with a per-season breakdown for shows and a "Largest first" sort. Sizes are measured in the background and cached, so big libraries open straight away. (#5) +- **Move a single season.** Shows list their seasons with sizes and a move + button each. A season joins the same show on the other server (matched by + 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) ### Fixed diff --git a/CLAUDE.md b/CLAUDE.md index 76bccc8..1b20a80 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -56,7 +56,9 @@ enough while developing. never by path. Relative paths from a peer always go through `jm_core::paths::join_relative`, which rejects `..`, absolute paths and `\`. - **Never overwrite** at the destination: `plan` refuses if the target folder - exists; `promote` refuses on any clash before renaming anything. + exists (for a season, the season's folder inside the show); `promote` + refuses on any clash before renaming anything. A season going into a show + the destination already has skips the show's own files (`Job.skip_files`). - Partial/trash folders start with `.jellymove-` (Jellyfin skips dot-folders) and get a `.ignore` file. - Two path namespaces: what Jellyfin reports vs. what the agent sees. diff --git a/README.md b/README.md index e0ceb6e..267d2ad 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,20 @@ One agent runs next to each Jellyfin and sees the same media folders. The A crash or restart at any point resumes from the last completed step. +### Moving a single season + +In TV Shows, **Show seasons** lists a show's seasons with their sizes, each +with its own move button. A season moves into the same show on the other +server, found by its TVDB/TMDB/IMDb ID or its name, and its episodes keep +their watch history. If the other server doesn't have the show yet, the show's +own files (`tvshow.nfo`, posters) are copied with the season; if it does, they +are left alone. When the last season leaves a server, what's left of the show +folder goes to the trash with it. + +A season can only move on its own if it has its own folder (`Show/Season 02/`) +holding just that season's episodes. Specials (`Season 00` or `Specials`) work +the same way. + ## Quick look (no Jellyfin needed) ```sh @@ -172,7 +186,8 @@ host. Prefer a socket proxy that only allows restarts, or restart by hand. - Nothing leaves the source until the destination has indexed every file. - The source copy goes to `.jellymove-trash/`. Empty it from the **Trash** tab once you're happy (automatic retention is on the roadmap). -- Nothing at the destination is ever overwritten. +- Nothing at the destination is ever overwritten. A season move refuses if + that season's folder already exists there. - A movie must be in **its own folder**. jellymove refuses flat folders like `Movies/Heat.mkv` + `Movies/Ronin.mkv`, because moving "the folder" would take both. - Peers can only fetch files the source has explicitly exported, by index. @@ -189,7 +204,7 @@ host. Prefer a socket proxy that only allows restarts, or restart by hand. ## Roadmap -- Season-level moves; "promote" (pre-warm) shortcuts +- "Promote" (pre-warm) shortcuts - Automatic trash retention (e.g. empty after N days) - Pairing codes and pinned TLS instead of a shared token - Outbound-only control channel so a NATed home agent needs no inbound port diff --git a/crates/jm-core/src/job.rs b/crates/jm-core/src/job.rs index 9208824..d1df5a3 100644 --- a/crates/jm-core/src/job.rs +++ b/crates/jm-core/src/job.rs @@ -38,6 +38,16 @@ impl std::str::FromStr for JobId { pub enum ItemKind { Movie, Series, + /// One season of a series, moved on its own into the show's folder. + Season, +} + +impl ItemKind { + /// Whether the item has episodes whose watch state is mapped by + /// (season, episode). + pub fn has_episodes(self) -> bool { + matches!(self, ItemKind::Series | ItemKind::Season) + } } /// The last milestone a job has *completed*. The runner looks at the stage, @@ -129,10 +139,31 @@ pub struct ExportInfo { pub rel_folder: String, pub manifest: Manifest, pub user_data: Vec, - /// Every episode the source knows about (series only). The destination - /// waits until its scan has found all of them before anything is deleted. + /// Every episode the source knows about (series and seasons). The + /// destination waits until its scan has found all of them before anything + /// is deleted. #[serde(default)] pub episode_keys: Vec, + /// Set for a season move. `rel_folder` and the manifest are then the + /// show's folder, holding only this season's folder and the show's own + /// loose files. + #[serde(default)] + pub season: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SeasonInfo { + pub number: i32, + /// The season's folder inside the show folder, e.g. `Season 02`. + pub folder: String, + pub show_name: String, + /// The show's provider IDs (Tvdb, Tmdb, Imdb...), for finding the same + /// show on the destination. + #[serde(default)] + pub show_provider_ids: std::collections::HashMap, + /// Manifest indexes of the show's own files (tvshow.nfo, artwork). Only + /// copied when the destination doesn't have the show yet. + pub show_files: Vec, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] @@ -167,6 +198,14 @@ pub struct Job { pub target_folder_jellyfin: Option, /// Item ID Jellyfin assigned on the destination after the scan. pub target_item_id: Option, + /// Destination library location (Jellyfin namespace) holding the target + /// folder. Missing on jobs from before v0.2.0. + #[serde(default)] + pub target_location: Option, + /// Manifest indexes not to copy, e.g. a show's files when a season goes + /// into a show the destination already has. + #[serde(default)] + pub skip_files: Vec, pub progress: Progress, /// Human-readable log of what happened, newest last. pub log: Vec, @@ -197,6 +236,8 @@ impl Job { target_library: None, target_folder_jellyfin: None, target_item_id: None, + target_location: None, + skip_files: Vec::new(), progress: Progress::default(), log: Vec::new(), } diff --git a/crates/jm-jellyfin/src/lib.rs b/crates/jm-jellyfin/src/lib.rs index 146d315..d26b4e7 100644 --- a/crates/jm-jellyfin/src/lib.rs +++ b/crates/jm-jellyfin/src/lib.rs @@ -103,9 +103,12 @@ pub struct Item { /// Season number for episodes. #[serde(default)] pub parent_index_number: Option, - /// Episode number for episodes. + /// Episode number for episodes; season number for seasons. #[serde(default)] pub index_number: Option, + /// The series a season or episode belongs to. + #[serde(default)] + pub series_id: Option, #[serde(default)] pub user_data: Option, } diff --git a/crates/jm-server/examples/demo.rs b/crates/jm-server/examples/demo.rs index aac9efe..0fc3293 100644 --- a/crates/jm-server/examples/demo.rs +++ b/crates/jm-server/examples/demo.rs @@ -63,12 +63,18 @@ async fn main() -> anyhow::Result<()> { write(&base.join(format!("{folder}.en.srt")), 40_000); write(&base.join("poster.jpg"), 200_000); } - for ep in 1..=6 { - write( - &cloud.join(format!("tv/Severance/Season 01/Severance S01E{ep:02}.mkv")), - 20 * MB, - ); + for (season, eps) in [(1, 6), (2, 4)] { + for ep in 1..=eps { + write( + &cloud.join(format!( + "tv/Severance/Season {season:02}/Severance S{season:02}E{ep:02}.mkv" + )), + 20 * MB, + ); + } } + write(&cloud.join("tv/Severance/tvshow.nfo"), 2_000); + write(&cloud.join("tv/Severance/poster.jpg"), 300_000); write( &home.join("movies/The Thing (1982)/The Thing (1982).mkv"), 40 * MB, diff --git a/crates/jm-server/src/api.rs b/crates/jm-server/src/api.rs index 90ce051..f375645 100644 --- a/crates/jm-server/src/api.rs +++ b/crates/jm-server/src/api.rs @@ -20,7 +20,7 @@ use tokio_stream::StreamExt; use tokio_stream::wrappers::BroadcastStream; use crate::export::{self, CompleteRequest, Export, ExportStatus}; -use crate::library::{self, Library, LibraryItem, LocationCheck}; +use crate::library::{self, Library, LibraryItem, LocationCheck, SeasonItem}; use crate::peer::{CreateJob, NodeInfo}; use crate::runner; use crate::state::Shared; @@ -59,6 +59,7 @@ pub fn router(state: Shared) -> Router { .route("/status", get(status)) .route("/libraries", get(ui_libraries)) .route("/items", get(ui_items)) + .route("/seasons", get(ui_seasons)) .route("/moves", post(ui_move)) .route("/jobs", get(ui_jobs)) .route("/jobs/{id}/retry", post(ui_retry)) @@ -70,6 +71,7 @@ pub fn router(state: Shared) -> Router { .route("/info", get(peer_info)) .route("/libraries", get(peer_libraries)) .route("/items", get(peer_items)) + .route("/seasons", get(peer_seasons)) .route("/exports", post(peer_create_export)) .route("/exports/{id}", get(peer_get_export)) .route("/exports/{id}/files/{idx}", get(peer_file)) @@ -253,6 +255,23 @@ async fn ui_items( })) } +#[derive(Deserialize)] +struct SeasonsQuery { + #[serde(default)] + node: Side, + series: String, +} + +async fn ui_seasons( + State(state): State, + Query(q): Query, +) -> ApiResult> { + Ok(Json(match q.node { + Side::Local => library::seasons(&state, &q.series).await?, + Side::Peer => state.peer()?.seasons(&q.series).await?, + })) +} + #[derive(Deserialize)] struct MoveRequest { /// Where the item is now. @@ -402,6 +421,18 @@ async fn peer_items( )) } +#[derive(Deserialize)] +struct PeerSeasonsQuery { + series: String, +} + +async fn peer_seasons( + State(state): State, + Query(q): Query, +) -> ApiResult> { + Ok(Json(library::seasons(&state, &q.series).await?)) +} + #[derive(Deserialize)] struct CreateExport { item_id: String, diff --git a/crates/jm-server/src/export.rs b/crates/jm-server/src/export.rs index 93dfa42..97377af 100644 --- a/crates/jm-server/src/export.rs +++ b/crates/jm-server/src/export.rs @@ -7,9 +7,9 @@ use std::path::{Path, PathBuf}; use anyhow::{Context, bail}; use jm_core::ItemKind; -use jm_core::job::ExportInfo; +use jm_core::job::{ExportInfo, SeasonInfo}; use jm_core::paths::{join_relative, relative_inside}; -use jm_core::safety::{check_inside_library, check_movie_folder}; +use jm_core::safety::{FolderProblem, check_inside_library, check_movie_folder, is_video}; use jm_core::userdata::{ItemKey, UserDataRecord}; use jm_jellyfin::ItemQuery; use serde::{Deserialize, Serialize}; @@ -40,6 +40,10 @@ pub struct Export { /// Library location (Jellyfin namespace) containing the folder. #[serde(default)] pub jellyfin_location: String, + /// Trash entry folder chosen when completing, kept so a re-run after a + /// crash finishes in the same entry. + #[serde(default)] + pub trash_entry: Option, } impl Export { @@ -80,6 +84,7 @@ pub async fn create(state: &Shared, item_id: &str) -> anyhow::Result { info: None, jellyfin_folder: String::new(), jellyfin_location: String::new(), + trash_entry: None, }; state.store.put_export(&id, &export).await?; spawn_prepare(state.clone(), export.clone()); @@ -137,19 +142,57 @@ async fn prepare(state: &AppState, item_id: &str) -> anyhow::Result<(ExportInfo, let kind = match item.kind.as_str() { "Movie" => ItemKind::Movie, "Series" => ItemKind::Series, - other => bail!("can only move movies and series, not {other}"), + "Season" => ItemKind::Season, + other => bail!("can only move movies, shows and seasons, not {other}"), }; - let item_path = PathBuf::from( - item.path - .clone() - .context("Jellyfin did not report a path for this item")?, - ); + let item_path = match (&item.path, kind) { + (Some(p), _) => PathBuf::from(p), + (None, ItemKind::Season) => bail!( + "{} has no folder of its own (its episodes sit in the show folder); move the whole show instead", + item.name + ), + (None, _) => bail!("Jellyfin did not report a path for this item"), + }; + + // The folder handed over. For a season it's the show's folder, and the + // manifest is narrowed to the season's folder and the show's own files. + let mut season: Option<(jm_jellyfin::Item, String)> = None; let folder = match kind { ItemKind::Movie => item_path .parent() .context("movie path has no parent folder")? .to_path_buf(), ItemKind::Series => item_path.clone(), + ItemKind::Season => { + let series_id = item + .series_id + .clone() + .context("Jellyfin did not say which show this season belongs to")?; + let series = jf + .item(&series_id) + .await + .context("looking up the season's show on Jellyfin")?; + let show = PathBuf::from( + series + .path + .clone() + .context("Jellyfin did not report a path for the show")?, + ); + if item_path.parent() != Some(show.as_path()) { + bail!( + "{} has no folder of its own directly inside {}; move the whole show instead", + item.name, + show.display() + ); + } + let name = item_path + .file_name() + .and_then(|n| n.to_str()) + .context("season folder has no name")? + .to_string(); + season = Some((series, name)); + show + } }; let libraries = jf.virtual_folders().await?; @@ -198,9 +241,48 @@ async fn prepare(state: &AppState, item_id: &str) -> anyhow::Result<(ExportInfo, check_movie_folder(&files, &own)?; } - let manifest = jm_transfer::build_manifest(&local_folder) - .await - .context("hashing files")?; + let manifest = match &season { + None => jm_transfer::build_manifest(&local_folder).await, + Some((_, season_folder)) => { + // Other seasons' episodes must not ride along with this one. + let episodes = jf + .items(&ItemQuery { + parent_id: Some(item_id), + include_types: &["Episode"], + recursive: true, + ..Default::default() + }) + .await?; + let sl = local_folder.join(season_folder); + let files = tokio::task::spawn_blocking(move || jm_transfer::list_relative(&sl)).await??; + let own: Vec = episodes + .iter() + .flat_map(|e| { + e.media_sources + .iter() + .flatten() + .filter_map(|m| m.path.clone()) + .chain(e.path.clone()) + }) + .filter_map(|p| relative_inside(&item_path, Path::new(&p))) + .collect(); + if let Err(FolderProblem::SharedFolder(list)) = check_movie_folder(&files, &own) { + bail!( + "the {} folder also holds videos that aren't its episodes ({list}); \ + sort them into their own season folders first", + item.name + ); + } + // The season's folder, plus the show's own loose files (NFO, + // artwork). Loose videos belong to other seasons, so they stay. + let prefix = format!("{season_folder}/"); + jm_transfer::build_manifest_filtered(&local_folder, move |rel| { + rel.starts_with(&prefix) || (!rel.contains('/') && !is_video(rel)) + }) + .await + } + } + .context("hashing files")?; if manifest.files.is_empty() { bail!("the item folder is empty"); } @@ -209,17 +291,21 @@ async fn prepare(state: &AppState, item_id: &str) -> anyhow::Result<(ExportInfo, let mut user_data = Vec::new(); let mut episode_keys = Vec::new(); for user in jf.users().await? { - 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()); + // 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 == ItemKind::Series { + if kind.has_episodes() { let episodes = jf .items(&ItemQuery { parent_id: Some(item_id), @@ -245,15 +331,40 @@ async fn prepare(state: &AppState, item_id: &str) -> anyhow::Result<(ExportInfo, } } + let (name, season) = match season { + None => (item.name, None), + Some((series, season_folder)) => { + let show_files = manifest + .files + .iter() + .enumerate() + .filter(|(_, f)| !f.rel_path.contains('/')) + .map(|(i, _)| i) + .collect(); + ( + format!("{} – {}", series.name, item.name), + Some(SeasonInfo { + number: item + .index_number + .with_context(|| format!("Jellyfin gave {} no season number", item.name))?, + folder: season_folder, + show_name: series.name, + show_provider_ids: series.provider_ids, + show_files, + }), + ) + } + }; let info = ExportInfo { item_id: item_id.to_string(), - name: item.name, + name, kind, library_name: library.name.clone(), rel_folder, manifest, user_data, episode_keys, + season, }; Ok((info, folder.display().to_string(), location)) } @@ -294,7 +405,7 @@ pub async fn complete(state: &Shared, id: &str, req: CompleteRequest) -> anyhow: ExportStatus::Ready => {} other => bail!("export is not ready to complete ({other:?})"), } - let info = export.info.as_ref().context("export has no info")?; + let info = export.info.clone().context("export has no info")?; let local_folder = export.local_folder(state); let location_local = state .cfg @@ -302,9 +413,18 @@ pub async fn complete(state: &Shared, id: &str, req: CompleteRequest) -> anyhow: .to_local(Path::new(&export.jellyfin_location)); let trash_root = location_local.join(trash::TRASH_DIR); + // What leaves: the item's folder, or for a season just the season's folder. + let (moving, rel_moving) = match &info.season { + None => (local_folder.clone(), info.rel_folder.clone()), + Some(s) => ( + join_relative(&local_folder, &s.folder).context("unsafe season folder name")?, + format!("{}/{}", info.rel_folder, s.folder), + ), + }; + // Re-running after a crash: if the folder is already gone it was moved - // last time, so only the rescan and status update remain. - if tokio::fs::metadata(&local_folder).await.is_ok() { + // last time, so only the steps after it remain. + if tokio::fs::metadata(&moving).await.is_ok() { tokio::fs::create_dir_all(&trash_root).await?; let marker = trash_root.join(".ignore"); if tokio::fs::metadata(&marker).await.is_err() { @@ -312,8 +432,16 @@ pub async fn complete(state: &Shared, id: &str, req: CompleteRequest) -> anyhow: } // The same item can be trashed more than once (moved away, back, // and away again), so each move gets its own entry folder. - let entry_dir = trash::new_entry_dir(&trash_root, &export.id); - let trash = join_relative(&entry_dir, &info.rel_folder).context("unsafe folder name")?; + let entry_dir = match &export.trash_entry { + Some(d) => d.clone(), + None => { + let d = trash::new_entry_dir(&trash_root, &export.id); + export.trash_entry = Some(d.clone()); + state.store.put_export(&export.id, &export).await?; + d + } + }; + let trash = join_relative(&entry_dir, &rel_moving).context("unsafe folder name")?; if let Some(parent) = trash.parent() { tokio::fs::create_dir_all(parent).await?; } @@ -323,13 +451,13 @@ pub async fn complete(state: &Shared, id: &str, req: CompleteRequest) -> anyhow: name: info.name.clone(), kind: info.kind, library: info.library_name.clone(), - rel_folder: info.rel_folder.clone(), + rel_folder: rel_moving.clone(), moved_at: time::OffsetDateTime::now_utc(), moved_to: req.moved_to, job_id: req.job_id, }, )?; - if let Err(e) = tokio::fs::rename(&local_folder, &trash).await { + if let Err(e) = tokio::fs::rename(&moving, &trash).await { // Don't leave an empty entry behind in the trash view. Only the // metadata file and empty folders are removed, never contents. let _ = tokio::fs::remove_file(entry_dir.join(trash::META_FILE)).await; @@ -340,9 +468,20 @@ pub async fn complete(state: &Shared, id: &str, req: CompleteRequest) -> anyhow: } dir = d.parent(); } - return Err(e).with_context(|| format!("moving {} to the trash", local_folder.display())); + return Err(e).with_context(|| format!("moving {} to the trash", moving.display())); + } + tracing::info!(from = %moving.display(), to = %trash.display(), "source moved to trash"); + } + + // If that was the show's last season, what's left of the show folder + // (its NFO and artwork) joins the season in the same trash entry. + if let (Some(_), Some(entry_dir)) = (&info.season, &export.trash_entry) { + let show = local_folder.clone(); + let dest = join_relative(entry_dir, &info.rel_folder).context("unsafe folder name")?; + let emptied = tokio::task::spawn_blocking(move || trash_leftover_show(&show, &dest)).await??; + if emptied { + tracing::info!(folder = %local_folder.display(), "last season moved; show folder moved to trash"); } - tracing::info!(from = %local_folder.display(), to = %trash.display(), "source moved to trash"); } if let Err(e) = state @@ -356,3 +495,63 @@ pub async fn complete(state: &Shared, id: &str, req: CompleteRequest) -> anyhow: state.store.put_export(&export.id, &export).await?; Ok(export) } + +/// Move everything left in `show` into `dest` and remove `show`, but only if +/// no videos are left in it (so no seasons, episodes or extras remain). +/// Returns whether it did. +fn trash_leftover_show(show: &Path, dest: &Path) -> anyhow::Result { + if !std::fs::symlink_metadata(show).is_ok_and(|m| m.is_dir()) || has_videos(show) { + return Ok(false); + } + std::fs::create_dir_all(dest)?; + for e in std::fs::read_dir(show)?.flatten() { + let to = dest.join(e.file_name()); + if std::fs::symlink_metadata(&to).is_ok() { + bail!("{} is already in the trash", to.display()); + } + std::fs::rename(e.path(), &to) + .with_context(|| format!("moving {} to the trash", e.path().display()))?; + } + std::fs::remove_dir(show).with_context(|| format!("removing {}", show.display()))?; + Ok(true) +} + +fn has_videos(dir: &Path) -> bool { + let mut stack = vec![dir.to_path_buf()]; + while let Some(d) = stack.pop() { + for e in std::fs::read_dir(&d).into_iter().flatten().flatten() { + let Ok(t) = e.file_type() else { continue }; + if t.is_dir() { + stack.push(e.path()); + } else if is_video(&e.file_name().to_string_lossy()) { + return true; + } + } + } + false +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn leftover_show_is_trashed_only_without_videos() { + let tmp = tempfile::tempdir().unwrap(); + let show = tmp.path().join("Show"); + let dest = tmp.path().join("trash/Show"); + std::fs::create_dir_all(show.join("Season 02")).unwrap(); + std::fs::write(show.join("tvshow.nfo"), b"n").unwrap(); + std::fs::write(show.join("Season 02/S02E01.mkv"), b"v").unwrap(); + assert!(!trash_leftover_show(&show, &dest).unwrap()); + assert!(show.join("tvshow.nfo").exists()); + + std::fs::remove_dir_all(show.join("Season 02")).unwrap(); + std::fs::create_dir_all(show.join("extrafanart")).unwrap(); + std::fs::write(show.join("extrafanart/1.jpg"), b"j").unwrap(); + assert!(trash_leftover_show(&show, &dest).unwrap()); + assert!(!show.exists()); + assert!(dest.join("tvshow.nfo").exists()); + assert!(dest.join("extrafanart/1.jpg").exists()); + } +} diff --git a/crates/jm-server/src/library.rs b/crates/jm-server/src/library.rs index a0aa371..27b85fd 100644 --- a/crates/jm-server/src/library.rs +++ b/crates/jm-server/src/library.rs @@ -29,6 +29,20 @@ pub struct LibraryItem { pub size: Option, } +/// A season of a show, as Jellyfin lists it. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SeasonItem { + pub id: String, + pub name: String, + pub number: Option, + /// The season's own folder. `None` when its episodes sit directly in the + /// show folder, in which case it can't be moved on its own. + pub path: Option, + /// Name of that folder inside the show folder, to match it with the + /// show's per-folder sizes. + pub folder: Option, +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct LocationCheck { pub library: String, @@ -103,6 +117,41 @@ pub async fn items( Ok(out) } +/// The seasons of a show, in order. Seasons without a folder of their own +/// inside the show folder are listed with no path. +pub async fn seasons(state: &AppState, series_id: &str) -> anyhow::Result> { + let series = state.jellyfin.item(series_id).await?; + let show = series.path.map(PathBuf::from); + let mut out: Vec = state + .jellyfin + .items(&ItemQuery { + parent_id: Some(series_id), + include_types: &["Season"], + ..Default::default() + }) + .await? + .into_iter() + .map(|s| { + let path = s + .path + .filter(|p| show.as_deref().is_some_and(|show| Path::new(p).parent() == Some(show))); + let folder = path + .as_deref() + .and_then(|p| Path::new(p).file_name()) + .map(|n| n.to_string_lossy().into_owned()); + SeasonItem { + id: s.id, + name: s.name, + number: s.index_number, + path, + folder, + } + }) + .collect(); + out.sort_by_key(|s| s.number.unwrap_or(i32::MAX)); + Ok(out) +} + /// The folder a move would take, as this agent sees it: a movie's parent /// folder, or the series folder itself. fn item_folder(state: &AppState, item: &LibraryItem) -> Option { diff --git a/crates/jm-server/src/peer.rs b/crates/jm-server/src/peer.rs index 9d6bcea..ed0e413 100644 --- a/crates/jm-server/src/peer.rs +++ b/crates/jm-server/src/peer.rs @@ -5,7 +5,7 @@ use reqwest::header::AUTHORIZATION; use serde::{Deserialize, Serialize, de::DeserializeOwned}; use crate::export::{CompleteRequest, Export}; -use crate::library::{Library, LibraryItem}; +use crate::library::{Library, LibraryItem, SeasonItem}; use crate::trash::{EmptyResult, TrashEntry}; #[derive(Clone)] @@ -85,6 +85,14 @@ impl PeerClient { .await } + pub async fn seasons(&self, series: &str) -> anyhow::Result> { + self.send( + self.http.get(self.url("/seasons")).query(&[("series", series)]), + "list seasons", + ) + .await + } + pub async fn create_export(&self, item_id: &str) -> anyhow::Result { self.send( self.http diff --git a/crates/jm-server/src/runner.rs b/crates/jm-server/src/runner.rs index a154f91..c65e60e 100644 --- a/crates/jm-server/src/runner.rs +++ b/crates/jm-server/src/runner.rs @@ -5,8 +5,9 @@ use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; use anyhow::{Context, bail}; -use jm_core::job::ExportInfo; +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::{ItemKind, Job, JobStatus, Stage}; use jm_jellyfin::ItemQuery; @@ -100,6 +101,10 @@ fn target_jellyfin(job: &Job) -> anyhow::Result { /// Destination library location (local path) that holds the target folder. fn target_library_root(state: &Shared, job: &Job) -> anyhow::Result { + if let Some(loc) = &job.target_location { + return Ok(state.cfg.path_map.to_local(Path::new(loc))); + } + // Jobs planned before v0.2.0: work it out from the folder's depth. let info = info(job)?; let target = target_jellyfin(job)?; let depth = info.rel_folder.split('/').count(); @@ -154,7 +159,7 @@ async fn plan(state: &Shared, job: &mut Job) -> anyhow::Result { })?; let expected = match info.kind { ItemKind::Movie => "movies", - ItemKind::Series => "tvshows", + ItemKind::Series | ItemKind::Season => "tvshows", }; if let Some(ct) = &lib.collection_type { if ct != expected { @@ -166,31 +171,65 @@ async fn plan(state: &Shared, job: &mut Job) -> anyhow::Result { ); } } - let location = lib + let first_location = lib .locations .first() .context("destination library has no folders")?; - let target = join_relative(Path::new(location), &info.rel_folder) - .context("unsafe folder name from source")?; - let target_local = state.cfg.path_map.to_local(&target); - if tokio::fs::metadata(&target_local).await.is_ok() { - bail!( - "{} already exists on this server; refusing to merge into it", - target_local.display() - ); - } + let (target, location, skip, place) = match &info.season { + None => { + let target = join_relative(Path::new(first_location), &info.rel_folder) + .context("unsafe folder name from source")?; + refuse_if_exists(state, &target)?; + let place = target.display().to_string(); + (target, first_location.clone(), Vec::new(), place) + } + Some(season) => { + // A season joins the show if this server already has it. + let existing = find_show(state, &lib.item_id, season).await?; + let show = match &existing { + Some(path) => PathBuf::from(path), + None => join_relative(Path::new(first_location), &info.rel_folder) + .context("unsafe folder name from source")?, + }; + let location = check_inside_library(&show, &lib.locations) + .map(str::to_string) + .unwrap_or_else(|_| first_location.clone()); + let season_target = + join_relative(&show, &season.folder).context("unsafe season folder name from source")?; + refuse_if_exists(state, &season_target)?; + let show_here = tokio::fs::metadata(state.cfg.path_map.to_local(&show)) + .await + .is_ok(); + // Never overwrite the show's own files here; only bring them for a new show. + let (skip, how) = if show_here { + (season.show_files.clone(), "adding to the show already here") + } else { + (Vec::new(), "a new show, with its NFO and artwork") + }; + let place = format!("{} ({how})", season_target.display()); + (show, location, skip, place) + } + }; job.name = info.name.clone(); - job.progress.bytes_total = info.manifest.total_bytes(); + job.progress.bytes_total = info + .manifest + .files + .iter() + .enumerate() + .filter(|(i, _)| !skip.contains(i)) + .map(|(_, f)| f.size) + .sum(); job.target_library = Some(lib.name.clone()); job.target_folder_jellyfin = Some(target.display().to_string()); + job.target_location = Some(location); job.note(format!( - "plan: {} files, {} into \"{}\" at {}", - info.manifest.files.len(), + "plan: {} files, {} into \"{}\" at {place}", + info.manifest.files.len() - skip.len(), human_bytes(job.progress.bytes_total), lib.name, - target.display() )); + job.skip_files = skip; job.export = Some(info); if job.dry_run { @@ -202,6 +241,50 @@ async fn plan(state: &Shared, job: &mut Job) -> anyhow::Result { Ok(Flow::Continue) } +/// Refuse to plan a move into a folder that already exists here. +fn refuse_if_exists(state: &Shared, target: &Path) -> anyhow::Result<()> { + let local = state.cfg.path_map.to_local(target); + if std::fs::symlink_metadata(&local).is_ok() { + bail!( + "{} already exists on this server; refusing to merge into it", + local.display() + ); + } + Ok(()) +} + +/// The folder of the show a season belongs to, if this library has it: +/// matched by provider ID (TVDB, TMDB, IMDb...) first, then by name. +async fn find_show( + state: &Shared, + library_id: &str, + season: &SeasonInfo, +) -> anyhow::Result> { + let shows = state + .jellyfin + .items(&ItemQuery { + parent_id: Some(library_id), + include_types: &["Series"], + recursive: true, + ..Default::default() + }) + .await?; + let same_id = |s: &&jm_jellyfin::Item| { + season.show_provider_ids.iter().any(|(k, v)| { + !v.trim().is_empty() + && s.provider_ids + .iter() + .any(|(k2, v2)| k2.eq_ignore_ascii_case(k) && v2.trim().eq_ignore_ascii_case(v.trim())) + }) + }; + let same_name = |s: &&jm_jellyfin::Item| s.name.trim().eq_ignore_ascii_case(season.show_name.trim()); + Ok(shows + .iter() + .find(same_id) + .or_else(|| shows.iter().find(same_name)) + .and_then(|s| s.path.clone())) +} + async fn copy(state: &Shared, job: &mut Job) -> anyhow::Result<()> { let peer = state.peer()?; let export_id = job.export_id.clone().context("no export")?; @@ -209,10 +292,14 @@ async fn copy(state: &Shared, job: &mut Job) -> anyhow::Result<()> { let partial = jm_transfer::partial_dir(&target_library_root(state, job)?, &job.id.to_string()); jm_transfer::prepare_partial(&partial).await?; + let skip = job.skip_files.clone(); let mut done_before: u64 = 0; let mut last_emit = Instant::now(); let mut last_save = Instant::now(); for (idx, entry) in files.iter().enumerate() { + if skip.contains(&idx) { + continue; + } job.progress.current_file = Some(entry.rel_path.clone()); let url = peer.file_url(&export_id, idx); let part = jm_transfer::part_path(&partial, idx); @@ -247,7 +334,7 @@ async fn copy(state: &Shared, job: &mut Job) -> anyhow::Result<()> { } } job.progress.current_file = None; - job.note(format!("copied and verified {} files", files.len())); + job.note(format!("copied and verified {} files", files.len() - skip.len())); job.advance(Stage::Copied); Ok(()) } @@ -255,8 +342,12 @@ async fn copy(state: &Shared, job: &mut Job) -> anyhow::Result<()> { async fn promote(state: &Shared, job: &mut Job) -> anyhow::Result<()> { let partial = jm_transfer::partial_dir(&target_library_root(state, job)?, &job.id.to_string()); let target_local = state.cfg.path_map.to_local(&target_jellyfin(job)?); - jm_transfer::promote(&partial, &target_local, &info(job)?.manifest).await?; - job.note(format!("moved into {}", target_local.display())); + jm_transfer::promote(&partial, &target_local, &info(job)?.manifest, &job.skip_files).await?; + let placed = match &info(job)?.season { + Some(season) => target_local.join(&season.folder), + None => target_local.clone(), + }; + job.note(format!("moved into {}", placed.display())); job.advance(Stage::Promoted); Ok(()) } @@ -322,16 +413,22 @@ async fn find_new_item( .iter() .find(|l| l.name == lib_name) .context("target library disappeared")?; + // A season's target is its show's folder: wait for the show, then for + // the season's episodes inside it. let kind = match info.kind { ItemKind::Movie => "Movie", - ItemKind::Series => "Series", + ItemKind::Series | ItemKind::Season => "Series", }; let matches = |p: &str| match info.kind { ItemKind::Movie => Path::new(p).parent() == Some(target), - ItemKind::Series => Path::new(p) == target, + ItemKind::Series | ItemKind::Season => Path::new(p) == target, }; // Search by name first (cheap), then fall back to listing the library. - for search in [Some(info.name.as_str()), None] { + let name = info + .season + .as_ref() + .map_or(info.name.as_str(), |s| s.show_name.as_str()); + for search in [Some(name), None] { let items = state .jellyfin .items(&ItemQuery { @@ -381,7 +478,7 @@ async fn missing_episodes( series_id: &str, info: &ExportInfo, ) -> anyhow::Result { - if info.kind != ItemKind::Series || info.episode_keys.is_empty() { + if !info.kind.has_episodes() || info.episode_keys.is_empty() { return Ok(0); } let found = episode_ids(state, series_id).await?; @@ -395,7 +492,7 @@ async fn missing_episodes( async fn apply_user_data(state: &Shared, job: &mut Job) -> anyhow::Result<()> { let info = info(job)?.clone(); let root_id = job.target_item_id.clone().context("no target item")?; - let episodes = if info.kind == ItemKind::Series { + let episodes = if info.kind.has_episodes() { episode_ids(state, &root_id).await? } else { HashMap::new() diff --git a/crates/jm-server/tests/e2e.rs b/crates/jm-server/tests/e2e.rs index 69aba23..62d5f93 100644 --- a/crates/jm-server/tests/e2e.rs +++ b/crates/jm-server/tests/e2e.rs @@ -567,6 +567,151 @@ async fn lists_folder_sizes_for_movies_shows_and_seasons() { assert_eq!(on_home[0]["size"], *alien); } +#[tokio::test] +async fn moves_seasons_one_at_a_time_and_trashes_the_empty_show() { + let (cloud, home) = pair(seed_series).await; + let e1 = cloud.fake.episode_id("Severance", 1, 1).unwrap(); + let e3 = cloud.fake.episode_id("Severance", 2, 1).unwrap(); + cloud.fake.set_user_data(&e1, json!({"Played": true})); + cloud + .fake + .set_user_data(&e3, json!({"PlaybackPositionTicks": 42})); + let series = cloud.fake.find("Series", "Severance").unwrap(); + cloud.fake.set_user_data(&series, json!({"IsFavorite": true})); + + // The UI lists the show's seasons with their folders. + let seasons = get( + &home.url, + &format!("/api/seasons?node=peer&series={series}"), + ) + .await; + assert_eq!(seasons[0]["name"], "Season 1"); + assert_eq!(seasons[0]["folder"], "Season 01"); + assert_eq!(seasons[1]["number"], 2); + + // Season 2 into a show home doesn't have yet: the show's NFO comes too. + let s2 = cloud.fake.season_id("Severance", 2).unwrap(); + assert_eq!(seasons[1]["id"], s2); + let job = move_item(&cloud.url, "local", &s2, "Season 2").await; + assert_eq!(job["name"], "Severance – Season 2"); + let show_home = home.tv().join("Severance"); + assert!(show_home.join("Season 02/Severance S02E01.mkv").exists()); + assert!(show_home.join("tvshow.nfo").exists()); + assert!(!show_home.join("Season 01").exists()); + // The source keeps the rest of the show. + let show_cloud = cloud.tv().join("Severance"); + assert!(!show_cloud.join("Season 02").exists()); + assert!(show_cloud.join("Season 01/Severance S01E01.mkv").exists()); + assert!(show_cloud.join("tvshow.nfo").exists()); + // Episode watch state followed; the season's show-level state didn't. + let new_e3 = home.fake.episode_id("Severance", 2, 1).unwrap(); + assert_eq!( + home.fake.get_user_data(&new_e3).unwrap()["PlaybackPositionTicks"], + 42 + ); + let home_series = home.fake.find("Series", "Severance").unwrap(); + assert!(home.fake.get_user_data(&home_series).is_none()); + + // Mark home's copy of the NFO so we can tell it isn't overwritten. + std::fs::write(show_home.join("tvshow.nfo"), b"home's own").unwrap(); + + // Season 1 joins the existing show, and was the last one on cloud. + let s1 = cloud.fake.season_id("Severance", 1).unwrap(); + let job = move_item(&home.url, "peer", &s1, "Season 1").await; + assert!( + job["log"] + .as_array() + .unwrap() + .iter() + .any(|l| l.as_str().unwrap().contains("adding to the show already here")), + "{job:#}" + ); + assert!(show_home.join("Season 01/Severance S01E02.mkv").exists()); + assert_eq!(std::fs::read(show_home.join("tvshow.nfo")).unwrap(), b"home's own"); + let new_e1 = home.fake.episode_id("Severance", 1, 1).unwrap(); + assert_eq!(home.fake.get_user_data(&new_e1).unwrap()["Played"], true); + + // Nothing is left of the show on cloud: its NFO went to the trash with + // the last season. + assert!(!show_cloud.exists()); + let trash = get(&cloud.url, "/api/trash?node=local").await; + let entries = trash.as_array().unwrap(); + assert_eq!(entries.len(), 2, "{trash:#}"); + let last = entries + .iter() + .find(|e| e["name"] == "Severance – Season 1") + .unwrap(); + assert_eq!(last["kind"], "Season"); + assert_eq!(last["folder"], "Severance/Season 01"); + assert_eq!(last["files"], 3); +} + +#[tokio::test] +async fn refuses_a_season_the_destination_already_has() { + let (cloud, home) = pair(seed_series).await; + write( + &home.tv().join("Severance/Season 02/Severance S02E01.mkv"), + b"home's copy", + ); + home.fake.scan(); + let s2 = cloud.fake.season_id("Severance", 2).unwrap(); + let job: Value = post( + &cloud.url, + "/api/moves", + json!({"from": "local", "item_id": s2, "name": "Season 2"}), + ) + .await + .json() + .await + .unwrap(); + let done = wait_job(&cloud.url, job["id"].as_str().unwrap()).await; + assert_eq!(done["status"]["kind"], "Failed"); + assert!( + done["status"]["detail"] + .as_str() + .unwrap() + .contains("already exists"), + "{done:#}" + ); + assert_eq!( + std::fs::read(home.tv().join("Severance/Season 02/Severance S02E01.mkv")).unwrap(), + b"home's copy" + ); + assert!(cloud.tv().join("Severance/Season 02").exists()); +} + +#[tokio::test] +async fn refuses_a_season_folder_holding_other_seasons() { + let (cloud, _home) = pair(|root| { + seed_series(root); + // A season 3 episode filed in the Season 02 folder. + write( + &root.join("tv/Severance/Season 02/Severance S03E01.mkv"), + b"misfiled", + ); + }) + .await; + let s2 = cloud.fake.season_id("Severance", 2).unwrap(); + let job: Value = post( + &cloud.url, + "/api/moves", + json!({"from": "local", "item_id": s2, "name": "Season 2"}), + ) + .await + .json() + .await + .unwrap(); + let done = wait_job(&cloud.url, job["id"].as_str().unwrap()).await; + assert_eq!(done["status"]["kind"], "Failed"); + assert!( + done["status"]["detail"] + .as_str() + .unwrap() + .contains("aren't its episodes"), + "{done:#}" + ); +} + #[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 c9f12c4..09393c2 100644 --- a/crates/jm-server/tests/fake_jellyfin/mod.rs +++ b/crates/jm-server/tests/fake_jellyfin/mod.rs @@ -34,7 +34,10 @@ struct FakeItem { kind: &'static str, path: String, parent: String, + /// The series a season or episode belongs to. + series: Option, season: Option, + /// Episode number, or a season's own number. episode: Option, } @@ -133,6 +136,7 @@ impl Fake { kind: "Movie", path: f.display().to_string(), parent: lib.id(), + series: None, season: None, episode: None, }); @@ -145,25 +149,74 @@ impl Fake { kind: "Series", path: folder.display().to_string(), parent: lib.id(), + series: None, season: None, episode: None, }); + // Like Jellyfin: a season per season folder, holding its + // episodes; episodes loose in the show folder hang off + // the series. + let mut seasons: Vec<(PathBuf, i32, String)> = Vec::new(); for f in files .iter() .filter(|f| f.extension().is_some_and(|e| e == "mkv")) { let fname = f.file_name().unwrap().to_string_lossy(); - if let Some((s, e)) = parse_sxxexx(&fname) { - items.push(FakeItem { - id: id_for(f), - name: fname.to_string(), - kind: "Episode", - path: f.display().to_string(), - parent: series_id.clone(), - season: Some(s), - episode: Some(e), - }); - } + let Some((s, e)) = parse_sxxexx(&fname) else { + continue; + }; + let in_folder = f + .strip_prefix(&folder) + .ok() + .and_then(|r| r.components().next()) + .map(|c| folder.join(c)) + .filter(|p| p.is_dir()); + // The folder name gives the season's number ("Season 02", + // "Specials"); an episode filed under the wrong season + // doesn't belong to it. + let folder_number = |p: &Path| { + let n = p.file_name()?.to_string_lossy().to_lowercase(); + if n == "specials" { + return Some(0); + } + n.chars() + .filter(|c| c.is_ascii_digit()) + .collect::() + .parse::() + .ok() + }; + let parent = match in_folder { + Some(season_folder) if folder_number(&season_folder) == Some(s) => { + let id = id_for(&season_folder); + if !seasons.iter().any(|(p, _, _)| p == &season_folder) { + seasons.push((season_folder, s, id.clone())); + } + id + } + _ => series_id.clone(), + }; + items.push(FakeItem { + id: id_for(f), + name: fname.to_string(), + kind: "Episode", + path: f.display().to_string(), + parent, + series: Some(series_id.clone()), + season: Some(s), + episode: Some(e), + }); + } + for (path, n, id) in seasons { + items.push(FakeItem { + id, + name: if n == 0 { "Specials".into() } else { format!("Season {n}") }, + kind: "Season", + path: path.display().to_string(), + parent: series_id.clone(), + series: Some(series_id.clone()), + season: None, + episode: Some(n), + }); } } } @@ -186,7 +239,22 @@ impl Fake { .lock() .unwrap() .iter() - .find(|i| i.parent == series_id && i.season == Some(season) && i.episode == Some(ep)) + .find(|i| { + i.kind == "Episode" + && i.series.as_deref() == Some(&series_id) + && i.season == Some(season) + && i.episode == Some(ep) + }) + .map(|i| i.id.clone()) + } + + pub fn season_id(&self, series: &str, season: i32) -> Option { + let series_id = self.find("Series", series)?; + self.items + .lock() + .unwrap() + .iter() + .find(|i| i.kind == "Season" && i.parent == series_id && i.episode == Some(season)) .map(|i| i.id.clone()) } @@ -250,7 +318,14 @@ async fn items(State(f): State, Query(q): Query>) let out: Vec = all .iter() .filter(|i| ids.as_ref().is_none_or(|ids| ids.contains(&i.id.as_str()))) - .filter(|i| q.get("parentId").is_none_or(|p| &i.parent == p)) + .filter(|i| { + // Recursive queries under a series also reach its episodes, + // which hang off their seasons. + let recursive = q.get("recursive").is_some_and(|r| r == "true"); + q.get("parentId").is_none_or(|p| { + &i.parent == p || (recursive && i.series.as_deref() == Some(p.as_str())) + }) + }) .filter(|i| types.as_ref().is_none_or(|t| t.contains(&i.kind))) .filter(|i| { q.get("searchTerm") @@ -258,7 +333,7 @@ async fn items(State(f): State, Query(q): Query>) }) .map(|i| { let mut v = json!({"Id": i.id, "Name": i.name, "Type": i.kind, "Path": i.path, - "ParentIndexNumber": i.season, "IndexNumber": i.episode, + "ParentIndexNumber": i.season, "IndexNumber": i.episode, "SeriesId": i.series, "MediaSources": [{"Path": i.path}]}); if let Some(u) = user { v["UserData"] = ud diff --git a/crates/jm-transfer/src/lib.rs b/crates/jm-transfer/src/lib.rs index 9046b62..17c8e36 100644 --- a/crates/jm-transfer/src/lib.rs +++ b/crates/jm-transfer/src/lib.rs @@ -12,7 +12,7 @@ pub mod promote; pub mod pull; pub mod serve; -pub use manifest::{build_manifest, hash_file, list_relative}; +pub use manifest::{build_manifest, build_manifest_filtered, hash_file, list_relative}; pub use promote::{part_path, partial_dir, prepare_partial, promote}; pub use pull::{Puller, PullerOptions}; pub use serve::range_response; diff --git a/crates/jm-transfer/src/manifest.rs b/crates/jm-transfer/src/manifest.rs index 4341df1..9f0005d 100644 --- a/crates/jm-transfer/src/manifest.rs +++ b/crates/jm-transfer/src/manifest.rs @@ -20,10 +20,21 @@ pub async fn hash_file(path: &Path) -> Result { /// them sorted by relative path. Symlinks and jellymove's own hidden folders /// are skipped. pub async fn build_manifest(root: &Path) -> Result { + build_manifest_filtered(root, |_| true).await +} + +/// Like [`build_manifest`], but only for files whose relative path passes +/// `keep`, e.g. one season's folder plus the show's loose files. +pub async fn build_manifest_filtered( + root: &Path, + keep: impl Fn(&str) -> bool + Send + 'static, +) -> Result { let root_owned = root.to_path_buf(); - let listed = tokio::task::spawn_blocking(move || list_files(&root_owned)) - .await - .expect("list task panicked")?; + let listed = tokio::task::spawn_blocking(move || { + list_files(&root_owned).map(|l| l.into_iter().filter(|(rel, _, _)| keep(rel)).collect::>()) + }) + .await + .expect("list task panicked")?; let mut files = Vec::with_capacity(listed.len()); for (rel, abs, size) in listed { @@ -101,4 +112,21 @@ mod tests { blake3::hash(b"video").to_hex().to_string() ); } + + #[tokio::test] + async fn filtered_manifest_keeps_only_matching_files() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + for f in ["tvshow.nfo", "Season 01/a.mkv", "Season 02/b.mkv"] { + std::fs::create_dir_all(root.join(f).parent().unwrap()).unwrap(); + std::fs::write(root.join(f), b"x").unwrap(); + } + let m = build_manifest_filtered(root, |rel| { + !rel.contains('/') || rel.starts_with("Season 02/") + }) + .await + .unwrap(); + let names: Vec<_> = m.files.iter().map(|f| f.rel_path.as_str()).collect(); + assert_eq!(names, ["Season 02/b.mkv", "tvshow.nfo"]); + } } diff --git a/crates/jm-transfer/src/promote.rs b/crates/jm-transfer/src/promote.rs index cdf7e02..6aff92d 100644 --- a/crates/jm-transfer/src/promote.rs +++ b/crates/jm-transfer/src/promote.rs @@ -29,16 +29,25 @@ pub async fn prepare_partial(partial: &Path) -> Result<(), TransferError> { Ok(()) } -/// Rename every verified `.part` into `target_folder`. Safe to run again after +/// Rename every verified `.part` into `target_folder`, except the manifest +/// entries listed in `skip` (which were never copied). Safe to run again after /// a crash: files already in place (part gone, target present with the right /// size) are skipped. Refuses to overwrite anything it didn't put there. pub async fn promote( partial: &Path, target_folder: &Path, manifest: &Manifest, + skip: &[usize], ) -> Result<(), TransferError> { + let wanted = || { + manifest + .files + .iter() + .enumerate() + .filter(|(idx, _)| !skip.contains(idx)) + }; // Check every destination first so we never half-promote into a clash. - for (idx, entry) in manifest.files.iter().enumerate() { + for (idx, entry) in wanted() { let dest = join_relative(target_folder, &entry.rel_path) .ok_or_else(|| TransferError::UnsafePath(entry.rel_path.clone()))?; let part_exists = tokio::fs::metadata(part_path(partial, idx)).await.is_ok(); @@ -47,7 +56,7 @@ pub async fn promote( } } - for (idx, entry) in manifest.files.iter().enumerate() { + for (idx, entry) in wanted() { let part = part_path(partial, idx); let dest = join_relative(target_folder, &entry.rel_path).expect("checked above"); match tokio::fs::metadata(&part).await { diff --git a/crates/jm-transfer/tests/transfer.rs b/crates/jm-transfer/tests/transfer.rs index 19ba3ba..c4b356b 100644 --- a/crates/jm-transfer/tests/transfer.rs +++ b/crates/jm-transfer/tests/transfer.rs @@ -119,7 +119,7 @@ async fn pull_all(fx: &Fixture, p: &Puller) -> PathBuf { .unwrap(); } let target = lib_root.join("Alien (1979)"); - promote(&partial, &target, &manifest).await.unwrap(); + promote(&partial, &target, &manifest, &[]).await.unwrap(); target } @@ -200,7 +200,7 @@ async fn refuses_to_overwrite_existing_files() { .await .unwrap(); } - let err = promote(&partial, &target, &manifest).await.unwrap_err(); + let err = promote(&partial, &target, &manifest, &[]).await.unwrap_err(); assert!(matches!(err, jm_transfer::TransferError::Exists(_))); // Nothing was moved: the stranger's file is untouched and no video landed. assert_eq!( @@ -216,11 +216,43 @@ async fn promote_is_idempotent() { let target = pull_all(&fx, &puller()).await; let manifest = build_manifest(&fx.src.root).await.unwrap(); // A second promote after a "crash" finds everything already in place. - promote(&partial_dir(fx.dst_dir.path(), "job1"), &target, &manifest) + promote(&partial_dir(fx.dst_dir.path(), "job1"), &target, &manifest, &[]) .await .unwrap(); } +#[tokio::test] +async fn promote_leaves_skipped_files_alone() { + let fx = fixture().await; + let manifest = build_manifest(&fx.src.root).await.unwrap(); + let nfo = manifest + .files + .iter() + .position(|f| f.rel_path == "Alien (1979).nfo") + .unwrap(); + // The target already has its own NFO; that entry is skipped and never copied. + let target = fx.dst_dir.path().join("Alien (1979)"); + std::fs::create_dir_all(&target).unwrap(); + std::fs::write(target.join("Alien (1979).nfo"), b"mine").unwrap(); + let partial = partial_dir(fx.dst_dir.path(), "job1"); + prepare_partial(&partial).await.unwrap(); + let p = puller(); + for (idx, entry) in manifest.files.iter().enumerate() { + if idx == nfo { + continue; + } + let url = format!("{}/files/{idx}", fx.base); + p.pull_verified(&url, entry, &part_path(&partial, idx), &mut |_| {}) + .await + .unwrap(); + } + promote(&partial, &target, &manifest, &[nfo]).await.unwrap(); + assert_eq!(std::fs::read(target.join("Alien (1979).nfo")).unwrap(), b"mine"); + assert!(target.join("Alien (1979).mkv").exists()); + // And it's still idempotent. + promote(&partial, &target, &manifest, &[nfo]).await.unwrap(); +} + #[tokio::test] async fn bandwidth_limit_is_applied() { let fx = fixture().await; diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c99ab48..b70b3c0 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -35,6 +35,7 @@ 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 | | `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` | @@ -83,6 +84,14 @@ after seven days regardless. The UI polls the list until every size is in. - Browse: `GET /Items?parentId=&includeItemTypes=Movie,Series&recursive=true&fields=Path,…` - Folder: a movie's parent folder, or a series' own folder. It must sit strictly inside a library location. A movie folder must contain no other main videos. +- Seasons: `includeItemTypes=Season` under the series. A season export's folder + is the show's; its manifest holds only `/…` plus the show's + loose non-video files (`SeasonInfo.show_files`). The destination finds the + show by provider ID, then name, and skips those show files if it already has + the show. A season's own user data isn't carried (it would land on the + whole show); its episodes' is. After the last season leaves, the source + moves what remains of the show folder into the same trash entry, but only if + no videos are left in it. - Rescan: `POST /Library/Media/Updated` for the exact folder, then poll. The first update can be lost, so it is re-sent halfway through the timeout. - Finding the new item: by **path**, since we know exactly where we put it. diff --git a/ui/src/lib/Library.svelte b/ui/src/lib/Library.svelte index 94ffcae..6b388b7 100644 --- a/ui/src/lib/Library.svelte +++ b/ui/src/lib/Library.svelte @@ -1,6 +1,6 @@