Files
Jellymove/crates/jm-server/tests/e2e.rs
T
IxianPixel 25a743b350
CI / test (push) Successful in 1m12s
Show folder sizes for movies, shows and seasons. Closes #5
The library lists now show how much space each movie and show takes on disk, counting everything a move copies, with a per-season breakdown for shows, a running total and a "Largest first" sort.

- sizes.rs: a single background worker measures one folder at a time. Listing returns cached sizes straight away and queues folders; the UI
  polls until every size has arrived.
- Cached in a new folder_sizes table (store migration v2). A size is kept while the folder's signature (mtimes of the folder and its direct
  subfolders) is unchanged, checked at most hourly and re-measured after 7 days.
- Each agent measures its own folders, so peer listings carry the peer's sizes.
- Tests for measuring, signatures, natural season order, the migration, and an e2e test covering both sides and a moved item.
2026-11-06 16:43:52 +00:00

605 lines
20 KiB
Rust

//! 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());
}
/// Total size of every file below `dir`.
fn tree_size(dir: &Path) -> u64 {
std::fs::read_dir(dir)
.unwrap()
.map(|e| {
let e = e.unwrap();
if e.file_type().unwrap().is_dir() {
tree_size(&e.path())
} else {
e.metadata().unwrap().len()
}
})
.sum()
}
async fn move_item(base: &str, from: &str, item_id: &str, name: &str) -> Value {
let resp = post(
base,
"/api/moves",
json!({"from": from, "item_id": item_id, "name": name}),
)
.await;
assert!(resp.status().is_success(), "{}", resp.text().await.unwrap());
let job: Value = resp.json().await.unwrap();
let done = wait_job(base, job["id"].as_str().unwrap()).await;
assert_eq!(done["status"]["kind"], "Done", "{done:#}");
done
}
#[tokio::test]
async fn trash_can_be_listed_and_emptied_from_either_side() {
let (cloud, home) = pair(seed_movie).await;
let size = tree_size(&cloud.movies().join("Alien (1979)"));
let movie = cloud.fake.find("Movie", "Alien").unwrap();
let job = move_item(&cloud.url, "local", &movie, "Alien").await;
// The source lists its own trash, with what was moved, where and how big.
let local = get(&cloud.url, "/api/trash?node=local").await;
let entries = local.as_array().unwrap();
assert_eq!(entries.len(), 1, "{local:#}");
let e = &entries[0];
assert_eq!(e["name"], "Alien");
assert_eq!(e["kind"], "Movie");
assert_eq!(e["library"], "Movies");
assert_eq!(e["folder"], "Alien (1979)");
assert_eq!(e["moved_to"], "home");
assert_eq!(e["job_id"], job["id"]);
assert_eq!(e["size"], size);
assert_eq!(e["files"], 4);
assert!(e["moved_at"].is_string());
// The destination sees the same entry as the peer's trash, and its own is empty.
let peer = get(&home.url, "/api/trash?node=peer").await;
assert_eq!(peer, local);
assert_eq!(get(&home.url, "/api/trash?node=local").await, json!([]));
// Paths are never accepted as IDs.
let bogus = post(
&home.url,
"/api/trash/empty",
json!({"node": "peer", "ids": ["../Alien (1979)", "/etc"]}),
)
.await;
let bogus: Value = bogus.json().await.unwrap();
assert_eq!(bogus["removed"], 0);
assert_eq!(bogus["missing"].as_array().unwrap().len(), 2);
assert!(home.movies().join("Alien (1979)/Alien (1979).mkv").exists());
// Empty it from the destination's UI: the source deletes its own files.
let id = e["id"].clone();
let resp = post(
&home.url,
"/api/trash/empty",
json!({"node": "peer", "ids": [id]}),
)
.await;
assert!(resp.status().is_success(), "{}", resp.text().await.unwrap());
let result: Value = resp.json().await.unwrap();
assert_eq!(result["removed"], 1);
assert_eq!(result["freed"], size);
let trash = cloud.movies().join(".jellymove-trash");
let left: Vec<_> = std::fs::read_dir(&trash)
.unwrap()
.map(|e| e.unwrap().file_name())
.collect();
assert_eq!(left, [".ignore"]);
assert_eq!(get(&cloud.url, "/api/trash?node=local").await, json!([]));
// The moved copy is untouched.
assert!(home.movies().join("Alien (1979)/Alien (1979).mkv").exists());
// Emptying again is harmless.
let again: Value = post(
&cloud.url,
"/api/trash/empty",
json!({"node": "local", "ids": [id]}),
)
.await
.json()
.await
.unwrap();
assert_eq!(again["removed"], 0);
assert_eq!(again["missing"], json!([id]));
// Like every other UI write, emptying needs the CSRF header.
let r = reqwest::Client::new()
.post(format!("{}/api/trash/empty", cloud.url))
.json(&json!({"ids": []}))
.send()
.await
.unwrap();
assert_eq!(r.status(), 403);
}
#[tokio::test]
async fn an_item_moved_away_twice_gets_two_trash_entries() {
let (cloud, home) = pair(seed_movie).await;
// Jellyfin item IDs come from the path, so when the movie comes back to
// the same folder it gets the same ID, and so the same export ID.
let movie = cloud.fake.find("Movie", "Alien").unwrap();
move_item(&cloud.url, "local", &movie, "Alien").await;
let on_home = home.fake.find("Movie", "Alien").unwrap();
move_item(&cloud.url, "peer", &on_home, "Alien").await;
let back = cloud.fake.find("Movie", "Alien").unwrap();
assert_eq!(back, movie);
move_item(&cloud.url, "local", &back, "Alien").await;
assert!(home.movies().join("Alien (1979)/Alien (1979).mkv").exists());
let cloud_trash = get(&cloud.url, "/api/trash?node=local").await;
let entries = cloud_trash.as_array().unwrap();
assert_eq!(entries.len(), 2, "{cloud_trash:#}");
assert_ne!(entries[0]["id"], entries[1]["id"]);
assert!(
cloud
.movies()
.join(format!(".jellymove-trash/item-{movie}-2/Alien (1979)/Alien (1979).mkv"))
.exists()
);
let home_trash = get(&home.url, "/api/trash?node=local").await;
assert_eq!(home_trash.as_array().unwrap().len(), 1);
assert_eq!(home_trash[0]["moved_to"], "cloud");
}
/// List a library until every item has a size, like the UI does.
async fn items_with_sizes(base: &str, query: &str) -> Vec<Value> {
let deadline = Instant::now() + Duration::from_secs(30);
loop {
let items = get(base, &format!("/api/items?{query}")).await;
let items = items.as_array().unwrap().clone();
if !items.is_empty() && items.iter().all(|i| i["size"].is_object()) {
return items;
}
assert!(Instant::now() < deadline, "sizes never arrived: {items:#?}");
tokio::time::sleep(Duration::from_millis(200)).await;
}
}
#[tokio::test]
async fn lists_folder_sizes_for_movies_shows_and_seasons() {
let (cloud, home) = pair(|root| {
seed_movie(root);
seed_series(root);
})
.await;
// A movie's size is its whole folder: video, subtitles, NFO and extras.
let movies = items_with_sizes(&cloud.url, "node=local&library=lib-movies").await;
let alien = &movies[0]["size"];
assert_eq!(alien["bytes"], tree_size(&cloud.movies().join("Alien (1979)")));
assert_eq!(alien["files"], 4);
// A show has a total plus one part per season folder; loose files such
// as tvshow.nfo count towards the total only.
let shows = items_with_sizes(&home.url, "node=peer&library=lib-tv-shows").await;
let s = &shows[0]["size"];
assert_eq!(shows[0]["name"], "Severance");
assert_eq!(s["bytes"], tree_size(&cloud.tv().join("Severance")));
assert_eq!(s["files"], 4);
assert_eq!(
s["parts"],
json!([
{"name": "Season 01", "bytes": 22, "files": 2},
{"name": "Season 02", "bytes": 13, "files": 1},
])
);
// After a move the item is measured where it now lives.
let movie = cloud.fake.find("Movie", "Alien").unwrap();
move_item(&cloud.url, "local", &movie, "Alien").await;
let on_home = items_with_sizes(&home.url, "node=local&library=lib-movies").await;
assert_eq!(on_home[0]["size"], *alien);
}
#[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);
}