Move a single season of a TV show (#4)
CI / test (push) Successful in 1m14s

Shows can be expanded to list their seasons, each with its size and its own Dry run / Move buttons. A season joins the same show on the other
server, so finished seasons can go to the big server while the current one stays on the fast one.

- Source exports a season from the show folder, with a manifest of just that season's folder plus the show's loose non-video files. Refuses
  seasons with no folder of their own, or whose folder holds otherseasons' episodes.
- Destination finds the show by provider ID, then name. If it already has the show, the show's own files are skipped (Job.skip_files) and
  never overwritten; otherwise they come with the season. Refuses if the season folder already exists.
- Only episode watch state is carried for a season.
- Source trashes just the season folder; after the last season, the leftover show folder joins it in the same trash entry if no videos
  remain. The chosen trash entry is saved so a re-run after a crash finishes in the same place.
- New GET /seasons (UI and peer). Fake Jellyfin gains season items.
- e2e tests: season into a new show, into an existing show, last season leaving, destination already has the season, misfiled episodes.
This commit is contained in:
IxianPixel committed 2026-11-06 17:02:40 +00:00
1 parent 25a743b350
commit 484ac50508
21 files changed
+959 -111

No files matched your search

+145
View File
@@ -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;
+89 -14
View File
@@ -34,7 +34,10 @@ struct FakeItem {
kind: &'static str,
path: String,
parent: String,
/// The series a season or episode belongs to.
series: Option<String>,
season: Option<i32>,
/// Episode number, or a season's own number.
episode: Option<i32>,
}
@@ -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::<String>()
.parse::<i32>()
.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<String> {
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<Fake>, Query(q): Query<HashMap<String, String>>)
let out: Vec<Value> = 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<Fake>, Query(q): Query<HashMap<String, String>>)
})
.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