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
@@ -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<Shared>,
|
||||
Query(q): Query<SeasonsQuery>,
|
||||
) -> ApiResult<Vec<SeasonItem>> {
|
||||
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<Shared>,
|
||||
Query(q): Query<PeerSeasonsQuery>,
|
||||
) -> ApiResult<Vec<SeasonItem>> {
|
||||
Ok(Json(library::seasons(&state, &q.series).await?))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CreateExport {
|
||||
item_id: String,
|
||||
|
||||
+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());
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,20 @@ pub struct LibraryItem {
|
||||
pub size: Option<FolderSize>,
|
||||
}
|
||||
|
||||
/// 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<i32>,
|
||||
/// 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<String>,
|
||||
/// Name of that folder inside the show folder, to match it with the
|
||||
/// show's per-folder sizes.
|
||||
pub folder: Option<String>,
|
||||
}
|
||||
|
||||
#[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<Vec<SeasonItem>> {
|
||||
let series = state.jellyfin.item(series_id).await?;
|
||||
let show = series.path.map(PathBuf::from);
|
||||
let mut out: Vec<SeasonItem> = 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<PathBuf> {
|
||||
|
||||
@@ -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<Vec<SeasonItem>> {
|
||||
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<Export> {
|
||||
self.send(
|
||||
self.http
|
||||
|
||||
+121
-24
@@ -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<PathBuf> {
|
||||
|
||||
/// Destination library location (local path) that holds the target folder.
|
||||
fn target_library_root(state: &Shared, job: &Job) -> anyhow::Result<PathBuf> {
|
||||
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<Flow> {
|
||||
})?;
|
||||
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<Flow> {
|
||||
);
|
||||
}
|
||||
}
|
||||
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<Flow> {
|
||||
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<Option<String>> {
|
||||
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<usize> {
|
||||
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()
|
||||
|
||||
Reference in new issue
Block a user