//! Source side of a move. An *export* is an item folder this node has agreed //! to hand over: it has been safety-checked, hashed and its users' watch state //! captured. Files are served from it by index, never by path, so a peer can //! only read what was exported. use std::path::{Path, PathBuf}; use anyhow::{Context, bail}; use jm_core::ItemKind; use jm_core::job::{ExportInfo, SeasonInfo}; use jm_core::paths::{join_relative, relative_inside}; 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}; use crate::state::{AppState, Shared}; use crate::trash; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", content = "detail")] pub enum ExportStatus { /// Checking the folder and hashing files. Preparing, Ready, Failed(String), /// Folder moved to the source trash; nothing left to serve. Completed, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Export { pub id: String, pub item_id: String, pub status: ExportStatus, pub info: Option, /// Item folder as Jellyfin sees it. #[serde(default)] pub jellyfin_folder: String, /// 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 { fn local_folder(&self, state: &AppState) -> PathBuf { state .cfg .path_map .to_local(Path::new(&self.jellyfin_folder)) } /// Absolute local path of manifest entry `idx`, if it exists in the export. pub fn file_path(&self, state: &AppState, idx: usize) -> Option { let info = self.info.as_ref()?; let entry = info.manifest.files.get(idx)?; join_relative(&self.local_folder(state), &entry.rel_path) } } /// Start (or reuse) an export for `item_id`. Hashing runs in the background; /// the caller polls [`get`] until the status is `Ready`. pub async fn create(state: &Shared, item_id: &str) -> anyhow::Result { // One export per item: re-requesting returns the existing one, so a // destination that restarts mid-copy reattaches instead of re-hashing. let id = format!("item-{item_id}"); if let Some(existing) = state.store.get_export::(&id).await? { let retry = matches!( existing.status, ExportStatus::Failed(_) | ExportStatus::Completed ); if !retry { return Ok(existing); } } let export = Export { id: id.clone(), item_id: item_id.to_string(), status: ExportStatus::Preparing, 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()); Ok(export) } /// Load an export. If it was being prepared when the daemon stopped, the /// preparation is restarted. pub async fn get(state: &Shared, id: &str) -> anyhow::Result> { let export: Option = state.store.get_export(id).await?; if let Some(e) = &export { if e.status == ExportStatus::Preparing { spawn_prepare(state.clone(), e.clone()); } } Ok(export) } fn spawn_prepare(state: Shared, mut export: Export) { if !state .preparing .lock() .expect("lock") .insert(export.id.clone()) { return; // already running } tokio::spawn(async move { match prepare(&state, &export.item_id).await { Ok((info, folder, location)) => { tracing::info!(item = %info.name, files = info.manifest.files.len(), "export ready"); export.info = Some(info); export.jellyfin_folder = folder; export.jellyfin_location = location; export.status = ExportStatus::Ready; } Err(e) => { tracing::warn!(item = %export.item_id, error = %format!("{e:#}"), "export failed"); export.status = ExportStatus::Failed(format!("{e:#}")); } } if let Err(e) = state.store.put_export(&export.id, &export).await { tracing::error!(error = %e, "could not save export"); } state.preparing.lock().expect("lock").remove(&export.id); }); } async fn prepare(state: &AppState, item_id: &str) -> anyhow::Result<(ExportInfo, String, String)> { let jf = &state.jellyfin; let item = jf .item(item_id) .await .context("looking up the item on Jellyfin")?; let kind = match item.kind.as_str() { "Movie" => ItemKind::Movie, "Series" => ItemKind::Series, "Season" => ItemKind::Season, other => bail!("can only move movies, shows and seasons, not {other}"), }; let 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?; let (library, location) = libraries .iter() .find_map(|lib| { check_inside_library(&folder, &lib.locations) .ok() .map(|loc| (lib, loc.to_string())) }) .with_context(|| { // Re-run against all locations for a precise error. let all: Vec = libraries.iter().flat_map(|l| l.locations.clone()).collect(); match check_inside_library(&folder, &all) { Err(e) => format!("{}: {e}", folder.display()), Ok(_) => format!("{} is not in a library", folder.display()), } })?; let rel_folder = relative_inside(Path::new(&location), &folder) .context("item folder is not below its library")?; let local_folder = state.cfg.path_map.to_local(&folder); if !tokio::fs::metadata(&local_folder) .await .map(|m| m.is_dir()) .unwrap_or(false) { bail!( "folder {} (Jellyfin path {}) is not visible to jellymove; check the volume mounts or path_map", local_folder.display(), folder.display() ); } if kind == ItemKind::Movie { let lf = local_folder.clone(); let files = tokio::task::spawn_blocking(move || jm_transfer::list_relative(&lf)).await??; let own: Vec = item .media_sources .iter() .flatten() .filter_map(|m| m.path.as_deref()) .chain(std::iter::once(item_path.to_str().unwrap_or_default())) .filter_map(|p| relative_inside(&folder, Path::new(p))) .collect(); check_movie_folder(&files, &own)?; } 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"); } // Capture each user's watch state now, before anything moves. let mut user_data = Vec::new(); let mut episode_keys = Vec::new(); for user in jf.users().await? { // A season's own watch state isn't carried: on the destination it // would land on the whole show. if kind != ItemKind::Season { let root = jf .items(&ItemQuery { ids: Some(item_id), user_id: Some(&user.id), ..Default::default() }) .await?; if let Some(ud) = root.into_iter().next().and_then(|i| i.user_data) { push_record(&mut user_data, &user.name, ItemKey::Root, ud.into()); } } if kind.has_episodes() { let episodes = jf .items(&ItemQuery { parent_id: Some(item_id), include_types: &["Episode"], recursive: true, user_id: Some(&user.id), ..Default::default() }) .await?; for ep in episodes { let (Some(season), Some(episode)) = (ep.parent_index_number, ep.index_number) else { continue; }; let key = ItemKey::Episode { season, episode }; if !episode_keys.contains(&key) { episode_keys.push(key); } if let Some(ud) = ep.user_data { push_record(&mut user_data, &user.name, key, ud.into()); } } } } let (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, kind, library_name: library.name.clone(), rel_folder, manifest, user_data, episode_keys, season, }; Ok((info, folder.display().to_string(), location)) } fn push_record( out: &mut Vec, user: &str, key: ItemKey, data: jm_core::userdata::UserData, ) { if !data.is_empty() { out.push(UserDataRecord { user_name: user.to_string(), key, data, }); } } /// Who finished the move; recorded with the trash entry. Older peers send /// nothing. #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct CompleteRequest { pub job_id: Option, pub moved_to: Option, } /// Final step on the source: move the folder into a hidden trash folder in /// the same library (same filesystem, so it's a rename) and rescan. pub async fn complete(state: &Shared, id: &str, req: CompleteRequest) -> anyhow::Result { let mut export: Export = state .store .get_export(id) .await? .context("no such export")?; match &export.status { ExportStatus::Completed => return Ok(export), ExportStatus::Ready => {} other => bail!("export is not ready to complete ({other:?})"), } let info = export.info.clone().context("export has no info")?; let local_folder = export.local_folder(state); let location_local = state .cfg .path_map .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 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() { tokio::fs::write(&marker, b"").await?; } // 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 = 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?; } trash::write_meta( &entry_dir, &trash::EntryMeta { name: info.name.clone(), kind: info.kind, library: info.library_name.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(&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; let mut dir = trash.parent(); while let Some(d) = dir { if !d.starts_with(&entry_dir) || tokio::fs::remove_dir(d).await.is_err() { break; } dir = d.parent(); } 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"); } } // After a season move the show is still listed here, but smaller. crate::sizes::forget(state, &local_folder).await; if let Err(e) = state .jellyfin .media_updated(std::slice::from_ref(&export.jellyfin_folder)) .await { tracing::warn!(error = %e, "could not ask Jellyfin to rescan the source folder"); } export.status = ExportStatus::Completed; 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()); } }