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

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

No files matched your search

+412
View File
@@ -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);
}
+296
View File
@@ -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
}