//! 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 { 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 = [ 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"Alien", ); 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""); 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); }