Initial code commit
CI / test (push) Successful in 5m7s

This commit is contained in:
IxianPixel committed 2026-11-05 14:19:37 +00:00
1 parent f47217d5a3
commit 8ceb3c8be8
60 files changed
+10884

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
[package]
name = "jm-core"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[dependencies]
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
thiserror = "2.0.21"
time = { version = "0.3.45", features = ["serde", "formatting", "parsing", "macros"] }
uuid = { version = "1.26.1", features = ["v4", "serde"] }
+263
View File
@@ -0,0 +1,263 @@
use serde::{Deserialize, Serialize};
use std::fmt;
use time::OffsetDateTime;
use uuid::Uuid;
use crate::userdata::{ItemKey, UserDataRecord};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct JobId(pub Uuid);
impl JobId {
pub fn new() -> Self {
Self(Uuid::new_v4())
}
}
impl Default for JobId {
fn default() -> Self {
Self::new()
}
}
impl fmt::Display for JobId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl std::str::FromStr for JobId {
type Err = uuid::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(s.parse()?))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ItemKind {
Movie,
Series,
}
/// The last milestone a job has *completed*. The runner looks at the stage,
/// performs the next step, then advances. Every step is idempotent, so a job
/// interrupted at any point can resume by simply running again.
///
/// Created → ExportReady → Copied → Promoted → TargetScanned
/// → UserDataApplied → SourceCleaned → Done
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Stage {
/// Job recorded; nothing done yet.
Created,
/// Source has hashed the item folder and returned a manifest.
ExportReady,
/// Every file is in the partial area and its BLAKE3 hash matches.
Copied,
/// Files renamed from the partial area into the destination library.
Promoted,
/// Destination Jellyfin has indexed the new item.
TargetScanned,
/// Played state, resume points and favourites re-applied on destination.
UserDataApplied,
/// Source folder moved to the source trash and source library rescanned.
SourceCleaned,
Done,
}
impl Stage {
pub fn label(self) -> &'static str {
match self {
Stage::Created => "Waiting for source",
Stage::ExportReady => "Copying",
Stage::Copied => "Moving into library",
Stage::Promoted => "Waiting for Jellyfin scan",
Stage::TargetScanned => "Restoring watch history",
Stage::UserDataApplied => "Cleaning up source",
Stage::SourceCleaned => "Finishing",
Stage::Done => "Done",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "detail")]
pub enum JobStatus {
Queued,
Running,
/// A dry run stops after planning. Nothing was copied or deleted.
Planned,
Failed(String),
Done,
}
impl JobStatus {
pub fn is_active(&self) -> bool {
matches!(self, JobStatus::Queued | JobStatus::Running)
}
}
/// One file inside the item folder, relative to that folder.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ManifestEntry {
pub rel_path: String,
pub size: u64,
/// Lowercase hex BLAKE3.
pub blake3: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Manifest {
pub files: Vec<ManifestEntry>,
}
impl Manifest {
pub fn total_bytes(&self) -> u64 {
self.files.iter().map(|f| f.size).sum()
}
}
/// What the source node tells the destination about the item being moved.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportInfo {
pub item_id: String,
pub name: String,
pub kind: ItemKind,
/// Library the item lives in on the source.
pub library_name: String,
/// Item folder relative to its library root, using `/` separators.
pub rel_folder: String,
pub manifest: Manifest,
pub user_data: Vec<UserDataRecord>,
/// Every episode the source knows about (series only). The destination
/// waits until its scan has found all of them before anything is deleted.
#[serde(default)]
pub episode_keys: Vec<ItemKey>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Progress {
pub bytes_done: u64,
pub bytes_total: u64,
pub current_file: Option<String>,
}
/// A move job. It lives on the *destination* node, which pulls the data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Job {
pub id: JobId,
#[serde(with = "time::serde::rfc3339")]
pub created: OffsetDateTime,
#[serde(with = "time::serde::rfc3339")]
pub updated: OffsetDateTime,
/// Item ID on the source Jellyfin.
pub source_item_id: String,
/// Display name; replaced by the source's name once the export is ready.
pub name: String,
pub source_node: String,
pub target_node: String,
pub dry_run: bool,
pub stage: Stage,
pub status: JobStatus,
pub export_id: Option<String>,
pub export: Option<ExportInfo>,
/// Destination library chosen for the item.
pub target_library: Option<String>,
/// Final item folder in the destination's *Jellyfin* path namespace.
pub target_folder_jellyfin: Option<String>,
/// Item ID Jellyfin assigned on the destination after the scan.
pub target_item_id: Option<String>,
pub progress: Progress,
/// Human-readable log of what happened, newest last.
pub log: Vec<String>,
}
impl Job {
pub fn new(
source_item_id: impl Into<String>,
name: impl Into<String>,
source_node: impl Into<String>,
target_node: impl Into<String>,
dry_run: bool,
) -> Self {
let now = OffsetDateTime::now_utc();
Self {
id: JobId::new(),
created: now,
updated: now,
source_item_id: source_item_id.into(),
name: name.into(),
source_node: source_node.into(),
target_node: target_node.into(),
dry_run,
stage: Stage::Created,
status: JobStatus::Queued,
export_id: None,
export: None,
target_library: None,
target_folder_jellyfin: None,
target_item_id: None,
progress: Progress::default(),
log: Vec::new(),
}
}
pub fn note(&mut self, msg: impl Into<String>) {
let ts = OffsetDateTime::now_utc()
.format(time::macros::format_description!(
"[year]-[month]-[day] [hour]:[minute]:[second]Z"
))
.unwrap_or_default();
self.log.push(format!("{ts} {}", msg.into()));
// Keep the log bounded; old lines are rarely useful.
if self.log.len() > 200 {
let excess = self.log.len() - 200;
self.log.drain(..excess);
}
self.touch();
}
pub fn advance(&mut self, stage: Stage) {
debug_assert!(stage > self.stage, "stages only move forward");
self.stage = stage;
self.touch();
}
pub fn touch(&mut self) {
self.updated = OffsetDateTime::now_utc();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stages_are_ordered() {
assert!(Stage::Created < Stage::ExportReady);
assert!(Stage::Promoted < Stage::TargetScanned);
assert!(Stage::SourceCleaned < Stage::Done);
}
#[test]
fn job_roundtrips_through_json() {
let mut job = Job::new("abc", "Alien (1979)", "cloud", "home", false);
job.note("created");
let json = serde_json::to_string(&job).unwrap();
let back: Job = serde_json::from_str(&json).unwrap();
assert_eq!(back.id, job.id);
assert_eq!(back.stage, Stage::Created);
assert_eq!(back.status, JobStatus::Queued);
assert_eq!(back.log.len(), 1);
}
#[test]
fn log_is_bounded() {
let mut job = Job::new("abc", "x", "a", "b", false);
for i in 0..250 {
job.note(format!("line {i}"));
}
assert_eq!(job.log.len(), 200);
assert!(job.log.last().unwrap().ends_with("line 249"));
}
}
+11
View File
@@ -0,0 +1,11 @@
//! Domain types shared by every jellymove crate: jobs and their stages,
//! path mapping between Jellyfin's view of the filesystem and the agent's,
//! and the safety rules that decide whether a folder can be moved.
pub mod job;
pub mod paths;
pub mod safety;
pub mod userdata;
pub use job::{ItemKind, Job, JobId, JobStatus, Stage};
pub use paths::PathMap;
+168
View File
@@ -0,0 +1,168 @@
//! Jellyfin reports paths as *it* sees them (inside its container). The agent
//! may see the same files at a different path. A `PathMap` translates between
//! the two. In the recommended Docker setup both containers mount media at the
//! same paths and the map is empty (identity).
use serde::{Deserialize, Serialize};
use std::path::{Component, Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PathMapping {
/// Prefix as Jellyfin reports it, e.g. `/media/tv`.
pub jellyfin: PathBuf,
/// The same location as this agent sees it, e.g. `/mnt/pool/tv`.
pub local: PathBuf,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct PathMap(pub Vec<PathMapping>);
impl PathMap {
/// Translate a Jellyfin path to a local one. The longest matching prefix
/// wins. With no matching mapping the path is returned unchanged.
pub fn to_local(&self, p: &Path) -> PathBuf {
translate(p, self.0.iter().map(|m| (&m.jellyfin, &m.local)))
}
pub fn to_jellyfin(&self, p: &Path) -> PathBuf {
translate(p, self.0.iter().map(|m| (&m.local, &m.jellyfin)))
}
}
fn translate<'a>(p: &Path, pairs: impl Iterator<Item = (&'a PathBuf, &'a PathBuf)>) -> PathBuf {
let best = pairs
.filter(|(from, _)| p.starts_with(from)) // component-wise, so /tv ≠ /tvshows
.max_by_key(|(from, _)| from.components().count());
match best {
Some((from, to)) => to.join(p.strip_prefix(from).expect("checked by starts_with")),
None => p.to_path_buf(),
}
}
/// A relative path that is safe to join onto a root: no `..`, no absolute
/// components, not empty.
pub fn is_safe_relative(rel: &Path) -> bool {
!rel.as_os_str().is_empty()
&& rel
.components()
.all(|c| matches!(c, Component::Normal(_) | Component::CurDir))
}
/// Path of `item` relative to `root`, as a `/`-separated string, if `item` is
/// strictly inside `root`.
pub fn relative_inside(root: &Path, item: &Path) -> Option<String> {
let rel = item.strip_prefix(root).ok()?;
if !is_safe_relative(rel) {
return None;
}
let parts: Vec<_> = rel
.components()
.filter_map(|c| match c {
Component::Normal(s) => Some(s.to_string_lossy().into_owned()),
_ => None,
})
.collect();
if parts.is_empty() {
None
} else {
Some(parts.join("/"))
}
}
/// Join a `/`-separated relative path received from a peer onto a root,
/// refusing anything that could escape it.
pub fn join_relative(root: &Path, rel: &str) -> Option<PathBuf> {
// Empty segments mean a leading `/` (absolute) or `//`; refuse both.
if rel.contains('\\') || rel.split('/').any(|seg| seg.is_empty() || seg == "..") {
return None;
}
let rel_path: PathBuf = rel.split('/').collect();
if !is_safe_relative(&rel_path) {
return None;
}
Some(root.join(rel_path))
}
#[cfg(test)]
mod tests {
use super::*;
fn map() -> PathMap {
PathMap(vec![
PathMapping {
jellyfin: "/media".into(),
local: "/mnt/pool".into(),
},
PathMapping {
jellyfin: "/media/tv".into(),
local: "/mnt/fast/tv".into(),
},
])
}
#[test]
fn longest_prefix_wins() {
let m = map();
assert_eq!(
m.to_local(Path::new("/media/tv/Show/S01")),
PathBuf::from("/mnt/fast/tv/Show/S01")
);
assert_eq!(
m.to_local(Path::new("/media/movies/A")),
PathBuf::from("/mnt/pool/movies/A")
);
}
#[test]
fn prefix_match_is_by_component() {
let m = PathMap(vec![PathMapping {
jellyfin: "/media/tv".into(),
local: "/x".into(),
}]);
assert_eq!(
m.to_local(Path::new("/media/tvshows/A")),
PathBuf::from("/media/tvshows/A")
);
}
#[test]
fn roundtrip() {
let m = map();
let p = Path::new("/media/movies/Alien (1979)/Alien.mkv");
assert_eq!(m.to_jellyfin(&m.to_local(p)), p);
}
#[test]
fn empty_map_is_identity() {
assert_eq!(
PathMap::default().to_local(Path::new("/a/b")),
PathBuf::from("/a/b")
);
}
#[test]
fn relative_inside_requires_strict_child() {
let root = Path::new("/media/movies");
assert_eq!(
relative_inside(root, Path::new("/media/movies/Alien (1979)")).as_deref(),
Some("Alien (1979)")
);
assert_eq!(relative_inside(root, Path::new("/media/movies")), None);
assert_eq!(relative_inside(root, Path::new("/media/tv/X")), None);
}
#[test]
fn join_relative_rejects_escapes() {
let root = Path::new("/data");
assert_eq!(
join_relative(root, "Show/Season 1/e.mkv"),
Some(PathBuf::from("/data/Show/Season 1/e.mkv"))
);
assert_eq!(join_relative(root, "../etc/passwd"), None);
assert_eq!(join_relative(root, "a/../../b"), None);
assert_eq!(join_relative(root, "/etc/passwd"), None);
assert_eq!(join_relative(root, ""), None);
assert_eq!(join_relative(root, "a\\..\\b"), None);
}
}
+187
View File
@@ -0,0 +1,187 @@
//! Rules that decide whether an item's folder can be moved as a unit.
//!
//! jellymove moves whole folders so sidecars (NFO, artwork, subtitles,
//! trickplay, extras) travel with the media. That is only safe when the folder
//! belongs to exactly one item. A flat movie library (`/movies/A.mkv`,
//! `/movies/B.mkv`) would otherwise drag every other movie along.
use std::path::Path;
pub const VIDEO_EXTENSIONS: &[&str] = &[
"mkv", "mp4", "m4v", "avi", "mov", "wmv", "ts", "m2ts", "mpg", "mpeg", "webm", "flv", "iso",
"vob",
];
/// Folder names Jellyfin treats as extras. Videos inside them belong to the item.
pub const EXTRAS_FOLDERS: &[&str] = &[
"extras",
"specials",
"shorts",
"scenes",
"featurettes",
"behind the scenes",
"deleted scenes",
"interviews",
"clips",
"trailers",
"other",
"theme-music",
"backdrops",
];
/// Filename suffixes Jellyfin treats as extras (`Movie-trailer.mkv`).
pub const EXTRAS_SUFFIXES: &[&str] = &[
"-trailer",
".trailer",
"_trailer",
"-sample",
".sample",
"_sample",
"-scene",
"-clip",
"-interview",
"-behindthescenes",
"-deleted",
"-deletedscene",
"-featurette",
"-short",
"-other",
"-extra",
];
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum FolderProblem {
#[error("the item folder is a library root; moving it would move the whole library")]
IsLibraryRoot,
#[error("the item folder is not inside any library location")]
OutsideLibraries,
#[error(
"the folder also holds other videos ({0}); give each movie its own folder before moving it"
)]
SharedFolder(String),
}
pub fn is_video(name: &str) -> bool {
Path::new(name)
.extension()
.and_then(|e| e.to_str())
.is_some_and(|e| VIDEO_EXTENSIONS.contains(&e.to_ascii_lowercase().as_str()))
}
fn is_extra(rel_path: &str) -> bool {
let lower = rel_path.to_ascii_lowercase();
let mut parts: Vec<&str> = lower.split('/').collect();
let file = parts.pop().unwrap_or_default();
if parts.iter().any(|p| EXTRAS_FOLDERS.contains(p)) {
return true;
}
let stem = Path::new(file)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or_default();
EXTRAS_SUFFIXES.iter().any(|s| stem.ends_with(s))
}
/// Check that a movie folder belongs to this movie alone.
///
/// `files` are every file in the folder relative to it (`/` separated).
/// `own_media` are the item's media source paths relative to the same folder,
/// so multi-version movies (`Movie - 1080p.mkv`, `Movie - 4K.mkv`) pass.
pub fn check_movie_folder(files: &[String], own_media: &[String]) -> Result<(), FolderProblem> {
let strangers: Vec<&String> = files
.iter()
.filter(|f| is_video(f) && !is_extra(f) && !own_media.iter().any(|m| m == *f))
.collect();
if strangers.is_empty() {
Ok(())
} else {
let mut names: Vec<String> = strangers.iter().take(3).map(|s| s.to_string()).collect();
if strangers.len() > 3 {
names.push(format!("and {} more", strangers.len() - 3));
}
Err(FolderProblem::SharedFolder(names.join(", ")))
}
}
/// Check that `folder` sits strictly inside one of the library `locations`.
/// Returns the matching location.
pub fn check_inside_library<'a>(
folder: &Path,
locations: &'a [String],
) -> Result<&'a str, FolderProblem> {
for loc in locations {
let loc_path = Path::new(loc);
if folder == loc_path {
return Err(FolderProblem::IsLibraryRoot);
}
if folder.starts_with(loc_path) {
return Ok(loc);
}
}
Err(FolderProblem::OutsideLibraries)
}
#[cfg(test)]
mod tests {
use super::*;
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|x| x.to_string()).collect()
}
#[test]
fn single_movie_folder_with_sidecars_passes() {
let files = s(&[
"Alien (1979).mkv",
"Alien (1979).nfo",
"poster.jpg",
"fanart.jpg",
"Alien (1979).en.srt",
"Alien (1979)-trailer.mp4",
"extras/Making of.mkv",
"Behind The Scenes/Ridley.mkv",
"trickplay/320 - 10x10/0.jpg",
]);
assert_eq!(
check_movie_folder(&files, &s(&["Alien (1979).mkv"])),
Ok(())
);
}
#[test]
fn multi_version_movie_passes() {
let files = s(&["Dune - 1080p.mkv", "Dune - 2160p.mkv", "movie.nfo"]);
assert_eq!(
check_movie_folder(&files, &s(&["Dune - 1080p.mkv", "Dune - 2160p.mkv"])),
Ok(())
);
}
#[test]
fn flat_folder_is_refused() {
let files = s(&["Alien (1979).mkv", "Aliens (1986).mkv", "Heat (1995).mp4"]);
let err = check_movie_folder(&files, &s(&["Alien (1979).mkv"])).unwrap_err();
assert!(matches!(err, FolderProblem::SharedFolder(ref m) if m.contains("Aliens")));
}
#[test]
fn library_root_is_refused() {
let locs = s(&["/media/movies"]);
assert_eq!(
check_inside_library(Path::new("/media/movies"), &locs),
Err(FolderProblem::IsLibraryRoot)
);
assert_eq!(
check_inside_library(Path::new("/media/movies/Alien"), &locs),
Ok("/media/movies")
);
assert_eq!(
check_inside_library(Path::new("/other/Alien"), &locs),
Err(FolderProblem::OutsideLibraries)
);
assert_eq!(
check_inside_library(Path::new("/media/moviesx/Alien"), &locs),
Err(FolderProblem::OutsideLibraries)
);
}
}
+82
View File
@@ -0,0 +1,82 @@
//! Watch state that has to be carried across a move.
//!
//! Jellyfin derives item IDs from file paths, so a moved item is a brand-new
//! item on the destination with no history. The source captures each user's
//! data before the move; the destination re-applies it once the scan has
//! produced the new items. Users are matched by name (case-insensitive).
//! Items are matched by position inside the moved folder: the root item
//! itself, or an episode's season and episode number.
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum ItemKey {
/// The movie or series being moved.
Root,
Episode {
season: i32,
episode: i32,
},
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct UserData {
pub played: bool,
pub play_count: i32,
pub is_favorite: bool,
pub playback_position_ticks: i64,
/// RFC 3339, as Jellyfin returns it.
pub last_played_date: Option<String>,
}
impl UserData {
/// Nothing worth copying: unwatched, not started, not a favourite.
pub fn is_empty(&self) -> bool {
!self.played
&& self.play_count == 0
&& !self.is_favorite
&& self.playback_position_ticks == 0
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UserDataRecord {
pub user_name: String,
pub key: ItemKey,
pub data: UserData,
}
pub fn same_user(a: &str, b: &str) -> bool {
a.trim().eq_ignore_ascii_case(b.trim())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_detection() {
assert!(UserData::default().is_empty());
assert!(
!UserData {
is_favorite: true,
..Default::default()
}
.is_empty()
);
assert!(
!UserData {
playback_position_ticks: 10,
..Default::default()
}
.is_empty()
);
}
#[test]
fn users_match_case_insensitively() {
assert!(same_user("Alice", " alice "));
assert!(!same_user("Alice", "Ali"));
}
}