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:
1 parent
25a743b350
commit
484ac50508
21 files changed
+959
-111
No files matched your search
+230
-31
@@ -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<PathBuf>,
|
||||
}
|
||||
|
||||
impl Export {
|
||||
@@ -80,6 +84,7 @@ pub async fn create(state: &Shared, item_id: &str) -> anyhow::Result<Export> {
|
||||
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<String> = 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<bool> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user