1 parent
f47217d5a3
commit
8ceb3c8be8
60 files changed
+10884
No files matched your search
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "jellymove"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.104"
|
||||
clap = { version = "4.6.7", features = ["derive", "env"] }
|
||||
figment = { version = "0.10.19", features = ["toml", "env"] }
|
||||
jm-core = { version = "0.1.0", path = "../jm-core" }
|
||||
jm-server = { version = "0.1.0", path = "../jm-server" }
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_json = "1.0.154"
|
||||
tokio = { version = "1.54.1", features = ["full"] }
|
||||
tracing = "0.1.44"
|
||||
tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] }
|
||||
@@ -0,0 +1,77 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::Context;
|
||||
use clap::{Parser, Subcommand};
|
||||
use figment::Figment;
|
||||
use figment::providers::{Env, Format, Toml};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
const EXAMPLE_CONFIG: &str = include_str!("../../../config.example.toml");
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(version, about = "Move media between two Jellyfin servers")]
|
||||
struct Cli {
|
||||
/// Config file (TOML). Values can be overridden with JELLYMOVE_* env vars.
|
||||
#[arg(
|
||||
short,
|
||||
long,
|
||||
env = "JELLYMOVE_CONFIG",
|
||||
default_value = "jellymove.toml",
|
||||
global = true
|
||||
)]
|
||||
config: PathBuf,
|
||||
/// Log as JSON lines (for log shippers).
|
||||
#[arg(long, env = "JELLYMOVE_LOG_JSON", global = true)]
|
||||
log_json: bool,
|
||||
#[command(subcommand)]
|
||||
command: Option<Command>,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Command {
|
||||
/// Run the daemon (default).
|
||||
Run,
|
||||
/// Load and validate the config, print it with secrets redacted, then exit.
|
||||
CheckConfig,
|
||||
/// Print an example config file.
|
||||
ExampleConfig,
|
||||
}
|
||||
|
||||
fn load(path: &PathBuf) -> anyhow::Result<jm_server::Config> {
|
||||
let mut fig = Figment::new();
|
||||
if path.exists() {
|
||||
fig = fig.merge(Toml::file(path));
|
||||
} else {
|
||||
tracing::warn!(path = %path.display(), "config file not found; using environment only");
|
||||
}
|
||||
fig.merge(
|
||||
Env::prefixed("JELLYMOVE_")
|
||||
.split("__")
|
||||
.ignore(&["config", "log_json"]),
|
||||
)
|
||||
.extract()
|
||||
.with_context(|| format!("invalid configuration (file: {})", path.display()))
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let cli = Cli::parse();
|
||||
let filter = EnvFilter::try_from_env("JELLYMOVE_LOG")
|
||||
.unwrap_or_else(|_| EnvFilter::new("info,tower_http=warn"));
|
||||
let fmt = tracing_subscriber::fmt().with_env_filter(filter);
|
||||
if cli.log_json {
|
||||
fmt.json().init()
|
||||
} else {
|
||||
fmt.init()
|
||||
}
|
||||
|
||||
match cli.command.unwrap_or(Command::Run) {
|
||||
Command::ExampleConfig => print!("{EXAMPLE_CONFIG}"),
|
||||
Command::CheckConfig => {
|
||||
let cfg = load(&cli.config)?;
|
||||
println!("{}", serde_json::to_string_pretty(&cfg.redacted())?);
|
||||
}
|
||||
Command::Run => jm_server::run(load(&cli.config)?).await?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -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"] }
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "jm-jellyfin"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
jm-core = { version = "0.1.0", path = "../jm-core" }
|
||||
reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "json", "query", "http2"] }
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_json = "1.0.154"
|
||||
thiserror = "2.0.21"
|
||||
tracing = "0.1.44"
|
||||
|
||||
[dev-dependencies]
|
||||
axum = "0.8.9"
|
||||
tokio = { version = "1.54.1", features = ["full"] }
|
||||
@@ -0,0 +1,425 @@
|
||||
//! A thin, typed client for the handful of Jellyfin endpoints jellymove needs.
|
||||
//!
|
||||
//! Written against Jellyfin 10.9+ (including the v12 line). Routes for user
|
||||
//! data moved in 10.9 (`/UserItems/...`); check against your server's
|
||||
//! `/api-docs/openapi.json` if something returns 404.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
|
||||
use reqwest::header::{AUTHORIZATION, HeaderMap, HeaderValue};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub use jm_core::userdata::UserData;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum JellyfinError {
|
||||
#[error("could not reach Jellyfin: {0}")]
|
||||
Http(#[from] reqwest::Error),
|
||||
#[error("Jellyfin returned HTTP {status} for {path}")]
|
||||
Status { status: u16, path: String },
|
||||
#[error("invalid Jellyfin URL: {0}")]
|
||||
BadUrl(String),
|
||||
}
|
||||
|
||||
type Result<T> = std::result::Result<T, JellyfinError>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Client {
|
||||
base: String,
|
||||
http: reqwest::Client,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
pub struct SystemInfo {
|
||||
pub server_name: String,
|
||||
pub version: String,
|
||||
#[serde(default)]
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
pub struct VirtualFolder {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub locations: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub collection_type: Option<String>,
|
||||
#[serde(default)]
|
||||
pub item_id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
pub struct MediaSource {
|
||||
#[serde(default)]
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
pub struct ItemUserData {
|
||||
#[serde(default)]
|
||||
pub played: bool,
|
||||
#[serde(default)]
|
||||
pub play_count: i32,
|
||||
#[serde(default)]
|
||||
pub is_favorite: bool,
|
||||
#[serde(default)]
|
||||
pub playback_position_ticks: i64,
|
||||
#[serde(default)]
|
||||
pub last_played_date: Option<String>,
|
||||
}
|
||||
|
||||
impl From<ItemUserData> for UserData {
|
||||
fn from(u: ItemUserData) -> Self {
|
||||
UserData {
|
||||
played: u.played,
|
||||
play_count: u.play_count,
|
||||
is_favorite: u.is_favorite,
|
||||
playback_position_ticks: u.playback_position_ticks,
|
||||
last_played_date: u.last_played_date,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
pub struct Item {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(rename = "Type")]
|
||||
pub kind: String,
|
||||
#[serde(default)]
|
||||
pub path: Option<String>,
|
||||
#[serde(default)]
|
||||
pub production_year: Option<i32>,
|
||||
#[serde(default)]
|
||||
pub provider_ids: HashMap<String, String>,
|
||||
#[serde(default)]
|
||||
pub media_sources: Option<Vec<MediaSource>>,
|
||||
/// Season number for episodes.
|
||||
#[serde(default)]
|
||||
pub parent_index_number: Option<i32>,
|
||||
/// Episode number for episodes.
|
||||
#[serde(default)]
|
||||
pub index_number: Option<i32>,
|
||||
#[serde(default)]
|
||||
pub user_data: Option<ItemUserData>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
struct ItemsPage {
|
||||
#[serde(default)]
|
||||
items: Vec<Item>,
|
||||
#[serde(default)]
|
||||
total_record_count: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
pub struct User {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// Query for `GET /Items`.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ItemQuery<'a> {
|
||||
pub ids: Option<&'a str>,
|
||||
pub parent_id: Option<&'a str>,
|
||||
pub include_types: &'a [&'a str],
|
||||
pub recursive: bool,
|
||||
pub search: Option<&'a str>,
|
||||
/// Ask for this user's watch state alongside each item.
|
||||
pub user_id: Option<&'a str>,
|
||||
}
|
||||
|
||||
const FIELDS: &str = "Path,ProviderIds,MediaSources,ProductionYear";
|
||||
const PAGE: usize = 500;
|
||||
|
||||
impl Client {
|
||||
pub fn new(base_url: &str, api_key: &str) -> Result<Self> {
|
||||
let base = base_url.trim_end_matches('/').to_string();
|
||||
if !(base.starts_with("http://") || base.starts_with("https://")) {
|
||||
return Err(JellyfinError::BadUrl(base_url.to_string()));
|
||||
}
|
||||
let mut headers = HeaderMap::new();
|
||||
let auth = format!(
|
||||
r#"MediaBrowser Client="jellymove", Device="jellymove", DeviceId="jellymove", Version="{}", Token="{}""#,
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
api_key
|
||||
);
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_str(&auth).map_err(|_| JellyfinError::BadUrl("api key".into()))?,
|
||||
);
|
||||
let http = reqwest::Client::builder()
|
||||
.default_headers(headers)
|
||||
.timeout(Duration::from_secs(60))
|
||||
.build()?;
|
||||
Ok(Self { base, http })
|
||||
}
|
||||
|
||||
async fn get<T: for<'de> Deserialize<'de>>(
|
||||
&self,
|
||||
path: &str,
|
||||
query: &[(&str, String)],
|
||||
) -> Result<T> {
|
||||
let resp = self
|
||||
.http
|
||||
.get(format!("{}{path}", self.base))
|
||||
.query(query)
|
||||
.send()
|
||||
.await?;
|
||||
check(resp, path).await?.json().await.map_err(Into::into)
|
||||
}
|
||||
|
||||
async fn post_json<B: Serialize>(
|
||||
&self,
|
||||
path: &str,
|
||||
query: &[(&str, String)],
|
||||
body: &B,
|
||||
) -> Result<()> {
|
||||
let resp = self
|
||||
.http
|
||||
.post(format!("{}{path}", self.base))
|
||||
.query(query)
|
||||
.json(body)
|
||||
.send()
|
||||
.await?;
|
||||
check(resp, path).await.map(|_| ())
|
||||
}
|
||||
|
||||
pub async fn system_info(&self) -> Result<SystemInfo> {
|
||||
self.get("/System/Info", &[]).await
|
||||
}
|
||||
|
||||
pub async fn virtual_folders(&self) -> Result<Vec<VirtualFolder>> {
|
||||
self.get("/Library/VirtualFolders", &[]).await
|
||||
}
|
||||
|
||||
pub async fn users(&self) -> Result<Vec<User>> {
|
||||
self.get("/Users", &[]).await
|
||||
}
|
||||
|
||||
pub async fn item(&self, id: &str) -> Result<Item> {
|
||||
let mut items = self
|
||||
.get::<ItemsPage>(
|
||||
"/Items",
|
||||
&[("ids", id.to_string()), ("fields", FIELDS.to_string())],
|
||||
)
|
||||
.await?
|
||||
.items;
|
||||
items.pop().ok_or(JellyfinError::Status {
|
||||
status: 404,
|
||||
path: format!("/Items?ids={id}"),
|
||||
})
|
||||
}
|
||||
|
||||
/// Fetch every item matching `q`, following pagination.
|
||||
pub async fn items(&self, q: &ItemQuery<'_>) -> Result<Vec<Item>> {
|
||||
let mut out = Vec::new();
|
||||
loop {
|
||||
let mut query: Vec<(&str, String)> = vec![
|
||||
("fields", FIELDS.to_string()),
|
||||
("recursive", q.recursive.to_string()),
|
||||
("startIndex", out.len().to_string()),
|
||||
("limit", PAGE.to_string()),
|
||||
("sortBy", "SortName".to_string()),
|
||||
];
|
||||
if let Some(ids) = q.ids {
|
||||
query.push(("ids", ids.to_string()));
|
||||
}
|
||||
if let Some(p) = q.parent_id {
|
||||
query.push(("parentId", p.to_string()));
|
||||
}
|
||||
if !q.include_types.is_empty() {
|
||||
query.push(("includeItemTypes", q.include_types.join(",")));
|
||||
}
|
||||
if let Some(s) = q.search {
|
||||
query.push(("searchTerm", s.to_string()));
|
||||
}
|
||||
if let Some(u) = q.user_id {
|
||||
query.push(("userId", u.to_string()));
|
||||
query.push(("enableUserData", "true".to_string()));
|
||||
}
|
||||
let page: ItemsPage = self.get("/Items", &query).await?;
|
||||
let got = page.items.len();
|
||||
out.extend(page.items);
|
||||
if got < PAGE || out.len() >= page.total_record_count {
|
||||
return Ok(out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask Jellyfin to rescan just these folders. Jellyfin answers 204 even for
|
||||
/// paths outside every library and waits `LibraryMonitorDelay` (60 s by
|
||||
/// default) before scanning, so callers must poll for the result.
|
||||
pub async fn media_updated(&self, paths: &[String]) -> Result<()> {
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
struct Update<'a> {
|
||||
path: &'a str,
|
||||
update_type: &'a str,
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
struct Body<'a> {
|
||||
updates: Vec<Update<'a>>,
|
||||
}
|
||||
let body = Body {
|
||||
updates: paths
|
||||
.iter()
|
||||
.map(|p| Update {
|
||||
path: p,
|
||||
update_type: "Modified",
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
self.post_json("/Library/Media/Updated", &[], &body).await
|
||||
}
|
||||
|
||||
/// Full library scan. A fallback when targeted updates don't take.
|
||||
pub async fn refresh_library(&self) -> Result<()> {
|
||||
let resp = self
|
||||
.http
|
||||
.post(format!("{}/Library/Refresh", self.base))
|
||||
.send()
|
||||
.await?;
|
||||
check(resp, "/Library/Refresh").await.map(|_| ())
|
||||
}
|
||||
|
||||
/// Write a user's watch state for an item (Jellyfin 10.9+).
|
||||
pub async fn set_user_data(&self, user_id: &str, item_id: &str, data: &UserData) -> Result<()> {
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
struct Dto<'a> {
|
||||
played: bool,
|
||||
play_count: i32,
|
||||
is_favorite: bool,
|
||||
playback_position_ticks: i64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
last_played_date: Option<&'a str>,
|
||||
}
|
||||
let dto = Dto {
|
||||
played: data.played,
|
||||
play_count: data.play_count,
|
||||
is_favorite: data.is_favorite,
|
||||
playback_position_ticks: data.playback_position_ticks,
|
||||
last_played_date: data.last_played_date.as_deref(),
|
||||
};
|
||||
self.post_json(
|
||||
&format!("/UserItems/{item_id}/UserData"),
|
||||
&[("userId", user_id.to_string())],
|
||||
&dto,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
async fn check(resp: reqwest::Response, path: &str) -> Result<reqwest::Response> {
|
||||
if resp.status().is_success() {
|
||||
Ok(resp)
|
||||
} else {
|
||||
Err(JellyfinError::Status {
|
||||
status: resp.status().as_u16(),
|
||||
path: path.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::extract::Query;
|
||||
use axum::http::{HeaderMap as AxHeaders, StatusCode};
|
||||
use axum::routing::{get, post};
|
||||
use axum::{Json, Router};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
async fn mock() -> String {
|
||||
async fn items(
|
||||
headers: AxHeaders,
|
||||
Query(q): Query<HashMap<String, String>>,
|
||||
) -> std::result::Result<Json<Value>, StatusCode> {
|
||||
let auth = headers
|
||||
.get("authorization")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.unwrap_or_default();
|
||||
if !auth.contains(r#"Token="secret""#) {
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
// 1 200 fake movies served in pages.
|
||||
let start: usize = q
|
||||
.get("startIndex")
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
let limit: usize = q.get("limit").and_then(|s| s.parse().ok()).unwrap_or(100);
|
||||
let total = 1200;
|
||||
let items: Vec<Value> = (start..(start + limit).min(total))
|
||||
.map(|i| json!({"Id": format!("id{i}"), "Name": format!("Movie {i}"), "Type": "Movie",
|
||||
"Path": format!("/media/movies/Movie {i}/Movie {i}.mkv"),
|
||||
"ProviderIds": {"Tmdb": i.to_string()},
|
||||
"UserData": {"Played": i % 2 == 0, "PlaybackPositionTicks": 0, "PlayCount": 1, "IsFavorite": false}}))
|
||||
.collect();
|
||||
Ok(Json(json!({"Items": items, "TotalRecordCount": total})))
|
||||
}
|
||||
async fn updated(Json(body): Json<Value>) -> StatusCode {
|
||||
assert_eq!(body["Updates"][0]["Path"], "/media/movies/X");
|
||||
StatusCode::NO_CONTENT
|
||||
}
|
||||
let app = Router::new()
|
||||
.route("/Items", get(items))
|
||||
.route("/Library/Media/Updated", post(updated))
|
||||
.route("/Library/VirtualFolders", get(|| async {
|
||||
Json(json!([{"Name": "Movies", "Locations": ["/media/movies"], "CollectionType": "movies", "ItemId": "lib1"}]))
|
||||
}));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
format!("http://{addr}/")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn paginates_and_parses_items() {
|
||||
let c = Client::new(&mock().await, "secret").unwrap();
|
||||
let items = c
|
||||
.items(&ItemQuery {
|
||||
include_types: &["Movie"],
|
||||
recursive: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(items.len(), 1200);
|
||||
assert_eq!(items[1199].name, "Movie 1199");
|
||||
assert_eq!(items[3].provider_ids["Tmdb"], "3");
|
||||
assert!(items[2].user_data.as_ref().unwrap().played);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bad_token_is_an_error() {
|
||||
let c = Client::new(&mock().await, "wrong").unwrap();
|
||||
let err = c.items(&ItemQuery::default()).await.unwrap_err();
|
||||
assert!(matches!(err, JellyfinError::Status { status: 401, .. }));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn virtual_folders_and_media_updated() {
|
||||
let c = Client::new(&mock().await, "secret").unwrap();
|
||||
let vf = c.virtual_folders().await.unwrap();
|
||||
assert_eq!(vf[0].locations, ["/media/movies"]);
|
||||
c.media_updated(&["/media/movies/X".to_string()])
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_url() {
|
||||
assert!(Client::new("jellyfin:8096", "k").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
[package]
|
||||
name = "jm-server"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.104"
|
||||
axum = { version = "0.8.9", features = ["macros"] }
|
||||
base64 = "0.23.1"
|
||||
futures = "0.3.34"
|
||||
jm-core = { version = "0.1.0", path = "../jm-core" }
|
||||
jm-jellyfin = { version = "0.1.0", path = "../jm-jellyfin" }
|
||||
jm-store = { version = "0.1.0", path = "../jm-store" }
|
||||
jm-transfer = { version = "0.1.0", path = "../jm-transfer" }
|
||||
mime_guess = "2.0.5"
|
||||
reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "json", "stream", "http2"] }
|
||||
rust-embed = "8.13.0"
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_json = "1.0.154"
|
||||
thiserror = "2.0.21"
|
||||
time = "0.3.45"
|
||||
tokio = { version = "1.54.1", features = ["full"] }
|
||||
tokio-stream = { version = "0.1.19", features = ["sync"] }
|
||||
tower-http = { version = "0.7.1", features = ["trace"] }
|
||||
tracing = "0.1.44"
|
||||
uuid = { version = "1.26.1", features = ["v4"] }
|
||||
|
||||
[dev-dependencies]
|
||||
anyhow = "1.0.104"
|
||||
blake3 = "1.8.7"
|
||||
reqwest = { version = "0.13.5", default-features = false, features = ["json"] }
|
||||
serde_json = "1.0.154"
|
||||
tempfile = "3.27.0"
|
||||
tokio = { version = "1.54.1", features = ["full"] }
|
||||
tower = "0.5.3"
|
||||
@@ -0,0 +1,132 @@
|
||||
//! Local demo: two jellymove agents ("cloud" on :8097, "home" on :8098), each
|
||||
//! with a fake Jellyfin and some throwaway media in a temp folder.
|
||||
//!
|
||||
//! npm --prefix ui ci && npm --prefix ui run build
|
||||
//! cargo run -p jm-server --example demo
|
||||
//!
|
||||
//! Then open http://127.0.0.1:8097 and move something to "home".
|
||||
|
||||
#[path = "../tests/fake_jellyfin/mod.rs"]
|
||||
#[allow(dead_code)]
|
||||
mod fake_jellyfin;
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use fake_jellyfin::{Fake, Lib};
|
||||
use jm_server::config::{
|
||||
Config, HooksConfig, JellyfinConfig, PeerConfig, TransferConfig, UiConfig,
|
||||
};
|
||||
|
||||
fn write(path: &Path, len: usize) {
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
let data: Vec<u8> = (0..len as u32)
|
||||
.map(|i| (i.wrapping_mul(2654435761) >> 11) as u8)
|
||||
.collect();
|
||||
std::fs::write(path, data).unwrap();
|
||||
}
|
||||
|
||||
fn libs(root: &Path) -> Vec<Lib> {
|
||||
vec![
|
||||
Lib {
|
||||
name: "Movies".into(),
|
||||
collection_type: "movies",
|
||||
location: root.join("movies"),
|
||||
},
|
||||
Lib {
|
||||
name: "TV Shows".into(),
|
||||
collection_type: "tvshows",
|
||||
location: root.join("tv"),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
tracing_subscriber_init();
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let cloud = tmp.path().join("cloud");
|
||||
let home = tmp.path().join("home");
|
||||
for r in [&cloud, &home] {
|
||||
std::fs::create_dir_all(r.join("movies"))?;
|
||||
std::fs::create_dir_all(r.join("tv"))?;
|
||||
}
|
||||
const MB: usize = 1024 * 1024;
|
||||
for (folder, size) in [
|
||||
("Arrival (2016)", 180 * MB),
|
||||
("Blade Runner (1982)", 120 * MB),
|
||||
("Heat (1995)", 60 * MB),
|
||||
] {
|
||||
let base = cloud.join("movies").join(folder);
|
||||
write(&base.join(format!("{folder}.mkv")), size);
|
||||
write(&base.join(format!("{folder}.nfo")), 300);
|
||||
write(&base.join(format!("{folder}.en.srt")), 40_000);
|
||||
write(&base.join("poster.jpg"), 200_000);
|
||||
}
|
||||
for ep in 1..=6 {
|
||||
write(
|
||||
&cloud.join(format!("tv/Severance/Season 01/Severance S01E{ep:02}.mkv")),
|
||||
20 * MB,
|
||||
);
|
||||
}
|
||||
write(
|
||||
&home.join("movies/The Thing (1982)/The Thing (1982).mkv"),
|
||||
40 * MB,
|
||||
);
|
||||
|
||||
let fake_cloud = Fake::new(libs(&cloud));
|
||||
let fake_home = Fake::new(libs(&home));
|
||||
if let Some(id) = fake_cloud.find("Movie", "Arrival") {
|
||||
fake_cloud.set_user_data(&id, serde_json::json!({"Played": true, "PlayCount": 1}));
|
||||
}
|
||||
let jf_cloud = fake_cloud.serve().await;
|
||||
let jf_home = fake_home.serve().await;
|
||||
|
||||
let mut tasks = Vec::new();
|
||||
for (name, root, jf, port, peer_port) in [
|
||||
("cloud", &cloud, jf_cloud, 8097, 8098),
|
||||
("home", &home, jf_home, 8098, 8097),
|
||||
] {
|
||||
let cfg = Config {
|
||||
node_name: name.into(),
|
||||
listen: format!("127.0.0.1:{port}").parse()?,
|
||||
data_dir: root.join(".state"),
|
||||
jellyfin: JellyfinConfig {
|
||||
url: jf,
|
||||
api_key: "demo".into(),
|
||||
},
|
||||
path_map: Default::default(),
|
||||
peer: Some(PeerConfig {
|
||||
url: format!("http://127.0.0.1:{peer_port}"),
|
||||
token: "demo-token".into(),
|
||||
}),
|
||||
incoming_libraries: Default::default(),
|
||||
// Throttled so you can watch the progress bar.
|
||||
transfer: TransferConfig {
|
||||
bandwidth_limit_mbps: 200.0,
|
||||
..Default::default()
|
||||
},
|
||||
ui: UiConfig::default(),
|
||||
hooks: HooksConfig::default(),
|
||||
};
|
||||
std::fs::create_dir_all(&cfg.data_dir)?;
|
||||
let store = jm_store::Store::open(&cfg.data_dir.join("db"))?;
|
||||
let state = Arc::new(jm_server::state::AppState::new(cfg, store)?);
|
||||
jm_server::runner::resume_all(&state).await?;
|
||||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await?;
|
||||
tasks.push(tokio::spawn(async move {
|
||||
axum::serve(listener, jm_server::api::router(state)).await
|
||||
}));
|
||||
}
|
||||
println!("demo media in {}", tmp.path().display());
|
||||
println!("cloud: http://127.0.0.1:8097 home: http://127.0.0.1:8098 (Ctrl+C to stop)");
|
||||
tokio::signal::ctrl_c().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn tracing_subscriber_init() {
|
||||
// Keep the demo quiet unless asked.
|
||||
if std::env::var_os("RUST_LOG").is_some() {
|
||||
eprintln!("(set up your own subscriber for logs)");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,444 @@
|
||||
//! HTTP routes. `/api/*` serves the browser UI; `/peer/v1/*` is the
|
||||
//! agent-to-agent protocol, authenticated with the shared peer token.
|
||||
|
||||
use std::convert::Infallible;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::extract::{Path, Query, Request, State};
|
||||
use axum::http::{HeaderMap, Method, StatusCode, header};
|
||||
use axum::middleware::{self, Next};
|
||||
use axum::response::sse::{Event, KeepAlive, Sse};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{get, post};
|
||||
use axum::{Json, Router};
|
||||
use base64::Engine;
|
||||
use futures::Stream;
|
||||
use jm_core::{Job, JobId, JobStatus};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
use tokio_stream::StreamExt;
|
||||
use tokio_stream::wrappers::BroadcastStream;
|
||||
|
||||
use crate::export::{self, Export, ExportStatus};
|
||||
use crate::library::{self, Library, LibraryItem, LocationCheck};
|
||||
use crate::peer::{CreateJob, NodeInfo};
|
||||
use crate::runner;
|
||||
use crate::state::Shared;
|
||||
|
||||
pub struct ApiError(StatusCode, String);
|
||||
|
||||
impl IntoResponse for ApiError {
|
||||
fn into_response(self) -> Response {
|
||||
(self.0, Json(json!({ "error": self.1 }))).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<anyhow::Error> for ApiError {
|
||||
fn from(e: anyhow::Error) -> Self {
|
||||
ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}"))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<jm_store::StoreError> for ApiError {
|
||||
fn from(e: jm_store::StoreError) -> Self {
|
||||
ApiError(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<jm_jellyfin::JellyfinError> for ApiError {
|
||||
fn from(e: jm_jellyfin::JellyfinError) -> Self {
|
||||
ApiError(StatusCode::BAD_GATEWAY, e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
type ApiResult<T> = Result<Json<T>, ApiError>;
|
||||
|
||||
pub fn router(state: Shared) -> Router {
|
||||
let ui_api = Router::new()
|
||||
.route("/status", get(status))
|
||||
.route("/libraries", get(ui_libraries))
|
||||
.route("/items", get(ui_items))
|
||||
.route("/moves", post(ui_move))
|
||||
.route("/jobs", get(ui_jobs))
|
||||
.route("/jobs/{id}/retry", post(ui_retry))
|
||||
.route("/events", get(events));
|
||||
|
||||
let peer_api = Router::new()
|
||||
.route("/info", get(peer_info))
|
||||
.route("/libraries", get(peer_libraries))
|
||||
.route("/items", get(peer_items))
|
||||
.route("/exports", post(peer_create_export))
|
||||
.route("/exports/{id}", get(peer_get_export))
|
||||
.route("/exports/{id}/files/{idx}", get(peer_file))
|
||||
.route("/exports/{id}/complete", post(peer_complete_export))
|
||||
.route("/jobs", get(peer_jobs).post(peer_create_job))
|
||||
.layer(middleware::from_fn_with_state(
|
||||
state.clone(),
|
||||
require_peer_token,
|
||||
));
|
||||
|
||||
Router::new()
|
||||
.nest(
|
||||
"/api",
|
||||
ui_api.layer(middleware::from_fn(require_csrf_header)),
|
||||
)
|
||||
.nest("/peer/v1", peer_api)
|
||||
.fallback(crate::ui::serve)
|
||||
.layer(middleware::from_fn_with_state(
|
||||
state.clone(),
|
||||
require_ui_auth,
|
||||
))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- auth
|
||||
|
||||
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
|
||||
}
|
||||
|
||||
async fn require_peer_token(State(state): State<Shared>, req: Request, next: Next) -> Response {
|
||||
let Some(peer) = &state.cfg.peer else {
|
||||
return ApiError(StatusCode::SERVICE_UNAVAILABLE, "no peer configured".into())
|
||||
.into_response();
|
||||
};
|
||||
let presented = req
|
||||
.headers()
|
||||
.get(header::AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Bearer "))
|
||||
.unwrap_or_default();
|
||||
if constant_time_eq(presented.as_bytes(), peer.token.as_bytes()) {
|
||||
next.run(req).await
|
||||
} else {
|
||||
ApiError(StatusCode::UNAUTHORIZED, "bad peer token".into()).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
/// HTTP Basic auth for everything except the peer API, if a password is set.
|
||||
async fn require_ui_auth(State(state): State<Shared>, req: Request, next: Next) -> Response {
|
||||
let (Some(user), Some(pass)) = (&state.cfg.ui.username, &state.cfg.ui.password) else {
|
||||
return next.run(req).await;
|
||||
};
|
||||
if req.uri().path().starts_with("/peer/") {
|
||||
return next.run(req).await;
|
||||
}
|
||||
let ok = req
|
||||
.headers()
|
||||
.get(header::AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Basic "))
|
||||
.and_then(|b| base64::engine::general_purpose::STANDARD.decode(b).ok())
|
||||
.is_some_and(|decoded| constant_time_eq(&decoded, format!("{user}:{pass}").as_bytes()));
|
||||
if ok {
|
||||
next.run(req).await
|
||||
} else {
|
||||
(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
[(header::WWW_AUTHENTICATE, r#"Basic realm="jellymove""#)],
|
||||
"login required",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
|
||||
/// Browsers send Basic credentials automatically, so state-changing requests
|
||||
/// must carry a header a cross-site form can't set.
|
||||
async fn require_csrf_header(req: Request, next: Next) -> Response {
|
||||
if req.method() != Method::GET && !req.headers().contains_key("x-jellymove") {
|
||||
return ApiError(StatusCode::FORBIDDEN, "missing X-Jellymove header".into())
|
||||
.into_response();
|
||||
}
|
||||
next.run(req).await
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- UI API
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Status {
|
||||
node: NodeInfo,
|
||||
jellyfin_error: Option<String>,
|
||||
locations: Vec<LocationCheck>,
|
||||
peer_url: Option<String>,
|
||||
peer: Option<NodeInfo>,
|
||||
peer_error: Option<String>,
|
||||
config: crate::config::Config,
|
||||
}
|
||||
|
||||
async fn node_info(state: &Shared) -> (NodeInfo, Option<String>) {
|
||||
let (server, err) = match state.jellyfin.system_info().await {
|
||||
Ok(i) => (Some(i), None),
|
||||
Err(e) => (None, Some(e.to_string())),
|
||||
};
|
||||
(
|
||||
NodeInfo {
|
||||
node_name: state.cfg.node_name.clone(),
|
||||
version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
jellyfin_server: server.as_ref().map(|s| s.server_name.clone()),
|
||||
jellyfin_version: server.map(|s| s.version),
|
||||
},
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
async fn status(State(state): State<Shared>) -> ApiResult<Status> {
|
||||
let (node, jellyfin_error) = node_info(&state).await;
|
||||
let locations = if jellyfin_error.is_none() {
|
||||
library::check_locations(&state).await?
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
let (peer, peer_error) = match &state.peer {
|
||||
None => (None, None),
|
||||
Some(p) => match p.info().await {
|
||||
Ok(i) => (Some(i), None),
|
||||
Err(e) => (None, Some(format!("{e:#}"))),
|
||||
},
|
||||
};
|
||||
Ok(Json(Status {
|
||||
node,
|
||||
jellyfin_error,
|
||||
locations,
|
||||
peer_url: state.cfg.peer.as_ref().map(|p| p.url.clone()),
|
||||
peer,
|
||||
peer_error,
|
||||
config: state.cfg.redacted(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct NodeQuery {
|
||||
#[serde(default)]
|
||||
node: Side,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum Side {
|
||||
#[default]
|
||||
Local,
|
||||
Peer,
|
||||
}
|
||||
|
||||
async fn ui_libraries(
|
||||
State(state): State<Shared>,
|
||||
Query(q): Query<NodeQuery>,
|
||||
) -> ApiResult<Vec<Library>> {
|
||||
Ok(Json(match q.node {
|
||||
Side::Local => library::libraries(&state).await?,
|
||||
Side::Peer => state.peer()?.libraries().await?,
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ItemsQuery {
|
||||
#[serde(default)]
|
||||
node: Side,
|
||||
library: String,
|
||||
search: Option<String>,
|
||||
}
|
||||
|
||||
async fn ui_items(
|
||||
State(state): State<Shared>,
|
||||
Query(q): Query<ItemsQuery>,
|
||||
) -> ApiResult<Vec<LibraryItem>> {
|
||||
Ok(Json(match q.node {
|
||||
Side::Local => library::items(&state, &q.library, q.search.as_deref()).await?,
|
||||
Side::Peer => state.peer()?.items(&q.library, q.search.as_deref()).await?,
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct MoveRequest {
|
||||
/// Where the item is now.
|
||||
from: Side,
|
||||
item_id: String,
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
dry_run: bool,
|
||||
}
|
||||
|
||||
/// Start a move. Jobs always run on the destination, which pulls the data.
|
||||
async fn ui_move(State(state): State<Shared>, Json(req): Json<MoveRequest>) -> ApiResult<Job> {
|
||||
let peer = state.peer()?;
|
||||
match req.from {
|
||||
Side::Peer => {
|
||||
let peer_name = peer.info().await?.node_name;
|
||||
let job = Job::new(
|
||||
&req.item_id,
|
||||
&req.name,
|
||||
peer_name,
|
||||
&state.cfg.node_name,
|
||||
req.dry_run,
|
||||
);
|
||||
state.save(&job).await?;
|
||||
runner::start(state.clone(), job.clone());
|
||||
Ok(Json(job))
|
||||
}
|
||||
Side::Local => {
|
||||
let job = peer
|
||||
.create_job(&CreateJob {
|
||||
item_id: req.item_id,
|
||||
name: req.name,
|
||||
dry_run: req.dry_run,
|
||||
})
|
||||
.await?;
|
||||
Ok(Json(job))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct JobsView {
|
||||
/// Jobs this node is running (items moving *to* here).
|
||||
local: Vec<Job>,
|
||||
/// Jobs the peer is running (items moving *from* here).
|
||||
peer: Vec<Job>,
|
||||
peer_error: Option<String>,
|
||||
}
|
||||
|
||||
async fn ui_jobs(State(state): State<Shared>) -> ApiResult<JobsView> {
|
||||
let local = state.store.list_jobs(100).await?;
|
||||
let (peer, peer_error) = match &state.peer {
|
||||
None => (vec![], None),
|
||||
Some(p) => match p.jobs().await {
|
||||
Ok(j) => (j, None),
|
||||
Err(e) => (vec![], Some(format!("{e:#}"))),
|
||||
},
|
||||
};
|
||||
Ok(Json(JobsView {
|
||||
local,
|
||||
peer,
|
||||
peer_error,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn ui_retry(State(state): State<Shared>, Path(id): Path<String>) -> ApiResult<Job> {
|
||||
let id: JobId = id
|
||||
.parse()
|
||||
.map_err(|_| ApiError(StatusCode::BAD_REQUEST, "bad job id".into()))?;
|
||||
let mut job = state
|
||||
.store
|
||||
.get_job(id)
|
||||
.await?
|
||||
.ok_or(ApiError(StatusCode::NOT_FOUND, "no such job".into()))?;
|
||||
match &job.status {
|
||||
JobStatus::Failed(_) => {}
|
||||
JobStatus::Planned => job.dry_run = false, // "run it for real"
|
||||
other => return Err(ApiError(StatusCode::CONFLICT, format!("job is {other:?}"))),
|
||||
}
|
||||
job.note("retry requested");
|
||||
state.save(&job).await?;
|
||||
runner::start(state.clone(), job.clone());
|
||||
Ok(Json(job))
|
||||
}
|
||||
|
||||
async fn events(State(state): State<Shared>) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
|
||||
let stream = BroadcastStream::new(state.events.subscribe()).filter_map(|msg| {
|
||||
msg.ok().and_then(|mut job| {
|
||||
job.export = None; // manifests can be large; the UI doesn't need them live
|
||||
Event::default().event("job").json_data(&job).ok().map(Ok)
|
||||
})
|
||||
});
|
||||
Sse::new(stream).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- peer API
|
||||
|
||||
async fn peer_info(State(state): State<Shared>) -> Json<NodeInfo> {
|
||||
Json(node_info(&state).await.0)
|
||||
}
|
||||
|
||||
async fn peer_libraries(State(state): State<Shared>) -> ApiResult<Vec<Library>> {
|
||||
Ok(Json(library::libraries(&state).await?))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PeerItemsQuery {
|
||||
library: String,
|
||||
search: Option<String>,
|
||||
}
|
||||
|
||||
async fn peer_items(
|
||||
State(state): State<Shared>,
|
||||
Query(q): Query<PeerItemsQuery>,
|
||||
) -> ApiResult<Vec<LibraryItem>> {
|
||||
Ok(Json(
|
||||
library::items(&state, &q.library, q.search.as_deref()).await?,
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CreateExport {
|
||||
item_id: String,
|
||||
}
|
||||
|
||||
async fn peer_create_export(
|
||||
State(state): State<Shared>,
|
||||
Json(req): Json<CreateExport>,
|
||||
) -> ApiResult<Export> {
|
||||
Ok(Json(export::create(&state, &req.item_id).await?))
|
||||
}
|
||||
|
||||
async fn peer_get_export(State(state): State<Shared>, Path(id): Path<String>) -> ApiResult<Export> {
|
||||
export::get(&state, &id)
|
||||
.await?
|
||||
.map(Json)
|
||||
.ok_or(ApiError(StatusCode::NOT_FOUND, "no such export".into()))
|
||||
}
|
||||
|
||||
async fn peer_file(
|
||||
State(state): State<Shared>,
|
||||
Path((id, idx)): Path<(String, usize)>,
|
||||
headers: HeaderMap,
|
||||
) -> Response {
|
||||
let export = match export::get(&state, &id).await {
|
||||
Ok(Some(e)) if e.status == ExportStatus::Ready => e,
|
||||
Ok(Some(_)) => {
|
||||
return ApiError(StatusCode::CONFLICT, "export not ready".into()).into_response();
|
||||
}
|
||||
Ok(None) => return StatusCode::NOT_FOUND.into_response(),
|
||||
Err(e) => return ApiError::from(e).into_response(),
|
||||
};
|
||||
match export.file_path(&state, idx) {
|
||||
Some(path) => jm_transfer::range_response(&path, &headers).await,
|
||||
None => StatusCode::NOT_FOUND.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn peer_complete_export(
|
||||
State(state): State<Shared>,
|
||||
Path(id): Path<String>,
|
||||
) -> ApiResult<Export> {
|
||||
Ok(Json(export::complete(&state, &id).await?))
|
||||
}
|
||||
|
||||
async fn peer_create_job(
|
||||
State(state): State<Shared>,
|
||||
Json(req): Json<CreateJob>,
|
||||
) -> ApiResult<Job> {
|
||||
let peer_name = state
|
||||
.peer()?
|
||||
.info()
|
||||
.await
|
||||
.map(|i| i.node_name)
|
||||
.unwrap_or_else(|_| "peer".into());
|
||||
let job = Job::new(
|
||||
&req.item_id,
|
||||
&req.name,
|
||||
peer_name,
|
||||
&state.cfg.node_name,
|
||||
req.dry_run,
|
||||
);
|
||||
state.save(&job).await?;
|
||||
runner::start(state.clone(), job.clone());
|
||||
Ok(Json(job))
|
||||
}
|
||||
|
||||
async fn peer_jobs(State(state): State<Shared>) -> ApiResult<Vec<Job>> {
|
||||
let mut jobs = state.store.list_jobs(100).await?;
|
||||
for j in &mut jobs {
|
||||
j.export = None;
|
||||
}
|
||||
Ok(Json(jobs))
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use jm_core::PathMap;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Daemon configuration. Loaded from TOML plus `JELLYMOVE_*` environment
|
||||
/// variables (nested keys use `__`, e.g. `JELLYMOVE_PEER__TOKEN`).
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct Config {
|
||||
/// Name shown in the UI and in job history, e.g. "cloud" or "home".
|
||||
pub node_name: String,
|
||||
#[serde(default = "default_listen")]
|
||||
pub listen: SocketAddr,
|
||||
/// Where the SQLite database lives.
|
||||
#[serde(default = "default_data_dir")]
|
||||
pub data_dir: PathBuf,
|
||||
pub jellyfin: JellyfinConfig,
|
||||
/// Jellyfin path → local path translations. Leave empty when this agent
|
||||
/// mounts media at the same paths as Jellyfin (recommended).
|
||||
#[serde(default)]
|
||||
pub path_map: PathMap,
|
||||
pub peer: Option<PeerConfig>,
|
||||
/// When an item arrives from the peer's library "X", put it in local
|
||||
/// library `incoming_libraries["X"]`. Unlisted libraries map to a local
|
||||
/// library with the same name.
|
||||
#[serde(default)]
|
||||
pub incoming_libraries: HashMap<String, String>,
|
||||
#[serde(default)]
|
||||
pub transfer: TransferConfig,
|
||||
#[serde(default)]
|
||||
pub ui: UiConfig,
|
||||
#[serde(default)]
|
||||
pub hooks: HooksConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct JellyfinConfig {
|
||||
pub url: String,
|
||||
pub api_key: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct PeerConfig {
|
||||
/// Base URL of the other jellymove agent, e.g. `https://cloud.example.com:8097`.
|
||||
pub url: String,
|
||||
/// Shared secret. Both agents must use the same value.
|
||||
pub token: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(default)]
|
||||
pub struct TransferConfig {
|
||||
/// Cap on incoming transfer speed in megabits per second. 0 = unlimited.
|
||||
pub bandwidth_limit_mbps: f64,
|
||||
/// Attempts per file before the job fails (each attempt resumes).
|
||||
pub retries: u32,
|
||||
/// How long to wait for Jellyfin to index a moved item.
|
||||
pub scan_timeout_secs: u64,
|
||||
pub max_concurrent_jobs: usize,
|
||||
}
|
||||
|
||||
impl Default for TransferConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
bandwidth_limit_mbps: 0.0,
|
||||
retries: 20,
|
||||
scan_timeout_secs: 1200,
|
||||
max_concurrent_jobs: 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||
pub struct UiConfig {
|
||||
/// Protect the web UI with HTTP Basic auth. Strongly recommended if the
|
||||
/// port is reachable from anywhere but localhost.
|
||||
pub username: Option<String>,
|
||||
pub password: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||
pub struct HooksConfig {
|
||||
/// Shell command run on the destination after a move finishes, e.g.
|
||||
/// `docker restart jellyswarrm` to clear Jellyswarrm's merge cache.
|
||||
/// Gets JELLYMOVE_ITEM_NAME and JELLYMOVE_TARGET_FOLDER in its environment.
|
||||
pub post_move: Option<String>,
|
||||
}
|
||||
|
||||
fn default_listen() -> SocketAddr {
|
||||
"0.0.0.0:8097".parse().expect("valid")
|
||||
}
|
||||
|
||||
fn default_data_dir() -> PathBuf {
|
||||
PathBuf::from("./data")
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn bytes_per_sec(&self) -> Option<std::num::NonZeroU32> {
|
||||
let bps = self.transfer.bandwidth_limit_mbps * 1_000_000.0 / 8.0;
|
||||
if bps >= 1.0 {
|
||||
std::num::NonZeroU32::new(bps.min(u32::MAX as f64) as u32)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Redacted copy safe to show in the UI.
|
||||
pub fn redacted(&self) -> Config {
|
||||
let mut c = self.clone();
|
||||
c.jellyfin.api_key = "••••".into();
|
||||
if let Some(p) = c.peer.as_mut() {
|
||||
p.token = "••••".into();
|
||||
}
|
||||
if c.ui.password.is_some() {
|
||||
c.ui.password = Some("••••".into());
|
||||
}
|
||||
c
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
//! 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;
|
||||
use jm_core::paths::{join_relative, relative_inside};
|
||||
use jm_core::safety::{check_inside_library, check_movie_folder};
|
||||
use jm_core::userdata::{ItemKey, UserDataRecord};
|
||||
use jm_jellyfin::ItemQuery;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::state::{AppState, Shared};
|
||||
|
||||
#[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<ExportInfo>,
|
||||
/// 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,
|
||||
}
|
||||
|
||||
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<PathBuf> {
|
||||
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<Export> {
|
||||
// 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::<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(),
|
||||
};
|
||||
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<Option<Export>> {
|
||||
let export: Option<Export> = 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,
|
||||
other => bail!("can only move movies and series, not {other}"),
|
||||
};
|
||||
let item_path = PathBuf::from(
|
||||
item.path
|
||||
.clone()
|
||||
.context("Jellyfin did not report a path for this item")?,
|
||||
);
|
||||
let folder = match kind {
|
||||
ItemKind::Movie => item_path
|
||||
.parent()
|
||||
.context("movie path has no parent folder")?
|
||||
.to_path_buf(),
|
||||
ItemKind::Series => item_path.clone(),
|
||||
};
|
||||
|
||||
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<String> = 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<String> = 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 = jm_transfer::build_manifest(&local_folder)
|
||||
.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? {
|
||||
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 {
|
||||
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 info = ExportInfo {
|
||||
item_id: item_id.to_string(),
|
||||
name: item.name,
|
||||
kind,
|
||||
library_name: library.name.clone(),
|
||||
rel_folder,
|
||||
manifest,
|
||||
user_data,
|
||||
episode_keys,
|
||||
};
|
||||
Ok((info, folder.display().to_string(), location))
|
||||
}
|
||||
|
||||
fn push_record(
|
||||
out: &mut Vec<UserDataRecord>,
|
||||
user: &str,
|
||||
key: ItemKey,
|
||||
data: jm_core::userdata::UserData,
|
||||
) {
|
||||
if !data.is_empty() {
|
||||
out.push(UserDataRecord {
|
||||
user_name: user.to_string(),
|
||||
key,
|
||||
data,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// 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) -> anyhow::Result<Export> {
|
||||
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.as_ref().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(".jellymove-trash");
|
||||
let trash = join_relative(&trash_root.join(&export.id), &info.rel_folder)
|
||||
.context("unsafe folder name")?;
|
||||
|
||||
if tokio::fs::metadata(&local_folder).await.is_ok() {
|
||||
if let Some(parent) = trash.parent() {
|
||||
tokio::fs::create_dir_all(parent).await?;
|
||||
}
|
||||
let marker = trash_root.join(".ignore");
|
||||
if tokio::fs::metadata(&marker).await.is_err() {
|
||||
tokio::fs::write(&marker, b"").await?;
|
||||
}
|
||||
tokio::fs::rename(&local_folder, &trash)
|
||||
.await
|
||||
.with_context(|| format!("moving {} to the trash", local_folder.display()))?;
|
||||
tracing::info!(from = %local_folder.display(), to = %trash.display(), "source moved to trash");
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//! The jellymove daemon: HTTP API, embedded UI, job runner and source exports.
|
||||
|
||||
pub mod api;
|
||||
pub mod config;
|
||||
pub mod export;
|
||||
pub mod library;
|
||||
pub mod peer;
|
||||
pub mod runner;
|
||||
pub mod state;
|
||||
pub mod ui;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use config::Config;
|
||||
use tower_http::trace::TraceLayer;
|
||||
|
||||
/// Open state, resume interrupted jobs and serve until shutdown.
|
||||
pub async fn run(cfg: Config) -> anyhow::Result<()> {
|
||||
std::fs::create_dir_all(&cfg.data_dir)?;
|
||||
let store = jm_store::Store::open(&cfg.data_dir.join("jellymove.db"))?;
|
||||
let listen = cfg.listen;
|
||||
let state = Arc::new(state::AppState::new(cfg, store)?);
|
||||
|
||||
match state.jellyfin.system_info().await {
|
||||
Ok(i) => {
|
||||
tracing::info!(server = %i.server_name, version = %i.version, "connected to Jellyfin")
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "can't reach Jellyfin yet; will keep trying on demand")
|
||||
}
|
||||
}
|
||||
runner::resume_all(&state).await?;
|
||||
|
||||
let app = api::router(state.clone()).layer(TraceLayer::new_for_http());
|
||||
let listener = tokio::net::TcpListener::bind(listen).await?;
|
||||
tracing::info!(%listen, node = %state.cfg.node_name, "jellymove listening");
|
||||
axum::serve(listener, app)
|
||||
.with_graceful_shutdown(shutdown_signal())
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn shutdown_signal() {
|
||||
let ctrl_c = async {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
};
|
||||
#[cfg(unix)]
|
||||
let term = async {
|
||||
if let Ok(mut s) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
|
||||
{
|
||||
s.recv().await;
|
||||
}
|
||||
};
|
||||
#[cfg(not(unix))]
|
||||
let term = std::future::pending::<()>();
|
||||
tokio::select! { _ = ctrl_c => {}, _ = term => {} }
|
||||
tracing::info!("shutting down; in-flight transfers will resume on next start");
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Browsing the local Jellyfin libraries.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use jm_jellyfin::ItemQuery;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::state::AppState;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Library {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub collection_type: Option<String>,
|
||||
pub locations: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct LibraryItem {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// "Movie" or "Series".
|
||||
pub kind: String,
|
||||
pub year: Option<i32>,
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct LocationCheck {
|
||||
pub library: String,
|
||||
pub jellyfin_path: String,
|
||||
pub local_path: String,
|
||||
pub exists: bool,
|
||||
pub writable: bool,
|
||||
}
|
||||
|
||||
/// Only libraries jellymove knows how to move items out of.
|
||||
fn supported(collection_type: Option<&str>) -> bool {
|
||||
matches!(collection_type, Some("movies") | Some("tvshows") | None)
|
||||
}
|
||||
|
||||
pub async fn libraries(state: &AppState) -> anyhow::Result<Vec<Library>> {
|
||||
Ok(state
|
||||
.jellyfin
|
||||
.virtual_folders()
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter(|v| supported(v.collection_type.as_deref()))
|
||||
.map(|v| Library {
|
||||
id: v.item_id,
|
||||
name: v.name,
|
||||
collection_type: v.collection_type,
|
||||
locations: v.locations,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub async fn items(
|
||||
state: &AppState,
|
||||
library_id: &str,
|
||||
search: Option<&str>,
|
||||
) -> anyhow::Result<Vec<LibraryItem>> {
|
||||
let search = search.map(str::trim).filter(|s| !s.is_empty());
|
||||
let items = state
|
||||
.jellyfin
|
||||
.items(&ItemQuery {
|
||||
parent_id: Some(library_id),
|
||||
include_types: &["Movie", "Series"],
|
||||
recursive: true,
|
||||
search,
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
Ok(items
|
||||
.into_iter()
|
||||
.map(|i| LibraryItem {
|
||||
id: i.id,
|
||||
name: i.name,
|
||||
kind: i.kind,
|
||||
year: i.production_year,
|
||||
path: i.path,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Confirm every library location exists and is writable from this agent.
|
||||
/// The most common setup mistakes (wrong mount, wrong PUID/PGID, missing
|
||||
/// path_map) all show up here.
|
||||
pub async fn check_locations(state: &AppState) -> anyhow::Result<Vec<LocationCheck>> {
|
||||
let mut out = Vec::new();
|
||||
for lib in libraries(state).await? {
|
||||
for loc in &lib.locations {
|
||||
let local = state.cfg.path_map.to_local(Path::new(loc));
|
||||
let exists = tokio::fs::metadata(&local)
|
||||
.await
|
||||
.map(|m| m.is_dir())
|
||||
.unwrap_or(false);
|
||||
let writable = exists && {
|
||||
let probe = local.join(format!(".jellymove-probe-{}", uuid::Uuid::new_v4()));
|
||||
let ok = tokio::fs::write(&probe, b"").await.is_ok();
|
||||
let _ = tokio::fs::remove_file(&probe).await;
|
||||
ok
|
||||
};
|
||||
out.push(LocationCheck {
|
||||
library: lib.name.clone(),
|
||||
jellyfin_path: loc.clone(),
|
||||
local_path: local.display().to_string(),
|
||||
exists,
|
||||
writable,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
//! Client for the other agent's `/peer/v1` API.
|
||||
|
||||
use jm_core::Job;
|
||||
use reqwest::header::AUTHORIZATION;
|
||||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||
|
||||
use crate::export::Export;
|
||||
use crate::library::{Library, LibraryItem};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PeerClient {
|
||||
http: reqwest::Client,
|
||||
base: String,
|
||||
token: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct NodeInfo {
|
||||
pub node_name: String,
|
||||
pub version: String,
|
||||
pub jellyfin_server: Option<String>,
|
||||
pub jellyfin_version: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct CreateJob {
|
||||
pub item_id: String,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub dry_run: bool,
|
||||
}
|
||||
|
||||
impl PeerClient {
|
||||
pub fn new(http: reqwest::Client, base: &str, token: &str) -> Self {
|
||||
Self {
|
||||
http,
|
||||
base: base.trim_end_matches('/').to_string(),
|
||||
token: token.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn url(&self, path: &str) -> String {
|
||||
format!("{}/peer/v1{path}", self.base)
|
||||
}
|
||||
|
||||
async fn send<T: DeserializeOwned>(
|
||||
&self,
|
||||
req: reqwest::RequestBuilder,
|
||||
what: &str,
|
||||
) -> anyhow::Result<T> {
|
||||
let resp = req
|
||||
.header(AUTHORIZATION, format!("Bearer {}", self.token))
|
||||
.timeout(std::time::Duration::from_secs(60))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("could not reach peer ({what}): {e}"))?;
|
||||
let status = resp.status();
|
||||
if !status.is_success() {
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
anyhow::bail!("peer refused {what}: HTTP {status}: {body}");
|
||||
}
|
||||
Ok(resp.json().await?)
|
||||
}
|
||||
|
||||
pub async fn info(&self) -> anyhow::Result<NodeInfo> {
|
||||
self.send(self.http.get(self.url("/info")), "info").await
|
||||
}
|
||||
|
||||
pub async fn libraries(&self) -> anyhow::Result<Vec<Library>> {
|
||||
self.send(self.http.get(self.url("/libraries")), "list libraries")
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn items(
|
||||
&self,
|
||||
library: &str,
|
||||
search: Option<&str>,
|
||||
) -> anyhow::Result<Vec<LibraryItem>> {
|
||||
let mut q = vec![("library", library)];
|
||||
if let Some(s) = search {
|
||||
q.push(("search", s));
|
||||
}
|
||||
self.send(self.http.get(self.url("/items")).query(&q), "list items")
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn create_export(&self, item_id: &str) -> anyhow::Result<Export> {
|
||||
self.send(
|
||||
self.http
|
||||
.post(self.url("/exports"))
|
||||
.json(&serde_json::json!({ "item_id": item_id })),
|
||||
"create export",
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn export(&self, id: &str) -> anyhow::Result<Export> {
|
||||
self.send(
|
||||
self.http.get(self.url(&format!("/exports/{id}"))),
|
||||
"get export",
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub fn file_url(&self, export_id: &str, idx: usize) -> String {
|
||||
self.url(&format!("/exports/{export_id}/files/{idx}"))
|
||||
}
|
||||
|
||||
pub async fn complete_export(&self, id: &str) -> anyhow::Result<Export> {
|
||||
self.send(
|
||||
self.http.post(self.url(&format!("/exports/{id}/complete"))),
|
||||
"clean up source",
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn create_job(&self, req: &CreateJob) -> anyhow::Result<Job> {
|
||||
self.send(self.http.post(self.url("/jobs")).json(req), "start job")
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn jobs(&self) -> anyhow::Result<Vec<Job>> {
|
||||
self.send(self.http.get(self.url("/jobs")), "list jobs")
|
||||
.await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
//! Destination side of a move: drives a job through its stages.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use jm_core::job::ExportInfo;
|
||||
use jm_core::paths::join_relative;
|
||||
use jm_core::userdata::{ItemKey, same_user};
|
||||
use jm_core::{ItemKind, Job, JobStatus, Stage};
|
||||
use jm_jellyfin::ItemQuery;
|
||||
|
||||
use crate::export::ExportStatus;
|
||||
use crate::state::Shared;
|
||||
|
||||
enum Flow {
|
||||
Continue,
|
||||
Stop,
|
||||
}
|
||||
|
||||
/// Re-queue jobs that were active when the daemon last stopped.
|
||||
pub async fn resume_all(state: &Shared) -> anyhow::Result<()> {
|
||||
for job in state.store.active_jobs().await? {
|
||||
tracing::info!(job = %job.id, name = %job.name, stage = ?job.stage, "resuming job");
|
||||
start(state.clone(), job);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run a job in the background. A job that is already running is ignored.
|
||||
pub fn start(state: Shared, mut job: Job) {
|
||||
if !state.running.lock().expect("lock").insert(job.id) {
|
||||
return;
|
||||
}
|
||||
tokio::spawn(async move {
|
||||
job.status = JobStatus::Queued;
|
||||
let _ = state.save(&job).await;
|
||||
let _permit = state
|
||||
.job_slots
|
||||
.clone()
|
||||
.acquire_owned()
|
||||
.await
|
||||
.expect("semaphore closed");
|
||||
job.status = JobStatus::Running;
|
||||
job.note(format!("started at stage {:?}", job.stage));
|
||||
let _ = state.save(&job).await;
|
||||
|
||||
loop {
|
||||
if job.stage == Stage::Done {
|
||||
job.status = JobStatus::Done;
|
||||
job.note("move complete");
|
||||
break;
|
||||
}
|
||||
match step(&state, &mut job).await {
|
||||
Ok(Flow::Continue) => {
|
||||
let _ = state.save(&job).await;
|
||||
}
|
||||
Ok(Flow::Stop) => break,
|
||||
Err(e) => {
|
||||
let msg = format!("{e:#}");
|
||||
tracing::warn!(job = %job.id, stage = ?job.stage, error = %msg, "job failed");
|
||||
job.note(format!("failed: {msg}"));
|
||||
job.status = JobStatus::Failed(msg);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Err(e) = state.save(&job).await {
|
||||
tracing::error!(job = %job.id, error = %e, "could not save job");
|
||||
}
|
||||
state.running.lock().expect("lock").remove(&job.id);
|
||||
});
|
||||
}
|
||||
|
||||
async fn step(state: &Shared, job: &mut Job) -> anyhow::Result<Flow> {
|
||||
match job.stage {
|
||||
Stage::Created => plan(state, job).await,
|
||||
Stage::ExportReady => copy(state, job).await.map(|_| Flow::Continue),
|
||||
Stage::Copied => promote(state, job).await.map(|_| Flow::Continue),
|
||||
Stage::Promoted => wait_for_scan(state, job).await.map(|_| Flow::Continue),
|
||||
Stage::TargetScanned => apply_user_data(state, job).await.map(|_| Flow::Continue),
|
||||
Stage::UserDataApplied => clean_source(state, job).await.map(|_| Flow::Continue),
|
||||
Stage::SourceCleaned => finish(state, job).await.map(|_| Flow::Continue),
|
||||
Stage::Done => Ok(Flow::Stop),
|
||||
}
|
||||
}
|
||||
|
||||
fn info(job: &Job) -> anyhow::Result<&ExportInfo> {
|
||||
job.export.as_ref().context("job has no export info")
|
||||
}
|
||||
|
||||
fn target_jellyfin(job: &Job) -> anyhow::Result<PathBuf> {
|
||||
Ok(PathBuf::from(
|
||||
job.target_folder_jellyfin
|
||||
.as_deref()
|
||||
.context("job has no target folder")?,
|
||||
))
|
||||
}
|
||||
|
||||
/// Destination library location (local path) that holds the target folder.
|
||||
fn target_library_root(state: &Shared, job: &Job) -> anyhow::Result<PathBuf> {
|
||||
let info = info(job)?;
|
||||
let target = target_jellyfin(job)?;
|
||||
let depth = info.rel_folder.split('/').count();
|
||||
let mut root = target.as_path();
|
||||
for _ in 0..depth {
|
||||
root = root
|
||||
.parent()
|
||||
.context("target folder is shallower than expected")?;
|
||||
}
|
||||
Ok(state.cfg.path_map.to_local(root))
|
||||
}
|
||||
|
||||
async fn plan(state: &Shared, job: &mut Job) -> anyhow::Result<Flow> {
|
||||
let peer = state.peer()?;
|
||||
if job.export_id.is_none() {
|
||||
let export = peer.create_export(&job.source_item_id).await?;
|
||||
job.note("source is checking and hashing the item");
|
||||
job.export_id = Some(export.id);
|
||||
state.save(job).await?;
|
||||
}
|
||||
let export_id = job.export_id.clone().expect("set above");
|
||||
|
||||
// Hashing a 50 GB remux takes a while on slow disks; just keep polling.
|
||||
let export = loop {
|
||||
let e = peer.export(&export_id).await?;
|
||||
match &e.status {
|
||||
ExportStatus::Ready => break e,
|
||||
ExportStatus::Preparing => tokio::time::sleep(Duration::from_secs(2)).await,
|
||||
ExportStatus::Failed(why) => bail!("source refused: {why}"),
|
||||
ExportStatus::Completed => bail!("source already completed this export"),
|
||||
}
|
||||
};
|
||||
let info = export.info.context("source sent no item info")?;
|
||||
|
||||
// Choose the destination library.
|
||||
let wanted = state
|
||||
.cfg
|
||||
.incoming_libraries
|
||||
.get(&info.library_name)
|
||||
.unwrap_or(&info.library_name)
|
||||
.clone();
|
||||
let libraries = state.jellyfin.virtual_folders().await?;
|
||||
let lib = libraries
|
||||
.iter()
|
||||
.find(|l| l.name == wanted)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"this server has no library called \"{wanted}\". Create it, or map it with \
|
||||
incoming_libraries.\"{}\" = \"<local library>\"",
|
||||
info.library_name
|
||||
)
|
||||
})?;
|
||||
let expected = match info.kind {
|
||||
ItemKind::Movie => "movies",
|
||||
ItemKind::Series => "tvshows",
|
||||
};
|
||||
if let Some(ct) = &lib.collection_type {
|
||||
if ct != expected {
|
||||
bail!(
|
||||
"library \"{}\" holds {ct}, but {} is a {:?}",
|
||||
lib.name,
|
||||
info.name,
|
||||
info.kind
|
||||
);
|
||||
}
|
||||
}
|
||||
let 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()
|
||||
);
|
||||
}
|
||||
|
||||
job.name = info.name.clone();
|
||||
job.progress.bytes_total = info.manifest.total_bytes();
|
||||
job.target_library = Some(lib.name.clone());
|
||||
job.target_folder_jellyfin = Some(target.display().to_string());
|
||||
job.note(format!(
|
||||
"plan: {} files, {} into \"{}\" at {}",
|
||||
info.manifest.files.len(),
|
||||
human_bytes(job.progress.bytes_total),
|
||||
lib.name,
|
||||
target.display()
|
||||
));
|
||||
job.export = Some(info);
|
||||
|
||||
if job.dry_run {
|
||||
job.status = JobStatus::Planned;
|
||||
job.note("dry run: stopping before anything is copied");
|
||||
return Ok(Flow::Stop);
|
||||
}
|
||||
job.advance(Stage::ExportReady);
|
||||
Ok(Flow::Continue)
|
||||
}
|
||||
|
||||
async fn copy(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
|
||||
let peer = state.peer()?;
|
||||
let export_id = job.export_id.clone().context("no export")?;
|
||||
let files = info(job)?.manifest.files.clone();
|
||||
let partial = jm_transfer::partial_dir(&target_library_root(state, job)?, &job.id.to_string());
|
||||
jm_transfer::prepare_partial(&partial).await?;
|
||||
|
||||
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() {
|
||||
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);
|
||||
let base = done_before;
|
||||
let snapshot_state = state.clone();
|
||||
let mut snapshot = job.clone();
|
||||
let mut on_progress = |have: u64| {
|
||||
if last_emit.elapsed() >= Duration::from_millis(500) {
|
||||
snapshot.progress.bytes_done = base + have;
|
||||
let _ = snapshot_state.events.send(snapshot.clone());
|
||||
last_emit = Instant::now();
|
||||
}
|
||||
if last_save.elapsed() >= Duration::from_secs(2) {
|
||||
snapshot.progress.bytes_done = base + have;
|
||||
let (st, snap) = (snapshot_state.clone(), snapshot.clone());
|
||||
tokio::spawn(async move {
|
||||
let _ = st.store.put_job(&snap).await;
|
||||
});
|
||||
last_save = Instant::now();
|
||||
}
|
||||
};
|
||||
state
|
||||
.puller
|
||||
.pull_verified(&url, entry, &part, &mut on_progress)
|
||||
.await
|
||||
.with_context(|| format!("copying {}", entry.rel_path))?;
|
||||
done_before += entry.size;
|
||||
job.progress.bytes_done = done_before;
|
||||
if last_save.elapsed() >= Duration::from_secs(2) {
|
||||
state.save(job).await?;
|
||||
last_save = Instant::now();
|
||||
}
|
||||
}
|
||||
job.progress.current_file = None;
|
||||
job.note(format!("copied and verified {} files", files.len()));
|
||||
job.advance(Stage::Copied);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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()));
|
||||
job.advance(Stage::Promoted);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn wait_for_scan(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
|
||||
let target = target_jellyfin(job)?;
|
||||
let target_str = target.display().to_string();
|
||||
state
|
||||
.jellyfin
|
||||
.media_updated(std::slice::from_ref(&target_str))
|
||||
.await?;
|
||||
job.note(
|
||||
"asked Jellyfin to scan the new folder (it waits LibraryMonitorDelay, 60 s by default)",
|
||||
);
|
||||
state.save(job).await?;
|
||||
|
||||
let info = info(job)?.clone();
|
||||
let deadline = Instant::now() + Duration::from_secs(state.cfg.transfer.scan_timeout_secs);
|
||||
let mut nudged = false;
|
||||
loop {
|
||||
if let Some(id) = find_new_item(state, job, &info, &target).await? {
|
||||
let missing = missing_episodes(state, &id, &info).await?;
|
||||
if missing == 0 {
|
||||
job.target_item_id = Some(id);
|
||||
job.note("Jellyfin has indexed the item");
|
||||
job.advance(Stage::TargetScanned);
|
||||
return Ok(());
|
||||
}
|
||||
tracing::debug!(job = %job.id, missing, "waiting for episodes to appear");
|
||||
}
|
||||
if Instant::now() > deadline {
|
||||
bail!(
|
||||
"Jellyfin hadn't indexed everything after {} s. Check the library on this server, \
|
||||
then retry: the copied files are in place and nothing has been deleted from the source",
|
||||
state.cfg.transfer.scan_timeout_secs
|
||||
);
|
||||
}
|
||||
// Halfway through, nudge again in case the first update was dropped.
|
||||
if !nudged
|
||||
&& deadline.saturating_duration_since(Instant::now()).as_secs()
|
||||
< state.cfg.transfer.scan_timeout_secs / 2
|
||||
{
|
||||
let _ = state
|
||||
.jellyfin
|
||||
.media_updated(std::slice::from_ref(&target_str))
|
||||
.await;
|
||||
nudged = true;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Find the item Jellyfin created for the moved folder, by path.
|
||||
async fn find_new_item(
|
||||
state: &Shared,
|
||||
job: &Job,
|
||||
info: &ExportInfo,
|
||||
target: &Path,
|
||||
) -> anyhow::Result<Option<String>> {
|
||||
let lib_name = job.target_library.as_deref().context("no target library")?;
|
||||
let libs = state.jellyfin.virtual_folders().await?;
|
||||
let lib = libs
|
||||
.iter()
|
||||
.find(|l| l.name == lib_name)
|
||||
.context("target library disappeared")?;
|
||||
let kind = match info.kind {
|
||||
ItemKind::Movie => "Movie",
|
||||
ItemKind::Series => "Series",
|
||||
};
|
||||
let matches = |p: &str| match info.kind {
|
||||
ItemKind::Movie => Path::new(p).parent() == Some(target),
|
||||
ItemKind::Series => 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 items = state
|
||||
.jellyfin
|
||||
.items(&ItemQuery {
|
||||
parent_id: Some(&lib.item_id),
|
||||
include_types: &[kind],
|
||||
recursive: true,
|
||||
search,
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
if let Some(found) = items
|
||||
.into_iter()
|
||||
.find(|i| i.path.as_deref().is_some_and(matches))
|
||||
{
|
||||
return Ok(Some(found.id));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
async fn episode_ids(state: &Shared, series_id: &str) -> anyhow::Result<HashMap<ItemKey, String>> {
|
||||
let eps = state
|
||||
.jellyfin
|
||||
.items(&ItemQuery {
|
||||
parent_id: Some(series_id),
|
||||
include_types: &["Episode"],
|
||||
recursive: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
Ok(eps
|
||||
.into_iter()
|
||||
.filter_map(|e| {
|
||||
Some((
|
||||
ItemKey::Episode {
|
||||
season: e.parent_index_number?,
|
||||
episode: e.index_number?,
|
||||
},
|
||||
e.id,
|
||||
))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn missing_episodes(
|
||||
state: &Shared,
|
||||
series_id: &str,
|
||||
info: &ExportInfo,
|
||||
) -> anyhow::Result<usize> {
|
||||
if info.kind != ItemKind::Series || info.episode_keys.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
let found = episode_ids(state, series_id).await?;
|
||||
Ok(info
|
||||
.episode_keys
|
||||
.iter()
|
||||
.filter(|k| !found.contains_key(k))
|
||||
.count())
|
||||
}
|
||||
|
||||
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 {
|
||||
episode_ids(state, &root_id).await?
|
||||
} else {
|
||||
HashMap::new()
|
||||
};
|
||||
let users = state.jellyfin.users().await?;
|
||||
|
||||
let (mut applied, mut no_user, mut no_item) = (0, 0, 0);
|
||||
let mut unknown_users: Vec<String> = Vec::new();
|
||||
for rec in &info.user_data {
|
||||
let Some(user) = users.iter().find(|u| same_user(&u.name, &rec.user_name)) else {
|
||||
no_user += 1;
|
||||
if !unknown_users.contains(&rec.user_name) {
|
||||
unknown_users.push(rec.user_name.clone());
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let item_id = match rec.key {
|
||||
ItemKey::Root => Some(&root_id),
|
||||
key => episodes.get(&key),
|
||||
};
|
||||
let Some(item_id) = item_id else {
|
||||
no_item += 1;
|
||||
continue;
|
||||
};
|
||||
state
|
||||
.jellyfin
|
||||
.set_user_data(&user.id, item_id, &rec.data)
|
||||
.await?;
|
||||
applied += 1;
|
||||
}
|
||||
job.note(format!("restored {applied} watch-state records"));
|
||||
if no_user > 0 {
|
||||
job.note(format!(
|
||||
"skipped {no_user} records for users missing on this server: {}",
|
||||
unknown_users.join(", ")
|
||||
));
|
||||
}
|
||||
if no_item > 0 {
|
||||
job.note(format!(
|
||||
"skipped {no_item} records whose episode wasn't found"
|
||||
));
|
||||
}
|
||||
job.advance(Stage::UserDataApplied);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn clean_source(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
|
||||
let export_id = job.export_id.clone().context("no export")?;
|
||||
state.peer()?.complete_export(&export_id).await?;
|
||||
job.note("source folder moved to its trash and source library rescanned");
|
||||
job.advance(Stage::SourceCleaned);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn finish(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
|
||||
if let Some(cmd) = state
|
||||
.cfg
|
||||
.hooks
|
||||
.post_move
|
||||
.as_deref()
|
||||
.filter(|c| !c.trim().is_empty())
|
||||
{
|
||||
let mut command = if cfg!(windows) {
|
||||
let mut c = tokio::process::Command::new("cmd");
|
||||
c.arg("/C").arg(cmd);
|
||||
c
|
||||
} else {
|
||||
let mut c = tokio::process::Command::new("sh");
|
||||
c.arg("-c").arg(cmd);
|
||||
c
|
||||
};
|
||||
command.env("JELLYMOVE_ITEM_NAME", &job.name).env(
|
||||
"JELLYMOVE_TARGET_FOLDER",
|
||||
job.target_folder_jellyfin.as_deref().unwrap_or_default(),
|
||||
);
|
||||
// A failing hook is reported but doesn't undo a finished move.
|
||||
match tokio::time::timeout(Duration::from_secs(300), command.output()).await {
|
||||
Ok(Ok(out)) if out.status.success() => job.note("post-move hook ran"),
|
||||
Ok(Ok(out)) => job.note(format!(
|
||||
"post-move hook exited with {}: {}",
|
||||
out.status,
|
||||
String::from_utf8_lossy(&out.stderr).trim()
|
||||
)),
|
||||
Ok(Err(e)) => job.note(format!("post-move hook could not start: {e}")),
|
||||
Err(_) => job.note("post-move hook timed out after 5 minutes"),
|
||||
}
|
||||
}
|
||||
job.advance(Stage::Done);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn human_bytes(b: u64) -> String {
|
||||
const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
|
||||
let mut v = b as f64;
|
||||
let mut u = 0;
|
||||
while v >= 1000.0 && u < UNITS.len() - 1 {
|
||||
v /= 1000.0;
|
||||
u += 1;
|
||||
}
|
||||
if u == 0 {
|
||||
format!("{b} B")
|
||||
} else {
|
||||
format!("{v:.1} {}", UNITS[u])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
use std::collections::HashSet;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use jm_core::{Job, JobId};
|
||||
use jm_store::Store;
|
||||
use jm_transfer::{Puller, PullerOptions};
|
||||
use tokio::sync::{Semaphore, broadcast};
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::peer::PeerClient;
|
||||
|
||||
pub struct AppState {
|
||||
pub cfg: Config,
|
||||
pub store: Store,
|
||||
pub jellyfin: jm_jellyfin::Client,
|
||||
pub peer: Option<PeerClient>,
|
||||
pub puller: Puller,
|
||||
/// Job snapshots for the UI's live view.
|
||||
pub events: broadcast::Sender<Job>,
|
||||
pub job_slots: Arc<Semaphore>,
|
||||
pub running: Mutex<HashSet<JobId>>,
|
||||
/// Exports currently being hashed, so a duplicate request doesn't start a second pass.
|
||||
pub preparing: Mutex<HashSet<String>>,
|
||||
}
|
||||
|
||||
pub type Shared = Arc<AppState>;
|
||||
|
||||
impl AppState {
|
||||
pub fn new(cfg: Config, store: Store) -> anyhow::Result<Self> {
|
||||
let jellyfin = jm_jellyfin::Client::new(&cfg.jellyfin.url, &cfg.jellyfin.api_key)?;
|
||||
// Transfers can run for hours; only bound the connect phase.
|
||||
let http = reqwest::Client::builder()
|
||||
.connect_timeout(std::time::Duration::from_secs(20))
|
||||
.read_timeout(std::time::Duration::from_secs(120))
|
||||
.build()?;
|
||||
let peer = cfg
|
||||
.peer
|
||||
.as_ref()
|
||||
.map(|p| PeerClient::new(http.clone(), &p.url, &p.token));
|
||||
let puller = Puller::new(
|
||||
http,
|
||||
PullerOptions {
|
||||
token: cfg.peer.as_ref().map(|p| p.token.clone()),
|
||||
bytes_per_sec: cfg.bytes_per_sec(),
|
||||
attempts: cfg.transfer.retries.max(1),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let (events, _) = broadcast::channel(256);
|
||||
let slots = cfg.transfer.max_concurrent_jobs.max(1);
|
||||
Ok(Self {
|
||||
cfg,
|
||||
store,
|
||||
jellyfin,
|
||||
peer,
|
||||
puller,
|
||||
events,
|
||||
job_slots: Arc::new(Semaphore::new(slots)),
|
||||
running: Mutex::new(HashSet::new()),
|
||||
preparing: Mutex::new(HashSet::new()),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn peer(&self) -> anyhow::Result<&PeerClient> {
|
||||
self.peer
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("no peer is configured on this node"))
|
||||
}
|
||||
|
||||
/// Save a job and tell anyone watching.
|
||||
pub async fn save(&self, job: &Job) -> anyhow::Result<()> {
|
||||
self.store.put_job(job).await?;
|
||||
let _ = self.events.send(job.clone());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//! The web UI, compiled into the binary. Build it with `npm --prefix ui run build`
|
||||
//! before `cargo build --release`; in debug builds files are read from disk.
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{StatusCode, Uri, header};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use rust_embed::RustEmbed;
|
||||
|
||||
#[derive(RustEmbed)]
|
||||
#[folder = "../../ui/dist"]
|
||||
#[allow_missing = true]
|
||||
struct Assets;
|
||||
|
||||
pub async fn serve(uri: Uri) -> Response {
|
||||
let path = uri.path().trim_start_matches('/');
|
||||
if path.starts_with("api/") || path.starts_with("peer/") {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
}
|
||||
if let Some(r) = asset(if path.is_empty() { "index.html" } else { path }) {
|
||||
return r;
|
||||
}
|
||||
// Single-page app: unknown paths get the shell.
|
||||
asset("index.html").unwrap_or_else(|| {
|
||||
(
|
||||
StatusCode::OK,
|
||||
[(header::CONTENT_TYPE, "text/html; charset=utf-8")],
|
||||
"<h1>jellymove</h1><p>The web UI wasn't built into this binary. \
|
||||
Run <code>npm --prefix ui ci && npm --prefix ui run build</code>, then rebuild.</p>",
|
||||
)
|
||||
.into_response()
|
||||
})
|
||||
}
|
||||
|
||||
fn asset(path: &str) -> Option<Response> {
|
||||
let file = Assets::get(path)?;
|
||||
let mime = mime_guess::from_path(path).first_or_octet_stream();
|
||||
// Vite fingerprints everything under assets/, so it can be cached forever.
|
||||
let cache = if path.starts_with("assets/") {
|
||||
"public, max-age=31536000, immutable"
|
||||
} else {
|
||||
"no-cache"
|
||||
};
|
||||
Some(
|
||||
Response::builder()
|
||||
.header(header::CONTENT_TYPE, mime.as_ref())
|
||||
.header(header::CACHE_CONTROL, cache)
|
||||
.body(Body::from(file.data.into_owned()))
|
||||
.expect("valid response"),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
//! Two real jellymove agents, each with its own fake Jellyfin and media
|
||||
//! folders, moving items between them through the same HTTP APIs the UI uses.
|
||||
|
||||
#[allow(dead_code)]
|
||||
mod fake_jellyfin;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use fake_jellyfin::{Fake, Lib};
|
||||
use jm_server::config::{
|
||||
Config, HooksConfig, JellyfinConfig, PeerConfig, TransferConfig, UiConfig,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const TOKEN: &str = "test-token";
|
||||
|
||||
struct Node {
|
||||
_tmp: tempfile::TempDir,
|
||||
root: PathBuf,
|
||||
fake: Fake,
|
||||
url: String,
|
||||
}
|
||||
|
||||
impl Node {
|
||||
fn movies(&self) -> PathBuf {
|
||||
self.root.join("movies")
|
||||
}
|
||||
fn tv(&self) -> PathBuf {
|
||||
self.root.join("tv")
|
||||
}
|
||||
}
|
||||
|
||||
fn libs(root: &Path) -> Vec<Lib> {
|
||||
vec![
|
||||
Lib {
|
||||
name: "Movies".into(),
|
||||
collection_type: "movies",
|
||||
location: root.join("movies"),
|
||||
},
|
||||
Lib {
|
||||
name: "TV Shows".into(),
|
||||
collection_type: "tvshows",
|
||||
location: root.join("tv"),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn write(path: &Path, data: &[u8]) {
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, data).unwrap();
|
||||
}
|
||||
|
||||
/// Start two peered agents. `seed` fills the first node's media folders.
|
||||
async fn pair(seed: impl FnOnce(&Path)) -> (Node, Node) {
|
||||
let tmp_a = tempfile::tempdir().unwrap();
|
||||
let tmp_b = tempfile::tempdir().unwrap();
|
||||
for t in [&tmp_a, &tmp_b] {
|
||||
std::fs::create_dir_all(t.path().join("movies")).unwrap();
|
||||
std::fs::create_dir_all(t.path().join("tv")).unwrap();
|
||||
}
|
||||
seed(tmp_a.path());
|
||||
|
||||
let fake_a = Fake::new(libs(tmp_a.path()));
|
||||
let fake_b = Fake::new(libs(tmp_b.path()));
|
||||
let jf_a = fake_a.clone().serve().await;
|
||||
let jf_b = fake_b.clone().serve().await;
|
||||
|
||||
let la = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let lb = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url_a = format!("http://{}", la.local_addr().unwrap());
|
||||
let url_b = format!("http://{}", lb.local_addr().unwrap());
|
||||
|
||||
for (name, tmp, jf, listener, peer_url) in [
|
||||
("cloud", &tmp_a, jf_a, la, url_b.clone()),
|
||||
("home", &tmp_b, jf_b, lb, url_a.clone()),
|
||||
] {
|
||||
let cfg = Config {
|
||||
node_name: name.into(),
|
||||
listen: listener.local_addr().unwrap(),
|
||||
data_dir: tmp.path().join("state"),
|
||||
jellyfin: JellyfinConfig {
|
||||
url: jf,
|
||||
api_key: "k".into(),
|
||||
},
|
||||
path_map: Default::default(),
|
||||
peer: Some(PeerConfig {
|
||||
url: peer_url,
|
||||
token: TOKEN.into(),
|
||||
}),
|
||||
incoming_libraries: Default::default(),
|
||||
transfer: TransferConfig {
|
||||
scan_timeout_secs: 60,
|
||||
..Default::default()
|
||||
},
|
||||
ui: UiConfig::default(),
|
||||
hooks: HooksConfig::default(),
|
||||
};
|
||||
std::fs::create_dir_all(&cfg.data_dir).unwrap();
|
||||
let store = jm_store::Store::open(&cfg.data_dir.join("db")).unwrap();
|
||||
let state = Arc::new(jm_server::state::AppState::new(cfg, store).unwrap());
|
||||
let app = jm_server::api::router(state);
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
}
|
||||
|
||||
let a = Node {
|
||||
root: tmp_a.path().to_path_buf(),
|
||||
_tmp: tmp_a,
|
||||
fake: fake_a,
|
||||
url: url_a,
|
||||
};
|
||||
let b = Node {
|
||||
root: tmp_b.path().to_path_buf(),
|
||||
_tmp: tmp_b,
|
||||
fake: fake_b,
|
||||
url: url_b,
|
||||
};
|
||||
(a, b)
|
||||
}
|
||||
|
||||
async fn post(base: &str, path: &str, body: Value) -> reqwest::Response {
|
||||
reqwest::Client::new()
|
||||
.post(format!("{base}{path}"))
|
||||
.header("X-Jellymove", "1")
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn get(base: &str, path: &str) -> Value {
|
||||
reqwest::get(format!("{base}{path}"))
|
||||
.await
|
||||
.unwrap()
|
||||
.json()
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Wait for the job to leave the active states; returns its final JSON.
|
||||
async fn wait_job(base: &str, id: &str) -> Value {
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
loop {
|
||||
let jobs = get(base, "/api/jobs").await;
|
||||
let all: Vec<Value> = [
|
||||
jobs["local"].as_array().unwrap().clone(),
|
||||
jobs["peer"].as_array().unwrap().clone(),
|
||||
]
|
||||
.concat();
|
||||
if let Some(j) = all.iter().find(|j| j["id"] == id) {
|
||||
let kind = j["status"]["kind"].as_str().unwrap();
|
||||
if !matches!(kind, "Queued" | "Running") {
|
||||
return j.clone();
|
||||
}
|
||||
}
|
||||
assert!(Instant::now() < deadline, "job {id} didn't finish in time");
|
||||
tokio::time::sleep(Duration::from_millis(250)).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn seed_movie(root: &Path) {
|
||||
let m = root.join("movies/Alien (1979)");
|
||||
write(&m.join("Alien (1979).mkv"), &vec![7u8; 2 * 1024 * 1024]);
|
||||
write(
|
||||
&m.join("Alien (1979).nfo"),
|
||||
b"<movie><title>Alien</title></movie>",
|
||||
);
|
||||
write(
|
||||
&m.join("Alien (1979).en.srt"),
|
||||
b"1\n00:00:01,000 --> 00:00:02,000\nIn space...\n",
|
||||
);
|
||||
write(&m.join("extras/Making of.mkv"), b"extra");
|
||||
}
|
||||
|
||||
fn seed_series(root: &Path) {
|
||||
let s = root.join("tv/Severance");
|
||||
write(&s.join("tvshow.nfo"), b"<tvshow/>");
|
||||
write(&s.join("Season 01/Severance S01E01.mkv"), b"episode one");
|
||||
write(&s.join("Season 01/Severance S01E02.mkv"), b"episode two");
|
||||
write(&s.join("Season 02/Severance S02E01.mkv"), b"episode three");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn moves_a_movie_with_sidecars_and_watch_state() {
|
||||
let (cloud, home) = pair(seed_movie).await;
|
||||
let movie = cloud.fake.find("Movie", "Alien").unwrap();
|
||||
cloud.fake.set_user_data(
|
||||
&movie,
|
||||
json!({"Played": true, "PlayCount": 2, "IsFavorite": true}),
|
||||
);
|
||||
|
||||
// Started from the cloud UI: "move this local item to the peer".
|
||||
let resp = post(
|
||||
&cloud.url,
|
||||
"/api/moves",
|
||||
json!({"from": "local", "item_id": movie, "name": "Alien"}),
|
||||
)
|
||||
.await;
|
||||
assert!(resp.status().is_success(), "{}", resp.text().await.unwrap());
|
||||
let job: Value = resp.json().await.unwrap();
|
||||
let done = wait_job(&cloud.url, job["id"].as_str().unwrap()).await;
|
||||
assert_eq!(done["status"]["kind"], "Done", "{done:#}");
|
||||
assert_eq!(done["target_node"], "home");
|
||||
|
||||
// Files arrived intact, sidecars included.
|
||||
let dest = home.movies().join("Alien (1979)");
|
||||
assert_eq!(
|
||||
std::fs::read(dest.join("Alien (1979).mkv")).unwrap(),
|
||||
vec![7u8; 2 * 1024 * 1024]
|
||||
);
|
||||
assert!(dest.join("Alien (1979).en.srt").exists());
|
||||
assert!(dest.join("extras/Making of.mkv").exists());
|
||||
// Nothing left in the partial area.
|
||||
assert_eq!(
|
||||
std::fs::read_dir(home.movies().join(".jellymove-partial"))
|
||||
.unwrap()
|
||||
.filter(|e| e.as_ref().unwrap().file_name() != ".ignore")
|
||||
.count(),
|
||||
0
|
||||
);
|
||||
|
||||
// Source moved to the hidden trash, not deleted outright.
|
||||
assert!(!cloud.movies().join("Alien (1979)").exists());
|
||||
let trash = cloud.movies().join(".jellymove-trash");
|
||||
assert!(
|
||||
trash
|
||||
.join(format!("item-{movie}/Alien (1979)/Alien (1979).mkv"))
|
||||
.exists()
|
||||
);
|
||||
|
||||
// Watch state followed the move to the new item ID.
|
||||
let new_id = home.fake.find("Movie", "Alien").unwrap();
|
||||
assert_ne!(new_id, movie);
|
||||
let ud = home.fake.get_user_data(&new_id).expect("user data applied");
|
||||
assert_eq!(ud["Played"], true);
|
||||
assert_eq!(ud["PlayCount"], 2);
|
||||
assert_eq!(ud["IsFavorite"], true);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn moves_a_series_and_maps_episode_watch_state() {
|
||||
let (cloud, home) = pair(seed_series).await;
|
||||
let series = cloud.fake.find("Series", "Severance").unwrap();
|
||||
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, "PlayCount": 1}));
|
||||
cloud
|
||||
.fake
|
||||
.set_user_data(&e3, json!({"PlaybackPositionTicks": 123456789}));
|
||||
|
||||
// Started from the *home* UI this time: "pull this item from the peer".
|
||||
let resp = post(
|
||||
&home.url,
|
||||
"/api/moves",
|
||||
json!({"from": "peer", "item_id": series, "name": "Severance"}),
|
||||
)
|
||||
.await;
|
||||
let job: Value = resp.json().await.unwrap();
|
||||
let done = wait_job(&home.url, job["id"].as_str().unwrap()).await;
|
||||
assert_eq!(done["status"]["kind"], "Done", "{done:#}");
|
||||
|
||||
assert!(
|
||||
home.tv()
|
||||
.join("Severance/Season 02/Severance S02E01.mkv")
|
||||
.exists()
|
||||
);
|
||||
assert!(!cloud.tv().join("Severance").exists());
|
||||
|
||||
let new_e1 = home.fake.episode_id("Severance", 1, 1).unwrap();
|
||||
let new_e3 = home.fake.episode_id("Severance", 2, 1).unwrap();
|
||||
assert_eq!(home.fake.get_user_data(&new_e1).unwrap()["Played"], true);
|
||||
assert_eq!(
|
||||
home.fake.get_user_data(&new_e3).unwrap()["PlaybackPositionTicks"],
|
||||
123456789
|
||||
);
|
||||
// Untouched episode gets nothing written.
|
||||
let new_e2 = home.fake.episode_id("Severance", 1, 2).unwrap();
|
||||
assert!(home.fake.get_user_data(&new_e2).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dry_run_changes_nothing() {
|
||||
let (cloud, home) = pair(seed_movie).await;
|
||||
let movie = cloud.fake.find("Movie", "Alien").unwrap();
|
||||
let job: Value = post(
|
||||
&cloud.url,
|
||||
"/api/moves",
|
||||
json!({"from": "local", "item_id": movie, "name": "Alien", "dry_run": true}),
|
||||
)
|
||||
.await
|
||||
.json()
|
||||
.await
|
||||
.unwrap();
|
||||
let done = wait_job(&cloud.url, job["id"].as_str().unwrap()).await;
|
||||
assert_eq!(done["status"]["kind"], "Planned", "{done:#}");
|
||||
assert!(
|
||||
done["log"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|l| l.as_str().unwrap().contains("plan: 4 files"))
|
||||
);
|
||||
assert!(
|
||||
cloud
|
||||
.movies()
|
||||
.join("Alien (1979)/Alien (1979).mkv")
|
||||
.exists()
|
||||
);
|
||||
assert!(!home.movies().join("Alien (1979)").exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refuses_flat_movie_folder() {
|
||||
let (cloud, home) = pair(|root| {
|
||||
// Two movies sharing one folder: moving "the folder" would take both.
|
||||
write(&root.join("movies/Unsorted/Heat (1995).mkv"), b"heat");
|
||||
write(&root.join("movies/Unsorted/Ronin (1998).mkv"), b"ronin");
|
||||
})
|
||||
.await;
|
||||
let heat = cloud.fake.find("Movie", "Unsorted").unwrap();
|
||||
let job: Value = post(
|
||||
&cloud.url,
|
||||
"/api/moves",
|
||||
json!({"from": "local", "item_id": heat, "name": "Heat"}),
|
||||
)
|
||||
.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("other videos"),
|
||||
"{done:#}"
|
||||
);
|
||||
assert!(cloud.movies().join("Unsorted/Ronin (1998).mkv").exists());
|
||||
assert!(!home.movies().join("Unsorted").exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refuses_when_destination_exists() {
|
||||
let (cloud, home) = pair(seed_movie).await;
|
||||
write(
|
||||
&home.movies().join("Alien (1979)/Alien (1979).mkv"),
|
||||
b"a different copy",
|
||||
);
|
||||
let movie = cloud.fake.find("Movie", "Alien").unwrap();
|
||||
let job: Value = post(
|
||||
&cloud.url,
|
||||
"/api/moves",
|
||||
json!({"from": "local", "item_id": movie, "name": "Alien"}),
|
||||
)
|
||||
.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")
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(home.movies().join("Alien (1979)/Alien (1979).mkv")).unwrap(),
|
||||
b"a different copy"
|
||||
);
|
||||
assert!(cloud.movies().join("Alien (1979)").exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn peer_api_rejects_bad_token_and_ui_requires_csrf_header() {
|
||||
let (cloud, _home) = pair(|_| {}).await;
|
||||
let r = reqwest::Client::new()
|
||||
.get(format!("{}/peer/v1/libraries", cloud.url))
|
||||
.bearer_auth("wrong")
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.status(), 401);
|
||||
|
||||
let r = reqwest::Client::new()
|
||||
.post(format!("{}/api/moves", cloud.url))
|
||||
.json(&json!({"from": "local", "item_id": "x", "name": "x"}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.status(), 403);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn export_files_are_only_reachable_by_index() {
|
||||
let (cloud, _home) = pair(seed_movie).await;
|
||||
// Path traversal attempts through the file route go nowhere.
|
||||
let r = reqwest::Client::new()
|
||||
.get(format!(
|
||||
"{}/peer/v1/exports/..%2F..%2Fetc/files/0",
|
||||
cloud.url
|
||||
))
|
||||
.bearer_auth(TOKEN)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.status(), 404);
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
//! A tiny filesystem-backed stand-in for Jellyfin, good enough to drive a
|
||||
//! real move end to end. Like real Jellyfin, item IDs are derived from paths,
|
||||
//! scans happen a moment after `/Library/Media/Updated`, and user data is
|
||||
//! keyed by (user, item).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::extract::{Path as AxPath, Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::routing::{get, post};
|
||||
use axum::{Json, Router};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Lib {
|
||||
pub name: String,
|
||||
pub collection_type: &'static str,
|
||||
pub location: PathBuf,
|
||||
}
|
||||
|
||||
impl Lib {
|
||||
pub fn id(&self) -> String {
|
||||
format!("lib-{}", self.name.to_lowercase().replace(' ', "-"))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct FakeItem {
|
||||
id: String,
|
||||
name: String,
|
||||
kind: &'static str,
|
||||
path: String,
|
||||
parent: String,
|
||||
season: Option<i32>,
|
||||
episode: Option<i32>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Fake {
|
||||
libs: Arc<Vec<Lib>>,
|
||||
items: Arc<Mutex<Vec<FakeItem>>>,
|
||||
/// (user id, item id) → UserData JSON
|
||||
pub user_data: Arc<Mutex<HashMap<(String, String), Value>>>,
|
||||
}
|
||||
|
||||
pub fn id_for(path: &Path) -> String {
|
||||
blake3::hash(path.to_string_lossy().as_bytes()).to_hex()[..32].to_string()
|
||||
}
|
||||
|
||||
fn parse_sxxexx(name: &str) -> Option<(i32, i32)> {
|
||||
// Find the first "S<digits>E<digits>" anywhere in the name.
|
||||
let up = name.to_uppercase();
|
||||
let b = up.as_bytes();
|
||||
for i in 0..b.len() {
|
||||
if b[i] != b'S' {
|
||||
continue;
|
||||
}
|
||||
let s: String = up[i + 1..]
|
||||
.chars()
|
||||
.take_while(|c| c.is_ascii_digit())
|
||||
.collect();
|
||||
let after = i + 1 + s.len();
|
||||
if s.is_empty() || b.get(after) != Some(&b'E') {
|
||||
continue;
|
||||
}
|
||||
let e: String = up[after + 1..]
|
||||
.chars()
|
||||
.take_while(|c| c.is_ascii_digit())
|
||||
.collect();
|
||||
if let (Ok(season), Ok(ep)) = (s.parse(), e.parse()) {
|
||||
return Some((season, ep));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let Ok(rd) = std::fs::read_dir(dir) else {
|
||||
return;
|
||||
};
|
||||
for e in rd.flatten() {
|
||||
let name = e.file_name().to_string_lossy().to_string();
|
||||
if name.starts_with('.') {
|
||||
continue; // Jellyfin skips hidden folders
|
||||
}
|
||||
if e.file_type().unwrap().is_dir() {
|
||||
walk(&e.path(), out);
|
||||
} else {
|
||||
out.push(e.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Fake {
|
||||
pub fn new(libs: Vec<Lib>) -> Self {
|
||||
let f = Self {
|
||||
libs: Arc::new(libs),
|
||||
items: Default::default(),
|
||||
user_data: Default::default(),
|
||||
};
|
||||
f.scan();
|
||||
f
|
||||
}
|
||||
|
||||
pub fn scan(&self) {
|
||||
let mut items = Vec::new();
|
||||
for lib in self.libs.iter() {
|
||||
let Ok(rd) = std::fs::read_dir(&lib.location) else {
|
||||
continue;
|
||||
};
|
||||
for entry in rd.flatten() {
|
||||
let name = entry.file_name().to_string_lossy().to_string();
|
||||
if name.starts_with('.') || !entry.file_type().unwrap().is_dir() {
|
||||
continue;
|
||||
}
|
||||
let folder = entry.path();
|
||||
let mut files = Vec::new();
|
||||
walk(&folder, &mut files);
|
||||
if lib.collection_type == "movies" {
|
||||
for f in files
|
||||
.iter()
|
||||
.filter(|f| f.extension().is_some_and(|e| e == "mkv"))
|
||||
{
|
||||
if f.parent() != Some(folder.as_path()) {
|
||||
continue; // extras
|
||||
}
|
||||
items.push(FakeItem {
|
||||
id: id_for(f),
|
||||
name: name.split(" (").next().unwrap().to_string(),
|
||||
kind: "Movie",
|
||||
path: f.display().to_string(),
|
||||
parent: lib.id(),
|
||||
season: None,
|
||||
episode: None,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
let series_id = id_for(&folder);
|
||||
items.push(FakeItem {
|
||||
id: series_id.clone(),
|
||||
name: name.clone(),
|
||||
kind: "Series",
|
||||
path: folder.display().to_string(),
|
||||
parent: lib.id(),
|
||||
season: None,
|
||||
episode: None,
|
||||
});
|
||||
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),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
*self.items.lock().unwrap() = items;
|
||||
}
|
||||
|
||||
pub fn find(&self, kind: &str, name: &str) -> Option<String> {
|
||||
self.items
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|i| i.kind == kind && i.name == name)
|
||||
.map(|i| i.id.clone())
|
||||
}
|
||||
|
||||
pub fn episode_id(&self, series: &str, season: i32, ep: i32) -> Option<String> {
|
||||
let series_id = self.find("Series", series)?;
|
||||
self.items
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|i| i.parent == series_id && i.season == Some(season) && i.episode == Some(ep))
|
||||
.map(|i| i.id.clone())
|
||||
}
|
||||
|
||||
pub fn set_user_data(&self, item: &str, data: Value) {
|
||||
self.user_data
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(("u1".into(), item.into()), data);
|
||||
}
|
||||
|
||||
pub fn get_user_data(&self, item: &str) -> Option<Value> {
|
||||
self.user_data
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&("u1".to_string(), item.to_string()))
|
||||
.cloned()
|
||||
}
|
||||
|
||||
pub async fn serve(self) -> String {
|
||||
let app = Router::new()
|
||||
.route(
|
||||
"/System/Info",
|
||||
get(|| async {
|
||||
Json(json!({"ServerName": "fake", "Version": "10.11.0", "Id": "x"}))
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/Users",
|
||||
get(|| async { Json(json!([{"Id": "u1", "Name": "Alice"}])) }),
|
||||
)
|
||||
.route("/Library/VirtualFolders", get(virtual_folders))
|
||||
.route("/Items", get(items))
|
||||
.route("/Library/Media/Updated", post(media_updated))
|
||||
.route("/UserItems/{id}/UserData", post(set_user_data))
|
||||
.with_state(self);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
format!("http://{addr}")
|
||||
}
|
||||
}
|
||||
|
||||
async fn virtual_folders(State(f): State<Fake>) -> Json<Value> {
|
||||
Json(Value::Array(
|
||||
f.libs
|
||||
.iter()
|
||||
.map(|l| {
|
||||
json!({"Name": l.name, "Locations": [l.location.display().to_string()],
|
||||
"CollectionType": l.collection_type, "ItemId": l.id()})
|
||||
})
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
async fn items(State(f): State<Fake>, Query(q): Query<HashMap<String, String>>) -> Json<Value> {
|
||||
let all = f.items.lock().unwrap().clone();
|
||||
let types: Option<Vec<&str>> = q.get("includeItemTypes").map(|t| t.split(',').collect());
|
||||
let ids: Option<Vec<&str>> = q.get("ids").map(|t| t.split(',').collect());
|
||||
let ud = f.user_data.lock().unwrap().clone();
|
||||
let user = q.get("userId");
|
||||
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| types.as_ref().is_none_or(|t| t.contains(&i.kind)))
|
||||
.filter(|i| {
|
||||
q.get("searchTerm")
|
||||
.is_none_or(|s| i.name.to_lowercase().contains(&s.to_lowercase()))
|
||||
})
|
||||
.map(|i| {
|
||||
let mut v = json!({"Id": i.id, "Name": i.name, "Type": i.kind, "Path": i.path,
|
||||
"ParentIndexNumber": i.season, "IndexNumber": i.episode,
|
||||
"MediaSources": [{"Path": i.path}]});
|
||||
if let Some(u) = user {
|
||||
v["UserData"] = ud
|
||||
.get(&(u.clone(), i.id.clone()))
|
||||
.cloned()
|
||||
.unwrap_or(json!({"Played": false}));
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
let n = out.len();
|
||||
Json(json!({"Items": out, "TotalRecordCount": n}))
|
||||
}
|
||||
|
||||
async fn media_updated(State(f): State<Fake>) -> StatusCode {
|
||||
// Like Jellyfin's LibraryMonitorDelay, but much shorter.
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
f.scan();
|
||||
});
|
||||
StatusCode::NO_CONTENT
|
||||
}
|
||||
|
||||
async fn set_user_data(
|
||||
State(f): State<Fake>,
|
||||
AxPath(id): AxPath<String>,
|
||||
Query(q): Query<HashMap<String, String>>,
|
||||
Json(body): Json<Value>,
|
||||
) -> StatusCode {
|
||||
f.user_data
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert((q["userId"].clone(), id), body);
|
||||
StatusCode::OK
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "jm-store"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
jm-core = { version = "0.1.0", path = "../jm-core" }
|
||||
rusqlite = { version = "0.40.2", features = ["bundled"] }
|
||||
serde = "1.0.229"
|
||||
serde_json = "1.0.154"
|
||||
thiserror = "2.0.21"
|
||||
tokio = { version = "1.54.1", features = ["macros", "rt", "rt-multi-thread", "sync"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3.27.0"
|
||||
@@ -0,0 +1,208 @@
|
||||
//! Persistent state in SQLite (WAL mode).
|
||||
//!
|
||||
//! Jobs and exports are stored as JSON documents with a few indexed columns.
|
||||
//! The schema is deliberately small; the job struct is the source of truth.
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use jm_core::{Job, JobId};
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use serde::{Serialize, de::DeserializeOwned};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum StoreError {
|
||||
#[error("database error: {0}")]
|
||||
Sql(#[from] rusqlite::Error),
|
||||
#[error("corrupt record: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
}
|
||||
|
||||
type Result<T> = std::result::Result<T, StoreError>;
|
||||
|
||||
const MIGRATIONS: &[&str] = &[
|
||||
// v1
|
||||
"CREATE TABLE jobs (
|
||||
id TEXT PRIMARY KEY,
|
||||
active INTEGER NOT NULL,
|
||||
created TEXT NOT NULL,
|
||||
body TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX jobs_active ON jobs(active);
|
||||
CREATE TABLE exports (
|
||||
id TEXT PRIMARY KEY,
|
||||
body TEXT NOT NULL
|
||||
);",
|
||||
];
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Store {
|
||||
conn: Arc<Mutex<Connection>>,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub fn open(path: &Path) -> Result<Self> {
|
||||
Self::init(Connection::open(path)?)
|
||||
}
|
||||
|
||||
pub fn in_memory() -> Result<Self> {
|
||||
Self::init(Connection::open_in_memory()?)
|
||||
}
|
||||
|
||||
fn init(conn: Connection) -> Result<Self> {
|
||||
conn.pragma_update(None, "journal_mode", "WAL")?;
|
||||
conn.pragma_update(None, "synchronous", "NORMAL")?;
|
||||
let version: i64 = conn.pragma_query_value(None, "user_version", |r| r.get(0))?;
|
||||
for (i, sql) in MIGRATIONS.iter().enumerate().skip(version as usize) {
|
||||
conn.execute_batch(sql)?;
|
||||
conn.pragma_update(None, "user_version", (i + 1) as i64)?;
|
||||
}
|
||||
Ok(Self {
|
||||
conn: Arc::new(Mutex::new(conn)),
|
||||
})
|
||||
}
|
||||
|
||||
async fn with<T: Send + 'static>(
|
||||
&self,
|
||||
f: impl FnOnce(&Connection) -> Result<T> + Send + 'static,
|
||||
) -> Result<T> {
|
||||
let conn = self.conn.clone();
|
||||
tokio::task::spawn_blocking(move || f(&conn.lock().expect("store mutex poisoned")))
|
||||
.await
|
||||
.expect("store task panicked")
|
||||
}
|
||||
|
||||
pub async fn put_job(&self, job: &Job) -> Result<()> {
|
||||
let id = job.id.to_string();
|
||||
let active = job.status.is_active();
|
||||
let created = job.created.unix_timestamp().to_string();
|
||||
let body = serde_json::to_string(job)?;
|
||||
self.with(move |c| {
|
||||
c.execute(
|
||||
"INSERT INTO jobs (id, active, created, body) VALUES (?1, ?2, ?3, ?4)
|
||||
ON CONFLICT(id) DO UPDATE SET active = excluded.active, body = excluded.body",
|
||||
params![id, active, created, body],
|
||||
)?;
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_job(&self, id: JobId) -> Result<Option<Job>> {
|
||||
let id = id.to_string();
|
||||
let body: Option<String> = self
|
||||
.with(move |c| {
|
||||
Ok(
|
||||
c.query_row("SELECT body FROM jobs WHERE id = ?1", [id], |r| r.get(0))
|
||||
.optional()?,
|
||||
)
|
||||
})
|
||||
.await?;
|
||||
body.map(|b| serde_json::from_str(&b).map_err(Into::into))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// Most recent jobs first.
|
||||
pub async fn list_jobs(&self, limit: usize) -> Result<Vec<Job>> {
|
||||
self.query_jobs(
|
||||
"SELECT body FROM jobs ORDER BY created DESC, rowid DESC LIMIT ?1",
|
||||
limit,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Jobs that were queued or running, e.g. when the daemon last stopped.
|
||||
pub async fn active_jobs(&self) -> Result<Vec<Job>> {
|
||||
self.query_jobs(
|
||||
"SELECT body FROM jobs WHERE active = 1 ORDER BY created ASC LIMIT ?1",
|
||||
10_000,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn query_jobs(&self, sql: &'static str, limit: usize) -> Result<Vec<Job>> {
|
||||
let bodies: Vec<String> = self
|
||||
.with(move |c| {
|
||||
let mut stmt = c.prepare(sql)?;
|
||||
let rows = stmt.query_map([limit as i64], |r| r.get(0))?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
})
|
||||
.await?;
|
||||
bodies
|
||||
.iter()
|
||||
.map(|b| serde_json::from_str(b).map_err(Into::into))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub async fn put_export<T: Serialize>(&self, id: &str, export: &T) -> Result<()> {
|
||||
let id = id.to_string();
|
||||
let body = serde_json::to_string(export)?;
|
||||
self.with(move |c| {
|
||||
c.execute(
|
||||
"INSERT INTO exports (id, body) VALUES (?1, ?2)
|
||||
ON CONFLICT(id) DO UPDATE SET body = excluded.body",
|
||||
params![id, body],
|
||||
)?;
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_export<T: DeserializeOwned>(&self, id: &str) -> Result<Option<T>> {
|
||||
let id = id.to_string();
|
||||
let body: Option<String> = self
|
||||
.with(move |c| {
|
||||
Ok(
|
||||
c.query_row("SELECT body FROM exports WHERE id = ?1", [id], |r| r.get(0))
|
||||
.optional()?,
|
||||
)
|
||||
})
|
||||
.await?;
|
||||
body.map(|b| serde_json::from_str(&b).map_err(Into::into))
|
||||
.transpose()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use jm_core::JobStatus;
|
||||
|
||||
#[tokio::test]
|
||||
async fn jobs_roundtrip_and_track_activity() {
|
||||
let store = Store::in_memory().unwrap();
|
||||
let mut a = Job::new("1", "A", "cloud", "home", false);
|
||||
let b = Job::new("2", "B", "cloud", "home", false);
|
||||
store.put_job(&a).await.unwrap();
|
||||
store.put_job(&b).await.unwrap();
|
||||
assert_eq!(store.active_jobs().await.unwrap().len(), 2);
|
||||
|
||||
a.status = JobStatus::Done;
|
||||
store.put_job(&a).await.unwrap();
|
||||
let active = store.active_jobs().await.unwrap();
|
||||
assert_eq!(active.len(), 1);
|
||||
assert_eq!(active[0].name, "B");
|
||||
|
||||
let got = store.get_job(a.id).await.unwrap().unwrap();
|
||||
assert_eq!(got.status, JobStatus::Done);
|
||||
assert_eq!(store.list_jobs(10).await.unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn survives_reopen() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("state.db");
|
||||
let job = Job::new("1", "A", "cloud", "home", false);
|
||||
{
|
||||
let s = Store::open(&path).unwrap();
|
||||
s.put_job(&job).await.unwrap();
|
||||
s.put_export("e1", &serde_json::json!({"x": 1}))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let s = Store::open(&path).unwrap();
|
||||
assert!(s.get_job(job.id).await.unwrap().is_some());
|
||||
let e: serde_json::Value = s.get_export("e1").await.unwrap().unwrap();
|
||||
assert_eq!(e["x"], 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "jm-transfer"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
axum = "0.8.9"
|
||||
blake3 = { version = "1.8.7", features = ["mmap", "rayon"] }
|
||||
bytes = "1.12.1"
|
||||
futures = "0.3.34"
|
||||
governor = "0.10.4"
|
||||
jm-core = { version = "0.1.0", path = "../jm-core" }
|
||||
reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "stream", "http2"] }
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_json = "1.0.154"
|
||||
thiserror = "2.0.21"
|
||||
tokio = { version = "1.54.1", features = ["full"] }
|
||||
tokio-util = "0.7.20"
|
||||
tracing = "0.1.44"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3.27.0"
|
||||
@@ -0,0 +1,60 @@
|
||||
//! Moving bytes between agents.
|
||||
//!
|
||||
//! The destination *pulls* each file from the source over HTTP with `Range`
|
||||
//! requests, writing to a `.part` file in a hidden partial area inside the
|
||||
//! destination library. The length of the `.part` file is the resume point, so
|
||||
//! a dropped link or a restart continues where it stopped. When a file is
|
||||
//! complete it is hashed with BLAKE3 and compared with the source's hash; only
|
||||
//! verified files are renamed into the library.
|
||||
|
||||
pub mod manifest;
|
||||
pub mod promote;
|
||||
pub mod pull;
|
||||
pub mod serve;
|
||||
|
||||
pub use manifest::{build_manifest, hash_file, list_relative};
|
||||
pub use promote::{part_path, partial_dir, prepare_partial, promote};
|
||||
pub use pull::{Puller, PullerOptions};
|
||||
pub use serve::range_response;
|
||||
|
||||
/// Prefix for jellymove's own hidden folders inside libraries. Jellyfin skips
|
||||
/// folders whose names start with a dot, and we also drop a `.ignore` file in
|
||||
/// them for good measure.
|
||||
pub const HIDDEN_PREFIX: &str = ".jellymove-";
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum TransferError {
|
||||
#[error("i/o error: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("http error: {0}")]
|
||||
Http(#[from] reqwest::Error),
|
||||
#[error("peer returned HTTP {0}")]
|
||||
Status(u16),
|
||||
#[error("hash mismatch for {file}: expected {expected}, got {actual}")]
|
||||
Integrity {
|
||||
file: String,
|
||||
expected: String,
|
||||
actual: String,
|
||||
},
|
||||
#[error("size mismatch for {file}: expected {expected} bytes, got {actual}")]
|
||||
Size {
|
||||
file: String,
|
||||
expected: u64,
|
||||
actual: u64,
|
||||
},
|
||||
#[error("refusing to overwrite existing file {0}")]
|
||||
Exists(String),
|
||||
#[error("unsafe path in manifest: {0}")]
|
||||
UnsafePath(String),
|
||||
}
|
||||
|
||||
impl TransferError {
|
||||
/// Errors that a retry cannot fix.
|
||||
pub fn is_permanent(&self) -> bool {
|
||||
match self {
|
||||
TransferError::Status(code) => matches!(code, 400 | 401 | 403 | 404 | 410 | 416),
|
||||
TransferError::Exists(_) | TransferError::UnsafePath(_) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use jm_core::job::{Manifest, ManifestEntry};
|
||||
|
||||
use crate::{HIDDEN_PREFIX, TransferError};
|
||||
|
||||
/// Hash a file with BLAKE3, memory-mapped and multithreaded for large files.
|
||||
pub async fn hash_file(path: &Path) -> Result<String, TransferError> {
|
||||
let path = path.to_path_buf();
|
||||
tokio::task::spawn_blocking(move || -> Result<String, TransferError> {
|
||||
let mut hasher = blake3::Hasher::new();
|
||||
hasher.update_mmap_rayon(&path)?;
|
||||
Ok(hasher.finalize().to_hex().to_string())
|
||||
})
|
||||
.await
|
||||
.expect("hash task panicked")
|
||||
}
|
||||
|
||||
/// List every regular file below `root` (recursively), hash each, and return
|
||||
/// them sorted by relative path. Symlinks and jellymove's own hidden folders
|
||||
/// are skipped.
|
||||
pub async fn build_manifest(root: &Path) -> Result<Manifest, TransferError> {
|
||||
let root_owned = root.to_path_buf();
|
||||
let listed = tokio::task::spawn_blocking(move || list_files(&root_owned))
|
||||
.await
|
||||
.expect("list task panicked")?;
|
||||
|
||||
let mut files = Vec::with_capacity(listed.len());
|
||||
for (rel, abs, size) in listed {
|
||||
let blake3 = hash_file(&abs).await?;
|
||||
files.push(ManifestEntry {
|
||||
rel_path: rel,
|
||||
size,
|
||||
blake3,
|
||||
});
|
||||
}
|
||||
Ok(Manifest { files })
|
||||
}
|
||||
|
||||
/// Relative paths (`/` separated) of every regular file below `root`, without
|
||||
/// hashing. Used for the folder safety check before we spend time hashing.
|
||||
pub fn list_relative(root: &Path) -> Result<Vec<String>, TransferError> {
|
||||
Ok(list_files(root)?
|
||||
.into_iter()
|
||||
.map(|(rel, _, _)| rel)
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn list_files(root: &Path) -> Result<Vec<(String, PathBuf, u64)>, TransferError> {
|
||||
let mut out = Vec::new();
|
||||
let mut stack = vec![PathBuf::new()];
|
||||
while let Some(rel_dir) = stack.pop() {
|
||||
for entry in std::fs::read_dir(root.join(&rel_dir))? {
|
||||
let entry = entry?;
|
||||
let name = entry.file_name();
|
||||
let name_str = name.to_string_lossy();
|
||||
if name_str.starts_with(HIDDEN_PREFIX) {
|
||||
continue;
|
||||
}
|
||||
let ft = entry.file_type()?;
|
||||
let rel = rel_dir.join(&name);
|
||||
if ft.is_dir() {
|
||||
stack.push(rel);
|
||||
} else if ft.is_file() {
|
||||
let size = entry.metadata()?.len();
|
||||
let rel_str = rel
|
||||
.components()
|
||||
.map(|c| c.as_os_str().to_string_lossy())
|
||||
.collect::<Vec<_>>()
|
||||
.join("/");
|
||||
out.push((rel_str, entry.path(), size));
|
||||
} else {
|
||||
tracing::warn!(path = %entry.path().display(), "skipping symlink or special file");
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn manifest_lists_nested_files_and_skips_hidden() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::create_dir_all(root.join("Season 01")).unwrap();
|
||||
std::fs::create_dir_all(root.join(".jellymove-partial")).unwrap();
|
||||
std::fs::write(root.join("tvshow.nfo"), b"<tvshow/>").unwrap();
|
||||
std::fs::write(root.join("Season 01/S01E01.mkv"), b"video").unwrap();
|
||||
std::fs::write(root.join(".jellymove-partial/0.part"), b"junk").unwrap();
|
||||
|
||||
let m = build_manifest(root).await.unwrap();
|
||||
let names: Vec<_> = m.files.iter().map(|f| f.rel_path.as_str()).collect();
|
||||
assert_eq!(names, ["Season 01/S01E01.mkv", "tvshow.nfo"]);
|
||||
assert_eq!(m.files[0].size, 5);
|
||||
assert_eq!(
|
||||
m.files[0].blake3,
|
||||
blake3::hash(b"video").to_hex().to_string()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use jm_core::job::Manifest;
|
||||
use jm_core::paths::join_relative;
|
||||
|
||||
use crate::{HIDDEN_PREFIX, TransferError};
|
||||
|
||||
/// Hidden staging folder for one job, inside the destination library root so
|
||||
/// the final rename stays on the same filesystem (and is therefore atomic).
|
||||
pub fn partial_dir(library_root: &Path, job_id: &str) -> PathBuf {
|
||||
library_root
|
||||
.join(format!("{HIDDEN_PREFIX}partial"))
|
||||
.join(job_id)
|
||||
}
|
||||
|
||||
pub fn part_path(partial: &Path, idx: usize) -> PathBuf {
|
||||
partial.join(format!("{idx}.part"))
|
||||
}
|
||||
|
||||
/// Create the partial folder and mark it so Jellyfin ignores it.
|
||||
pub async fn prepare_partial(partial: &Path) -> Result<(), TransferError> {
|
||||
tokio::fs::create_dir_all(partial).await?;
|
||||
if let Some(parent) = partial.parent() {
|
||||
let marker = parent.join(".ignore");
|
||||
if tokio::fs::metadata(&marker).await.is_err() {
|
||||
tokio::fs::write(&marker, b"").await?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rename every verified `.part` into `target_folder`. Safe to run again after
|
||||
/// a crash: files already in place (part gone, target present with the right
|
||||
/// size) are skipped. Refuses to overwrite anything it didn't put there.
|
||||
pub async fn promote(
|
||||
partial: &Path,
|
||||
target_folder: &Path,
|
||||
manifest: &Manifest,
|
||||
) -> Result<(), TransferError> {
|
||||
// Check every destination first so we never half-promote into a clash.
|
||||
for (idx, entry) in manifest.files.iter().enumerate() {
|
||||
let dest = join_relative(target_folder, &entry.rel_path)
|
||||
.ok_or_else(|| TransferError::UnsafePath(entry.rel_path.clone()))?;
|
||||
let part_exists = tokio::fs::metadata(part_path(partial, idx)).await.is_ok();
|
||||
if part_exists && tokio::fs::metadata(&dest).await.is_ok() {
|
||||
return Err(TransferError::Exists(dest.display().to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
for (idx, entry) in manifest.files.iter().enumerate() {
|
||||
let part = part_path(partial, idx);
|
||||
let dest = join_relative(target_folder, &entry.rel_path).expect("checked above");
|
||||
match tokio::fs::metadata(&part).await {
|
||||
Ok(_) => {
|
||||
if let Some(parent) = dest.parent() {
|
||||
tokio::fs::create_dir_all(parent).await?;
|
||||
}
|
||||
tokio::fs::rename(&part, &dest).await?;
|
||||
}
|
||||
Err(_) => {
|
||||
// Already promoted on an earlier run?
|
||||
let meta = tokio::fs::metadata(&dest).await?;
|
||||
if meta.len() != entry.size {
|
||||
return Err(TransferError::Size {
|
||||
file: entry.rel_path.clone(),
|
||||
expected: entry.size,
|
||||
actual: meta.len(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = tokio::fs::remove_dir(partial).await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
use std::num::NonZeroU32;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use futures::StreamExt;
|
||||
use governor::{DefaultDirectRateLimiter, Quota, RateLimiter};
|
||||
use jm_core::job::ManifestEntry;
|
||||
use reqwest::StatusCode;
|
||||
use reqwest::header::{AUTHORIZATION, RANGE};
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
use crate::{TransferError, hash_file};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PullerOptions {
|
||||
/// Bearer token presented to the peer.
|
||||
pub token: Option<String>,
|
||||
/// Bytes per second across every transfer this puller makes. `None` = unlimited.
|
||||
pub bytes_per_sec: Option<NonZeroU32>,
|
||||
/// Attempts per file before giving up (resumes between attempts).
|
||||
pub attempts: u32,
|
||||
/// First backoff delay; doubles each attempt, capped at one minute.
|
||||
pub initial_backoff: Duration,
|
||||
}
|
||||
|
||||
impl Default for PullerOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
token: None,
|
||||
bytes_per_sec: None,
|
||||
attempts: 10,
|
||||
initial_backoff: Duration::from_secs(2),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Puller {
|
||||
http: reqwest::Client,
|
||||
opts: PullerOptions,
|
||||
limiter: Option<Arc<DefaultDirectRateLimiter>>,
|
||||
}
|
||||
|
||||
impl Puller {
|
||||
pub fn new(http: reqwest::Client, opts: PullerOptions) -> Self {
|
||||
let limiter = opts
|
||||
.bytes_per_sec
|
||||
.map(|bps| Arc::new(RateLimiter::direct(Quota::per_second(bps))));
|
||||
Self {
|
||||
http,
|
||||
opts,
|
||||
limiter,
|
||||
}
|
||||
}
|
||||
|
||||
/// Pull one file into `part`, resuming and retrying as needed, then verify
|
||||
/// its BLAKE3 hash. `on_progress` receives the bytes held for this file.
|
||||
pub async fn pull_verified(
|
||||
&self,
|
||||
url: &str,
|
||||
entry: &ManifestEntry,
|
||||
part: &Path,
|
||||
on_progress: &mut (dyn FnMut(u64) + Send),
|
||||
) -> Result<(), TransferError> {
|
||||
let mut delay = self.opts.initial_backoff;
|
||||
let mut attempt = 1;
|
||||
loop {
|
||||
match self.pull_once(url, entry, part, on_progress).await {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) if e.is_permanent() || attempt >= self.opts.attempts => return Err(e),
|
||||
Err(e) => {
|
||||
tracing::warn!(file = %entry.rel_path, attempt, error = %e, "transfer failed; will resume");
|
||||
tokio::time::sleep(delay).await;
|
||||
delay = (delay * 2).min(Duration::from_secs(60));
|
||||
attempt += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn pull_once(
|
||||
&self,
|
||||
url: &str,
|
||||
entry: &ManifestEntry,
|
||||
part: &Path,
|
||||
on_progress: &mut (dyn FnMut(u64) + Send),
|
||||
) -> Result<(), TransferError> {
|
||||
if let Some(parent) = part.parent() {
|
||||
tokio::fs::create_dir_all(parent).await?;
|
||||
}
|
||||
let mut have = match tokio::fs::metadata(part).await {
|
||||
Ok(m) => m.len(),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
if entry.size == 0 {
|
||||
// Nothing to fetch; an empty file is still part of the folder.
|
||||
tokio::fs::File::create(part).await?;
|
||||
}
|
||||
0
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
if have > entry.size {
|
||||
// Can't be ours; start again.
|
||||
tokio::fs::remove_file(part).await?;
|
||||
have = 0;
|
||||
}
|
||||
|
||||
if have < entry.size {
|
||||
let mut req = self.http.get(url);
|
||||
if let Some(t) = &self.opts.token {
|
||||
req = req.header(AUTHORIZATION, format!("Bearer {t}"));
|
||||
}
|
||||
if have > 0 {
|
||||
req = req.header(RANGE, format!("bytes={have}-"));
|
||||
}
|
||||
let resp = req.send().await?;
|
||||
let mut file = match resp.status() {
|
||||
StatusCode::PARTIAL_CONTENT if have > 0 => {
|
||||
tokio::fs::OpenOptions::new()
|
||||
.append(true)
|
||||
.open(part)
|
||||
.await?
|
||||
}
|
||||
StatusCode::OK => {
|
||||
// Server ignored the range (or we asked from zero): rewrite.
|
||||
have = 0;
|
||||
tokio::fs::File::create(part).await?
|
||||
}
|
||||
s => return Err(TransferError::Status(s.as_u16())),
|
||||
};
|
||||
on_progress(have);
|
||||
|
||||
let mut stream = resp.bytes_stream();
|
||||
while let Some(chunk) = stream.next().await {
|
||||
let chunk = chunk?;
|
||||
self.throttle(chunk.len()).await;
|
||||
file.write_all(&chunk).await?;
|
||||
have += chunk.len() as u64;
|
||||
on_progress(have);
|
||||
if have > entry.size {
|
||||
break;
|
||||
}
|
||||
}
|
||||
file.flush().await?;
|
||||
file.sync_all().await?;
|
||||
}
|
||||
|
||||
if have != entry.size {
|
||||
if have > entry.size {
|
||||
tokio::fs::remove_file(part).await?;
|
||||
}
|
||||
return Err(TransferError::Size {
|
||||
file: entry.rel_path.clone(),
|
||||
expected: entry.size,
|
||||
actual: have,
|
||||
});
|
||||
}
|
||||
|
||||
let actual = hash_file(part).await?;
|
||||
if actual != entry.blake3 {
|
||||
// Corrupt; discard so the next attempt starts from scratch.
|
||||
tokio::fs::remove_file(part).await?;
|
||||
return Err(TransferError::Integrity {
|
||||
file: entry.rel_path.clone(),
|
||||
expected: entry.blake3.clone(),
|
||||
actual,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn throttle(&self, len: usize) {
|
||||
let Some(limiter) = &self.limiter else { return };
|
||||
let burst = self.opts.bytes_per_sec.map(|b| b.get()).unwrap_or(u32::MAX) as usize;
|
||||
let mut remaining = len;
|
||||
while remaining > 0 {
|
||||
let n = remaining.min(burst);
|
||||
let n32 = NonZeroU32::new(n as u32).expect("n > 0");
|
||||
// Can't fail: n never exceeds the burst size.
|
||||
let _ = limiter.until_n_ready(n32).await;
|
||||
remaining -= n;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
use std::io::SeekFrom;
|
||||
use std::path::Path;
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use tokio::io::{AsyncReadExt, AsyncSeekExt};
|
||||
use tokio_util::io::ReaderStream;
|
||||
|
||||
/// Serve a file with support for a single `Range: bytes=start-[end]` header.
|
||||
/// The caller is responsible for deciding *which* file may be served.
|
||||
pub async fn range_response(path: &Path, headers: &HeaderMap) -> Response {
|
||||
let mut file = match tokio::fs::File::open(path).await {
|
||||
Ok(f) => f,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
}
|
||||
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
|
||||
};
|
||||
let len = match file.metadata().await {
|
||||
Ok(m) => m.len(),
|
||||
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
|
||||
};
|
||||
|
||||
let range = headers.get(header::RANGE).and_then(|v| v.to_str().ok());
|
||||
let (start, end) = match range.map(|r| parse_range(r, len)) {
|
||||
None => (0, len.saturating_sub(1)),
|
||||
Some(Some(r)) => r,
|
||||
Some(None) => {
|
||||
let mut resp = StatusCode::RANGE_NOT_SATISFIABLE.into_response();
|
||||
resp.headers_mut().insert(
|
||||
header::CONTENT_RANGE,
|
||||
HeaderValue::from_str(&format!("bytes */{len}")).expect("valid header"),
|
||||
);
|
||||
return resp;
|
||||
}
|
||||
};
|
||||
|
||||
if start > 0 {
|
||||
if let Err(e) = file.seek(SeekFrom::Start(start)).await {
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
|
||||
}
|
||||
}
|
||||
let count = if len == 0 { 0 } else { end - start + 1 };
|
||||
let stream = ReaderStream::with_capacity(file.take(count), 256 * 1024);
|
||||
|
||||
let mut builder = Response::builder()
|
||||
.header(header::ACCEPT_RANGES, "bytes")
|
||||
.header(header::CONTENT_LENGTH, count)
|
||||
.header(header::CONTENT_TYPE, "application/octet-stream");
|
||||
if range.is_some() {
|
||||
builder = builder
|
||||
.status(StatusCode::PARTIAL_CONTENT)
|
||||
.header(header::CONTENT_RANGE, format!("bytes {start}-{end}/{len}"));
|
||||
} else {
|
||||
builder = builder.status(StatusCode::OK);
|
||||
}
|
||||
builder
|
||||
.body(Body::from_stream(stream))
|
||||
.expect("valid response")
|
||||
}
|
||||
|
||||
/// Parse `bytes=start-` or `bytes=start-end` against a file of `len` bytes.
|
||||
/// Returns an inclusive range, or `None` if unsatisfiable or malformed.
|
||||
/// Suffix ranges (`bytes=-500`) and multi-range requests aren't needed by our
|
||||
/// puller and are rejected.
|
||||
fn parse_range(value: &str, len: u64) -> Option<(u64, u64)> {
|
||||
let spec = value.strip_prefix("bytes=")?;
|
||||
if spec.contains(',') {
|
||||
return None;
|
||||
}
|
||||
let (s, e) = spec.split_once('-')?;
|
||||
let start: u64 = s.trim().parse().ok()?;
|
||||
if start >= len {
|
||||
return None;
|
||||
}
|
||||
let end = match e.trim() {
|
||||
"" => len - 1,
|
||||
e => e.parse::<u64>().ok()?.min(len - 1),
|
||||
};
|
||||
(start <= end).then_some((start, end))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::parse_range;
|
||||
|
||||
#[test]
|
||||
fn ranges() {
|
||||
assert_eq!(parse_range("bytes=0-", 10), Some((0, 9)));
|
||||
assert_eq!(parse_range("bytes=4-", 10), Some((4, 9)));
|
||||
assert_eq!(parse_range("bytes=4-6", 10), Some((4, 6)));
|
||||
assert_eq!(parse_range("bytes=4-100", 10), Some((4, 9)));
|
||||
assert_eq!(parse_range("bytes=10-", 10), None);
|
||||
assert_eq!(parse_range("bytes=-5", 10), None);
|
||||
assert_eq!(parse_range("bytes=0-1,4-5", 10), None);
|
||||
assert_eq!(parse_range("items=0-", 10), None);
|
||||
assert_eq!(parse_range("bytes=6-4", 10), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
//! End-to-end tests: a real axum source, a real puller, real files on disk.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::Router;
|
||||
use axum::body::{Body, Bytes};
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::{HeaderMap, StatusCode, header};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::get;
|
||||
use jm_transfer::{
|
||||
Puller, PullerOptions, build_manifest, part_path, partial_dir, prepare_partial, promote,
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Src {
|
||||
root: PathBuf,
|
||||
rels: Arc<Vec<String>>,
|
||||
/// When non-zero, the next request is cut off after this many bytes.
|
||||
cut_after: Arc<AtomicUsize>,
|
||||
requests: Arc<AtomicUsize>,
|
||||
/// Requests that asked to resume with a Range header.
|
||||
ranged: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
async fn file(State(s): State<Src>, Path(idx): Path<usize>, headers: HeaderMap) -> Response {
|
||||
s.requests.fetch_add(1, Ordering::SeqCst);
|
||||
if headers.contains_key(header::RANGE) {
|
||||
s.ranged.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
let Some(rel) = s.rels.get(idx) else {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
};
|
||||
let path = s.root.join(rel);
|
||||
let cut = s.cut_after.swap(0, Ordering::SeqCst);
|
||||
if cut == 0 {
|
||||
return jm_transfer::range_response(&path, &headers).await;
|
||||
}
|
||||
// Simulate a dropped link: promise the whole file, send part, then error.
|
||||
let data = std::fs::read(&path).unwrap();
|
||||
let head = Bytes::from(data[..cut].to_vec());
|
||||
let stream = futures::stream::iter(vec![
|
||||
Ok::<_, std::io::Error>(head),
|
||||
Err(std::io::Error::other("link dropped")),
|
||||
]);
|
||||
Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(header::CONTENT_LENGTH, data.len())
|
||||
.body(Body::from_stream(stream))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
struct Fixture {
|
||||
_src_dir: tempfile::TempDir,
|
||||
dst_dir: tempfile::TempDir,
|
||||
src: Src,
|
||||
base: String,
|
||||
}
|
||||
|
||||
async fn fixture() -> Fixture {
|
||||
let src_dir = tempfile::tempdir().unwrap();
|
||||
let item = src_dir.path().join("Alien (1979)");
|
||||
std::fs::create_dir_all(item.join("extras")).unwrap();
|
||||
// 3 MiB of non-repeating bytes so a resume at the wrong offset is detected.
|
||||
let big: Vec<u8> = (0..3 * 1024 * 1024u32)
|
||||
.map(|i| (i.wrapping_mul(2654435761) >> 13) as u8)
|
||||
.collect();
|
||||
std::fs::write(item.join("Alien (1979).mkv"), &big).unwrap();
|
||||
std::fs::write(item.join("Alien (1979).nfo"), b"<movie/>").unwrap();
|
||||
std::fs::write(item.join("extras/Making of.mkv"), b"extra").unwrap();
|
||||
std::fs::write(item.join("empty.txt"), b"").unwrap();
|
||||
|
||||
let manifest = build_manifest(&item).await.unwrap();
|
||||
let src = Src {
|
||||
root: item,
|
||||
rels: Arc::new(manifest.files.iter().map(|f| f.rel_path.clone()).collect()),
|
||||
cut_after: Arc::new(AtomicUsize::new(0)),
|
||||
requests: Arc::new(AtomicUsize::new(0)),
|
||||
ranged: Arc::new(AtomicUsize::new(0)),
|
||||
};
|
||||
let app = Router::new()
|
||||
.route("/files/{idx}", get(file))
|
||||
.with_state(src.clone());
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
|
||||
Fixture {
|
||||
_src_dir: src_dir,
|
||||
dst_dir: tempfile::tempdir().unwrap(),
|
||||
src,
|
||||
base: format!("http://{addr}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn puller() -> Puller {
|
||||
Puller::new(
|
||||
reqwest::Client::new(),
|
||||
PullerOptions {
|
||||
initial_backoff: Duration::from_millis(10),
|
||||
attempts: 5,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
async fn pull_all(fx: &Fixture, p: &Puller) -> PathBuf {
|
||||
let manifest = build_manifest(&fx.src.root).await.unwrap();
|
||||
let lib_root = fx.dst_dir.path();
|
||||
let partial = partial_dir(lib_root, "job1");
|
||||
prepare_partial(&partial).await.unwrap();
|
||||
for (idx, entry) in manifest.files.iter().enumerate() {
|
||||
let url = format!("{}/files/{idx}", fx.base);
|
||||
p.pull_verified(&url, entry, &part_path(&partial, idx), &mut |_| {})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let target = lib_root.join("Alien (1979)");
|
||||
promote(&partial, &target, &manifest).await.unwrap();
|
||||
target
|
||||
}
|
||||
|
||||
fn assert_same_tree(a: &std::path::Path, b: &std::path::Path) {
|
||||
for rel in [
|
||||
"Alien (1979).mkv",
|
||||
"Alien (1979).nfo",
|
||||
"extras/Making of.mkv",
|
||||
"empty.txt",
|
||||
] {
|
||||
assert_eq!(
|
||||
std::fs::read(a.join(rel)).unwrap(),
|
||||
std::fs::read(b.join(rel)).unwrap(),
|
||||
"{rel}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn copies_folder_with_sidecars() {
|
||||
let fx = fixture().await;
|
||||
let target = pull_all(&fx, &puller()).await;
|
||||
assert_same_tree(&fx.src.root, &target);
|
||||
// Partial area is cleaned up and hidden from Jellyfin.
|
||||
assert!(!partial_dir(fx.dst_dir.path(), "job1").exists());
|
||||
assert!(
|
||||
fx.dst_dir
|
||||
.path()
|
||||
.join(".jellymove-partial/.ignore")
|
||||
.exists()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resumes_after_dropped_connection() {
|
||||
let fx = fixture().await;
|
||||
fx.src.cut_after.store(1024 * 1024, Ordering::SeqCst); // first request dies at 1 MiB
|
||||
let target = pull_all(&fx, &puller()).await;
|
||||
assert_same_tree(&fx.src.root, &target);
|
||||
// 3 non-empty files (the empty one needs no request) + 1 resume.
|
||||
assert_eq!(fx.src.requests.load(Ordering::SeqCst), 4);
|
||||
// The retry continued from where the link dropped rather than restarting.
|
||||
assert_eq!(fx.src.ranged.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn corrupt_partial_is_discarded_and_refetched() {
|
||||
let fx = fixture().await;
|
||||
let manifest = build_manifest(&fx.src.root).await.unwrap();
|
||||
let idx = manifest
|
||||
.files
|
||||
.iter()
|
||||
.position(|f| f.rel_path.ends_with(".mkv") && f.size > 100)
|
||||
.unwrap();
|
||||
let partial = partial_dir(fx.dst_dir.path(), "job1");
|
||||
prepare_partial(&partial).await.unwrap();
|
||||
// Plant a half-file of garbage, as if a previous run wrote bad bytes.
|
||||
std::fs::write(part_path(&partial, idx), vec![0u8; 1024 * 1024]).unwrap();
|
||||
|
||||
let target = pull_all(&fx, &puller()).await;
|
||||
assert_same_tree(&fx.src.root, &target);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refuses_to_overwrite_existing_files() {
|
||||
let fx = fixture().await;
|
||||
let target = fx.dst_dir.path().join("Alien (1979)");
|
||||
std::fs::create_dir_all(&target).unwrap();
|
||||
std::fs::write(target.join("Alien (1979).nfo"), b"someone else's").unwrap();
|
||||
|
||||
let manifest = build_manifest(&fx.src.root).await.unwrap();
|
||||
let partial = partial_dir(fx.dst_dir.path(), "job1");
|
||||
prepare_partial(&partial).await.unwrap();
|
||||
let p = puller();
|
||||
for (idx, entry) in manifest.files.iter().enumerate() {
|
||||
let url = format!("{}/files/{idx}", fx.base);
|
||||
p.pull_verified(&url, entry, &part_path(&partial, idx), &mut |_| {})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let err = promote(&partial, &target, &manifest).await.unwrap_err();
|
||||
assert!(matches!(err, jm_transfer::TransferError::Exists(_)));
|
||||
// Nothing was moved: the stranger's file is untouched and no video landed.
|
||||
assert_eq!(
|
||||
std::fs::read(target.join("Alien (1979).nfo")).unwrap(),
|
||||
b"someone else's"
|
||||
);
|
||||
assert!(!target.join("Alien (1979).mkv").exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn promote_is_idempotent() {
|
||||
let fx = fixture().await;
|
||||
let target = pull_all(&fx, &puller()).await;
|
||||
let manifest = build_manifest(&fx.src.root).await.unwrap();
|
||||
// A second promote after a "crash" finds everything already in place.
|
||||
promote(&partial_dir(fx.dst_dir.path(), "job1"), &target, &manifest)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bandwidth_limit_is_applied() {
|
||||
let fx = fixture().await;
|
||||
let p = Puller::new(
|
||||
reqwest::Client::new(),
|
||||
PullerOptions {
|
||||
bytes_per_sec: std::num::NonZeroU32::new(2 * 1024 * 1024),
|
||||
initial_backoff: Duration::from_millis(10),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let start = std::time::Instant::now();
|
||||
pull_all(&fx, &p).await;
|
||||
// ~3 MiB at 2 MiB/s with a one-second burst: at least ~0.5 s.
|
||||
assert!(
|
||||
start.elapsed() >= Duration::from_millis(400),
|
||||
"took {:?}",
|
||||
start.elapsed()
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user